fix(routing): harden originating reply routing

This commit is contained in:
Peter Steinberger
2026-01-07 05:02:34 +00:00
parent 2a2e327cae
commit 3668388912
12 changed files with 356 additions and 51 deletions

View File

@@ -10,6 +10,7 @@ type TelegramSendOpts = {
verbose?: boolean;
mediaUrl?: string;
maxBytes?: number;
messageThreadId?: number;
api?: Bot["api"];
};
@@ -88,6 +89,10 @@ export async function sendMessageTelegram(
const bot = opts.api ? null : new Bot(token);
const api = opts.api ?? bot?.api;
const mediaUrl = opts.mediaUrl?.trim();
const threadParams =
typeof opts.messageThreadId === "number"
? { message_thread_id: Math.trunc(opts.messageThreadId) }
: undefined;
const sleep = (ms: number) =>
new Promise((resolve) => setTimeout(resolve, ms));
@@ -150,35 +155,35 @@ export async function sendMessageTelegram(
| Awaited<ReturnType<typeof api.sendDocument>>;
if (isGif) {
result = await sendWithRetry(
() => api.sendAnimation(chatId, file, { caption }),
() => api.sendAnimation(chatId, file, { caption, ...threadParams }),
"animation",
).catch((err) => {
throw wrapChatNotFound(err);
});
} else if (kind === "image") {
result = await sendWithRetry(
() => api.sendPhoto(chatId, file, { caption }),
() => api.sendPhoto(chatId, file, { caption, ...threadParams }),
"photo",
).catch((err) => {
throw wrapChatNotFound(err);
});
} else if (kind === "video") {
result = await sendWithRetry(
() => api.sendVideo(chatId, file, { caption }),
() => api.sendVideo(chatId, file, { caption, ...threadParams }),
"video",
).catch((err) => {
throw wrapChatNotFound(err);
});
} else if (kind === "audio") {
result = await sendWithRetry(
() => api.sendAudio(chatId, file, { caption }),
() => api.sendAudio(chatId, file, { caption, ...threadParams }),
"audio",
).catch((err) => {
throw wrapChatNotFound(err);
});
} else {
result = await sendWithRetry(
() => api.sendDocument(chatId, file, { caption }),
() => api.sendDocument(chatId, file, { caption, ...threadParams }),
"document",
).catch((err) => {
throw wrapChatNotFound(err);
@@ -192,7 +197,11 @@ export async function sendMessageTelegram(
throw new Error("Message must be non-empty for Telegram sends");
}
const res = await sendWithRetry(
() => api.sendMessage(chatId, text, { parse_mode: "Markdown" }),
() =>
api.sendMessage(chatId, text, {
parse_mode: "Markdown",
...threadParams,
}),
"message",
).catch(async (err) => {
// Telegram rejects malformed Markdown (e.g., unbalanced '_' or '*').
@@ -205,7 +214,10 @@ export async function sendMessageTelegram(
);
}
return await sendWithRetry(
() => api.sendMessage(chatId, text),
() =>
threadParams
? api.sendMessage(chatId, text, threadParams)
: api.sendMessage(chatId, text),
"message-plain",
).catch((err2) => {
throw wrapChatNotFound(err2);