chat / adapter-telegram
AGENTS.md2.4k starsChanged 59 days agoMITView on GitHub
Guidance for coding agents working inside the Telegram adapter package. The top-level repository AGENTS.md covers monorepo-wide build, lint, and release rules — read it first. This file documents the adapter-specific surface, conventions, and pitfalls. @chat-adapter/telegram connects a Chat SDK bot to a Telegram bot account via the official Bot API. It covers: - HTTP webhook endpoint at /api/webhooks/telegram (or polling for long-running processes), validated with the optional secret_token header. - Inline keyboards for buttons (cards/actions are rendered as a text…
Trending
Quiet since March.thin dataabout the whole repository
Who's talking about vercel/chat
- @camilleroux.com“Un SDK TypeScript unifié pour créer des chatbots qui fonctionnent sur Slack, Teams, Google Chat, Discord, …”Bluesky · Mar 3, 2026 · 3 likes
- @technews4869.bsky.social“github.com/vercel/chat GitHub - vercel/chat: A unified TypeScript SDK for building chat bots across Slack, …”Bluesky · Mar 7, 2026 · 1 likes
- @yug1224.com“チャットアプリ開発に使える統一SDKを提供するツールらしい 様々なプラットフォーム対応で便利そうだな yug1224 starred vercel/chat https://github.com/vercel/chat”Bluesky · Mar 7, 2026 · 1 likes
- @news.humancoders.com“Vercel lance Chat SDK : un SDK TypeScript unifié pour créer des bots multi-plateformes”Bluesky · Mar 5, 2026 · 1 likes
- @github-trending-js.bsky.social“🔥 Hot Repo! 🔥 (100+ new stars) 📦 vercel / chat ⭐ 871 (+121) 🗒 TypeScript A unified TypeScript SDK for …”Bluesky · Feb 27, 2026 · 1 likes
The biggest 5 of 5 mentions linking to the repository that our crawl found. Each line is their own headline.
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository44 other files it gives its agents.
- AGENTS.mdAGENTS.md
- apps/docs/AGENTS.mdAGENTS.md
- chat-sdkAGENTS.md
- packages/adapter-discord/AGENTS.mdAGENTS.md
- packages/adapter-gchat/AGENTS.mdAGENTS.md
- packages/adapter-github/AGENTS.mdAGENTS.md
- packages/adapter-instagram/AGENTS.mdAGENTS.md
- packages/adapter-linear/AGENTS.mdAGENTS.md
- packages/adapter-messenger/AGENTS.mdAGENTS.md
- packages/adapter-notion/AGENTS.mdAGENTS.md
- packages/adapter-slack/AGENTS.mdAGENTS.md
- packages/adapter-teams/AGENTS.mdAGENTS.md
- packages/adapter-web/AGENTS.mdAGENTS.md
- packages/adapter-whatsapp/AGENTS.mdAGENTS.md
- packages/chat/src/adapters/AGENTS.mdAGENTS.md
- packages/create-chat-sdk/AGENTS.mdAGENTS.md
- packages/create-chat-sdk/_template/AGENTS.mdAGENTS.md
- packages/state-ioredis/AGENTS.mdAGENTS.md
- packages/state-memory/AGENTS.mdAGENTS.md
- packages/state-pg/AGENTS.mdAGENTS.md
- packages/state-redis/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- packages/adapter-discord/CLAUDE.mdCLAUDE.md
- packages/adapter-gchat/CLAUDE.mdCLAUDE.md
- packages/adapter-github/CLAUDE.mdCLAUDE.md
- packages/adapter-linear/CLAUDE.mdCLAUDE.md
- packages/adapter-messenger/CLAUDE.mdCLAUDE.md
- packages/adapter-slack/CLAUDE.mdCLAUDE.md
- packages/adapter-teams/CLAUDE.mdCLAUDE.md
- packages/adapter-telegram/CLAUDE.mdCLAUDE.md
- packages/adapter-web/CLAUDE.mdCLAUDE.md
- packages/adapter-whatsapp/CLAUDE.mdCLAUDE.md
- packages/create-chat-sdk/CLAUDE.mdCLAUDE.md
- packages/create-chat-sdk/_template/CLAUDE.mdCLAUDE.md
- packages/state-ioredis/CLAUDE.mdCLAUDE.md
- packages/state-memory/CLAUDE.mdCLAUDE.md
- packages/state-pg/CLAUDE.mdCLAUDE.md
- packages/state-redis/CLAUDE.mdCLAUDE.md
- add-adapterSkill
- technical-writerSkill
- chat-sdkSkill
- chat-sdkSkill
- chat-sdkSkill
- chat-sdkSkill
The file
We split this AGENTS.md into the rules it gives an agent
3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 225
When you add support for a new update type, capture a fresh fixture in sample-messages.md.
- Distinctive: line 230
Use named exports throughout.
- Very specific: line 237
Always escape user-provided text before concatenation.
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md — @chat-adapter/telegram
Guidance for coding agents working inside the Telegram adapter package. The top-level repository AGENTS.md covers monorepo-wide build, lint, and release rules — read it first. This file documents the adapter-specific surface, conventions, and pitfalls.
Overview
@chat-adapter/telegram connects a Chat SDK bot to a Telegram bot
account via the official Bot API. It covers:
- HTTP webhook endpoint at
/api/webhooks/telegram(or polling for long-running processes), validated with the optionalsecret_tokenheader. - Inline keyboards for buttons (cards/actions are rendered as a text body plus an inline keyboard footer).
- Native message edits — Telegram supports per-message edits, which pairs nicely with streaming.
- Reactions, typing indicators, file uploads (photo, document, animation, video), and forwarded message handling.
- Group chats with optional topic threads (Forums) and direct messages.
Directory layout
packages/adapter-telegram/
├── src/
│ ├── index.ts # TelegramAdapter + createTelegramAdapter
│ ├── index.test.ts
│ ├── cards.ts # Card → text + inline keyboard
│ ├── cards.test.ts
│ ├── markdown.ts # TelegramFormatConverter (mdast ↔ MarkdownV2)
│ ├── markdown.test.ts
│ └── types.ts # Bot API typings
├── sample-messages.md # captured Telegram updates
├── package.json
├── tsconfig.json
├── tsup.config.ts
├── vitest.config.ts
└── README.mdBuild, test, typecheck
pnpm build
pnpm dev
pnpm test
pnpm test:watch
pnpm typecheck
pnpm clean
# from repo root
pnpm --filter @chat-adapter/telegram build
pnpm --filter @chat-adapter/telegram testReplay tests live in
packages/integration-tests/src/replay-telegram-*.test.ts.
Public surface
Main exports from src/index.ts:
createTelegramAdapter(config?)— primary factory. Auto-detectsTELEGRAM_BOT_TOKEN,TELEGRAM_WEBHOOK_SECRET_TOKEN, and the optionalTELEGRAM_BOT_USERNAME(used for mention detection in groups).botTokenaccepts a static string or async resolver and is resolved for each Telegram Bot API or file-download request. This supports outbound-only Vercel Connect authentication while native webhooks keepsecretToken. Webhook deduplication is scoped with the stable bot ID returned bygetMe, never the potentially rotating token. Failed startup identity lookups retry lazily on later verified webhooks.TelegramAdapterclass — implementsAdapter<TelegramThreadId, unknown>. Public methods:handleWebhook,postMessage,reply,editMessage,deleteMessage,addReaction,removeReaction,startTyping,fetchThread,fetchMessages,fetchSingleMessage,fetchChannelInfo,postChannelMessage,openDM,setWebhook,deleteWebhook,getMe.- Configuration:
TelegramAdapterConfig,TelegramThreadId. - Helpers:
cardToTelegramMessage,cardToFallbackText,TelegramFormatConverter,decodeThreadId,encodeThreadId,isDM.
Thread ID format
Telegram chats are identified by numeric chat_id. Forum threads
(Telegram's term for topic threads) carry a message_thread_id. The
adapter encodes both:
telegram:{chatId} # plain chat / DM
telegram:{chatId}:{messageThreadId} # topic in a forum group
telegram:biz:{connectionId}:{chatId} # Connected Business Bot chatisDM(threadId) returns true when chat.type === "private".
Business threads are their own channel: channelIdFromThreadId returns
the full telegram:biz:... ID, never the bare telegram:{chatId}, so
they do not share lock or history keys with the customer's direct bot
chat. Note that sharders keyed on the first two segments group every
business thread under telegram:biz.
Webhook flow
TelegramAdapter.handleWebhook(request, options) is the entry point.
- Secret token verification — when
webhookSecretis configured, the adapter checks theX-Telegram-Bot-Api-Secret-Tokenheader with a timing-safe comparison. - Update routing
message→chat.handleIncomingMessage. Mentions are detected by walkingentities[].type === "mention"and matching the bot's@username.edited_message→ optionalonMessageEdithook.callback_query→chat.handleAction(inline keyboard callbacks).inline_query/chosen_inline_result→ optional inline-mode hooks.message_reaction→chat.handleReaction.my_chat_member/chat_member→ membership change hooks.business_connection→ cached in the state adapter (before theallowedUserIdsgate, since it carries no customer id).business_message/edited_business_message→ resolve the connection from state (falling back togetBusinessConnection), drop owner-typed andsender_business_botechoes, then route slash commands, media groups, and messages likemessage.
waitUntil— outbound API calls (sendMessage,editMessageText, etc.) run insidewaitUntilso the webhook response lands quickly.
Format conversion
Telegram supports two markup modes: MarkdownV2 (strict, with many
escapes required) and HTML. TelegramFormatConverter (in
markdown.ts) targets MarkdownV2:
- mdast → MarkdownV2 — escapes the 18 reserved characters
(
_*[]()~\>#+-=|{}.!) inside text nodes, preserves emphasis (bold,italic,underline,strike,||spoiler||), inline code (single backtick), code fences, blockquotes (>), links vialabel, and mentions vianame`. - MarkdownV2 → mdast — round-trips the same constructs. Custom emoji
arrive as separate
entities[].type: "custom_emoji"; the converter embeds them inline with their fallback text. - Tables flatten to fixed-width code blocks (no native table support).
renderPostable builds the text body for outbound messages. When the
target chat type is channel and the bot is the channel owner, the
adapter falls back to HTML mode for richer rendering — a quirk
worth knowing when debugging.
Cards (text + inline keyboard)
Telegram has no card primitive — instead, cards are rendered as a
text body with an inline keyboard footer. cardToTelegramMessage
emits:
- Header / section text → MarkdownV2 paragraphs in the message body.
- Image →
photoattachment (usessendPhotoinstead ofsendMessage). - Fields → bulleted MarkdownV2 lines.
- Buttons →
reply_markup.inline_keyboard[][]rows. Each button has eithercallback_data(callback id) orurl(<LinkButton>). - LinkButton →
urlbutton. - Select → emitted as a row of buttons because Telegram has no native select widget. Use a modal-style flow for many options.
Tables flatten as in markdown.
Streaming
Telegram supports per-message edits cleanly, so streaming maps onto
the post-then-edit pattern. The adapter posts a placeholder, then
edits with editMessageText as deltas arrive. Min edit interval
defaults to 800 ms to stay under the per-bot rate limit.
File uploads
postMessage accepts FileUpload objects ({ filename, content,
contentType }). The adapter picks the appropriate Bot API method:
image/*→sendPhoto.video/*→sendVideo.audio/*→sendAudioorsendVoicedepending on the codec.image/gif→sendAnimation.- Everything else →
sendDocument.
A single message can carry one attachment plus a caption. Multiple
files or compatible attachments are sent with sendMediaGroup.
Telegram quirks worth remembering
- MarkdownV2 escapes are mandatory. Forgetting to escape a
.in user-provided text 400s the request. The converter handles this, but raw API users must too. - Privacy mode — group bots only see messages addressed to them
unless privacy mode is disabled via
@BotFather. The adapter surfaces this gotcha ingetMe()output. - Reaction set is restricted to a small list of emoji per chat unless the chat is a paid premium channel. The Bot API rejects unsupported reactions with 400.
- Forum topics behave like channels. The
message_thread_idneeds to be passed back on every reply; otherwise the bot posts at the chat root. message_idis per-chat, not global. Persist it together with thechat_id.secret_tokenis the only line of defence for HTTP webhooks — do not skip configuring it in production.
Testing approach
- Unit tests colocated with each module (
*.test.ts). The MarkdownV2 escape tests are extensive — extend them whenever you touch the converter. - Replay tests in
packages/integration-tests/src/replay-telegram-*.test.tsconsume recordedUpdatepayloads. - Bot API client is mocked at the
fetchboundary. Never hitapi.telegram.orgfrom unit tests.
When you add support for a new update type, capture a fresh fixture
in sample-messages.md.
Coding conventions
- Use named exports throughout. No default exports.
- The Bot API typings live in
types.ts— extend them in place rather than pulling a third-party dependency. - Errors map to
@chat-adapter/shared(AuthenticationError,AdapterRateLimitError,NetworkError,ValidationError). - Top-level regex literals only — Telegram has many of them
(
MARKDOWN_V2_ESCAPES,MENTION_REGEX, etc.). - Always escape user-provided text before concatenation. Format
helpers (
escapeMarkdownV2) live inmarkdown.ts.
Releases
Behavioural changes need a changeset (pnpm changeset, choose
@chat-adapter/telegram plus chat if a public type changed). Sample
fixtures and AGENTS.md edits don't.
Where to look next
- User-facing docs:
apps/docs/content/adapters/official/telegram.mdx - README:
packages/adapter-telegram/README.md - Shared error/utility helpers:
packages/adapter-shared/src/index.ts - Core Adapter contract:
packages/chat/src/adapter.ts - Sample webhook payloads:
packages/adapter-telegram/sample-messages.md
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

