Python實現將愛詞霸每日一句定時推送至微信


前言

前幾天在網上看到一篇文章《教你用微信每天給女票說晚安》,感覺很神奇的樣子,隨后研究了一下,構思的確是巧妙。好,那就開始動工吧!服務器有了,Python環境有了,IDE打開了...然而...然而...我意識到了一個非常嚴重的問題...沒有女朋友 (T_T)...

微信開發已經活躍了很長時間了,在微信開發中有一個神奇的接口它叫模板消息接口,它可以根據用戶的openid從服務端給用戶推送自定義的模板消息,正因如此,我們可以利用這個特征在服務器端隨時向用戶推送消息(前提是該用戶關注了該公眾號)。

總結出3點,1.模板消息的格式可以自定義,2.模板消息的內容可以自定義,3.模板消息發送的時間可以自定義。那么我們可以利用這些性質為自己做一款說早安的程序啦!

實驗環境

  1. 阿里雲Linux服務器
  2. Python環境

愛詞霸每日一句API介紹

調用地址:http://open.iciba.com/dsapi/
請求方式:GET
請求參數:

參數 必選 類型 說明
date string 格式為:2013-05-06;如果date為空,則默認取當天
type string 可選值為lastnext;以date日期為准的,last返回前一天的,next返回后一天的

返回類型:JSON
JSON字段解釋:

屬性名 屬性值類型 說明
sid string 每日一句ID
tts string 音頻地址
content string 英文內容
note string 中文內容
love string 每日一句喜歡個數
translation string 詞霸小編
picture string 圖片地址
picture2 string 大圖片地址
caption string 標題
dateline string 時間
s_pv string 瀏覽數
sp_pv string 語音評測瀏覽數
tags array 相關標簽
fenxiang_img string 合成圖片,建議分享微博用的

正常返回示例:

{
  "sid": "3080",
  "tts": "http://news.iciba.com/admin/tts/2018-08-01-day.mp3",
  "content": "No matter how hard we try to be mature, we will always be a kid when we all get hurt and cry. ",
  "note": "不管多努力蛻變成熟,一旦受傷哭泣時,我們還是像個孩子。",
  "love": "1966",
  "translation": "小編的話:這句話出自小說《彼得·潘》。歲月永遠年輕,我們慢慢老去。不管你如何蛻變,最后你會發現:童心未泯,是一件值得驕傲的事情。長大有時很簡單,但凡事都能抱着一顆童心去快樂享受卻未必容易。",
  "picture": "http://cdn.iciba.com/news/word/20180801.jpg",
  "picture2": "http://cdn.iciba.com/news/word/big_20180801b.jpg",
  "caption": "詞霸每日一句",
  "dateline": "2018-08-01",
  "s_pv": "0",
  "sp_pv": "0",
  "tags": [
    {
      "id": null,
      "name": null
    }
  ],
  "fenxiang_img": "http://cdn.iciba.com/web/news/longweibo/imag/2018-08-01.jpg"
}

請求示例:

Python2請求示例

#!/usr/bin/python2
#coding=utf-8
import json
import urllib2
def get_iciba_everyday():
  url = 'http://open.iciba.com/dsapi/'
  request = urllib2.Request(url)
  response = urllib2.urlopen(request)
  json_data = response.read()
  data = json.loads(json_data)
  return data
print get_iciba_everyday()

Python3請求示例

#!/usr/bin/python3
#coding=utf-8
import json
import requests
def get_iciba_everyday():
	url = 'http://open.iciba.com/dsapi/'
	r = requests.get(url)
	return json.loads(r.text)
print(get_iciba_everyday())

PHP請求示例

<?php
function https_request($url, $data = null){
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_HEADER, 0);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
  if (!empty($data)) {
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  }
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  $output = curl_exec($curl);
  curl_close($curl);
  return $output;
}
function get_iciba_everyday(){
  $url = 'http://open.iciba.com/dsapi/'
  $result = https_request($url);
  $data = json_decode($result);
  return $data;
}
echo get_iciba_everyday();

本接口(每日一句)官方文檔:http://open.iciba.com/?c=wiki
參考資料:金山詞霸 · 開發平台

登錄微信公眾平台接口測試賬號

掃描登錄公眾平台測試號
申請測試號的地址 https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

手機上確認登錄

找到新增測試模板,添加模板消息

填寫模板標題每日一句,填寫如下模板內容

{{content.DATA}}

{{note.DATA}}

{{translation.DATA}}

提交保存之后,記住該模板ID,一會兒會用到

找到測試號信息,記住appidappsecret,一會兒會用到

找到測試號二維碼。手機掃描此二維碼,關注之后,你的昵稱會出現在右側列表里,記住該微信號,一會兒會用到(注:此微信號非你真實的微信號)

發送微信模板消息的程序

本程序的GitHub地址:https://github.com/varlemon/wechat-iciba-everyday

本程序您只需要修改4個地方即可,請看注釋

Python2實現

#!/usr/bin/python2
#coding=utf-8
import json
import urllib2

class iciba:
	# 初始化
    def __init__(self, wechat_config):
    	self.appid = wechat_config['appid']
    	self.appsecret = wechat_config['appsecret']
    	self.template_id = wechat_config['template_id']
    	self.access_token = ''

    # 獲取access_token
    def get_access_token(self, appid, appsecret):
    	url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (appid, appsecret)
    	request = urllib2.Request(url)
    	response = urllib2.urlopen(request)
    	json_data = response.read()
    	data = json.loads(json_data)
    	access_token = data['access_token']
    	self.access_token = access_token
    	return self.access_token

    # 獲取用戶列表
    def get_user_list(self):
    	if self.access_token == '':
    		self.get_access_token(self.appid, self.appsecret)
    	access_token = self.access_token
    	url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=' % str(access_token)
    	request = urllib2.Request(url)
    	response = urllib2.urlopen(request)
        result = response.read()
        return json.loads(result)

    # 發送消息
    def send_msg(self, openid, template_id, iciba_everyday):
    	msg = {
	    	'touser': openid,
	    	'template_id': template_id,
	    	'url': iciba_everyday['fenxiang_img'],
	    	'data': {
	    		'content': {
	    			'value': iciba_everyday['content'],
	    			'color': '#0000CD'
	    			},
	    		'note': {
		    		'value': iciba_everyday['note'],
	    		},
	    		'translation': {
		    		'value': iciba_everyday['translation'],
	    		}
	    	}
    	}
    	json_data = json.dumps(msg)
    	if self.access_token == '':
    		self.get_access_token(self.appid, self.appsecret)
    	access_token = self.access_token
    	url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s' % str(access_token)
    	request = urllib2.Request(url, data=json_data)
    	response = urllib2.urlopen(request)
        result = response.read()
        return json.loads(result)

    # 獲取愛詞霸每日一句
    def get_iciba_everyday(self):
    	url = 'http://open.iciba.com/dsapi/'
    	request = urllib2.Request(url)
    	response = urllib2.urlopen(request)
    	json_data = response.read()
    	data = json.loads(json_data)
    	return data

    # 為設置的用戶列表發送消息
    def send_everyday_words(self, openids):
    	everyday_words = self.get_iciba_everyday()
    	for openid in openids:
    		result = self.send_msg(openid, self.template_id, everyday_words)
    		if result['errcode'] == 0:
    			print ' [INFO] send to %s is success' % openid
    		else:
    			print ' [ERROR] send to %s is error' % openid

    # 執行
    def run(self, openids=[]):
    	if openids == []:
    		# 如果openids為空,則遍歷用戶列表
    		result = self.get_user_list()
    		openids = result['data']['openid']
    	# 根據openids對用戶進行群發
    	self.send_everyday_words(openids)


if __name__ == '__main__':
	# 微信配置
	wechat_config = {
		'appid': 'xxxxx', #(No.1)此處填寫你的appid
		'appsecret': 'xxxxx', #(No.2)此處填寫你的appsecret
		'template_id': 'xxxxx' #(No.3)此處填寫你的模板消息ID
	}
	
	# 用戶列表
	openids = [
		'xxxxx', #(No.4)此處填寫你的微信號(微信公眾平台上你的微信號)
		#'xxxxx', #如果有多個用戶也可以
		#'xxxxx',
	]
	

	# 執行
	icb = iciba(wechat_config)
	
	# run()方法可以傳入openids列表,也可不傳參數
	# 不傳參數則對微信公眾號的所有用戶進行群發
	icb.run()



Python3實現

#!/usr/bin/python3
#coding=utf-8
import json
import requests

class iciba:
    # 初始化
    def __init__(self, wechat_config):
        self.appid = wechat_config['appid']
        self.appsecret = wechat_config['appsecret']
        self.template_id = wechat_config['template_id']
        self.access_token = ''

    # 獲取access_token
    def get_access_token(self, appid, appsecret):
        url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (str(appid), str(appsecret))
        r = requests.get(url)
        data = json.loads(r.text)
        access_token = data['access_token']
        self.access_token = access_token
        return self.access_token

    # 獲取用戶列表
    def get_user_list(self):
        if self.access_token == '':
            self.get_access_token(self.appid, self.appsecret)
        access_token = self.access_token
        url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=' % str(access_token)
        r = requests.get(url)
        return json.loads(r.text)

    # 發送消息
    def send_msg(self, openid, template_id, iciba_everyday):
        msg = {
            'touser': openid,
            'template_id': template_id,
            'url': iciba_everyday['fenxiang_img'],
            'data': {
                'content': {
                    'value': iciba_everyday['content'],
                    'color': '#0000CD'
                    },
                'note': {
                    'value': iciba_everyday['note'],
                },
                'translation': {
                    'value': iciba_everyday['translation'],
                }
            }
        }
        json_data = json.dumps(msg)
        if self.access_token == '':
            self.get_access_token(self.appid, self.appsecret)
        access_token = self.access_token
        url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s' % str(access_token)
        r = requests.post(url, json_data)
        return json.loads(r.text)

    # 獲取愛詞霸每日一句
    def get_iciba_everyday(self):
        url = 'http://open.iciba.com/dsapi/'
        r = requests.get(url)
        return json.loads(r.text)

    # 為設置的用戶列表發送消息
    def send_everyday_words(self, openids):
        everyday_words = self.get_iciba_everyday()
        for openid in openids:
            result = self.send_msg(openid, self.template_id, everyday_words)
            if result['errcode'] == 0:
                print (' [INFO] send to %s is success' % openid)
            else:
                print (' [ERROR] send to %s is error' % openid)

    # 執行
    def run(self, openids=[]):
        if openids == []:
            # 如果openids為空,則遍歷用戶列表
            result = self.get_user_list()
            openids = result['data']['openid']
        # 根據openids對用戶進行群發
        self.send_everyday_words(openids)


if __name__ == '__main__':
    # 微信配置
    wechat_config = {
        'appid': 'xxxxx', #(No.1)此處填寫你的appid
        'appsecret': 'xxxxx', #(No.2)此處填寫你的appsecret
        'template_id': 'xxxxx' #(No.3)此處填寫你的模板消息ID
    }
    
    # 用戶列表
    openids = [
        'xxxxx', #(No.4)此處填寫你的微信號(微信公眾平台上你的微信號)
        #'xxxxx', #如果有多個用戶也可以
        #'xxxxx',
    ]

    
    # 執行
    icb = iciba(wechat_config)

    # run()方法可以傳入openids列表,也可不傳參數
    # 不傳參數則對微信公眾號的所有用戶進行群發
    icb.run()



測試程序

在Linux上執行程序

在手機上查看,已經收到了每日一句的消息

部署程序

在Linux上設置定時任務

crontab -e

添加如下內容

0 6 * * *    python /root/python/iciba/main-v1.0.py

注:以上內容的含義是,在每天6:00的時候,執行這個Python程序
查看定時任務是否設置成功

crontab -l

至此,程序部署完成,請您明天6:00查收吧!
效果圖如下

本文鏈接:https://www.cnblogs.com/connect/p/python-wechat-iciba.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM