利用Python將每日一句定時(shí)推送至微信的實(shí)現(xiàn)方法
前言
前幾天在網(wǎng)上看到一篇文章《教你用微信每天給女票說(shuō)晚安》,感覺(jué)很神奇的樣子,隨后研究了一下,構(gòu)思的確是巧妙。好,那就開始動(dòng)工吧!服務(wù)器有了,Python環(huán)境有了,IDE打開了...然而...然而...我意識(shí)到了一個(gè)非常嚴(yán)重的問(wèn)題...沒(méi)有女朋友 (T_T)...
微信開發(fā)已經(jīng)活躍了很長(zhǎng)時(shí)間了,在微信開發(fā)中有一個(gè)神奇的接口它叫模板消息接口,它可以根據(jù)用戶的openid從服務(wù)端給用戶推送自定義的模板消息,正因如此,我們可以利用這個(gè)特征在服務(wù)器端隨時(shí)向用戶推送消息(前提是該用戶關(guān)注了該公眾號(hào))。
總結(jié)出3點(diǎn),1.模板消息的格式可以自定義,2.模板消息的內(nèi)容可以自定義,3.模板消息發(fā)送的時(shí)間可以自定義。那么我們可以利用這些性質(zhì)為自己做一款說(shuō)早安的程序啦!
實(shí)驗(yàn)環(huán)境
- 阿里云Linux服務(wù)器
- Python環(huán)境
調(diào)用地址:http://open.iciba.com/dsapi/
請(qǐng)求方式:GET
請(qǐng)求參數(shù):
參數(shù) | 必選 | 類型 | 說(shuō)明 |
---|---|---|---|
date | 否 | string | 格式為:2013-05-06;如果date為,則默認(rèn)取當(dāng)天 |
type | 否 | string | 可選值為last和next;以date日期為準(zhǔn)的,last返回前一天的,next返回后一天的 |
返回類型:JSON
JSON字段解釋:
屬性名 | 屬性值類型 | 說(shuō)明 |
---|---|---|
sid | string | 每日一句ID |
tts | string | 音頻地址 |
content | string | 英文內(nèi)容 |
note | string | 中文內(nèi)容 |
love | string | 每日一句喜歡個(gè)數(shù) |
translation | string | 詞霸小編 |
picture | string | 圖片地址 |
picture2 | string | 大圖片地址 |
caption | string | 標(biāo)題 |
dateline | string | 時(shí)間 |
s_pv | string | 瀏覽數(shù) |
sp_pv | string | 語(yǔ)音評(píng)測(cè)瀏覽數(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": "不管多努力蛻變成熟,一旦受傷哭泣時(shí),我們還是像個(gè)孩子。", "love": "1966", "translation": "小編的話:這句話出自小說(shuō)《彼得·潘》。歲月永遠(yuǎn)年輕,我們慢慢老去。不管你如何蛻變,最后你會(huì)發(fā)現(xiàn):童心未泯,是一件值得驕傲的事情。長(zhǎng)大有時(shí)很簡(jiǎn)單,但凡事都能抱著一顆童心去快樂(lè)享受卻未必容易。", "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" }
請(qǐng)求示例:
Python2請(qǐng)求示例
#!/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請(qǐng)求示例
#!/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請(qǐng)求示例
<?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ā)平臺(tái)
登錄微信公眾平臺(tái)接口測(cè)試賬號(hào)
掃描登錄公眾平臺(tái)測(cè)試號(hào)
申請(qǐng)測(cè)試號(hào)的地址 https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
手機(jī)上確認(rèn)登錄
找到新增測(cè)試模板,添加模板消息
填寫模板標(biāo)題每日一句,填寫如下模板內(nèi)容
{{content.DATA}}
{{note.DATA}}
{{translation.DATA}}
提交保存之后,記住該模板ID,一會(huì)兒會(huì)用到
找到測(cè)試號(hào)信息,記住appid和appsecret,一會(huì)兒會(huì)用到
找到測(cè)試號(hào)二維碼。手機(jī)掃描此二維碼,關(guān)注之后,你的昵稱會(huì)出現(xiàn)在右側(cè)列表里,記住該微信號(hào),一會(huì)兒會(huì)用到(注:此微信號(hào)非你真實(shí)的微信號(hào))
發(fā)送微信模板消息的程序
本程序您只需要修改4個(gè)地方即可,請(qǐng)看注釋
Python2實(shí)現(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) # 獲取愛(ài)詞霸每日一句 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對(duì)用戶進(jìn)行群發(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)此處填寫你的微信號(hào)(微信公眾平臺(tái)上你的微信號(hào)) #'xxxxx', #如果有多個(gè)用戶也可以 #'xxxxx', ] # 執(zhí)行 icb = iciba(wechat_config) # run()方法可以傳入openids列表,也可不傳參數(shù) # 不傳參數(shù)則對(duì)微信公眾號(hào)的所有用戶進(jìn)行群發(fā) icb.run()
Python3實(shí)現(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) # 獲取愛(ài)詞霸每日一句 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對(duì)用戶進(jìn)行群發(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)此處填寫你的微信號(hào)(微信公眾平臺(tái)上你的微信號(hào)) #'xxxxx', #如果有多個(gè)用戶也可以 #'xxxxx', ] # 執(zhí)行 icb = iciba(wechat_config) # run()方法可以傳入openids列表,也可不傳參數(shù) # 不傳參數(shù)則對(duì)微信公眾號(hào)的所有用戶進(jìn)行群發(fā) icb.run()
本程序的GitHub地址:https://github.com/varlemon/wechat-iciba-everyday
測(cè)試程序
在Linux上執(zhí)行程序
在手機(jī)上查看,已經(jīng)收到了每日一句的消息
部署程序
在Linux上設(shè)置定時(shí)任務(wù)
crontab -e
添加如下內(nèi)容
0 6 * * * python /root/python/iciba/main-v1.0.py
注:以上內(nèi)容的含義是,在每天6:00
的時(shí)候,執(zhí)行這個(gè)Python程序
查看定時(shí)任務(wù)是否設(shè)置成功
crontab -l
至此,程序部署完成,請(qǐng)您明天6:00
查收吧!
效果圖如下
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
python字符串string的內(nèi)置方法實(shí)例詳解
這篇文章主要介紹了python字符串string的內(nèi)置方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2018-05-05基于Python的身份證號(hào)碼自動(dòng)生成程序
今天收到一個(gè)小需求:需要一個(gè)自動(dòng)生成身份證號(hào)碼的小程序。近期用python較多,因此打算用python實(shí)現(xiàn)2014-08-08python的endswith()的使用方法及實(shí)例
這篇文章主要介紹了python的endswith()的使用方法及實(shí)例,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-07-07Pytorch dataloader在加載最后一個(gè)batch時(shí)卡死的解決
這篇文章主要介紹了Pytorch dataloader在加載最后一個(gè)batch時(shí)卡死的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05Python實(shí)現(xiàn)抓取網(wǎng)頁(yè)并且解析的實(shí)例
這篇文章主要介紹了Python實(shí)現(xiàn)抓取網(wǎng)頁(yè)并且解析的功能實(shí)例,主要以解析百度問(wèn)答為例說(shuō)明其原理與方法,需要的朋友可以參考下2014-09-09python-pandas創(chuàng)建Series數(shù)據(jù)類型的操作
這篇文章主要介紹了python-pandas創(chuàng)建Series數(shù)據(jù)類型的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04