Python快速搭建自動回復微信公眾號
在之前的一篇文章 Python利用 AIML 和 Tornado 搭建聊天機器人微信訂閱號 中用 aiml 實現了一個簡單的英文聊天機器人訂閱號。但是只能處理英文消息,現在用 圖靈機器人 來實現一個中文的聊天機器人訂閱號。
這里主要介紹如何利用 Python 的 Tornado Web框架以及wechat-python-sdk 微信公眾平臺 Python 開發包來快速搭建微信公眾號。
完整的公眾號代碼 GitHub 地址:green ,由于目前此公眾號有一些功能正在開發中,此完整代碼會與下文所描述的代碼有不一致的地方,但是自動回復的功能會一直保留。
自動回復效果:
安裝Python庫
通過 pip 安裝 wechat-python-sdk , Requests 以及 Tornado
pip install tornado
pip install wechat-sdk
pip install requests
訂閱號申請
要搭建訂閱號,首先需要在微信公眾平臺官網進行注冊,注冊網址: 微信公眾平臺。
目前個人用戶可以免費申請微信訂閱號,雖然很多權限申請不到,但是基本的消息回復是沒有問題的。
服務器接入
具體的接入步驟可以參考官網上的接入指南。
本訂閱號的配置為:
配置里的URL為服務器提供訂閱號后臺的url路徑,本文用到的源代碼配置的是 http://server_ip/wx 其中 server_ip 是運行源代碼的主機的公網ip地址。
Token 可以設置為任意字符串。
EncodingAESKey 可以選擇隨機生成。
消息加密方式可以設置為比較簡單的明文模式。
接受并處理微信服務器發送的接入請求的關鍵代碼為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,分別對應于 明文/兼容/安全 模式
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')
此代碼的作用就是驗證消息是來自微信官方服務器后直接返回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()
配置好程序源代碼后運行,確認運行無誤后再在公眾號設置頁面點擊 提交 ,如果程序運行沒問題,會顯示接入成功。
接入圖靈機器人
要接入圖靈機器人,首先需要在官網申請API Key。
申請到之后可以利用以下代碼包裝一個自動回復接口:
# -*- 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
編寫公眾號自動回復代碼
利用 wechat-python-sdk 微信公眾平臺 Python 開發包可以很容易地處理公眾號的所有消息。
如下為處理來自微信官方服務器的微信公眾號消息的 Tornado Handler對象(此代碼會獲取公眾號收到的用戶消息并調用剛剛包裝的圖靈機器人API自動回復) 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
來自: http://blog.csdn.net/tobacco5648/article/details/51190039