Python開發(fā)之快速搭建自動回復(fù)微信公眾號功能
在之前的一篇文章 Python利用 AIML 和 Tornado 搭建聊天機器人微信訂閱號 中用 aiml 實現(xiàn)了一個簡單的英文聊天機器人訂閱號。但是只能處理英文消息,現(xiàn)在用 圖靈機器人 來實現(xiàn)一個中文的聊天機器人訂閱號。
這里主要介紹如何利用 Python 的 Tornado Web框架以及wechat-python-sdk 微信公眾平臺 Python 開發(fā)包來快速搭建微信公眾號。
完整的公眾號代碼 GitHub 地址:green ,由于目前此公眾號有一些功能正在開發(fā)中,此完整代碼會與下文所描述的代碼有不一致的地方,但是自動回復(fù)的功能會一直保留。
本文搭建的微信公眾號為 Ms_haoqi,可以掃碼關(guān)注后測試效果
自動回復(fù)效果:
安裝Python庫
通過 pip 安裝 wechat-python-sdk , Requests 以及 Tornado
pip install tornado pip install wechat-sdk pip install requests
訂閱號申請
要搭建訂閱號,首先需要在微信公眾平臺官網(wǎng)進行注冊,注冊網(wǎng)址: 微信公眾平臺。
目前個人用戶可以免費申請微信訂閱號,雖然很多權(quán)限申請不到,但是基本的消息回復(fù)是沒有問題的。
服務(wù)器接入
具體的接入步驟可以參考官網(wǎng)上的接入指南。
本訂閱號的配置為:
配置里的URL為服務(wù)器提供訂閱號后臺的url路徑,本文用到的源代碼配置的是 http://server_ip/wx 其中 server_ip 是運行源代碼的主機的公網(wǎng)ip地址。
Token 可以設(shè)置為任意字符串。
EncodingAESKey 可以選擇隨機生成。
消息加密方式可以設(shè)置為比較簡單的明文模式。
接受并處理微信服務(wù)器發(fā)送的接入請求的關(guān)鍵代碼為Tornado的一個Handle, wx.py :
import tornado.escape import tornado.web from wechat_sdk import WechatConf conf = WechatConf( token='your_token', # 你的公眾號Token appid='your_appid', # 你的公眾號的AppID appsecret='your_appsecret', # 你的公眾號的AppSecret encrypt_mode='safe', # 可選項:normal/compatible/safe,分別對應(yīng)于 明文/兼容/安全 模式 encoding_aes_key='your_encoding_aes_key' # 如果傳入此值則必須保證同時傳入 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')
此代碼的作用就是驗證消息是來自微信官方服務(wù)器后直接返回echostr。
啟動后臺的 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()
配置好程序源代碼后運行,確認運行無誤后再在公眾號設(shè)置頁面點擊 提交 ,如果程序運行沒問題,會顯示接入成功。
接入圖靈機器人
要接入圖靈機器人,首先需要在官網(wǎng)申請API Key。
申請到之后可以利用以下代碼包裝一個自動回復(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
編寫公眾號自動回復(fù)代碼
利用 wechat-python-sdk 微信公眾平臺 Python 開發(fā)包可以很容易地處理公眾號的所有消息。
如下為處理來自微信官方服務(wù)器的微信公眾號消息的 Tornado Handler對象(此代碼會獲取公眾號收到的用戶消息并調(diào)用剛剛包裝的圖靈機器人API自動回復(fù)) wx.py部分代碼:
# -*- coding: utf-8 -*- import tornado.escape import tornado.web auto_reply = TulingAutoReply(key, url) # key和url填入自己申請到的圖靈key以及圖靈請求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ā)之快速搭建自動回復(fù)微信公眾號功能就給大家介紹這么多,希望對大家有所幫助!
相關(guān)文章
el-table 多表格彈窗嵌套數(shù)據(jù)顯示異常錯亂問題解決方案
使用vue+element開發(fā)報表功能時,需要列表上某列的超鏈接按鈕彈窗展示,在彈窗的el-table列表某列中再次使用超鏈接按鈕點開彈窗,以此類推多表格彈窗嵌套,本文以彈窗兩次為例,需要的朋友可以參考下2023-11-11Pandas?DataFrame.drop()刪除數(shù)據(jù)的方法實例
pandas作為數(shù)據(jù)分析強大的庫,是基于numpy數(shù)組構(gòu)建的,專門用來處理表格和混雜的數(shù)據(jù),下面這篇文章主要給大家介紹了關(guān)于Pandas?DataFrame.drop()刪除數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2022-07-07tensorflow從ckpt和從.pb文件讀取變量的值方式
這篇文章主要介紹了tensorflow從ckpt和從.pb文件讀取變量的值方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python 中的判斷語句,循環(huán)語句,函數(shù)
這篇文章主要介紹了Python 中的判斷語句,循環(huán)語句,函數(shù),文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08