Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: support telegram bot access (#12671)

Rdmclin21be9c000ece0
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index 9cf1813acda..3e50eaf2db0 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -10,6 +10,8 @@
"integration.copied": "Copied to clipboard",
"integration.copy": "Copy",
"integration.deleteConfirm": "Are you sure you want to remove this integration?",
+ "integration.devWebhookProxyUrl": "HTTPS Tunnel URL",
+ "integration.devWebhookProxyUrlHint": "Telegram requires HTTPS for webhooks. Paste your tunnel URL (e.g. from cloudflared or ngrok) to forward webhook requests to your local dev server.",
"integration.disabled": "Disabled",
"integration.discord.description": "Connect this assistant to Discord server for channel chat and direct messages.",
"integration.documentation": "Documentation",
@@ -26,6 +28,9 @@
"integration.saveFailed": "Failed to save configuration",
"integration.saveFirstWarning": "Please save configuration first",
"integration.saved": "Configuration saved successfully",
+ "integration.secretToken": "Webhook Secret Token",
+ "integration.secretTokenHint": "Optional. Used to verify webhook requests from Telegram.",
+ "integration.secretTokenPlaceholder": "Optional secret for webhook verification",
"integration.testConnection": "Test Connection",
"integration.testFailed": "Connection test failed",
"integration.testSuccess": "Connection test passed",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index 440cd8f3bc9..a826cbed8c3 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -10,6 +10,8 @@
"integration.copied": "已复制到剪贴板",
"integration.copy": "复制",
"integration.deleteConfirm": "确定要移除此集成吗?",
+ "integration.devWebhookProxyUrl": "HTTPS 隧道地址",
+ "integration.devWebhookProxyUrlHint": "Telegram Webhook 需要 HTTPS。请粘贴隧道地址(如 cloudflared 或 ngrok 生成的 URL),将 Webhook 请求转发到本地开发服务器。",
"integration.disabled": "已禁用",
"integration.discord.description": "将助手连接到 Discord 服务器,支持频道聊天和私信。",
"integration.documentation": "文档",
@@ -26,6 +28,9 @@
"integration.saveFailed": "保存配置失败",
"integration.saveFirstWarning": "请先保存配置",
"integration.saved": "配置保存成功",
+ "integration.secretToken": "Webhook 密钥",
+ "integration.secretTokenHint": "可选。用于验证来自 Telegram 的 Webhook 请求。",
+ "integration.secretTokenPlaceholder": "可选的 Webhook 验证密钥",
"integration.testConnection": "测试连接",
"integration.testFailed": "连接测试失败",
"integration.testSuccess": "连接测试通过",
diff --git a/package.json b/package.json
index c051e237172..15298c07470 100644
--- a/package.json
+++ b/package.json
@@ -170,6 +170,7 @@
"@cfworker/json-schema": "^4.1.1",
"@chat-adapter/discord": "^4.14.0",
"@chat-adapter/state-ioredis": "^4.14.0",
+ "@chat-adapter/telegram": "^4.15.0",
"@codesandbox/sandpack-react": "^2.20.0",
"@discordjs/rest": "^2.6.0",
"@dnd-kit/core": "^6.3.1",
diff --git a/src/app/(backend)/api/agent/webhooks/[platform]/[appId]/route.ts b/src/app/(backend)/api/agent/webhooks/[platform]/[appId]/route.ts
new file mode 100644
index 00000000000..ed394dd1e28
--- /dev/null
+++ b/src/app/(backend)/api/agent/webhooks/[platform]/[appId]/route.ts
@@ -0,0 +1,27 @@
+import debug from 'debug';
+
+import { getBotMessageRouter } from '@/server/services/bot';
+
+const log = debug('lobe-server:bot:webhook-route');
+
+/**
+ * Bot-specific webhook endpoint.
+ *
+ * Telegram bots register webhooks as `/api/agent/webhooks/telegram/{appId}`
+ * so the router can look up the correct Chat SDK bot instance directly
+ * without iterating all registered bots.
+ *
+ * Route: POST /api/agent/webhooks/[platform]/[appId]
+ */
+export const POST = async (
+ req: Request,
+ { params }: { params: Promise<{ appId: string; platform: string }> },
+): Promise<Response> => {
+ const { platform, appId } = await params;
+
+ log('Received webhook: platform=%s, appId=%s, url=%s', platform, appId, req.url);
+
+ const router = getBotMessageRouter();
+ const handler = router.getWebhookHandler(platform, appId);
+ return handler(req);
+};
diff --git a/src/app/(backend)/api/agent/webhooks/bot-callback/route.ts b/src/app/(backend)/api/agent/webhooks/bot-callback/route.ts
index 680ae34acd8..8062c960205 100644
--- a/src/app/(backend)/api/agent/webhooks/bot-callback/route.ts
+++ b/src/app/(backend)/api/agent/webhooks/bot-callback/route.ts
@@ -13,10 +13,13 @@ import {
renderStepProgress,
splitMessage,
} from '@/server/services/bot/replyTemplate';
+import { TelegramRestApi } from '@/server/services/bot/telegramRestApi';
import { SystemAgentService } from '@/server/services/systemAgent';
const log = debug('api-route:agent:bot-callback');
+// --------------- Platform-specific helpers ---------------
+
/**
* Parse a Chat SDK platformThreadId (e.g. "discord:guildId:channelId[:threadId]")
* and return the actual Discord channel ID to send messages to.
@@ -28,12 +31,87 @@ function extractDiscordChannelId(platformThreadId: string): string {
return parts[3] || parts[2];
}
+/**
+ * Parse a Chat SDK platformThreadId (e.g. "telegram:chatId[:messageThreadId]")
+ * and return the Telegram chat ID.
+ */
+function extractTelegramChatId(platformThreadId: string): string {
+ const parts = platformThreadId.split(':');
+ // parts[0]='telegram', parts[1]=chatId
+ return parts[1];
+}
+
+/**
+ * Detect platform from platformThreadId prefix.
+ */
+function detectPlatform(platformThreadId: string): string {
+ return platformThreadId.split(':')[0];
+}
+
+/** Telegram has a 4096 char limit vs Discord's 2000 */
+const TELEGRAM_CHAR_LIMIT = 4000;
+
+// --------------- Platform-agnostic message interface ---------------
+
+interface PlatformMessenger {
+ createMessage: (content: string) => Promise<void>;
+ editMessage: (messageId: string, content: string) => Promise<void>;
+ removeReaction: (messageId: string, emoji: string) => Promise<void>;
+ triggerTyping: () => Promise<void>;
+ updateThreadName?: (name: string) => Promise<void>;
+}
+
+function createDiscordMessenger(
+ discord: DiscordRestApi,
+ channelId: string,
+ platformThreadId: string,
+): PlatformMessenger {
+ return {
+ createMessage: (content) => discord.createMessage(channelId, content).then(() => {}),
+ editMessage: (messageId, content) => discord.editMessage(channelId, messageId, content),
+ removeReaction: (messageId, emoji) => discord.removeOwnReaction(channelId, messageId, emoji),
+ triggerTyping: () => discord.triggerTyping(channelId),
+ updateThreadName: (name) => {
+ const parts = platformThreadId.split(':');
+ const threadId = parts[3];
+ if (threadId) {
+ return discord.updateChannelName(threadId, name);
+ }
+ return Promise.resolve();
+ },
+ };
+}
+
+/**
+ * Parse a Chat SDK composite Telegram message ID ("chatId:messageId") into
+ * the raw numeric message ID that the Telegram Bot API expects.
+ */
+function parseTelegramMessageId(compositeId: string): number {
+ // Format: "chatId:messageId" e.g. "-100123456:42"
+ const colonIdx = compositeId.lastIndexOf(':');
+ if (colonIdx !== -1) {
+ return Number(compositeId.slice(colonIdx + 1));
+ }
+ return Number(compositeId);
+}
+
+function createTelegramMessenger(telegram: TelegramRestApi, chatId: string): PlatformMessenger {
+ return {
+ createMessage: (content) => telegram.sendMessage(chatId, content).then(() => {}),
+ editMessage: (messageId, content) =>
+ telegram.editMessageText(chatId, parseTelegramMessageId(messageId), content),
+ removeReaction: (messageId) =>
+ telegram.removeMessageReaction(chatId, parseTelegramMessageId(messageId)),
+ triggerTyping: () => telegram.sendChatAction(chatId, 'typing'),
+ };
+}
+
/**
* Bot callback endpoint for agent step/completion webhooks.
*
* In queue mode, AgentRuntimeService fires webhooks (via QStash) after each step
* and on completion. This endpoint processes those callbacks and updates
- * Discord messages via REST API.
+ * platform messages via REST API.
*
* Route: POST /api/agent/webhooks/bot-callback
*/
@@ -67,19 +145,27 @@ export async function POST(request: Request): Promise<Response> {
);
}
- log('bot-callback: type=%s, appId=%s, thread=%s', type, applicationId, platformThreadId);
+ const platform = detectPlatform(platformThreadId);
+
+ log(
+ 'bot-callback: type=%s, platform=%s, appId=%s, thread=%s',
+ type,
+ platform,
+ applicationId,
+ platformThreadId,
+ );
try {
// Look up bot token from DB
const serverDB = await getServerDB();
const row = await AgentBotProviderModel.findByPlatformAndAppId(
serverDB,
- 'discord',
+ platform,
applicationId,
);
if (!row?.credentials) {
- log('bot-callback: no bot provider found for appId=%s', applicationId);
+ log('bot-callback: no bot provider found for %s appId=%s', platform, applicationId);
return NextResponse.json({ error: 'Bot provider not found' }, { status: 404 });
}
@@ -94,28 +180,46 @@ export async function POST(request: Request): Promise<Response> {
const botToken = credentials.botToken;
if (!botToken) {
- log('bot-callback: no botToken in credentials for appId=%s', applicationId);
+ log('bot-callback: no botToken in credentials for %s appId=%s', platform, applicationId);
return NextResponse.json({ error: 'Bot token not found' }, { status: 500 });
}
- const discord = new DiscordRestApi(botToken);
- const channelId = extractDiscordChannelId(platformThreadId);
+ // Create platform-specific messenger
+ let messenger: PlatformMessenger;
+ let charLimit: number | undefined;
+
+ switch (platform) {
+ case 'telegram': {
+ const telegram = new TelegramRestApi(botToken);
+ const chatId = extractTelegramChatId(platformThreadId);
+ messenger = createTelegramMessenger(telegram, chatId);
+ charLimit = TELEGRAM_CHAR_LIMIT;
+ break;
+ }
+ case 'discord':
+ default: {
+ const discord = new DiscordRestApi(botToken);
+ const channelId = extractDiscordChannelId(platformThreadId);
+ messenger = createDiscordMessenger(discord, channelId, platformThreadId);
+ break;
+ }
+ }
if (type === 'step') {
- await handleStepCallback(body, discord, channelId, progressMessageId);
+ await handleStepCallback(body, messenger, progressMessageId, platform);
} else if (type === 'completion') {
- await handleCompletionCallback(body, discord, channelId, progressMessageId);
+ await handleCompletionCallback(body, messenger, progressMessageId, platform, charLimit);
// Remove eyes reaction from the original user message
if (userMessageId) {
try {
- await discord.removeOwnReaction(channelId, userMessageId, '👀');
+ await messenger.removeReaction(userMessageId, '👀');
} catch (error) {
log('bot-callback: failed to remove eyes reaction: %O', error);
}
}
- // Fire-and-forget: summarize topic title and update Discord thread name
+ // Fire-and-forget: summarize topic title and update thread name
const { reason, topicId, userId, userPrompt, lastAssistantContent } = body;
if (reason !== 'error' && topicId && userId && userPrompt && lastAssistantContent) {
const topicModel = new TopicModel(serverDB, userId);
@@ -134,12 +238,10 @@ export async function POST(request: Request): Promise<Response> {
await topicModel.update(topicId, { title });
- // Update Discord thread name if there's a thread ID
- const parts = platformThreadId.split(':');
- const threadId = parts[3];
- if (threadId) {
- discord.updateChannelName(threadId, title).catch((error) => {
- log('bot-callback: failed to update Discord thread name: %O', error);
+ // Update thread/channel name if the platform supports it
+ if (messenger.updateThreadName) {
+ messenger.updateThreadName(title).catch((error) => {
+ log('bot-callback: failed to update thread name: %O', error);
});
}
})
@@ -163,9 +265,9 @@ export async function POST(request: Request): Promise<Response> {
async function handleStepCallback(
body: Record<string, any>,
- discord: DiscordRestApi,
- channelId: string,
+ messenger: PlatformMessenger,
progressMessageId: string,
+ platform?: string,
): Promise<void> {
const { shouldContinue } = body;
if (!shouldContinue) return;
@@ -176,6 +278,7 @@ async function handleStepCallback(
executionTimeMs: body.executionTimeMs ?? 0,
lastContent: body.lastLLMContent,
lastToolsCalling: body.lastToolsCalling,
+ platform,
reasoning: body.reasoning,
stepType: body.stepType ?? 'call_llm',
thinking: body.thinking ?? false,
@@ -194,9 +297,9 @@ async function handleStepCallback(
body.stepType === 'call_llm' && !body.toolsCalling?.length && body.content;
try {
- await discord.editMessage(channelId, progressMessageId, progressText);
+ await messenger.editMessage(progressMessageId, progressText);
if (!isLlmFinalResponse) {
- await discord.triggerTyping(channelId);
+ await messenger.triggerTyping();
}
} catch (error) {
log('handleStepCallback: failed to edit progress message: %O', error);
@@ -205,16 +308,17 @@ async function handleStepCallback(
async function handleCompletionCallback(
body: Record<string, any>,
- discord: DiscordRestApi,
- channelId: string,
+ messenger: PlatformMessenger,
progressMessageId: string,
+ platform?: string,
+ charLimit?: number,
): Promise<void> {
const { reason, lastAssistantContent, errorMessage } = body;
if (reason === 'error') {
const errorText = renderError(errorMessage || 'Agent execution failed');
try {
- await discord.editMessage(channelId, progressMessageId, errorText);
+ await messenger.editMessage(progressMessageId, errorText);
} catch (error) {
log('handleCompletionCallback: failed to edit error message: %O', error);
}
@@ -229,19 +333,20 @@ async function handleCompletionCallback(
const finalText = renderFinalReply(lastAssistantContent, {
elapsedMs: body.duration,
llmCalls: body.llmCalls ?? 0,
+ platform,
toolCalls: body.toolCalls ?? 0,
totalCost: body.cost ?? 0,
totalTokens: body.totalTokens ?? 0,
});
- const chunks = splitMessage(finalText);
+ const chunks = splitMessage(finalText, charLimit);
try {
- await discord.editMessage(channelId, progressMessageId, chunks[0]);
+ await messenger.editMessage(progressMessageId, chunks[0]);
// Post overflow chunks as follow-up messages
for (let i = 1; i < chunks.length; i++) {
- await discord.createMessage(channelId, chunks[i]);
+ await messenger.createMessage(chunks[i]);
}
} catch (error) {
log('handleCompletionCallback: failed to edit/post final message: %O', error);
diff --git a/src/locales/default/agent.ts b/src/locales/default/agent.ts
index b55685f80ce..69a3f591805 100644
--- a/src/locales/default/agent.ts
+++ b/src/locales/default/agent.ts
@@ -25,6 +25,9 @@ export default {
'integration.removed': 'Integration removed',
'integration.removeFailed': 'Failed to remove integration',
'integration.save': 'Save Configuration',
+ 'integration.secretToken': 'Webhook Secret Token',
+ 'integration.secretTokenHint': 'Optional. Used to verify webhook requests from Telegram.',
+ 'integration.secretTokenPlaceholder': 'Optional secret for webhook verification',
'integration.saveFailed': 'Failed to save configuration',
'integration.saveFirstWarning': 'Please save configuration first',
'integration.saved': 'Configuration saved successfully',
@@ -33,4 +36,7 @@ export default {
'integration.testSuccess': 'Connection test passed',
'integration.updateFailed': 'Failed to update status',
'integration.validationError': 'Please fill in Application ID and Token',
+ 'integration.devWebhookProxyUrl': 'HTTPS Tunnel URL',
+ 'integration.devWebhookProxyUrlHint':
+ 'Telegram requires HTTPS for webhooks. Paste your tunnel URL (e.g. from cloudflared or ngrok) to forward webhook requests to your local dev server.',
} as const;
diff --git a/src/routes/(main)/agent/integration/PlatformDetail/Body.tsx b/src/routes/(main)/agent/integration/PlatformDetail/Body.tsx
index 6debbe6021f..71f0ace516e 100644
--- a/src/routes/(main)/agent/integration/PlatformDetail/Body.tsx
+++ b/src/routes/(main)/agent/integration/PlatformDetail/Body.tsx
@@ -148,17 +148,19 @@ const Body = memo<BodyProps>(
<div className={styles.section}>
<div className={styles.sectionTitle}>{t('integration.connectionConfig')}</div>
- <div className={styles.field}>
- <div className={styles.label}>
- <div className={styles.labelLeft}>
- {t('integration.applicationId')}
- {provider.fieldTags.appId && <Tag>{provider.fieldTags.appId}</Tag>}
+ {!provider.autoAppId && (
+ <div className={styles.field}>
+ <div className={styles.label}>
+ <div className={styles.labelLeft}>
+ {t('integration.applicationId')}
+ {provider.fieldTags.appId && <Tag>{provider.fieldTags.appId}</Tag>}
+ </div>
</div>
+ <Form.Item noStyle name="applicationId" rules={[{ required: true }]}>
+ <Input placeholder={t('integration.applicationIdPlaceholder')} />
+ </Form.Item>
</div>
- <Form.Item noStyle name="applicationId" rules={[{ required: true }]}>
- <Input placeholder={t('integration.applicationIdPlaceholder')} />
- </Form.Item>
- </div>
+ )}
<div className={styles.field}>
<div className={styles.label}>
@@ -214,12 +216,65 @@ const Body = memo<BodyProps>(
</Form.Item>
</div>
)}
+
+ {provider.fieldTags.secretToken && (
+ <div className={styles.field}>
+ <div className={styles.label}>
+ <div className={styles.labelLeft}>
+ {t('integration.secretToken')}
+ <Tag>{provider.fieldTags.secretToken}</Tag>
+ </div>
+ </div>
+ <Form.Item noStyle name="secretToken">
+ <Input.Password
+ placeholder={t('integration.secretTokenPlaceholder')}
+ style={{ fontFamily: 'monospace' }}
+ />
+ </Form.Item>
+ <Text
+ type="secondary"
+ style={{
+ alignItems: 'center',
+ display: 'flex',
+ fontSize: 12,
+ gap: 4,
+ }}
+ >
+ <Icon icon={Info} size={'small'} /> {t('integration.secretTokenHint')}
+ </Text>
+ </div>
+ )}
+ {/* Dev-only: HTTPS tunnel URL for Telegram webhook */}
+ {provider.webhookMode === 'auto' && process.env.NODE_ENV === 'development' && (
+ <div className={styles.field}>
+ <div className={styles.label}>
+ <div className={styles.labelLeft}>{t('integration.devWebhookProxyUrl')}</div>
+ </div>
+ <Form.Item noStyle name="webhookProxyUrl">
+ <Input
+ placeholder="https://xxx.trycloudflare.com"
+ style={{ fontFamily: 'monospace' }}
+ />
+ </Form.Item>
+ <Text
+ type="secondary"
+ style={{
+ alignItems: 'center',
+ display: 'flex',
+ fontSize: 12,
+ gap: 4,
+ }}
+ >
+ <Icon icon={Info} size={'small'} /> {t('integration.devWebhookProxyUrlHint')}
+ </Text>
+ </div>
+ )}
</div>
{/* Action Bar */}
<div className={styles.actionBar}>
{hasConfig ? (
- <Button danger icon={<Trash2 size={16} />} type="text" onClick={onDelete}>
+ <Button danger icon={<Trash2 size={16} />} type="primary" onClick={onDelete}>
{t('integration.removeIntegration')}
</Button>
) : (
@@ -264,8 +319,8 @@ const Body = memo<BodyProps>(
/>
)}
- {/* Endpoint URL - only shown after config is saved */}
- {hasConfig && (
+ {/* Endpoint URL - platform-specific rendering */}
+ {hasConfig && provider.webhookMode !== 'auto' && (
<div className={styles.field}>
<div className={styles.label}>
<div className={styles.labelLeft}>
diff --git a/src/routes/(main)/agent/integration/PlatformDetail/Header.tsx b/src/routes/(main)/agent/integration/PlatformDetail/Header.tsx
index 7c8492a918b..59facca5a17 100644
--- a/src/routes/(main)/agent/integration/PlatformDetail/Header.tsx
+++ b/src/routes/(main)/agent/integration/PlatformDetail/Header.tsx
@@ -71,7 +71,7 @@ const Header = memo<HeaderProps>(({ provider, currentConfig, onToggleEnable }) =
<Icon fill={'white'} icon={ProviderIcon} size={'large'} />
</div>
<div>
- <Flexbox align="center">
+ <Flexbox align="flex-start">
<Title level={5} style={{ margin: 0 }}>
{provider.name}
</Title>
diff --git a/src/routes/(main)/agent/integration/PlatformDetail/index.tsx b/src/routes/(main)/agent/integration/PlatformDetail/index.tsx
index e7202143eec..67fef12e995 100644
--- a/src/routes/(main)/agent/integration/PlatformDetail/index.tsx
+++ b/src/routes/(main)/agent/integration/PlatformDetail/index.tsx
@@ -36,6 +36,8 @@ export interface IntegrationFormValues {
applicationId: string;
botToken: string;
publicKey: string;
+ secretToken?: string;
+ webhookProxyUrl?: string;
}
export interface TestResult {
@@ -75,6 +77,8 @@ const PlatformDetail = memo<PlatformDetailProps>(({ provider, agentId, currentCo
applicationId: currentConfig.applicationId || '',
botToken: currentConfig.credentials?.botToken || '',
publicKey: currentConfig.credentials?.publicKey || '',
+ secretToken: currentConfig.credentials?.secretToken || '',
+ webhookProxyUrl: currentConfig.credentials?.webhookProxyUrl || '',
});
}
}, [currentConfig, form]);
@@ -86,20 +90,37 @@ const PlatformDetail = memo<PlatformDetailProps>(({ provider, agentId, currentCo
setSaving(true);
setSaveResult(undefined);
- const credentials = {
- botToken: values.botToken,
- publicKey: values.publicKey || 'default',
- };
+ // Auto-derive applicationId from bot token for Telegram
+ let applicationId = values.applicationId;
+ if (provider.autoAppId && values.botToken) {
+ const colonIdx = values.botToken.indexOf(':');
+ if (colonIdx !== -1) {
+ applicationId = values.botToken.slice(0, colonIdx);
+ form.setFieldValue('applicationId', applicationId);
+ }
+ }
+
+ // Build platform-specific credentials
+ const credentials: Record<string, string> = { botToken: values.botToken };
+ if (provider.fieldTags.publicKey) {
+ credentials.publicKey = values.publicKey || 'default';
+ }
+ if (provider.fieldTags.secretToken && values.secretToken) {
+ credentials.secretToken = values.secretToken;
+ }
+ if (provider.webhookMode === 'auto' && values.webhookProxyUrl) {
+ credentials.webhookProxyUrl = values.webhookProxyUrl;
+ }
if (currentConfig) {
await updateBotProvider(currentConfig.id, agentId, {
- applicationId: values.applicationId,
+ applicationId,
credentials,
});
} else {
await createBotProvider({
agentId,
- applicationId: values.applicationId,
+ applicationId,
credentials,
platform: provider.id,
});
@@ -113,7 +134,16 @@ const PlatformDetail = memo<PlatformDetailProps>(({ provider, agentId, currentCo
} finally {
setSaving(false);
}
- }, [agentId, provider.id, form, currentConfig, createBotProvider, updateBotProvider]);
+ }, [
+ agentId,
+ provider.id,
+ provider.autoAppId,
+ provider.fieldTags,
+ form,
+ currentConfig,
+ createBotProvider,
+ updateBotProvider,
+ ]);
const handleDelete = useCallback(async () => {
if (!currentConfig) return;
diff --git a/src/routes/(main)/agent/integration/const.ts b/src/routes/(main)/agent/integration/const.ts
index ab866105883..cab6a9a07fa 100644
--- a/src/routes/(main)/agent/integration/const.ts
+++ b/src/routes/(main)/agent/integration/const.ts
@@ -1,20 +1,26 @@
-import { SiDiscord } from '@icons-pack/react-simple-icons';
+import { SiDiscord, SiTelegram } from '@icons-pack/react-simple-icons';
import type { LucideIcon } from 'lucide-react';
import type { FC } from 'react';
export interface IntegrationProvider {
+ /** Whether applicationId can be auto-derived from the bot token */
+ autoAppId?: boolean;
color: string;
description: string;
docsLink: string;
fieldTags: {
appId: string;
publicKey?: string;
+ secretToken?: string;
token: string;
- webhook: string;
+ webhook?: string;
};
icon: FC<any> | LucideIcon;
id: string;
name: string;
+ /** 'manual' = user must copy endpoint URL to platform portal (Discord);
+ * 'auto' = webhook is set automatically via API (Telegram) */
+ webhookMode?: 'auto' | 'manual';
}
export const INTEGRATION_PROVIDERS: IntegrationProvider[] = [
@@ -32,4 +38,19 @@ export const INTEGRATION_PROVIDERS: IntegrationProvider[] = [
id: 'discord',
name: 'Discord',
},
+ {
+ autoAppId: true,
+ color: '#26A5E4',
+ description: 'Connect this assistant to Telegram for private and group chats.',
+ docsLink: 'https://core.telegram.org/bots#how-do-i-create-a-bot',
+ fieldTags: {
+ appId: 'Bot User ID',
+ secretToken: 'Webhook Secret',
+ token: 'Bot Token',
+ },
+ icon: SiTelegram,
+ id: 'telegram',
+ name: 'Telegram',
+ webhookMode: 'auto',
+ },
];
diff --git a/src/server/services/bot/AgentBridgeService.ts b/src/server/services/bot/AgentBridgeService.ts
index 868402cf01f..aa50acbee3b 100644
--- a/src/server/services/bot/AgentBridgeService.ts
+++ b/src/server/services/bot/AgentBridgeService.ts
@@ -149,6 +149,11 @@ export class AgentBridgeService {
await thread.subscribe();
await thread.startTyping();
+ // Keep typing indicator alive (Telegram's expires after ~5s)
+ const typingInterval = setInterval(() => {
+ thread.startTyping().catch(() => {});
+ }, 4000);
+
// Fetch channel context for Discord context injection
const channelContext = await this.fetchChannelContext(thread);
@@ -174,6 +179,7 @@ export class AgentBridgeService {
const msg = error instanceof Error ? error.message : String(error);
await thread.post(`**Agent Execution Failed**\n\`\`\`\n${msg}\n\`\`\``);
} finally {
+ clearInterval(typingInterval);
// In queue mode, reaction is removed by the bot-callback webhook on completion
if (!queueMode) {
await this.removeReceivedReaction(thread, message);
@@ -217,6 +223,11 @@ export class AgentBridgeService {
);
await thread.startTyping();
+ // Keep typing indicator alive (Telegram's expires after ~5s)
+ const typingInterval = setInterval(() => {
+ thread.startTyping().catch(() => {});
+ }, 4000);
+
try {
// executeWithCallback handles progress message (post + edit at each step)
await this.executeWithCallback(thread, message, {
@@ -227,10 +238,22 @@ export class AgentBridgeService {
trigger: 'bot',
});
} catch (error) {
+ // If the cached topicId references a deleted topic (FK violation),
+ // clear thread state and retry as a fresh mention instead of surfacing the DB error.
+ const errMsg = error instanceof Error ? error.message : String(error);
+ if (errMsg.includes('Failed query') && errMsg.includes('topic_id')) {
+ log(
+ 'handleSubscribedMessage: stale topicId=%s, resetting and retrying as new mention',
+ topicId,
+ );
+ await thread.setState({ ...threadState, topicId: undefined });
+ return this.handleMention(thread, message, { agentId, botContext });
+ }
+
log('handleSubscribedMessage error: %O', error);
- const msg = error instanceof Error ? error.message : String(error);
- await thread.post(`**Agent Execution Failed**. Details:\n\`\`\`\n${msg}\n\`\`\``);
+ await thread.post(`**Agent Execution Failed**. Details:\n\`\`\`\n${errMsg}\n\`\`\``);
} finally {
+ clearInterval(typingInterval);
// In queue mode, reaction is removed by the bot-callback webhook on completion
if (!queueMode) {
await this.removeReceivedReaction(thread, message);
@@ -379,6 +402,8 @@ export class AgentBridgeService {
log('executeWithInMemoryCallbacks: failed to post progress message: %O', error);
}
+ const platform = botContext?.platform;
+
// Track the last LLM content and tool calls for showing during tool execution
let lastLLMContent = '';
let lastToolsCalling:
@@ -431,6 +456,7 @@ export class AgentBridgeService {
elapsedMs: getElapsedMs(),
lastContent: lastLLMContent,
lastToolsCalling,
+ platform,
totalToolCalls,
});
@@ -475,12 +501,15 @@ export class AgentBridgeService {
const finalText = renderFinalReply(lastAssistantContent, {
elapsedMs: getElapsedMs(),
llmCalls: finalState.usage?.llm?.apiCalls ?? 0,
+ platform,
toolCalls: finalState.usage?.tools?.totalCalls ?? 0,
totalCost: finalState.cost?.total ?? 0,
totalTokens: finalState.usage?.llm?.tokens?.total ?? 0,
});
- const chunks = splitMessage(finalText);
+ // Telegram supports 4096 chars vs Discord's 2000
+ const charLimit = platform === 'telegram' ? 4000 : undefined;
+ const chunks = splitMessage(finalText, charLimit);
if (progressMessage) {
try {
diff --git a/src/server/services/bot/BotMessageRouter.ts b/src/server/services/bot/BotMessageRouter.ts
index 0a3d5a82bef..4fb74dadabe 100644
--- a/src/server/services/bot/BotMessageRouter.ts
+++ b/src/server/services/bot/BotMessageRouter.ts
@@ -1,15 +1,18 @@
import { createDiscordAdapter } from '@chat-adapter/discord';
import { createIoRedisState } from '@chat-adapter/state-ioredis';
+import { createTelegramAdapter } from '@chat-adapter/telegram';
import { Chat, ConsoleLogger } from 'chat';
import debug from 'debug';
import { getServerDB } from '@/database/core/db-adaptor';
import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
import type { LobeChatDatabase } from '@/database/type';
+import { appEnv } from '@/envs/app';
import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import { AgentBridgeService } from './AgentBridgeService';
+import { setTelegramWebhook } from './platforms/telegram';
const log = debug('lobe-server:bot:message-router');
@@ -18,10 +21,40 @@ interface ResolvedAgentInfo {
userId: string;
}
-interface DiscordCredentials {
- applicationId: string;
- botToken: string;
- publicKey: string;
+interface StoredCredentials {
+ [key: string]: string;
+}
+
+/**
+ * Adapter factory: creates the correct Chat SDK adapter from platform + credentials.
+ */
+function createAdapterForPlatform(
+ platform: string,
+ credentials: StoredCredentials,
+ applicationId: string,
+): Record<string, any> | null {
+ switch (platform) {
+ case 'discord': {
+ return {
+ discord: createDiscordAdapter({
+ applicationId,
+ botToken: credentials.botToken,
+ publicKey: credentials.publicKey,
+ }),
+ };
+ }
+ case 'telegram': {
+ return {
+ telegram: createTelegramAdapter({
+ botToken: credentials.botToken,
+ secretToken: credentials.secretToken,
+ }),
+ };
+ }
+ default: {
+ return null;
+ }
+ }
}
/**
@@ -29,17 +62,17 @@ interface DiscordCredentials {
* and triggers message processing via AgentBridgeService.
*/
export class BotMessageRouter {
- /** botToken → Chat instance (for webhook routing via x-discord-gateway-token) */
+ /** botToken → Chat instance (for Discord webhook routing via x-discord-gateway-token) */
private botInstancesByToken = new Map<string, Chat<any>>();
- /** applicationId → { agentId, userId } */
- private discordAgentMap = new Map<string, ResolvedAgentInfo>();
+ /** "platform:applicationId" → { agentId, userId } */
+ private agentMap = new Map<string, ResolvedAgentInfo>();
- /** Cached Chat instances keyed by applicationId */
+ /** "platform:applicationId" → Chat instance */
private botInstances = new Map<string, Chat<any>>();
- /** Store credentials for getDiscordBotConfigs() */
- private credentialsByAppId = new Map<string, DiscordCredentials>();
+ /** "platform:applicationId" → credentials */
+ private credentialsByKey = new Map<string, StoredCredentials>();
// ------------------------------------------------------------------
// Public API
@@ -48,16 +81,24 @@ export class BotMessageRouter {
/**
* Get the webhook handler for a given platform.
* Returns a function compatible with Next.js Route Handler: `(req: Request) => Promise<Response>`
+ *
+ * @param appId Optional application ID for direct bot lookup (e.g. Telegram bot-specific endpoints).
*/
- getWebhookHandler(platform: string): (req: Request) => Promise<Response> {
+ getWebhookHandler(platform: string, appId?: string): (req: Request) => Promise<Response> {
return async (req: Request) => {
await this.ensureInitialized();
- if (platform === 'discord') {
- return this.handleDiscordWebhook(req);
+ switch (platform) {
+ case 'discord': {
+ return this.handleDiscordWebhook(req);
+ }
+ case 'telegram': {
+ return this.handleTelegramWebhook(req, appId);
+ }
+ default: {
+ return new Response('No bot configured for this platform', { status: 404 });
+ }
}
-
- return new Response('No bot configured for this platform', { status: 404 });
};
}
@@ -109,7 +150,7 @@ export class BotMessageRouter {
const appId = payload.application_id;
if (appId) {
- const bot = this.botInstances.get(appId);
+ const bot = this.botInstances.get(`discord:${appId}`);
if (bot?.webhooks && 'discord' in bot.webhooks) {
return bot.webhooks.discord(this.cloneRequest(req, bodyBuffer));
}
@@ -118,8 +159,9 @@ export class BotMessageRouter {
// Not valid JSON — fall through
}
- // Fallback: try all registered bots
- for (const bot of this.botInstances.values()) {
+ // Fallback: try all registered Discord bots
+ for (const [key, bot] of this.botInstances) {
+ if (!key.startsWith('discord:')) continue;
if (bot.webhooks && 'discord' in bot.webhooks) {
try {
const resp = await bot.webhooks.discord(this.cloneRequest(req, bodyBuffer));
@@ -133,6 +175,72 @@ export class BotMessageRouter {
return new Response('No bot configured for Discord', { status: 404 });
}
+ // ------------------------------------------------------------------
+ // Telegram webhook routing
+ // ------------------------------------------------------------------
+
+ private async handleTelegramWebhook(req: Request, appId?: string): Promise<Response> {
+ const bodyBuffer = await req.arrayBuffer();
+
+ log(
+ 'handleTelegramWebhook: method=%s, appId=%s, content-length=%d',
+ req.method,
+ appId ?? '(none)',
+ bodyBuffer.byteLength,
+ );
+
+ // Log raw update for debugging
+ try {
+ const bodyText = new TextDecoder().decode(bodyBuffer);
+ const update = JSON.parse(bodyText);
+ const msg = update.message;
+ if (msg) {
+ log(
+ 'Telegram update: chat_type=%s, from=%s (id=%s), text=%s',
+ msg.chat?.type,
+ msg.from?.username || msg.from?.first_name,
+ msg.from?.id,
+ msg.text?.slice(0, 100),
+ );
+ } else {
+ log('Telegram update (non-message): keys=%s', Object.keys(update).join(','));
+ }
+ } catch {
+ // ignore parse errors
+ }
+
+ // Direct lookup by applicationId (bot-specific endpoint: /webhooks/telegram/{appId})
+ if (appId) {
+ const key = `telegram:${appId}`;
+ const bot = this.botInstances.get(key);
+ if (bot?.webhooks && 'telegram' in bot.webhooks) {
+ log('handleTelegramWebhook: direct lookup hit for %s', key);
+ return bot.webhooks.telegram(this.cloneRequest(req, bodyBuffer));
+ }
+ log('handleTelegramWebhook: no bot registered for %s', key);
+ return new Response('No bot configured for Telegram', { status: 404 });
+ }
+
+ // Fallback: iterate all registered Telegram bots (legacy /webhooks/telegram endpoint).
+ // Secret token verification will reject mismatches.
+ for (const [key, bot] of this.botInstances) {
+ if (!key.startsWith('telegram:')) continue;
+ if (bot.webhooks && 'telegram' in bot.webhooks) {
+ try {
+ log('handleTelegramWebhook: trying bot %s', key);
+ const resp = await bot.webhooks.telegram(this.cloneRequest(req, bodyBuffer));
+ log('handleTelegramWebhook: bot %s responded with status=%d', key, resp.status);
+ if (resp.status !== 401) return resp;
+ } catch (error) {
+ log('handleTelegramWebhook: bot %s webhook error: %O', key, error);
+ }
+ }
+ }
+
+ log('handleTelegramWebhook: no matching bot found');
+ return new Response('No bot configured for Telegram', { status: 404 });
+ }
+
private cloneRequest(req: Request, body: ArrayBuffer): Request {
return new Request(req.url, {
body,
@@ -185,49 +293,69 @@ export class BotMessageRouter {
const serverDB = await getServerDB();
const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
- const providers = await AgentBotProviderModel.findEnabledByPlatform(
- serverDB,
- 'discord',
- gateKeeper,
- );
-
- this.lastLoadedAt = Date.now();
-
- log('Found %d Discord bot providers in DB', providers.length);
-
- for (const provider of providers) {
- const { agentId, userId, applicationId, credentials } = provider;
- const { botToken, publicKey } = credentials as any;
-
- if (this.botInstances.has(applicationId)) {
- log('Skipping provider %s: already registered', applicationId);
- continue;
- }
-
- const adapters: Record<string, any> = {
- discord: createDiscordAdapter({
+ // Load all supported platforms
+ for (const platform of ['discord', 'telegram']) {
+ const providers = await AgentBotProviderModel.findEnabledByPlatform(
+ serverDB,
+ platform,
+ gateKeeper,
+ );
+
+ log('Found %d %s bot providers in DB', providers.length, platform);
+
+ for (const provider of providers) {
+ const { agentId, userId, applicationId, credentials } = provider;
+ const key = `${platform}:${applicationId}`;
+
+ if (this.botInstances.has(key)) {
+ log('Skipping provider %s: already registered', key);
+ continue;
+ }
+
+ const adapters = createAdapterForPlatform(platform, credentials, applicationId);
+ if (!adapters) {
+ log('Unsupported platform: %s', platform);
+ continue;
+ }
+
+ const bot = this.createBot(adapters, `agent-${agentId}`);
+ this.registerHandlers(bot, serverDB, {
+ agentId,
applicationId,
- botToken,
- publicKey,
- }),
- };
-
- const bot = this.createBot(adapters, `agent-${agentId}`);
- this.registerHandlers(bot, serverDB, {
- agentId,
- applicationId,
- platform: 'discord',
- userId,
- });
- await bot.initialize();
-
- this.botInstances.set(applicationId, bot);
- this.botInstancesByToken.set(botToken, bot);
- this.discordAgentMap.set(applicationId, { agentId, userId });
- this.credentialsByAppId.set(applicationId, { applicationId, botToken, publicKey });
-
- log('Created Discord bot for agent=%s, appId=%s', agentId, applicationId);
+ platform,
+ userId,
+ });
+ await bot.initialize();
+
+ this.botInstances.set(key, bot);
+ this.agentMap.set(key, { agentId, userId });
+ this.credentialsByKey.set(key, credentials);
+
+ // Discord-specific: also index by botToken for gateway forwarding
+ if (platform === 'discord' && credentials.botToken) {
+ this.botInstancesByToken.set(credentials.botToken, bot);
+ }
+
+ // Telegram: call setWebhook to ensure Telegram-side secret_token
+ // stays in sync with the adapter config (idempotent, safe on every init)
+ if (platform === 'telegram' && credentials.botToken) {
+ const baseUrl = (credentials.webhookProxyUrl || appEnv.APP_URL || '').replace(
+ /\/$/,
+ '',
+ );
+ const webhookUrl = `${baseUrl}/api/agent/webhooks/telegram/${applicationId}`;
+ setTelegramWebhook(credentials.botToken, webhookUrl, credentials.secretToken).catch(
+ (err) => {
+ log('Failed to set Telegram webhook for appId=%s: %O', applicationId, err);
+ },
+ );
+ }
+
+ log('Created %s bot for agent=%s, appId=%s', platform, agentId, applicationId);
+ }
}
+
+ this.lastLoadedAt = Date.now();
} catch (error) {
log('Failed to load agent bots: %O', error);
}
@@ -264,7 +392,13 @@ export class BotMessageRouter {
const bridge = new AgentBridgeService(serverDB, userId);
bot.onNewMention(async (thread, message) => {
- log('onNewMention: agent=%s, author=%s', agentId, message.author.userName);
+ log(
+ 'onNewMention: agent=%s, platform=%s, author=%s, thread=%s',
+ agentId,
+ platform,
+ message.author.userName,
+ thread.id,
+ );
await bridge.handleMention(thread, message, {
agentId,
botContext: { applicationId, platform, platformThreadId: thread.id },
@@ -274,13 +408,42 @@ export class BotMessageRouter {
bot.onSubscribedMessage(async (thread, message) => {
if (message.author.isBot === true) return;
- log('onSubscribedMessage: agent=%s, author=%s', agentId, message.author.userName);
+ log(
+ 'onSubscribedMessage: agent=%s, platform=%s, author=%s, thread=%s',
+ agentId,
+ platform,
+ message.author.userName,
+ thread.id,
+ );
await bridge.handleSubscribedMessage(thread, message, {
agentId,
botContext: { applicationId, platform, platformThreadId: thread.id },
});
});
+
+ // Telegram-only: handle messages in unsubscribed threads that aren't @mentions.
+ // This covers Telegram private chats where users message the bot directly.
+ // Discord relies solely on onNewMention/onSubscribedMessage — registering a
+ // catch-all there would cause unsolicited replies in active channels.
+ if (platform === 'telegram') {
+ bot.onNewMessage(/./, async (thread, message) => {
+ if (message.author.isBot === true) return;
+
+ log(
+ 'onNewMessage (telegram catch-all): agent=%s, author=%s, thread=%s, text=%s',
+ agentId,
+ message.author.userName,
+ thread.id,
+ message.text?.slice(0, 80),
+ );
+
+ await bridge.handleMention(thread, message, {
+ agentId,
+ botContext: { applicationId, platform, platformThreadId: thread.id },
+ });
+ });
+ }
}
}
diff --git a/src/server/services/bot/index.ts b/src/server/services/bot/index.ts
index 6861c55e899..88e17df050d 100644
--- a/src/server/services/bot/index.ts
+++ b/src/server/services/bot/index.ts
@@ -2,4 +2,5 @@ export { AgentBridgeService } from './AgentBridgeService';
export { BotMessageRouter, getBotMessageRouter } from './BotMessageRouter';
export { platformBotRegistry } from './platforms';
export { Discord, type DiscordBotConfig } from './platforms/discord';
+export { Telegram, type TelegramBotConfig } from './platforms/telegram';
export type { PlatformBot, PlatformBotClass } from './types';
diff --git a/src/server/services/bot/platforms/index.ts b/src/server/services/bot/platforms/index.ts
index 040839e86ad..ed49fa8a559 100644
--- a/src/server/services/bot/platforms/index.ts
+++ b/src/server/services/bot/platforms/index.ts
@@ -1,6 +1,8 @@
import type { PlatformBotClass } from '../types';
import { Discord } from './discord';
+import { Telegram } from './telegram';
export const platformBotRegistry: Record<string, PlatformBotClass> = {
discord: Discord,
+ telegram: Telegram,
};
diff --git a/src/server/services/bot/platforms/telegram.ts b/src/server/services/bot/platforms/telegram.ts
new file mode 100644
index 00000000000..b4dd79a704c
--- /dev/null
+++ b/src/server/services/bot/platforms/telegram.ts
@@ -0,0 +1,106 @@
+import debug from 'debug';
+
+import { appEnv } from '@/envs/app';
+
+import type { PlatformBot } from '../types';
+
+const log = debug('lobe-server:bot:gateway:telegram');
+
+export interface TelegramBotConfig {
+ [key: string]: string | undefined;
+ botToken: string;
+ secretToken?: string;
+ /** Optional HTTPS proxy URL for webhook (e.g. cloudflare tunnel for local dev) */
+ webhookProxyUrl?: string;
+}
+
+/**
+ * Extract the bot user ID from a Telegram bot token.
+ * Telegram bot tokens have the format: `<bot_id>:<secret>`.
+ */
+function extractBotId(botToken: string): string {
+ const colonIndex = botToken.indexOf(':');
+ if (colonIndex === -1) return botToken;
+ return botToken.slice(0, colonIndex);
+}
+
+/**
+ * Call Telegram setWebhook API. Idempotent — safe to call on every startup.
+ */
+export async function setTelegramWebhook(
+ botToken: string,
+ url: string,
+ secretToken?: string,
+): Promise<void> {
+ const params: Record<string, string> = { url };
+ if (secretToken) {
+ params.secret_token = secretToken;
+ }
+
+ const response = await fetch(`https://api.telegram.org/bot${botToken}/setWebhook`, {
+ body: JSON.stringify(params),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ });
+
+ if (!response.ok) {
+ const text = await response.text();
+ throw new Error(`Failed to set Telegram webhook: ${response.status} ${text}`);
+ }
+}
+
+export class Telegram implements PlatformBot {
+ readonly platform = 'telegram';
+ readonly applicationId: string;
+
+ private config: TelegramBotConfig;
+
+ constructor(config: TelegramBotConfig) {
+ this.config = config;
+ this.applicationId = extractBotId(config.botToken);
+ }
+
+ async start(): Promise<void> {
+ log('Starting TelegramBot appId=%s', this.applicationId);
+
+ // Set the webhook URL so Telegram pushes updates to us.
+ // Include applicationId in the path so the router can do a direct lookup
+ // without iterating all registered bots.
+ // Always call setWebhook (it's idempotent) to ensure Telegram-side
+ // secret_token stays in sync with the adapter config.
+ const baseUrl = (this.config.webhookProxyUrl || appEnv.APP_URL || '').replace(/\/$/, '');
+ const webhookUrl = `${baseUrl}/api/agent/webhooks/telegram/${this.applicationId}`;
+ await this.setWebhookInternal(webhookUrl);
+
+ log('TelegramBot appId=%s started', this.applicationId);
+ }
+
+ async stop(): Promise<void> {
+ log('Stopping TelegramBot appId=%s', this.applicationId);
+ // Optionally remove the webhook on stop
+ try {
+ await this.deleteWebhook();
+ } catch (error) {
+ log('Failed to delete webhook for appId=%s: %O', this.applicationId, error);
+ }
+ }
+
+ private async setWebhookInternal(url: string): Promise<void> {
+ await setTelegramWebhook(this.config.botToken, url, this.config.secretToken);
+ log('TelegramBot appId=%s webhook set to %s', this.applicationId, url);
+ }
+
+ private async deleteWebhook(): Promise<void> {
+ const response = await fetch(
+ `https://api.telegram.org/bot${this.config.botToken}/deleteWebhook`,
+ { method: 'POST' },
+ );
+
+ if (!response.ok) {
+ const text = await response.text();
+ throw new Error(`Failed to delete Telegram webhook: ${response.status} ${text}`);
+ }
+
+ log('TelegramBot appId=%s webhook deleted', this.applicationId);
+ }
+}
diff --git a/src/server/services/bot/replyTemplate.ts b/src/server/services/bot/replyTemplate.ts
index a22711166c6..4de142b2038 100644
--- a/src/server/services/bot/replyTemplate.ts
+++ b/src/server/services/bot/replyTemplate.ts
@@ -46,6 +46,7 @@ export interface RenderStepParams extends StepPresentationData {
elapsedMs?: number;
lastContent?: string;
lastToolsCalling?: ToolCallItem[];
+ platform?: string;
totalToolCalls?: number;
}
@@ -123,11 +124,12 @@ export function formatDuration(ms: number): string {
function renderInlineStats(params: {
elapsedMs?: number;
+ platform?: string;
totalCost: number;
totalTokens: number;
totalToolCalls?: number;
}): { footer: string; header: string } {
- const { elapsedMs, totalToolCalls, totalTokens, totalCost } = params;
+ const { elapsedMs, platform, totalToolCalls, totalTokens, totalCost } = params;
const time = elapsedMs && elapsedMs > 0 ? ` · ${formatDuration(elapsedMs)}` : '';
const header =
@@ -137,7 +139,9 @@ function renderInlineStats(params: {
if (totalTokens <= 0) return { footer: '', header };
- const footer = `\n\n-# ${formatTokens(totalTokens)} tokens · $${totalCost.toFixed(4)}`;
+ const stats = `${formatTokens(totalTokens)} tokens · $${totalCost.toFixed(4)}`;
+ // Discord uses -# for small text; Telegram renders it as literal text
+ const footer = platform === 'telegram' ? `\n\n${stats}` : `\n\n-# ${stats}`;
return { footer, header };
}
@@ -159,6 +163,7 @@ export function renderLLMGenerating(params: RenderStepParams): string {
content,
elapsedMs,
lastContent,
+ platform,
reasoning,
toolsCalling,
totalCost,
@@ -168,6 +173,7 @@ export function renderLLMGenerating(params: RenderStepParams): string {
const displayContent = (content || lastContent)?.trim();
const { header, footer } = renderInlineStats({
elapsedMs,
+ platform,
totalCost,
totalTokens,
totalToolCalls,
@@ -205,6 +211,7 @@ export function renderToolExecuting(params: RenderStepParams): string {
elapsedMs,
lastContent,
lastToolsCalling,
+ platform,
toolsResult,
totalCost,
totalTokens,
@@ -212,6 +219,7 @@ export function renderToolExecuting(params: RenderStepParams): string {
} = params;
const { header, footer } = renderInlineStats({
elapsedMs,
+ platform,
totalCost,
totalTokens,
totalToolCalls,
@@ -240,15 +248,18 @@ export function renderFinalReply(
params: {
elapsedMs?: number;
llmCalls: number;
+ platform?: string;
toolCalls: number;
totalCost: number;
totalTokens: number;
},
): string {
- const { totalTokens, totalCost, llmCalls, toolCalls, elapsedMs } = params;
+ const { totalTokens, totalCost, llmCalls, toolCalls, elapsedMs, platform } = params;
const time = elapsedMs && elapsedMs > 0 ? ` · ${formatDuration(elapsedMs)}` : '';
const calls = llmCalls > 1 || toolCalls > 0 ? ` | llm×${llmCalls} | tools×${toolCalls}` : '';
- const footer = `-# ${formatTokens(totalTokens)} tokens · $${totalCost.toFixed(4)}${time}${calls}`;
+ const stats = `${formatTokens(totalTokens)} tokens · $${totalCost.toFixed(4)}${time}${calls}`;
+ // Discord uses -# for small text; Telegram renders it as literal text
+ const footer = platform === 'telegram' ? stats : `-# ${stats}`;
return `${content.trimEnd()}\n\n${footer}`;
}
diff --git a/src/server/services/bot/telegramRestApi.ts b/src/server/services/bot/telegramRestApi.ts
new file mode 100644
index 00000000000..ab2a37e6a16
--- /dev/null
+++ b/src/server/services/bot/telegramRestApi.ts
@@ -0,0 +1,108 @@
+import debug from 'debug';
+
+const log = debug('lobe-server:bot:telegram-rest');
+
+const TELEGRAM_API_BASE = 'https://api.telegram.org';
+
+/**
+ * Lightweight wrapper around the Telegram Bot API.
+ * Used by bot-callback webhooks to update messages directly
+ * (bypassing the Chat SDK adapter).
+ */
+export class TelegramRestApi {
+ private readonly botToken: string;
+
+ constructor(botToken: string) {
+ this.botToken = botToken;
+ }
+
+ async sendMessage(chatId: string | number, text: string): Promise<{ message_id: number }> {
+ log('sendMessage: chatId=%s', chatId);
+ const data = await this.call('sendMessage', {
+ chat_id: chatId,
+ text: this.truncateText(text),
+ });
+ return { message_id: data.result.message_id };
+ }
+
+ async editMessageText(chatId: string | number, messageId: number, text: string): Promise<void> {
+ log('editMessageText: chatId=%s, messageId=%s', chatId, messageId);
+ await this.call('editMessageText', {
+ chat_id: chatId,
+ message_id: messageId,
+ text: this.truncateText(text),
+ });
+ }
+
+ async sendChatAction(chatId: string | number, action = 'typing'): Promise<void> {
+ log('sendChatAction: chatId=%s, action=%s', chatId, action);
+ await this.call('sendChatAction', { action, chat_id: chatId });
+ }
+
+ async deleteMessage(chatId: string | number, messageId: number): Promise<void> {
+ log('deleteMessage: chatId=%s, messageId=%s', chatId, messageId);
+ await this.call('deleteMessage', { chat_id: chatId, message_id: messageId });
+ }
+
+ async setMessageReaction(
+ chatId: string | number,
+ messageId: number,
+ emoji: string,
+ ): Promise<void> {
+ log('setMessageReaction: chatId=%s, messageId=%s, emoji=%s', chatId, messageId, emoji);
+ await this.call('setMessageReaction', {
+ chat_id: chatId,
+ message_id: messageId,
+ reaction: [{ emoji, type: 'emoji' }],
+ });
+ }
+
+ async removeMessageReaction(chatId: string | number, messageId: number): Promise<void> {
+ log('removeMessageReaction: chatId=%s, messageId=%s', chatId, messageId);
+ await this.call('setMessageReaction', {
+ chat_id: chatId,
+ message_id: messageId,
+ reaction: [],
+ });
+ }
+
+ // ------------------------------------------------------------------
+
+ private truncateText(text: string): string {
+ // Telegram message limit is 4096 characters
+ if (text.length > 4096) return text.slice(0, 4093) + '...';
+ return text;
+ }
+
+ private async call(method: string, body: Record<string, unknown>): Promise<any> {
+ const url = `${TELEGRAM_API_BASE}/bot${this.botToken}/${method}`;
+
+ const response = await fetch(url, {
+ body: JSON.stringify(body),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ });
+
+ if (!response.ok) {
+ const text = await response.text();
+ log('Telegram API error: method=%s, status=%d, body=%s', method, response.status, text);
+ throw new Error(`Telegram API ${method} failed: ${response.status} ${text}`);
+ }
+
+ const data = await response.json();
+
+ // Telegram can return HTTP 200 with {"ok": false, ...} for logical errors
+ if (data.ok === false) {
+ const desc = data.description || 'Unknown error';
+ log(
+ 'Telegram API logical error: method=%s, error_code=%d, description=%s',
+ method,
+ data.error_code,
+ desc,
+ );
+ throw new Error(`Telegram API ${method} failed: ${data.error_code} ${desc}`);
+ }
+
+ return data;
+ }
+}