Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(message): native WhatsApp polls via send-poll on both engines (#622)
Alejandroca6777c9cc03
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6eaa5aa18..b94884a4b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **Native WhatsApp polls** via `POST /api/sessions/:sessionId/messages/send-poll`: question, 2–12 options and an optional `allowMultipleAnswers` flag (default single choice), implemented on both engines (whatsapp-web.js `Poll`, Baileys `poll` content with `selectableCount` 1/0). The message history stores the poll question as the body so the log stays readable.+## [0.8.7] - 2026-07-03### Addeddiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex c1d0bf148..eab39caa2 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -1138,6 +1138,39 @@ Send a sticker (by URL or base64; typically webp). Reuses `SendMediaMessageDto`.**Errors:** `400` media validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error+#### POST /api/sessions/:sessionId/messages/send-poll++Send a native WhatsApp poll.++**Auth:** API key (OPERATOR)++**Path parameters**++| Name | Type | Description |+| --- | --- | --- |+| sessionId | string | Session ID |++**Request body** — `SendPollDto`++| Field | Type | Required | Constraints | Description |+| --- | --- | --- | --- | --- |+| chatId | string | Yes | non-empty | Target chat |+| name | string | Yes | max 255 | Poll question / title |+| options | string[] | Yes | 2–12 items, each non-empty, max 100 chars | Options to vote on |+| allowMultipleAnswers | boolean | No | — | Allow picking several options (default single choice) |++```json+{ "chatId": "[email protected]", "name": "Where should we meet?", "options": ["Park", "Beach", "Downtown"], "allowMultipleAnswers": false }+```++**Response** `201`++```json+{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }+```++**Errors:** `400` validation failure (option count/length) / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error+#### POST /api/sessions/:sessionId/messages/replyReply to a message, quoting a prior message.diff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex 2e341a6f0..8864ee58a 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -331,6 +331,17 @@ curl -X POST "$BASE/api/sessions/my-session/messages/send-sticker" \-d '{ "chatId": "[email protected]", "url": "https://example.com/sticker.webp", "mimetype": "image/webp" }'```+#### POST /api/sessions/:sessionId/messages/send-poll++Send a native WhatsApp poll (2–12 options; single choice unless `allowMultipleAnswers` is true).++```bash+curl -X POST "$BASE/api/sessions/my-session/messages/send-poll" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/json" \+ -d '{ "chatId": "[email protected]", "name": "Where should we meet?", "options": ["Park", "Beach", "Downtown"] }'+```+#### POST /api/sessions/:sessionId/messages/replyReply to a message, quoting a prior one.diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 657f4cfce..a0e1a3255 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -487,7 +487,7 @@ describe('BaileysAdapter capability gating', () => {});});-describe('BaileysAdapter location + contact sends', () => {+describe('BaileysAdapter location + contact + poll sends', () => {beforeEach(() => {fakeSock.user = { id: '628999:[email protected]', name: 'Me' };fakeSock.resetEmitter();@@ -537,6 +537,26 @@ describe('BaileysAdapter location + contact sends', () => {expect(vcard).not.toMatch(/\nEMAIL:evil@x\.com/);expect(vcard).toContain('FN:Eve EMAIL:[email protected]');});++ it('sendPollMessage maps name/values and defaults to single choice (selectableCount 1)', async () => {+ const adapter = await ready();+ await adapter.sendPollMessage('[email protected]', { name: 'Where?', options: ['Park', 'Beach'] });+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {+ poll: { name: 'Where?', values: ['Park', 'Beach'], selectableCount: 1 },+ });+ });++ it('sendPollMessage uses selectableCount 0 (no limit) when multiple answers are allowed', async () => {+ const adapter = await ready();+ await adapter.sendPollMessage('[email protected]', {+ name: 'Toppings?',+ options: ['Cheese', 'Ham', 'Olives'],+ allowMultipleAnswers: true,+ });+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {+ poll: { name: 'Toppings?', values: ['Cheese', 'Ham', 'Olives'], selectableCount: 0 },+ });+ });});describe('BaileysAdapter messaging', () => {diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 38c0352ac..e341405ba 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -25,6 +25,7 @@ import {MessageReaction,MessageResult,PaginatedProducts,+ PollInput,Product,ProductQueryOptions,ReactionEvent,@@ -581,6 +582,19 @@ export class BaileysAdapter implements IWhatsAppEngine {});}+ async sendPollMessage(chatId: string, poll: PollInput): Promise<MessageResult> {+ this.ensureReady();+ // selectableCount 1 = single choice; 0 = no limit, which is how WhatsApp expresses+ // "allow multiple answers". Baileys generates the poll's messageSecret itself.+ return this.sendContent(chatId, {+ poll: {+ name: poll.name,+ values: poll.options,+ selectableCount: poll.allowMultipleAnswers ? 0 : 1,+ },+ });+ }+async replyToMessage(chatId: string, quotedMsgId: string, text: string): Promise<MessageResult> {this.ensureReady();const quoted = await this.requireStored(quotedMsgId);diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 9f562d1f5..50c59d725 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -255,6 +255,56 @@ describe('WhatsAppWebJsAdapter.getChatHistory enrichment (parity with the live p});});+describe('WhatsAppWebJsAdapter.sendPollMessage', () => {+ const readyAdapter = (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;+ };++ it('sends a wwebjs Poll with mapped options and the allowMultipleAnswers flag', async () => {+ const sendMessage = jest.fn().mockResolvedValue({ id: { _serialized: 'POLL1' }, timestamp: 1700000010 });+ const result = await readyAdapter({ sendMessage }).sendPollMessage('[email protected]', {+ name: 'Where?',+ options: ['Park', 'Beach'],+ allowMultipleAnswers: true,+ });++ expect(result).toEqual({ id: 'POLL1', timestamp: 1700000010 });+ const [to, poll] = sendMessage.mock.calls[0] as [+ string,+ {+ pollName: string;+ pollOptions: { name: string; localId: number }[];+ options: { allowMultipleAnswers: boolean };+ },+ ];+ expect(to).toBe('[email protected]');+ expect(poll.pollName).toBe('Where?');+ expect(poll.pollOptions).toEqual([+ { name: 'Park', localId: 0 },+ { name: 'Beach', localId: 1 },+ ]);+ expect(poll.options.allowMultipleAnswers).toBe(true);+ });++ it('defaults to single choice (allowMultipleAnswers false) when the flag is omitted', async () => {+ const sendMessage = jest.fn().mockResolvedValue({ id: { _serialized: 'POLL2' }, timestamp: 1700000011 });+ await readyAdapter({ sendMessage }).sendPollMessage('[email protected]', { name: 'Q', options: ['A', 'B'] });++ const [, poll] = sendMessage.mock.calls[0] as [string, { options: { allowMultipleAnswers: boolean } }];+ expect(poll.options.allowMultipleAnswers).toBe(false);+ });++ it('rejects with EngineNotReadyError when the session is not connected', async () => {+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });+ await expect(adapter.sendPollMessage('[email protected]', { name: 'Q', options: ['A', 'B'] })).rejects.toBeInstanceOf(+ EngineNotReadyError,+ );+ });+});+describe('WhatsAppWebJsAdapter.forwardMessage (returns the real sent id, not a synthetic fwd_ id)', () => {const readyAdapter = (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.tsindex 497a3b34a..cf219d295 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -15,6 +15,7 @@ import {GroupInfo,GroupParticipant,LocationInput,+ PollInput,ContactCard,MessageReaction,Label,@@ -1100,6 +1101,28 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin};}+ async sendPollMessage(chatId: string, poll: PollInput): Promise<MessageResult> {+ this.ensureReady();+ // Import Poll dynamically like Location; the .default fallback covers builds where the+ // classes land on module.default (a plain `module.Poll` would be undefined there and+ // `new Poll` fails with "not a constructor").+ const module = await import('whatsapp-web.js');+ const Poll = module.Poll || module.default?.Poll;++ // wwebjs's typings mark `messageSecret` as required, but at runtime it is optional (it is+ // only used as a custom poll id), so cast to the constructor's options type to pass just+ // allowMultipleAnswers.+ type PollSendOptions = ConstructorParameters<typeof Poll>[2];+ const pollOptions = { allowMultipleAnswers: poll.allowMultipleAnswers === true } as PollSendOptions;+ const msg = await this.sendResolved(chatId, to =>+ this.client!.sendMessage(to, new Poll(poll.name, poll.options, pollOptions)),+ );+ return {+ id: msg.id._serialized,+ timestamp: msg.timestamp,+ };+ }+async replyToMessage(chatId: string, quotedMsgId: string, text: string): Promise<MessageResult> {this.ensureReady();// Find the message to quotediff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex a52e2f113..a2d4ee3e0 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -206,6 +206,15 @@ export interface LocationInput {address?: string;}+export interface PollInput {+ /** Poll question / title. */+ name: string;+ /** Options to vote on (WhatsApp accepts between 2 and 12). */+ options: string[];+ /** When true a voter can pick several options; default is single choice. */+ allowMultipleAnswers?: boolean;+}+export interface ReactionSender {senderId: string;emoji: string;@@ -441,6 +450,7 @@ export interface IWhatsAppEngine {sendLocationMessage(chatId: string, location: LocationInput): Promise<MessageResult>;sendContactMessage(chatId: string, contact: ContactCard): Promise<MessageResult>;sendStickerMessage(chatId: string, media: MediaInput): Promise<MessageResult>;+ sendPollMessage(chatId: string, poll: PollInput): Promise<MessageResult>;// Reply & ForwardreplyToMessage(chatId: string, quotedMsgId: string, text: string): Promise<MessageResult>;diff --git a/src/modules/message/dto/message-actions.dto.spec.ts b/src/modules/message/dto/message-actions.dto.spec.tsindex a1b2e21c6..5c43413f0 100644--- a/src/modules/message/dto/message-actions.dto.spec.ts+++ b/src/modules/message/dto/message-actions.dto.spec.ts@@ -1,6 +1,12 @@import { plainToInstance } from 'class-transformer';import { validate, ValidationError } from 'class-validator';-import { SendLocationDto, ReactMessageDto, DeleteMessageDto, ForwardMessageDto } from './message-actions.dto';+import {+ SendLocationDto,+ SendPollDto,+ ReactMessageDto,+ DeleteMessageDto,+ ForwardMessageDto,+} from './message-actions.dto';/*** Regression locks: these endpoints previously took inline @Body literals (no@@ -33,6 +39,41 @@ describe('message action DTOs', () => {expect(errs.some(e => e.property === 'latitude')).toBe(true);});+ it('SendPollDto: a valid poll passes', async () => {+ expect(+ await errorsFor(SendPollDto, { chatId: '[email protected]', name: 'Where?', options: ['Park', 'Beach'] }),+ ).toHaveLength(0);+ });++ it('SendPollDto: fewer than 2 options is rejected', async () => {+ const errs = await errorsFor(SendPollDto, { chatId: '[email protected]', name: 'Q', options: ['Only one'] });+ expect(errs.some(e => e.property === 'options')).toBe(true);+ });++ it('SendPollDto: more than 12 options is rejected (WhatsApp cap)', async () => {+ const errs = await errorsFor(SendPollDto, {+ chatId: '[email protected]',+ name: 'Q',+ options: Array.from({ length: 13 }, (_, i) => `Opt ${i}`),+ });+ expect(errs.some(e => e.property === 'options')).toBe(true);+ });++ it('SendPollDto: an empty option is rejected', async () => {+ const errs = await errorsFor(SendPollDto, { chatId: '[email protected]', name: 'Q', options: ['A', ''] });+ expect(errs.some(e => e.property === 'options')).toBe(true);+ });++ it('SendPollDto: allowMultipleAnswers must be boolean when present', async () => {+ const errs = await errorsFor(SendPollDto, {+ chatId: '[email protected]',+ name: 'Q',+ options: ['A', 'B'],+ allowMultipleAnswers: 'yes',+ });+ expect(errs.some(e => e.property === 'allowMultipleAnswers')).toBe(true);+ });+it('ReactMessageDto: empty emoji is VALID (removes the reaction — foot-gun preserved)', async () => {expect(await errorsFor(ReactMessageDto, { chatId: '[email protected]', messageId: 'm1', emoji: '' })).toHaveLength(0);});diff --git a/src/modules/message/dto/message-actions.dto.ts b/src/modules/message/dto/message-actions.dto.tsindex a8e97d65b..2bc03b330 100644--- a/src/modules/message/dto/message-actions.dto.ts+++ b/src/modules/message/dto/message-actions.dto.ts@@ -1,5 +1,16 @@import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';-import { IsString, IsNotEmpty, IsOptional, IsLatitude, IsLongitude, IsBoolean, MaxLength } from 'class-validator';+import {+ IsString,+ IsNotEmpty,+ IsOptional,+ IsLatitude,+ IsLongitude,+ IsBoolean,+ IsArray,+ ArrayMinSize,+ ArrayMaxSize,+ MaxLength,+} from 'class-validator';/*** Validated DTOs for the message action endpoints. These replaced inline@@ -53,6 +64,39 @@ export class SendContactDto {contactNumber: string;}+export class SendPollDto {+ @ApiProperty({ description: 'Chat ID (e.g. [email protected] or [email protected])' })+ @IsString()+ @IsNotEmpty()+ chatId: string;++ @ApiProperty({ description: 'Poll question / title', maxLength: 255, example: 'Where should we meet?' })+ @IsString()+ @IsNotEmpty()+ @MaxLength(255)+ name: string;++ // WhatsApp itself caps polls at 12 options and ~100 chars per option; validating here keeps the+ // failure a clean 400 instead of an engine error deep in the send path.+ @ApiProperty({+ description: 'Options to vote on (WhatsApp allows between 2 and 12)',+ type: [String],+ example: ['Park', 'Beach', 'Downtown'],+ })+ @IsArray()+ @ArrayMinSize(2)+ @ArrayMaxSize(12)+ @IsString({ each: true })+ @IsNotEmpty({ each: true })+ @MaxLength(100, { each: true })+ options: string[];++ @ApiPropertyOptional({ description: 'Allow voters to pick several options (default single choice)' })+ @IsOptional()+ @IsBoolean()+ allowMultipleAnswers?: boolean;+}+export class ReplyMessageDto {@ApiProperty()@IsString()diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex ba1343911..72e659644 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -8,6 +8,7 @@ import { SendBulkMessageDto, BulkMessageResponseDto } from './dto/bulk-message.dimport {SendLocationDto,SendContactDto,+ SendPollDto,ReplyMessageDto,ForwardMessageDto,ReactMessageDto,@@ -217,6 +218,19 @@ export class MessageController {return this.messageService.sendSticker(sessionId, dto);}+ @Post('send-poll')+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Send a native WhatsApp poll' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiResponse({+ status: 201,+ description: 'Poll sent',+ type: MessageResponseDto,+ })+ async sendPoll(@Param('sessionId') sessionId: string, @Body() dto: SendPollDto): Promise<MessageResponseDto> {+ return this.messageService.sendPoll(sessionId, dto);+ }+@Post('reply')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Reply to a message' })diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 377018c06..cd612176f 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -23,6 +23,7 @@ function createMockEngine() {sendStickerMessage: jest.fn().mockResolvedValue(mockEngineResult),sendLocationMessage: jest.fn().mockResolvedValue(mockEngineResult),sendContactMessage: jest.fn().mockResolvedValue(mockEngineResult),+ sendPollMessage: jest.fn().mockResolvedValue(mockEngineResult),replyToMessage: jest.fn().mockResolvedValue(mockEngineResult),forwardMessage: jest.fn().mockResolvedValue(mockEngineResult),reactToMessage: jest.fn().mockResolvedValue(undefined),@@ -632,6 +633,39 @@ describe('MessageService', () => {});});+ // ── sendPoll ──────────────────────────────────────────────────────++ describe('sendPoll', () => {+ it('should send a poll and default to single choice', async () => {+ const result = await service.sendPoll('sess-1', {+ chatId: '[email protected]',+ name: 'Where should we meet?',+ options: ['Park', 'Beach'],+ });++ expect(result.messageId).toBe('wa-msg-1');+ expect(mockEngine.sendPollMessage).toHaveBeenCalledWith('[email protected]', {+ name: 'Where should we meet?',+ options: ['Park', 'Beach'],+ allowMultipleAnswers: false,+ });+ });++ it('should pass allowMultipleAnswers through to the engine', async () => {+ await service.sendPoll('sess-1', {+ chatId: '[email protected]',+ name: 'Pick toppings',+ options: ['Cheese', 'Ham', 'Olives'],+ allowMultipleAnswers: true,+ });++ expect(mockEngine.sendPollMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ allowMultipleAnswers: true }),+ );+ });+ });+// ── reply / forward ───────────────────────────────────────────────describe('reply', () => {diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 0fea5a036..6856c3be9 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -322,6 +322,34 @@ export class MessageService {return this.persistSentState(message, result);}+ async sendPoll(+ sessionId: string,+ dto: { chatId: string; name: string; options: string[]; allowMultipleAnswers?: boolean },+ ): Promise<MessageResponseDto> {+ const engine = this.getEngine(sessionId);++ // Save message as pending BEFORE sending. A poll has no plain-text body, so store the+ // question — that keeps the message history readable.+ const message = await this.saveOutgoingMessage(sessionId, {+ chatId: dto.chatId,+ body: `📊 ${dto.name}`,+ type: 'poll',+ });++ let result: MessageResult;+ try {+ result = await engine.sendPollMessage(dto.chatId, {+ name: dto.name,+ options: dto.options,+ allowMultipleAnswers: dto.allowMultipleAnswers === true,+ });+ } catch (error) {+ await this.saveFailedMessage(message);+ throw this.toClientFacingError(error);+ }+ return this.persistSentState(message, result);+ }+async sendSticker(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {const engine = this.getEngine(sessionId);const media = this.buildMediaInput(dto);