cap_im_tg — Telegram IM integration
Source: cap_im_tg.c · header: cap_im_tg.h
cap_im_tg is the reference IM capability, showing one component playing two roles:
- Event source: background long-poll of the Telegram Bot API, turning user messages into
claw_event_routerevents - Callable tools: send text/image/file so the Agent can proactively reply
That dual pattern is the common architecture for IM caps (Feishu, QQ, WeChat).
Architecture sketch
Section titled “Architecture sketch”Event source: long polling
Section titled “Event source: long polling”cap_im_tg starts two FreeRTOS tasks from the start hook:
tg_poll_task
Section titled “tg_poll_task”Calls getUpdates with a 20 s long-poll timeout, parses each update, and publishes events:
claw_event_router then routes to claw_core for the Agent or to automation actions.
Dedup cache
Section titled “Dedup cache”Network jitter can replay updates; cap_im_tg keeps a ring of FNV-1a 64-bit hashes (64 slots) so the same message is not handled twice:
Attachments (tg_attachment_task)
Section titled “Attachments (tg_attachment_task)”Media download is slow, so it is async:
tg_poll_taskenqueuescap_im_tg_attachment_job_t(depth 8)tg_attachment_taskconsumes jobs, callsgetFile, streams into FATFS- On completion it publishes
attachment_savedwithpayload_json(local path, MIME, size, …)
Downstream rules can listen for attachment_saved and chain cap_llm_inspect, etc.
Callable tools
Section titled “Callable tools”cap_im_tg registers four descriptors:
| Tool ID | Description | kind |
|---|---|---|
tg_gateway | Poll gateway (event source) | EVENT_SOURCE |
tg_send_message | Send text to a chat_id | CALLABLE |
tg_send_image | Send a local image file | CALLABLE |
tg_send_file | Send a local arbitrary file | CALLABLE |
tg_send_message notes
Section titled “tg_send_message notes”- If
chat_idis missing ininput_json, fall back toctx->chat_id(reply to the current conversation) - Long text is chunked (4096 bytes max per
sendMessage)
Images/files: multipart streaming
Section titled “Images/files: multipart streaming”tg_send_image / tg_send_file upload via multipart/form-data:
stat()for exactContent-Lengthesp_http_client_open+ manual parts—no full-file RAM buffer- MIME guessed from extension (
.jpg,.png,.pdf,.txt,.json)
Configuration API
Section titled “Configuration API”Application code configures cap_im_tg through:
Compared to other IM caps
Section titled “Compared to other IM caps”cap_im_feishu, cap_im_qq, cap_im_wechat share the same split; only protocol and auth differ:
| Component | Protocol | Notes |
|---|---|---|
cap_im_tg | Bot API + long poll | Simplest, no server of your own |
cap_im_feishu | Webhook / Event API | Needs public reachability |
cap_im_qq | QQ Bot API | Tencent approval |
cap_im_wechat | WeCom API | Enterprise scenarios |