--- name: tg-rich-messages description: "Use when sending structured or richly formatted messages from a Telegram bot — tables, section headings, collapsible blocks, photo galleries, maps, math formulas, audio, native styled buttons, bot UI cards, or streaming AI responses. Also use for understanding rich message types and limits when plain sendMessage with parse_mode HTML/Markdown is not sufficient." license: MIT --- # tg-rich-messages Sending requires network access to `api.telegram.org` and a Telegram bot token. Checked against the official docs on 2026-10-30: Bot API 10.3 (latest, August 24, 2026). Nothing here was run against a live bot. ## Overview Bot API 10.1 introduced **Rich Messages**. Bot API 10.2 (July 14, 2026) added direct outgoing block JSON and explicit media bindings. Bot API 10.3 (August 24, 2026) added buttons, compact tables, expandable quotations and document blocks. Rich messages are document-grade content delivered directly in chat. Think Instant View articles — headings, tables, collage, slideshow, map, math, collapsible blocks — but sent by a bot via `sendRichMessage`. **Use `sendRichMessage` instead of `sendMessage` when you need:** | Need | Mechanism | |---|---| | Section headings (h1–h6) | `RichBlockSectionHeading` | | Tables with header rows / spanning cells | `RichBlockTable` | | Collapsible sections | `RichBlockDetails` | | Photo grid or slide deck | `RichBlockCollage` / `RichBlockSlideshow` | | Embedded map | `RichBlockMap` | | LaTeX math (inline or block) | `RichTextMathematicalExpression` / `RichBlockMathematicalExpression` | | Streaming AI reply with "Thinking…" block | `sendRichMessageDraft` + `RichBlockThinking` | | Footnotes / anchor links | `RichTextReference` / `RichTextAnchorLink` | **Stay on classic `sendMessage` when:** | Need | Why classic wins | |---|---| | Bold, italic, code, spoiler and links only | `parse_mode: HTML` covers it | | Link preview under the post, or a chosen preview URL | `sendRichMessage` and `InputRichMessage` have no `link_preview_options` | | Custom emoji in a bot's channel post | The docs allow them in private, group and supergroup chats, or for bots with a Fragment username; see [Custom emoji](#custom-emoji) | | A message you will edit, with custom emoji | Rich edits can lose them; see [Known bugs](#known-bugs) | --- ## Bot UI composition (10.3) Use the network-free [Python helper](scripts/rich_ui.py) for deterministic heading, paragraph, pre, compact table, details and photo blocks with literal strings. It validates a narrow subset, not the complete Bot API. Photo uploads stay in the consumer's authorized transport. See [consumer integration](consumer-integration.md) for the exact API, illustrated previews, provenance, send/edit lifecycle and local tests. Inline keyboard styles: `primary`, `success`, `danger`; omit for app default. Product composition: at most one primary CTA per screen; neutral secondary navigation. Green is reserved for confirmed success or a desirable commit, red for genuinely destructive actions. Ordinary Back/Cancel, bonus offers and verification actions remain neutral. Start with heading → brief value → next action; move provider plumbing and limits to contextual About/limits views. Review actual mobile outcomes and user feedback before adding emphasis. RichMessageButton additionally accepts `link` only for callback buttons. Never put `link` on InlineKeyboardButton. Native rich button rows use `type: "buttons"`, 1–8 buttons and optional `align: left|center|right`; these are documented in the reference and intentionally outside the helper subset. For decision/inference bots, explain what the product does and why it helps with a concrete **input → criteria → result** sequence. Offer a free catalogue and case preview before an explicit paid/quota-consuming run; cached navigation should not silently repeat inference. Attribute source-backed cases as your observed experiment, an external project, or a synthetic teaching adaptation. Keep source links available and longer provenance in a closed details block. Show actual outputs and disclose missing values honestly. See the onboarding section in [consumer integration](consumer-integration.md). Direct block text is literal RichText. Keep dynamic strings unescaped; HTML escaping belongs only to an HTML renderer. A native JSON code block is `{"type":"pre","text":json_string,"language":"json"}`. Table cells require `align` and `valign`; compact tables use `is_compact: true`. Update an acknowledged screen with `editMessageText.rich_message`, exactly one of `text` and `rich_message`. Keep returned Bot API message IDs and check callback ownership/current-screen binding. There is no `editRichMessage`. Do not silently duplicate a message after an unknown delivery outcome. ## Sending: InputRichMessage `sendRichMessage` takes an `InputRichMessage` object in its `rich_message` field. Choose exactly one content field: | Field | When to use | |---|---| | `html` | Rich HTML with Telegram-specific tags | | `markdown` | GitHub-Flavored Markdown + Telegram extensions | | `blocks` | Direct `InputRichBlock[]` JSON for deterministic programmatic composition | Do not pass multiple content fields. With `html` or `markdown`, add optional `media` bindings for uploaded files, Telegram `file_id` values, or HTTP URLs. Optional fields on `InputRichMessage`: | Field | Type | Purpose | |---|---|---| | `is_rtl` | Boolean | Render message right-to-left | | `skip_entity_detection` | Boolean | Disable auto-detection of URLs, emails, mentions, etc. | | `media` | InputRichMessageMedia[] | Resolve `tg://photo`, `tg://video`, `tg://document`, and `tg://audio` references in markup | ### Media bindings for HTML and Markdown Reference media in markup: ```markdown ![](tg://photo?id=cover) ![](tg://video?id=demo) ![](tg://document?id=report) ![](tg://audio?id=voice) ``` Then bind each ID: ```json { "markdown": "## Launch\n\n![](tg://photo?id=cover)", "media": [ { "id": "cover", "media": {"type": "photo", "media": "AgAC...file_id"} } ] } ``` Media IDs are 1–64 characters using only letters, digits, `_`, and `-`. The nested `InputMedia*.media` accepts a Telegram `file_id`, an HTTP/HTTPS URL, or `attach://`. Use JSON for `file_id` and URLs. Use multipart/form-data for `attach://` uploads and provide a file part with the same name. `InputRichMessageMedia.media` may be `InputMediaAnimation`, `InputMediaAudio`, `InputMediaDocument`, `InputMediaPhoto`, `InputMediaVideo`, or `InputMediaVoiceNote`. Markup exposes four reference schemes: `photo`, `video`, `document`, and `audio`; animation travels through `video`, and voice note through `audio`. #### Captions and player metadata The caption comes from the **markup**, not from the binding — the title argument of the Markdown image syntax (or `
` in HTML): ```markdown ![](tg://photo?id=cover "Release notes: the model shipped on July 29") ``` `InputMedia*.caption` inside the binding is ignored. What the binding *does* carry is player metadata, and for audio it is what turns a raw file into a labelled track in the message: ```json { "id": "live_answer", "media": { "type": "audio", "media": "attach://live_answer_file", "duration": 4, "performer": "Grok Voice 2.0", "title": "Answer: 323" } } ``` | Type | Metadata worth setting | |---|---| | `audio` | `duration`, `performer`, `title` — shown in the inline player | | `video` | `duration`, `width`, `height`, `thumbnail`, `supports_streaming`, `has_spoiler` | | `photo` | `has_spoiler` | Set `duration` even when Telegram can infer it: several short clips in one message render as a consistent list only when every one of them reports its length. ### Preflight: validate bindings before sending Telegram reports a bad binding as one opaque `Bad Request`. Validate locally first and the failure names the offending id. Four checks, all cheap: 1. **Every `tg://…?id=X` in markup has a binding.** Missing → the media silently never renders or the call fails. 2. **Every binding is referenced by the markup.** An unused binding means an editing slip — a renamed id, a dropped paragraph. Telegram's behaviour here is unspecified; treat it as a build error of your own. 3. **The reference scheme matches the bound type.** `tg://audio?id=X` accepts `audio` or `voice_note`; `tg://video?id=X` accepts `video` or `animation`; `tg://photo?id=X` accepts `photo`; `tg://document?id=X` accepts `document`. A mismatch is a definite error. 4. **Every `attach://` has a matching file part**, and the file exists on disk. ```python import re REF = re.compile(r"tg://(photo|video|document|audio)\?id=([A-Za-z0-9_-]+)") ACCEPTS = {"photo": {"photo"}, "video": {"video", "animation"}, "document": {"document"}, "audio": {"audio", "voice_note"}} def check(markup: str, media: list[dict]) -> None: bound = {item["id"]: item["media"]["type"] for item in media} refs = set(REF.findall(markup)) referenced = {media_id for _, media_id in refs} if missing := referenced - bound.keys(): raise ValueError(f"missing bindings: {sorted(missing)}") if unused := bound.keys() - referenced: raise ValueError(f"unused bindings: {sorted(unused)}") for scheme, media_id in refs: if bound[media_id] not in ACCEPTS[scheme]: raise ValueError(f"{media_id}: tg://{scheme} cannot carry {bound[media_id]}") ``` Keep the file paths in a small manifest next to the payload — attachment name, path, MIME type — so the multipart step is a lookup rather than a second source of truth: ```json [ {"id": "cover", "attachment_name": "cover_file", "path": "cover.png", "mime_type": "image/png"} ] ``` ### Direct block JSON Use `blocks` when code already has a structured document tree: ```json { "blocks": [ {"type": "heading", "size": 2, "text": "Daily AI Brief"}, {"type": "paragraph", "text": ["One release matters today: ", {"type": "bold", "text": "Opus 5"}]}, { "type": "photo", "photo": {"type": "photo", "media": "AgAC...file_id"}, "caption": {"text": "Official launch image"} } ] } ``` Nested blocks use `InputRichBlock`. Media blocks embed `InputMedia*` directly. Put captions in the outer block; captions inside nested `InputMedia*` are ignored. --- ## Sending: HTTP calls ### curl (HTML mode) ```bash curl -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendRichMessage" \ -H "Content-Type: application/json" \ -d '{ "chat_id": '"$CHAT_ID"', "rich_message": { "html": "

Weekly Report

Highlights from the past week.

ItemValue
Sales142
" } }' ``` ### Python (stdlib, HTML mode) ```python import json import os import urllib.request TOKEN = os.environ["TELEGRAM_BOT_TOKEN"] CHAT_ID = int(os.environ["CHAT_ID"]) payload = { "chat_id": CHAT_ID, "rich_message": { "html": ( "

Weekly Report

" "

Highlights from the past week.

" "" "" "" "
ItemValue
Sales142
" ) }, } req = urllib.request.Request( f"https://api.telegram.org/bot{TOKEN}/sendRichMessage", data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"}, method="POST", ) with urllib.request.urlopen(req) as resp: result = json.load(resp) ``` ### Python (stdlib, Markdown mode) ```python payload = { "chat_id": CHAT_ID, "rich_message": { "markdown": ( "## Weekly Report\n\n" "Highlights from the past week.\n\n" "| Item | Value |\n" "|------|-------|\n" "| Sales | **142** |\n" ) }, } ``` See [`examples.md`](examples.md) for more complete examples including streaming drafts, collages, details blocks, and a full multipart upload. ### Delivery outcomes: what a failed call actually means A rich message with uploads is a large multipart request, so the interesting failures are not validation errors — they are the ones where you do not know whether the message went out. Split the response three ways: | Response | Meaning | Correct reaction | |---|---|---| | `ok: true` | Delivered | Store `message_id` — it is the handle for later `editMessageText` | | HTTP 4xx with `ok: false` | Definite failure, nothing was posted | Fix the payload and resend | | HTTP 429 or 5xx, or a transport timeout | **Unknown** — the message may already be in the channel | Do not blind-retry | The third row is the one that bites. Retrying a timed-out `sendRichMessage` is how a channel gets the same article twice, and there is no dedup on Telegram's side. Mark the send as *unresolved* instead, and require a human (or a lookup of the channel's last message) to decide before anything is sent again. If you retry automatically anywhere, retry only calls that failed with a definite 4xx. --- ## Block types — quick reference ### Structural blocks | Type string | HTML tag | Purpose | Key fields | |---|---|---|---| | `paragraph` | `

` | Text paragraph | `text: RichText` | | `heading` | `

`–`

` | Section heading | `text`, `size: 1–6` (1 = largest) | | `pre` | `
` | Preformatted / code block | `text`, `language?: string` |
| `footer` | `