Skip to content

快速开始

安装

shell
pip install pywechat-libencode

支持版本

大版本支持版本
3.x3.9.12.51
4.x4.1.5.16 / 4.1.6.14 / 4.1.6.46 / 4.1.7.30 / 4.1.8.27 / 4.1.8.28 / 4.1.8.67

最简示例

python
from pywechat_libencode import WeChat, events

# 自动根据版本号选择 WeChat3 或 WeChat4
bot = WeChat(version="4.1.8.67")

@bot.handle(events=events.TEXT_MESSAGE)
def on_text(bot, data):
    print(f"收到文本消息: {data}")

bot.run()

WeChat4 示例(4.x 版本)

python
from pywechat_libencode import WeChat4, events

bot = WeChat4(version="4.1.8.67")

@bot.handle(events=events.TEXT_MESSAGE)
def on_text(bot: WeChat4, data: dict):
    content = data["content"]["String"]
    from_wxid = data["fromUserName"]["String"]
    account_wxid = data["account_wxid"]

    # 跳过自己发出的消息和群消息
    if from_wxid == account_wxid or from_wxid.endswith("@chatroom"):
        return

    bot.send_text(from_wxid, content)

bot.run()

WeChat3 示例(3.x 版本)

python
from pywechat_libencode import WeChat3, events

bot = WeChat3(version="3.9.12.51")

@bot.handle(events=events.TEXT_MESSAGE)
def on_text(bot: WeChat3, data: dict):
    content = data["Content"]["String"]
    from_wxid = data["FromUserName"]["String"]
    self_wxid = data["from"]

    # 跳过自己发出的消息和群消息
    if from_wxid == self_wxid or from_wxid.endswith("@chatroom"):
        return

    bot.send_text(from_wxid, content)

bot.run()

工厂类自动选择

python
from pywechat_libencode import WeChat

# 传入3.x版本号自动创建 WeChat3 实例
bot3 = WeChat(version="3.9.12.51")

# 传入4.x版本号自动创建 WeChat4 实例
bot4 = WeChat(version="4.1.8.67")

关闭调试日志

python
from loguru import logger

logger.remove()

# 或者通过环境变量
# import os
# os.environ["PYWECHAT_LIBENCODE_LOG_LEVEL"] = "INFO"

基于 MIT 许可发布