WeCom AI Bot Python SDK - Based on WebSocket long connection, provides core capabilities including message sending/receiving, streaming replies, template cards, event callbacks, and file download decryption
Project description
WeCom AI Bot Python SDK
Enterprise WeChat AI Bot Python SDK - Based on WebSocket long connection, providing message sending/receiving, streaming replies, template cards, event callbacks, file download/decryption and other core capabilities.
Features
- WebSocket Long Connection - Built-in default address
wss://openws.work.weixin.qq.com, ready to use - Auto Authentication - Automatically sends authentication frame after connection (botId + secret)
- Heartbeat Keep-Alive - Automatic heartbeat maintenance, auto-detects connection issues when ACKs are missing
- Auto Reconnect - Exponential backoff reconnection strategy (1s → 2s → 4s → ... → 30s max)
- Message Dispatch - Auto-parses message types and triggers corresponding events (text/image/mixed/voice/file)
- Streaming Reply - Built-in streaming reply methods, supports Markdown and mixed content
- Template Cards - Supports replying with template card messages, stream+card combo replies, card updates
- Proactive Push - Proactively send Markdown or template card messages to specified chats
- Event Callbacks - Supports enter_chat, template_card_event, feedback_event
- Serial Reply Queue - Replies with same req_id are sent serially, auto-waits for receipt
- File Download & Decryption - Built-in AES-256-CBC file decryption, each image/file message has its own aeskey
- Pluggable Logging - Supports custom Logger, includes DefaultLogger with timestamps
Installation
pip install wecom-aibot-sdk
Quick Start
import asyncio
from wecom_aibot_sdk import WSClient, generate_req_id
async def main():
# 1. Create client instance
client = WSClient({
"bot_id": "your-bot-id",
"secret": "your-bot-secret",
})
# 2. Listen for text messages and reply with streaming
async def on_text(frame):
content = frame.body.get("text", {}).get("content", "")
stream_id = generate_req_id("stream")
# Send intermediate content
await client.reply_stream(frame, stream_id, "Thinking...", finish=False)
# Send final result
await client.reply_stream(frame, stream_id, f'You said: "{content}"', finish=True)
client.on("message.text", on_text)
# 3. Listen for enter_chat event (send welcome)
async def on_enter(frame):
await client.reply_welcome(frame, {
"msgtype": "text",
"text": {"content": "Hello! How can I help you?"},
})
client.on("event.enter_chat", on_enter)
# 4. Connect
await client.connect_async()
# Keep running
while client.is_connected:
await asyncio.sleep(1)
asyncio.run(main())
API Reference
WSClient
Core client class providing connection management, message sending/receiving.
client = WSClient({
"bot_id": "your-bot-id",
"secret": "your-bot-secret",
# Optional:
"reconnect_interval": 1000, # Reconnect base delay (ms)
"max_reconnect_attempts": 10, # Max reconnect attempts (-1 for infinite)
"heartbeat_interval": 30000, # Heartbeat interval (ms)
"request_timeout": 10000, # HTTP request timeout (ms)
"ws_url": "wss://...", # Custom WebSocket URL
"logger": custom_logger, # Custom logger instance
})
Methods
| Method | Description | Returns |
|---|---|---|
connect_async() |
Establish WebSocket connection | None |
disconnect() |
Disconnect | None |
reply(frame, body, cmd?) |
Send reply message (generic) | None |
reply_stream(frame, stream_id, content, finish?, msg_item?, feedback?) |
Send streaming reply | None |
reply_welcome(frame, body) |
Send welcome reply (within 5s of event) | None |
reply_template_card(frame, template_card, feedback?) |
Reply with template card | None |
reply_stream_with_card(frame, stream_id, content, finish?, options?) |
Send stream + card combo | None |
update_template_card(frame, template_card, userids?) |
Update template card (within 5s) | None |
send_message(chatid, body) |
Proactively send message | None |
download_file(url, aes_key) |
Download and decrypt file | tuple[bytes, str?] |
Events
| Event | Callback | Description |
|---|---|---|
connected |
() |
WebSocket connected |
authenticated |
() |
Authentication successful |
disconnected |
(reason) |
Connection lost |
reconnecting |
(attempt) |
Reconnecting (attempt N) |
error |
(frame) |
Error occurred |
message |
(frame) |
Any message received |
message.text |
(frame) |
Text message |
message.image |
(frame) |
Image message |
message.mixed |
(frame) |
Mixed content message |
message.voice |
(frame) |
Voice message |
message.file |
(frame) |
File message |
event |
(frame) |
Any event |
event.enter_chat |
(frame) |
User entered chat |
event.template_card_event |
(frame) |
Card button clicked |
event.feedback_event |
(frame) |
User feedback |
Project Structure
wecom_aibot_sdk/
├── __init__.py # Package entry, exports
├── client.py # WSClient core client
├── ws.py # WebSocket connection manager
├── message_handler.py # Message parsing and event dispatch
├── api.py # HTTP API client (file download)
├── crypto.py # AES-256-CBC file decryption
├── logger.py # Default logger implementation
├── utils.py # Utility functions (generate_req_id, etc.)
└── types/ # Type definitions
├── __init__.py
├── config.py # Configuration types
├── event.py # Event types
├── message.py # Message types
├── api.py # API/WebSocket frame types
└── common.py # Common types (Logger)
Development
# Install dev dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Format code
ruff format .
License
MIT
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file wecom_aibot_sdk_python-0.1.0.tar.gz.
File metadata
- Download URL: wecom_aibot_sdk_python-0.1.0.tar.gz
- Upload date:
- Size: 17.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ef473fdbcd5ef58c678d398bf61ec81cf42145571d6a88be4f3e8c763fbfeb82
|
|
| MD5 |
fd31bd66a98453b7ffb3b31e932944ff
|
|
| BLAKE2b-256 |
18f3b56c7afa22a11a3cac1e24bf04fbbae59ee5cfaeaed322f5507005033cb7
|
Provenance
The following attestation bundles were made for wecom_aibot_sdk_python-0.1.0.tar.gz:
Publisher:
publish.yml on chengyongru/wecom_aibot_sdk
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
wecom_aibot_sdk_python-0.1.0.tar.gz -
Subject digest:
ef473fdbcd5ef58c678d398bf61ec81cf42145571d6a88be4f3e8c763fbfeb82 - Sigstore transparency entry: 1065719701
- Sigstore integration time:
-
Permalink:
chengyongru/wecom_aibot_sdk@301e482eb874cf0c99643b042f91e20af4e52e31 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/chengyongru
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@301e482eb874cf0c99643b042f91e20af4e52e31 -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file wecom_aibot_sdk_python-0.1.0-py3-none-any.whl.
File metadata
- Download URL: wecom_aibot_sdk_python-0.1.0-py3-none-any.whl
- Upload date:
- Size: 17.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8911eaf0692558775c6c80e06565a41179cf94d3e044815aff3568237e484f49
|
|
| MD5 |
176b4cde627d1e0ad4c8b3620831c81f
|
|
| BLAKE2b-256 |
a55fab4648f831e294d62e8f6f57b5b9e93c5386e3f30d990cf09447a98dc9cd
|
Provenance
The following attestation bundles were made for wecom_aibot_sdk_python-0.1.0-py3-none-any.whl:
Publisher:
publish.yml on chengyongru/wecom_aibot_sdk
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
wecom_aibot_sdk_python-0.1.0-py3-none-any.whl -
Subject digest:
8911eaf0692558775c6c80e06565a41179cf94d3e044815aff3568237e484f49 - Sigstore transparency entry: 1065719703
- Sigstore integration time:
-
Permalink:
chengyongru/wecom_aibot_sdk@301e482eb874cf0c99643b042f91e20af4e52e31 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/chengyongru
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@301e482eb874cf0c99643b042f91e20af4e52e31 -
Trigger Event:
workflow_dispatch
-
Statement type: