Tg Rich Messages 标志

Tg Rich Messages

社区
serejaris
tg-rich-messages

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.

Add to TypingMind

概览

发布者serejaris
代码仓库telegram-skills
技能名称tg-rich-messages
星标数
35
复刻数
4
附带文件
4
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 4 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 serejaris 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Tg Rich Messages AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/serejaris/telegram-skills/tree/main/skills/tg-rich-messages
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/serejaris/telegram-skills.git /tmp/telegram-skills
mkdir -p .claude/skills
cp -r /tmp/telegram-skills/skills/tg-rich-messages .claude/skills/tg-rich-messages
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Tg Rich Messages,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Tg Rich Messages。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Tg Rich Messages 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

tg-rich-messages

Sending requires network access to api.telegram.org and a Telegram bot token.

Overview

Bot API 10.1 introduced Rich Messages. Bot API 10.2 (July 14, 2026) added direct outgoing block JSON and explicit media bindings. 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:

NeedMechanism
Section headings (h1–h6)RichBlockSectionHeading
Tables with header rows / spanning cellsRichBlockTable
Collapsible sectionsRichBlockDetails
Photo grid or slide deckRichBlockCollage / RichBlockSlideshow
Embedded mapRichBlockMap
LaTeX math (inline or block)RichTextMathematicalExpression / RichBlockMathematicalExpression
Streaming AI reply with "Thinking…" blocksendRichMessageDraft + RichBlockThinking
Footnotes / anchor linksRichTextReference / RichTextAnchorLink

Plain sendMessage with parse_mode: HTML still covers bold/italic/code/spoiler/links for simple formatting. Move to sendRichMessage only when you need structural blocks.


Bot UI composition (10.3)

Use the network-free Python helper 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 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.

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:

FieldWhen to use
htmlRich HTML with Telegram-specific tags
markdownGitHub-Flavored Markdown + Telegram extensions
blocksDirect 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:

FieldTypePurpose
is_rtlBooleanRender message right-to-left
skip_entity_detectionBooleanDisable auto-detection of URLs, emails, mentions, etc.
mediaInputRichMessageMedia[]Resolve tg://photo, tg://video, 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://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://<part_name>. 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, InputMediaPhoto, InputMediaVideo, or InputMediaVoiceNote. Markup exposes three reference schemes: photo, video, 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 <figcaption> 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"
  }
}
TypeMetadata worth setting
audioduration, performer, title — shown in the inline player
videoduration, width, height, thumbnail, supports_streaming, has_spoiler
photohas_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. A mismatch is a definite error.
  4. Every attach://<name> has a matching file part, and the file exists on disk.
python
import re

REF = re.compile(r"tg://(photo|video|audio)\?id=([A-Za-z0-9_-]+)")
ACCEPTS = {"photo": {"photo"}, "video": {"video", "animation"}, "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": "<h2>Weekly Report</h2><p>Highlights from the past week.</p><table bordered><tr><th>Item</th><th>Value</th></tr><tr><td>Sales</td><td><b>142</b></td></tr></table>"
    }
  }'

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": (
            "<h2>Weekly Report</h2>"
            "<p>Highlights from the past week.</p>"
            "<table bordered>"
            "<tr><th>Item</th><th>Value</th></tr>"
            "<tr><td>Sales</td><td><b>142</b></td></tr>"
            "</table>"
        )
    },
}

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 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:

ResponseMeaningCorrect reaction
ok: trueDeliveredStore message_id — it is the handle for later editMessageText
HTTP 4xx with ok: falseDefinite failure, nothing was postedFix the payload and resend
HTTP 429 or 5xx, or a transport timeoutUnknown — the message may already be in the channelDo 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 stringHTML tagPurposeKey fields
paragraph<p>Text paragraphtext: RichText
heading<h1>–<h6>Section headingtext, size: 1–6 (1 = largest)
pre<pre>Preformatted / code blocktext, language?: string
footer<footer>Footer texttext: RichText
divider<hr/>Horizontal rule(no content fields)
anchor<a name="...">Named anchor pointname: string
mathematical_expression<tg-math-block>Block LaTeX formulaexpression: string
list<ul> / <ol>Ordered or unordered listitems: RichBlockListItem[]
blockquote<blockquote>Block quotationblocks: RichBlock[], credit?: RichText
pullquote<aside>Centered pull quotetext, credit?: RichText
details<details>Collapsible sectionsummary: RichText, blocks: RichBlock[], is_open?: true
table<table>Data tablecells: RichBlockTableCell[][], is_bordered?, is_striped?, caption?: RichText
map<tg-map>Static embedded maplocation: Location, zoom: 0–24, width, height, caption?
collage<tg-collage>Photo/video gridblocks: RichBlock[], caption?: RichBlockCaption
slideshow<tg-slideshow>Swipeable photo/video deckblocks: RichBlock[], caption?: RichBlockCaption
photo<img>Photo blockphoto: PhotoSize[], has_spoiler?: true, caption?
video<video>Video blockvideo: Video, has_spoiler?: true, caption?
animation<video> (gif)Animation / GIF blockanimation: Animation, has_spoiler?: true, caption?
audio<audio> (mp3)Audio / music blockaudio: Audio, caption?
voice_note<audio> (ogg)Voice message blockvoice_note: Voice, caption?
thinking<tg-thinking>"Thinking…" placeholder (draft only)text: RichText

thinking is only valid in sendRichMessageDraft. It cannot appear in sendRichMessage and is never stored in a Message.

Inline text types (RichText)

Type stringHTML tagPurposeExtra fields
bold<b>Boldtext
italic<i>Italictext
underline<u>Underlinetext
strikethrough<s>Strikethroughtext
spoiler<tg-spoiler>Hidden spoiler texttext
marked<mark>Highlighttext
code<code>Inline monospacetext
subscript<sub>Subscripttext
superscript<sup>Superscripttext
custom_emoji<tg-emoji>Custom emojicustom_emoji_id, alternative_text
mathematical_expression<tg-math>Inline LaTeXexpression: string
date_time<tg-time>Formatted timestamptext, unix_time: int, date_time_format: string
text_mention<a href="tg://user?id=...">User mention by IDtext, user: User
mentionauto-detectedUsername mentiontext, username: string
url<a href="https://...">URL linktext, url: string
email_address<a href="mailto:...">Email linktext, email_address: string
phone_number<a href="tel:...">Phone linktext, phone_number: string
bank_card_numberauto-detectedBank card highlighttext, bank_card_number: string
hashtagauto-detectedHashtagtext, hashtag: string
cashtagauto-detectedCashtagtext, cashtag: string
bot_commandauto-detectedBot commandtext, bot_command: string
anchor<a name="..."> (inline)Inline anchor pointname: string
anchor_link<a href="#...">Link to anchortext, anchor_name: string (empty = top)
reference<tg-reference name="...">Footnote definitiontext, name: string
reference_link<a href="#..."> (ref)Link to footnotetext, reference_name: string

Markdown quick syntax

**bold**   *italic*   __bold__   _italic_
~~strikethrough~~   `code`   ==marked==   ||spoiler||

[Link text](https://example.com)
[Email](mailto:user@example.com)
[Phone](tel:+1234567890)
[Mention user](tg://user?id=123456789)
![custom emoji](tg://emoji?id=5368324170671202286)
![timestamp label](tg://time?unix=1647531900&format=wDT)
$inline LaTeX formula$
$$block LaTeX formula$$

# H1  ## H2  ...  ###### H6

```python
code block with language

--- (divider)

  • unordered item 1. ordered item
  • task - [x] done task

blockquote line

# photo block # with caption # video block # audio block # voice note # animation

Col 1Col 2
leftright

Text[^fn1]. [^fn1]: Footnote text.


Limits & traps

LimitValue
Max UTF-8 characters (text, alt-text, formulas)32 768
Max blocks (including nested: list items, table rows, blockquote/details blocks)500
Max nesting levels16
Max media attachments (photos, videos, audio)50
Max table columns20
Map zoom range0–24

Critical constraints

Choose exactly one content representation. Use html, markdown, or blocks.

Markup media has two source paths.

  • Media must be specified as separate blocks, not inline in text.
  • Direct HTTP/HTTPS media URLs work without media.
  • tg://photo?id=, tg://video?id=, and tg://audio?id= require a matching entry in media.
  • Each bound InputMedia*.media accepts file_id, HTTP/HTTPS URL, or multipart attach://.
  • Direct URL media type is inferred from MIME type and URL extension. Bound media type comes from the nested InputMedia* object.

Table cells: inline formatting only. No blocks (<p>, <ul>, <img>, etc.) inside <td> / <th>. Only inline tags.

RichBlockThinking is draft-only. Can only appear in sendRichMessageDraft. Never in sendRichMessage. Never stored in a Message object.

sendRichMessageDraft is private-chat only. chat_id must be an Integer. @username strings are not accepted.

editMessageText: text and rich_message are mutually exclusive. Pass exactly one. Sending both (or neither) is an error.

Map is static, no markers. RichBlockMap renders a static tile at the given location and zoom level. No pins, no interactivity.

Block count includes nesting. The 500-block limit counts every RichBlockListItem, every table row, every block inside blockquote / details. Deep nesting exhausts the budget fast.

Collage and slideshow accept both photos and videos. blocks can mix photo and video blocks. Both may also be placed inside a details block as collapsible media.


Common mistakes

MistakeFix
Passing an array directly as rich_messageWrap it as {"blocks":[...]}
Using tg://...id=cover without mediaAdd an InputRichMessageMedia with id: "cover"
Leaving a bound id that markup no longer referencesDrop the binding — an unused one is an editing slip, not a no-op
Binding voice_note behind tg://video?id=Match the scheme: photo→photo, video→video/animation, audio→audio/voice_note
Sending attach://cover in JSON onlySwitch the request to multipart/form-data and add the cover file part
Nesting the multipart form fields as JSON objectsEvery non-file field is a string: json.dumps(rich_message) in one form field
Putting the caption in InputMedia*.caption of a bindingCaptions come from markup — the image title argument or <figcaption>
Shipping audio bindings without duration/titleThe inline player shows an unlabelled blob; set the metadata on the binding
Retrying a sendRichMessage that timed outOutcome is unknown — retrying duplicates the post; resolve it before resending
Putting an InputMedia* caption inside a direct media blockPut the caption on InputRichBlockPhoto / Video / Audio
Putting <img> or <video> inline in <p>Move media to its own block, outside <p>
Adding block elements inside <td>Only inline tags inside table cells
Using RichBlockThinking in sendRichMessagethinking is valid only in sendRichMessageDraft
Calling sendRichMessageDraft with @usernameUse numeric chat_id (Integer)
Sending text and rich_message together in editMessageTextPass exactly one
Forgetting to call sendRichMessage after streamingDraft expires after 30 s — always finalize with full message
Assuming a narrower fixed map zoom rangeOutgoing InputRichBlockMap.zoom is optional and ranges 0–24
Using skip_entity_detection for manual link formattingSet it to true to prevent double-detection when you already mark up URLs manually

Full spec

All types, all fields, all format details: ../../reference/rich-messages-spec.md

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Tg Rich Messages AI 技能有什么作用?

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.

为什么在 TypingMind 中使用 Tg Rich Messages?

因为您只需安装一次,就能搭配任何模型使用。Tg Rich Messages 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Tg Rich Messages?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/serejaris/telegram-skills/tree/main/skills/tg-rich-messages。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Tg Rich Messages?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Tg Rich Messages 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Tg Rich Messages 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Tg Rich Messages AI 技能免费吗?

是的。serejaris 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇