Skip to main content

TelegramProvider

TelegramProvider connects Mastra agents to Telegram bots through the Bot API. Register it on Mastra.channels to manage bot installations, choose webhook or polling delivery, verify webhook secrets, register commands, and route Telegram conversations to agents.

Use TelegramProvider when you want Mastra to own the bot lifecycle. For the lower-level path where you configure the Telegram adapter and webhook yourself, use createTelegramAdapter on the agent's channels.adapters.

Usage example
Direct link to Usage example

Create a bot with BotFather, set TELEGRAM_BOT_TOKEN, and register the provider with a public base URL for webhook delivery:

src/mastra/index.ts
import { Agent } from '@mastra/core/agent'
import { Mastra } from '@mastra/core/mastra'
import { TelegramProvider } from '@mastra/telegram'

const supportAgent = new Agent({
id: 'support',
name: 'Support agent',
instructions: 'Help users with product questions.',
model: 'openai/gpt-5-mini',
})

const telegram = new TelegramProvider({
baseUrl: 'https://your-app.example.com',
})

export const mastra = new Mastra({
agents: { supportAgent },
channels: { telegram },
})

await telegram.connect('support', {
botToken: process.env.TELEGRAM_BOT_TOKEN,
})

When botToken is omitted, connect() creates a pending installation and returns a BotFather deep link instead of activating the bot immediately.

Constructor parameters
Direct link to Constructor parameters

TelegramProviderConfig combines Telegram lifecycle options, adapter behavior, and a curated subset of ChannelConfig options forwarded to each connected agent. All fields are optional.

baseUrl?:

string
Public HTTPS base URL used to register per-bot webhooks. May be auto-detected from the Mastra server config. Required when the resolved mode is webhook.

storage?:

ChannelsStorage
Storage for bot installations. Defaults to Mastra's channels storage when available, then falls back to in-memory storage for development and tests.

apiBaseUrl?:

string
= 'https://api.telegram.org'
Telegram Bot API origin. Override it for a self-hosted Bot API server or test server.

encryptionKey?:

string
Passphrase used to encrypt bot and webhook secret tokens at rest with AES-256-GCM. Falls back to MASTRA_ENCRYPTION_KEY. Without a key, persistent storage saves the tokens as plaintext.

mode?:

'auto' | 'webhook' | 'polling'
= 'auto'
Update transport. 'auto' uses webhooks when a base URL is available and polling otherwise. Telegram doesn't allow webhooks and long polling for the same bot at the same time.

allowedUpdates?:

string[]
Update types requested from Telegram in webhook mode. Defaults include messages, edited messages, channel posts, callback queries, and message reactions.

longPolling?:

TelegramAdapterConfig['longPolling']
Polling configuration such as timeout, limit, allowed updates, and retry delay. Ignored in webhook mode.

commands?:

TelegramCommand[]
Default commands registered for each connected agent. Defaults to start, help, and settings. Per-agent connect options override this list.

commandScope?:

Record<string, unknown>
Telegram Bot API command scope passed to setMyCommands, such as { type: 'all_private_chats' }.

streaming?:

StreamingConfig
= true
Streams generated text by posting and editing Telegram messages. The adapter handles the Telegram message length limit.

typingStatus?:

boolean
= true
Keeps a Telegram typing indicator active while the agent generates a response.

toolDisplay?:

ChannelAdapterConfig['toolDisplay']
= 'text'
Controls tool-call rendering. Rich Slack-oriented display modes degrade to plain fallback text in Telegram, so the provider defaults to 'text'.

tools?:

ChannelConfig['tools']
= true
Controls whether channel reaction tools are exposed to the agent.

waitUntil?:

WaitUntilFn
Keeps serverless invocations alive while agent streaming continues after the webhook response.

resolveWaitUntil?:

ChannelConfig['resolveWaitUntil']
Resolves a platform waitUntil function from the webhook request's Hono context.

handlers?:

ChannelHandlers
Overrides built-in direct message, mention, or subscribed-message handlers.

inlineMedia?:

ChannelConfig['inlineMedia']
Controls which Telegram media types are sent inline to the model.

state?:

ChannelConfig['state']
State adapter used for event deduplication, locking, and subscriptions.

threadContext?:

ChannelConfig['threadContext']
Controls fetching recent Telegram thread messages when an agent joins a conversation.

chatOptions?:

ChannelConfig['chatOptions']
Additional options passed to the Chat SDK.

resolveResourceId?:

ChannelConfig['resolveResourceId']
Resolves the memory resource ID before a channel thread is created.

cors?:

ChannelAdapterConfig['cors']
CORS configuration for the generated Telegram webhook route.

formatError?:

ChannelAdapterConfig['formatError']
Overrides how errors are rendered in Telegram messages.

logger?:

TelegramAdapterConfig['logger']
Logger passed to the underlying Telegram adapter.

onInstall?:

(installation: TelegramInstallation) => void | Promise<void>
Called after an agent successfully connects a bot and its installation is persisted.

Methods
Direct link to Methods

Installation lifecycle
Direct link to Installation lifecycle

connect(agentId, options)
Direct link to connectagentid-options

Connects an agent to a Telegram bot. The provider validates a BotFather token with getMe, prepares the selected delivery mode and commands, then stores the installation before activating the adapter.

const result = await telegram.connect('support', {
botToken: process.env.TELEGRAM_BOT_TOKEN,
name: 'Support bot',
commands: [
{ command: 'help', description: 'Show support options' },
{ command: 'status', description: 'Check service status' },
],
})

TelegramConnectOptions fields:

botToken?:

string
BotFather token. When provided, the connection completes immediately. When omitted, connect() returns a BotFather deep link and a pending installation ID.

name?:

string
Display name for the bot. Defaults to the bot's Telegram username or first name.

commands?:

TelegramCommand[]
Commands registered for this agent. Overrides the provider's default commands.

Returns: Promise<ChannelConnectResult>

disconnect(agentId)
Direct link to disconnectagentid

Stops the active transport and removes its stored installation. In webhook mode, it also removes the Telegram webhook.

await telegram.disconnect('support')

Returns: Promise<void>

listInstallations()
Direct link to listinstallations

Lists active and pending Telegram installations without exposing bot or webhook secret tokens.

const installations = await telegram.listInstallations()

Returns: Promise<ChannelInstallationInfo[]>

getInstallation(agentId)
Direct link to getinstallationagentid

Returns the full installation for an agent, including sensitive bot and webhook tokens, or null when no installation exists.

const installation = await telegram.getInstallation('support')

Returns: Promise<TelegramInstallation | null>

Configuration and status
Direct link to Configuration and status

configure(credentials)
Direct link to configurecredentials

Updates the Bot API origin or webhook base URL at runtime. Passing null is a no-op because Telegram credentials belong to individual bot installations.

await telegram.configure({
baseUrl: 'https://new-app.example.com',
apiBaseUrl: 'https://api.telegram.org',
})

Returns: Promise<void>

initialize()
Direct link to initialize

Restores active installations from storage and rebuilds their Telegram adapters before reconnecting the registered agents. Mastra calls this during startup.

await telegram.initialize()

Returns: Promise<void>

isConfigured()
Direct link to isconfigured

Returns whether at least one active Telegram installation exists.

const configured = telegram.isConfigured()

getInfo()
Direct link to getinfo

Returns channel discovery metadata for the Editor UI, including connection status and the botToken and name connect-option schema.

const info = telegram.getInfo()

Returns: ChannelPlatformInfo

getAdapter(installationId)
Direct link to getadapterinstallationid

Returns the live TelegramAdapter for an active installation.

const adapter = telegram.getAdapter(installationId)

Returns: TelegramAdapter | undefined

getRoutes()
Direct link to getroutes

Returns the provider's unauthenticated POST /telegram/events/:webhookId route. Mastra registers this route automatically.

const routes = telegram.getRoutes()

Returns: ApiRoute[]

Delivery modes
Direct link to Delivery modes

  • webhook registers a per-bot webhook under /telegram/events/:webhookId and verifies the X-Telegram-Bot-Api-Secret-Token header.
  • polling removes any existing webhook before starting Telegram's getUpdates loop.
  • auto selects webhooks when a public base URL is available and polling otherwise.

In production, use persistent channels storage and set encryptionKey or MASTRA_ENCRYPTION_KEY, because the in-memory fallback doesn't preserve installations across restarts.