Python開發(fā)之快速搭建自動(dòng)回復(fù)微信公眾號(hào)功能
在之前的一篇文章 Python利用 AIML 和 Tornado 搭建聊天機(jī)器人微信訂閱號(hào) 中用 aiml 實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的英文聊天機(jī)器人訂閱號(hào)。但是只能處理英文消息,現(xiàn)在用 圖靈機(jī)器人 來實(shí)現(xiàn)一個(gè)中文的聊天機(jī)器人訂閱號(hào)。
這里主要介紹如何利用 Python 的 Tornado Web框架以及wechat-python-sdk 微信公眾平臺(tái) Python 開發(fā)包來快速搭建微信公眾號(hào)。
完整的公眾號(hào)代碼 GitHub 地址:green ,由于目前此公眾號(hào)有一些功能正在開發(fā)中,此完整代碼會(huì)與下文所描述的代碼有不一致的地方,但是自動(dòng)回復(fù)的功能會(huì)一直保留。
本文搭建的微信公眾號(hào)為 Ms_haoqi,可以掃碼關(guān)注后測(cè)試效果
自動(dòng)回復(fù)效果:
安裝Python庫(kù)
通過 pip 安裝 wechat-python-sdk , Requests 以及 Tornado
pip install tornado pip install wechat-sdk pip install requests
訂閱號(hào)申請(qǐng)
要搭建訂閱號(hào),首先需要在微信公眾平臺(tái)官網(wǎng)進(jìn)行注冊(cè),注冊(cè)網(wǎng)址: 微信公眾平臺(tái)。
目前個(gè)人用戶可以免費(fèi)申請(qǐng)微信訂閱號(hào),雖然很多權(quán)限申請(qǐng)不到,但是基本的消息回復(fù)是沒有問題的。
服務(wù)器接入
具體的接入步驟可以參考官網(wǎng)上的接入指南。
本訂閱號(hào)的配置為:
配置里的URL為服務(wù)器提供訂閱號(hào)后臺(tái)的url路徑,本文用到的源代碼配置的是 http://server_ip/wx 其中 server_ip 是運(yùn)行源代碼的主機(jī)的公網(wǎng)ip地址。
Token 可以設(shè)置為任意字符串。
EncodingAESKey 可以選擇隨機(jī)生成。
消息加密方式可以設(shè)置為比較簡(jiǎn)單的明文模式。
接受并處理微信服務(wù)器發(fā)送的接入請(qǐng)求的關(guān)鍵代碼為Tornado的一個(gè)Handle, wx.py :
import tornado.escape import tornado.web from wechat_sdk import WechatConf conf = WechatConf( token='your_token', # 你的公眾號(hào)Token appid='your_appid', # 你的公眾號(hào)的AppID appsecret='your_appsecret', # 你的公眾號(hào)的AppSecret encrypt_mode='safe', # 可選項(xiàng):normal/compatible/safe,分別對(duì)應(yīng)于 明文/兼容/安全 模式 encoding_aes_key='your_encoding_aes_key' # 如果傳入此值則必須保證同時(shí)傳入 token, appid ) from wechat_sdk import WechatBasic wechat = WechatBasic(conf=conf) class WX(tornado.web.RequestHandler): def get(self): signature = self.get_argument('signature', 'default') timestamp = self.get_argument('timestamp', 'default') nonce = self.get_argument('nonce', 'default') echostr = self.get_argument('echostr', 'default') if signature != 'default' and timestamp != 'default' and nonce != 'default' and echostr != 'default' \ and wechat.check_signature(signature, timestamp, nonce): self.write(echostr) else: self.write('Not Open')
此代碼的作用就是驗(yàn)證消息是來自微信官方服務(wù)器后直接返回echostr。
啟動(dòng)后臺(tái)的 main.py 代碼:
import tornado.web import tornado.httpserver from tornado.options import define, options settings = { 'static_path': os.path.join(os.path.dirname(__file__), 'static'), 'template_path': os.path.join(os.path.dirname(__file__), 'view'), 'cookie_secret': 'e440769943b4e8442f09de341f3fea28462d2341f483a0ed9a3d5d3859f==78d', 'login_url': '/', 'session_secret': "3cdcb1f07693b6e75ab50b466a40b9977db123440c28307f428b25e2231f1bcc", 'session_timeout': 3600, 'port': 5601, 'wx_token': 'weixin', } web_handlers = [ (r'/wx', wx.WX), ] define("port", default=settings['port'], help="run on the given port", type=int) if __name__ == '__main__': app = tornado.web.Application(web_handlers, **settings) tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
配置好程序源代碼后運(yùn)行,確認(rèn)運(yùn)行無誤后再在公眾號(hào)設(shè)置頁面點(diǎn)擊 提交 ,如果程序運(yùn)行沒問題,會(huì)顯示接入成功。
接入圖靈機(jī)器人
要接入圖靈機(jī)器人,首先需要在官網(wǎng)申請(qǐng)API Key。
申請(qǐng)到之后可以利用以下代碼包裝一個(gè)自動(dòng)回復(fù)接口:
# -*- coding: utf-8 -*- import json import requests import traceback class TulingAutoReply: def __init__(self, tuling_key, tuling_url): self.key = tuling_key self.url = tuling_url def reply(self, unicode_str): body = {'key': self.key, 'info': unicode_str.encode('utf-8')} r = requests.post(self.url, data=body) r.encoding = 'utf-8' resp = r.text if resp is None or len(resp) == 0: return None try: js = json.loads(resp) if js['code'] == 100000: return js['text'].replace('<br>', '\n') elif js['code'] == 200000: return js['url'] else: return None except Exception: traceback.print_exc() return None
編寫公眾號(hào)自動(dòng)回復(fù)代碼
利用 wechat-python-sdk 微信公眾平臺(tái) Python 開發(fā)包可以很容易地處理公眾號(hào)的所有消息。
如下為處理來自微信官方服務(wù)器的微信公眾號(hào)消息的 Tornado Handler對(duì)象(此代碼會(huì)獲取公眾號(hào)收到的用戶消息并調(diào)用剛剛包裝的圖靈機(jī)器人API自動(dòng)回復(fù)) wx.py部分代碼:
# -*- coding: utf-8 -*- import tornado.escape import tornado.web auto_reply = TulingAutoReply(key, url) # key和url填入自己申請(qǐng)到的圖靈key以及圖靈請(qǐng)求url class WX(tornado.web.RequestHandler): def wx_proc_msg(self, body): try: wechat.parse_data(body) except ParseError: print 'Invalid Body Text' return if isinstance(wechat.message, TextMessage): # 消息為文本消息 content = wechat.message.content reply = auto_reply.reply(content) if reply is not None: return wechat.response_text(content=reply) else: return wechat.response_text(content=u"不知道你說的什么") return wechat.response_text(content=u'知道了') def post(self): signature = self.get_argument('signature', 'default') timestamp = self.get_argument('timestamp', 'default') nonce = self.get_argument('nonce', 'default') if signature != 'default' and timestamp != 'default' and nonce != 'default' \ and wechat.check_signature(signature, timestamp, nonce): body = self.request.body.decode('utf-8') try: result = self.wx_proc_msg(body) if result is not None: self.write(result) except IOError, e: return
關(guān)于Python開發(fā)之快速搭建自動(dòng)回復(fù)微信公眾號(hào)功能就給大家介紹這么多,希望對(duì)大家有所幫助!
相關(guān)文章
運(yùn)籌學(xué)-Python實(shí)現(xiàn)圖論與最短距離
需要求解任意兩個(gè)節(jié)點(diǎn)之間的最短距離,使用?Floyd?算法,只要求解單源最短路徑問題,有負(fù)權(quán)邊時(shí)使用?Bellman-Ford?算法,沒有負(fù)權(quán)邊時(shí)使用?Dijkstra?算法,本節(jié)我們只討論Dijkstra?算法,需要的朋友可以參考一下2022-01-01el-table 多表格彈窗嵌套數(shù)據(jù)顯示異常錯(cuò)亂問題解決方案
使用vue+element開發(fā)報(bào)表功能時(shí),需要列表上某列的超鏈接按鈕彈窗展示,在彈窗的el-table列表某列中再次使用超鏈接按鈕點(diǎn)開彈窗,以此類推多表格彈窗嵌套,本文以彈窗兩次為例,需要的朋友可以參考下2023-11-11python實(shí)現(xiàn)支付寶當(dāng)面付(掃碼支付)功能
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)支付寶當(dāng)面付,掃碼支付功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05Pandas?DataFrame.drop()刪除數(shù)據(jù)的方法實(shí)例
pandas作為數(shù)據(jù)分析強(qiáng)大的庫(kù),是基于numpy數(shù)組構(gòu)建的,專門用來處理表格和混雜的數(shù)據(jù),下面這篇文章主要給大家介紹了關(guān)于Pandas?DataFrame.drop()刪除數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2022-07-07tensorflow從ckpt和從.pb文件讀取變量的值方式
這篇文章主要介紹了tensorflow從ckpt和從.pb文件讀取變量的值方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python 中的判斷語句,循環(huán)語句,函數(shù)
這篇文章主要介紹了Python 中的判斷語句,循環(huán)語句,函數(shù),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08