@chat-adapter/telegram

中文文档
4.44.0发布于 2026/11/02MITTypeScriptES Module构建来源已验证近 30 天下载 153.1万

Telegram adapter for Chat SDK — Bot API webhooks, inline keyboards, reactions, and streaming

原始使用文档
文档目录24 节
  1. Installation
  2. Scaffold with the CLI
  3. Quick start
  4. Configuration
  5. Authentication
  6. Option A — Vercel Connect
  7. Option B — Bot token
  8. Webhook route
  9. Business mode (Connected Business Bots)
  10. Polling (local development)
  11. Auto mode
  12. Inbound attachments
  13. Environment variables
  14. Features
  15. Messaging
  16. Rich content
  17. Conversations
  18. Message history
  19. Streaming
  20. Markdown formatting
  21. Long messages
  22. Notes
  23. AI Coding Agents
  24. License

Telegram adapter for Chat SDK

@chat-adapter/telegram

npm package: @chat-adapter/telegram

Agent Stack MIT License

Telegram adapter for Chat SDK. Configure for bot webhooks and messaging.

Documentation: chat-sdk.dev/adapters/official/telegram · Guides: vercel.com/kb/chat-sdk

Installation

pnpm add @chat-adapter/telegram

Scaffold with the CLI

To scaffold a new Telegram bot with this adapter preselected:

npx create-chat-sdk@latest my-bot --adapter telegram memory

Visit the adapters directory to see other available official and vendor-official adapters.

Quick start

For managed credentials, see Vercel Connect.

The adapter auto-detects TELEGRAM_BOT_TOKEN, TELEGRAM_WEBHOOK_SECRET_TOKEN, TELEGRAM_ALLOW_UNVERIFIED_WEBHOOKS, TELEGRAM_BOT_USERNAME, TELEGRAM_MENTION_ON_REPLY, and TELEGRAM_API_BASE_URL from environment variables:

import { Chat } from "chat";
import { createTelegramAdapter } from "@chat-adapter/telegram";

const bot = new Chat({
  userName: "mybot",
  adapters: {
    telegram: createTelegramAdapter(),
  },
});

bot.onNewMention(async (thread, message) => {
  await thread.post(`You said: ${message.text}`);
});

Configuration

Most options are auto-detected from environment variables when not provided. nativeStreaming, persistThreadHistory, streamingEditIntervalMs, and longMessages are config only and have no environment variables.

OptionRequiredDescription
allowUnverifiedWebhooksNoAccept webhook requests without secret-token verification. Auto-detected from TELEGRAM_ALLOW_UNVERIFIED_WEBHOOKS=true. Use only for local development or behind a trusted verifying proxy
allowedUserIdsNoTelegram user IDs allowed to trigger the adapter. Auto-detected from TELEGRAM_ALLOWED_USER_IDS (comma-separated). All users are allowed when omitted or empty
botTokenNo*Telegram bot token. Auto-detected from TELEGRAM_BOT_TOKEN
secretTokenWebhook*Webhook secret token. Auto-detected from TELEGRAM_WEBHOOK_SECRET_TOKEN
modeNoAdapter mode: auto (default), webhook, or polling
longPollingNoOptional long polling config for getUpdates (timeout, limit, allowedUpdates, deleteWebhook, dropPendingUpdates, retryDelayMs)
businessModeNoEnable Telegram Business mode (business_connection, business_message, edited_business_message). Defaults to false
userNameNoBot username used for mention detection. Auto-detected from TELEGRAM_BOT_USERNAME or getMe
mentionOnReplyNoTreat a reply to one of the bot's own messages as a mention, so it routes to onNewMention. Defaults to false. Auto-detected from TELEGRAM_MENTION_ON_REPLY=true. Implicit forum-topic replies and the bot's own messages never count
nativeStreamingNoStream with Telegram's native draft previews in private chats. Defaults to false, which uses post-and-edit in every chat type
persistThreadHistoryNoSave incoming messages and the bot's own posts in the Chat state adapter so thread.messages and channel.messages return earlier turns. Defaults to true. Telegram has no Bot API for reading chat history, so with false handlers see only messages cached in the current process. Turn it off when your app keeps its own transcript
streamingEditIntervalMsNoMinimum interval between edits on the post-and-edit streaming path. Defaults to 1100 in private chats and 3100 in other chats, and acts as a floor for the Chat-level streamingUpdateIntervalMs
longMessagesNoHow text posts longer than Telegram's message limit are sent: truncate (default) cuts them with an ellipsis, split sends the full text as consecutive messages. See Long messages
apiUrlNoTelegram API base URL. Auto-detected from TELEGRAM_API_BASE_URL. Use apiUrl for cross-adapter consistency; the legacy apiBaseUrl alias is still accepted
loggerNoLogger instance (defaults to ConsoleLogger("info"))

*botToken is always required. Webhook mode also requires secretToken unless allowUnverifiedWebhooks is explicitly enabled. Polling mode does not require webhook verification.

Authentication

Use Vercel Connect to manage the outbound bot token, or provide the token directly. Both options use Telegram's native webhook verification; polling does not require a webhook secret.

Option A — Vercel Connect

Use connectTelegramAdapter to resolve the outbound bot token from Vercel Connect:

import { createTelegramAdapter } from "@chat-adapter/telegram";
import { connectTelegramAdapter } from "@vercel/connect/chat";

const telegram = createTelegramAdapter({
  ...connectTelegramAdapter("telegram/acme-telegram"),
  secretToken: process.env.TELEGRAM_WEBHOOK_SECRET_TOKEN,
});

Connect does not forward Telegram webhooks. Keep TELEGRAM_WEBHOOK_SECRET_TOKEN when using webhook mode, or use polling mode without an inbound webhook. TELEGRAM_BOT_TOKEN is not needed when using the Connect helper. The adapter derives webhook deduplication scope from Telegram's stable bot identity, so token rotation does not split update claims. If bot identity lookup fails at startup, the next accepted webhook retries it.

Option B — Bot token

Create a bot via BotFather and provide its token directly to the adapter:

  1. Send /newbot and follow the prompts.
  2. Copy the token to TELEGRAM_BOT_TOKEN.
  3. Optionally pick a username and copy it to TELEGRAM_BOT_USERNAME.

Webhook route

import { bot } from "@/lib/bot";


export async function POST(request: Request): Promise<Response> {
  return bot.webhooks.telegram(request);
}

Configure this URL as your bot webhook in BotFather / Telegram API:

curl -X POST "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/setWebhook" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-domain.com/api/webhooks/telegram",
    "secret_token": "your-secret-token"
  }'

Business mode (Connected Business Bots)

Enable Telegram Business mode when your bot manages customer conversations on behalf of a connected business account:

const telegram = createTelegramAdapter({
  businessMode: true,
});

With businessMode: true, the adapter:

  • Handles business_connection, business_message, and edited_business_message updates
  • Skips messages typed by the business owner, messages the bot itself sent on the account's behalf (sender_business_bot), and connections without can_reply
  • Encodes business threads as telegram:biz:{connectionId}:{chatId}. Each business conversation is its own channel, kept apart from any direct chat the same customer has with the bot
  • Passes business_connection_id on outbound sendMessage, edits, typing, file uploads, and on threads created from inline-keyboard callbacks
  • Routes /commands from business chats through onSlashCommand, the same as regular chats
  • Deletes messages with deleteBusinessMessages, which needs the can_delete_sent_messages right on the connection
  • Stores connection state in the Chat SDK state adapter, so a revoked or disabled connection is honoured by every running instance

Reactions are not available on business threads. The Bot API has no business variant of setMessageReaction, so addReaction and removeReaction throw a NotImplementedError there.

When polling, the adapter always sends an explicit allowed_updates list in Business mode: the default update types plus the business ones, or your longPolling.allowedUpdates merged with the business ones. Telegram otherwise reuses whatever list an earlier call set, which can silently exclude business updates. When registering a webhook yourself, include the business update types:

[
  "message",
  "business_connection",
  "business_message",
  "edited_business_message"
]

Business thread IDs start with telegram:biz, so state adapters that shard by the first two ID segments (such as Cloudflare Agents) place every business conversation in one shard. Override the sharder with a key that includes the connection ID if that matters for your deployment.

Defaults to false for backward compatibility.

Polling (local development)

When developing locally you typically can't expose a public URL for Telegram to deliver webhooks to. Polling mode uses getUpdates to fetch messages directly from Telegram instead — no public endpoint needed.

The longPolling option is entirely optional. Sensible defaults are applied when omitted.

import { Chat } from "chat";
import { createTelegramAdapter } from "@chat-adapter/telegram";
import { createMemoryState } from "@chat-adapter/state-memory";

const telegram = createTelegramAdapter({
  mode: "polling",
  // Optional — fine-tune polling behavior:
  // longPolling: { timeout: 30, dropPendingUpdates: false },
});

const bot = new Chat({
  userName: "mybot",
  adapters: { telegram },
  state: createMemoryState(),
});

// Optional manual lifecycle control:
// await telegram.resetWebhook();
// await telegram.startPolling();
// await telegram.stopPolling();

Auto mode

With mode: "auto" (the default), the adapter picks the right strategy for you. When deployed to a serverless environment like Vercel it uses webhooks; everywhere else (e.g. local dev) it falls back to polling automatically.

import { Chat } from "chat";
import { createTelegramAdapter } from "@chat-adapter/telegram";
import { createMemoryState } from "@chat-adapter/state-memory";

const telegram = createTelegramAdapter({
  mode: "auto", // default
});

export const bot = new Chat({
  userName: "mybot",
  adapters: { telegram },
  state: createMemoryState(),
});

// Call initialize() so polling can start in long-running local processes:
void bot.initialize();

console.log(telegram.runtimeMode); // "webhook" | "polling"

Inbound attachments

Incoming file attachments expose a lazy fetchData() served from the configured Bot API host. Downloads are limited to 25 MB and time out after 30 seconds. They use the Web Fetch API, so file downloads keep working in runtimes like Cloudflare Workers.

Environment variables

TELEGRAM_ALLOWED_USER_IDS=123456789,987654321
TELEGRAM_BOT_TOKEN=123456:ABCDEF...
TELEGRAM_WEBHOOK_SECRET_TOKEN=your-webhook-secret
TELEGRAM_BOT_USERNAME=mybot
# Optional (treat replies to the bot as mentions)
TELEGRAM_MENTION_ON_REPLY=true
# Optional (self-hosted API gateway)
TELEGRAM_API_BASE_URL=https://api.telegram.org

Set TELEGRAM_ALLOW_UNVERIFIED_WEBHOOKS=true only for local development or when a trusted upstream verifies every request before it reaches the adapter.

Features

Messaging

FeatureSupported
Post messageYes
Edit messageYes
Delete messageYes
File uploadsYes (sendDocument, sendMediaGroup)
Attachment uploadsYes (sendPhoto, sendAudio, sendVideo, sendDocument, sendMediaGroup)
StreamingPost/edit + opt-in private chat rich drafts

Rich content

FeatureSupported
Card formatMarkdownV2 + inline keyboard buttons
ButtonsInline keyboard callbacks
Link buttonsInline keyboard URLs
Select menusNo
TablesNative for markdown and AST messages, ASCII in cards
FieldsYes
Images in cardsNo
ModalsNo

Conversations

FeatureSupported
Slash commandsNo
MentionsYes
Add reactionsYes
Remove reactionsYes
Typing indicatorYes
DMsYes
Ephemeral messagesNo

Message history

FeatureSupported
Fetch messagesCached
Fetch single messageCached
Fetch thread infoYes
Fetch channel messagesCached
List threadsNo
Fetch channel infoYes
Post channel messageYes

Streaming

Streams use post-and-edit by default for consistent behavior across Telegram clients. To opt into native draft previews in private chats:

const telegram = createTelegramAdapter({ nativeStreaming: true });

Telegram clients should dismiss a draft preview when the final message arrives, but draft rendering varies between clients. Keep the default when your bot must work consistently across Telegram clients.

Telegram recommends at most one message per second in a single chat and limits groups to 20 messages per minute. Sends and edits share flood control, so the post-and-edit path defaults to 1100ms between operations in private chats and 3100ms in other chats. This is a floor: a lower streamingUpdateIntervalMs on your Chat instance does not push the adapter past it. Override it with streamingEditIntervalMs:

const telegram = createTelegramAdapter({ streamingEditIntervalMs: 4000 });

If Telegram rate limits the final edit, the adapter waits and retries when the requested delay is 5 seconds or less. Longer delays and failed retries reject the post so it never reports text that Telegram did not receive.

Markdown formatting

On Telegram Bot API 10.1 and newer, explicit { markdown } and { ast } messages use rich messages, including native headings, lists, tables, task lists, formulas, details, and separate media blocks supported by the Bot API.

Plain strings, raw messages, cards, and media captions retain their existing lightweight message paths. Cards and captions use Telegram's MarkdownV2 parse mode with context-aware escaping. If an older or custom Bot API server does not support rich message methods, the adapter automatically falls back to the existing MarkdownV2 path.

Behavior change in 4.27.0: previous versions used Telegram's legacy Markdown parse mode, which used different syntax (*bold* instead of **bold**) and silently rejected any text containing unescaped ., !, (, ), -, _. If you were emitting raw legacy-Markdown strings or hand-escaping characters yourself, drop the manual escaping. The renderer does it for you. Pass { raw: "..." } only if you need to ship a fully pre-escaped MarkdownV2 string.

Long messages

Telegram limits a message to 4,096 characters, or 32,768 for rich messages. By default, the adapter truncates longer text posts and ends them with an ellipsis. MarkdownV2 escaping counts toward the limit, so heavily punctuated markdown is cut earlier than its source length suggests.

Set longMessages: "split" to send the full text as consecutive messages, each within the limit:

const telegram = createTelegramAdapter({ longMessages: "split" });

The adapter splits between blocks where possible, then at line breaks or spaces, and reopens formatting in the next message. Split tables repeat their header row when it fits beside a body row. Only the first message replies to the original message, and post() returns the last message. Cards, media captions, edits, and the message edited during post-and-edit streaming still truncate.

The adapter waits about 1 second between messages in private chats and about 3 seconds in groups and channels, so a 40-message group post takes about two minutes. Once the first message is delivered, a rate-limited message is sent again after Telegram's retry_after period, up to three attempts. If a wait would be longer than 30 seconds, all three attempts are rate limited, or the waits for one post would add up to more than 60 seconds, post() throws an AdapterRateLimitError and the messages already sent stay in the chat. A rate limit on the first message throws right away, before anything is sent.

Notes

  • Accepted webhook updates with an integer update_id are deduplicated for 24 hours through the configured state adapter. Use shared durable state across serverless instances. If state is unavailable, the adapter returns 503 so Telegram retries without dispatching.
  • Webhook mode requires secretToken unless allowUnverifiedWebhooks is explicitly enabled. Polling mode does not require webhook verification.
  • Telegram does not expose full historical message APIs to bots. fetchMessages / fetchChannelMessages return adapter-cached messages from the current process.
  • listThreads is not available for Telegram chats.
  • Polling and webhooks are mutually exclusive in Telegram.
  • mode: "polling" deletes webhook by default before calling getUpdates.
  • mode: "auto" checks getWebhookInfo: if a webhook URL exists it uses webhook mode; if it is empty it falls back to polling on non-serverless runtimes without deleting webhook.
  • If getWebhookInfo fails in mode: "auto", the adapter stays in webhook mode (safe fallback).
  • Button and LinkButton in card Actions render as inline keyboard buttons.
  • Telegram callback data is limited to 64 bytes. Keep button id/value payloads short.
  • Incoming attachments preserve Telegram's downloadable file_id and stable file_unique_id as fetchMetadata.fileId and fetchMetadata.fileUniqueId. Photo attachments use the image/jpeg MIME type.
  • files upload as Telegram documents. Multiple files are sent as Telegram media groups. attachments preserve image, audio, video, or file media type and also use media groups when multiple compatible attachments are posted. Use data or fetchData for private/authenticated files; URL-only attachments must be public URLs Telegram can fetch directly.
  • Other rich card elements (images/select menus/radios) render as fallback text only.

AI Coding Agents

If you use an AI coding agent such as OpenAI Codex, Claude Code, or Cursor, install the Chat SDK skill so it knows the SDK APIs, adapter patterns, and project conventions before writing code.

npx skills add vercel/chat

The skill references bundled documentation in node_modules/chat/docs, plus adapter guides and starter templates in the published package.

You can also install the Vercel Plugin for a broader agent toolkit — it includes the Chat SDK skill alongside specialist agents, agent slash commands, and more:

npx plugins add vercel/vercel-plugin

The plugin is optional; the skill alone is enough to build with Chat SDK.

For agent-readable documentation, see chat-sdk.dev/llms.txt (page index) or chat-sdk.dev/llms-full.txt (full text).

License

MIT

版本与发布记录

@chat-adapter/telegram 共发布 35 个版本,首次发布于 2026/02/27;过去 12 个月发布了 35 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
4.44.0latest2026/11/026 天前
4.43.02026/10/1921 天前
4.42.02026/10/1425 天前
4.41.12026/09/291 个月前
4.41.02026/09/181 个月前
4.40.02026/09/052 个月前

关于 @chat-adapter/telegram 的常见问题

@chat-adapter/telegram 是什么?

Telegram adapter for Chat SDK — Bot API webhooks, inline keyboards, reactions, and streaming

如何安装 @chat-adapter/telegram?

在项目目录运行 npm install @chat-adapter/telegram,或使用 pnpm add / yarn add / bun add。

@chat-adapter/telegram 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@chat-adapter/telegram 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@chat-adapter/telegram 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@chat-adapter/telegram 可以商用吗?

@chat-adapter/telegram 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@chat-adapter/telegram 的下载量有多少?

根据 npm 官方下载统计,@chat-adapter/telegram 在 2026/10/10 – 2026/11/08 这 30 天内被下载 1,530,979 次,日均约 51,033 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@chat-adapter/telegram 还在维护吗?

最新版本 4.44.0 发布于 2026/11/02(6 天前);至今共发布 35 个版本,其中过去 12 个月发布了 35 个;首次发布于 2026/02/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。