在之前的一篇文章 Python利用 AIML 和 Tornado 搭建聊天機器人微信訂閱號 中用 aiml 實現了一個簡單的英文聊天機器人訂閱號。但是只能處理英文消息,現在用 圖靈機器人 來實現一個中文的聊天機器人訂閱號。
這里主要介紹如何利用 Python 的 Tornado Web框架以及wechat-python-sdk 微信公眾平臺 Python 開發包來快速搭建微信公眾號。
完整的公眾號代碼 GitHub 地址:green ,由于目前此公眾號有一些功能正在開發中,此完整代碼會與下文所描述的代碼有不一致的地方,但是自動回復的功能會一直保留。
本文搭建的微信公眾號為 Ms_haoqi,可以掃碼關注后測試效果
自動回復效果:
安裝Python庫
通過 pip 安裝 wechat-python-sdk , Requests 以及 Tornado
pip install tornadopip install wechat-sdkpip install requests
訂閱號申請
要搭建訂閱號,首先需要在微信公眾平臺官網進行注冊,注冊網址: 微信公眾平臺。
目前個人用戶可以免費申請微信訂閱號,雖然很多權限申請不到,但是基本的消息回復是沒有問題的。
服務器接入
具體的接入步驟可以參考官網上的接入指南。
本訂閱號的配置為:
配置里的URL為服務器提供訂閱號后臺的url路徑,本文用到的源代碼配置的是 http://server_ip/wx 其中 server_ip 是運行源代碼的主機的公網ip地址。
Token 可以設置為任意字符串。
EncodingAESKey 可以選擇隨機生成。
消息加密方式可以設置為比較簡單的明文模式。
接受并處理微信服務器發送的接入請求的關鍵代碼為Tornado的一個Handle, wx.py :
import tornado.escapeimport tornado.webfrom wechat_sdk import WechatConfconf = WechatConf(token='your_token', # 你的公眾號Tokenappid='your_appid', # 你的公眾號的AppIDappsecret='your_appsecret', # 你的公眾號的AppSecretencrypt_mode='safe', # 可選項:normal/compatible/safe,分別對應于 明文/兼容/安全 模式encoding_aes_key='your_encoding_aes_key' # 如果傳入此值則必須保證同時傳入 token, appid)from wechat_sdk import WechatBasicwechat = 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.webimport tornado.httpserverfrom tornado.options import define, optionssettings = {'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 jsonimport requestsimport tracebackclass TulingAutoReply:def __init__(self, tuling_key, tuling_url):self.key = tuling_keyself.url = tuling_urldef 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.textif resp is None or len(resp) == 0:return Nonetry:js = json.loads(resp)if js['code'] == 100000:return js['text'].replace('<br>', '/n')elif js['code'] == 200000:return js['url']else:return Noneexcept Exception:traceback.print_exc()return None 編寫公眾號自動回復代碼
利用 wechat-python-sdk 微信公眾平臺 Python 開發包可以很容易地處理公眾號的所有消息。
如下為處理來自微信官方服務器的微信公眾號消息的 Tornado Handler對象(此代碼會獲取公眾號收到的用戶消息并調用剛剛包裝的圖靈機器人API自動回復) wx.py部分代碼:
# -*- coding: utf-8 -*-import tornado.escapeimport tornado.webauto_reply = TulingAutoReply(key, url) # key和url填入自己申請到的圖靈key以及圖靈請求urlclass WX(tornado.web.RequestHandler):def wx_proc_msg(self, body):try:wechat.parse_data(body)except ParseError:print 'Invalid Body Text'returnif isinstance(wechat.message, TextMessage): # 消息為文本消息content = wechat.message.contentreply = 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 關于Python開發之快速搭建自動回復微信公眾號功能就給大家介紹這么多,希望對大家有所幫助!






















