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

.com/gunthercox/chatterbot-corpus/tree/master/chatterbot_corpus/data/chinese 。
那么我们怎么添加训练数据呢?
 
训练机器人chatterBot 内置了training class , 自带的方法有两种 , 一种是使用通过输入list 来训练 , 比如 ["你好", "我不好"] , 后者是前者的回答 , 另一种是通过导入Corpus 格式的文件来训练 。也支持自定义的训练模块 , 不过最终都是转为上述两种类型 。
chatterBot 通过调用 train 函数训练 , 不过在这之前要先用 set_trainer 来进行设置 。例如:
In[12]: from chatterbot.trainers import ListTrainer # 导入训练模块的 ListTrainer 类In[13]: momo.get_response('你叫什么?') # 现在是答非所问 , 因为在这之前我们并没有训练过Out[13]: <Statement text:我在烤蛋糕.>In[14]: momo.set_trainer(ListTrainer) # 指定训练方式In[15]: momo.train(['你叫什么?', '我叫魔魔!']) # 训练In[16]: momo.get_response('你叫什么?') # 现在机器人已经可以回答了Out[16]: <Statement text:我叫魔魔!>训练好的数据默认存在 ./database.db , 这里使用的是 jsondb 。
对 chatterBot 的介绍先到这里 , 具体用法可以参考文档:ChatterBot Tutorial:http://chatterbot.readthedocs.io/en/stable/tutorial.html
接下来 , 介绍如何在项目中使用 chatterBot 。
 
使用 Sanic 创建项目Sanic 是一个和类Flask 的基于Python3.5+的web框架 , 它编写的代码速度特别快 。
除了像Flask 以外 , Sanic 还支持以异步请求的方式处理请求 。这意味着你可以使用新的 async/await 语法 , 编写非阻塞的快速的代码 。
这里之所以使用 Sanic 是因为他和Flask 非常像 , 之前我一直使用Flask , 并且它也是专门为Python3.5 写的 , 使用到了协程 。
首先建个项目 , 这里项目我已经建好了 , 项目结构如下:
.├── LICENSE├── README.md├── manage.py # 运行文件 启动项目 使用 python manage.py 命令├── momo│ ├── __init__.py│ ├── App.py # 创建app 模块│ ├── helper.py│ ├── settings.py # 应用配置│ └── views│ ├── __init__.py│ ├── hello.py # 测试模块│ └── mweixin.py # 微信消息处理模块├── requirements.txt└── supervisord.conf源码我已经上传到github , 有兴趣的可以看一下 , 也可以直接拉下来测试 。项目代码地址
我们先重点看下 hello.py文件 和helper.py
# hello.py# -*- coding: utf-8 -*-from sanic import Sanic, Blueprintfrom sanic.views import HTTPMethodViewfrom sanic.response import textfrom momo.helper import get_momo_answer # 导入获取机器人回答获取函数blueprint = Blueprint('index', url_prefix='/')class ChatBot(HTTPMethodView):# 聊天机器人 http 请求处理逻辑async def get(self, request):ask = request.args.get('ask')# 先获取url 参数值 如果没有值 , 返回 '你说啥'if ask:answer = get_momo_answer(ask)return text(answer)return text('你说啥?')blueprint.add_route(ChatBot.as_view, '/momo')# helper.pyfrom chatterbot import ChatBotmomo_chat = ChatBot('Momo',# 指定存储方式 使用mongodb 存储数据storage_adapter='chatterbot.storage.MongoDatabaseAdapter',# 指定 logic adpater 这里我们指定三个logic_adapters=["chatterbot.logic.BestMatch","chatterbot.logic.MathematicalEvaluation", # 数学模块"chatterbot.logic.TimeLogicAdapter", # 时间模块],input_adapter='chatterbot.input.VariableInputTypeAdapter',output_adapter='chatterbot.output.OutputAdapter',database='chatterbot',read_only=True)def get_momo_answer(content):# 获取机器人返回结果函数response = momo_chat.get_response(content)if isinstance(response, str):return responsereturn response.text运行命令 python manage.py启动项目 。
在浏览器访问url:http://0.0.0.0:8000/momo?ask=你是程序员吗

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

文章插图
到这里 , 我们已经启动了一个web 项目 , 可以通过访问url 的方式和机器人对话 , 是时候接入微信公号了!
 
接入微信公众号前提
  1. 拥有一个可以使用的微信公众号(订阅号服务号都可以 , 如果没有 , 可以使用微信提供的测试账号)
  2. 拥有一个外网可以访问的服务器(vps 或公有云都可以 aws 新用户免费使用一年 , 可以试试)


    推荐阅读