大部分初学者都是以:自动回复和关键字入群这两个基础功能上手聊天机器人,在此我将介绍如何使用python-wechaty快速实现这两个功能。
一、安装 & 配置
python-wechaty
聊天机器人框架只需要指定版本包以及协议token
即可,安装和配置过程非常简单,无脑复制粘贴即可。
1.1 安装依赖包
# 安装python-wechaty包
pip install wechaty
# 安装插件库
pip install wechaty-plugin-contrib
1.2 配置Token
Token的配置可以有多种方式:
方法一:通过环境变量来配置
*export* WECHATY_PUPPET_HOSTIE_TOKEN='your-token'
方法二:通过python代码来配置
import os
os.environ['WECHATY_PUPPET_HOSTIE_TOKEN'] = 'your-token'
那如何获取长期Token呢?详细请看:Everything-about-Wechaty
二、关键字入群
基于python-wechaty来开发关键字入群功能非常简单,只需要使用到插件库中的:RoomInviterPlugin
插件。
使用方法如下所示:
import asyncio
from typing import Dict
from wechaty import Wechaty
from wechaty_plugin_contrib.contrib import (
RoomInviterOptions,
RoomInviterPlugin
)
from wechaty_plugin_contrib.matchers import (
MessageMatcher,
RoomMatcher
)
async def run():
"""async run method"""
rules: Dict[MessageMatcher, RoomMatcher] = {
MessageMatcher('wechaty'): RoomMatcher('Wechaty开发者群(1)'),
MessageMatcher('python-wechaty'): RoomMatcher('Python-Wechaty开发者群(2)')
}
plugin = RoomInviterPlugin(options=RoomInviterOptions(
name='python-wechaty关键字入群插件',
rules=rules,
welcome='欢迎入群 ~'
))
bot = Wechaty().use(plugin)
await bot.start()
asyncio.run(run())
在有token的前提下,以上代码复制粘贴即可开发一个关键字入群的聊天机器人,是不是非常简单呢?
三、自动回复
自动回复也是我们日常生活工作中的一些高频使用场景,而回复内容不仅限于文字,还可以是图片,文件,链接以及小程序等等。
示例代码如下所示:
import asyncio
from wechaty import Wechaty, MiniProgram # type: ignore
from wechaty_puppet import ( # type: ignore
FileBox
)
from wechaty_plugin_contrib import (
AutoReplyRule,
AutoReplyPlugin,
AutoReplyOptions,
)
from wechaty_plugin_contrib.matchers import ContactMatcher
async def run():
"""async run method"""
img_url = 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy' \
'/it/u=1257042014,3164688936&fm=26&gp=0.jpg'
plugin = AutoReplyPlugin(options=AutoReplyOptions(
rules=[
AutoReplyRule(keyword='ding', reply_content='dong'),
AutoReplyRule(keyword='七龙珠', reply_content='七龙珠'),
AutoReplyRule(
keyword='七龙珠',
reply_content=FileBox.from_url(img_url, name='python.png')
),
AutoReplyRule(
keyword='网易-李白',
reply_content=MiniProgram.create_from_json({...})
)
],
matchers=[
ContactMatcher('秋客'),
]
))
bot = Wechaty().use(plugin)
await bot.start()
asyncio.run(run())
代码非常简单(API设计的很人性化),相信大家一眼就能够看懂,在此我就不做过多解释。
四、总结
python-wechaty有非常人性化的API,同时内置了很多高频功能插件库,提供给开发者能够快速上手开发出自己的小应用。
整个wechaty的目标是面向所有IM平台,打造一款通用聊天机器人框架,也欢迎各位关注并使用python-wechaty框架。