Python基于Wechaty構(gòu)建一個簡單的微信機器人
在當(dāng)今自動化和智能化需求日益增長的時代,企業(yè)微信、公眾號、小助手等自動聊天工具層出不窮。Wechaty 是一個跨平臺的聊天機器人 SDK,支持多語言開發(fā),包括 JavaScript、Python、Go、Rust 等,幫助開發(fā)者快速構(gòu)建微信機器人。
本文將介紹如何基于 Python 語言使用 Wechaty,構(gòu)建一個簡單的微信機器人。
一、什么是 Wechaty
Wechaty 是一個專為微信生態(tài)設(shè)計的聊天機器人框架,它支持私有部署、云端服務(wù),并提供多種 Puppet 插件接入微信協(xié)議,如:
- wechaty-puppet-wechat4u(個人微信網(wǎng)頁版)
- wechaty-puppet-padplus(已停用)
- wechaty-puppet-service(推薦,官方提供 token 服務(wù)接入)
- wechaty-puppet-wecom(企業(yè)微信)
二、環(huá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/ 并注冊一個賬號,獲取免費的 puppet_service_token。這是連接微信服務(wù)的關(guān)鍵憑據(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”,機器人會回復(fù)“pong”。
五、配置 Puppet token 運行
你可以通過環(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 本地運行(可選)
如果你不想本地安裝所有依賴,可以用 Docker 來運行 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 或配置鏡像加速器
八、方法補充
python wechaty實現(xiàn)微信機器人,完成定時群發(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())完成定時群發(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'您好,我是食神券坊智能機器人,今天正式上線! -> {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)消息的微信機器人。借助 puppet-service 的云服務(wù),我們無需逆向協(xié)議,即可專注于業(yè)務(wù)邏輯開發(fā)。
到此這篇關(guān)于Python基于Wechaty構(gòu)建一個簡單的微信機器人的文章就介紹到這了,更多相關(guān)Python Wechaty構(gòu)建微信機器人內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
OpenCV根據(jù)面積篩選連通域?qū)W習(xí)示例
這篇文章主要為大家介紹了OpenCV根據(jù)面積篩選連通域?qū)W習(xí)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06
Python+OpenCV實現(xiàn)信用卡數(shù)字識別的方法詳解
這篇文章主要介紹了如何利用python?opencv實現(xiàn)信用卡數(shù)字識別,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-09-09
Python實現(xiàn)讀取.nc數(shù)據(jù)并提取指定時間與經(jīng)緯度維度對應(yīng)的變量數(shù)值
這篇文章主要為大家詳細介紹了如何使用Python語言的netCDF4庫實現(xiàn)讀取.nc格式的數(shù)據(jù)文件,并提取指定維(時間、經(jīng)度與緯度)下的變量數(shù)據(jù),需要的可以了解下2024-02-02
pandas探索你的數(shù)據(jù)實現(xiàn)可視化示例詳解
這篇文章主要為大家介紹了pandas探索你的數(shù)據(jù)實現(xiàn)可視化示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10
解析Pytorch中的torch.gather()函數(shù)
本文給大家介紹了Pytorch中的torch.gather()函數(shù),通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-11-11
Python中g(shù)lob.glob()函數(shù)的使用
glob 模塊用于查找規(guī)定路徑下的文件路徑名,本文主要介紹了Python中g(shù)lob.glob()函數(shù)的使用,具有一定的參考價值,感興趣的可以了解一下2024-03-03
Python進程間通信 multiProcessing Queue隊列實現(xiàn)詳解
這篇文章主要介紹了python進程間通信 mulitiProcessing Queue隊列實現(xiàn)詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-09-09

