|
| 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 | +} |
0 commit comments