Skip to content

Commit c02e393

Browse files
authored
fix(telegram): route poll answers into agent turns
Route public poll votes through Telegram’s authorized inbound turn path while preserving chat/topic origin and durable ordering. Surface unsupported routing without duplicating sent polls. Co-authored-by: clawSean <[email protected]>
1 parent dedfc01 commit c02e393

32 files changed

Lines changed: 2206 additions & 124 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/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;
Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
// Telegram public-poll answer handler registration.
2+
import type { ChatMember } from "grammy/types";
3+
import { danger, logVerbose } from "openclaw/plugin-sdk/runtime-env";
4+
import type { TelegramHandlerAuthorizationRuntime } from "./bot-handlers.authorization.runtime.js";
5+
import type { TelegramHandlerMessageRuntime } from "./bot-handlers.message.runtime.js";
6+
import type { RegisterTelegramHandlerParams } from "./bot-native-commands.js";
7+
import {
8+
isTelegramSpooledReplayUpdate,
9+
recordTelegramMessageProcessingResult,
10+
} from "./bot-processing-outcome.js";
11+
import { getPreparedTelegramPollAnswer } from "./poll-answer-context.js";
12+
import { findTelegramPollRegistryEntry, retireTelegramPollRegistryEntry } from "./poll-registry.js";
13+
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,
26+
authorizationRuntime: TelegramHandlerAuthorizationRuntime,
27+
) {
28+
const { resolveTelegramEventAuthorizationContext, authorizeTelegramEventSender } =
29+
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+
});
49+
50+
// Telegram emits poll_answer only for non-anonymous polls, and the update omits
51+
// chat/thread data. The send path records that origin in the keyed plugin store.
52+
bot.on("poll_answer", async (ctx) => {
53+
try {
54+
const pollAnswer = ctx.pollAnswer;
55+
if (!pollAnswer || shouldSkipUpdate(ctx)) {
56+
return;
57+
}
58+
const optionIds = pollAnswer.option_ids ?? [];
59+
const user = pollAnswer.user;
60+
// Retractions have no selection to route. Bot voters and voter_chat-only
61+
// answers have no user identity that can pass the sender authorization gate.
62+
if (optionIds.length === 0 || !user || user.is_bot) {
63+
return;
64+
}
65+
66+
// A true miss is a safe no-op. Store failures throw so durable ingress can
67+
// release the claim and replay instead of permanently dropping the vote.
68+
const pollId = pollAnswer.poll_id;
69+
const prepared = getPreparedTelegramPollAnswer(ctx.update);
70+
const entry = prepared
71+
? prepared.entry
72+
: await findTelegramPollRegistryEntry({ pollId, accountId });
73+
if (!entry) {
74+
logVerbose(`telegram: poll_answer for poll ${pollId} has no registry entry; skipping`);
75+
return;
76+
}
77+
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;
81+
const senderId = user?.id != null ? String(user.id) : "";
82+
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+
}
93+
const authorizationCfg = telegramDeps.getRuntimeConfig();
94+
const eventAuthContext = await resolveTelegramEventAuthorizationContext({
95+
cfg: authorizationCfg,
96+
chatId,
97+
isGroup,
98+
isForum,
99+
senderId,
100+
messageThreadId: entry.messageThreadId,
101+
});
102+
const senderAuthorization = await authorizeTelegramEventSender({
103+
chatId,
104+
chatTitle: "title" in entry.chat ? entry.chat.title : undefined,
105+
isGroup,
106+
senderId,
107+
senderUsername,
108+
// Poll votes and reactions are both user-originated updates attached to
109+
// bot-created UI, so they share the reaction authorization boundary.
110+
mode: "reaction",
111+
context: eventAuthContext,
112+
});
113+
if (!senderAuthorization) {
114+
return;
115+
}
116+
117+
// poll_answer has no thread id. A DM poll without persisted topic context
118+
// cannot satisfy requireTopic and must not wake the base DM session.
119+
if (!isGroup) {
120+
const requireTopic = (
121+
eventAuthContext.groupConfig as { requireTopic?: boolean } | undefined
122+
)?.requireTopic;
123+
if (requireTopic === true && eventAuthContext.dmThreadId == null) {
124+
logVerbose(
125+
`Blocked telegram poll_answer in DM ${chatId}: requireTopic=true but topic unknown`,
126+
);
127+
return;
128+
}
129+
}
130+
131+
const optionLabels = optionIds.map((index) => entry.options[index] ?? `option ${index}`);
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,
146+
});
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+
},
159+
});
160+
recordTelegramMessageProcessingResult(result);
161+
logVerbose(`telegram: poll_answer dispatched for poll ${pollId} by ${senderId}`);
162+
} catch (err) {
163+
runtime.error?.(danger(`telegram poll_answer handler failed: ${String(err)}`));
164+
if (isTelegramSpooledReplayUpdate(ctx.update)) {
165+
recordTelegramMessageProcessingResult({ kind: "failed-retryable", error: err });
166+
return;
167+
}
168+
throw err;
169+
}
170+
});
171+
}

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +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 { registerTelegramPollHandlers } from "./bot-handlers.poll-answer.runtime.js";
89
import { registerTelegramReactionHandler } from "./bot-handlers.reaction.runtime.js";
910
import type { RegisterTelegramHandlerParams } from "./bot-native-commands.js";
1011

@@ -14,6 +15,7 @@ export const registerTelegramHandlers = (params: RegisterTelegramHandlerParams)
1415
const inboundRuntime = createTelegramHandlerInboundRuntime(params, messageRuntime);
1516

1617
registerTelegramReactionHandler(params, messageRuntime, authorizationRuntime);
18+
registerTelegramPollHandlers(params, messageRuntime, authorizationRuntime);
1719
registerTelegramCallbackQueryHandler(params, messageRuntime, authorizationRuntime);
1820
registerTelegramMigrationHandler(params);
1921
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)