Skip to main content

wecom-aibot-py-sdk (Python)

企业微信智能机器人 Python SDK —— 基于 WebSocket 长连接通道,提供消息收发、流式回复、模板卡片、事件回调、文件下载解密等核心能力。

本项目是 @wecom/aibot-node-sdk(Node.js 版)的 Python 等价实现。 补齐了官方NodeSDK更新未同步的功能。 借鉴了@ticoAg/wecom-aibot-python-sdk的扩展功能。

新增功能:素材上传、媒体消息和连接配置

from pathlib import Path

# 上传并回复文件;type 支持 file / image / voice / video
media = await ws_client.upload_media(
    Path("document.pdf").read_bytes(),
    {"type": "file", "filename": "document.pdf"},
)
await ws_client.reply_media(frame, "file", media["media_id"])
await ws_client.send_media_message("target_userid", "file", media["media_id"])

# 视频可附带标题和描述
await ws_client.reply_media(frame, "video", video_media_id,
                            {"title": "演示", "description": "操作说明"})

# 前一帧未收到 ACK 时跳过当前中间帧,返回 "skipped";最终帧仍进入队列
await ws_client.reply_stream_non_blocking(frame, stream_id, "中间内容", False)
await ws_client.reply_stream_non_blocking(frame, stream_id, "最终完整内容", True)

上传按 512 KiB 分片,最多 100 片(50 MiB);1~4 片全部并发,5~10 片并发 3,更多片并发 2。每片失败后最多重试两次,全部成功后才完成上传。空素材会被拒绝;服务端仍可能有各媒体类型自己的大小和格式限制。

新增 message.video 事件。event.disconnected_event 表示被新连接踢下线,此时 SDK 清理等待中的请求、关闭连接并停止自动重连;可显式调用 await connect() 重新连接。

新增配置:

参数 默认值 说明
scene None 可选认证场景值
plug_version None 可选插件版本
max_auth_failure_attempts 5 首次认证失败后允许的重试次数,-1 为无限
max_reply_queue_size 500 单个 req_id 的回复队列上限,超过则拒绝新消息
ws_options {} 传入 websockets.connect 的 Python 连接参数

认证失败会主动关闭连接并指数退避重试;认证成功后重置认证与网络重试计数。耗尽后分别触发 WSAuthFailureError、WSReconnectExhaustedError,可在 error 事件中按异常类型或 code 判断。

自定义 CA 示例:

import ssl

context = ssl.create_default_context(cafile="company-ca.pem")
options = WSClientOptions(
    bot_id="bot-id", secret="secret",
    ws_url="wss://your-server.example",
    ws_options={"ssl": context},
)

通用消息加解密(独立于文件解密):

from aibot import WecomCrypto

crypto = WecomCrypto("token", "your_encoding_aes_key", receive_id="your_corp_or_bot_id")
result = crypto.encrypt("消息正文", "1234567890", "nonce")
assert crypto.verify_signature(result["signature"], "1234567890", "nonce", result["encrypt"])
assert crypto.decrypt(result["encrypt"]) == "消息正文"

在 SDK 根目录运行测试(集成测试需要允许监听本机临时端口):

uv run python -m unittest discover -s tests -v

媒体便捷接口

支持 MediaType.File/Image/Voice/Video 枚举和对应字符串。上传保留原有 options 参数与字典返回值,也可传入预计算的 MD5:

from aibot import MediaType

media = await ws_client.upload_media(
    image_bytes, {"type": MediaType.Image, "filename": "image.png"},
    # md5="预先计算的 MD5",  # 可选;省略时自动计算
)
await ws_client.reply_image(frame, media["media_id"])
await ws_client.reply_file(frame, file_media_id)
await ws_client.reply_voice(frame, voice_media_id)
await ws_client.reply_video(frame, video_media_id, title="演示", description="操作说明")

以上便捷方法复用 reply_media。分片并发与重试保持不变。心跳超时会独立调度重连,避免等待底层关闭阻塞恢复;复用现有重连任务去重与手动断开取消逻辑。

多媒体回显示例:uv run examples/media_echo.py(使用 .env 中的 WECHAT_BOT_ID 和 WECHAT_BOT_SECRET)。支持图片原样回复、文本转为 txt 文件回复。

发布到 PyPI

工作流位于 .github/workflows/publish.yml,发布 GitHub Release 时自动构建并通过 PyPI Trusted Publishing 上传,无需配置 API Token。普通 push 不会发布。

首次使用需要完成账户侧配置:

  1. 在 GitHub 仓库 Settings → Environments 创建 pypi 环境。
  2. 在 PyPI 的项目管理 → Publishing 添加 GitHub Trusted Publisher;如果是尚未创建的新包,在 https://pypi.org/manage/account/publishing/ 添加 Pending Publisher。
  3. 按当前 Git remote 填写:Owner 为 oxy-projects,Repository 为 wecom-aibot-python-sdk,Workflow 为 publish.yml,Environment 为 pypi。PyPI 项目名为 wecom-aibot-py-sdk。仓库转移后需同步更新这些配置。

已有 PyPI 同名项目必须拥有维护权限;若属于其他维护者,需要先更换为可用的包名,并同步修改 pyproject.toml 和工作流中的 PyPI 链接。

每次发布先同步修改 pyproject.toml 的 version 和 src/aibot/__init__.py 的 __version__,提交后针对该提交发布 v版本号 的 GitHub Release(当前为 v2.0.0)。工作流会检查这三个版本一致。已上传到 PyPI 的版本不能覆盖,需要增加版本号。

当前包要求 Python >=3.15,工作流也使用 Python 3.15。标准 Ubuntu 运行器在公开仓库中运行免费;构建产物仅保留一天。

✨ 特性

  • 🔗 WebSocket 长连接 — 基于 wss://openws.work.weixin.qq.com 内置默认地址,开箱即用
  • 🔐 自动认证 — 连接建立后自动发送认证帧(bot_id + secret)
  • 💓 心跳保活 — 自动维护心跳,连续未收到 ack 时自动判定连接异常
  • 🔄 断线重连 — 指数退避重连策略(1s → 2s → 4s → ... → 30s 上限),支持自定义最大重连次数
  • 📨 消息分发 — 自动解析消息类型并触发对应事件(text / image / mixed / voice / file)
  • 🌊 流式回复 — 内置流式回复方法,支持 Markdown 和图文混排
  • 🃏 模板卡片 — 支持回复模板卡片消息、流式+卡片组合回复、更新卡片
  • 📤 主动推送 — 支持向指定会话主动发送 Markdown 或模板卡片消息,无需依赖回调帧
  • 📡 事件回调 — 支持进入会话、模板卡片按钮点击、用户反馈等事件
  • ⏩ 串行回复队列 — 同一 req_id 的回复消息串行发送,自动等待回执
  • 🔑 文件下载解密 — 内置 AES-256-CBC 文件解密,每个图片/文件消息自带独立的 aeskey
  • 🪵 可插拔日志 — 支持自定义 Logger,内置带时间戳的 DefaultLogger
  • 🐍 asyncio 原生 — 基于 Python asyncio 异步架构,支持 async/await

📦 安装

uv add wecom-aibot-py-sdk

依赖:

  • Python >= 3.15
  • websockets >= 12.0
  • aiohttp >= 3.9
  • pyee >= 11.0
  • cryptography >= 42.0
  • certifi>=2023.0
  • python-dotenv>=1.0 (可选,用于加载 .env 文件)

本地开发与构建

在本项目根目录执行(需预先安装 uv):

uv python install 3.15
uv sync --locked
cp .env.example .env
uv run examples/basic.py
uv run python -m unittest discover -s tests -v
uv build

uv sync 自动创建 .venv,以可编辑模式安装 SDK,并默认安装 dev 依赖组中的 python-dotenv。示例通过 uv run 使用已安装的 SDK。仅安装运行依赖时使用 uv sync --locked --no-dev。

依赖统一在 pyproject.toml 中维护:uv add 包名 添加运行依赖,uv add --dev 包名 添加开发依赖;变更后提交 pyproject.toml 与 uv.lock。uv build 使用 hatchling 生成 wheel 和源码包,输出到 dist/。

⚙️ 配置

# 复制示例配置文件
cp .env.example .env

# 编辑 .env 文件,填入真实配置
# WECHAT_BOT_ID=your-bot-id
# WECHAT_BOT_SECRET=your-bot-secret

🚀 快速开始

import asyncio
import os
from dotenv import load_dotenv
from aibot import WSClient, WSClientOptions, generate_req_id

# 加载 .env 文件中的环境变量
load_dotenv()

# 1. 创建客户端实例
ws_client = WSClient(
    WSClientOptions(
        bot_id=os.getenv('WECHAT_BOT_ID'),       # 企业微信后台获取的机器人 ID
        secret=os.getenv('WECHAT_BOT_SECRET'),   # 企业微信后台获取的机器人 Secret
    )
)

# 2. 监听认证成功
@ws_client.on('authenticated')
def on_authenticated():
    print('🔐 认证成功')

# 3. 监听文本消息并进行流式回复
@ws_client.on('message.text')
async def on_text(frame):
    content = frame.get('body', {}).get('text', {}).get('content', '')
    print(f'收到文本: {content}')

    stream_id = generate_req_id('stream')

    # 发送流式中间内容
    await ws_client.reply_stream(frame, stream_id, '正在思考中...', False)

    # 发送最终结果
    await asyncio.sleep(1)
    await ws_client.reply_stream(frame, stream_id, f'你好!你说的是: "{content}"', True)

# 4. 监听进入会话事件(发送欢迎语)
@ws_client.on('event.enter_chat')
async def on_enter_chat(frame):
    await ws_client.reply_welcome(frame, {
        'msgtype': 'text',
        'text': {'content': '您好!我是智能助手,有什么可以帮您的吗?'},
    })

# 5. 启动(便捷方法,内部管理事件循环)
ws_client.run()

或者手动管理事件循环:

async def main():
    await ws_client.connect()
    # 保持运行
    await asyncio.Event().wait()

asyncio.run(main())

📖 API 文档

WSClient

核心客户端类,继承自 pyee.AsyncIOEventEmitter,提供连接管理、消息收发等功能。

构造函数

ws_client = WSClient(options: WSClientOptions)

方法

方法 说明 返回值
await connect() 建立 WebSocket 连接,连接后自动认证 WSClient(支持链式调用)
disconnect() 主动断开连接 None
await reply(frame, body, cmd?) 通过 WebSocket 通道发送回复消息(通用方法) WsFrame
await reply_stream(frame, stream_id, content, finish?, msg_item?, feedback?) 发送流式文本回复(便捷方法,支持 Markdown) WsFrame
await reply_welcome(frame, body) 发送欢迎语回复(支持文本或模板卡片),需在收到事件 5s 内调用 WsFrame
await reply_template_card(frame, template_card, feedback?) 回复模板卡片消息 WsFrame
await reply_stream_with_card(frame, stream_id, content, finish?, ...) 发送流式消息 + 模板卡片组合回复 WsFrame
await update_template_card(frame, template_card, userids?) 更新模板卡片,需在收到事件 5s 内调用 WsFrame
await send_message(chatid, body) 主动发送消息(支持 Markdown 或模板卡片),无需依赖回调帧 WsFrame
await download_file(url, aes_key?) 下载文件并使用 AES 密钥解密 tuple[bytes, str | None]
run() 便捷启动方法(创建事件循环并连接) None

属性

属性 说明 类型
is_connected 当前 WebSocket 连接状态 bool
api 内部 API 客户端实例(高级用途) WeComApiClient

reply_stream 详细说明

await ws_client.reply_stream(
    frame,              # 收到的原始 WebSocket 帧(透传 req_id)
    stream_id: str,     # 流式消息 ID(使用 generate_req_id('stream') 生成)
    content: str,       # 回复内容(支持 Markdown)
    finish: bool = False,  # 是否结束流式消息
    msg_item: list = None, # 图文混排项(仅 finish=True 时有效)
    feedback: dict = None, # 反馈信息(仅首次回复时设置)
)

reply_welcome 详细说明

发送欢迎语回复,需在收到 event.enter_chat 事件 5 秒内调用。

# 文本欢迎语
await ws_client.reply_welcome(frame, {
    'msgtype': 'text',
    'text': {'content': '欢迎!'},
})

# 模板卡片欢迎语
await ws_client.reply_welcome(frame, {
    'msgtype': 'template_card',
    'template_card': {'card_type': 'text_notice', 'main_title': {'title': '欢迎'}},
})

reply_stream_with_card 详细说明

await ws_client.reply_stream_with_card(
    frame,                          # 收到的原始 WebSocket 帧
    stream_id: str,                 # 流式消息 ID
    content: str,                   # 回复内容(支持 Markdown)
    finish: bool = False,           # 是否结束流式消息
    msg_item: list = None,          # 图文混排项(仅 finish=True 时有效)
    stream_feedback: dict = None,   # 流式消息反馈信息(首次回复时设置)
    template_card: dict = None,     # 模板卡片内容(同一消息只能回复一次)
    card_feedback: dict = None,     # 模板卡片反馈信息
)

send_message 详细说明

主动向指定会话推送消息,无需依赖收到的回调帧。

# 发送 Markdown 消息
await ws_client.send_message('userid_or_chatid', {
    'msgtype': 'markdown',
    'markdown': {'content': '这是一条**主动推送**的消息'},
})

# 发送模板卡片消息
await ws_client.send_message('userid_or_chatid', {
    'msgtype': 'template_card',
    'template_card': {'card_type': 'text_notice', 'main_title': {'title': '通知'}},
})

download_file 使用示例

# aes_key 取自消息体中的 image.aeskey 或 file.aeskey
@ws_client.on('message.image')
async def on_image(frame):
    body = frame.get('body', {})
    image = body.get('image', {})
    buffer, filename = await ws_client.download_file(image.get('url'), image.get('aeskey'))
    print(f'文件名: {filename}, 大小: {len(buffer)} bytes')

⚙️ 配置选项

WSClientOptions 完整配置:

参数 类型 必填 默认值 说明
bot_id str ✅ — 机器人 ID(企业微信后台获取)
secret str ✅ — 机器人 Secret(企业微信后台获取)
reconnect_interval int — 1000 重连基础延迟(毫秒),实际延迟按指数退避递增
max_reconnect_attempts int — 10 最大重连次数(-1 表示无限重连)
heartbeat_interval int — 30000 心跳间隔(毫秒)
request_timeout int — 10000 HTTP 请求超时时间(毫秒)
ws_url str — wss://openws.work.weixin.qq.com 自定义 WebSocket 连接地址
logger Logger — DefaultLogger 自定义日志实例

📡 事件列表

所有事件均通过 @ws_client.on(event) 装饰器或 ws_client.on(event, handler) 监听:

事件 回调参数 说明
connected — WebSocket 连接建立
authenticated — 认证成功
disconnected reason: str 连接断开
reconnecting attempt: int 正在重连(第 N 次)
error error: Exception 发生错误
message frame: WsFrame 收到消息(所有类型)
message.text frame: WsFrame 收到文本消息
message.image frame: WsFrame 收到图片消息
message.mixed frame: WsFrame 收到图文混排消息
message.voice frame: WsFrame 收到语音消息
message.file frame: WsFrame 收到文件消息
event frame: WsFrame 收到事件回调(所有事件类型)
event.enter_chat frame: WsFrame 收到进入会话事件
event.template_card_event frame: WsFrame 收到模板卡片事件
event.feedback_event frame: WsFrame 收到用户反馈事件

📋 消息类型

SDK 支持以下消息类型(MessageType 枚举):

类型 值 说明
MessageType.Text 'text' 文本消息
MessageType.Image 'image' 图片消息
MessageType.Mixed 'mixed' 图文混排消息
MessageType.Voice 'voice' 语音消息
MessageType.File 'file' 文件消息

SDK 支持以下事件类型(EventType 枚举):

类型 值 说明
EventType.EnterChat 'enter_chat' 进入会话事件
EventType.TemplateCardEvent 'template_card_event' 模板卡片事件
EventType.FeedbackEvent 'feedback_event' 用户反馈事件

🪵 自定义日志

实现 Logger Protocol 接口即可自定义日志输出:

class MyLogger:
    def debug(self, message: str, *args) -> None:
        pass  # 静默 debug 日志

    def info(self, message: str, *args) -> None:
        print(f"[INFO] {message}", *args)

    def warn(self, message: str, *args) -> None:
        print(f"[WARN] {message}", *args)

    def error(self, message: str, *args) -> None:
        print(f"[ERROR] {message}", *args)

ws_client = WSClient(
    WSClientOptions(
        bot_id='your-bot-id',
        secret='your-bot-secret',
        logger=MyLogger(),
    )
)

📂 项目结构

wecom-aibot-python-sdk/
├── src/aibot/              # SDK 源码,安装后仍使用 import aibot
├── tests/                  # unittest 单元与本地集成测试
├── examples/               # basic.py / media_echo.py / comparison_test.py
├── pyproject.toml          # 元数据、依赖、开发依赖与 hatchling 构建配置
├── uv.lock                 # uv 依赖锁文件,纳入版本控制
├── .python-version         # Python 3.15
├── .env.example            # 示例环境变量
├── README.md
├── COMPARISON.md
└── LICENSE

📄 License

MIT

Metadata

Release files for wecom-aibot-py-sdk 2.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for wecom-aibot-py-sdk 2.0.0
File Size Uploaded Provenance Actions
wecom_aibot_py_sdk-2.0.0.tar.gz 68.1 kB With provenance Details for wecom_aibot_py_sdk-2.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for wecom-aibot-py-sdk 2.0.0
File Interpreter ABI Platform Actions
wecom_aibot_py_sdk-2.0.0-py3-none-any.whl Python 3 none any Details for wecom_aibot_py_sdk-2.0.0-py3-none-any.whl

Total release size: 98.0 kB

Release files / wecom_aibot_py_sdk-2.0.0.tar.gz

Download URL wecom_aibot_py_sdk-2.0.0.tar.gz
Size 68.1 kB
Tags Source
SHA-256 checksum
How to use checksums
ed7ba33f7a570b9b57b180b38c202abb566736352964e4f385d8f3ef31740d8a
BLAKE2b-256 checksum
How to use checksums
b1f544e509767b6e0f5d9bacff6d2056115195faa8ec0550c68be490d31b5b5b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 6, 2026.

Transparency log

Release files / wecom_aibot_py_sdk-2.0.0-py3-none-any.whl

Download URL wecom_aibot_py_sdk-2.0.0-py3-none-any.whl
Size 29.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c430a03180c4e3939664478c6f47f6181dd29fc217e2830c7a1b9a2c301e7345
BLAKE2b-256 checksum
How to use checksums
35977fa5091843ead66cb4685d787fae059e9c317453abef64c5cc915b50564c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 6, 2026.

Transparency log

Security for wecom-aibot-py-sdk 2.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for wecom_aibot_py_sdk-2.0.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 6, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.0.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page