跳到主要内容

Telegram

Telegram Channels 让 Mastra Agent 能够接收来自 Telegram 的私信、群组消息和机器人提及。Mastra 负责 Agent 接线和 webhook 路由;Chat SDK Telegram 适配器文档则介绍机器人设置、webhook 注册和轮询行为。

安装适配器
安装适配器的直接链接

从 Chat SDK 安装 Telegram 适配器:

npm install @chat-adapter/telegram

Agent 配置
Agent 配置的直接链接

createTelegramAdapter() 添加到 Agent 的 channels.adapters 对象:

src/mastra/agents/telegram-agent.ts
import { Agent } from '@mastra/core/agent'
import { createTelegramAdapter } from '@chat-adapter/telegram'

export const telegramAgent = new Agent({
id: 'telegram-agent',
name: 'Telegram Agent',
instructions: 'Answer questions and help with tasks in Telegram.',
model: 'openai/gpt-5.6-sol',
channels: {
adapters: {
telegram: createTelegramAdapter(),
},
},
})

在 Mastra 实例上注册该 Agent:

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { telegramAgent } from './agents/telegram-agent'

export const mastra = new Mastra({
agents: { telegramAgent },
})

适配器设置
适配器设置的直接链接

按照 Chat SDK Telegram 适配器文档完成 Telegram 专用设置,包括 BotFather、webhook 注册、secret token 和轮询模式。

适配器从以下环境变量中读取 Telegram 凭据:

.env
TELEGRAM_BOT_TOKEN=your-telegram-bot-token
TELEGRAM_WEBHOOK_SECRET_TOKEN=your-webhook-secret-token
TELEGRAM_BOT_USERNAME=your_bot_username

Webhook URL
Webhook URL的直接链接

Mastra 根据 Agent ID 和适配器键生成 Telegram webhook 路由:

/api/agents/telegram-agent/channels/telegram/webhook

使用公开的 Mastra Server URL 作为基础 URL:

https://your-app.example.com/api/agents/telegram-agent/channels/telegram/webhook

在 Telegram 适配器文档要求填写 webhook URL 的任何位置使用此 URL。Telegram 也支持轮询模式;如果希望在本地开发时使用轮询,请按照 Chat SDK 适配器文档操作。