Skip to content

Commit ef3ffac

Browse files
committed
fix(telegram): dispatch poll answers as inbound turns
1 parent e3ebc4f commit ef3ffac

32 files changed

Lines changed: 1643 additions & 351 deletions

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

Lines changed: 67 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -164,11 +164,19 @@ const sendDurableMessageBatch = vi.fn(
164164
} as const;
165165
},
166166
);
167-
const sendPollTelegram = vi.fn(async () => ({
168-
messageId: "790",
169-
chatId: "123",
170-
pollId: "poll-1",
171-
}));
167+
const sendPollTelegram = vi.fn(
168+
async (): Promise<{
169+
messageId: string;
170+
chatId: string;
171+
pollId: string;
172+
pollAnswerRouting?: "enabled" | "unavailable";
173+
warning?: string;
174+
}> => ({
175+
messageId: "790",
176+
chatId: "123",
177+
pollId: "poll-1",
178+
}),
179+
);
172180
const sendStickerTelegram = vi.fn(async () => ({
173181
messageId: "456",
174182
chatId: "123",
@@ -1355,6 +1363,60 @@ describe("handleTelegramAction", () => {
13551363
expect(details.pollId).toBe("poll-1");
13561364
});
13571365

1366+
it("returns a model-visible warning when public poll routing is unavailable", async () => {
1367+
sendPollTelegram.mockResolvedValueOnce({
1368+
messageId: "790",
1369+
chatId: "123",
1370+
pollId: "poll-1",
1371+
pollAnswerRouting: "unavailable",
1372+
warning: "Poll answers cannot reach the agent. Ask the user to reply in text.",
1373+
});
1374+
1375+
const result = await handleTelegramAction(
1376+
{
1377+
action: "poll",
1378+
to: "@testchannel",
1379+
question: "Ready?",
1380+
answers: ["Yes", "No"],
1381+
isAnonymous: false,
1382+
},
1383+
telegramConfig(),
1384+
);
1385+
1386+
expect(resultDetails(result)).toMatchObject({
1387+
pollAnswerRouting: "unavailable",
1388+
warning: "Poll answers cannot reach the agent. Ask the user to reply in text.",
1389+
});
1390+
});
1391+
1392+
it("returns the public-poll opt-in for default anonymous polls", async () => {
1393+
sendPollTelegram.mockResolvedValueOnce({
1394+
messageId: "790",
1395+
chatId: "123",
1396+
pollId: "poll-1",
1397+
pollAnswerRouting: "unavailable",
1398+
warning:
1399+
"Poll sent anonymously, so Telegram does not identify voters and answers cannot reach the agent. Send a public poll to route votes into this conversation.",
1400+
});
1401+
1402+
const result = await handleTelegramAction(
1403+
{
1404+
action: "poll",
1405+
to: "@testchannel",
1406+
question: "Ready?",
1407+
answers: ["Yes", "No"],
1408+
},
1409+
telegramConfig(),
1410+
);
1411+
1412+
const options = requireRecord(mockCall(sendPollTelegram, 0, "anonymous poll")[2], "options");
1413+
expect(options.isAnonymous).toBeUndefined();
1414+
expect(resultDetails(result)).toMatchObject({
1415+
pollAnswerRouting: "unavailable",
1416+
warning: expect.stringContaining("Send a public poll"),
1417+
});
1418+
});
1419+
13581420
it("rejects fractional poll durations before sending", async () => {
13591421
await expect(
13601422
handleTelegramAction(

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -750,6 +750,8 @@ export async function handleTelegramAction(
750750
messageId: result.messageId,
751751
chatId: result.chatId,
752752
pollId: result.pollId,
753+
...(result.pollAnswerRouting ? { pollAnswerRouting: result.pollAnswerRouting } : {}),
754+
...(result.warning ? { warning: result.warning } : {}),
753755
});
754756
}
755757

‎extensions/telegram/src/allowed-updates.ts‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,6 @@ type TelegramUpdateType = (typeof API_CONSTANTS.ALL_UPDATE_TYPES)[number];
66
const DEFAULT_TELEGRAM_UPDATE_TYPES: ReadonlyArray<TelegramUpdateType> =
77
API_CONSTANTS.DEFAULT_UPDATE_TYPES;
88

9-
// grammy's DEFAULT_UPDATE_TYPES omits message_reaction, so it must always be opted in.
10-
// channel_post and poll_answer are in the current defaults, but reaction/channel-post/poll-vote
11-
// routing all *depend* on receiving those updates; the idempotent guards below pin that
12-
// dependency so the features keep working if a future grammy/Telegram default ever drops them.
139
export function resolveTelegramAllowedUpdates(): ReadonlyArray<TelegramUpdateType> {
1410
const updates = [...DEFAULT_TELEGRAM_UPDATE_TYPES] as TelegramUpdateType[];
1511
if (!updates.includes("message_reaction")) {
@@ -18,8 +14,5 @@ export function resolveTelegramAllowedUpdates(): ReadonlyArray<TelegramUpdateTyp
1814
if (!updates.includes("channel_post")) {
1915
updates.push("channel_post");
2016
}
21-
if (!updates.includes("poll_answer")) {
22-
updates.push("poll_answer");
23-
}
2417
return updates;
2518
}

‎extensions/telegram/src/bot-core.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import {
3838
ensureTelegramMessageProcessingResult,
3939
getTelegramSpooledReplayDeferredParticipant,
4040
isTelegramSpooledReplayUpdate,
41+
recordTelegramMessageProcessingResult,
4142
runWithTelegramUpdateProcessingFrame,
4243
TelegramSpooledReplayProcessingError,
4344
} from "./bot-processing-outcome.js";
@@ -63,6 +64,10 @@ import {
6364
recordTelegramGroupHistoryEntry,
6465
} from "./group-history-window.js";
6566
import { registerTelegramOutboundGroupHistoryRecorder } from "./outbound-message-context.js";
67+
import {
68+
prepareTelegramPollAnswerContext,
69+
settleTelegramPollAnswerContext,
70+
} from "./poll-answer-context.js";
6671
import { formatTelegramRawUpdateForLog } from "./raw-update-log.js";
6772
import { createTelegramSendChatActionHandler } from "./sendchataction-401-backoff.js";
6873
import { getTelegramSequentialConstraints } from "./sequential-key.js";
@@ -234,8 +239,30 @@ export function createTelegramBotCore(
234239
await next();
235240
});
236241

242+
// poll_answer omits its chat and topic. Resolve the send-time route before
243+
// sequentialize so the vote shares the same lane as ordinary session turns.
244+
bot.use(async (ctx, next) => {
245+
try {
246+
prepareTelegramPollAnswerContext({ update: ctx.update, accountId: account.accountId });
247+
} catch (error) {
248+
if (isTelegramSpooledReplayUpdate(ctx.update)) {
249+
recordTelegramMessageProcessingResult({ kind: "failed-retryable", error });
250+
return;
251+
}
252+
throw error;
253+
}
254+
await next();
255+
});
256+
237257
bot.use(botRuntime.sequentialize(getTelegramSequentialConstraints));
238258

259+
// A fast vote can know its route before outbound verification finishes. Hold
260+
// only that route's sequential lane until registration succeeds or declines it.
261+
bot.use(async (ctx, next) => {
262+
await settleTelegramPollAnswerContext({ update: ctx.update, accountId: account.accountId });
263+
await next();
264+
});
265+
239266
const rawUpdateLogger = createSubsystemLogger("gateway/channels/telegram/raw-update");
240267

241268
bot.use(async (ctx, next) => {

‎extensions/telegram/src/bot-handlers.message-lifecycle.runtime.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ export function createTelegramMessageLifecycleRuntime({
146146
return { process: true, claims: claim.kind === "claimed" ? [claim.handle] : [] };
147147
};
148148
const buildSyntheticTextMessage = (params: {
149-
base: Message;
149+
base: Message.ServiceMessage;
150150
text: string;
151151
entities?: Message["entities"];
152152
date?: number;

‎extensions/telegram/src/bot-handlers.poll-answer.runtime.ts‎

Lines changed: 81 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,51 @@
11
// Telegram public-poll answer handler registration.
2+
import type { ChatMember } from "grammy/types";
23
import { danger, logVerbose } from "openclaw/plugin-sdk/runtime-env";
34
import type { TelegramHandlerAuthorizationRuntime } from "./bot-handlers.authorization.runtime.js";
5+
import type { TelegramHandlerMessageRuntime } from "./bot-handlers.message.runtime.js";
46
import type { RegisterTelegramHandlerParams } from "./bot-native-commands.js";
57
import {
68
isTelegramSpooledReplayUpdate,
79
recordTelegramMessageProcessingResult,
810
} from "./bot-processing-outcome.js";
9-
import { resolveTelegramForumFlag } from "./bot/helpers.js";
10-
import { resolveTelegramConversationRoute } from "./conversation-route.js";
11-
import { findTelegramPollRegistryEntry } from "./poll-registry.js";
11+
import { getPreparedTelegramPollAnswer } from "./poll-answer-context.js";
12+
import { findTelegramPollRegistryEntry, retireTelegramPollRegistryEntry } from "./poll-registry.js";
1213

13-
export function registerTelegramPollAnswerHandler(
14-
{
15-
accountId,
16-
bot,
17-
runtime,
18-
telegramDeps,
19-
resolveTelegramGroupConfig,
20-
shouldSkipUpdate,
21-
}: RegisterTelegramHandlerParams,
14+
function isCurrentTelegramChatMember(member: ChatMember): boolean {
15+
return (
16+
member.status === "creator" ||
17+
member.status === "administrator" ||
18+
member.status === "member" ||
19+
(member.status === "restricted" && member.is_member)
20+
);
21+
}
22+
23+
export function registerTelegramPollHandlers(
24+
{ accountId, bot, runtime, telegramDeps, shouldSkipUpdate }: RegisterTelegramHandlerParams,
25+
messageRuntime: TelegramHandlerMessageRuntime,
2226
authorizationRuntime: TelegramHandlerAuthorizationRuntime,
2327
) {
2428
const { resolveTelegramEventAuthorizationContext, authorizeTelegramEventSender } =
2529
authorizationRuntime;
30+
const { buildSyntheticTextMessage, buildSyntheticContext, processMessageWithReplyChain } =
31+
messageRuntime;
32+
33+
bot.on("poll", async (ctx) => {
34+
try {
35+
const poll = ctx.poll;
36+
if (!poll?.is_closed || shouldSkipUpdate(ctx)) {
37+
return;
38+
}
39+
await retireTelegramPollRegistryEntry({ accountId, pollId: poll.id });
40+
} catch (err) {
41+
runtime.error?.(danger(`telegram poll handler failed: ${String(err)}`));
42+
if (isTelegramSpooledReplayUpdate(ctx.update)) {
43+
recordTelegramMessageProcessingResult({ kind: "failed-retryable", error: err });
44+
return;
45+
}
46+
throw err;
47+
}
48+
});
2649

2750
// Telegram emits poll_answer only for non-anonymous polls, and the update omits
2851
// chat/thread data. The send path records that origin in the keyed plugin store.
@@ -43,24 +66,30 @@ export function registerTelegramPollAnswerHandler(
4366
// A true miss is a safe no-op. Store failures throw so durable ingress can
4467
// release the claim and replay instead of permanently dropping the vote.
4568
const pollId = pollAnswer.poll_id;
46-
const entry = await findTelegramPollRegistryEntry({ pollId, accountId });
69+
const prepared = getPreparedTelegramPollAnswer(ctx.update);
70+
const entry = prepared
71+
? prepared.entry
72+
: await findTelegramPollRegistryEntry({ pollId, accountId });
4773
if (!entry) {
4874
logVerbose(`telegram: poll_answer for poll ${pollId} has no registry entry; skipping`);
4975
return;
5076
}
5177

52-
const chatId = Number(entry.chatId);
53-
const isGroup = entry.chatId.startsWith("-");
54-
const isForum = isGroup
55-
? await resolveTelegramForumFlag({
56-
chatId,
57-
chatType: "supergroup",
58-
isGroup,
59-
getChat: bot.api.getChat.bind(bot.api),
60-
})
61-
: false;
78+
const chatId = entry.chat.id;
79+
const isGroup = entry.chat.type === "group" || entry.chat.type === "supergroup";
80+
const isForum = entry.chat.type === "supergroup" && entry.chat.is_forum === true;
6281
const senderId = user?.id != null ? String(user.id) : "";
6382
const senderUsername = user?.username ?? "";
83+
if (!isGroup && user.id !== chatId) {
84+
logVerbose(`Blocked forwarded telegram poll_answer for DM ${chatId} from ${senderId}`);
85+
return;
86+
}
87+
if (isGroup && !isCurrentTelegramChatMember(await bot.api.getChatMember(chatId, user.id))) {
88+
logVerbose(
89+
`Blocked forwarded telegram poll_answer for group ${chatId} from non-member ${senderId}`,
90+
);
91+
return;
92+
}
6493
const authorizationCfg = telegramDeps.getRuntimeConfig();
6594
const eventAuthContext = await resolveTelegramEventAuthorizationContext({
6695
cfg: authorizationCfg,
@@ -72,6 +101,7 @@ export function registerTelegramPollAnswerHandler(
72101
});
73102
const senderAuthorization = await authorizeTelegramEventSender({
74103
chatId,
104+
chatTitle: "title" in entry.chat ? entry.chat.title : undefined,
75105
isGroup,
76106
senderId,
77107
senderUsername,
@@ -98,49 +128,37 @@ export function registerTelegramPollAnswerHandler(
98128
}
99129
}
100130

101-
const senderName = user
102-
? [user.first_name, user.last_name].filter(Boolean).join(" ").trim() || user.username
103-
: undefined;
104-
const senderUsernameLabel = user?.username ? `@${user.username}` : undefined;
105-
let senderLabel = senderName;
106-
if (senderName && senderUsernameLabel) {
107-
senderLabel = `${senderName} (${senderUsernameLabel})`;
108-
} else if (!senderName && senderUsernameLabel) {
109-
senderLabel = senderUsernameLabel;
110-
}
111-
if (!senderLabel && user?.id) {
112-
senderLabel = `id:${user.id}`;
113-
}
114-
senderLabel = senderLabel || "unknown";
115-
116131
const optionLabels = optionIds.map((index) => entry.options[index] ?? `option ${index}`);
117-
const text = `Telegram poll vote: "${entry.question}" — ${senderLabel} voted: ${optionLabels.join(
118-
", ",
119-
)}`;
120-
const resolvedThreadId = eventAuthContext.resolvedThreadId;
121-
const routeThreadId =
122-
resolvedThreadId ?? eventAuthContext.dmThreadId ?? entry.messageThreadId;
123-
const { topicConfig } = resolveTelegramGroupConfig(
124-
chatId,
125-
routeThreadId,
126-
eventAuthContext.cfg,
127-
);
128-
const { route } = resolveTelegramConversationRoute({
129-
cfg: eventAuthContext.cfg,
130-
accountId,
131-
chatId,
132-
isGroup,
133-
resolvedThreadId,
134-
replyThreadId: routeThreadId,
135-
senderId,
136-
topicAgentId: topicConfig?.agentId,
132+
const text = `Poll response to "${entry.question}": ${optionLabels.join(", ")}`;
133+
const syntheticMessage = buildSyntheticTextMessage({
134+
base: {
135+
message_id: entry.messageId,
136+
date: Math.floor(Date.now() / 1000),
137+
chat: entry.chat,
138+
...(entry.messageThreadId == null
139+
? {}
140+
: {
141+
message_thread_id: entry.messageThreadId,
142+
}),
143+
},
144+
from: user,
145+
text,
137146
});
138-
139-
telegramDeps.enqueueSystemEvent(text, {
140-
sessionKey: route.sessionKey,
141-
contextKey: `telegram:poll_answer:${pollId}:${user?.id ?? "anon"}:${optionIds.join("-")}`,
147+
const result = await processMessageWithReplyChain({
148+
ctx: buildSyntheticContext(ctx, syntheticMessage),
149+
msg: syntheticMessage,
150+
allMedia: [],
151+
storeAllowFrom: eventAuthContext.storeAllowFrom,
152+
options: {
153+
forceWasMentioned: true,
154+
messageIdOverride:
155+
typeof ctx.update.update_id === "number"
156+
? String(ctx.update.update_id)
157+
: `poll:${pollId}:${user.id}:${optionIds.join("-")}`,
158+
},
142159
});
143-
logVerbose(`telegram: poll_answer event enqueued for poll ${pollId} by ${senderLabel}`);
160+
recordTelegramMessageProcessingResult(result);
161+
logVerbose(`telegram: poll_answer dispatched for poll ${pollId} by ${senderId}`);
144162
} catch (err) {
145163
runtime.error?.(danger(`telegram poll_answer handler failed: ${String(err)}`));
146164
if (isTelegramSpooledReplayUpdate(ctx.update)) {

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { createTelegramHandlerInboundRuntime } from "./bot-handlers.inbound.runt
55
import { registerTelegramMessageHandlers } from "./bot-handlers.message-events.runtime.js";
66
import { createTelegramHandlerMessageRuntime } from "./bot-handlers.message.runtime.js";
77
import { registerTelegramMigrationHandler } from "./bot-handlers.migration.runtime.js";
8-
import { registerTelegramPollAnswerHandler } from "./bot-handlers.poll-answer.runtime.js";
8+
import { registerTelegramPollHandlers } from "./bot-handlers.poll-answer.runtime.js";
99
import { registerTelegramReactionHandler } from "./bot-handlers.reaction.runtime.js";
1010
import type { RegisterTelegramHandlerParams } from "./bot-native-commands.js";
1111

@@ -15,7 +15,7 @@ export const registerTelegramHandlers = (params: RegisterTelegramHandlerParams)
1515
const inboundRuntime = createTelegramHandlerInboundRuntime(params, messageRuntime);
1616

1717
registerTelegramReactionHandler(params, messageRuntime, authorizationRuntime);
18-
registerTelegramPollAnswerHandler(params, authorizationRuntime);
18+
registerTelegramPollHandlers(params, messageRuntime, authorizationRuntime);
1919
registerTelegramCallbackQueryHandler(params, messageRuntime, authorizationRuntime);
2020
registerTelegramMigrationHandler(params);
2121
registerTelegramMessageHandlers(params, messageRuntime, authorizationRuntime, inboundRuntime);

‎extensions/telegram/src/bot.create-telegram-bot.test-harness.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,7 @@ const telegramBotRuntimeForTest = {
457457
setMyCommands: grammySpies.setMyCommandsSpy,
458458
getMe: grammySpies.getMeSpy,
459459
getChat: grammySpies.getChatSpy,
460+
getChatMember: grammySpies.getChatSpy,
460461
sendMessage: grammySpies.sendMessageSpy,
461462
sendAnimation: grammySpies.sendAnimationSpy,
462463
sendPhoto: grammySpies.sendPhotoSpy,

0 commit comments

Comments
 (0)