Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(messages): vote on polls (whatsapp-web.js engine)

Yudhi Armyndhariscc5e8570d2b2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a65fe9a54..4b4a97b79 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Polls can be voted on, on the whatsapp-web.js engine:**
+ `POST /api/sessions/:sessionId/messages/vote-poll` with `{ chatId, pollMessageId, options }`.
+ Exposed in all five SDKs as `messages.votePoll`. Baileys returns `501` — it has no vote-send
+ helper at all, only `decryptPollVote` for *receiving*.
+
+ `options` are the option **texts**, not ids: whatsapp-web.js matches options by name, and no
+ engine surfaces a stable per-option id through this API, so there is nothing else to name an
+ option by. A poll with two identically-worded options will select both. The list replaces the
+ current selection, and `[]` clears the vote.
+
+ Two limits are documented rather than papered over: the poll must be inside the engine's
+ 100-message window for the chat (an older one is `404`), and a non-poll target is `400` — the
+ library throws a bare string there, which would otherwise have surfaced as an opaque `500`.
+
- **Group pictures can be read, set and removed:**
`GET|PUT|DELETE /api/sessions/:sessionId/groups/:groupId/picture`. Supported on both engines and
exposed in all five SDKs as `groups.getPicture` / `setPicture` / `deletePicture`. The `PUT` body
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 1d8fab00a..c520e1af3 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -991,6 +991,36 @@ Returns a bare array of `MessageReaction`:
**Errors:** `400` session not active · `401` missing/invalid API key · `500` engine error
+#### POST /api/sessions/:sessionId/messages/vote-poll
+
+Cast a vote on a poll.
+
+**Auth:** API key (OPERATOR) · **Engines:** whatsapp-web.js only — Baileys returns `501`
+
+**Body**
+
+| Field | Type | Required | Description |
+| --- | --- | --- | --- |
+| chatId | string | yes | Chat containing the poll |
+| pollMessageId | string | yes | The poll creation message |
+| options | string[] | yes | The option **texts** to select, exactly as they appear on the poll (max 12). Replaces the current selection; `[]` clears the vote |
+
+**Response** `200` — `{ "success": true }`
+
+> **Options are texts, not ids.** whatsapp-web.js matches poll options by name, and no engine
+> surfaces a stable per-option id through this API, so the text is the only handle available. A poll
+> with two identically-worded options will therefore select **both**.
+
+> **Only recent polls can be voted on.** The poll must be within the 100-message window the engine
+> fetches for the chat — the same limit that applies to react/delete/edit/pin. An older poll comes
+> back `404`.
+
+> **Baileys returns `501`.** The library exposes no vote-send helper at all — only `decryptPollVote`
+> for *receiving* votes. Sending one requires hand-building a `PollUpdateMessage` with HMAC-SHA256
+> vote encryption keyed by the poll creation's `messageSecret`, which is not wired here.
+
+**Errors:** `400` session not active, or the target message is not a poll · `401` missing/invalid API key · `403` key lacks OPERATOR role · `404` poll not found in recent history · `501` Baileys engine
+
#### POST /api/sessions/:sessionId/messages/pin
Pin a message in its chat for a bounded window.
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 7cba93e10..4eb442c12 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -274,6 +274,16 @@ curl "$BASE/api/sessions/$SESSION_ID/messages/[email protected]/true_62812345678
-H "X-API-Key: $API_KEY"
```
+#### POST /api/sessions/:sessionId/messages/vote-poll
+
+Vote on a poll (whatsapp-web.js only).
+
+```bash
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/vote-poll" \
+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
+ -d '{"chatId":"[email protected]","pollMessageId":"[email protected]_3EB0ABCD","options":["Pizza"]}'
+```
+
#### POST /api/sessions/:sessionId/messages/pin
Pin a message for 24h (default), 7d or 30d.
diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.md
index f782877b3..a9c89477a 100644
--- a/docs/18-sdk-design.md
+++ b/docs/18-sdk-design.md
@@ -29,7 +29,7 @@ All five SDKs expose the same fluent surface:
| Resource | Methods |
| --- | --- |
| `sessions` | list, get, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, stats |
-| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, star, sendBulk, batchStatus, cancelBatch |
+| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, star, votePoll, sendBulk, batchStatus, cancelBatch |
| `contacts` | list, get, check, profilePicture, profilePictures, phone, upsert, delete, block, unblock |
| `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, getGroupSettings, updateGroupSettings, leave, getPicture, setPicture, deletePicture, inviteCode, revokeInviteCode |
| `webhooks` | list, get, create, update, delete, test |
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index 38df95749..5967841d4 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -168,9 +168,9 @@ These are hand-maintained and had drifted from the source before this pass; they
from `engine-capability-matrix.ts` rather than adjusted by hand. Re-derive them the same way when
adding a method, instead of incrementing the previous figure.
-- **90** interface methods, **180** adapter-cells (90 × 2 engines).
-- **163** supported cells; **17** not-available cells across **16** methods.
-- Of the 17 not-available cells: **2 adapter-gaps** (fixable) + **15 library-limitations** + **0 uncertain**.
+- **91** interface methods, **182** adapter-cells (91 × 2 engines).
+- **164** supported cells; **18** not-available cells across **17** methods.
+- Of the 18 not-available cells: **2 adapter-gaps** (fixable) + **16 library-limitations** + **0 uncertain**.
- **0 phantom-support rows** — every `not-available` row throws at the adapter boundary.
Note that the drift gate does **not** verify that for whatsapp-web.js. `engine-parity.spec.ts`
diff --git a/openapi.json b/openapi.json
index 367cf85c8..f5baf7c5d 100644
--- a/openapi.json
+++ b/openapi.json
@@ -2226,6 +2226,50 @@
]
}
},
+ "/api/sessions/{sessionId}/messages/vote-poll": {
+ "post": {
+ "operationId": "MessageController_votePoll",
+ "parameters": [
+ {
+ "name": "sessionId",
+ "required": true,
+ "in": "path",
+ "description": "Session ID",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/VotePollDto"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Vote cast"
+ },
+ "400": {
+ "description": "Session not active, or the target message is not a poll"
+ },
+ "404": {
+ "description": "Poll not found in the chat’s recent history"
+ },
+ "501": {
+ "description": "Not supported on the Baileys engine"
+ }
+ },
+ "summary": "Cast a vote on a poll",
+ "tags": [
+ "messages"
+ ]
+ }
+ },
"/api/sessions/{sessionId}/messages/pin": {
"post": {
"operationId": "MessageController_pinMessage",
@@ -7539,6 +7583,31 @@
"messageId"
]
},
+ "VotePollDto": {
+ "type": "object",
+ "properties": {
+ "chatId": {
+ "type": "string"
+ },
+ "pollMessageId": {
+ "type": "string",
+ "description": "The poll creation message to vote on."
+ },
+ "options": {
+ "description": "The option TEXTS to select, exactly as they appear on the poll. Replaces the current selection; an empty array clears the vote.",
+ "maxItems": 12,
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "chatId",
+ "pollMessageId",
+ "options"
+ ]
+ },
"PinMessageDto": {
"type": "object",
"properties": {
diff --git a/sdk/README.md b/sdk/README.md
index c1d038142..986279cce 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -25,7 +25,7 @@ All five SDKs expose the same fluent resource surface:
| Resource | Methods |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sessions` | list, get, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, stats |
-| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, star, sendBulk, batchStatus, cancelBatch |
+| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, star, votePoll, sendBulk, batchStatus, cancelBatch |
| `contacts` | list, get, check, profilePicture, profilePictures, phone, upsert, delete, block, unblock |
| `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, get/updateGroupSettings, leave, getPicture, setPicture, deletePicture, inviteCode, revokeInviteCode |
| `webhooks` | list, get, create, update, delete, test |
diff --git a/sdk/go/messages.go b/sdk/go/messages.go
index 3b70e5fa9..e750e8f98 100644
--- a/sdk/go/messages.go
+++ b/sdk/go/messages.go
@@ -146,6 +146,15 @@ func (s *MessagesService) Pin(ctx context.Context, sessionID string, body PinMes
return &out, nil
}
+// VotePoll casts a vote on a poll. Not supported on the Baileys engine (501).
+func (s *MessagesService) VotePoll(ctx context.Context, sessionID string, body VotePollRequest) (*SuccessResult, error) {
+ var out SuccessResult
+ if err := s.client.do(ctx, "POST", s.base(sessionID)+"/vote-poll", nil, body, &out); err != nil {
+ return nil, err
+ }
+ return &out, nil
+}
+
// Star stars or unstars a message.
func (s *MessagesService) Star(ctx context.Context, sessionID string, body StarMessageRequest) (*SuccessResult, error) {
var out SuccessResult
diff --git a/sdk/go/routing_test.go b/sdk/go/routing_test.go
index 5dec8b5a6..f801efada 100644
--- a/sdk/go/routing_test.go
+++ b/sdk/go/routing_test.go
@@ -99,6 +99,7 @@ func TestRouting(t *testing.T) {
{"Status.List", func(c *Client) { c.Status.List(ctx, "s1") }, "GET", "/api/sessions/s1/status"},
{"Status.FromContact", func(c *Client) { c.Status.FromContact(ctx, "s1", "u1") }, "GET", "/api/sessions/s1/status/u1"},
{"Messages.Pin", func(c *Client) { c.Messages.Pin(ctx, "s1", PinMessageRequest{}) }, "POST", "/api/sessions/s1/messages/pin"},
+ {"Messages.VotePoll", func(c *Client) { c.Messages.VotePoll(ctx, "s1", VotePollRequest{}) }, "POST", "/api/sessions/s1/messages/vote-poll"},
{"Messages.Star", func(c *Client) { c.Messages.Star(ctx, "s1", StarMessageRequest{}) }, "POST", "/api/sessions/s1/messages/star"},
{"Messages.Unpin", func(c *Client) { c.Messages.Unpin(ctx, "s1", UnpinMessageRequest{}) }, "POST", "/api/sessions/s1/messages/unpin"},
{"Messages.Media", func(c *Client) { c.Messages.Media(ctx, "s1", "c1", "m1") }, "GET", "/api/sessions/s1/messages/c1/m1/media"},
diff --git a/sdk/go/types_message.go b/sdk/go/types_message.go
index 76c1c128e..381831972 100644
--- a/sdk/go/types_message.go
+++ b/sdk/go/types_message.go
@@ -348,3 +348,11 @@ type StarMessageRequest struct {
MessageID string `json:"messageId"`
Star bool `json:"star"`
}
+
+// VotePollRequest casts a vote on a poll. Options are option TEXTS, not ids —
+// no engine surfaces stable per-option ids. An empty slice clears the vote.
+type VotePollRequest struct {
+ ChatID string `json:"chatId"`
+ PollMessageID string `json:"pollMessageId"`
+ Options []string `json:"options"`
+}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/VotePollRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/VotePollRequest.java
new file mode 100644
index 000000000..e244efc66
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/VotePollRequest.java
@@ -0,0 +1,39 @@
+package com.rmyndharis.openwa.model;
+
+import java.util.List;
+
+/**
+ * Request body for voting on a poll. {@code options} are the option TEXTS as they appear on the
+ * poll — no engine surfaces stable per-option ids. The list replaces the current selection; an
+ * empty list clears the vote.
+ */
+public record VotePollRequest(String chatId, String pollMessageId, List<String> options) {
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static final class Builder {
+ private String chatId;
+ private String pollMessageId;
+ private List<String> options;
+
+ public Builder chatId(String v) {
+ this.chatId = v;
+ return this;
+ }
+
+ public Builder pollMessageId(String v) {
+ this.pollMessageId = v;
+ return this;
+ }
+
+ public Builder options(List<String> v) {
+ this.options = v;
+ return this;
+ }
+
+ public VotePollRequest build() {
+ return new VotePollRequest(chatId, pollMessageId, options);
+ }
+ }
+}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java
index 933425f29..4512affb7 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java
@@ -28,6 +28,7 @@ import com.rmyndharis.openwa.model.SendPollRequest;
import com.rmyndharis.openwa.model.SendTemplateRequest;
import com.rmyndharis.openwa.model.SendTextRequest;
import com.rmyndharis.openwa.model.StarMessageRequest;
+import com.rmyndharis.openwa.model.VotePollRequest;
import com.rmyndharis.openwa.model.SuccessResult;
import com.rmyndharis.openwa.model.UnpinMessageRequest;
import java.util.List;
@@ -172,6 +173,16 @@ public final class MessagesResource {
SuccessResult.class);
}
+ /** Cast a vote on a poll. Not supported on the Baileys engine (501). */
+ public SuccessResult votePoll(String sessionId, VotePollRequest body) {
+ return client.request(
+ HttpMethod.POST,
+ "/api/sessions/" + encodeSegment(sessionId) + "/messages/vote-poll",
+ null,
+ body,
+ SuccessResult.class);
+ }
+
/**
* Star or unstar a message. Best-effort on whatsapp-web.js, which silently ignores a message it
* will not star.
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java
index 34a304084..f960ccfe1 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java
@@ -28,6 +28,7 @@ import com.rmyndharis.openwa.model.SendPollRequest;
import com.rmyndharis.openwa.model.SendTemplateRequest;
import com.rmyndharis.openwa.model.SendTextRequest;
import com.rmyndharis.openwa.model.StarMessageRequest;
+import com.rmyndharis.openwa.model.VotePollRequest;
import com.rmyndharis.openwa.model.UnpinMessageRequest;
import com.rmyndharis.openwa.support.MockTransport;
import java.nio.charset.StandardCharsets;
@@ -302,4 +303,13 @@ class MessagesResourceTest {
assertEquals("http://h/api/sessions/s/messages/star", tx.lastRequest().url());
assertEquals(HttpMethod.POST, tx.lastRequest().method());
}
+
+ @Test
+ void votePollPostsToItsRoute() {
+ tx.respond(200, "{\"success\":true}");
+ client.messages.votePoll(
+ "s", VotePollRequest.builder().chatId("c1").pollMessageId("p1").options(List.of("Pizza")).build());
+ assertEquals("http://h/api/sessions/s/messages/vote-poll", tx.lastRequest().url());
+ assertEquals(HttpMethod.POST, tx.lastRequest().method());
+ }
}
diff --git a/sdk/javascript/src/resources/messages.ts b/sdk/javascript/src/resources/messages.ts
index 73e36140e..b21576c9f 100644
--- a/sdk/javascript/src/resources/messages.ts
+++ b/sdk/javascript/src/resources/messages.ts
@@ -31,6 +31,7 @@ import type {
SendMediaRequest,
StarMessageRequest,
UnpinMessageRequest,
+ VotePollRequest,
SendPollRequest,
SendTemplateRequest,
SendTextRequest,
@@ -193,6 +194,18 @@ export class MessagesResource {
});
}
+ /**
+ * Cast a vote on a poll. Not supported on the Baileys engine (501).
+ * `options` are the option texts, not ids.
+ */
+ votePoll(sessionId: string, body: VotePollRequest): Promise<SuccessResult> {
+ return this.client.request<SuccessResult>({
+ method: 'POST',
+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/vote-poll`,
+ body,
+ });
+ }
+
/**
* Star or unstar a message. Best-effort on whatsapp-web.js: it silently ignores a message it
* will not star, so a resolved call is not proof the star is set.
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index fc695cb49..bf639f8da 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -209,6 +209,17 @@ export interface ArchiveChatRequest {
archive: boolean;
}
+export interface VotePollRequest {
+ chatId: Jid;
+ /** The poll creation message to vote on. */
+ pollMessageId: string;
+ /**
+ * Option TEXTS to select, exactly as they appear on the poll — there are no option ids.
+ * Replaces the current selection; an empty array clears the vote.
+ */
+ options: string[];
+}
+
export interface StarMessageRequest {
chatId: Jid;
messageId: string;
diff --git a/sdk/javascript/test/resources.test.ts b/sdk/javascript/test/resources.test.ts
index e9597caab..b55754849 100644
--- a/sdk/javascript/test/resources.test.ts
+++ b/sdk/javascript/test/resources.test.ts
@@ -215,6 +215,13 @@ describe('StatusResource — nested media bodies', () => {
expect(t.lastCall!.body).toEqual({ video: { url: 'http://vid' }, recipients: ['[email protected]'] });
});
+ it('votePoll posts the option texts', async () => {
+ const t = new MockTransport().on('POST', /\/messages\/vote-poll$/, { body: { success: true } });
+ await client(t).messages.votePoll('s', { chatId: 'c1', pollMessageId: 'p1', options: ['Pizza'] });
+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/messages/vote-poll');
+ expect(t.lastCall!.body).toEqual({ chatId: 'c1', pollMessageId: 'p1', options: ['Pizza'] });
+ });
+
it('star posts the boolean through', async () => {
const t = new MockTransport().on('POST', /\/messages\/star$/, { body: { success: true } });
await client(t).messages.star('s', { chatId: 'c1', messageId: 'm1', star: false });
diff --git a/sdk/php/src/Resources/MessagesResource.php b/sdk/php/src/Resources/MessagesResource.php
index 8a50ff023..82d5c5275 100644
--- a/sdk/php/src/Resources/MessagesResource.php
+++ b/sdk/php/src/Resources/MessagesResource.php
@@ -175,6 +175,17 @@ class MessagesResource
return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/pin", [], $body) ?? [];
}
+ /**
+ * Cast a vote on a poll. Not supported on the Baileys engine (501).
+ *
+ * @param array<string,mixed> $body chatId, pollMessageId and options (option TEXTS; [] clears).
+ * @return array<string,mixed>
+ */
+ public function votePoll(string $sessionId, array $body): array
+ {
+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/vote-poll", [], $body) ?? [];
+ }
+
/**
* Star or unstar a message. Best-effort on whatsapp-web.js, which silently ignores a message
* it will not star.
diff --git a/sdk/php/tests/ResourcesTest.php b/sdk/php/tests/ResourcesTest.php
index 4b9612ec8..5deb5c86a 100644
--- a/sdk/php/tests/ResourcesTest.php
+++ b/sdk/php/tests/ResourcesTest.php
@@ -304,6 +304,16 @@ class ResourcesTest extends TestCase
$this->assertSame(['video' => ['url' => 'http://vid'], 'recipients' => ['[email protected]']], $backend->lastCall()['body']);
}
+ public function testVotePollPostsOptionTexts(): void
+ {
+ $backend = new MockBackend();
+ $backend->on(200, ['success' => true]);
+ $client = $backend->makeClient();
+ $client->messages->votePoll('s', ['chatId' => 'c1', 'pollMessageId' => 'p1', 'options' => ['Pizza']]);
+ $this->assertSame('/api/sessions/s/messages/vote-poll', $backend->lastCall()['path']);
+ $this->assertSame('POST', $backend->lastCall()['method']);
+ }
+
public function testStarPostsTheBooleanThrough(): void
{
$backend = new MockBackend();
diff --git a/sdk/python/openwa/resources/messages.py b/sdk/python/openwa/resources/messages.py
index ca1ef2b18..9391c44bf 100644
--- a/sdk/python/openwa/resources/messages.py
+++ b/sdk/python/openwa/resources/messages.py
@@ -13,6 +13,7 @@ from ..types import (
MessageMedia,
PinMessageRequest,
StarMessageRequest,
+ VotePollRequest,
UnpinMessageRequest,
BatchStatusResponse,
BulkMessageResponse,
@@ -115,6 +116,10 @@ class MessagesResource:
"""Pin a message. ``durationSeconds`` must be 86400, 604800 or 2592000; defaults to 24h."""
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/pin", body=body)
+ def vote_poll(self, session_id: str, body: VotePollRequest) -> SuccessResult:
+ """Cast a vote on a poll. Not supported on the Baileys engine (501)."""
+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/vote-poll", body=body)
+
def star(self, session_id: str, body: StarMessageRequest) -> SuccessResult:
"""Star or unstar a message. Best-effort on whatsapp-web.js."""
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/star", body=body)
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index 2f14cbc9a..d2931a219 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -665,6 +665,14 @@ class ArchiveChatRequest(TypedDict):
archive: bool
+class VotePollRequest(TypedDict):
+ """Vote on a poll. options are option TEXTS (no ids); [] clears the vote."""
+
+ chatId: str
+ pollMessageId: str
+ options: list[str]
+
+
class StarMessageRequest(TypedDict):
"""Star or unstar a message. Best-effort on whatsapp-web.js."""
diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py
index 16c8eae69..23c4a560e 100644
--- a/sdk/python/tests/test_sdk.py
+++ b/sdk/python/tests/test_sdk.py
@@ -497,6 +497,12 @@ class TestStatus:
client.status.send_video("s", {"video": {"url": "http://vid"}, "recipients": ["[email protected]"]})
assert backend.calls[-1].body == {"video": {"url": "http://vid"}, "recipients": ["[email protected]"]}
+ def test_vote_poll_posts_option_texts(self):
+ backend = MockBackend().on("POST", "/messages/vote-poll", body={"success": True})
+ make_client(backend).messages.vote_poll("s", {"chatId": "c1", "pollMessageId": "p1", "options": ["Pizza"]})
+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s/messages/vote-poll"
+ assert backend.last_call.body == {"chatId": "c1", "pollMessageId": "p1", "options": ["Pizza"]}
+
def test_star_posts_the_boolean_through(self):
backend = MockBackend().on("POST", "/messages/star", body={"success": True})
make_client(backend).messages.star("s", {"chatId": "c1", "messageId": "m1", "star": False})
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 21a81f568..ee05fae27 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -2530,6 +2530,13 @@ describe('BaileysAdapter store-backed ops', () => {
);
});
+ it('votePoll is an honest 501 — Baileys has no vote-send helper, only decryptPollVote', async () => {
+ const adapter = await ready();
+ await expect(adapter.votePoll('[email protected]', 'P1', ['Pizza'])).rejects.toBeInstanceOf(
+ EngineNotSupportedError,
+ );
+ });
+
it('pinMessage pins IN CHAT via the stored key, with the requested window', async () => {
fakeStore.getMessage.mockResolvedValue(stored);
const adapter = await ready();
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 67ee4ea32..589b4a3b2 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -511,6 +511,13 @@ export class BaileysAdapter implements IWhatsAppEngine {
getMessageReactions(_chatId: string, _messageId: string): Promise<MessageReaction[]> {
return this.unsupported('getMessageReactions');
}
+
+ // No vote-send helper exists in Baileys — only decryptPollVote for RECEIVING. Sending one needs a
+ // hand-built proto.Message.PollUpdateMessage with HMAC-SHA256 vote encryption keyed by the poll
+ // creation's messageSecret.
+ votePoll(_chatId: string, _pollMessageId: string, _options: string[]): Promise<void> {
+ return this.unsupported('votePoll');
+ }
getChatHistory(
_chatId: string,
_limit?: number,
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index c6f394c90..2834b4f2f 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -17,7 +17,7 @@ import { getEffectiveWebVersionInfo, resolveWebVersionPin, __resetWebVersionCach
import * as fs from 'fs';
import * as path from 'path';
import * as qrcode from 'qrcode';
-import { InternalServerErrorException, UnprocessableEntityException } from '@nestjs/common';
+import { InternalServerErrorException, UnprocessableEntityException, BadRequestException } from '@nestjs/common';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
import { MessageNotFoundError } from '../../common/errors/message-not-found.error';
import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';
@@ -3654,6 +3654,57 @@ describe('editMessage', () => {
});
});
+describe('votePoll', () => {
+ const ready = (client: unknown): WhatsAppWebJsAdapter => {
+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });
+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.READY;
+ (adapter as unknown as { client: unknown }).client = client;
+ return adapter;
+ };
+ const chatWith = (messages: unknown[]) => ({
+ getChatById: jest.fn().mockResolvedValue({ fetchMessages: jest.fn().mockResolvedValue(messages) }),
+ });
+
+ it('passes the option TEXTS straight through — wwjs matches by name, not id', async () => {
+ const vote = jest.fn().mockResolvedValue(undefined);
+ const adapter = ready(chatWith([{ id: { _serialized: 'P1' }, vote }]));
+ await adapter.votePoll('[email protected]', 'P1', ['Pizza', 'Sushi']);
+ expect(vote).toHaveBeenCalledWith(['Pizza', 'Sushi']);
+ });
+
+ it('passes an empty array through to clear the vote', async () => {
+ const vote = jest.fn().mockResolvedValue(undefined);
+ const adapter = ready(chatWith([{ id: { _serialized: 'P1' }, vote }]));
+ await adapter.votePoll('[email protected]', 'P1', []);
+ expect(vote).toHaveBeenCalledWith([]);
+ });
+
+ it('maps the BARE STRING throw on a non-poll target to a 400, not an opaque 500', async () => {
+ // Message.js:1010 throws a plain string, which would otherwise escape as an unhandled
+ // non-Error and surface as a 500 for what is really a client mistake.
+ const vote = jest.fn().mockRejectedValue('Invalid usage! Can only be used with a pollCreation message');
+ const adapter = ready(chatWith([{ id: { _serialized: 'M1' }, vote }]));
+ const err = await adapter.votePoll('[email protected]', 'M1', ['x']).catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(BadRequestException);
+ expect((err as Error).message).toMatch(/is not a poll/);
+ });
+
+ it('propagates a genuine Error unchanged rather than calling it a client mistake', async () => {
+ const vote = jest.fn().mockRejectedValue(new Error('Evaluation failed'));
+ const adapter = ready(chatWith([{ id: { _serialized: 'P1' }, vote }]));
+ const err = await adapter.votePoll('[email protected]', 'P1', ['x']).catch((e: unknown) => e);
+ // Asserting the TYPE, not the message: a wrapped error would still contain the original text,
+ // so a message match alone would not notice a real engine fault being downgraded to a 400.
+ expect(err).not.toBeInstanceOf(BadRequestException);
+ expect((err as Error).message).toBe('Evaluation failed');
+ });
+
+ it('404s for a poll outside the 100-message fetch window', async () => {
+ const adapter = ready(chatWith([]));
+ await expect(adapter.votePoll('[email protected]', 'OLD', ['x'])).rejects.toBeInstanceOf(MessageNotFoundError);
+ });
+});
+
describe('pinMessage / unpinMessage', () => {
const ready = (client: unknown): WhatsAppWebJsAdapter => {
const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 48ae069b0..1dbb0bddf 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -1442,6 +1442,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
return this.messaging.pinMessage(chatId, messageId, durationSeconds);
}
+ votePoll(chatId: string, pollMessageId: string, options: string[]): Promise<void> {
+ return this.messaging.votePoll(chatId, pollMessageId, options);
+ }
+
unpinMessage(chatId: string, messageId: string): Promise<void> {
return this.messaging.unpinMessage(chatId, messageId);
}
diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.ts
index 61c4850d6..d2d036f8e 100644
--- a/src/engine/adapters/wwebjs-messaging.ts
+++ b/src/engine/adapters/wwebjs-messaging.ts
@@ -10,6 +10,7 @@ import {
PollInput,
} from '../interfaces/whatsapp-engine.interface';
import { MessageWithReactions, SerializedWid } from '../types/whatsapp-web-js.types';
+import { BadRequestException } from '@nestjs/common';
import { MessageNotFoundError } from '../../common/errors/message-not-found.error';
import { EngineRefusedError } from '../../common/errors/engine-refused.error';
import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';
@@ -675,6 +676,25 @@ export class WwebjsMessaging {
return message;
}
+ async votePoll(chatId: string, pollMessageId: string, options: string[]): Promise<void> {
+ this.host.ensureReady();
+ // Same 100-message window as pin/react/delete, so a poll older than that is unreachable and
+ // reported as not-found rather than as a failed vote.
+ const message = await this.findInFetchWindow(chatId, pollMessageId);
+ try {
+ await (message as unknown as { vote(selected: string[]): Promise<void> }).vote(options);
+ } catch (error) {
+ // vote() throws a BARE STRING (not an Error) when the target is not a poll creation message
+ // (Message.js:1010). Left alone that surfaces as an opaque 500; it is a client mistake, so
+ // map it to a 400. Anything that is a real Error is a genuine engine fault and propagates.
+ if (typeof error === 'string') {
+ throw new BadRequestException(`Message ${pollMessageId} is not a poll: ${error}`);
+ }
+ throw error;
+ }
+ this.host.logger.log(`Voted on poll ${pollMessageId} in chat ${chatId} (${options.length} option(s))`);
+ }
+
async pinMessage(chatId: string, messageId: string, durationSeconds: number): Promise<void> {
this.host.ensureReady();
const message = await this.findInFetchWindow(chatId, messageId);
diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.ts
index 64d22b06c..edb22c2c5 100644
--- a/src/engine/engine-capability-matrix.ts
+++ b/src/engine/engine-capability-matrix.ts
@@ -336,6 +336,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {
evidence:
"wwjs Client.saveOrEditAddressbookContact(phoneNumber, firstName, lastName, syncToAddressbook=false) → void (index.d.ts:293-299; Client.js:3266) — lastName is positional and required, so an absent one is passed as ''; baileys addOrEditContact(jid, IContactAction{firstName,fullName,saveOnPrimaryAddressbook}) (Socket/chats.d.ts:66; WAProto IContactAction:11812)",
},
+ votePoll: {
+ wwjs: { status: 'supported' },
+ baileys: { status: 'not-available', rootCause: 'library-limitation' },
+ evidence:
+ "wwjs Message.vote(selectedOptions: string[]) (index.d.ts:1376) matches poll options BY NAME against msg.pollOptions and throws a bare STRING on a non-poll target (Message.js:1009-1040); baileys has no vote-send helper at all — only decryptPollVote for RECEIVING (Utils/messages.d.ts), so sending needs a hand-built proto.Message.PollUpdateMessage with HMAC-SHA256 vote encryption keyed by the poll creation's messageSecret",
+ },
unblockContact: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
unpinMessage: {
wwjs: { status: 'supported' },
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 1e29b744f..84e5ccab1 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -719,6 +719,17 @@ export interface IWhatsAppEngine {
* it is not visible to the other party and has no group-admin restriction.
*/
starMessage(chatId: string, messageId: string, star: boolean): Promise<void>;
+ /**
+ * Cast a vote on a poll. `options` are the option TEXTS, not ids: whatsapp-web.js matches by name
+ * (`Message.js:1027-1031`), and no engine surfaces a stable per-option id through this interface,
+ * so a caller has nothing else to name an option by. Pass every option that should end up
+ * selected — the list replaces the current selection rather than adding to it, and an empty array
+ * clears the vote.
+ *
+ * A poll whose options include duplicate texts will select ALL matching options; WhatsApp permits
+ * duplicates, and the name is the only handle available.
+ */
+ votePoll(chatId: string, pollMessageId: string, options: string[]): Promise<void>;
/**
* Pin a message in its chat for a bounded window. WhatsApp only recognises three durations —
* 86400 (24h), 604800 (7d), 2592000 (30d) — so `durationSeconds` must be one of those; it is
diff --git a/src/modules/message/dto/message-actions.dto.ts b/src/modules/message/dto/message-actions.dto.ts
index 8c38e4770..08581c942 100644
--- a/src/modules/message/dto/message-actions.dto.ts
+++ b/src/modules/message/dto/message-actions.dto.ts
@@ -224,6 +224,33 @@ export class PinMessageDto {
durationSeconds?: number;
}
+/** Cap on how many options one vote may select — WhatsApp polls hold at most 12. */
+export const POLL_VOTE_MAX_OPTIONS = 12;
+
+export class VotePollDto {
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ chatId: string;
+
+ @ApiProperty({ description: 'The poll creation message to vote on.' })
+ @IsString()
+ @IsNotEmpty()
+ pollMessageId: string;
+
+ @ApiProperty({
+ description:
+ 'The option TEXTS to select, exactly as they appear on the poll. Replaces the current ' +
+ 'selection; an empty array clears the vote.',
+ type: [String],
+ maxItems: POLL_VOTE_MAX_OPTIONS,
+ })
+ @IsArray()
+ @ArrayMaxSize(POLL_VOTE_MAX_OPTIONS)
+ @IsString({ each: true })
+ options: string[];
+}
+
export class StarMessageDto {
@ApiProperty()
@IsString()
diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.ts
index 9616011ba..a041b40de 100644
--- a/src/modules/message/message.controller.ts
+++ b/src/modules/message/message.controller.ts
@@ -17,6 +17,7 @@ import {
EditMessageDto,
PinMessageDto,
StarMessageDto,
+ VotePollDto,
UnpinMessageDto,
} from './dto/message-actions.dto';
import { RequireRole } from '../auth/decorators/auth.decorators';
@@ -407,6 +408,19 @@ export class MessageController {
return { success: true };
}
+ @Post('vote-poll')
+ @HttpCode(HttpStatus.OK)
+ @RequireRole(ApiKeyRole.OPERATOR)
+ @ApiOperation({ summary: 'Cast a vote on a poll' })
+ @ApiParam({ name: 'sessionId', description: 'Session ID' })
+ @ApiResponse({ status: 200, description: 'Vote cast' })
+ @ApiResponse({ status: 400, description: 'Session not active, or the target message is not a poll' })
+ @ApiResponse({ status: 404, description: 'Poll not found in the chat’s recent history' })
+ @ApiResponse({ status: 501, description: 'Not supported on the Baileys engine' })
+ async votePoll(@Param('sessionId') sessionId: string, @Body() dto: VotePollDto): Promise<{ success: boolean }> {
+ return this.messageService.votePoll(sessionId, dto);
+ }
+
// ========== Pin / Unpin ==========
@Post('pin')
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index bfd39fe02..d7f6ebb22 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -34,6 +34,7 @@ function createMockEngine() {
deleteMessage: jest.fn().mockResolvedValue(undefined),
pinMessage: jest.fn().mockResolvedValue(undefined),
starMessage: jest.fn().mockResolvedValue(undefined),
+ votePoll: jest.fn().mockResolvedValue(undefined),
unpinMessage: jest.fn().mockResolvedValue(undefined),
editMessage: jest.fn().mockResolvedValue(mockEngineResult),
getChatHistory: jest.fn().mockResolvedValue([]),
@@ -1455,6 +1456,18 @@ describe('MessageService', () => {
});
});
+ describe('votePoll', () => {
+ it('passes the option texts through unchanged', async () => {
+ await service.votePoll('sess-1', { chatId: '[email protected]', pollMessageId: 'P1', options: ['A', 'B'] });
+ expect(mockEngine.votePoll).toHaveBeenCalledWith('[email protected]', 'P1', ['A', 'B']);
+ });
+
+ it('forwards an empty selection, which clears the vote rather than being a no-op', async () => {
+ await service.votePoll('sess-1', { chatId: '[email protected]', pollMessageId: 'P1', options: [] });
+ expect(mockEngine.votePoll).toHaveBeenCalledWith('[email protected]', 'P1', []);
+ });
+ });
+
describe('starMessage', () => {
it.each([true, false])('passes star=%s straight through to the engine', async star => {
await service.starMessage('sess-1', { chatId: '[email protected]', messageId: 'M1', star });
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index 83e75ea84..9afaada25 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -818,6 +818,16 @@ export class MessageService {
return { success: true };
}
+ /**
+ * Cast a vote on a poll. Not supported on the Baileys engine, which surfaces as a 501 from the
+ * adapter. `options` are option texts — see the engine interface for why there are no ids.
+ */
+ async votePoll(sessionId: string, dto: { chatId: string; pollMessageId: string; options: string[] }) {
+ const engine = this.getEngine(sessionId);
+ await engine.votePoll(dto.chatId, dto.pollMessageId, dto.options);
+ return { success: true };
+ }
+
async deleteMessage(
sessionId: string,
dto: { chatId: string; messageId: string; forEveryone?: boolean },