Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(status): post an audio status as a voice note

Yudhi Armyndharisf5d9099fd02f
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 6f913edd4..1ddf020e6 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -291,7 +291,7 @@ export interface ChannelMessage {
export interface StatusUpdate {
id: string;
contact: { id: string; name?: string; pushName?: string };
- type: 'text' | 'image' | 'video';
+ type: 'text' | 'image' | 'video' | 'voice';
caption?: string;
mediaUrl?: string;
backgroundColor?: string;
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index fe9d36769..5f45742be 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -3606,7 +3606,7 @@ Get all contact status updates (stories) visible to the session, read from the s
}
```
-The controller wraps the store array in `{ statuses }`, ordered newest-first. `type` is one of `text | image | video`; `caption`, `backgroundColor`, `font` are optional. `mediaUrl` is present only when the status carried media that the store kept (see the media endpoint below) — it is a same-origin path into this API, not an external WhatsApp CDN link. `timestamp` and `expiresAt` serialize to ISO strings (these are `Date` values, not the epoch-number convention used by message timestamps).
+The controller wraps the store array in `{ statuses }`, ordered newest-first. `type` is one of `text | image | video | voice` (`voice` was added with the send-voice endpoint below; before that anything that was not an image or a video read back as `text`); `caption`, `backgroundColor`, `font` are optional. `mediaUrl` is present only when the status carried media that the store kept (see the media endpoint below) — it is a same-origin path into this API, not an external WhatsApp CDN link. `timestamp` and `expiresAt` serialize to ISO strings (these are `Date` values, not the epoch-number convention used by message timestamps).
**Errors:** `401` missing/invalid API key, or key not scoped to this session
@@ -3798,6 +3798,42 @@ Returns the engine `StatusResult` directly. POST default status is `201`.
**Errors:** `400` validation failure (unknown body field, an empty media wrapper, a JID not matching `@c.us`/`@lid`, more than 256 recipients, or a caption over 1024 chars) · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected
+#### POST /api/sessions/:sessionId/status/send-voice
+
+Post an audio status (story) as a **voice note**, from a URL or base64 payload. The recipients allow-list is honored on Baileys only; whatsapp-web.js broadcasts to the account's status-privacy audience.
+
+> **Format matters.** WhatsApp plays a status voice note only when it is Ogg/Opus, and neither engine transcodes — bytes are sent as supplied. Convert first via `POST /api/sessions/:sessionId/media/convert/voice` (§6.4.15) and post the `base64` it returns. Sending another format produces a bubble that will not play.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | WhatsApp session identifier |
+
+**Request body** — `SendVoiceStatusDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| audio | object (`StatusMediaInput`) | yes | validated nested object; one of `url`/`base64` must be present — an empty `{}` is rejected with `400` | Media source wrapper |
+| audio.url | string | no | must be a non-empty string whenever `base64` is absent **or** `url` is present at all | Media source URL |
+| audio.base64 | string | no | must be a non-empty string whenever `url` is absent **or** `base64` is present at all | Base64-encoded media data |
+| audio.mimetype | string | no | — | Media MIME type; if omitted the service defaults to `audio/ogg; codecs=opus` |
+| recipients | string[] | no | 0–256 items, each matching `^\d+@(c\.us\|lid)$` | JIDs permitted to view the status (`statusJidList`). Required in practice on Baileys; ignored by whatsapp-web.js |
+
+There is **no `caption`**: WhatsApp has nowhere to render one on a status voice note.
+
+```json
+{ "audio": { "base64": "T2dnUwACAAAA..." }, "recipients": ["[email protected]"] }
+```
+
+**Response** `201` — the engine `StatusResult`, identical in shape to the image/video variants.
+
+**Read-back:** a voice status is listed with `"type": "voice"`. That member was added with this endpoint; before it, anything that was not an image or a video was reported as `text`.
+
+**Errors:** `400` validation failure, or neither `url` nor `base64` supplied · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected · `413` base64 media exceeds `MEDIA_DOWNLOAD_MAX_BYTES`
+
#### DELETE /api/sessions/:sessionId/status/:statusId
Delete one of the session's own posted statuses.
diff --git a/openapi.json b/openapi.json
index ac4398916..b9ef67f48 100644
--- a/openapi.json
+++ b/openapi.json
@@ -5398,6 +5398,46 @@
]
}
},
+ "/api/sessions/{sessionId}/status/send-voice": {
+ "post": {
+ "operationId": "StatusController_sendVoiceStatus",
+ "parameters": [
+ {
+ "name": "sessionId",
+ "required": true,
+ "in": "path",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SendVoiceStatusDto"
+ }
+ }
+ }
+ },
+ "responses": {
+ "201": {
+ "description": "Voice status posted. WhatsApp plays a status voice note only as Ogg/Opus and neither engine transcodes, so convert first via POST /media/convert/voice. The recipients allow-list is honored on Baileys only; whatsapp-web.js broadcasts to the account's status-privacy audience."
+ },
+ "400": {
+ "description": "Neither url nor base64 provided, or the post was blocked by a plugin."
+ },
+ "413": {
+ "description": "Base64 media exceeds MEDIA_DOWNLOAD_MAX_BYTES."
+ }
+ },
+ "summary": "Post an audio status as a voice note",
+ "tags": [
+ "status"
+ ]
+ }
+ },
"/api/sessions/{sessionId}/status/{statusId}": {
"delete": {
"operationId": "StatusController_deleteStatus",
@@ -9145,6 +9185,33 @@
"video"
]
},
+ "SendVoiceStatusDto": {
+ "type": "object",
+ "properties": {
+ "audio": {
+ "description": "Audio source (URL or base64). WhatsApp plays a status voice note only as Ogg/Opus, and neither engine transcodes — use the media conversion endpoint to produce it. The mimetype defaults to 'audio/ogg; codecs=opus'.",
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/StatusMediaInput"
+ }
+ ]
+ },
+ "recipients": {
+ "description": "Recipient JIDs (0–256), @c.us or @lid. Required on the Baileys engine (it posts to exactly this allow-list); ignored by whatsapp-web.js, which broadcasts to the account's status-privacy audience — omit it there.",
+ "example": [
+ ],
+ "maxItems": 256,
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "audio"
+ ]
+ },
"ConvertMediaDto": {
"type": "object",
"properties": {
diff --git a/src/engine/adapters/baileys-status.ts b/src/engine/adapters/baileys-status.ts
index ab366cb76..178bd3f86 100644
--- a/src/engine/adapters/baileys-status.ts
+++ b/src/engine/adapters/baileys-status.ts
@@ -38,17 +38,27 @@ export class BaileysStatus {
return this.postMediaStatus('video', media, options);
}
+ postVoiceStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult> {
+ return this.postMediaStatus('voice', media, options);
+ }
+
private async postMediaStatus(
- kind: 'image' | 'video',
+ kind: 'image' | 'video' | 'voice',
media: MediaInput,
options: StatusPostOptions,
): Promise<StatusResult> {
this.host.ensureReady();
const { data, mimetype } = await resolveMediaBuffer(media);
+ // A voice status carries no caption: WhatsApp has nowhere to render one on a status voice note,
+ // and `ptt` is what makes it a voice note rather than an audio file. Baileys reads that same flag
+ // to decide a status may take a background colour, so the colour `postStatus` already forwards
+ // applies here for free.
const content: AnyMessageContent =
kind === 'image'
? { image: data, caption: options.caption, mimetype }
- : { video: data, caption: options.caption, mimetype };
+ : kind === 'video'
+ ? { video: data, caption: options.caption, mimetype }
+ : { audio: data, mimetype, ptt: true };
return this.postStatus(content, options);
}
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 96689ff8b..ad8ff853c 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -4708,3 +4708,65 @@ describe('BaileysAdapter custom link preview', () => {
expect(sentContent().linkPreview).not.toHaveProperty('description');
});
});
+
+/**
+ * A status voice note differs from a status audio file by one flag, and Baileys applies no
+ * validation: `{ audio, ptt }` is copied into the proto as given. So the shape of the content this
+ * builds is the whole behaviour, and it is invisible at runtime — a wrong flag still sends.
+ */
+describe('BaileysAdapter voice status', () => {
+ beforeEach(() => {
+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };
+ fakeSock.resetEmitter();
+ jest.clearAllMocks();
+ fakeSock.sendMessage.mockResolvedValue({ key: { id: 'S1' }, messageTimestamp: 1700000006 });
+ });
+
+ const ready = async (): Promise<BaileysAdapter> => {
+ const adapter = newAdapter();
+ await adapter.initialize({});
+ fakeSock.fire('connection.update', { connection: 'open' });
+ return adapter;
+ };
+
+ it('sends audio with ptt set, to the status broadcast, for exactly the recipients given', async () => {
+ const adapter = await ready();
+
+ await adapter.postVoiceStatus(
+ { mimetype: 'audio/ogg; codecs=opus', data: Buffer.from('audio').toString('base64') },
+ { recipients: ['[email protected]'] },
+ );
+
+ const [chatId, content, options] = fakeSock.sendMessage.mock.calls[0] as [
+ string,
+ { audio?: unknown; ptt?: boolean; caption?: string },
+ { statusJidList?: string[] },
+ ];
+ expect(chatId).toBe('status@broadcast');
+ expect(content.ptt).toBe(true);
+ expect(content.audio).toBeDefined();
+ expect(options.statusJidList).toEqual(['[email protected]']);
+ });
+
+ // WhatsApp has nowhere to render a caption on a status voice note.
+ it('carries no caption', async () => {
+ const adapter = await ready();
+
+ await adapter.postVoiceStatus(
+ { mimetype: 'audio/ogg; codecs=opus', data: Buffer.from('audio').toString('base64'), caption: 'ignored' },
+ { recipients: ['[email protected]'], caption: 'also ignored' },
+ );
+
+ const [, content] = fakeSock.sendMessage.mock.calls[0] as [string, { caption?: string }];
+ expect(content.caption).toBeUndefined();
+ });
+
+ // Baileys posts to exactly statusJidList, so an empty one would publish to nobody.
+ it('still refuses an empty recipients list', async () => {
+ const adapter = await ready();
+
+ await expect(
+ adapter.postVoiceStatus({ mimetype: 'audio/ogg; codecs=opus', data: 'QUJD' }, { recipients: [] }),
+ ).rejects.toThrow(/recipients is required/);
+ });
+});
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index a1d936028..042259a84 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -659,6 +659,10 @@ export class BaileysAdapter implements IWhatsAppEngine {
postVideoStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult> {
return this.statusOps.postVideoStatus(media, options);
}
+
+ postVoiceStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult> {
+ return this.statusOps.postVoiceStatus(media, options);
+ }
async deleteStatus(statusId: string): Promise<void> {
return this.statusOps.deleteStatus(statusId);
}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 19273ed35..67640f834 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -5916,3 +5916,45 @@ describe('WhatsAppWebJsAdapter custom link preview', () => {
expect(sendMessage).not.toHaveBeenCalled();
});
});
+
+/**
+ * `sendAudioAsVoice` is the whole difference between a status voice note and a status audio file:
+ * inside the page it becomes `isPtt`, which selects the mic bubble. Dropping it would still send the
+ * audio and still succeed, so nothing but this assertion would notice.
+ */
+describe('WhatsAppWebJsAdapter voice status', () => {
+ const readyWith = (sendMessage: jest.Mock): 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 = { sendMessage };
+ return adapter;
+ };
+
+ it('posts to status@broadcast as a voice note', async () => {
+ const sendMessage = jest.fn().mockResolvedValue({ id: { _serialized: 'S1' }, timestamp: 1700000000 });
+
+ await readyWith(sendMessage).postVoiceStatus(
+ { mimetype: 'audio/ogg; codecs=opus', data: Buffer.from('audio').toString('base64') },
+ { recipients: [] },
+ );
+
+ expect(sendMessage).toHaveBeenCalledTimes(1);
+ const [chatId, , options] = sendMessage.mock.calls[0] as [string, unknown, { sendAudioAsVoice?: boolean }];
+ expect(chatId).toBe('status@broadcast');
+ expect(options.sendAudioAsVoice).toBe(true);
+ });
+
+ // An image or video status must not acquire the flag: it is audio-only, and the shared media path
+ // is what both go through.
+ it('does not set the voice flag for an image status', async () => {
+ const sendMessage = jest.fn().mockResolvedValue({ id: { _serialized: 'S2' }, timestamp: 1700000000 });
+
+ await readyWith(sendMessage).postImageStatus(
+ { mimetype: 'image/png', data: Buffer.from('img').toString('base64') },
+ { recipients: [] },
+ );
+
+ const [, , options] = sendMessage.mock.calls[0] as [string, unknown, { sendAudioAsVoice?: boolean }];
+ expect(options.sendAudioAsVoice).toBeUndefined();
+ });
+});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 0d2906abf..3be1ce1c6 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -1644,6 +1644,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
return this.statuses.postVideoStatus(media, options);
}
+ postVoiceStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult> {
+ return this.statuses.postVoiceStatus(media, options);
+ }
+
deleteStatus(statusId: string): Promise<void> {
return this.statuses.deleteStatus(statusId);
}
diff --git a/src/engine/adapters/wwebjs-status.ts b/src/engine/adapters/wwebjs-status.ts
index c6dba9d14..0ffadd919 100644
--- a/src/engine/adapters/wwebjs-status.ts
+++ b/src/engine/adapters/wwebjs-status.ts
@@ -113,7 +113,16 @@ export class WwebjsStatus {
// listed status unactionable (#747). The contact id above is a Wid and is unaffected.
id: ((msg.id as unknown as SerializedWid)?._serialized ?? (msg.id as unknown as SerializedWid)?.$1) || '',
contact: contactSummary,
- type: msg.type === MessageTypes.IMAGE ? 'image' : msg.type === MessageTypes.VIDEO ? 'video' : 'text',
+ type:
+ msg.type === MessageTypes.IMAGE
+ ? 'image'
+ : msg.type === MessageTypes.VIDEO
+ ? 'video'
+ : // MessageTypes.VOICE is wwjs' name for 'ptt'. Without this a posted voice status
+ // reads back as a text status, which is what everything non-image/video collapsed to.
+ msg.type === MessageTypes.VOICE
+ ? 'voice'
+ : 'text',
...(msg.body ? { caption: msg.body } : {}),
...(media ? { media } : {}),
timestamp: ts,
@@ -149,12 +158,24 @@ export class WwebjsStatus {
return this.postMediaStatus(media, options);
}
- private async postMediaStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult> {
+ async postVoiceStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult> {
+ // `sendAudioAsVoice` is what makes the bubble a voice note rather than an audio file: it becomes
+ // `isPtt` inside the page. The waveform is separate — whatsapp-web.js already generates one for
+ // any audio going to status, so it appears either way, but only this flag changes the bubble.
+ return this.postMediaStatus(media, options, { sendAudioAsVoice: true });
+ }
+
+ private async postMediaStatus(
+ media: MediaInput,
+ options: StatusPostOptions,
+ extra?: { sendAudioAsVoice: true },
+ ): Promise<StatusResult> {
this.host.ensureReady();
this.warnStatusRecipientsOnce(options);
const messageMedia = await toMessageMedia(media);
const msg = await this.client().sendMessage('status@broadcast', messageMedia, {
...(options.caption !== undefined ? { caption: options.caption } : {}),
+ ...extra,
});
return toStatusResult(msg);
}
diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.ts
index 456c8ae33..509c87b31 100644
--- a/src/engine/engine-capability-matrix.ts
+++ b/src/engine/engine-capability-matrix.ts
@@ -233,6 +233,7 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {
postImageStatus: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
postTextStatus: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
postVideoStatus: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
+ postVoiceStatus: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
promoteParticipants: {
wwjs: { status: 'supported' },
baileys: { status: 'supported' },
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 4c6cf5f17..68b6e7571 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -339,7 +339,12 @@ export interface Status {
name?: string;
pushName?: string;
};
- type: 'text' | 'image' | 'video';
+ /**
+ * `voice` covers an audio status posted as a voice note (PTT). It was added alongside voice status
+ * posting; before that a voice status read back as `text`, since anything that was not an image or
+ * a video collapsed to it.
+ */
+ type: 'text' | 'image' | 'video' | 'voice';
caption?: string;
mediaUrl?: string;
/** Downloaded media bytes for an image/video status, when the engine fetched them (see `capInboundMediaFor`). */
@@ -1007,6 +1012,11 @@ export interface IWhatsAppEngine {
postTextStatus(text: string, options: StatusPostOptions): Promise<StatusResult>;
postImageStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult>;
postVideoStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult>;
+ /**
+ * Post an audio status as a voice note. WhatsApp plays a status voice note only for Ogg/Opus, and
+ * neither engine transcodes — the media conversion endpoints exist to produce it.
+ */
+ postVoiceStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult>;
deleteStatus(statusId: string): Promise<void>;
// Catalog (Phase 3) - WhatsApp Business only
diff --git a/src/modules/status-store/entities/status-update.entity.ts b/src/modules/status-store/entities/status-update.entity.ts
index c1161386e..674b875d2 100644
--- a/src/modules/status-store/entities/status-update.entity.ts
+++ b/src/modules/status-store/entities/status-update.entity.ts
@@ -26,7 +26,7 @@ export class StatusUpdate {
waStatusId!: string;
@Column()
- type!: 'text' | 'image' | 'video';
+ type!: 'text' | 'image' | 'video' | 'voice';
@Column({ type: 'text', nullable: true })
caption?: string;
diff --git a/src/modules/status-store/incoming-status.spec.ts b/src/modules/status-store/incoming-status.spec.ts
index 1320a892d..96e627adb 100644
--- a/src/modules/status-store/incoming-status.spec.ts
+++ b/src/modules/status-store/incoming-status.spec.ts
@@ -59,3 +59,25 @@ it('returns null when there is no resolvable poster (author/from both the broadc
it('returns null when the message has no id', () => {
expect(buildIncomingStatus({ ...base, id: '' })).toBeNull();
});
+
+/**
+ * Both engines map a PTT message to `voice`, and everything that was not an image or a video used to
+ * collapse into `text`. That silently turned an incoming voice status into a text one — a status with
+ * audio attached but a type saying otherwise.
+ */
+it('keeps a voice status as voice rather than collapsing it to text', () => {
+ const s = buildIncomingStatus({
+ ...base,
+ type: 'voice',
+ body: '',
+ media: { mimetype: 'audio/ogg; codecs=opus', data: 'AAAA' },
+ })!;
+
+ expect(s.type).toBe('voice');
+ expect(s.media?.mimetype).toBe('audio/ogg; codecs=opus');
+});
+
+it('still collapses a type the status union does not model', () => {
+ expect(buildIncomingStatus({ ...base, type: 'document' })!.type).toBe('text');
+ expect(buildIncomingStatus({ ...base, type: 'audio' })!.type).toBe('text');
+});
diff --git a/src/modules/status-store/incoming-status.ts b/src/modules/status-store/incoming-status.ts
index c8dcee2a6..ad9aefe3f 100644
--- a/src/modules/status-store/incoming-status.ts
+++ b/src/modules/status-store/incoming-status.ts
@@ -6,7 +6,7 @@ export interface IncomingStatus {
contactJid: string;
contactName?: string;
contactPushName?: string;
- type: 'text' | 'image' | 'video';
+ type: 'text' | 'image' | 'video' | 'voice';
caption?: string;
backgroundColor?: string;
font?: number;
@@ -14,9 +14,14 @@ export interface IncomingStatus {
postedAt: number;
}
-/** Collapse the rich MessageType to the status union (image/video, else text). */
-function statusType(t: string): 'text' | 'image' | 'video' {
- return t === 'image' || t === 'video' ? t : 'text';
+/**
+ * Collapse the rich MessageType to the status union.
+ *
+ * `voice` is listed explicitly because both engines map a PTT message to it, and without that an
+ * incoming voice status would be stored as `text` — the bucket everything non-image/video fell into.
+ */
+function statusType(t: string): 'text' | 'image' | 'video' | 'voice' {
+ return t === 'image' || t === 'video' || t === 'voice' ? t : 'text';
}
/**
diff --git a/src/modules/status/dto/send-media-status.dto.ts b/src/modules/status/dto/send-media-status.dto.ts
index 76513d21b..05c300e84 100644
--- a/src/modules/status/dto/send-media-status.dto.ts
+++ b/src/modules/status/dto/send-media-status.dto.ts
@@ -99,3 +99,37 @@ export class SendVideoStatusDto {
@Matches(/^\d+@(c\.us|lid)$/, { each: true, message: 'Invalid recipient JID' })
recipients?: string[];
}
+
+/**
+ * A voice status carries no caption: WhatsApp has nowhere to render one on a status voice note.
+ */
+export class SendVoiceStatusDto {
+ @ApiProperty({
+ description:
+ 'Audio source (URL or base64). WhatsApp plays a status voice note only as Ogg/Opus, and neither ' +
+ 'engine transcodes — use the media conversion endpoint to produce it. The mimetype defaults to ' +
+ "'audio/ogg; codecs=opus'.",
+ type: StatusMediaInput,
+ })
+ @IsDefined()
+ @ValidateNested()
+ @Type(() => StatusMediaInput)
+ audio!: StatusMediaInput;
+
+ @ApiPropertyOptional({
+ description:
+ 'Recipient JIDs (0–256), @c.us or @lid. Required on the Baileys engine (it posts to exactly this ' +
+ "allow-list); ignored by whatsapp-web.js, which broadcasts to the account's status-privacy " +
+ 'audience — omit it there.',
+ type: String,
+ isArray: true,
+ example: ['[email protected]'],
+ maxItems: 256,
+ })
+ @IsOptional()
+ @IsArray()
+ @ArrayMaxSize(256)
+ @IsString({ each: true })
+ @Matches(/^\d+@(c\.us|lid)$/, { each: true, message: 'Invalid recipient JID' })
+ recipients?: string[];
+}
diff --git a/src/modules/status/status.controller.ts b/src/modules/status/status.controller.ts
index 605c05ff7..4d1b7a1a7 100644
--- a/src/modules/status/status.controller.ts
+++ b/src/modules/status/status.controller.ts
@@ -3,7 +3,7 @@ import type { Response } from 'express';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { StatusService } from './status.service';
import { SendTextStatusDto } from './dto/send-text-status.dto';
-import { SendImageStatusDto, SendVideoStatusDto } from './dto/send-media-status.dto';
+import { SendImageStatusDto, SendVideoStatusDto, SendVoiceStatusDto } from './dto/send-media-status.dto';
import { RequireRole } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
@@ -102,6 +102,25 @@ export class StatusController {
});
}
+ @Post('send-voice')
+ @RequireRole(ApiKeyRole.OPERATOR)
+ @ApiOperation({ summary: 'Post an audio status as a voice note' })
+ @ApiResponse({
+ status: 201,
+ description:
+ 'Voice status posted. WhatsApp plays a status voice note only as Ogg/Opus and neither engine ' +
+ 'transcodes, so convert first via POST /media/convert/voice. The recipients allow-list is honored ' +
+ "on Baileys only; whatsapp-web.js broadcasts to the account's status-privacy audience.",
+ })
+ @ApiResponse({
+ status: 400,
+ description: 'Neither url nor base64 provided, or the post was blocked by a plugin.',
+ })
+ @ApiResponse({ status: 413, description: 'Base64 media exceeds MEDIA_DOWNLOAD_MAX_BYTES.' })
+ async sendVoiceStatus(@Param('sessionId') sessionId: string, @Body() dto: SendVoiceStatusDto) {
+ return this.statusService.postVoiceStatus(sessionId, dto.audio, { recipients: dto.recipients });
+ }
+
@Delete(':statusId')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Delete own status' })
diff --git a/src/modules/status/status.service.spec.ts b/src/modules/status/status.service.spec.ts
index 3cf999197..d55646e6f 100644
--- a/src/modules/status/status.service.spec.ts
+++ b/src/modules/status/status.service.spec.ts
@@ -1,5 +1,6 @@
import { BadRequestException, NotFoundException, PayloadTooLargeException } from '@nestjs/common';
import { StatusService } from './status.service';
+import { StatusController } from './status.controller';
import { EngineRegistry } from '../../engine/engine-registry.service';
import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
import { StatusStoreService } from '../status-store/status-store.service';
@@ -7,7 +8,7 @@ import { StorageService } from '../../common/storage/storage.service';
import { HookManager } from '../../core/hooks';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
-import { SendImageStatusDto, SendVideoStatusDto } from './dto/send-media-status.dto';
+import { SendImageStatusDto, SendVideoStatusDto, SendVoiceStatusDto } from './dto/send-media-status.dto';
import { SendPacingService } from '../message/send-pacing.service';
describe('StatusService media validation and selection', () => {
@@ -15,6 +16,7 @@ describe('StatusService media validation and selection', () => {
postTextStatus: jest.fn().mockResolvedValue({ id: 'text-status' }),
postImageStatus: jest.fn().mockResolvedValue({ id: 'image-status' }),
postVideoStatus: jest.fn().mockResolvedValue({ id: 'video-status' }),
+ postVoiceStatus: jest.fn().mockResolvedValue({ id: 'voice-status' }),
};
const engines = new EngineRegistry();
// Both ids the tests below post from; the store-only paths ('sess') never reach the engine.
@@ -119,6 +121,73 @@ describe('StatusService media validation and selection', () => {
expect(engine.postVideoStatus).toHaveBeenCalledWith(expect.objectContaining({ data: 'QUJD' }), expect.anything());
});
+ describe('voice status', () => {
+ // Ogg/Opus is the only thing WhatsApp plays as a status voice note, and neither engine
+ // transcodes — so the default has to be that, not a generic audio type.
+ it('defaults the mimetype to Ogg/Opus when the caller omits it', async () => {
+ await service.postVoiceStatus('s1', { base64: 'QUJD' }, { recipients: ['[email protected]'] });
+
+ expect(engine.postVoiceStatus).toHaveBeenCalledWith(
+ expect.objectContaining({ mimetype: 'audio/ogg; codecs=opus', data: 'QUJD' }),
+ expect.anything(),
+ );
+ });
+
+ it('takes a caller-supplied mimetype at its word', async () => {
+ await service.postVoiceStatus('s1', { base64: 'QUJD', mimetype: 'audio/mpeg' }, { recipients: ['[email protected]'] });
+
+ expect(engine.postVoiceStatus).toHaveBeenCalledWith(
+ expect.objectContaining({ mimetype: 'audio/mpeg' }),
+ expect.anything(),
+ );
+ });
+
+ it('rejects a body carrying neither url nor base64', async () => {
+ await expect(service.postVoiceStatus('s1', {}, { recipients: ['[email protected]'] })).rejects.toBeInstanceOf(
+ BadRequestException,
+ );
+ });
+
+ /**
+ * `guardGatedMedia` re-checks the cap after the plugin gate, so an oversized payload is refused
+ * either way. What the early check buys is that it is refused BEFORE plugins run — so the
+ * assertion is that no plugin was handed 50 MiB of audio, not merely that a 413 came back.
+ */
+ it('refuses oversized base64 before the plugin gate sees it', async () => {
+ const oversized = Buffer.alloc(51 * 1024 * 1024).toString('base64');
+ hookManager.execute.mockClear();
+
+ await expect(
+ service.postVoiceStatus('s1', { base64: oversized }, { recipients: ['[email protected]'] }),
+ ).rejects.toBeInstanceOf(PayloadTooLargeException);
+
+ expect(hookManager.execute).not.toHaveBeenCalled();
+ });
+
+ /**
+ * WhatsApp has nowhere to render a caption on a status voice note, so the request body carries
+ * none — and the controller must not invent one. This matters on whatsapp-web.js specifically:
+ * its status path forwards `caption` whenever it is defined, so a caption arriving here would be
+ * sent rather than ignored.
+ */
+ it('forwards no caption, even when the body carries an unmodelled one', async () => {
+ const controller = new StatusController(service);
+
+ await controller.sendVoiceStatus(
+ 's1',
+ plainToInstance(SendVoiceStatusDto, {
+ audio: { base64: 'QUJD' },
+ recipients: ['[email protected]'],
+ caption: 'not part of the contract',
+ } as object),
+ );
+
+ const [, options] = engine.postVoiceStatus.mock.calls.at(-1) as [unknown, { caption?: string }];
+ expect(options.caption).toBeUndefined();
+ expect(options).toMatchObject({ recipients: ['[email protected]'] });
+ });
+ });
+
it('strips a data-URI prefix before handing base64 bytes to either engine path', async () => {
const prefixed = 'data:image/png;base64,QUJD';
await service.postImageStatus('s1', { base64: prefixed, mimetype: 'image/png' }, { recipients: ['[email protected]'] });
diff --git a/src/modules/status/status.service.ts b/src/modules/status/status.service.ts
index 005470ef1..b272253a3 100644
--- a/src/modules/status/status.service.ts
+++ b/src/modules/status/status.service.ts
@@ -142,6 +142,39 @@ export class StatusService {
return engine.postVideoStatus(this.guardGatedMedia(gated.media), gated.options);
}
+ /**
+ * Post an audio status as a voice note.
+ *
+ * The mimetype defaults to Ogg/Opus because that is the only thing WhatsApp plays as a status
+ * voice note, and neither engine transcodes — the media conversion endpoints produce it. A caller
+ * that supplies another type is taken at its word; the result is an unplayable bubble, exactly as
+ * it is for a voice message.
+ *
+ * There is no caption: WhatsApp has nowhere to render one on a status voice note.
+ */
+ async postVoiceStatus(
+ sessionId: string,
+ media: { url?: string; base64?: string; mimetype?: string } | undefined,
+ options: StatusPostOptions,
+ ): Promise<StatusResult> {
+ const base64 = stripBase64DataUri(media?.base64);
+ const url = media?.url;
+ const mimetype = media?.mimetype;
+ if (!url && !base64) {
+ throw new BadRequestException('Either url or base64 must be provided');
+ }
+ assertBase64WithinMediaCap(base64);
+ const engine = this.engines.require(
+ sessionId,
+ () => new NotFoundException(`Session ${sessionId} not found or not connected`),
+ );
+ const gated = await this.gate(sessionId, 'status-voice', {
+ media: { mimetype: mimetype ?? 'audio/ogg; codecs=opus', data: base64 || url || '' },
+ options,
+ });
+ return engine.postVoiceStatus(this.guardGatedMedia(gated.media), gated.options);
+ }
+
async deleteStatus(sessionId: string, statusId: string): Promise<void> {
const engine = this.engines.require(
sessionId,