一小时搭建微信聊天机器人(如何搭建聊天机器人)
ccwgpt 2024-10-02 12:18 45 浏览 0 评论
最近在研究公众号的开发,前段时间已经上线了电子书关键词的回复功能,调研过程中发现了 Chatterbot 这个不错的 Python 机器人库,因此找了一篇还不错的实践教程,经作者授权后分享推荐给大家。
看完之后,你应该可以学会如何正确地接入一个 Chatterbot 应用。
另外,周日推的那篇推文我在筛选合作的时候不够谨慎,商家的主体和宣传信息存在很大的误导性,因此我已经删除文章了,在这里跟大家道个歉!也提醒昨天几位购买了产品的同学,建议拒收或者退货处理。抱歉~
EarlGrey
文 | goodspeed
编辑 | EarlGrey
推荐 | 编程派公众号(ID:codingpy)
使用Python实现聊天机器人的方案有多种:AIML、chatterBot以及图灵聊天机器人和微软小冰等。
考虑到以后可能会做一些定制化的需求,这里我选择了chatterBot
(github 项目地址:https://github.com/gunthercox/ChatterBot)。
chatterbot是一款python接口的,基于一系列规则和机器学习算法完成的聊天机器人。具有结构清晰,可扩展性好,简单实用的特点。
chatterBot 的工作流程如图:
输入模块(input adapter)从终端或者API等输入源获取数据
输入源会被指定的逻辑处理模块(logic Adapter)分别处理,逻辑处理模块会匹配训练集中已知的最接近输入数据句子A,然后根据句子A去找到相关度最高的结果B,如果有多个逻辑处理模块返回了不同的结果,会返回一个相关度最高的结果。
输出模块(output adapter)将匹配到的结果返回给终端或者API。
值得一说的是chatterBot 是一个模块化的项目,分为 input Adapter、logic Adapter、storage Adapter、output Adapter以及Trainer 模块。
logic Adapter是一个插件式设计,主进程在启动时会将用户定义的所有逻辑处理插件添加到logic context中,然后交MultiLogicAdapter 进行处理,MultiLogicAdapter 依次调用每个 logic Adapter,logic Adapter 被调用时先执行can_process 方式判断输入是否可以命中这个逻辑处理插件。比如”今天天气怎么样“这样的问题显然需要命中天气逻辑处理插件,这时时间逻辑处理插件的can_process 则会返回False。在命中后logic Adapter 负责计算出对应的回答(Statement对象)以及可信度(confidence),MultiLogicAdapter会取可信度最高的回答,并进入下一步。
下面我们来看下 chatterBot 如何使用
安装
chatterBot 是使用Python编写的,可以使用 pip 安装:
pip install chatterbot
chatterBot 的中文对话要求Python3 以上版本,建议在Python3.x 环境下开发
测试
打开iPython,输入测试一下
In[1]: from chatterbot import ChatBot # import ChatBot
In[2]: momo = ChatBot('Momo', trainer='chatterbot.trainers.ChatterBotCorpusTrainer')
/Users/gs/.virtualenvs/py3/lib/python3.6/site-packages/chatterbot/storage/jsonfile.py:26: UnsuitableForProductionWarning: The JsonFileStorageAdapter is not recommended for production environments.
self.UnsuitableForProductionWarning # 这里storage adapter 默认使用的是 json 格式存储数据的,如果想在服务端部署,应该避免使用这种格式,因为实在是太慢了
In[3]: momo.train("chatterbot.corpus.chinese") # 指定训练集,这里我们使用中文
# 下边是对话结果
In[4]: momo.get_response('你好')
Out[4]: <Statement text:你好>
In[5]: momo.get_response('怎么了')
Out[5]: <Statement text:没什么.>
In[6]: momo.get_response('你知道它的所有内容吗?')
Out[6]: <Statement text:优美胜于丑陋.>
In[7]: momo.get_response('你是一个程序员吗?')
Out[7]: <Statement text:我是个程序员>
In[8]: momo.get_response('你使用什么语言呢?')
Out[8]: <Statement text:我经常使用 Python, Java 和 C++ .>
这时你已经可以和机器人对话了,不过现在由于训练数据太少,机器人只能返回简单的对话。
这里是默认的中文对话训练数据 中文训练数据地址:https://github.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, Blueprint
from sanic.views import HTTPMethodView
from sanic.response import text
from 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.py
from chatterbot import ChatBot
momo_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 response
return response.text
运行命令 python manage.py
启动项目。
在浏览器访问url:http://0.0.0.0:8000/momo?ask=你是程序员吗
到这里,我们已经启动了一个web 项目,可以通过访问url 的方式和机器人对话,是时候接入微信公号了!
接入微信公众号
前提
拥有一个可以使用的微信公众号(订阅号服务号都可以,如果没有,可以使用微信提供的测试账号)
拥有一个外网可以访问的服务器(vps 或公有云都可以 aws 新用户免费使用一年,可以试试)
服务器配置了python3 环境,(建议使用 virtualenvwrapper 配置虚拟环境)
微信设置
登录微信公众号:https://mp.weixin.qq.com
打开:开发>基本配置
查看公号开发信息:
开启服务器配置:
设置请求url,这里是你配置的url(需要外网可访问,只能是80或443端口)
填写token和EncodingAESKey,这里我选择的是兼容模式,既有明文方便调试,又有信息加密。
详细配置可以参考官方文档:接入指南
如果你的 服务器地址
已经配置完成,现在点击提交应该就成功了。如果没有成功我们接下来看怎么配置服务器地址。
代码示例
先看下 微信请求的视图代码:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from six import StringIO
import re
import xmltodict
from chatterbot.trainers import ListTrainer
from sanic import Blueprint
from sanic.views import HTTPMethodView
from sanic.response import text
from sanic.exceptions import ServerError
from weixin import WeixinMpAPI
from weixin.lib.WXBizMsgCrypt import WXBizMsgCrypt
from momo.settings import Config
blueprint = Blueprint('weixin', url_prefix='/weixin')
class WXRequestView(HTTPMethodView):
def _get_args(self, request):
# 获取微信请求参数,加上token 拼接为完整的请求参数
params = request.raw_args
if 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 args
def get(self, request):
# 微信验证服务器这一步是get 请求,参数可以使用 request.raw_args 获取
args = self._get_args(request)
weixin = WeixinMpAPI(**args) # 这里我使用了 第三方包 python-weixin 可以直接实例化一个WeixinMpAPI对象
if weixin.validate_signature: # 验证参数合法性
# 如果参数争取,我们将微信发过来的echostr参数再返回给微信,否则返回 fail
return 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 Sanic
from momo.settings import Config
def create_app(register_bp=True, test=False):
# 创建app
app = Sanic(__name__)
if test:
app.config['TESTING'] = True
# 从object 导入配置
app.config.from_object(Config)
register_blueprints(app)
return app
def register_blueprints(app):
from momo.views.hello import blueprint as hello_bp
from momo.views.mweixin import blueprint as wx_bp
app.register_blueprint(hello_bp)
# 注册 wx_bp
app.register_blueprint(wx_bp)
详细代码参考github: 微信聊天机器人 momo
接入聊天机器人
现在我们公号已经接入了自己的服务,是时候接入微信聊天机器人。
微信聊天机器人的工作流程如下:
看我们消息逻辑处理代码:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from six import StringIO
import re
import xmltodict
from chatterbot.trainers import ListTrainer
from sanic import Blueprint
from sanic.views import HTTPMethodView
from sanic.response import text
from sanic.exceptions import ServerError
from weixin import WeixinMpAPI
from weixin.reply import TextReply
from weixin.response import WXResponse as _WXResponse
from weixin.lib.WXBizMsgCrypt import WXBizMsgCrypt
from momo.settings import Config
from momo.helper import validate_xml, smart_str, get_momo_answer
from momo.media import media_fetch
blueprint = Blueprint('weixin', url_prefix='/weixin')
appid = smart_str(Config.WEIXINMP_APPID)
token = smart_str(Config.WEIXINMP_TOKEN)
encoding_aeskey = smart_str(Config.WEIXINMP_ENCODINGAESKEY)
# 关注后自动返回的文案
AUTO_REPLY_CONTENT = """
Hi,朋友!
这是我妈四月的公号,我是魔魔,我可以陪你聊天呦!
我还能"记账",输入"记账"会有惊喜呦!
<a href=""">历史记录</a>
"""
class ReplyContent(object):
_source = 'value'
def __init__(self, event, keyword, content=None, momo=True):
self.momo = momo
self.event = event
self.content = content
self.keyword = keyword
if self.event == 'scan':
pass
@property
def value(self):
if self.momo:
answer = get_momo_answer(self.content)
return answer
return ''
class WXResponse(_WXResponse):
auto_reply_content = AUTO_REPLY_CONTENT
def _subscribe_event_handler(self):
# 关注公号后的处理逻辑
self.reply_params['content'] = self.auto_reply_content
self.reply = TextReply(**self.reply_params).render
def _unsubscribe_event_handler(self):
# 取关后的处理逻辑,取关我估计会哭吧
pass
def _text_msg_handler(self):
# 文字消息处理逻辑 聊天机器人的主要逻辑
event_key = 'text'
content = self.data.get('Content')
reply_content = ReplyContent('text', event_key, content)
self.reply_params['content'] = reply_content.value
self.reply = TextReply(**self.reply_params).render
class WXRequestView(HTTPMethodView):
def _get_args(self, request):
params = request.raw_args
if 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 args
def get(self, request):
args = self._get_args(request)
weixin = WeixinMpAPI(**args)
if weixin.validate_signature:
return text(args.get('echostr') or 'fail')
return text('fail')
def _get_xml(self, data):
post_str = smart_str(data)
# 验证xml 格式是否正确
validate_xml(StringIO(post_str))
return post_str
def _decrypt_xml(self, params, crypt, xml_str):
# 解密消息
nonce = params.get('nonce')
msg_sign = params.get('msg_signature')
timestamp = params.get('timestamp')
ret, decryp_xml = crypt.DecryptMsg(xml_str, msg_sign,
timestamp, nonce)
return decryp_xml, nonce
def _encryp_xml(self, crypt, to_xml, nonce):
# 加密消息
to_xml = smart_str(to_xml)
ret, encrypt_xml = crypt.EncryptMsg(to_xml, nonce)
return encrypt_xml
def post(self, request):
# 获取微信服务器发送的请求参数
args = self._get_args(request)
weixin = WeixinMpAPI(**args)
if not weixin.validate_signature: # 验证参数合法性
raise AttributeError("Invalid weixin signature")
xml_str = self._get_xml(request.body) # 获取form data
crypt = WXBizMsgCrypt(token, encoding_aeskey, appid)
decryp_xml, nonce = self._decrypt_xml(request.raw_args, crypt, xml_str) # 解密
xml_dict = xmltodict.parse(decryp_xml)
xml = WXResponse(xml_dict) or 'success' # 使用WXResponse 根据消息获取机器人返回值
encryp_xml = self._encryp_xml(crypt, xml, nonce) # 加密消息
return text(encryp_xml or xml) # 回应微信请求
blueprint.add_route(WXRequestView.as_view, '/request')
可以看到,我处理微信请求返回结果比较简单,也是使用的 python-weixin 包封装的接口,主要的处理逻辑是 WXResponse。
这里需要注意的是,如果服务器在5秒内没有响应微信服务器会重试。为了加快响应速度,不要在服务器 将 chatterBot 的 storage adapter 设置为使用 jsondb。
上边这些就是,微信聊天机器人的主要处理逻辑,我们运行服务,示例如下:
可以看到这里聊天机器人也可以做简单的数学运算和报时,是因为我在上边指定处理逻辑的时候添加了数学模块和时间模块:
momo_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
)
到这里,微信机器人的搭建就完成了,详细代码已经长传到了 github: https://github.com/gusibi/momo/tree/chatterbot,感兴趣的可以参考一下。
参考链接
ChatterBot 项目地址:https://github.com/gunthercox/ChatterBot
ChatterBot Tutorial:http://chatterbot.readthedocs.io/en/stable/tutorial.html
用Python快速实现一个聊天机器人:http://www.jianshu.com/p/d1333fde266f
基于Python-ChatterBot搭建不同adapter的聊天机器人:https://ask.hellobi.com/blog/guodongwei1991/7626
擁有自動學習的 Python 機器人 - ChatterBot:https://kantai235.github.io/2017/03/16/ChatterBotTeaching/
使用 ChatterBot构建聊天机器人:https://www.biaodianfu.com/chatterbot.html
python-weixin sdk: https://github.com/gusibi/python-weixin
回复下方「关键词」,获取优质资源
回复关键词「 pybook03」,立即获取主页君与小伙伴一起翻译的《Think Python 2e》电子版
回复关键词「书单02」,立即获取主页君整理的 10 本 Python 入门书的电子版
相关推荐
- 一个基于.Net Core遵循Clean Architecture原则开源架构
-
今天给大家推荐一个遵循CleanArchitecture原则开源架构。项目简介这是基于Asp.netCore6开发的,遵循CleanArchitecture原则,可以高效、快速地构建基于Ra...
- AI写代码翻车无数次,我发现只要提前做好这3步,bug立减80%
-
写十万行全是bug之后终于找到方法了开发"提示词管理助手"新版本那会儿,我差点被bug整崩溃。刚开始两周,全靠AI改代码架构,结果十万行程序漏洞百出。本来以为AI说没问题就稳了,结果...
- OneCode低代码平台的事件驱动设计:架构解析与实践
-
引言:低代码平台的事件驱动范式在现代软件开发中,事件驱动架构(EDA)已成为构建灵活、松耦合系统的核心范式。OneCode低代码平台通过创新性的注解驱动设计,将事件驱动理念深度融入平台架构,实现了业务...
- 国内大厂AI插件评测:根据UI图生成Vue前端代码
-
在IDEA中安装大厂的AI插件,打开ruoyi增强项目:yudao-ui-admin-vue31.CodeBuddy插件登录腾讯的CodeBuddy后,大模型选择deepseek-v3,输入提示语:...
- AI+低代码技术揭秘(二):核心架构
-
本文档介绍了为VTJ低代码平台提供支持的基本架构组件,包括Engine编排层、Provider服务系统、数据模型和代码生成管道。有关UI组件库和widget系统的信息,请参阅UI...
- GitDiagram用AI把代码库变成可视化架构图
-
这是一个名为gitdiagram的开源工具,可将GitHub仓库实时转换为交互式架构图,帮助开发者快速理解代码结构。核心功能一键可视化:替换GitHubURL中的"hub...
- 30天自制操作系统:第六天:代码架构整理与中断处理
-
1.拆开bootpack.c文件。根据设计模式将对应的功能封装成独立的文件。2.初始化pic:pic(可编程中断控制器):在设计上,cpu单独只能处理一个中断。而pic是将8个中断信号集合成一个中断...
- AI写代码越帮越忙?2025年研究揭露惊人真相
-
近年来,AI工具如雨后春笋般涌现,许多人开始幻想程序员的未来就是“对着AI说几句话”,就能轻松写出完美的代码。然而,2025年的一项最新研究却颠覆了这一期待,揭示了一个令人意外的结果。研究邀请了16位...
- 一键理解开源项目:两个自动生成GitHub代码架构图与说明书工具
-
一、GitDiagram可以一键生成github代码仓库的架构图如果想要可视化github开源项目:https://github.com/luler/reflex_ai_fast,也可以直接把域名替换...
- 5分钟掌握 c# 网络通讯架构及代码示例
-
以下是C#网络通讯架构的核心要点及代码示例,按协议类型分类整理:一、TCP协议(可靠连接)1.同步通信//服务器端usingSystem.Net.Sockets;usingTcpListene...
- 从复杂到优雅:用建造者和责任链重塑代码架构
-
引用设计模式是软件开发中的重要工具,它为解决常见问题提供了标准化的解决方案,提高了代码的可维护性和可扩展性,提升了开发效率,促进了团队协作,提高了软件质量,并帮助开发者更好地适应需求变化。通过学习和应...
- 低代码开发当道,我还需要学习LangChain这些框架吗?| IT杂谈
-
专注LLM深度应用,关注我不迷路前两天有位兄弟问了个问题:当然我很能理解这位朋友的担忧:期望效率最大化,时间用在刀刃上,“不要重新发明轮子”嘛。铺天盖地的AI信息轰炸与概念炒作,很容易让人浮躁与迷茫。...
- 框架设计并不是简单粗暴地写代码,而是要先弄清逻辑
-
3.框架设计3.框架设计本节我们要开发一个UI框架,底层以白鹭引擎为例。框架设计的第一步并不是直接撸代码,而是先想清楚设计思想,抽象。一个一个的UI窗口是独立的吗?不是的,...
- 大佬用 Avalonia 框架开发的 C# 代码 IDE
-
AvalonStudioAvalonStudio是一个开源的跨平台的开发编辑器(IDE),AvalonStudio的目标是成为一个功能齐全,并且可以让开发者快速使用的IDE,提高开发的生产力。A...
- 轻量级框架Lagent 仅需20行代码即可构建自己的智能代理
-
站长之家(ChinaZ.com)8月30日消息:Lagent是一个专注于基于LLM模型的代理开发的轻量级框架。它的设计旨在简化和提高这种模型下代理的开发效率。LLM模型是一种强大的工具,可以...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- 框架图 (58)
- flask框架 (53)
- quartz框架 (51)
- abp框架 (47)
- springmvc框架 (49)
- 分布式事务框架 (65)
- scrapy框架 (56)
- shiro框架 (61)
- 定时任务框架 (56)
- java日志框架 (61)
- mfc框架 (52)
- abb框架断路器 (48)
- beego框架 (52)
- java框架spring (58)
- grpc框架 (65)
- tornado框架 (48)
- 前端框架bootstrap (54)
- orm框架有哪些 (51)
- 知识框架图 (52)
- ppt框架 (55)
- 框架图模板 (59)
- 内联框架 (52)
- cad怎么画框架 (58)
- ssm框架实现登录注册 (49)
- oracle字符串长度 (48)