Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(message): outbound @mentions on text and media sends (#530) (#539)
Yudhi Armyndharis2176ae92326d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3cfb1553d..d321c9a9f 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++- **Outbound @mentions on text and media sends.** `send-text` and the media send routes now accept an optional `mentions` array of WIDs (`<phone>@c.us`) to tag participants — most useful in groups. The contract is engine-neutral: pass neutral `@c.us` WIDs and the active engine (whatsapp-web.js or Baileys) de-normalizes them. For a tag to render and notify, the `text`/`caption` must also contain the matching `@<number>` token. This brings outbound parity with the `mentions` field already surfaced on inbound webhooks. (#530) Thanks @adampalli.+## [0.7.13] - 2026-06-29### Fixeddiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex b1f711ea0..2207e024e 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -125,6 +125,7 @@ All media send routes (`send-image`, `send-video`, `send-audio`, `send-document`| `mimetype` | string | conditional | required when `base64` is used | MIME type, e.g. `image/jpeg`, `video/mp4`, `application/pdf` || `filename` | string | no | max 255 chars | Optional file name (also used as the persisted body fallback for documents) || `caption` | string | no | max 1024 chars | Optional caption (not persisted for audio) |+| `mentions` | string[] | no | array of WIDs | WIDs to @mention in the caption (e.g. `["[email protected]"]`). See **Mentions** below |Provide **exactly one** of `url` or `base64`. Omitting both, or supplying `base64` without `mimetype`, returns `400`.@@ -153,6 +154,15 @@ There is a **single shared media byte cap**, not a per-type table. A base64 (or`send-text` enforces a maximum body length of **4096 characters** (`text` is `@MaxLength(4096)`). Media captions are limited to **1024 characters**.+### Mentions++`send-text` and the media send routes accept an optional `mentions` array of WIDs (`<phone>@c.us`) to tag participants — most useful in groups. Two things are required for WhatsApp to render a tag and notify the participant:++1. The `mentions` array lists the WID(s), e.g. `["[email protected]"]`.+2. The `text`/`caption` contains the matching `@<number>` token, e.g. `Hello @62811`.++The contract is engine-neutral: pass neutral `@c.us` WIDs and the active engine (whatsapp-web.js or Baileys) de-normalizes them internally. Whether a mention surfaces a notification is ultimately client-side — outside a shared group some clients may not render it.+## 6.4 REST API ReferenceEvery path below is prefixed with `/api`. Unless marked **public**, send `X-API-Key: <key>`; `OPERATOR`/`ADMIN` annotations require a key of at least that role. Responses are the raw payload (no envelope); list endpoints return a bare array.@@ -864,11 +874,16 @@ Send a plain text message.| --- | --- | --- | --- | --- || chatId | string | Yes | non-empty | `[email protected]` or `[email protected]` || text | string | Yes | non-empty, max 4096 | Message text |+| mentions | string[] | No | array of WIDs | WIDs to @mention (e.g. `["[email protected]"]`). See **Mentions** below |```json{ "chatId": "[email protected]", "text": "Hello from OpenWA!" }```+```json+{ "chatId": "[email protected]", "text": "Hello @62811", "mentions": ["[email protected]"] }+```+**Response** `201````jsondiff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex d30da83e4..37947eecc 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -573,6 +573,23 @@ describe('BaileysAdapter messaging', () => {);});+ it('sendTextMessage de-normalizes mentions to engine jids (#530)', async () => {+ fakeSock.sendMessage.mockResolvedValue({ key: { id: 'OUT1' }, messageTimestamp: 1700000001 });+ const adapter = await readyAdapter();+ await adapter.sendTextMessage('[email protected]', 'hi @62811', ['[email protected]']);+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {+ text: 'hi @62811',+ mentions: ['[email protected]'],+ });+ });++ it('sendTextMessage omits the mentions key when none are given (no behavior change)', async () => {+ fakeSock.sendMessage.mockResolvedValue({ key: { id: 'OUT1' }, messageTimestamp: 1700000001 });+ const adapter = await readyAdapter();+ await adapter.sendTextMessage('[email protected]', 'plain', []);+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', { text: 'plain' });+ });+it('getNumberId resolves via onWhatsApp and returns a NEUTRAL jid (never @s.whatsapp.net)', async () => {fakeSock.onWhatsApp.mockResolvedValue([{ jid: '[email protected]', exists: true }]);const adapter = await readyAdapter();@@ -1239,6 +1256,20 @@ describe('BaileysAdapter media sends', () => {expect(res).toEqual({ id: 'M1', timestamp: 1700000005 });});+ it('sendImageMessage de-normalizes media.mentions into the content (#530)', async () => {+ const adapter = await ready();+ await adapter.sendImageMessage('[email protected]', {+ mimetype: 'image/png',+ data: Buffer.from([1]),+ caption: 'look @62811',+ mentions: ['[email protected]'],+ });+ expect(fakeSock.sendMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ mentions: ['[email protected]'] }),+ );+ });+it('resolves a base64 data string to a Buffer (no URL fetch)', async () => {const adapter = await ready();await adapter.sendDocumentMessage('[email protected]', {diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 00eaf3682..fbdea61ba 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -468,12 +468,13 @@ export class BaileysAdapter implements IWhatsAppEngine {// ----- Messaging ------ async sendTextMessage(chatId: string, text: string): Promise<MessageResult> {+ async sendTextMessage(chatId: string, text: string, mentions?: string[]): Promise<MessageResult> {this.ensureReady();const options = this.withEphemeral(chatId);+ const content = { text, ...this.withMentions(mentions) };const sent = options- ? await this.sock!.sendMessage(chatId, { text }, options)- : await this.sock!.sendMessage(chatId, { text });+ ? await this.sock!.sendMessage(chatId, content, options)+ : await this.sock!.sendMessage(chatId, content);if (sent) {void this.config.messageStore?.put(this.config.sessionId, sent).catch(err =>this.logger.warn('Failed to persist sent message to store', {@@ -510,13 +511,23 @@ export class BaileysAdapter implements IWhatsAppEngine {async sendImageMessage(chatId: string, media: MediaInput): Promise<MessageResult> {this.ensureReady();const { data, mimetype } = await this.resolveMediaBuffer(media);- return this.sendContent(chatId, { image: data, caption: media.caption, mimetype });+ return this.sendContent(chatId, {+ image: data,+ caption: media.caption,+ mimetype,+ ...this.withMentions(media.mentions),+ });}async sendVideoMessage(chatId: string, media: MediaInput): Promise<MessageResult> {this.ensureReady();const { data, mimetype } = await this.resolveMediaBuffer(media);- return this.sendContent(chatId, { video: data, caption: media.caption, mimetype });+ return this.sendContent(chatId, {+ video: data,+ caption: media.caption,+ mimetype,+ ...this.withMentions(media.mentions),+ });}async sendAudioMessage(chatId: string, media: MediaInput): Promise<MessageResult> {@@ -533,6 +544,7 @@ export class BaileysAdapter implements IWhatsAppEngine {mimetype,fileName: media.filename ?? 'file',caption: media.caption,+ ...this.withMentions(media.mentions),});}@@ -648,6 +660,16 @@ export class BaileysAdapter implements IWhatsAppEngine {return participants.map(p => this.sessionStore.toEngineJid(p));}+ /**+ * Build the `{ mentions }` slice of a Baileys message content, de-normalizing neutral `@c.us` WIDs to+ * the engine dialect. Returns an empty object when none are given so the content is byte-identical to+ * the pre-#530 send (no stray `mentions` key). The text must still contain the `@<number>` token for+ * WhatsApp to render the tag — that is the caller's responsibility.+ */+ private withMentions(mentions?: string[]): { mentions?: string[] } {+ return mentions?.length ? { mentions: this.toEngineParticipants(mentions) } : {};+ }+async leaveGroup(groupId: string): Promise<void> {this.ensureReady();await this.sock!.groupLeave(groupId);diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex b71f8cd04..5d0485036 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -873,3 +873,40 @@ describe('WhatsAppWebJsAdapter inbound media (MEDIA_DOWNLOAD_ENABLED=false)', ()expect(msg.media?.sizeBytes).toBe(5000);});});++describe('outbound mentions (#530)', () => {+ 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 sentMessage = { id: { _serialized: 'OUT1' }, timestamp: 1700000001 };++ it('sendTextMessage forwards mentions as a wwebjs option (WIDs pass through)', async () => {+ const sendMessage = jest.fn().mockResolvedValue(sentMessage);+ await ready({ sendMessage }).sendTextMessage('[email protected]', 'hi @62811', ['[email protected]']);+ expect(sendMessage).toHaveBeenCalledWith('[email protected]', 'hi @62811', { mentions: ['[email protected]'] });+ });++ it('sendTextMessage sends no options object when there are no mentions (no behavior change)', async () => {+ const sendMessage = jest.fn().mockResolvedValue(sentMessage);+ await ready({ sendMessage }).sendTextMessage('[email protected]', 'plain');+ expect(sendMessage).toHaveBeenCalledWith('[email protected]', 'plain');+ });++ it('sendImageMessage forwards media.mentions alongside the caption', async () => {+ const sendMessage = jest.fn().mockResolvedValue(sentMessage);+ await ready({ sendMessage }).sendImageMessage('[email protected]', {+ mimetype: 'image/png',+ data: Buffer.from([1]).toString('base64'),+ caption: 'look @62811',+ mentions: ['[email protected]'],+ });+ expect(sendMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.anything(),+ expect.objectContaining({ caption: 'look @62811', mentions: ['[email protected]'] }),+ );+ });+});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 25ac16a55..1af0fe0a3 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -752,9 +752,13 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginreturn this.pushName;}- async sendTextMessage(chatId: string, text: string): Promise<MessageResult> {+ async sendTextMessage(chatId: string, text: string, mentions?: string[]): Promise<MessageResult> {this.ensureReady();- const msg = await this.client!.sendMessage(chatId, text);+ // wwebjs accepts neutral `<phone>@c.us` WIDs directly as mentionedJidList, so no de-normalization+ // is needed. Omit the options object entirely when none are given to keep today's send behavior.+ const msg = mentions?.length+ ? await this.client!.sendMessage(chatId, text, { mentions })+ : await this.client!.sendMessage(chatId, text);return {id: msg.id._serialized,timestamp: msg.timestamp,@@ -797,6 +801,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginconst msg = await this.client!.sendMessage(chatId, messageMedia, {caption: media.caption,+ ...(media.mentions?.length ? { mentions: media.mentions } : {}),});return {diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 4f7d31b83..299484225 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -33,6 +33,8 @@ export interface MediaInput {data: Buffer | string; // Buffer or base64 or URLfilename?: string;caption?: string;+ /** Neutral WIDs (`<phone>@c.us`) to @mention in the caption. The adapter de-normalizes per engine. */+ mentions?: string[];}/**@@ -407,7 +409,7 @@ export interface IWhatsAppEngine {getPushName(): string | null;// Messaging - Basic- sendTextMessage(chatId: string, text: string): Promise<MessageResult>;+ sendTextMessage(chatId: string, text: string, mentions?: string[]): Promise<MessageResult>;sendImageMessage(chatId: string, media: MediaInput): Promise<MessageResult>;sendVideoMessage(chatId: string, media: MediaInput): Promise<MessageResult>;sendAudioMessage(chatId: string, media: MediaInput): Promise<MessageResult>;diff --git a/src/modules/message/dto/send-message.dto.spec.ts b/src/modules/message/dto/send-message.dto.spec.tsnew file mode 100644index 000000000..a0122c4ab--- /dev/null+++ b/src/modules/message/dto/send-message.dto.spec.ts@@ -0,0 +1,44 @@+import { plainToInstance } from 'class-transformer';+import { validate } from 'class-validator';+import { SendTextMessageDto, SendMediaMessageDto } from './send-message.dto';++// Mirror the global ValidationPipe (main.ts): whitelist + forbidNonWhitelisted strip/reject unknown props.+const validateDto = (cls: new () => object, obj: unknown) =>+ validate(plainToInstance(cls, obj), { whitelist: true, forbidNonWhitelisted: true });++describe('SendTextMessageDto mentions', () => {+ it('accepts an optional array of mention WIDs', async () => {+ const errors = await validateDto(SendTextMessageDto, {+ chatId: '[email protected]',+ text: 'hi @62811',+ mentions: ['[email protected]'],+ });+ expect(errors).toHaveLength(0);+ });++ it('is omittable (mentions stays optional)', async () => {+ const errors = await validateDto(SendTextMessageDto, { chatId: '[email protected]', text: 'hi' });+ expect(errors).toHaveLength(0);+ });++ it('rejects a non-string element in mentions', async () => {+ const errors = await validateDto(SendTextMessageDto, {+ chatId: '[email protected]',+ text: 'hi',+ mentions: [123],+ });+ expect(errors.length).toBeGreaterThan(0);+ });+});++describe('SendMediaMessageDto mentions', () => {+ it('accepts an optional array of mention WIDs', async () => {+ const errors = await validateDto(SendMediaMessageDto, {+ chatId: '[email protected]',+ url: 'https://example.com/a.jpg',+ caption: 'look @62811',+ mentions: ['[email protected]'],+ });+ expect(errors).toHaveLength(0);+ });+});diff --git a/src/modules/message/dto/send-message.dto.ts b/src/modules/message/dto/send-message.dto.tsindex 387435fad..e4f897c36 100644--- a/src/modules/message/dto/send-message.dto.ts+++ b/src/modules/message/dto/send-message.dto.ts@@ -1,5 +1,8 @@import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';-import { IsString, IsNotEmpty, IsOptional, MaxLength, IsUrl, ValidateIf } from 'class-validator';+import { IsString, IsNotEmpty, IsOptional, MaxLength, IsUrl, ValidateIf, IsArray } from 'class-validator';++const MENTIONS_DESCRIPTION =+ 'WIDs to @mention (e.g. ["[email protected]"]). The text/caption must also contain the @<number> token.';export class SendTextMessageDto {@ApiProperty({@@ -19,6 +22,12 @@ export class SendTextMessageDto {@IsNotEmpty()@MaxLength(4096)text: string;++ @ApiPropertyOptional({ description: MENTIONS_DESCRIPTION, example: ['[email protected]'], type: [String] })+ @IsOptional()+ @IsArray()+ @IsString({ each: true })+ mentions?: string[];}export class SendMediaMessageDto {@@ -73,6 +82,12 @@ export class SendMediaMessageDto {@IsString()@MaxLength(1024)caption?: string;++ @ApiPropertyOptional({ description: MENTIONS_DESCRIPTION, example: ['[email protected]'], type: [String] })+ @IsOptional()+ @IsArray()+ @IsString({ each: true })+ mentions?: string[];}export class MessageResponseDto {diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 8935664d2..f8eb7ab03 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -127,6 +127,16 @@ describe('MessageService', () => {expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hello');});+ it('threads mentions through to the engine (#530)', async () => {+ const input = { chatId: '[email protected]', text: 'hi @62811', mentions: ['[email protected]'] };+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({+ continue: true,+ data: { sessionId: 'sess-1', input, type: 'text' },+ });+ await service.sendText('sess-1', input);+ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'hi @62811', ['[email protected]']);+ });+it('should save outgoing message as pending before sending, then update to sent', async () => {await service.sendText('sess-1', {chatId: '[email protected]',@@ -295,6 +305,20 @@ describe('MessageService', () => {);});+ it('threads media mentions into the MediaInput (#530)', async () => {+ await service.sendImage('sess-1', {+ chatId: '[email protected]',+ base64: 'AAAA',+ mimetype: 'image/png',+ caption: 'look @62811',+ mentions: ['[email protected]'],+ });+ expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ mentions: ['[email protected]'] }),+ );+ });+it('maps a blocked-media-URL SSRF error to HTTP 400', async () => {mockEngine.sendImageMessage.mockRejectedValueOnce(new SsrfBlockedError('Blocked internal address: 127.0.0.1'));diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex a0f13ea9e..0400407e8 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -64,7 +64,10 @@ export class MessageService {await this.simulateTypingIfEnabled(engine, finalDto.chatId, finalDto.text);try {- const result = await engine.sendTextMessage(finalDto.chatId, finalDto.text);+ // Keep the 2-arg call shape for plain sends; only pass mentions when the caller supplied any.+ const result = finalDto.mentions?.length+ ? await engine.sendTextMessage(finalDto.chatId, finalDto.text, finalDto.mentions)+ : await engine.sendTextMessage(finalDto.chatId, finalDto.text);// Update with actual WhatsApp message ID and statusmessage.waMessageId = result.id;@@ -662,6 +665,7 @@ export class MessageService {data: dto.url || dto.base64!,filename: dto.filename,caption: dto.caption,+ mentions: dto.mentions,};}}