Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(webhook): key poll.vote on the millisecond the voter changed it
Yudhi Armyndharis724884a91ea1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 756c6d074..8efd3cddf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added-- Report poll votes as a `poll.vote` webhook and WebSocket event on whatsapp-web.js: the poll, chat, voter, the option texts now selected (`[]` when the vote is cleared), the poll question when WhatsApp Web still holds the poll, and the time of the change; the JavaScript, Python, Go and Java SDKs list the event name from SDK 0.7.0 ([#1922](https://github.com/rmyndharis/OpenWA/pull/1922)). Thanks @laviniarochaprec.+- Report poll votes as a `poll.vote` webhook and WebSocket event on whatsapp-web.js: the poll, chat, voter, the option texts now selected (`[]` when the vote is cleared), the poll question when WhatsApp Web still holds the poll, and the time of the change in seconds and in milliseconds (`timestampMs`, which orders a voter's changes within one second); the JavaScript, Python, Go and Java SDKs list the event name from SDK 0.7.0 ([#1922](https://github.com/rmyndharis/OpenWA/pull/1922)). Thanks @laviniarochaprec.- Add Number Checker page in dashboard for single and bulk WhatsApp recipient pre-validation, in every dashboard language (#1865). Thanks @Purushotham-Prajapati-24.- Add the opt-in `message.receipt` event for per-recipient group and status receipts on Baileys, sent to the webhooks and `/events` subscribers that name it (#1748); the JavaScript, Python, Go and Java SDKs list the event name from SDK 0.7.0. Receipts are bounded per webhook: a quarter of `WEBHOOK_DISPATCH_CONCURRENCY` deliveries run at once, shared by a session's receipt webhooks, three quarters of `WEBHOOK_DISPATCH_MAX_QUEUED` events wait for each, and further receipts are dropped and counted in `openwa_webhook_delivery_failures_total`. Thanks @KGMA74, and @berodcdev for the request.- Record plugin install, update, uninstall, enable, disable, configuration and session activation changes in the audit log.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex f9996c5c0..a7cb7b34b 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -7287,7 +7287,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve| `session.reconnect_loop` | Every 5th consecutive reconnect attempt is scheduled (attempt 5, 10, 15, …) — the session is failing to come back up | `{ sessionId, attempts, nextDelayMs }` || `presence.update` | A subscribed chat's presence changed — someone came online, started typing, or stopped. Only actual CHANGES are dispatched: WhatsApp repeats itself freely, and every repeat would otherwise be a delivery | `{ sessionId, chatId, participants: [{ id, state, lastSeen? }], groupOnlineCount? }` — `state` is `available`/`unavailable`/`composing`/`recording`/`paused`; `lastSeen` is epoch **seconds** and absent when the contact hides it. Requires `POST .../presence/subscribe` first, and Baileys — whatsapp-web.js cannot observe presence || `event.response` | A guest answered a WhatsApp event invitation (going, not going, maybe). **Baileys only**; see the payload note below | `{ sessionId, eventMessageId, chatId, responderId, contact?, fromMe, response, extraGuestCount?, eventName?, responseMessageId, timestamp }`. `response` is `going`/`not_going`/`maybe`/`unknown`; `timestamp` is epoch **seconds** on the guest's clock. Order a guest's answers by `timestamp`, not by delivery |-| `poll.vote` | A voter selected or cleared options on a poll. **whatsapp-web.js only**; see the payload note below | `{ sessionId, pollMessageId, chatId, voterId, selectedOptions, pollName?, timestamp }`. `selectedOptions` holds the option texts now selected, `[]` when the vote was cleared; `timestamp` is epoch **seconds** on the voter's clock. Order a voter's changes by `timestamp`, not by delivery |+| `poll.vote` | A voter selected or cleared options on a poll. **whatsapp-web.js only**; see the payload note below | `{ sessionId, pollMessageId, chatId, voterId, selectedOptions, pollName?, timestamp, timestampMs }`. `selectedOptions` holds the option texts now selected, `[]` when the vote was cleared; `timestamp` is epoch **seconds** and `timestampMs` the same instant in milliseconds, both on the voter's clock. Order a voter's changes by `timestampMs`, not by delivery || `session.restriction` | WhatsApp places a restriction on the account, or lifts one. Deduped: an unchanged restriction is not re-announced, and a lift is only sent when one was in force | `{ sessionId, active, kind, code, expiresAt }` — `active` is `false` for a lift and `kind`/`code` then describe the restriction that ended; `expiresAt` is an ISO timestamp or `null`. See `restriction` on the session response for the `kind` values || `session.status` | The session status transitions | `{ sessionId, status }` where `status` is one of `created` / `initializing` / `qr_ready` / `authenticating` / `ready` / `disconnected` / `action_required` / `failed` || `group.join` | Participant(s) are added to or join a group this session is in | `{ groupId, actorId?, participantIds, timestamp }`. `actorId` is the admin/inviter when known. **Baileys**: a session added to or joining a group reports only its own id in `participantIds` (members added with it are not listed) |@@ -7354,11 +7354,12 @@ Existing stored mappings from older releases have mixed origins, so an upgrade r> "voterId": "[email protected]",> "selectedOptions": ["Done"],> "pollName": "Did you finish the report?",-> "timestamp": 1786000000+> "timestamp": 1786000000,+> "timestampMs": 1786000000123> }> ```>-> `selectedOptions` are the option texts exactly as they appear on the poll, the same strings [`vote-poll`](#post-apisessionssessionidmessagesvote-poll) takes. It is the voter's whole current selection, not a delta: `[]` means they cleared their vote, and the event with the latest `timestamp` per `voterId` is the current state. Order by `timestamp` rather than by arrival. `pollName` is present only when WhatsApp Web still holds the poll creation message; without it whatsapp-web.js cannot name the options either, so a vote on such a poll is not reported (a cleared vote still is, with `[]`). Vote counts are not kept by the gateway: tally them from these events. Baileys accepts the subscription and never fires it.+> `selectedOptions` are the option texts exactly as they appear on the poll, the same strings [`vote-poll`](#post-apisessionssessionidmessagesvote-poll) takes. It is the voter's whole current selection, not a delta: `[]` means they cleared their vote, and the event with the latest `timestampMs` per `voterId` is the current state. Order by `timestampMs` rather than by arrival: `timestamp` has one-second resolution, so a voter's changes within one second share it. `pollName` is present only when WhatsApp Web still holds the poll creation message; without it whatsapp-web.js cannot name the options either, so a vote on such a poll is not reported (a cleared vote still is, with `[]`). Vote counts are not kept by the gateway: tally them from these events. Baileys accepts the subscription and never fires it.> WhatsApp also sends a contact's edit, and a reaction in some chats, encrypted under a secret carried by the message it changes. On Baileys they are read with the stored copy of that message, so `message.edited` fires for a message **this session received** and `message.reaction` for one it **received or sent**, while its message store still holds it; an edit or reaction of one the store no longer holds (evicted past `BAILEYS_MESSAGE_STORE_LIMIT`, or from before the number was linked) is not delivered. An edit the account makes from its own phone to its own message is applied under the account's own id the same way, whether it arrives as a plain or as an encrypted edit. whatsapp-web.js gets both already decrypted from WhatsApp Web.@@ -7444,7 +7445,7 @@ Every delivery includes:- `session.restriction`: `restr_{sessionId}_{kind}_{active}_{occurrenceId}`- `presence.update`: `pres_{sessionId}_{chatId}_{hash(participants)}_{occurrenceId}`- `event.response`: `rsvp_{sessionId}_{responseMessageId}` (every answer is its own message with its own id, so no `occurrenceId` salt)-- `poll.vote`: `vote_{sessionId}_{pollMessageId}_{voterId}_{timestamp}_{hash(selectedOptions)}` (each change of a selection carries the voter's own timestamp and the selection is hashed in, so two changes within one second stay distinct and no `occurrenceId` salt is needed)+- `poll.vote`: `vote_{sessionId}_{pollMessageId}_{voterId}_{timestampMs}_{hash(selectedOptions)}` (each change of a selection carries the voter's own millisecond timestamp and the selection is hashed in, so changes within one second stay distinct, including a return to an earlier selection, and no `occurrenceId` salt is needed)- any other event (for example `status.received`): `evt_{event with . replaced by _}_{hash(data)}`Recurring lifecycle events (and `message.reaction` / `message.edited` / `presence.update`) carry the same content across occurrences — the same phone on every reconnect, a constant disconnect reason, a re-applied emoji, or editing the same message multiple times — so they are salted with an `occurrenceId`, a random id minted **once per dispatch and reused across that dispatch's retries**; it is not a timestamp, so two occurrences within the same millisecond still get distinct keys. This gives distinct occurrences distinct keys while keeping retries of one occurrence stable. Message keys are scoped by `sessionId` because WhatsApp message ids are unique per account, not globally.diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex 485415e1c..9bae5bdad 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -1473,7 +1473,7 @@ available_events:- session.restriction # WhatsApp restricted the account, or lifted it (payload: sessionId, active, kind, code, expiresAt)- presence.update # A subscribed chat's presence changed (Baileys only; the subscribe route answers 501 on whatsapp-web.js; payload: sessionId, chatId, participants, groupOnlineCount)- event.response # A guest answered a WhatsApp event invitation (Baileys only; payload: sessionId, eventMessageId, chatId, responderId, response, responseMessageId, timestamp)- - poll.vote # A voter selected or cleared options on a poll (whatsapp-web.js only; payload: sessionId, pollMessageId, chatId, voterId, selectedOptions, pollName, timestamp)+ - poll.vote # A voter selected or cleared options on a poll (whatsapp-web.js only; payload: sessionId, pollMessageId, chatId, voterId, selectedOptions, pollName, timestamp, timestampMs)- call.accepted # A ringing call was answered (Baileys only; payload: sessionId, callId, from, outcome, isVideo, isGroup, timestamp)- call.rejected # A ringing call was declined (Baileys only)- call.missed # A ringing call was never picked up (Baileys only)diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex a906c37c2..92c307fea 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -4038,6 +4038,7 @@ describe('WhatsAppWebJsAdapter vote_update (poll.vote)', () => {selectedOptions: ['Done'],pollName: 'Did you finish the report?',timestamp: 1786000000,+ timestampMs: 1786000000123,});});@@ -4073,6 +4074,7 @@ describe('WhatsAppWebJsAdapter vote_update (poll.vote)', () => {voterId: '[email protected]',selectedOptions: [],timestamp: 1786000000,+ timestampMs: 1786000000123,});expect(event).not.toHaveProperty('pollName');});diff --git a/src/engine/adapters/wwebjs-message-events.ts b/src/engine/adapters/wwebjs-message-events.tsindex 7e300c904..e1f4e25de 100644--- a/src/engine/adapters/wwebjs-message-events.ts+++ b/src/engine/adapters/wwebjs-message-events.ts@@ -396,6 +396,8 @@ export function registerWwebjsMessageEvents(client: Client, host: WwebjsEngineHo});return;}+ // Sender clock, in milliseconds. Without it a re-delivered vote gets a fresh stamp and so a fresh key.+ const interactedAtMs = Math.floor(Number(vote.interractedAtTs) || Date.now());const event: PollVoteEvent = {pollMessageId: readWid(pollId) ?? readWid(raw.parentMsgKey) ?? '',// Direction flag, as Message._getChatId (see message_revoke_everyone).@@ -403,7 +405,8 @@ export function registerWwebjsMessageEvents(client: Client, host: WwebjsEngineHovoterId: readWid(raw.voter) ?? '',selectedOptions,...(poll?.pollName ? { pollName: poll.pollName } : {}),- timestamp: Math.floor((Number(vote.interractedAtTs) || Date.now()) / 1000),+ timestamp: Math.floor(interactedAtMs / 1000),+ timestampMs: interactedAtMs,};host.getCallbacks().onPollVote?.(event);} catch (error) {diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex f35c40972..2874fddc1 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -719,6 +719,11 @@ export interface PollVoteEvent {pollName?: string;/** Unix seconds the voter changed the selection (sender clock). */timestamp: number;+ /**+ * The same instant in Unix milliseconds. Two changes of one voter within a second share `timestamp`, so+ * this is what orders them and tells them apart.+ */+ timestampMs: number;}/**diff --git a/src/modules/session/session-poll-vote-wiring.spec.ts b/src/modules/session/session-poll-vote-wiring.spec.tsindex 70776b358..05ecc61de 100644--- a/src/modules/session/session-poll-vote-wiring.spec.ts+++ b/src/modules/session/session-poll-vote-wiring.spec.ts@@ -10,6 +10,7 @@ describe('poll.vote wiring', () => {selectedOptions: ['Done'],pollName: 'Did you finish the report?',timestamp: 1786000000,+ timestampMs: 1786000000123,};const setup = (live: boolean) => {diff --git a/src/modules/webhook/utils/idempotency.util.spec.ts b/src/modules/webhook/utils/idempotency.util.spec.tsindex fb5840e3c..af1fc11f3 100644--- a/src/modules/webhook/utils/idempotency.util.spec.ts+++ b/src/modules/webhook/utils/idempotency.util.spec.ts@@ -319,6 +319,7 @@ describe('Idempotency Utils', () => {const at = '2026-07-20T00:00:00.000Z';const data = { sessionId: 'A', pollMessageId: 'POLL1', voterId: 'V1', selectedOptions: ['Yes'], timestamp: 100 };const key = generateIdempotencyKey('poll.vote', data, at);+ // Without the millisecond stamp the whole second stands in for it.expect(key).toMatch(/^vote_A_POLL1_V1_100_[0-9a-f]{12}$/);expect(generateIdempotencyKey('poll.vote', data, '2026-07-20T01:00:00.000Z')).toBe(key);// An identical redelivery dedupes, a different selection in the same second does not.@@ -331,6 +332,27 @@ describe('Idempotency Utils', () => {expect(generateIdempotencyKey('poll.vote', { ...data, voterId: 'V2' }, at)).not.toBe(key);});+ // A voter flipping A, B, A within one second: the third change shares the whole second, the selection and so+ // the hash with the first. Under the key of the first it would be dropped by a receiver that dedupes on it,+ // which would then end on B while the voter's choice is A.+ it('keeps a vote that returns to an earlier selection within the same second apart from the first', () => {+ const at = '2026-07-20T00:00:00.000Z';+ const first = {+ sessionId: 'A',+ pollMessageId: 'POLL1',+ voterId: 'V1',+ selectedOptions: ['A'],+ timestamp: 100,+ timestampMs: 100100,+ };+ const third = { ...first, timestampMs: 100900 };+ expect(generateIdempotencyKey('poll.vote', third, at)).not.toBe(generateIdempotencyKey('poll.vote', first, at));+ // A redelivery of the same change still carries the same stamp and the same key.+ expect(generateIdempotencyKey('poll.vote', { ...first }, '2026-07-20T01:00:00.000Z')).toBe(+ generateIdempotencyKey('poll.vote', first, at),+ );+ });+it('keys call.received on the session + call id (unique per call, no occurrence salt needed)', () => {const at = '2026-07-20T00:00:00.000Z';const data = { sessionId: 'A', callId: 'CALL1', from: '[email protected]', timestamp: 1782000000 };diff --git a/src/modules/webhook/utils/idempotency.util.ts b/src/modules/webhook/utils/idempotency.util.tsindex 316f232f6..acc0f1550 100644--- a/src/modules/webhook/utils/idempotency.util.ts+++ b/src/modules/webhook/utils/idempotency.util.ts@@ -120,10 +120,12 @@ export function generateIdempotencyKey(event: string, data: Record<string, unknocase 'poll.vote':// A vote carries no id of its own, but each change of a voter's selection is stamped by the- // voter's clock, so (session, poll, voter, timestamp) is distinct per change and stable across- // retries. The stamp is whole seconds, so the selection is hashed in as well: two taps on a- // multiple-choice poll within one second are two changes and must not share a key.- return `vote_${toStr(data.sessionId)}_${toStr(data.pollMessageId)}_${toStr(data.voterId)}_${toStr(data.timestamp)}_${hashData({ selectedOptions: data.selectedOptions ?? null })}`;+ // voter's clock in milliseconds, so (session, poll, voter, timestampMs) is distinct per change and+ // stable across retries. The selection is hashed in as well, and the whole second stays the+ // fallback for a payload without the millisecond stamp: a voter flipping A, B, A within one second+ // would otherwise send the third change under the key of the first, and a receiver that dedupes on+ // the key would end on B.+ return `vote_${toStr(data.sessionId)}_${toStr(data.pollMessageId)}_${toStr(data.voterId)}_${toStr(data.timestampMs ?? data.timestamp)}_${hashData({ selectedOptions: data.selectedOptions ?? null })}`;case 'presence.update':// Keyed on the chat and salted per occurrence. Only genuine state CHANGES are dispatched, and