الأكاديمية ← قنوات المراسلةتوثيق رسمي · إرشاد عربي

قناة Weixin (WeChat)

Weixin (WeChat)

متوسط إلى متقدم14 دقيقة قراءةالدرس 224 أسئلة✓ 2026-08-18
قبل أن تقرأ

ما هذه الصفحة، وماذا تحتوي.

بوابة المراسلة: الوصلة التي تجعلك تكلّم Hermes من تطبيق تستعمله أصلًا، مثل Telegram أو WhatsApp، بدل الطرفية. الوكيل الذي تصله من هاتفك تستعمله فعلًا. الذي يحتاج فتح الحاسوب تنساه بعد أسبوع. الصفحة فيها تحذير من المصدر، و14 دقيقة قراءة. انتبه: افتح القناة لنفسك فقط في البداية عبر قائمة سماح. القناة المفتوحة تعني أن أي شخص يراسل وكيلك.

13أقسام
7أمثلة برمجية
8جداول
2أوامر
2,327كلمة من المصدر
الوصف الرسمي في سطر

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

ماذا ستستطيع بعدها

نتائج مأخوذة من هذه الصفحة، لا من قالب.

  • تعرف ما بوابة المراسلة ولماذا قد تحتاجه.
  • تنفّذ hermes gateway setup وhermes gateway وتفهم ما يحدث بعدها.
  • تقرأ الجدول وتأخذ منه السطر الذي يخصّك فقط.
  • تضبط WEIXIN_GROUP_POLICY في المكان الصحيح.
ما ستقابله من أسماء

كما تظهر تمامًا داخل Hermes.

الأوامر
  • hermes gateway setup
  • hermes gateway
متغيرات البيئة
  • 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
خريطة الصفحة

انتقل مباشرة إلى ما تحتاجه.

  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
الصفحة الرسمية كاملة

بلا اختصار أو حذف.

النص أدناه منقول من المصدر الرسمي بالإنجليزية حتى تبقى الأوامر والأسماء دقيقة كما هي. قبل كل قسم شرح عربي يوضّح ما بداخله.

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

شرح للفكرة نفسها. اقرأه ببطء، فبقية الأقسام تبني عليه. تذكير: الوصلة التي تجعلك تكلّم Hermes من تطبيق تستعمله أصلًا، مثل Telegram أو WhatsApp، بدل الطرفية.

  • 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 أسطر
pip install aiohttp cryptography
# Optional: for terminal QR code display
cd ~/.hermes/hermes-agent && uv pip install -e ".[messaging]"

Setup

خطوات عملية بالترتيب. نفّذ خطوة وتأكد أنها نجحت قبل الانتقال للتالية. الأوامر هنا: hermes gateway، hermes gateway setup.

1. Run the Setup Wizard

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

Shellسطر واحد
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:

Textسطر واحد
微信连接成功,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 سطرًا
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

Shellسطر واحد
hermes gateway

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

Features

أوامر تكتبها في الطرفية. افهم ما يفعله الأمر قبل نسخه. الأوامر هنا: 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

جدول مرجعي. لا تقرأه كله، ابحث عن السطر الذي يخصّك فقط.

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

جدول مرجعي. لا تقرأه كله، ابحث عن السطر الذي يخصّك فقط. الأوامر هنا: 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)
Shellسطران
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 أسطر
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

جدول مرجعي. لا تقرأه كله، ابحث عن السطر الذي يخصّك فقط.

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

شرح للفكرة نفسها. اقرأه ببطء، فبقية الأقسام تبني عليه.

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

شرح للفكرة نفسها. اقرأه ببطء، فبقية الأقسام تبني عليه.

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

شرح للفكرة نفسها. اقرأه ببطء، فبقية الأقسام تبني عليه.

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

شرح للفكرة نفسها. اقرأه ببطء، فبقية الأقسام تبني عليه.

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

جدول مرجعي. لا تقرأه كله، ابحث عن السطر الذي يخصّك فقط.

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

جدول مرجعي. لا تقرأه كله، ابحث عن السطر الذي يخصّك فقط.

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

قسم لحل المشكلات. ابحث فيه عن العطل الذي يشبه حالتك بدل قراءته كاملًا.

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
اختبار الفهم

4 أسئلة إجاباتها كلها في هذه الصفحة.

كل خيار اسم حقيقي من توثيق Hermes. حتى الخيارات الخاطئة حقيقية، لكنها من صفحات أخرى.

1. في جدول هذا الدرس، ما «Default» المقابل لـ«textbatchsplitdelayseconds»؟
2. أي متغير بيئة من التالي يظهر فعليًا في هذا الدرس؟
3. ما التحذير الذي يذكره المصدر في هذا الدرس؟
4. أي عنوان من التالي لا يظهر في هذا الدرس؟