sailor0913

须知少时凌云志,曾许人间第一流

从0到1系列_微信机器人之Python_Wechaty_UOS

前言

目标

项目介绍

前置条件

正式开始

# 安装wechaty
npm install -g wechaty wechaty-puppet-wechat

# 设置环境变量,linux和mac使用export代替set
# WECHATY_PUPPET_SERVICE_TOKEN随机字符串,最好唯一,建议使用python的uuid.uuid4()生成
set  WECHATY_PUPPET_WECHAT_PUPPETEER_UOS=true
set  WECHATY_PUPPET_SERVICE_TOKEN="insecure_40fc7334-1234-5678-7777-780948c983d41"
set  WECHATY_PUPPET="wechaty-puppet-wechat"
set  WECHATY_LOG="verbose"
set  WECHATY_PUPPET_SERVER_PORT="8080"
set  WECHATY_PUPPET_SERVICE_NO_TLS_INSECURE_SERVER=true

# 运行wechaty网关服务
wechaty gateway --token %WECHATY_PUPPET_SERVICE_TOKEN% --port %WECHATY_PUPPET_SERVER_PORT%  --puppet wechaty-puppet-wechat
# mac or linux
wechaty gateway --token $WECHATY_PUPPET_SERVICE_TOKEN --port $WECHATY_PUPPET_SERVER_PORT --puppet wechaty-puppet-wechat

正常情况下会提示一个URL,打开使用微信机器人账号登陆

# python环境要有wechaty,这里的wechaty和上面npm安装的不是一回事(pip install wechaty)
from wechaty import Wechaty, Message
import asyncio, os

os.environ["WECHATY_PUPPET_SERVICE_ENDPOINT"] = "127.0.0.1:8080"
os.environ["WECHATY_PUPPET_SERVICE_TOKEN"] ="insecure_40fc7334-1234-5678-7777-780948c983d41"

os.environ["WECHATY_PUPPET_WECHAT_PUPPETEER_UOS"] = "true"

bot = Wechaty()

class MyBot(Wechaty):
    async def on_message(self, msg: Message) -> None:
        text = msg.text()
        if text == "ding":
            res = "dong"
            await msg.say(res)

asyncio.run(MyBot().start())

运行python代码,一切正常的话,使用别的微信号在机器人账号发送ding,机器人回复dong即代表成功。