利用 EasyWeChat 和 ChatterBot 简单搭建一个公众号「自动回复机器人」

2,964 阅读4分钟

自从公众号列表页改版以来,很多人都说会弱化公众号菜单的作用。

363F584F-0C0A-4D9C-B23B-7A6EAA0B0A3B

而且,对于个人号来说,开发模式下是不能操作菜单开发的。

所以我们索性「放弃菜单」,制作「自动回复」来替代菜单功能。

开发「自动回复」功能,本文特推荐两个工具:

  • EasyWeChat

微信开发,从未如此简单 每一个功能设计,都经过精心打磨,只为了提供更好的开发体验

www.easywechat.com/

在我的「Laravel 学习图谱」github.com/fanly/larav…中,把这个 EasyWeChat 作为首推,值得大家一试。

  • ChatterBot

ChatterBot is a Python library that makes it easy to generate automated responses to a user’s input.

chatterbot.readthedocs.io/en/stable/

注: 上图来自 ChatterBot 网站

下面简述对这两个工具的使用,来构建我们的「自动回复」功能。

EasyWeChat

正如其官网所述的那样,只要简单引入,几步就可以开发公众号管理系统了。

1. 安装 EasyWeChat 插件
composer require "overtrue/laravel-wechat:~4.0"

2. 添加配置文件
php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider"

3. 在 config/wechat.php 配置文件加入公众号参数

4. 添加路由
Route::any('wechat', 'WeChatController@serve');

5. 增加 WeChatController
public function serve()
{
    $app = app('wechat.official_account');
    $app->server->push(function ($message) {
        switch ($message['MsgType']) {
            case 'text':
                return $this->getChatBotMessage($message['Content']);
                break;
            default:
                $data = $this->article->random();
                if ($data) {
                    return $data->title
                        ."\n"
                        ."https://www.coding01.cn/"
                        .$data->slug;
                }
                return '收到其它消息';
                break;
        }
    });

    return $app->server->serve();
}

好了,我们根据获取的消息的类型,做对应的处理,如,发送的文本消息,则通过 ChatterBot 自动聊天回复;如果是其他的消息,则随机回复一篇我们的文章。

可以看看效果:

1F022C85-8757-4338-B2DB-CB6732D0ADE6

对于「EasyWeChat」其它功能,可以参考官网说明。目前暂时够用,就不再深入分析了。

ChatterBot

无论国内网,有很多做「自动机器人」的

  • 国外:wit.ai, api.ai, luis.ai
  • 国内:yige.ai, ruyi.ai

但对于程序员来说,使用平台来达到目标,好像显得有点 low,不够装逼

所以我们还是折腾折腾,找一些比较简单又易于扩展的开源代码来用用,而且还能学习扩展,一举多得。

在我读书的时候,知道要实现 AI,主要步骤包含:

  1. 模式建立;
  2. 训练集训练;
  3. 特征提取;
  4. 模式识别,智能匹配;
  5. 测试

而寻找了一圈,发现 ChatterBot 比较合适我们使用和学习。

当然今天的目标是看如何使用:

安装 ChatterBot

使用 pip 安装,还是很方便:

pip install chatterbot

初次使用

简单加入几条语句用于训练。

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

chatbot = ChatBot("yemeishuBot")

conversation = [
    "Hello",
    "Hi there!",
    "How are you doing?",
    "I'm doing great",
    "That is good to hear",
    "Thank you.",
    "You're welcome."
]

chatbot.set_trainer(ListTrainer)
chatbot.train(conversation)

response = chatbot.get_response("How are you doing?")
print(response)

看看运行结果:

TerminalAdapter

使用终端输入输出。

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

chatbot = ChatBot(
    "yemeishuBot",
    input_adapter="chatterbot.input.TerminalAdapter",
    output_adapter="chatterbot.output.TerminalAdapter",
    )

conversation = [
    "Hello",
    "Hi there!",
    "How are you doing?",
    "I'm doing great",
    "That is good to hear",
    "Thank you.",
    "You're welcome."
]

chatbot.set_trainer(ListTrainer)
chatbot.train(conversation)

print("Type something to begin...")

# The following loop will execute each time the user enters input
while True:
    try:
        # We pass None to this method because the parameter
        # is not used by the TerminalAdapter
        bot_input = chatbot.get_response(None)

    # Press ctrl-c or ctrl-d on the keyboard to exit
    except (KeyboardInterrupt, EOFError, SystemExit):
        break

可以在终端输入,得结果了:

使用中文语料

我的公众号,主要针对国内用户,当然要使用中文语料来做智能回复。

from chatterbot import ChatBot

chatbot = ChatBot(
    "yemeishuBot",
    input_adapter="chatterbot.input.TerminalAdapter",
    output_adapter="chatterbot.output.TerminalAdapter",
    trainer='chatterbot.trainers.ChatterBotCorpusTrainer'
)

chatbot.train('chatterbot.corpus.chinese')
print("Type something to begin...")

# The following loop will execute each time the user enters input
while True:
    try:
        # We pass None to this method because the parameter
        # is not used by the TerminalAdapter
        bot_input = chatbot.get_response(None)

    # Press ctrl-c or ctrl-d on the keyboard to exit
    except (KeyboardInterrupt, EOFError, SystemExit):
        break

使用 flask 封装

当然最后,我们需要做成接口,供多地方使用。

本文推荐使用这个:github.com/chamkank/fl…

Simple boilerplate for ChatterBot using Flask

安装插件:

pip install -r requirements.txt

在后台运行:

nohup python -u flush.py > flush.log 2>&1 &

结合 EasyWeChat 和 ChatterBot

这就很简单了,只要在我们的 PHP 代码中直接调用这个接口即可:

public function getChatBotMessage($content)
{
    $client = new Client(['base_uri' => 'http://localhost:5000']);
    $response = $client->request('GET', 'get', [
        'query' => ['msg' => $content]
    ]);

    return $response->getBody()->getContents();
}

显示效果:

总结

今天利用 EasyWeChat 和 ChatterBot 简单搭建一个公众号「自动回复机器人」,利用 EasyWeChat 桥接好公众号和机器人。

之后我们就可以不断完善 ChatterBot 功能,结合系统项目中的文章内容,作为我们自己的语料做训练,提高机器人的自动回复能力。

当然可以参考微软推出 AI 开发免费电子书,手把手教你构建智能聊天机器人《A Developer’s Guide to Building AI Applications》中的架构来设计:

最后,你也可以试试其他,如基于 tensorflow 的机器人。