fix: refine telegram reactions (#964) (thanks @bohdanpodvirnyi)

This commit is contained in:
Peter Steinberger
2026-01-15 17:20:17 +00:00
parent f12c1b391f
commit 2b1c26f900
13 changed files with 157 additions and 28 deletions

View File

@@ -0,0 +1,11 @@
import { API_CONSTANTS } from "grammy";
type TelegramUpdateType = (typeof API_CONSTANTS.ALL_UPDATE_TYPES)[number];
export function resolveTelegramAllowedUpdates(): ReadonlyArray<TelegramUpdateType> {
const updates = [...API_CONSTANTS.DEFAULT_UPDATE_TYPES] as TelegramUpdateType[];
if (!updates.includes("message_reaction")) {
updates.push("message_reaction");
}
return updates;
}

View File

@@ -151,6 +151,7 @@ describe("createTelegramBot", () => {
setMessageReactionSpy.mockReset();
answerCallbackQuerySpy.mockReset();
setMyCommandsSpy.mockReset();
wasSentByBot.mockReset();
middlewareUseSpy.mockReset();
sequentializeSpy.mockReset();
botCtorSpy.mockReset();
@@ -2132,6 +2133,99 @@ describe("createTelegramBot", () => {
);
});
it("skips reaction in own mode when message is not sent by bot", async () => {
onSpy.mockReset();
enqueueSystemEvent.mockReset();
wasSentByBot.mockReturnValue(false);
loadConfig.mockReturnValue({
channels: {
telegram: { dmPolicy: "open", reactionNotifications: "own" },
},
});
createTelegramBot({ token: "tok" });
const handler = getOnHandler("message_reaction") as (
ctx: Record<string, unknown>,
) => Promise<void>;
await handler({
update: { update_id: 503 },
messageReaction: {
chat: { id: 1234, type: "private" },
message_id: 99,
user: { id: 9, first_name: "Ada" },
date: 1736380800,
old_reaction: [],
new_reaction: [{ type: "emoji", emoji: "🎉" }],
},
});
expect(enqueueSystemEvent).not.toHaveBeenCalled();
});
it("allows reaction in own mode when message is sent by bot", async () => {
onSpy.mockReset();
enqueueSystemEvent.mockReset();
wasSentByBot.mockReturnValue(true);
loadConfig.mockReturnValue({
channels: {
telegram: { dmPolicy: "open", reactionNotifications: "own" },
},
});
createTelegramBot({ token: "tok" });
const handler = getOnHandler("message_reaction") as (
ctx: Record<string, unknown>,
) => Promise<void>;
await handler({
update: { update_id: 503 },
messageReaction: {
chat: { id: 1234, type: "private" },
message_id: 99,
user: { id: 9, first_name: "Ada" },
date: 1736380800,
old_reaction: [],
new_reaction: [{ type: "emoji", emoji: "🎉" }],
},
});
expect(enqueueSystemEvent).toHaveBeenCalledTimes(1);
});
it("skips reaction from bot users", async () => {
onSpy.mockReset();
enqueueSystemEvent.mockReset();
wasSentByBot.mockReturnValue(true);
loadConfig.mockReturnValue({
channels: {
telegram: { dmPolicy: "open", reactionNotifications: "all" },
},
});
createTelegramBot({ token: "tok" });
const handler = getOnHandler("message_reaction") as (
ctx: Record<string, unknown>,
) => Promise<void>;
await handler({
update: { update_id: 503 },
messageReaction: {
chat: { id: 1234, type: "private" },
message_id: 99,
user: { id: 9, first_name: "Bot", is_bot: true },
date: 1736380800,
old_reaction: [],
new_reaction: [{ type: "emoji", emoji: "🎉" }],
},
});
expect(enqueueSystemEvent).not.toHaveBeenCalled();
});
it("skips reaction removal (only processes added reactions)", async () => {
onSpy.mockReset();
enqueueSystemEvent.mockReset();

View File

@@ -40,6 +40,7 @@ import {
type TelegramUpdateKeyContext,
} from "./bot-updates.js";
import { resolveTelegramFetch } from "./fetch.js";
import { wasSentByBot } from "./sent-message-cache.js";
export type TelegramBotOptions = {
token: string;
@@ -317,6 +318,8 @@ export function createTelegramBot(opts: TelegramBotOptions) {
// Resolve reaction notification mode (default: "off")
const reactionMode = telegramCfg.reactionNotifications ?? "off";
if (reactionMode === "off") return;
if (user?.is_bot) return;
if (reactionMode === "own" && !wasSentByBot(chatId, messageId)) return;
// Detect added reactions
const oldEmojis = new Set(

View File

@@ -5,6 +5,7 @@ import { computeBackoff, sleepWithAbort } from "../infra/backoff.js";
import { formatDurationMs } from "../infra/format-duration.js";
import type { RuntimeEnv } from "../runtime.js";
import { resolveTelegramAccount } from "./accounts.js";
import { resolveTelegramAllowedUpdates } from "./allowed-updates.js";
import { createTelegramBot } from "./bot.js";
import { makeProxyFetch } from "./proxy.js";
import { readTelegramUpdateOffset, writeTelegramUpdateOffset } from "./update-offset-store.js";
@@ -33,8 +34,8 @@ export function createTelegramRunnerOptions(cfg: ClawdbotConfig): RunOptions<unk
fetch: {
// Match grammY defaults
timeout: 30,
// Request reaction updates from Telegram
allowed_updates: ["message", "message_reaction"],
// Request reactions without dropping default update types.
allowed_updates: resolveTelegramAllowedUpdates(),
},
// Suppress grammY getUpdates stack traces; we log concise errors ourselves.
silent: true,
@@ -114,23 +115,6 @@ export async function monitorTelegramProvider(opts: MonitorTelegramOpts = {}) {
},
});
const log = opts.runtime?.log ?? console.log;
// When using polling mode, ensure no webhook is active
if (!opts.useWebhook) {
try {
const webhookInfo = await bot.api.getWebhookInfo();
if (webhookInfo.url) {
await bot.api.deleteWebhook({ drop_pending_updates: false });
log(`telegram: deleted webhook to enable polling`);
}
} catch (err) {
(opts.runtime?.error ?? console.error)(
`telegram: failed to check/delete webhook: ${String(err)}`,
);
}
}
if (opts.useWebhook) {
await startTelegramWebhook({
token,
@@ -148,6 +132,7 @@ export async function monitorTelegramProvider(opts: MonitorTelegramOpts = {}) {
}
// Use grammyjs/runner for concurrent update processing
const log = opts.runtime?.log ?? console.log;
let restartAttempts = 0;
while (!opts.abortSignal?.aborted) {

View File

@@ -16,9 +16,10 @@ const createTelegramBotSpy = vi.fn(() => ({
stop: stopSpy,
}));
vi.mock("grammy", () => ({
webhookCallback: () => handlerSpy,
}));
vi.mock("grammy", async (importOriginal) => {
const actual = await importOriginal<typeof import("grammy")>();
return { ...actual, webhookCallback: () => handlerSpy };
});
vi.mock("./bot.js", () => ({
createTelegramBot: (...args: unknown[]) => createTelegramBotSpy(...args),

View File

@@ -5,6 +5,7 @@ import type { ClawdbotConfig } from "../config/config.js";
import { formatErrorMessage } from "../infra/errors.js";
import type { RuntimeEnv } from "../runtime.js";
import { defaultRuntime } from "../runtime.js";
import { resolveTelegramAllowedUpdates } from "./allowed-updates.js";
import { createTelegramBot } from "./bot.js";
export async function startTelegramWebhook(opts: {
@@ -63,7 +64,7 @@ export async function startTelegramWebhook(opts: {
await bot.api.setWebhook(publicUrl, {
secret_token: opts.secret,
allowed_updates: ["message", "message_reaction"],
allowed_updates: resolveTelegramAllowedUpdates(),
});
await new Promise<void>((resolve) => server.listen(port, host, resolve));