Academy → Messaging ChannelsOfficial documentation · Arabic guidance

Weixin (WeChat)

قناة Weixin (WeChat)

Intermediate to advanced14 min readLesson 224 questions✓ 2026-08-18
Before you read

What this page is, and what it holds.

This page covers Weixin (WeChat). It carries a source warning and takes about 14 minutes to read. Open the channel to yourself first with an allowlist. An open channel means anyone can message your agent.

13sections
7code examples
8tables
2commands
2,327source words
The official one-line description

Connect Hermes Agent to personal WeChat accounts via the iLink Bot API

What you will be able to do

Outcomes taken from this page, not a template.

  • Understand what بوابة المراسلة is and when you need it.
  • Run hermes gateway setup and hermes gateway and understand what happens next.
  • Read the table and take only the row that applies to you.
  • Set WEIXIN_GROUP_POLICY in the right place.
Identifiers you will meet

Exactly as they appear in Hermes.

Commands
  • hermes gateway setup
  • hermes gateway
Environment variables
  • WEIXIN_GROUP_POLICY
  • WEIXIN_GROUP_ALLOWED_USERS
  • WEIXIN_ACCOUNT_ID
  • WEIXIN_TOKEN
  • WEIXIN_DM_POLICY
  • WEIXIN_ALLOWED_USERS
  • WEIXIN_SPLIT_MULTILINE_MESSAGES
  • WEIXIN_HOME_CHANNEL
Page map

Jump to the part you need.

  1. 01Prerequisites
  2. 02Setup
  3. 03Features
  4. 04Configuration Options
  5. 05Access Policies
  6. 06Media Support
  7. 07Context Token Persistence
  8. 08Markdown Formatting
  9. 09Message Chunking
  10. 10Typing Indicators
  11. 11Long-Poll Connection
  12. 12All Environment Variables
  13. 13Troubleshooting
The full official page

Nothing summarised away.

The documentation body below is reproduced from the official source so commands and identifiers stay exact. Each section carries a short note describing what it contains.

Connect Hermes to WeChat ↗ (微信), Tencent's personal messaging platform. The adapter uses Tencent's iLink Bot API for personal WeChat accounts — this is distinct from WeCom (Enterprise WeChat). Messages are delivered via long-polling, so no public endpoint or webhook is required.

Prerequisites

Explains the idea itself. Read it slowly; the later sections build on it.

  • A personal WeChat account
  • Python packages: aiohttp and cryptography
  • Terminal QR rendering is included when Hermes is installed with the messaging extra

Install the required dependencies:

Shell3 lines
pip install aiohttp cryptography
# Optional: for terminal QR code display
cd ~/.hermes/hermes-agent && uv pip install -e ".[messaging]"

Setup

Ordered, practical steps. Run one and confirm it worked before moving on. Commands here: hermes gateway, hermes gateway setup.

1. Run the Setup Wizard

The easiest way to connect your WeChat account is through the interactive setup:

Shell1 line
hermes gateway setup

Select Weixin when prompted. The wizard will:

  1. Request a QR code from the iLink Bot API
  2. Display the QR code in your terminal (or provide a URL)
  3. Wait for you to scan the QR code with the WeChat mobile app
  4. Prompt you to confirm the login on your phone
  5. Save the account credentials automatically to ~/.hermes/weixin/accounts/

Once confirmed, you'll see a message like:

Text1 line
微信连接成功,account_id=your-account-id

The wizard stores the account_id, token, and base_url so you don't need to configure them manually.

2. Configure Environment Variables

After initial QR login, set at minimum the account ID in ~/.hermes/.env:

Shell15 lines
WEIXIN_ACCOUNT_ID=your-account-id

# Optional: override the token (normally auto-saved from QR login)
# WEIXIN_TOKEN=your-bot-token

# Optional: restrict access
WEIXIN_DM_POLICY=open
WEIXIN_ALLOWED_USERS=user_id_1,user_id_2

# Optional: restore legacy multiline splitting behavior
# WEIXIN_SPLIT_MULTILINE_MESSAGES=true

# Optional: home channel for cron/notifications
WEIXIN_HOME_CHANNEL=chat_id
WEIXIN_HOME_CHANNEL_NAME=Home

3. Start the Gateway

Shell1 line
hermes gateway

The adapter will restore saved credentials, connect to the iLink API, and begin long-polling for messages.

Features

Commands you type in a terminal. Understand what one does before copying it. Commands here: hermes gateway setup.

  • Long-poll transport — no public endpoint, webhook, or WebSocket needed
  • QR code login — scan-to-connect setup via hermes gateway setup
  • DM messaging — configurable access policies; group messaging depends on iLink actually delivering group events for the connected identity (often not the case for iLink bot accounts — see the warning above)
  • Media support — images, video, files, and voice messages
  • AES-128-ECB encrypted CDN — automatic encryption/decryption for all media transfers
  • Context token persistence — disk-backed reply continuity across restarts
  • Markdown formatting — preserves Markdown, including headers, tables, and code blocks, so WeChat clients that support Markdown can render it natively
  • Smart message chunking — messages stay as a single bubble when under the limit; only oversized payloads split at logical boundaries
  • Typing indicators — shows "typing…" status in the WeChat client while the agent processes
  • SSRF protection — outbound media URLs are validated before download
  • Message deduplication — 5-minute sliding window prevents double-processing
  • Automatic retry with backoff — recovers from transient API errors

Configuration Options

A lookup table. Do not read it all; find the row that applies to you.

Set these in config.yaml under platforms.weixin.extra:

KeyDefaultDescription
account_id—iLink Bot account ID (required)
token—iLink Bot token (required, auto-saved from QR login)
base_urlhttps://ilinkai.weixin.qq.comiLink API base URL
cdn_base_urlhttps://novac2c.cdn.weixin.qq.com/c2cCDN base URL for media transfer
dm_policyopenDM access: open, allowlist, disabled, pairing
group_policydisabledGroup access: open, allowlist, disabled
allow_from[]User IDs allowed for DMs (when dm_policy=allowlist)
group_allow_from[]Group IDs allowed (when group_policy=allowlist)
split_multiline_messagesfalseWhen true, split multi-line replies into multiple chat messages (legacy behavior). When false, keep multi-line replies as one message unless they exceed the length limit.
text_batch_delay_seconds3.0Quiet period (seconds) before a buffered burst of rapid text messages is flushed as one combined request. iLink delivers messages individually, so this debounce avoids one agent invocation per fragment. Set 0 to dispatch each message immediately.
text_batch_split_delay_seconds5.0Extended flush delay used when the latest fragment is near the split threshold (long messages iLink may have chunked).

Access Policies

A lookup table. Do not read it all; find the row that applies to you. Commands here: hermes gateway setup.

DM Policy

Controls who can send direct messages to the bot:

ValueBehavior
openAnyone can DM the bot (default)
allowlistOnly user IDs in allow_from can DM
disabledAll DMs are ignored
pairingPairing mode (for initial setup)
Shell2 lines
WEIXIN_DM_POLICY=allowlist
WEIXIN_ALLOWED_USERS=user_id_1,user_id_2

WEIXIN_ALLOWED_USERS is an inbound filter, not an invitation system. QR login connects one iLink bot identity to Hermes. Other people do not scan the Hermes QR code with their own accounts; they must message the connected iLink bot/contact through WeChat, and Hermes will process the DM only if the sender's Weixin user ID is present in WEIXIN_ALLOWED_USERS.

A practical setup flow is:

  1. Pair Hermes once with hermes gateway setup and note the connected iLink bot account.
  2. Have each allowed user send a direct message to that bot/contact.
  3. Read the sender/user ID from the gateway logs or the inbound event payload.
  4. Add those IDs to WEIXIN_ALLOWED_USERS, then restart the gateway.

If only the account that scanned the QR code can talk to Hermes, verify that the other users are messaging the iLink bot identity itself, not the personal WeChat account that performed the QR login. The iLink bot is a separate identity, and ordinary WeChat contact/group routing can be limited by Tencent's iLink behavior.

Group Policy

Controls which groups the bot responds in when iLink delivers group events for the connected identity. For QR-login iLink bot identities (e.g. ...@im.bot), group events are typically not delivered at all, so this policy may have no effect — see the iLink bot limitation warning at the top of the page.

ValueBehavior
openBot responds in all groups (if events are delivered)
allowlistBot only responds in group IDs listed in group_allow_from (if events are delivered)
disabledAll group messages are ignored (default)
Shell4 lines
WEIXIN_GROUP_POLICY=allowlist
# NOTE: this is a comma-separated list of group chat IDs, NOT member user IDs,
# despite the variable name containing "USERS". Keep this in mind when configuring.
WEIXIN_GROUP_ALLOWED_USERS=group_id_1,group_id_2

Media Support

A lookup table. Do not read it all; find the row that applies to you.

Inbound (receiving)

The adapter receives media attachments from users, downloads them from the WeChat CDN, decrypts them, and caches them locally for agent processing:

TypeHow it's handled
ImagesDownloaded, AES-decrypted, and cached as JPEG.
VideoDownloaded, AES-decrypted, and cached as MP4.
FilesDownloaded, AES-decrypted, and cached. Original filename is preserved.
VoiceIf a text transcription is available, it's extracted as text. Otherwise the audio (SILK format) is downloaded and cached.

Quoted messages: Media from quoted (replied-to) messages is also extracted, so the agent has context about what the user is replying to.

AES-128-ECB Encrypted CDN

WeChat media files are transferred through an encrypted CDN. The adapter handles this transparently:

  • Inbound: Encrypted media is downloaded from the CDN using encrypted_query_param URLs, then decrypted with AES-128-ECB using the per-file key provided in the message payload.
  • Outbound: Files are encrypted locally with a random AES-128-ECB key, uploaded to the CDN, and the encrypted reference is included in the outbound message.
  • The AES key is 16 bytes (128-bit). Keys may arrive as raw base64 or hex-encoded — the adapter handles both formats.
  • This requires the cryptography Python package.

No configuration is needed — encryption and decryption happen automatically.

Outbound (sending)

MethodWhat it sends
sendText messages with Markdown formatting
send_image / send_image_fileNative image messages (via CDN upload)
send_documentFile attachments (via CDN upload)
send_videoVideo messages (via CDN upload)

All outbound media goes through the encrypted CDN upload flow:

  1. Generate a random AES-128 key
  2. Encrypt the file with AES-128-ECB + PKCS#7 padding
  3. Request an upload URL from the iLink API (getuploadurl)
  4. Upload the ciphertext to the CDN
  5. Send the message with the encrypted media reference

Context Token Persistence

Explains the idea itself. Read it slowly; the later sections build on it.

The iLink Bot API requires a context_token to be echoed back with each outbound message for a given peer. The adapter maintains a disk-backed context token store:

  • Tokens are saved per account+peer to ~/.hermes/weixin/accounts/<account_id>.context-tokens.json
  • On startup, previously saved tokens are restored
  • Every inbound message updates the stored token for that sender
  • Outbound messages automatically include the latest context token

This ensures reply continuity even after gateway restarts.

Markdown Formatting

Explains the idea itself. Read it slowly; the later sections build on it.

WeChat clients connected through the iLink Bot API can render Markdown directly, so the adapter preserves Markdown instead of rewriting it:

  • Headers stay as Markdown headings (#, ##, ...)
  • Tables stay as Markdown tables
  • Code fences stay as fenced code blocks
  • Excessive blank lines are collapsed to double newlines outside fenced code blocks

Message Chunking

Explains the idea itself. Read it slowly; the later sections build on it.

Messages are delivered as a single chat message whenever they fit within the platform limit. Only oversized payloads are split for delivery:

  • Maximum message length: 4000 characters
  • Messages under the limit stay intact even when they contain multiple paragraphs or line breaks
  • Oversized messages split at logical boundaries (paragraphs, blank lines, code fences)
  • Code fences are kept intact whenever possible (never split mid-block unless the fence itself exceeds the limit)
  • Oversized individual blocks fall back to the base adapter's truncation logic
  • A 0.3 s inter-chunk delay prevents WeChat rate-limit drops when multiple chunks are sent

Typing Indicators

Explains the idea itself. Read it slowly; the later sections build on it.

The adapter shows typing status in the WeChat client:

  1. When a message arrives, the adapter fetches a typing_ticket via the getconfig API
  2. Typing tickets are cached for 10 minutes per user
  3. send_typing sends a typing-start signal; stop_typing sends a typing-stop signal
  4. The gateway automatically triggers typing indicators while the agent processes a message

Long-Poll Connection

A lookup table. Do not read it all; find the row that applies to you.

The adapter uses HTTP long-polling (not WebSocket) to receive messages:

How It Works

  1. Connect: Validates credentials and starts the poll loop
  2. Poll: Calls getupdates with a 35-second timeout; the server holds the request until messages arrive or the timeout expires
  3. Dispatch: Inbound messages are dispatched concurrently via asyncio.create_task
  4. Sync buffer: A persistent sync cursor (get_updates_buf) is saved to disk so the adapter resumes from the correct position after restarts

Retry Behavior

On API errors, the adapter uses a simple retry strategy:

ConditionBehavior
Transient error (1st–2nd)Retry after 2 seconds
Repeated errors (3+)Back off for 30 seconds, then reset counter
Session expired (errcode=-14)Pause for 10 minutes (re-login may be needed)
TimeoutImmediately re-poll (normal long-poll behavior)

Deduplication

Inbound messages are deduplicated using message IDs with a 5-minute window. This prevents double-processing during network hiccups or overlapping poll responses.

Token Lock

Only one Weixin gateway instance can use a given token at a time. The adapter acquires a scoped lock on startup and releases it on shutdown. If another gateway is already using the same token, startup fails with an informative error message.

All Environment Variables

A lookup table. Do not read it all; find the row that applies to you.

VariableRequiredDefaultDescription
WEIXIN_ACCOUNT_ID✅—iLink Bot account ID (from QR login)
WEIXIN_TOKEN✅—iLink Bot token (auto-saved from QR login)
WEIXIN_BASE_URL—https://ilinkai.weixin.qq.comiLink API base URL
WEIXIN_CDN_BASE_URL—https://novac2c.cdn.weixin.qq.com/c2cCDN base URL for media transfer
WEIXIN_DM_POLICY—openDM access policy: open, allowlist, disabled, pairing
WEIXIN_GROUP_POLICY—disabledGroup access policy: open, allowlist, disabled
WEIXIN_ALLOWED_USERS—_(empty)_Comma-separated user IDs for DM allowlist
WEIXIN_GROUP_ALLOWED_USERS—_(empty)_Comma-separated group chat IDs (not member user IDs) for group allowlist. The variable name is legacy — it expects group IDs, not user IDs.
WEIXIN_HOME_CHANNEL——Chat ID for cron/notification output
WEIXIN_HOME_CHANNEL_NAME—HomeDisplay name for the home channel
WEIXIN_ALLOW_ALL_USERS——Gateway-level flag to allow all users (used by setup wizard)

Troubleshooting

A troubleshooting section. Find the symptom that matches yours rather than reading it end to end.

ProblemFix
Weixin startup failed: aiohttp and cryptography are requiredInstall both: pip install aiohttp cryptography
Weixin startup failed: WEIXIN_TOKEN is requiredRun hermes gateway setup to complete QR login, or set WEIXIN_TOKEN manually
Weixin startup failed: WEIXIN_ACCOUNT_ID is requiredSet WEIXIN_ACCOUNT_ID in your .env or run hermes gateway setup
Another local Hermes gateway is already using this Weixin tokenStop the other gateway instance first — only one poller per token is allowed
Session expired (errcode=-14)Your login session has expired. Re-run hermes gateway setup to scan a new QR code
QR code expired during setupThe QR auto-refreshes up to 3 times. If it keeps expiring, check your network connection
Bot doesn't respond to DMsCheck WEIXIN_DM_POLICY — if set to allowlist, the sender must be in WEIXIN_ALLOWED_USERS
Bot ignores group messagesGroup policy defaults to disabled. Set WEIXIN_GROUP_POLICY=open or allowlist — but note that QR-login iLink bot identities (...@im.bot) typically cannot receive ordinary WeChat group messages at all. If the gateway logs show no raw inbound events for group messages, the limitation is on the iLink side, not in Hermes.
Media download/upload failsEnsure cryptography is installed. Check network access to novac2c.cdn.weixin.qq.com
Blocked unsafe URL (SSRF protection)The outbound media URL points to a private/internal address. Only public URLs are allowed
Voice messages show as textIf WeChat provides a transcription, the adapter uses the text. This is expected behavior
Messages appear duplicatedThe adapter deduplicates by message ID. If you see duplicates, check if multiple gateway instances are running
iLink POST ... HTTP 4xx/5xxAPI error from the iLink service. Check your token validity and network connectivity
Terminal QR code doesn't renderReinstall with the messaging extra: cd ~/.hermes/hermes-agent && uv pip install -e ".[messaging]". Alternatively, open the URL printed above the QR
Knowledge check

4 questions answered by this page alone.

Every option is a real identifier from the Hermes documentation. The wrong ones are real too, just from other pages.

1. In this lesson's table, what is the “Default” for “textbatchsplitdelayseconds”?
2. Which of these environment variables actually appears in this lesson?
3. Which warning does the source state in this lesson?
4. Which of these headings does not appear in this lesson?