在当今自动化和智能化需求日益增长的时代,企业微信、公众号、小助手等自动聊天工具层出不穷。wechaty 是一个跨平台的聊天机器人 sdk,支持多语言开发,包括 javascript、python、go、rust 等,帮助开发者快速构建微信机器人。
本文将介绍如何基于 python 语言使用 wechaty,构建一个简单的微信机器人。
一、什么是 wechaty
wechaty 是一个专为微信生态设计的聊天机器人框架,它支持私有部署、云端服务,并提供多种 puppet 插件接入微信协议,如:
- wechaty-puppet-wechat4u(个人微信网页版)
- wechaty-puppet-padplus(已停用)
- wechaty-puppet-service(推荐,官方提供 token 服务接入)
- wechaty-puppet-wecom(企业微信)
二、环境准备
1. 安装 python 环境
确保本地已安装 python3.7+,推荐使用 python3.9 版本:
python3 --version pip3 --version
建议创建虚拟环境:
python3 -m venv .venv source .venv/bin/activate
2. 安装 wechaty python sdk
pip install wechaty
三、获取 puppet token
以 wechaty-puppet-service 为例
访问 https://wechaty.js.org/docs/puppet-services/ 并注册一个账号,获取免费的 puppet_service_token。这是连接微信服务的关键凭据。
四、编写机器人代码
from wechaty import wechaty, message, contact
class mybot(wechaty):
async def on_message(self, msg: message):
text = msg.text()
talker = msg.talker()
print(f'message from {talker.name}: {text}')
if text.lower() == 'ping':
await msg.say('pong')
if __name__ == '__main__':
import asyncio
asyncio.run(mybot().start())
上述代码会监听微信消息,如果有人发“ping”,机器人会回复“pong”。
五、配置 puppet token 运行
你可以通过环境变量指定你的 puppet_service_token:
export wechaty_puppet=wechaty-puppet-service export wechaty_puppet_service_token=your_token_here python bot.py
或者直接在代码中指定:
bot = mybot() bot.options.puppet = 'wechaty-puppet-service' bot.options.puppet_token = 'your_token_here' asyncio.run(bot.start())
六、使用 docker 本地运行(可选)
如果你不想本地安装所有依赖,可以用 docker 来运行 wechaty:
docker run -e wechaty_puppet=wechaty-puppet-service \
-e wechaty_puppet_service_token=your_token \
wechaty/wechaty
七、常见问题与排查
1.无法连接服务端
错误:wechatypuppetgrpcerror: service server is invalid
原因:puppet_token 不正确或网络不通
2.消息接收不到
请检查是否扫码登录成功,或是否被微信屏蔽
3.docker 拉取失败
使用国内代理,如 dockerproxy.com 或配置镜像加速器
八、方法补充
python wechaty实现微信机器人,完成定时群发功能
步骤:(必须要python3.7以上版本,我用的python3.7)
1.安装wechaty
pip install wechaty
2.导入申请的token
export wechaty_puppet_hostie_token='your-token'
3.编写代码
最基础功能:发送ding会返回给你一张图片
import asyncio
from wechaty import wechaty, message
class mybot(wechaty):
async def on_message(self, msg: message):
talker = msg.talker()
await talker.ready()
if msg.text() == "ding":
await talker.say('dong')
elif msg.text() == 'image':
file_box = filebox.from_url(
'https://ss3.bdstatic.com/70cfv8sh_q1ynxgkpowk1hf6hhy/it/'
'u=1116676390,2305043183&fm=26&gp=0.jpg',
name='ding-dong.jpg')
await talker.say(file_box)
async def main():
bot = mybot()
await bot.start()
asyncio.run(main())完成定时群发功能
#encoding = utf-8
from wechaty import wechaty
from wechaty.plugin import wechatyplugin
from apscheduler.schedulers.asyncio import asyncioscheduler
import asyncio
import datetime
#from wechaty import get_room_id
class dailyplugin(wechatyplugin):
@property
def name(self) -> str:
return 'dayily'
async def tick(self):
rooms = await self.bot.room.find_all()
for currroom in rooms:
print(f'room pay load topic: {currroom.payload.topic}, topic: {currroom.topic}, currroom.room_id: {currroom.room_id}')
topic = currroom.payload.topic
if(topic.startswith("ding") or topic.startswith("曼玲-食神券坊外卖")):
room = currroom
await room.say(f'您好,我是食神券坊智能机器人,今天正式上线! -> {datetime.datetime.now()}')
async def init_plugin(self, wechaty: wechaty):
await super().init_plugin(wechaty)
scheduler = asyncioscheduler()
scheduler.add_job(self.tick, 'cron', hour=9, minute=43, second=55)
scheduler.start()
async def main():
bot = wechaty().use(dailyplugin())
await bot.start()
asyncio.run(main())
小结
通过 wechaty python sdk,我们可以快速构建一个可响应消息的微信机器人。借助 puppet-service 的云服务,我们无需逆向协议,即可专注于业务逻辑开发。
到此这篇关于python基于wechaty构建一个简单的微信机器人的文章就介绍到这了,更多相关python wechaty构建微信机器人内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论