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.

🐛 fix(messenger): support Telegram slash commands (#16545)

orangeboy468f1f3dbc4a
diff --git a/apps/server/src/services/messenger/MessengerRouter.test.ts b/apps/server/src/services/messenger/MessengerRouter.test.ts
index 4f49835e911..f91a25b5d47 100644
--- a/apps/server/src/services/messenger/MessengerRouter.test.ts
+++ b/apps/server/src/services/messenger/MessengerRouter.test.ts
@@ -185,17 +185,20 @@ vi.mock('./platforms/slack/binder', () => ({
MessengerSlackBinder: vi.fn().mockImplementation(() => mockSlackBinder),
}));
+const mockTelegramBinder = {
+ createClient: () => ({
+ createAdapter: () => ({}),
+ // Telegram thread ids are `telegram:<chatId>[:<messageThreadId>]`.
+ extractChatId: (id: string) => id.split(':')[1] ?? id,
+ }),
+ handleUnlinkedMessage: vi.fn(),
+ notifyLinkSuccess: vi.fn(),
+ registerWebhook: vi.fn(),
+ sendAgentPicker: vi.fn(),
+ sendDmText: vi.fn(),
+};
vi.mock('./platforms/telegram/binder', () => ({
- MessengerTelegramBinder: vi.fn().mockImplementation(() => ({
- createClient: () => ({
- createAdapter: () => ({}),
- extractChatId: (id: string) => id,
- }),
- handleUnlinkedMessage: vi.fn(),
- notifyLinkSuccess: vi.fn(),
- registerWebhook: vi.fn(),
- sendDmText: vi.fn(),
- })),
+ MessengerTelegramBinder: vi.fn().mockImplementation(() => mockTelegramBinder),
}));
const mockWechatBinder = {
@@ -233,6 +236,15 @@ const slackCreds = (tenantId: string) => ({
tenantId,
});
+const telegramCreds = {
+ applicationId: 'telegram:singleton',
+ botToken: 'tg-token',
+ installationKey: 'telegram:singleton',
+ metadata: {},
+ platform: 'telegram' as const,
+ tenantId: '',
+};
+
const wechatCreds = {
applicationId: 'wechat-bot',
baseUrl: 'https://ilink.example.com',
@@ -276,6 +288,9 @@ beforeEach(() => {
mockSlackBinder.replyPrivately.mockReset();
mockSlackBinder.sendAgentPicker.mockReset();
mockSlackBinder.sendDmText.mockReset();
+ mockTelegramBinder.handleUnlinkedMessage.mockReset();
+ mockTelegramBinder.sendAgentPicker.mockReset();
+ mockTelegramBinder.sendDmText.mockReset();
mockWechatBinder.handleUnlinkedMessage.mockReset();
mockWechatBinder.sendDmText.mockReset();
});
@@ -461,6 +476,17 @@ const loadSlackBot = async (): Promise<void> => {
);
};
+const loadTelegramBot = async (): Promise<void> => {
+ mockResolveByPayload.mockResolvedValue(telegramCreds);
+ const router = new MessengerRouter();
+ await router.getWebhookHandler('telegram')(
+ new Request('https://app.example.com/api/agent/messenger/webhooks/telegram', {
+ body: JSON.stringify({ message: { text: 'hi' } }),
+ method: 'POST',
+ }),
+ );
+};
+
const loadWechatBot = async (): Promise<void> => {
mockResolveByPayload.mockResolvedValue(wechatCreds);
const router = new MessengerRouter();
@@ -852,6 +878,80 @@ describe('MessengerRouter slash command dispatch', () => {
...overrides,
});
+ const fakeTelegramSlashEvent = (overrides: Partial<any> = {}): any => ({
+ channel: { id: 'telegram:123', isDM: false, post: vi.fn() },
+ command: '/start',
+ text: '',
+ user: { userId: '123', userName: 'alice' },
+ ...overrides,
+ });
+
+ it('registers Telegram slash commands and routes private /start to the link flow', async () => {
+ await loadTelegramBot();
+ mockFindLink.mockResolvedValue(null);
+
+ const [paths, handler] = mockChatBot.onSlashCommand.mock.calls[0] as [
+ string[],
+ (event: any) => Promise<void>,
+ ];
+ expect(paths).toContain('/start');
+
+ await handler(fakeTelegramSlashEvent());
+
+ expect(mockTelegramBinder.handleUnlinkedMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ authorUserId: '123',
+ chatId: '123',
+ channelMentionThreadId: undefined,
+ }),
+ );
+ expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();
+ });
+
+ it('keeps an unlinked Telegram group /start visible without leaking a link token', async () => {
+ await loadTelegramBot();
+ mockFindLink.mockResolvedValue(null);
+ const post = vi.fn();
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(
+ fakeTelegramSlashEvent({ channel: { id: 'telegram:-100123:42', isDM: false, post } }),
+ );
+
+ expect(post).toHaveBeenCalledWith(expect.stringContaining('send `/start` there'));
+ expect(mockTelegramBinder.handleUnlinkedMessage).not.toHaveBeenCalled();
+ expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();
+ expect(mockOpenDM).not.toHaveBeenCalled();
+ });
+
+ it('routes a linked Telegram group /agents picker to the invoker DM', async () => {
+ await loadTelegramBot();
+ mockFindLink.mockResolvedValue({
+ activeAgentId: 'agt_a',
+ id: 'link_1',
+ platformUserId: '123',
+ tenantId: '',
+ userId: 'user_alice',
+ });
+
+ const handler = mockChatBot.onSlashCommand.mock.calls[0][1] as (event: any) => Promise<void>;
+ await handler(
+ fakeTelegramSlashEvent({
+ channel: { id: 'telegram:-100123', isDM: false, post: vi.fn() },
+ command: '/agents',
+ }),
+ );
+
+ expect(mockTelegramBinder.sendAgentPicker).toHaveBeenCalledWith(
+ '123',
+ expect.objectContaining({
+ ephemeralTo: '123',
+ text: expect.stringContaining('Tap an agent'),
+ }),
+ );
+ expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();
+ });
+
it('renders the picker as ephemeral when /agents is invoked from a public channel', async () => {
await loadSlackBot();
mockFindLink.mockResolvedValue({
diff --git a/apps/server/src/services/messenger/MessengerRouter.ts b/apps/server/src/services/messenger/MessengerRouter.ts
index a7d17ad7d6d..09b9461d850 100644
--- a/apps/server/src/services/messenger/MessengerRouter.ts
+++ b/apps/server/src/services/messenger/MessengerRouter.ts
@@ -726,11 +726,16 @@ export class MessengerRouter {
await handle(thread, message, 'handleMention');
});
- // Native slash commands — wired only for platforms that opt in by
- // exposing `replyPrivately` (Slack, Discord). The full set of command
- // names comes from the shared registry so every native-slash platform
- // surfaces the same menu.
- if (binder.replyPrivately) {
+ // Native slash commands. chat-adapter routes a leading `/command` to the
+ // slash-command channel (NOT onNewMention / onSubscribedMessage), so any
+ // platform that surfaces slash commands MUST register here or the command
+ // is silently dropped. Slack / Discord reply via `replyPrivately`; the
+ // Telegram binder does not implement that helper, so register it explicitly
+ // and fall back to `sendDmText` in the dispatcher. The full set of command
+ // names comes from the shared registry so every platform surfaces the same menu.
+ const supportsNativeSlashCommands =
+ binder.replyPrivately !== undefined || creds.platform === 'telegram';
+ if (supportsNativeSlashCommands) {
const slashPaths = commands.map((cmd) => `/${cmd.name}`);
bot.onSlashCommand(slashPaths, async (event) => {
await this.handleSlashCommand({ binder, bot, client, creds, event, serverDB });
@@ -804,8 +809,9 @@ export class MessengerRouter {
// • Slack — `chat.postEphemeral` in the channel is invoker-only
// and keeps the link flow inline (no DM context switch).
// • Discord — no text-channel ephemeral primitive for non-
- // interaction messages, so we still open a DM. Telegram has no
- // channel slash surface today, falls through to DM as well.
+ // interaction messages, so we still open a DM.
+ // Telegram group `/start` is intercepted by `handleSlashCommand`
+ // before this handler and gets a safe prompt to open the bot DM.
// Detection key: presence of `binder.replyEphemeral`, which is what
// the @mention path also uses to decide ephemeral-vs-DM.
const canEphemeralInChannel = !ctx.isDM && !!ctx.binder.replyEphemeral;
@@ -999,12 +1005,6 @@ export class MessengerRouter {
return;
}
- const replyPrivately = binder.replyPrivately;
- if (!replyPrivately) {
- log('handleSlashCommand: binder for %s has no replyPrivately', creds.platform);
- return;
- }
-
// `event.command` is the literal `/foo` the platform sent.
const cmdName = event.command.replace(/^\//, '').toLowerCase();
// chat-sdk wraps the raw channel id with the platform prefix
@@ -1012,8 +1012,16 @@ export class MessengerRouter {
// the bare id so direct platform API calls see what they expect.
const chatId = client.extractChatId((event.channel as any).id as string);
const args = event.text?.trim() ?? '';
+ const isTelegramGroup = creds.platform === 'telegram' && chatId.startsWith('-');
+ const replyChatId = isTelegramGroup ? senderId : chatId;
- const reply = (text: string) => replyPrivately.call(binder, event.channel, event.user, text);
+ // Slack / Discord reply privately (ephemeral / DM); Telegram has no
+ // `replyPrivately`, so fall back to a direct message in the slash
+ // command's chat. Both keep the reply scoped to the invoker.
+ const replyPrivately = binder.replyPrivately;
+ const reply = replyPrivately
+ ? (text: string) => replyPrivately.call(binder, event.channel, event.user, text)
+ : (text: string) => binder.sendDmText(replyChatId, text);
const systemStrings = getMessengerSystemStrings(creds.platform);
const command = this.getCommandsForPlatform(creds.platform).find((c) => c.name === cmdName);
@@ -1029,6 +1037,16 @@ export class MessengerRouter {
creds.tenantId,
);
+ // Telegram bots cannot initiate a private conversation with a user. A
+ // first-time user invoking `/start` from a group therefore cannot receive
+ // the account-link button at `senderId`. Keep the one-shot link out of the
+ // group and post only a safe instruction back to the originating chat (or
+ // forum topic); the user can then open the bot DM and retry `/start`.
+ if (isTelegramGroup && cmdName === 'start' && !link) {
+ await event.channel.post(systemStrings.startDirectMessageOnly);
+ return;
+ }
+
// Slash command events have no chat-sdk Thread attached (slash isn't
// posted into any specific thread). Worse, chat-sdk's
// `handleSlashCommandEvent` constructs the ChannelImpl WITHOUT an
@@ -1055,7 +1073,9 @@ export class MessengerRouter {
// group DMs, `C` is public). For other platforms (Discord today) the
// chat-sdk flag is reliable so we keep that path too.
const isDmChannel =
- event.channel.isDM === true || (creds.platform === 'slack' && chatId.startsWith('D'));
+ event.channel.isDM === true ||
+ (creds.platform === 'slack' && chatId.startsWith('D')) ||
+ (creds.platform === 'telegram' && !isTelegramGroup);
// Discord slash commands arrive as deferred interactions (the
// `patchDiscordForwardedInteractions` patch ack's them with type 5
@@ -1072,7 +1092,7 @@ export class MessengerRouter {
authorUserId: senderId,
authorUserName: event.user.userName,
binder,
- chatId,
+ chatId: replyChatId,
interaction,
// `isDM` lets handlers like `/agents` keep the picker public in
// DMs (so it stays in history) and widen to an ephemeral when
diff --git a/apps/server/src/services/messenger/systemReply.ts b/apps/server/src/services/messenger/systemReply.ts
index d9c28759134..e5365063afa 100644
--- a/apps/server/src/services/messenger/systemReply.ts
+++ b/apps/server/src/services/messenger/systemReply.ts
@@ -35,6 +35,7 @@ interface MessengerSystemStrings {
scopesUsage: (count: number) => string;
scopeSwitched: (name: string, agentTitle?: string) => string;
staleScope: string;
+ startDirectMessageOnly: string;
stopDirectMessageOnly: string;
stopNotActive: string;
stopRequested: string;
@@ -90,6 +91,8 @@ const EN_US: MessengerSystemStrings = {
scopesHeading: 'Scopes:',
scopesHint: 'Reply with /switch <n> to switch scope.',
scopesUsage: (count) => `Usage: /switch <n>, where n is between 1 and ${count}.`,
+ startDirectMessageOnly:
+ 'Open your direct message with the LobeHub bot and send `/start` there to link your account.',
staleScope: 'Your active workspace is no longer available. Send /switch to choose another scope.',
stopDirectMessageOnly: 'Open your direct message with the LobeHub bot and send `/stop` there.',
stopNotActive: 'No active execution to stop.',
@@ -145,6 +148,7 @@ const ZH_CN: MessengerSystemStrings = {
scopesHeading: '可切换空间:',
scopesHint: '回复 /switch <序号> 可切换空间。',
scopesUsage: (count) => `用法:/switch <序号>,序号范围为 1–${count}。`,
+ startDirectMessageOnly: '请打开与 LobeHub 机器人的私聊,并在那里发送 `/start` 绑定账号。',
staleScope: '当前工作区已不可用。请发送 /switch 选择其他空间。',
stopDirectMessageOnly: '请在与 LobeHub 机器人的私聊中发送 `/stop`。',
stopNotActive: '当前没有正在执行的任务可以停止。',
diff --git a/apps/server/src/services/messenger/types.ts b/apps/server/src/services/messenger/types.ts
index c6d2fb17a95..4a60d711bea 100644
--- a/apps/server/src/services/messenger/types.ts
+++ b/apps/server/src/services/messenger/types.ts
@@ -160,9 +160,9 @@ export interface MessengerPlatformBinder {
*
* Defining this also opts the platform into native slash command wiring
* — the router registers every name from its shared command registry so
- * the slash menu stays symmetric across platforms. Telegram leaves this
- * unset because `/cmd` arrives as plain message text and is dispatched
- * by `parseCommand` instead.
+ * the slash menu stays symmetric across platforms. The Telegram binder
+ * leaves this unset; the router registers Telegram explicitly and sends
+ * command replies through its DM helpers instead.
*/
replyPrivately?: (
channel: SlashCommandEvent['channel'],