利用Python將每日一句定時推送至微信的實現(xiàn)方法
前言
前幾天在網(wǎng)上看到一篇文章《教你用微信每天給女票說晚安》,感覺很神奇的樣子,隨后研究了一下,構(gòu)思的確是巧妙。好,那就開始動工吧!服務(wù)器有了,Python環(huán)境有了,IDE打開了...然而...然而...我意識到了一個非常嚴(yán)重的問題...沒有女朋友 (T_T)...
微信開發(fā)已經(jīng)活躍了很長時間了,在微信開發(fā)中有一個神奇的接口它叫模板消息接口,它可以根據(jù)用戶的openid從服務(wù)端給用戶推送自定義的模板消息,正因如此,我們可以利用這個特征在服務(wù)器端隨時向用戶推送消息(前提是該用戶關(guān)注了該公眾號)。
總結(jié)出3點,1.模板消息的格式可以自定義,2.模板消息的內(nèi)容可以自定義,3.模板消息發(fā)送的時間可以自定義。那么我們可以利用這些性質(zhì)為自己做一款說早安的程序啦!
實驗環(huán)境
- 阿里云Linux服務(wù)器
- Python環(huán)境
調(diào)用地址:http://open.iciba.com/dsapi/
請求方式:GET
請求參數(shù):
| 參數(shù) | 必選 | 類型 | 說明 |
|---|---|---|---|
| date | 否 | string | 格式為:2013-05-06;如果date為,則默認取當(dāng)天 |
| type | 否 | string | 可選值為last和next;以date日期為準(zhǔn)的,last返回前一天的,next返回后一天的 |
返回類型:JSON
JSON字段解釋:
| 屬性名 | 屬性值類型 | 說明 |
|---|---|---|
| sid | string | 每日一句ID |
| tts | string | 音頻地址 |
| content | string | 英文內(nèi)容 |
| note | string | 中文內(nèi)容 |
| love | string | 每日一句喜歡個數(shù) |
| translation | string | 詞霸小編 |
| picture | string | 圖片地址 |
| picture2 | string | 大圖片地址 |
| caption | string | 標(biāo)題 |
| dateline | string | 時間 |
| s_pv | string | 瀏覽數(shù) |
| sp_pv | string | 語音評測瀏覽數(shù) |
| tags | array | 相關(guān)標(biāo)簽 |
| 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": "小編的話:這句話出自小說《彼得·潘》。歲月永遠年輕,我們慢慢老去。不管你如何蛻變,最后你會發(fā)現(xiàn):童心未泯,是一件值得驕傲的事情。長大有時很簡單,但凡事都能抱著一顆童心去快樂享受卻未必容易。",
"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_everybody()
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
參考資料:金山詞霸 · 開發(fā)平臺
登錄微信公眾平臺接口測試賬號
掃描登錄公眾平臺測試號
申請測試號的地址 https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

手機上確認登錄

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

填寫模板標(biāo)題每日一句,填寫如下模板內(nèi)容
{{content.DATA}}
{{note.DATA}}
{{translation.DATA}}

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

找到測試號信息,記住appid和appsecret,一會兒會用到

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

發(fā)送微信模板消息的程序
本程序您只需要修改4個地方即可,請看注釋
Python2實現(xiàn)
#!/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)
# 發(fā)送消息
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
# 為設(shè)置的用戶列表發(fā)送消息
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
# 執(zhí)行
def run(self, openids=[]):
if openids == []:
# 如果openids為空,則遍歷用戶列表
result = self.get_user_list()
openids = result['data']['openid']
# 根據(jù)openids對用戶進行群發(fā)
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',
]
# 執(zhí)行
icb = iciba(wechat_config)
# run()方法可以傳入openids列表,也可不傳參數(shù)
# 不傳參數(shù)則對微信公眾號的所有用戶進行群發(fā)
icb.run()
Python3實現(xiàn)
#!/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)
# 發(fā)送消息
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)
# 為設(shè)置的用戶列表發(fā)送消息
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)
# 執(zhí)行
def run(self, openids=[]):
if openids == []:
# 如果openids為空,則遍歷用戶列表
result = self.get_user_list()
openids = result['data']['openid']
# 根據(jù)openids對用戶進行群發(fā)
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',
]
# 執(zhí)行
icb = iciba(wechat_config)
# run()方法可以傳入openids列表,也可不傳參數(shù)
# 不傳參數(shù)則對微信公眾號的所有用戶進行群發(fā)
icb.run()
本程序的GitHub地址:https://github.com/varlemon/wechat-iciba-everyday
測試程序
在Linux上執(zhí)行程序

在手機上查看,已經(jīng)收到了每日一句的消息

部署程序
在Linux上設(shè)置定時任務(wù)
crontab -e
添加如下內(nèi)容
0 6 * * * python /root/python/iciba/main-v1.0.py
注:以上內(nèi)容的含義是,在每天6:00的時候,執(zhí)行這個Python程序
查看定時任務(wù)是否設(shè)置成功
crontab -l
至此,程序部署完成,請您明天6:00查收吧!
效果圖如下

總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
Pytorch dataloader在加載最后一個batch時卡死的解決
這篇文章主要介紹了Pytorch dataloader在加載最后一個batch時卡死的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
Python實現(xiàn)抓取網(wǎng)頁并且解析的實例
這篇文章主要介紹了Python實現(xiàn)抓取網(wǎng)頁并且解析的功能實例,主要以解析百度問答為例說明其原理與方法,需要的朋友可以參考下2014-09-09
python-pandas創(chuàng)建Series數(shù)據(jù)類型的操作
這篇文章主要介紹了python-pandas創(chuàng)建Series數(shù)據(jù)類型的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04

