一小时搭建微信聊天机器人( 三 )


  • 服务器配置了python3 环境 , (建议使用 virtualenvwrapper 配置虚拟环境)
  •  
    微信设置登录微信公众号:https://mp.weixin.qq.com
     
    打开:开发>基本配置查看公号开发信息:
    一小时搭建微信聊天机器人

    文章插图
     
    开启服务器配置:设置请求url , 这里是你配置的url(需要外网可访问 , 只能是80或443端口)
    一小时搭建微信聊天机器人

    文章插图
    填写token和EncodingAESKey , 这里我选择的是兼容模式 , 既有明文方便调试 , 又有信息加密 。
    一小时搭建微信聊天机器人

    文章插图
    详细配置可以参考官方文档:接入指南
    如果你的 服务器地址已经配置完成 , 现在点击提交应该就成功了 。如果没有成功我们接下来看怎么配置服务器地址 。
     
    代码示例先看下 微信请求的视图代码:
    # -*- coding: utf-8 -*-from __future__ import unicode_literalsfrom six import StringIOimport reimport xmltodictfrom chatterbot.trainers import ListTrainerfrom sanic import Blueprintfrom sanic.views import HTTPMethodViewfrom sanic.response import textfrom sanic.exceptions import ServerErrorfrom weixin import WeixinMpAPIfrom weixin.lib.WXBizMsgCrypt import WXBizMsgCryptfrom momo.settings import Configblueprint = Blueprint('weixin', url_prefix='/weixin')class WXRequestView(HTTPMethodView):def _get_args(self, request):# 获取微信请求参数 , 加上token 拼接为完整的请求参数params = request.raw_argsif not params:raise ServerError("invalid params", status_code=400)args = {'mp_token': Config.WEIXINMP_TOKEN,'signature': params.get('signature'),'timestamp': params.get('timestamp'),'echostr': params.get('echostr'),'nonce': params.get('nonce'),}return argsdef get(self, request):# 微信验证服务器这一步是get 请求 , 参数可以使用 request.raw_args 获取args = self._get_args(request)weixin = WeixinMpAPI(**args) # 这里我使用了 第三方包 python-weixin 可以直接实例化一个WeixinMpAPI对象if weixin.validate_signature: # 验证参数合法性# 如果参数争取 , 我们将微信发过来的echostr参数再返回给微信 , 否则返回 failreturn text(args.get('echostr') or 'fail')return text('fail')blueprint.add_route(WXRequestView.as_view, '/request')这里处理微信请求我使用的是 我用python 写的 微信SDK python-weixin , 可以使用 pip 安装:
    pip install python-weixin这个包最新版本对Python3 加密解密有点问题 , 可以直接从github 安装:
    pip install git+https://github.com/zongxiao/python-weixin.git@py3然后更新 app.py 文件:
    # -*- coding: utf-8 -*-from sanic import Sanicfrom momo.settings import Configdef create_app(register_bp=True, test=False):# 创建appapp = Sanic(__name__)if test:app.config['TESTING'] = True# 从object 导入配置app.config.from_object(Config)register_blueprints(app)return appdef register_blueprints(app):from momo.views.hello import blueprint as hello_bpfrom momo.views.mweixin import blueprint as wx_bpapp.register_blueprint(hello_bp)# 注册 wx_bpapp.register_blueprint(wx_bp)详细代码参考github: 微信聊天机器人 momo
     
    接入聊天机器人现在我们公号已经接入了自己的服务 , 是时候接入微信聊天机器人 。
    微信聊天机器人的工作流程如下:
    一小时搭建微信聊天机器人

    文章插图
    看我们消息逻辑处理代码:
    # -*- coding: utf-8 -*-from __future__ import unicode_literalsfrom six import StringIOimport reimport xmltodictfrom chatterbot.trainers import ListTrainerfrom sanic import Blueprintfrom sanic.views import HTTPMethodViewfrom sanic.response import textfrom sanic.exceptions import ServerErrorfrom weixin import WeixinMpAPIfrom weixin.reply import TextReplyfrom weixin.response import WXResponse as _WXResponsefrom weixin.lib.WXBizMsgCrypt import WXBizMsgCryptfrom momo.settings import Configfrom momo.helper import validate_xml, smart_str, get_momo_answerfrom momo.media import media_fetchblueprint = Blueprint('weixin', url_prefix='/weixin')appid = smart_str(Config.WEIXINMP_APPID)token = smart_str(Config.WEIXINMP_TOKEN)encoding_aeskey = smart_str(Config.WEIXINMP_ENCODINGAESKEY)#


    推荐阅读