Skip to content

Commit d7133e7

Browse files
authored
fix(telegram): preserve direct messages topic routing (#120916)
Replies, previews, and media in channel Direct Messages topics now remain in their originating topic. Bot-private and forum topic routing remains unchanged.
1 parent c315a94 commit d7133e7

26 files changed

Lines changed: 730 additions & 223 deletions

‎extensions/telegram/src/action-runtime.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,10 @@ function resolveActionTopicNameCacheScope(cfg: OpenClawConfig, accountId?: strin
162162

163163
function formatTelegramDeliveryTarget(to: string, messageThreadId?: number | null): string {
164164
const parsed = parseTelegramTarget(to);
165+
const directTopicId = parsed.directMessagesTopicId;
166+
if (directTopicId != null) {
167+
return `${parsed.chatId}:direct-topic:${directTopicId}`;
168+
}
165169
const topicId = messageThreadId ?? parsed.messageThreadId;
166170
if (topicId == null) {
167171
return to;

‎extensions/telegram/src/bot-handlers.callback-actions.runtime.ts‎

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { Message } from "grammy/types";
22
import type { RegisterTelegramHandlerParams } from "./bot-native-commands.js";
3-
import { buildTelegramThreadParams, resolveTelegramThreadSpec } from "./bot/helpers.js";
3+
import { buildTelegramThreadParams, resolveTelegramMessageThreadSpec } from "./bot/helpers.js";
44
import { buildInlineKeyboard } from "./send.js";
55

66
export type TelegramCallbackButton = {
@@ -35,7 +35,7 @@ export function createTelegramCallbackMessageActions(params: {
3535
isGroup: boolean;
3636
isForum: boolean;
3737
}): TelegramCallbackMessageActions {
38-
const { bot, callbackMessage, isGroup, isForum } = params;
38+
const { bot, callbackMessage, isForum } = params;
3939
const callbackBusinessParams =
4040
callbackMessage.business_connection_id !== undefined
4141
? { business_connection_id: callbackMessage.business_connection_id }
@@ -82,22 +82,16 @@ export function createTelegramCallbackMessageActions(params: {
8282
replyParams?: Parameters<typeof bot.api.sendMessage>[2],
8383
) => {
8484
const threadParams = buildTelegramThreadParams(
85-
resolveTelegramThreadSpec({
86-
isGroup,
87-
isForum,
88-
messageThreadId: callbackMessage.message_thread_id,
89-
}),
85+
resolveTelegramMessageThreadSpec(callbackMessage, isForum),
9086
);
91-
const topicParams = {
92-
...callbackBusinessParams,
93-
...threadParams,
94-
...(callbackMessage.direct_messages_topic?.topic_id != null
95-
? { direct_messages_topic_id: callbackMessage.direct_messages_topic.topic_id }
96-
: {}),
97-
};
87+
const {
88+
message_thread_id: _messageThreadId,
89+
direct_messages_topic_id: _directMessagesTopicId,
90+
...ordinaryReplyParams
91+
} = replyParams ?? {};
9892
const mergedParams =
99-
Object.keys(topicParams).length > 0 || replyParams
100-
? { ...topicParams, ...replyParams }
93+
callbackBusinessParams || threadParams || replyParams
94+
? { ...ordinaryReplyParams, ...callbackBusinessParams, ...threadParams }
10195
: replyParams;
10296
return await bot.api.sendMessage(callbackMessage.chat.id, text, mergedParams);
10397
};

‎extensions/telegram/src/bot-handlers.inbound-debounce.runtime.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,12 @@ import type { TelegramMediaRef } from "./bot-message-context.js";
1212
import type { TelegramAmbientTranscriptWatermark } from "./bot-message-context.types.js";
1313
import type { RegisterTelegramHandlerParams } from "./bot-native-commands.js";
1414
import type { TelegramSpooledReplayDeferredParticipant } from "./bot-processing-outcome.js";
15-
import { getTelegramTextParts, joinTelegramTextParts } from "./bot/helpers.js";
15+
import {
16+
buildTelegramThreadParams,
17+
getTelegramTextParts,
18+
joinTelegramTextParts,
19+
resolveTelegramMessageThreadSpec,
20+
} from "./bot/helpers.js";
1621
import type { TelegramContext } from "./bot/types.js";
1722
import type { TelegramMessageDispatchReplayClaim } from "./message-dispatch-dedupe.js";
1823

@@ -199,12 +204,15 @@ export function createTelegramInboundDebounceRuntime(
199204
}
200205
const chatId = items[0]?.msg.chat.id;
201206
if (chatId != null) {
202-
const threadId = items[0]?.msg.message_thread_id;
207+
const firstMessage = items[0]?.msg;
208+
const threadParams = firstMessage
209+
? buildTelegramThreadParams(resolveTelegramMessageThreadSpec(firstMessage))
210+
: undefined;
203211
void bot.api
204212
.sendMessage(
205213
chatId,
206214
"Something went wrong while processing your message. Please try again.",
207-
threadId != null ? { message_thread_id: threadId } : undefined,
215+
threadParams,
208216
)
209217
.catch((sendError: unknown) => {
210218
logVerbose(`telegram: error fallback send failed: ${String(sendError)}`);

‎extensions/telegram/src/bot-handlers.inbound-media-group.runtime.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ import {
3333
buildTelegramThreadParams,
3434
getTelegramTextParts,
3535
hasBotMention,
36+
resolveTelegramMessageThreadSpec,
3637
resolveTelegramPrimaryMedia,
37-
resolveTelegramThreadSpec,
3838
} from "./bot/helpers.js";
3939
import type { TelegramContext } from "./bot/types.js";
4040
import { isTelegramForumServiceMessage } from "./forum-service-message.js";
@@ -373,11 +373,7 @@ export function createTelegramInboundMediaGroupRuntime(
373373
`⚠️ Received ${materializedCount} of ${entry.messages.length} images — ${skippedCount} could not be fetched and ${verb} skipped.`,
374374
{
375375
...buildTelegramThreadParams(
376-
resolveTelegramThreadSpec({
377-
isGroup: entry.isGroup,
378-
isForum: entry.isForum,
379-
messageThreadId: entry.resolvedThreadId ?? entry.dmThreadId,
380-
}),
376+
resolveTelegramMessageThreadSpec(primary.msg, entry.isForum),
381377
),
382378
reply_parameters: {
383379
message_id: primary.msg.message_id,

‎extensions/telegram/src/bot-handlers.inbound.runtime.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ import { resolveMedia } from "./bot/delivery.resolve-media.js";
3535
import {
3636
buildTelegramThreadParams,
3737
getTelegramTextParts,
38+
resolveTelegramMessageThreadSpec,
3839
resolveTelegramPrimaryMedia,
39-
resolveTelegramThreadSpec,
4040
} from "./bot/helpers.js";
4141
import type { TelegramContext } from "./bot/types.js";
4242
import { resolveTelegramCommandIngressAuthorization } from "./ingress.js";
@@ -236,11 +236,7 @@ export function createTelegramHandlerInboundRuntime(
236236
} catch (mediaErr) {
237237
const replayingSpooledUpdate = isTelegramSpooledReplayUpdate(ctx.update);
238238
const warningThreadParams = buildTelegramThreadParams(
239-
resolveTelegramThreadSpec({
240-
isGroup,
241-
isForum,
242-
messageThreadId: resolvedThreadId ?? dmThreadId,
243-
}),
239+
resolveTelegramMessageThreadSpec(msg, isForum),
244240
);
245241
if (mediaRuntime.abortSignal?.aborted && isDurablyRetryableInboundMediaError(mediaErr)) {
246242
// Abort mid-media-resolution must stay retryable for live updates too;

‎extensions/telegram/src/bot-message-context.dm-threads.test.ts‎

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ describe("buildTelegramMessageContext dm thread sessions", () => {
8888
message: Record<string, unknown>,
8989
params?: Pick<
9090
Parameters<typeof buildTelegramMessageContextForTest>[0],
91-
"cfg" | "me" | "resolveTelegramGroupConfig"
91+
"cfg" | "me" | "resolveTelegramGroupConfig" | "sendChatActionHandler"
9292
>,
9393
) =>
9494
await buildTelegramMessageContextForTest({
@@ -130,7 +130,7 @@ describe("buildTelegramMessageContext dm thread sessions", () => {
130130
expect(ctx?.ctxPayload?.SessionKey).toBe("agent:main:main:thread:1234:42");
131131
});
132132

133-
it("does not use configured DM topics without bot topic capability", async () => {
133+
it("does not use configured bot-private topics without bot topic capability", async () => {
134134
const ctx = await buildContext(
135135
{
136136
...dmThreadMessage,
@@ -149,7 +149,7 @@ describe("buildTelegramMessageContext dm thread sessions", () => {
149149
expect(ctx?.ctxPayload?.SessionKey).toBe("agent:support:main");
150150
});
151151

152-
it("uses configured DM topic routing once bot topic capability is present", async () => {
152+
it("uses configured bot-private topic routing once bot topic capability is present", async () => {
153153
const ctx = await buildContext(
154154
{
155155
...dmThreadMessage,
@@ -184,11 +184,18 @@ describe("buildTelegramMessageContext dm thread sessions", () => {
184184
});
185185

186186
describe("buildTelegramMessageContext group sessions without forum", () => {
187-
const buildContext = async (message: Record<string, unknown>) =>
187+
const buildContext = async (
188+
message: Record<string, unknown>,
189+
params?: Pick<
190+
Parameters<typeof buildTelegramMessageContextForTest>[0],
191+
"sendChatActionHandler"
192+
>,
193+
) =>
188194
await buildTelegramMessageContextForTest({
189195
message,
190196
options: { forceWasMentioned: true },
191197
resolveGroupActivation: () => true,
198+
...params,
192199
});
193200

194201
it("ignores message_thread_id for regular groups (not forums)", async () => {
@@ -212,6 +219,45 @@ describe("buildTelegramMessageContext group sessions without forum", () => {
212219
expect(ctx.ctxPayload.MessageThreadId).toBeUndefined();
213220
});
214221

222+
it("round-trips channel Direct Messages topics with their distinct target marker", async () => {
223+
const sendChatAction = vi.fn(async () => undefined);
224+
const ctx = await buildContext(
225+
{
226+
message_id: 8,
227+
chat: {
228+
id: -1001234567890,
229+
type: "supergroup",
230+
title: "Channel Direct Messages",
231+
is_direct_messages: true,
232+
},
233+
date: 1700000007,
234+
text: "@bot hello",
235+
message_thread_id: 999,
236+
direct_messages_topic: {
237+
topic_id: 77,
238+
user: { id: 700, is_bot: false, first_name: "Subscriber" },
239+
},
240+
from: { id: 700, first_name: "Subscriber" },
241+
},
242+
{
243+
sendChatActionHandler: {
244+
sendChatAction,
245+
isSuspended: () => false,
246+
reset: () => {},
247+
},
248+
},
249+
);
250+
251+
expect(ctx?.ctxPayload.MessageThreadId).toBe(77);
252+
expect(ctx?.ctxPayload.OriginatingTo).toBe("telegram:-1001234567890:direct-topic:77");
253+
expect(ctx?.ctxPayload.SessionKey).toBe("agent:main:telegram:group:-1001234567890:topic:77");
254+
expect(ctx?.turn.record.updateLastRoute).toMatchObject({
255+
to: "telegram:-1001234567890:direct-topic:77",
256+
threadId: "77",
257+
});
258+
expect(sendChatAction).not.toHaveBeenCalled();
259+
});
260+
215261
it("carries the body-layer inbound event kind instead of restamping from copied mention booleans", async () => {
216262
inboundBodyResult.value = {
217263
...inboundBodyResult.reset(),

‎extensions/telegram/src/bot-message-context.ts‎

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import {
3636
extractTelegramForumFlag,
3737
resolveTelegramForumFlag,
3838
resolveTelegramBotHasTopicsEnabled,
39+
resolveTelegramMessageThreadSpec,
3940
resolveTelegramThreadSpec,
4041
shouldUseTelegramDmThreadSession,
4142
} from "./bot/helpers.js";
@@ -146,7 +147,7 @@ export const buildTelegramMessageContext = async ({
146147
const chatId = msg.chat.id;
147148
const isGroup = msg.chat.type === "group" || msg.chat.type === "supergroup";
148149
const senderId = msg.from?.id ? String(msg.from.id) : "";
149-
const messageThreadId = (msg as { message_thread_id?: number }).message_thread_id;
150+
const isDirectMessagesChat = msg.chat.is_direct_messages === true;
150151
const reactionApi =
151152
typeof bot.api.setMessageReaction === "function"
152153
? bot.api.setMessageReaction.bind(bot.api)
@@ -155,20 +156,21 @@ export const buildTelegramMessageContext = async ({
155156
typeof bot.api.getChat === "function"
156157
? (bot.api.getChat.bind(bot.api) as TelegramGetChat)
157158
: undefined;
158-
const isForum = await resolveTelegramForumFlag({
159-
chatId,
160-
chatType: msg.chat.type,
161-
isGroup,
162-
isForum: extractTelegramForumFlag(msg.chat),
163-
isTopicMessage: msg.is_topic_message,
164-
getChat: getChatApi,
165-
});
166-
const threadSpec = resolveTelegramThreadSpec({
167-
isGroup,
168-
isForum,
169-
messageThreadId,
170-
});
171-
const resolvedThreadId = threadSpec.scope === "forum" ? threadSpec.id : undefined;
159+
const isForum = isDirectMessagesChat
160+
? false
161+
: await resolveTelegramForumFlag({
162+
chatId,
163+
chatType: msg.chat.type,
164+
isGroup,
165+
isForum: extractTelegramForumFlag(msg.chat),
166+
isTopicMessage: msg.is_topic_message,
167+
getChat: getChatApi,
168+
});
169+
const threadSpec = resolveTelegramMessageThreadSpec(msg, isForum);
170+
const resolvedThreadId =
171+
threadSpec.scope === "forum" || threadSpec.scope === "direct-messages"
172+
? threadSpec.id
173+
: undefined;
172174
const replyThreadId = threadSpec.id;
173175
const dmThreadId = threadSpec.scope === "dm" ? threadSpec.id : undefined;
174176
let topicName: string | undefined;
@@ -321,6 +323,9 @@ export const buildTelegramMessageContext = async ({
321323
}
322324

323325
const sendTyping = async () => {
326+
if (threadSpec.scope === "direct-messages") {
327+
return;
328+
}
324329
await withTelegramApiErrorLogging({
325330
operation: "sendChatAction",
326331
fn: () =>
@@ -333,6 +338,9 @@ export const buildTelegramMessageContext = async ({
333338
};
334339

335340
const sendRecordVoice = async () => {
341+
if (threadSpec.scope === "direct-messages") {
342+
return;
343+
}
336344
try {
337345
await withTelegramApiErrorLogging({
338346
operation: "sendChatAction",

‎extensions/telegram/src/bot-message-dispatch-delivery.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@ import type {
3232
} from "./bot-message-dispatch.types.js";
3333
import type { TelegramBotOptions } from "./bot.types.js";
3434
import { deliverReplies, emitTelegramMessageSentHooks } from "./bot/delivery.js";
35-
import type { TelegramThreadSpec } from "./bot/helpers.js";
36-
import { resolveTelegramReplyId } from "./bot/helpers.js";
35+
import { resolveTelegramReplyId, type TelegramThreadSpec } from "./bot/helpers.js";
3736
import type { TelegramNativeQuoteCandidateByMessageId } from "./bot/native-quote.js";
3837
import type { TelegramInlineButtons } from "./button-types.js";
3938
import { canonicalizeTelegramPresentationPayload } from "./interactive-fallback.js";
@@ -266,7 +265,8 @@ export function createTelegramDeliveryController(params: {
266265
const durable = await durableDelivery({
267266
cfg: params.cfg,
268267
channel: "telegram",
269-
to: String(context.chatId),
268+
to:
269+
context.ctxPayload.OriginatingTo ?? context.ctxPayload.To ?? `telegram:${context.chatId}`,
270270
accountId: context.route.accountId,
271271
agentId: context.route.agentId,
272272
ctxPayload: context.ctxPayload,

0 commit comments

Comments
 (0)