Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/calm-bots-repeat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@chat-adapter/telegram": patch
---

Deduplicate repeated Telegram webhook updates by their update ID using the configured state adapter.
1 change: 1 addition & 0 deletions apps/docs/content/adapters/official/telegram.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ Pass `{ raw: "..." }` only if you need to ship a fully pre-escaped MarkdownV2 st

### Notes

- Webhook updates with a numeric `update_id` are deduplicated for 24 hours through the configured state adapter. Use shared durable state across serverless instances; if the state is unavailable, the adapter returns 503 so Telegram retries without dispatching.
- Telegram does not expose full historical message APIs to bots. `fetchMessages` returns adapter-cached messages from the current process.
- `listThreads` is not available for Telegram chats.
- Telegram callback data is limited to 64 bytes — keep `Button` `id`/`value` payloads short.
Expand Down
142 changes: 142 additions & 0 deletions packages/adapter-telegram/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,148 @@ describe("TelegramAdapter", () => {
).toBe(false);
});

it("deduplicates sequential and concurrent webhook updates", async () => {
mockFetch.mockResolvedValue(
telegramOk({
id: 999,
is_bot: true,
first_name: "Bot",
username: "mybot",
})
);

const state = createMockState();
const adapters = [0, 1].map(() =>
createTelegramAdapter({
botToken: "token",
mode: "webhook",
logger: mockLogger,
userName: "mybot",
})
);
const chats = [0, 1].map(() =>
createMockChatInstance({ logger: mockLogger, state, userName: "mybot" })
);
await Promise.all(
adapters.map((adapter, index) => adapter.initialize(chats[index]))
);

const request = (updateId: number) =>
new Request("https://example.com/webhook", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ update_id: updateId, message: sampleMessage() }),
});
const dispatchCount = () =>
chats.reduce(
(count, chat) =>
count +
(chat.processMessage as ReturnType<typeof vi.fn>).mock.calls.length,
0
);

const firstResponse = await adapters[0]?.handleWebhook(request(1));
const duplicateResponse = await adapters[1]?.handleWebhook(request(1));
expect(firstResponse?.status).toBe(200);
expect(duplicateResponse?.status).toBe(200);
expect(dispatchCount()).toBe(1);

const concurrentResponses = await Promise.all(
adapters.map((adapter) => adapter.handleWebhook(request(2)))
);
expect(concurrentResponses.map(({ status }) => status)).toEqual([200, 200]);
expect(dispatchCount()).toBe(2);
});

it("dispatches distinct and missing webhook update IDs", async () => {
mockFetch.mockResolvedValue(
telegramOk({
id: 999,
is_bot: true,
first_name: "Bot",
username: "mybot",
})
);

const adapter = createTelegramAdapter({
botToken: "token",
mode: "webhook",
logger: mockLogger,
userName: "mybot",
});
const state = createMockState();
const chat = createMockChatInstance({
logger: mockLogger,
state,
userName: "mybot",
});
await adapter.initialize(chat);

const updates = [
{ update_id: 1, message: sampleMessage() },
{ update_id: 2, message: sampleMessage() },
{ message: sampleMessage() },
];
await Promise.all(
updates.map((update) =>
adapter.handleWebhook(
new Request("https://example.com/webhook", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(update),
})
)
)
);

expect(chat.processMessage).toHaveBeenCalledTimes(3);
expect(state.setIfNotExists).toHaveBeenCalledTimes(2);
expect(state.setIfNotExists).toHaveBeenCalledWith(
"telegram:webhook-update:1",
true,
86_400_000
);
});

it("returns 503 without dispatch when the deduplication state fails", async () => {
mockFetch.mockResolvedValue(
telegramOk({
id: 999,
is_bot: true,
first_name: "Bot",
username: "mybot",
})
);

const state = createMockState();
vi.spyOn(state, "setIfNotExists").mockRejectedValue(
new Error("state unavailable")
);
const adapter = createTelegramAdapter({
botToken: "token",
mode: "webhook",
logger: mockLogger,
userName: "mybot",
});
const chat = createMockChatInstance({
logger: mockLogger,
state,
userName: "mybot",
});
await adapter.initialize(chat);

const response = await adapter.handleWebhook(
new Request("https://example.com/webhook", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ update_id: 1, message: sampleMessage() }),
})
);

expect(response.status).toBe(503);
expect(chat.processMessage).not.toHaveBeenCalled();
});

it("combines an incoming media group into one ordered message", async () => {
vi.useFakeTimers();
mockFetch.mockResolvedValue(
Expand Down
25 changes: 25 additions & 0 deletions packages/adapter-telegram/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ const TELEGRAM_INCOMING_MEDIA_GROUP_BUFFER_TTL_MS = 30_000;
const TELEGRAM_INCOMING_MEDIA_GROUP_LOCK_TTL_MS = 5_000;
const TELEGRAM_INCOMING_MEDIA_GROUP_RETRY_MS = 50;
const TELEGRAM_INCOMING_MEDIA_GROUP_SETTLE_MS = 1_000;
const TELEGRAM_WEBHOOK_UPDATE_TTL_MS = 24 * 60 * 60 * 1000;
const TELEGRAM_MEDIA_GROUP_MIN = 2;
const TELEGRAM_MEDIA_GROUP_MAX = 10;
const TELEGRAM_MARKDOWN_PARSE_ERROR_PATTERN =
Expand Down Expand Up @@ -463,6 +464,30 @@ export class TelegramAdapter
return new Response("OK", { status: 200 });
}

if (Number.isInteger(update.update_id)) {
try {
const claimed = await this.chat
.getState()
.setIfNotExists(
`${this.name}:webhook-update:${update.update_id}`,
true,
TELEGRAM_WEBHOOK_UPDATE_TTL_MS
);
if (!claimed) {
this.logger.debug("Ignoring duplicate Telegram webhook update", {
updateId: update.update_id,
});
return new Response("OK", { status: 200 });
}
} catch (error) {
this.logger.warn("Failed to claim Telegram webhook update", {
error: String(error),
updateId: update.update_id,
});
return new Response("Service unavailable", { status: 503 });
}
}

try {
this.processUpdate(update, options);
} catch (error) {
Expand Down