Python基于Wechaty構(gòu)建一個簡單的微信機(jī)器人
在當(dāng)今自動化和智能化需求日益增長的時(shí)代,企業(yè)微信、公眾號、小助手等自動聊天工具層出不窮。Wechaty 是一個跨平臺的聊天機(jī)器人 SDK,支持多語言開發(fā),包括 JavaScript、Python、Go、Rust 等,幫助開發(fā)者快速構(gòu)建微信機(jī)器人。
本文將介紹如何基于 Python 語言使用 Wechaty,構(gòu)建一個簡單的微信機(jī)器人。
一、什么是 Wechaty
Wechaty 是一個專為微信生態(tài)設(shè)計(jì)的聊天機(jī)器人框架,它支持私有部署、云端服務(wù),并提供多種 Puppet 插件接入微信協(xié)議,如:
- wechaty-puppet-wechat4u(個人微信網(wǎng)頁版)
- wechaty-puppet-padplus(已停用)
- wechaty-puppet-service(推薦,官方提供 token 服務(wù)接入)
- wechaty-puppet-wecom(企業(yè)微信)
二、環(huán)境準(zhǔn)備
1. 安裝 Python 環(huán)境
確保本地已安裝 Python3.7+,推薦使用 Python3.9 版本:
python3 --version pip3 --version
建議創(chuàng)建虛擬環(huán)境:
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/ 并注冊一個賬號,獲取免費(fèi)的 puppet_service_token。這是連接微信服務(wù)的關(guān)鍵憑據(jù)。
四、編寫機(jī)器人代碼
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())
上述代碼會監(jiān)聽微信消息,如果有人發(fā)“ping”,機(jī)器人會回復(fù)“pong”。
五、配置 Puppet token 運(yùn)行
你可以通過環(huán)境變量指定你的 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 本地運(yùn)行(可選)
如果你不想本地安裝所有依賴,可以用 Docker 來運(yùn)行 Wechaty:
docker run -e WECHATY_PUPPET=wechaty-puppet-service \ -e WECHATY_PUPPET_SERVICE_TOKEN=your_token \ wechaty/wechaty
七、常見問題與排查
1.無法連接服務(wù)端
錯誤:WechatyPuppetGrpcError: service server is invalid
原因:puppet_token 不正確或網(wǎng)絡(luò)不通
2.消息接收不到
請檢查是否掃碼登錄成功,或是否被微信屏蔽
3.Docker 拉取失敗
使用國內(nèi)代理,如 dockerproxy.com 或配置鏡像加速器
八、方法補(bǔ)充
python wechaty實(shí)現(xiàn)微信機(jī)器人,完成定時(shí)群發(fā)功能
步驟:(必須要python3.7以上版本,我用的python3.7)
1.安裝wechaty
pip install wechaty
2.導(dǎo)入申請的token
export WECHATY_PUPPET_HOSTIE_TOKEN='your-token'
3.編寫代碼
最基礎(chǔ)功能:發(fā)送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())
完成定時(shí)群發(fā)功能
#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'您好,我是食神券坊智能機(jī)器人,今天正式上線! -> {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())
小結(jié)
通過 Wechaty Python SDK,我們可以快速構(gòu)建一個可響應(yīng)消息的微信機(jī)器人。借助 puppet-service 的云服務(wù),我們無需逆向協(xié)議,即可專注于業(yè)務(wù)邏輯開發(fā)。
到此這篇關(guān)于Python基于Wechaty構(gòu)建一個簡單的微信機(jī)器人的文章就介紹到這了,更多相關(guān)Python Wechaty構(gòu)建微信機(jī)器人內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談Keras中fit()和fit_generator()的區(qū)別及其參數(shù)的坑
這篇文章主要介紹了Keras中fit()和fit_generator()的區(qū)別及其參數(shù)的坑,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05淺談OpenCV中的新函數(shù)connectedComponentsWithStats用法
這篇文章主要介紹了淺談OpenCV中的新函數(shù)connectedComponentsWithStats用法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07Pycharm創(chuàng)建文件時(shí)自動生成文件頭注釋(自定義設(shè)置作者日期)
這篇文章主要介紹了Pycharm創(chuàng)建文件時(shí)自動生成文件頭注釋(自定義設(shè)置作者日期),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11Linux 下 Python 實(shí)現(xiàn)按任意鍵退出的實(shí)現(xiàn)方法
這篇文章主要介紹了Linux 下 Python 實(shí)現(xiàn)按任意鍵退出的實(shí)現(xiàn)方法的相關(guān)資料,本文介紹的非常詳細(xì),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-09-09Python向MySQL批量插數(shù)據(jù)的實(shí)例講解
下面小編就為大家分享一篇Python向MySQL批量插數(shù)據(jù)的實(shí)例講解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03Python中關(guān)于列表的常規(guī)操作范例以及介紹
列表是一種有序的集合,可以隨時(shí)添加和刪除其中的元素。在python中使用的頻率非常高,本篇文章對大家的學(xué)習(xí)或工作具有一定的價(jià)值,需要的朋友可以參考下2021-09-09