Python SDK for the WeChat iLink Bot API.
cd python
pip install .from weixin_bot import WeixinBot
bot = WeixinBot()
bot.login()
@bot.on_message
async def handle(msg):
print(f"{msg.user_id}: {msg.text}")
await bot.send_typing(msg.user_id)
await bot.reply(msg, f"你说了: {msg.text}")
bot.run()Creates a bot client.
base_url: Override the iLink API base URL.token_path: Override the credential file path. Default:~/.weixin-bot/credentials.jsonon_error: Receive polling or handler errors.
Starts QR login if needed, stores credentials locally, and returns the active session.
Registers an async or sync message handler. Each inbound user message is converted into:
IncomingMessage(
user_id: str,
text: str,
type: Literal["text", "image", "voice", "file", "video"],
raw: dict,
_context_token: str,
timestamp: datetime,
)Replies to an inbound message using that message's context_token. It also triggers stop_typing() in the background after the reply is sent.
Shows the typing indicator in the WeChat chat. The SDK fetches the required typing_ticket through getconfig.
Cancels the typing indicator.
Sends a proactive text message using the latest cached context_token for that user. This only works after the SDK has seen at least one inbound message from that user.
Starts the long-poll loop, dispatches incoming messages to registered handlers, reconnects on transient failures, and forces a fresh QR login if the session expires.
Stops the long-poll loop gracefully.
login()fetches a QR login URL, waits for WeChat confirmation, and saves the returned bot token.run()performs long polling againstgetupdates.- Each inbound message is normalized into
IncomingMessageand sent to your callbacks. reply()andsend()reuse the internally managedcontext_tokenrequired by the protocol.- On
errcode = -14, the SDK clears saved credentials, requests a fresh QR login, and resumes polling with exponential backoff.
- Credentials are stored at
~/.weixin-bot/credentials.jsonwith mode0o600. - The package tries to render the QR code in the terminal if
qrcodeis installed, otherwise it prints the URL to stderr. - Long-poll requests use a 40-second timeout and send operations use a 15-second timeout.
- Text messages are split into 2000-character chunks automatically.
MIT