Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(messages): expose poll choices

Yudhi Armyndharisc0b1c60d2562
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e56f82851..acdd34e1e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- Expose poll choices and selection mode in message events, stored messages, history, and dashboard chats.
- Expose optional last-message types in chat lists and SDKs.
- Add bounded webhook failure redrive with optional payload retention.
- Expose caller-supplied send idempotency keys in all five SDKs.
diff --git a/dashboard/src/components/chats/ChatThread.test.ts b/dashboard/src/components/chats/ChatThread.test.ts
index 1f59f6b09..3e80febf3 100644
--- a/dashboard/src/components/chats/ChatThread.test.ts
+++ b/dashboard/src/components/chats/ChatThread.test.ts
@@ -217,3 +217,26 @@ test('archive-only media previews inline from the media route; a plain omitted m
URL.revokeObjectURL = revokeOriginal;
}
});
+
+test('poll messages display exact choices, including outgoing and legacy polls', () => {
+ const poll = { name: 'Where?', options: [' Park ', '<script>Beach</script>'], allowMultipleAnswers: false };
+ const { container } = renderThread('viewer', [
+ { ...PROMPT, type: 'poll', body: 'Where?', metadata: { poll } },
+ {
+ ...PROMPT,
+ id: 'out',
+ waMessageId: 'out',
+ type: 'poll',
+ direction: 'outgoing',
+ body: 'Where?',
+ metadata: { poll },
+ },
+ { ...PROMPT, id: 'legacy', waMessageId: 'legacy', type: 'poll', body: 'Legacy question', metadata: undefined },
+ ]);
+ assert.deepEqual(
+ Array.from(container.querySelectorAll('li bdi')).map(node => node.textContent),
+ [...poll.options, ...poll.options],
+ );
+ assert.equal(container.querySelector('script'), null);
+ assert.ok(container.textContent?.includes('Legacy question'));
+});
diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsx
index 3ed89fb79..01300639c 100644
--- a/dashboard/src/components/chats/ChatThread.tsx
+++ b/dashboard/src/components/chats/ChatThread.tsx
@@ -282,6 +282,7 @@ function ChatThread({
const isMediaMessage = msg.type !== 'text';
const mediaInfo = msg.metadata?.media;
+ const displayBody = msg.body || (msg.type === 'poll' ? msg.metadata?.poll?.name : undefined);
const renderMedia = () => {
if (msg.type === 'revoked') return null;
@@ -461,14 +462,24 @@ function ChatThread({
) : isMasked ? (
<div className="message-text message-masked">{t('chats.messageMasked')}</div>
) : (
- msg.body &&
- (!mediaInfo || msg.body !== mediaInfo.filename) &&
+ displayBody &&
+ (!mediaInfo || displayBody !== mediaInfo.filename) &&
msg.type !== 'location' &&
msg.type !== 'call' && (
- <MessageBody text={resolveMentions(msg.body, mentionNames)} className="message-text" />
+ <MessageBody text={resolveMentions(displayBody, mentionNames)} className="message-text" />
)
)}
+ {!isRevoked && msg.type === 'poll' && (msg.metadata?.poll?.options?.length ?? 0) > 0 && (
+ <ul className="message-text" aria-label={t('messageTester.pollOptions')}>
+ {msg.metadata!.poll!.options.map((option, index) => (
+ <li key={index}>
+ <bdi>{option}</bdi>
+ </li>
+ ))}
+ </ul>
+ )}
+
{/* Inbound business prompt choices; a tap calls POST .../messages/click-button. */}
{!isMe && !isRevoked && !isMasked && (msg.metadata?.buttons?.length ?? 0) > 0 && (
<div className="message-prompt-buttons" role="group" aria-label={t('chats.promptButtons')}>
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index e2a2331a7..0f641e74c 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -82,6 +82,7 @@ interface IncomingWsMessage {
call?: { video: boolean; missed: boolean };
/** Business prompt choices (Baileys); top-level on the live event, folded into metadata for the UI. */
buttons?: Array<{ id: string; text: string }>;
+ poll?: { name: string; options: string[]; allowMultipleAnswers: boolean };
metadata?: ChatMessageView['metadata'];
kind?: ChatKind;
/** Group poster: `from` is the group JID, so `contact`/`author` identify who actually sent it. */
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 1322044e4..5cd8af24b 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -317,6 +317,7 @@ export interface ChatMessage {
timestamp?: number;
createdAt: string;
metadata?: {
+ poll?: { name: string; options: string[]; allowMultipleAnswers: boolean };
media?: {
mimetype: string;
filename?: string;
@@ -389,6 +390,7 @@ export interface EngineHistoryMessage {
sizeBytes?: number;
archived?: boolean;
};
+ poll?: { name: string; options: string[]; allowMultipleAnswers: boolean };
quotedMessage?: { id: string; body: string };
location?: { latitude: number; longitude: number; description?: string; address?: string; url?: string };
/** Present on `order` messages only: the placed cart, plus the single-order token for its items. */
diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.ts
index 35d1a9708..3e78e0c9d 100644
--- a/dashboard/src/utils/chatMessages.test.ts
+++ b/dashboard/src/utils/chatMessages.test.ts
@@ -643,3 +643,33 @@ test('a push name whose first word is invisible renders its first visible word,
assert.equal(resolveMentions('@6281112345', names), wrap('@Bob'));
}
});
+
+test('live and history poll choices survive metadata projection', () => {
+ const poll = { name: 'Q', options: ['a', 'b'], allowMultipleAnswers: true };
+ assert.deepEqual(liveMessageMetadata({ poll }), { poll });
+ const mapped = mapEngineHistoryMessage({
+ id: 'p',
+ chatId: '[email protected]',
+ to: 'me',
+ body: 'Q',
+ type: 'poll',
+ timestamp: 100,
+ fromMe: false,
+ isGroup: false,
+ kind: 'individual',
+ poll,
+ });
+ assert.deepEqual(mapped.metadata?.poll, poll);
+});
+
+test('legacy poll rows inherit available history choices without replacing stored state', () => {
+ const poll = { name: 'Q', options: ['a', 'b'], allowMultipleAnswers: false };
+ const historical = mapEngineHistoryMessage(hist({ type: 'poll', poll }));
+ const stored = { ...historical, status: 'delivered' as const, metadata: { reactions: { sender: 'ok' } } };
+ const merged = mergeChatMessages([stored], [historical])[0];
+ assert.equal(merged.status, 'delivered');
+ assert.deepEqual(merged.metadata, { reactions: { sender: 'ok' }, poll });
+ const revoked = mergeChatMessages([{ ...stored, type: 'revoked', body: '', metadata: undefined }], [historical])[0];
+ assert.equal(revoked.metadata?.poll, undefined);
+});
diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.ts
index 25026a9be..bcad08447 100644
--- a/dashboard/src/utils/chatMessages.ts
+++ b/dashboard/src/utils/chatMessages.ts
@@ -35,6 +35,7 @@ export function mapEngineHistoryMessage(h: EngineHistoryMessage): ChatMessage {
}
if (h.quotedMessage) metadata.quotedMessage = h.quotedMessage;
if (h.call) metadata.call = h.call;
+ if (h.poll) metadata.poll = h.poll;
return Object.keys(metadata).length > 0 ? metadata : undefined;
})(),
};
@@ -56,7 +57,11 @@ export function mergeChatMessages(db: ChatMessage[], history: ChatMessage[]): Ch
// The DB copy wins (authoritative status) — but a legacy row has no stable sender id, so
// salvage the engine-history copy's author or two same-named participants collapse into one
// attribution run in the chat view.
- byId.set(key, hist?.author && !m.author ? { ...m, author: hist.author } : m);
+ let merged = hist?.author && !m.author ? { ...m, author: hist.author } : m;
+ if (m.type === 'poll' && !m.metadata?.poll && hist?.metadata?.poll) {
+ merged = { ...merged, metadata: { ...merged.metadata, poll: hist.metadata.poll } };
+ }
+ byId.set(key, merged);
}
const sorted = [...byId.values()].sort((a, b) => msgTime(a) - msgTime(b) || a.createdAt.localeCompare(b.createdAt));
return capMediaPayloads(sorted);
@@ -244,6 +249,7 @@ export interface ChatMessageView extends ChatMessage {
reactions?: Record<string, string>;
call?: { video: boolean; missed: boolean };
buttons?: Array<{ id: string; text: string }>;
+ poll?: { name: string; options: string[]; allowMultipleAnswers: boolean };
};
}
@@ -257,6 +263,7 @@ export function liveMessageMetadata(msg: {
quotedMessage?: { id: string; body: string };
call?: { video: boolean; missed: boolean };
buttons?: Array<{ id: string; text: string }>;
+ poll?: { name: string; options: string[]; allowMultipleAnswers: boolean };
metadata?: ChatMessageView['metadata'];
}): ChatMessageView['metadata'] {
if (msg.metadata) return msg.metadata;
@@ -264,6 +271,7 @@ export function liveMessageMetadata(msg: {
if (msg.media) metadata.media = msg.media;
if (msg.quotedMessage) metadata.quotedMessage = msg.quotedMessage;
if (msg.call) metadata.call = msg.call;
+ if (msg.poll) metadata.poll = msg.poll;
if (msg.buttons?.length) metadata.buttons = msg.buttons;
return Object.keys(metadata).length > 0 ? metadata : undefined;
}
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 69b6dc775..8f34bd1d2 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1440,6 +1440,10 @@ Returns a bare array of `MessageReaction`:
**Errors:** `400` session not active · `401` missing/invalid API key · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine · `503` the whatsapp-web.js page died mid-read (retryable)
+Poll creation messages include `poll { name, options, allowMultipleAnswers }` when the engine provides the choices. Live `message.received` and `message.sent` events and whatsapp-web.js history carry it at the top level. Stored-message responses carry the same object in `metadata.poll`, including polls sent through `send-poll`. The dashboard displays these option texts. Use the exact strings in `options` when voting; their order and whitespace are preserved.
+
+Legacy stored polls may have no choices because they were captured before this field was stored. Vote counts are not included.
+
#### POST /api/sessions/:sessionId/messages/vote-poll
Cast a vote on a poll.
diff --git a/openapi.json b/openapi.json
index f9595044a..f830ac2dc 100644
--- a/openapi.json
+++ b/openapi.json
@@ -20549,6 +20549,34 @@
"body"
]
},
+ "ChatHistoryPollDto": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "example": "Where?"
+ },
+ "options": {
+ "example": [
+ "Park",
+ "Beach"
+ ],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "allowMultipleAnswers": {
+ "type": "boolean",
+ "example": false
+ }
+ },
+ "required": [
+ "name",
+ "options",
+ "allowMultipleAnswers"
+ ]
+ },
"ChatHistoryLocationDto": {
"type": "object",
"properties": {
@@ -20757,6 +20785,14 @@
"quotedMessage": {
"$ref": "#/components/schemas/ChatHistoryQuotedMessageDto"
},
+ "poll": {
+ "description": "Poll choices and selection mode, when available.",
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ChatHistoryPollDto"
+ }
+ ]
+ },
"location": {
"$ref": "#/components/schemas/ChatHistoryLocationDto"
},
diff --git a/sdk/go/chat_history_decode_test.go b/sdk/go/chat_history_decode_test.go
index 7e7754453..f36b89180 100644
--- a/sdk/go/chat_history_decode_test.go
+++ b/sdk/go/chat_history_decode_test.go
@@ -75,3 +75,13 @@ func TestChatSummaryDecodesOptionalLastMessageType(t *testing.T) {
t.Fatal("absent type must stay omitted")
}
}
+
+func TestChatHistoryDecodesPollChoices(t *testing.T) {
+ var m ChatHistoryMessage
+ if err := json.Unmarshal([]byte(`{"poll":{"name":"Q","options":[" Park ","Beach"],"allowMultipleAnswers":false}}`), &m); err != nil {
+ t.Fatal(err)
+ }
+ if m.Poll == nil || m.Poll.Name != "Q" || m.Poll.Options[0] != " Park " || m.Poll.AllowMultipleAnswers {
+ t.Fatalf("poll = %+v", m.Poll)
+ }
+}
diff --git a/sdk/go/types_message.go b/sdk/go/types_message.go
index bd2c15615..377405132 100644
--- a/sdk/go/types_message.go
+++ b/sdk/go/types_message.go
@@ -303,6 +303,14 @@ type ChatHistoryMessage struct {
Location *MessageLocation `json:"location,omitempty"`
Order *MessageOrder `json:"order,omitempty"`
Product *MessageProduct `json:"product,omitempty"`
+ Poll *ChatHistoryPoll `json:"poll,omitempty"`
+}
+
+// ChatHistoryPoll contains the poll question, choices, and selection mode.
+type ChatHistoryPoll struct {
+ Name string `json:"name"`
+ Options []string `json:"options"`
+ AllowMultipleAnswers bool `json:"allowMultipleAnswers"`
}
// MessageOrder is the order block on a live history message, present on order messages only: the
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java
index 596adb382..537abd30d 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java
@@ -36,7 +36,23 @@ public record ChatHistoryMessage(
QuotedMessage quotedMessage,
Location location,
Order order,
- Product product) {
+ Product product,
+ Poll poll) {
+
+ /** Construct a history message without poll metadata. */
+ public ChatHistoryMessage(
+ String id, String from, String to, String chatId, String body, MessageType type,
+ long timestamp, boolean fromMe, boolean isGroup, Boolean isStatusBroadcast,
+ ChatKind kind, Integer ephemeralDuration, String author, List<String> mentionedIds,
+ Call call, Boolean isLidSender, String senderPhone, Contact contact,
+ String backgroundColor, Integer font, Media media, QuotedMessage quotedMessage,
+ Location location, Order order, Product product) {
+ this(id, from, to, chatId, body, type, timestamp, fromMe, isGroup, isStatusBroadcast,
+ kind, ephemeralDuration, author, mentionedIds, call, isLidSender, senderPhone,
+ contact, backgroundColor, font, media, quotedMessage, location, order, product, null);
+ }
+
+ public record Poll(String name, List<String> options, boolean allowMultipleAnswers) {}
/** Attached media; {@code data} is absent when the payload was omitted (too large). */
public record Media(String mimetype, String filename, String data, Boolean omitted, Long sizeBytes) {}
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/model/ChatHistoryMessageDecodeTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/model/ChatHistoryMessageDecodeTest.java
index 9b5b7e6bd..bf56e2077 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/model/ChatHistoryMessageDecodeTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/model/ChatHistoryMessageDecodeTest.java
@@ -43,6 +43,17 @@ class ChatHistoryMessageDecodeTest {
assertEquals(0, m.contact().verifiedLevel());
}
+ @Test
+ void decodesPollChoicesWithoutTrimming() {
+ var m = GSON.fromJson("{\"poll\":{\"name\":\"Q\",\"options\":[\" Park \",\"Beach\"],\"allowMultipleAnswers\":false}}", ChatHistoryMessage.class);
+ assertEquals(List.of(" Park ", "Beach"), m.poll().options());
+ assertFalse(m.poll().allowMultipleAnswers());
+ var legacy = new ChatHistoryMessage("id", "from", "to", "chat", "Q", MessageType.POLL,
+ 1L, false, false, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null);
+ assertNull(legacy.poll());
+ }
+
@Test
void leavesAbsentOptionalsNull() {
String json = "{\"id\":\"x\",\"from\":\"a\",\"to\":\"b\",\"chatId\":\"c\",\"body\":\"\","
@@ -50,6 +61,7 @@ class ChatHistoryMessageDecodeTest {
ChatHistoryMessage m = GSON.fromJson(json, ChatHistoryMessage.class);
+ assertNull(m.poll());
assertNull(m.call());
assertNull(m.contact());
assertNull(m.ephemeralDuration());
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index bd3047b0f..8f09addf6 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -623,6 +623,7 @@ export interface ChatHistoryMessage {
sizeBytes?: number;
};
quotedMessage?: { id: string; body: string };
+ poll?: { name: string; options: string[]; allowMultipleAnswers: boolean };
location?: { latitude: number; longitude: number; description?: string; address?: string; url?: string };
/** Present on `order` messages only: the placed cart, plus the single-order token for its items. */
order?: { orderId: string; token?: string };
diff --git a/sdk/javascript/test/wire-contract.test-d.ts b/sdk/javascript/test/wire-contract.test-d.ts
index c7c310ac7..8448ebafe 100644
--- a/sdk/javascript/test/wire-contract.test-d.ts
+++ b/sdk/javascript/test/wire-contract.test-d.ts
@@ -139,6 +139,7 @@ interface WireChatHistoryMessage {
font?: number;
media?: { mimetype: string; filename?: string; data?: string; omitted?: boolean; sizeBytes?: number };
quotedMessage?: { id: string; body: string };
+ poll?: { name: string; options: string[]; allowMultipleAnswers: boolean };
location?: { latitude: number; longitude: number; description?: string; address?: string; url?: string };
order?: { orderId: string; token?: string };
product?: { productId: string; title?: string; description?: string; businessOwnerJid?: string };
@@ -182,6 +183,7 @@ const channel: Mirrors<WireChannel, ChannelRecord> = true;
const channelMessage: Mirrors<WireChannelMessage, ChannelMessageRecord> = true;
const catalog: Mirrors<WireCatalog, CatalogInfo> = true;
const chatHistoryMessage: Mirrors<WireChatHistoryMessage, ChatHistoryMessage> = true;
+const poll: Mirrors<NonNullable<WireChatHistoryMessage['poll']>, NonNullable<ChatHistoryMessage['poll']>> = true;
const readiness: Mirrors<WireReadiness, HealthReadyResponse> = true;
-export const contract = [label, status, channel, channelMessage, catalog, chatHistoryMessage, readiness];
+export const contract = [label, status, channel, channelMessage, catalog, chatHistoryMessage, poll, readiness];
diff --git a/sdk/php/src/Resources/MessagesResource.php b/sdk/php/src/Resources/MessagesResource.php
index a38e9704b..283baaaab 100644
--- a/sdk/php/src/Resources/MessagesResource.php
+++ b/sdk/php/src/Resources/MessagesResource.php
@@ -165,6 +165,7 @@ class MessagesResource
}
/**
+ * Poll messages include poll.name, poll.options, and poll.allowMultipleAnswers when available.
* @param array<string,mixed> $query
* @return array<int,array<string,mixed>>
*/
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index 515e784dc..6a97b4a64 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -592,6 +592,12 @@ class MessageContact(TypedDict, total=False):
labels: list
+class ChatHistoryPoll(TypedDict):
+ name: str
+ options: list[str]
+ allowMultipleAnswers: bool
+
+
# A message read live from WhatsApp by ``messages.history()`` — the engine
# payload, richer and differently shaped than the persisted MessageRecord.
ChatHistoryMessage = TypedDict(
@@ -619,6 +625,7 @@ ChatHistoryMessage = TypedDict(
"font": NotRequired[int],
"media": NotRequired[ChatHistoryMedia],
"quotedMessage": NotRequired[QuotedMessage],
+ "poll": NotRequired[ChatHistoryPoll],
"location": NotRequired[MessageLocation],
"order": NotRequired[MessageOrder],
"product": NotRequired[MessageProduct],
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.ts
index 49d803835..dc15b0175 100644
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@ -21,6 +21,7 @@ import {
extractBaileysButtonReply,
extractBaileysButtons,
extractBaileysCommerce,
+ extractBaileysPoll,
extractBaileysContext,
extractBaileysLocation,
isBaileysCatalogShare,
@@ -1470,6 +1471,7 @@ export class BaileysEvents {
quotedMessage: context.quotedMessage,
order: commerce.order,
product: commerce.product,
+ poll: extractBaileysPoll(normalized),
button,
buttons,
isCatalogShare: isBaileysCatalogShare(normalized),
diff --git a/src/engine/adapters/baileys-history.ts b/src/engine/adapters/baileys-history.ts
index 2af9ec7cb..8458f351c 100644
--- a/src/engine/adapters/baileys-history.ts
+++ b/src/engine/adapters/baileys-history.ts
@@ -8,6 +8,7 @@ import {
extractBaileysButtonReply,
extractBaileysButtons,
extractBaileysCommerce,
+ extractBaileysPoll,
isBaileysCatalogShare,
} from './baileys-message-mapper';
import { BAILEYS_QUERY_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';
@@ -271,6 +272,7 @@ export class BaileysHistory {
// Same commerce mapping as the live path, so a whole-catalog share is `unknown` on both.
order: commerce.order,
product: commerce.product,
+ poll: extractBaileysPoll(content),
button,
buttons,
isCatalogShare: isBaileysCatalogShare(content),
diff --git a/src/engine/adapters/baileys-message-mapper.spec.ts b/src/engine/adapters/baileys-message-mapper.spec.ts
index d632a42ae..f3b51f2a4 100644
--- a/src/engine/adapters/baileys-message-mapper.spec.ts
+++ b/src/engine/adapters/baileys-message-mapper.spec.ts
@@ -3,6 +3,7 @@ import {
BaileysIncomingFields,
baileysChatJid,
buildIncomingMessageFromBaileys,
+ extractBaileysPoll,
extractBaileysBody,
extractBaileysButtonReply,
extractBaileysButtons,
@@ -1155,3 +1156,33 @@ describe('isBaileysCatalogShare (the productMessage arm with no product)', () =>
);
});
});
+
+describe('native poll choice metadata', () => {
+ it.each(['pollCreationMessage', 'pollCreationMessageV2', 'pollCreationMessageV3'] as const)(
+ 'reads %s without changing option texts',
+ key => {
+ expect(
+ extractBaileysPoll({
+ [key]: {
+ name: 'Where?',
+ options: [{ optionName: ' Park ' }, { optionName: 'Beach' }],
+ selectableOptionsCount: 1,
+ },
+ }),
+ ).toEqual({ name: 'Where?', options: [' Park ', 'Beach'], allowMultipleAnswers: false });
+ },
+ );
+ it('reports multiple choices and omits unavailable poll data', () => {
+ expect(
+ extractBaileysPoll({
+ pollCreationMessageV3: {
+ name: 'Q',
+ options: [{ optionName: 'a' }, { optionName: 'b' }],
+ selectableOptionsCount: 0,
+ },
+ })?.allowMultipleAnswers,
+ ).toBe(true);
+ expect(extractBaileysPoll({})).toBeUndefined();
+ expect(extractBaileysPoll({ pollCreationMessage: {} })).toBeUndefined();
+ });
+});
diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.ts
index e41677055..35d444b1f 100644
--- a/src/engine/adapters/baileys-message-mapper.ts
+++ b/src/engine/adapters/baileys-message-mapper.ts
@@ -1,3 +1,4 @@
+import type { proto } from '@whiskeysockets/baileys';
import { DeliveryStatus, IncomingMessage, MessageType } from '../interfaces/whatsapp-engine.interface';
import { chatKind } from '../identity/wa-id';
@@ -912,6 +913,17 @@ export function mapBaileysStatus(status: number | null | undefined): DeliverySta
}
}
+/** Extract native poll versions from content already normalized by Baileys. */
+export function extractBaileysPoll(content: proto.IMessage): IncomingMessage['poll'] {
+ const poll = content.pollCreationMessage ?? content.pollCreationMessageV2 ?? content.pollCreationMessageV3;
+ if (!poll) return undefined;
+ const options = (poll.options ?? [])
+ .map(option => option.optionName)
+ .filter((option): option is string => typeof option === 'string');
+ if (!options.length) return undefined;
+ return { name: poll.name ?? '', options, allowMultipleAnswers: poll.selectableOptionsCount !== 1 };
+}
+
/**
* The subset of a Baileys `WAMessage` the adapter reads (after proto extraction) to build the
* base of an {@link IncomingMessage}. Declared explicitly so the neutral-shape logic is
@@ -942,6 +954,7 @@ export interface BaileysIncomingFields {
/** Pre-extracted commerce ids. Populated by the adapter for `orderMessage` / `productMessage`. */
order?: IncomingMessage['order'];
product?: IncomingMessage['product'];
+ poll?: IncomingMessage['poll'];
/** Pre-extracted button/list reply. Populated by the adapter when the user tapped a control. */
button?: IncomingMessage['button'];
/** Pre-extracted prompt choices. Populated by the adapter for business button/list prompts. */
@@ -1051,6 +1064,8 @@ export function buildIncomingMessageFromBaileys(
incoming.media = fields.media;
}
+ if (fields.poll) incoming.poll = fields.poll;
+
if (fields.location) {
incoming.location = fields.location;
}
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 9fec78bd5..85d57b7e1 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -6361,6 +6361,50 @@ describe('BaileysAdapter contact + chat reads', () => {
expect(listed.find(c => c.id === '[email protected]')?.lastMessageType).toBe('voice');
});
+ it.each(['live', 'history', 'API'] as const)('carries wrapped poll choices through the %s path', async path => {
+ const emitted = jest.fn();
+ const history = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize({ onMessage: emitted, onMessageCreate: emitted, onHistoryMessages: history });
+ fakeSock.fire('connection.update', { connection: 'open' });
+ const baileys = jest.requireMock<Record<string, jest.Mock>>('@whiskeysockets/baileys');
+ baileys.getContentType.mockImplementation(realGetContentType);
+ baileys.normalizeMessageContent.mockImplementation(
+ (m?: { ephemeralMessage?: { message?: unknown } }) => m?.ephemeralMessage?.message ?? m,
+ );
+ const message = {
+ key: { remoteJid: '[email protected]', id: 'POLL', fromMe: path === 'API' },
+ messageTimestamp: 100,
+ message: {
+ ephemeralMessage: {
+ message: {
+ pollCreationMessageV3: {
+ name: 'Where?',
+ options: [{ optionName: ' Park ' }, { optionName: 'Beach' }],
+ selectableOptionsCount: 1,
+ },
+ },
+ },
+ },
+ };
+ if (path === 'API') {
+ fakeSock.sendMessage.mockResolvedValueOnce(message);
+ await adapter.sendPollMessage('[email protected]', { name: 'Where?', options: [' Park ', 'Beach'] });
+ } else if (path === 'history') {
+ fakeSock.fire('messaging-history.set', { contacts: [], chats: [], messages: [message] });
+ } else {
+ fakeSock.fire('messages.upsert', { type: 'notify', messages: [message] });
+ }
+ await new Promise(r => setImmediate(r));
+ await new Promise(r => setImmediate(r));
+ const expected: unknown = expect.objectContaining({
+ type: 'poll',
+ poll: { name: 'Where?', options: [' Park ', 'Beach'], allowMultipleAnswers: false },
+ });
+ if (path === 'history') expect(history).toHaveBeenCalledWith([expected]);
+ else expect(emitted).toHaveBeenCalledWith(expected);
+ });
+
it('keeps the content preview when newer history entries only modify messages', async () => {
const adapter = await ready();
const baileys = jest.requireMock<Record<string, jest.Mock>>('@whiskeysockets/baileys');
diff --git a/src/engine/adapters/message-mapper.spec.ts b/src/engine/adapters/message-mapper.spec.ts
index af4b09dcd..b43a444f2 100644
--- a/src/engine/adapters/message-mapper.spec.ts
+++ b/src/engine/adapters/message-mapper.spec.ts
@@ -280,3 +280,24 @@ describe('mapContactFields', () => {
});
});
});
+
+describe('poll choice metadata', () => {
+ it.each([
+ [' Park ', 'Beach'],
+ [{ name: ' Park ' }, { name: 'Beach' }],
+ ])('preserves choices from the library representation', (...pollOptions) => {
+ const mapped = buildIncomingMessageBase({
+ id: { _serialized: 'P1' },
+ to: 'me',
+ body: 'Where?',
+ type: 'poll_creation',
+ timestamp: 100,
+ fromMe: false,
+ pollName: 'Where?',
+ pollOptions,
+ allowMultipleAnswers: true,
+ });
+ expect(mapped.poll).toEqual({ name: 'Where?', options: [' Park ', 'Beach'], allowMultipleAnswers: true });
+ });
+});
diff --git a/src/engine/adapters/message-mapper.ts b/src/engine/adapters/message-mapper.ts
index 1e6043bf5..db583ce37 100644
--- a/src/engine/adapters/message-mapper.ts
+++ b/src/engine/adapters/message-mapper.ts
@@ -81,6 +81,9 @@ export interface RawMessageFields {
token?: string;
/** Set on `product` messages: the shared catalog product. */
productId?: string;
+ pollName?: string;
+ pollOptions?: Array<string | { name?: string }>;
+ allowMultipleAnswers?: boolean;
/** Product title / description. whatsapp-web.js exposes these only for a product card. */
title?: string;
description?: string;
@@ -159,6 +162,19 @@ export function buildIncomingMessageBase(msg: RawMessageFields): IncomingMessage
};
}
+ if (incoming.type === 'poll' && Array.isArray(msg.pollOptions)) {
+ const options = msg.pollOptions
+ .map(option => (typeof option === 'string' ? option : option?.name))
+ .filter((option): option is string => typeof option === 'string');
+ if (options.length) {
+ incoming.poll = {
+ name: msg.pollName ?? msg.body,
+ options,
+ allowMultipleAnswers: msg.allowMultipleAnswers === true,
+ };
+ }
+ }
+
return incoming;
}
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 8e534ef4a..c0d31e92b 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -187,6 +187,7 @@ export interface IncomingMessage {
backgroundColor?: string;
/** Styling of a text status/story: the WhatsApp font index. Only set by engines that expose it. */
font?: number;
+ poll?: PollDetails;
media?: {
mimetype: string;
filename?: string;
@@ -388,6 +389,13 @@ export interface LocationInput extends Quotable {
address?: string;
}
+/** Poll choices as received from the engine, without vote counts. */
+export interface PollDetails {
+ name: string;
+ options: string[];
+ allowMultipleAnswers: boolean;
+}
+
export interface PollInput extends Quotable {
/** Poll question / title. */
name: string;
diff --git a/src/modules/message/dto/message-responses.dto.ts b/src/modules/message/dto/message-responses.dto.ts
index 1304bd253..a10d306e1 100644
--- a/src/modules/message/dto/message-responses.dto.ts
+++ b/src/modules/message/dto/message-responses.dto.ts
@@ -249,6 +249,17 @@ export class ChatHistoryProductDto {
businessOwnerJid?: string;
}
+export class ChatHistoryPollDto {
+ @ApiProperty({ example: 'Where?' })
+ name!: string;
+
+ @ApiProperty({ type: [String], example: ['Park', 'Beach'] })
+ options!: string[];
+
+ @ApiProperty({ example: false })
+ allowMultipleAnswers!: boolean;
+}
+
/** OpenAPI mirror of the engine `IncomingMessage` served by the live chat-history route. */
export class ChatHistoryMessageDto {
@ApiProperty({ example: '[email protected]_3EB0123456789' })
@@ -327,6 +338,9 @@ export class ChatHistoryMessageDto {
@ApiPropertyOptional({ type: ChatHistoryQuotedMessageDto })
quotedMessage?: ChatHistoryQuotedMessageDto;
+ @ApiPropertyOptional({ type: ChatHistoryPollDto, description: 'Poll choices and selection mode, when available.' })
+ poll?: ChatHistoryPollDto;
+
@ApiPropertyOptional({ type: ChatHistoryLocationDto })
location?: ChatHistoryLocationDto;
diff --git a/src/modules/message/message-send.service.spec.ts b/src/modules/message/message-send.service.spec.ts
index 938ed8fc6..ff9defc15 100644
--- a/src/modules/message/message-send.service.spec.ts
+++ b/src/modules/message/message-send.service.spec.ts
@@ -941,7 +941,13 @@ describe('MessageSendService', () => {
});
// A poll has no plain-text body, so it is persisted as type 'poll' with the question as the body.
expect(repository.create).toHaveBeenCalledWith(
- expect.objectContaining({ type: 'poll', body: '📊 Where should we meet?' }),
+ expect.objectContaining({
+ type: 'poll',
+ body: '📊 Where should we meet?',
+ metadata: {
+ poll: { name: 'Where should we meet?', options: ['Park', 'Beach'], allowMultipleAnswers: false },
+ },
+ }),
);
});
diff --git a/src/modules/message/message-send.service.ts b/src/modules/message/message-send.service.ts
index a4956a8f6..ebbb16da5 100644
--- a/src/modules/message/message-send.service.ts
+++ b/src/modules/message/message-send.service.ts
@@ -487,6 +487,13 @@ export class MessageSendService {
chatId: finalDto.chatId,
body: `📊 ${finalDto.name}`,
type: 'poll',
+ metadata: {
+ poll: {
+ name: finalDto.name,
+ options: [...finalDto.options],
+ allowMultipleAnswers: finalDto.allowMultipleAnswers === true,
+ },
+ },
quotedMessageId: finalDto.quotedMessageId,
});
diff --git a/src/modules/session/message-row.mapper.spec.ts b/src/modules/session/message-row.mapper.spec.ts
index 661e6ad8e..f4580c040 100644
--- a/src/modules/session/message-row.mapper.spec.ts
+++ b/src/modules/session/message-row.mapper.spec.ts
@@ -26,6 +26,12 @@ describe('buildMessageMetadata', () => {
expect(buildMessageMetadata(msg({ call }))).toEqual({ call });
});
+ it('keeps exact poll choices for live, echo, and history rows', () => {
+ const poll = { name: 'Where?', options: [' Park ', 'Beach'], allowMultipleAnswers: false };
+ expect(buildMessageMetadata(msg({ type: 'poll', poll }))).toEqual({ poll });
+ expect(buildMessageMetadata(msg({ type: 'poll', poll }), true)).toEqual({ poll });
+ });
+
it('stores prompt buttons', () => {
const buttons = [
{ id: 'yes', text: 'Sim' },
diff --git a/src/modules/session/message-row.mapper.ts b/src/modules/session/message-row.mapper.ts
index 52a456b68..6d5aa5e77 100644
--- a/src/modules/session/message-row.mapper.ts
+++ b/src/modules/session/message-row.mapper.ts
@@ -29,7 +29,7 @@ export const OMITTED_MEDIA = { mimetype: '', omitted: true } as const;
* and an empty object would be noise).
*/
export function buildMessageMetadata(
- message: Pick<IncomingMessage, 'media' | 'quotedMessage' | 'call' | 'buttons' | 'type'>,
+ message: Pick<IncomingMessage, 'media' | 'quotedMessage' | 'call' | 'buttons' | 'poll' | 'type'>,
synthesizeOmittedMedia = false,
): Record<string, unknown> | undefined {
const metadata: Record<string, unknown> = {};
@@ -41,6 +41,7 @@ export function buildMessageMetadata(
if (message.quotedMessage) {
metadata.quotedMessage = message.quotedMessage;
}
+ if (message.poll) metadata.poll = message.poll;
if (message.call) {
metadata.call = message.call;
}