Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

add support buttons

Gabriel Moraese5f324e75887
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 96cb11bab..88f79273c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- Baileys inbound button, template quick-reply, list-row and native-flow replies arrive as `type: "text"` with a structured `button { id, text? }` on `message.received` / chat history (whatsapp-web.js still has no interactive reply fields).
+- Baileys inbound business prompts that offer buttons (or list rows) also carry `buttons: [{ id, text }, …]` on `message.received`, so choices like Sim/Não are no longer flattened away into `body` only.
+- `POST /api/sessions/:sessionId/messages/click-button` sends a structured button/list reply against a stored WhatsApp Business prompt on Baileys (whatsapp-web.js returns `501`).
+
### Changed
- The PostgreSQL data connection is pinned to UTC: parameters bind as UTC, naive timestamps read back as UTC, every pooled connection sets its session `TimeZone`, and boot fails when the effective zone is not UTC year round.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 144711064..765b4b3fb 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1320,7 +1320,7 @@ Returns a bare array of engine-neutral `IncomingMessage` objects:
]
```
-Each item may also include `isStatusBroadcast`, `mentionedIds`, `isLidSender`, `ephemeralDuration` (the chat's disappearing-messages timer in seconds, present only when one is set), `contact`, `media { mimetype, filename?, data?, omitted?, sizeBytes? }`, `quotedMessage { id, body }`, `call { video, missed }` (for `call` messages), `location { latitude, longitude, description?, address?, url? }`, `order { orderId, token? }` (for `order` messages) and `product { productId, title?, description?, businessOwnerJid? }` (for `product` messages). `senderPhone` is **not** among them: this endpoint reads live from the engine and performs no privacy-id resolution, which runs only on the inbound `message.received` path (§6.6). To map an `@lid` sender seen here, call `GET /api/sessions/:sessionId/contacts/:contactId/phone`. `type` is one of `text|image|video|audio|voice|document|sticker|location|contact|poll|call|revoked|order|product|masked|unknown`. An `order` is a cart the customer placed from the business catalog and a `product` is a single catalog product shared into the chat. Only whatsapp-web.js serves this route (Baileys answers `501`), so every `order` and `product` block here comes from that engine. The message carries no line items and this API exposes no order lookup, so `orderId` plus the single-order `token` are a correlation handle you redeem elsewhere. The catalog routes answer `501` on whatsapp-web.js, so a `productId` read here does not resolve through them. whatsapp-web.js exposes no catalog field and cannot tell a share of a whole catalog from a product: a `product` message without a product id arrives with no `product` block. On Baileys the blocks arrive on `message.received`, where `GET /api/sessions/:sessionId/catalog/products/:productId` resolves a `productId` only when the product came from the session's own catalog (`businessOwnerJid` says whose it is), and a share of a whole catalog is typed `unknown`, both live and in the rows history sync stores. A `masked` message is one WhatsApp deliberately withholds from linked/companion devices — e.g. a high-security business OTP — so its `body` is empty by design (the content is only available on the primary phone) rather than a parsing failure; this occurs on the Baileys engine. `kind` is the user-facing chat discriminator of `chatId` — one of `individual|group|channel|status|broadcast|unknown`; it supersedes `isStatusBroadcast` (equivalent to `kind === 'status'`), which is retained for back-compat.
+Each item may also include `isStatusBroadcast`, `mentionedIds`, `isLidSender`, `ephemeralDuration` (the chat's disappearing-messages timer in seconds, present only when one is set), `contact`, `media { mimetype, filename?, data?, omitted?, sizeBytes? }`, `quotedMessage { id, body }`, `call { video, missed }` (for `call` messages), `location { latitude, longitude, description?, address?, url? }`, `order { orderId, token? }` (for `order` messages) and `product { productId, title?, description?, businessOwnerJid? }` (for `product` messages). `senderPhone` is **not** among them: this endpoint reads live from the engine and performs no privacy-id resolution, which runs only on the inbound `message.received` path (§6.6). To map an `@lid` sender seen here, call `GET /api/sessions/:sessionId/contacts/:contactId/phone`. `type` is one of `text|image|video|audio|voice|document|sticker|location|contact|poll|call|revoked|order|product|masked|unknown`. An `order` is a cart the customer placed from the business catalog and a `product` is a single catalog product shared into the chat. Only whatsapp-web.js serves this route (Baileys answers `501`), so every `order` and `product` block here comes from that engine. The message carries no line items and this API exposes no order lookup, so `orderId` plus the single-order `token` are a correlation handle you redeem elsewhere. The catalog routes answer `501` on whatsapp-web.js, so a `productId` read here does not resolve through them. whatsapp-web.js exposes no catalog field and cannot tell a share of a whole catalog from a product: a `product` message without a product id arrives with no `product` block. On Baileys the blocks arrive on `message.received`, where `GET /api/sessions/:sessionId/catalog/products/:productId` resolves a `productId` only when the product came from the session's own catalog (`businessOwnerJid` says whose it is), and a share of a whole catalog is typed `unknown`, both live and in the rows history sync stores. A Baileys `message.received` may also carry `button { id, text? }` when the sender tapped a WhatsApp Business button, template quick-reply, list row, or native-flow control (this live-history route never sees it — Baileys answers `501` here). A `masked` message is one WhatsApp deliberately withholds from linked/companion devices — e.g. a high-security business OTP — so its `body` is empty by design (the content is only available on the primary phone) rather than a parsing failure; this occurs on the Baileys engine. `kind` is the user-facing chat discriminator of `chatId` — one of `individual|group|channel|status|broadcast|unknown`; it supersedes `isStatusBroadcast` (equivalent to `kind === 'status'`), which is retained for back-compat.
**Errors:** `400` session not active · `401` missing/invalid API key · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine · `503` the whatsapp-web.js page died mid-read (retryable)
@@ -2028,6 +2028,47 @@ The quoted body is best-effort resolved from the DB for the reply preview.
**Errors:** `400` validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error · `409` conflict or engine not ready (retryable)
+#### POST /api/sessions/:sessionId/messages/click-button
+
+Tap a choice on a WhatsApp Business button / list prompt by sending the structured reply proto WhatsApp expects.
+
+**Auth:** API key (OPERATOR) · **Engines:** Baileys only — whatsapp-web.js returns `501`
+
+**Path parameters**
+
+| Name | Type | Description |
+| --------- | ------ | ----------- |
+| sessionId | string | Session ID |
+
+**Request body** — `ClickButtonDto`
+
+| Field | Type | Required | Constraints | Description |
+| -------- | ------ | -------- | ----------- | --------------------------------------------------------------------------- |
+| chatId | string | Yes | non-empty | Chat that holds the prompt |
+| messageId| string | Yes | non-empty | WhatsApp id of the inbound prompt (`buttons` on `message.received`) |
+| buttonId | string | Yes | non-empty | Stable id of the choice (`buttons[].id`) |
+| text | string | No | non-empty | Visible label; resolved from the stored prompt when omitted, else `buttonId` |
+
+```json
+{ "chatId": "[email protected]", "messageId": "0587502EE4F5C80E5C", "buttonId": "yes", "text": "Sim" }
+```
+
+**Response** `201`
+
+```json
+{ "messageId": "3EB0CLICK1", "timestamp": 1719312100 }
+```
+
+> **Baileys only.** whatsapp-web.js has no interactive-reply send path and answers `501`.
+
+> **Not a native UI tap.** The gateway relays a `buttonsResponseMessage` /
+> `templateButtonReplyMessage` / `listResponseMessage` quoted to the stored prompt. WhatsApp may
+> reject or treat it differently from a phone tap. The prompt must already be in the Baileys message
+> store (received while the session was live). URL/call CTA buttons cannot be clicked this way —
+> only quick-reply style choices and list rows.
+
+**Errors:** `400` validation failure, session not active, the message is not a clickable prompt, or `buttonId` is not among its choices · `401` · `403` · `404` prompt not in the engine store / wrong chat · `501` whatsapp-web.js · `409` conflict or engine not ready (retryable) · `500` engine error
+
#### POST /api/sessions/:sessionId/messages/forward
Forward a message from one chat to another.
@@ -6852,7 +6893,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve
| Event | When it fires | `data` payload sketch |
| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `message.received` | An inbound message arrives | The full message object: `id`, `from`, `to`, `body`, `type`, `timestamp` (epoch **seconds**), `isGroup`, `kind` (user-facing chat discriminator of `chatId` — `individual\|group\|channel\|status\|broadcast\|unknown`), `hasMedia`, `contact{…}` (plus optional `senderPhone` for `@lid` senders, and `order{orderId,token?}` / `product{productId,…}` on `order` / `product` messages) |
+| `message.received` | An inbound message arrives | The full message object: `id`, `from`, `to`, `body`, `type`, `timestamp` (epoch **seconds**), `isGroup`, `kind` (user-facing chat discriminator of `chatId` — `individual\|group\|channel\|status\|broadcast\|unknown`), `hasMedia`, `contact{…}` (plus optional `senderPhone` for `@lid` senders, `order{orderId,token?}` / `product{productId,…}` on `order` / `product` messages, `buttons:[{id,text}]` on a WhatsApp Business prompt that offers choices, and `button{id,text?}` when the sender tapped one — **Baileys only**) |
| `message.sent` | An outbound message is created/sent from this session | Same message object shape as `message.received` |
| `message.ack` | A delivery/read receipt updates an outbound message | `{ id, messageId, status, ack }` — `status` is the canonical state (`pending`/`sent`/`delivered`/`read`/`failed`); `ack` is the deprecated legacy integer derived from it |
| `message.failed` | A receipt resolves to `failed` (dispatched in addition to `message.ack`) | `{ id, messageId, status: "failed", ack: -1 }` |
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index 5aa06c8d0..8b945e045 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -3,7 +3,7 @@
Three-way comparison of every capability: the **Baileys library** (`@whiskeysockets/baileys`
7.0.0-rc14), the **whatsapp-web.js library** (1.34.7), and what **OpenWA actually exposes** through
its adapter layer and REST API — including which "supported" cells only work because OpenWA patches
-the installed library. Coverage is total: all 112 `IWhatsAppEngine` methods (29.4), **all 152
+the installed library. Coverage is total: all 113 `IWhatsAppEngine` methods (29.4), **all 152
Baileys + 81 whatsapp-web.js library methods** (29.5), all 34 + 31 library events (29.5.4), and all
9 install-time patches (29.3). If it exists upstream or in OpenWA, it has a row here.
@@ -25,7 +25,7 @@ Statuses used in the tables:
Two complementary views:
-- **29.4 — the OpenWA contract view.** Rows are the 112 `IWhatsAppEngine` methods; use it to see
+- **29.4 — the OpenWA contract view.** Rows are the 113 `IWhatsAppEngine` methods; use it to see
what a REST caller gets per engine. Source of truth: `src/engine/engine-capability-matrix.ts`
(per-cell `evidence` strings cite the exact library `file:symbol` inspected).
- **29.5 — the full engine inventory.** Rows are **every method the installed libraries expose**,
@@ -37,14 +37,14 @@ Two complementary views:
## 29.2 Adapter architecture
OpenWA never calls a WhatsApp library directly from a controller. Every session owns one engine
-instance behind the neutral `IWhatsAppEngine` interface (112 methods +
+instance behind the neutral `IWhatsAppEngine` interface (113 methods +
`EngineEventCallbacks`), and all modules go through it:
```mermaid
flowchart LR
subgraph OpenWA["OpenWA"]
API["REST API controllers"] --> SVC["Modules / services"]
- SVC --> IF["IWhatsAppEngine - 112 methods"]
+ SVC --> IF["IWhatsAppEngine - 113 methods"]
IF --> WA["WhatsAppWebJsAdapter"]
IF --> BA["BaileysAdapter"]
SVC --> STORE["OpenWA-side stores"]
@@ -203,7 +203,7 @@ opens `if (!channel) return false;` before its try, so its `false` conflates _ch
_WhatsApp refused_, and the adapter answers 403 for both. That distinction is ours to make in our own
adapter and involves no library change.
-## 29.4 Full capability matrix — the OpenWA contract view (112 methods)
+## 29.4 Full capability matrix — the OpenWA contract view (113 methods)
Legend recap: **✅** supported · **✅🔧ⁿ** supported via OpenWA patch `🔧ⁿ` (29.3) ·
**❌ gap** adapter-gap · **❌ lib** library-limitation. Column headers carry the engine-wide
@@ -264,6 +264,7 @@ socket is caught by the transport instead. No REST route: the session watchdog p
| `unpinMessage` | ✅ | ✅ | ✅ |
| `getMessageReactions` | ❌ lib | ✅ | ⚠️ wwjs only |
| `votePoll` | ❌ lib | ✅ | ⚠️ wwjs only |
+| `clickButton` | ✅ | ❌ lib | ⚠️ Baileys only |
### 29.4.4 Chats
@@ -395,9 +396,9 @@ answers 501.
| `rejectCall` | ✅ | ✅ | ✅ |
| `createCallLink` | ✅ | ✅ | ✅ |
-**Totals:** 112 methods → 224 adapter cells: **199 ✅, 25 ❌** (2 adapter-gaps, 23
-library-limitations, 0 uncertain) across 24 methods. From the REST caller's side: **90** methods
-work on any engine (89 fully supported + 2 store-backed status reads), **11** are Baileys-only,
+**Totals:** 113 methods → 226 adapter cells: **200 ✅, 26 ❌** (2 adapter-gaps, 24
+library-limitations, 0 uncertain) across 25 methods. From the REST caller's side: **90** methods
+work on any engine (89 fully supported + 2 store-backed status reads), **12** are Baileys-only,
**9** are wwjs-only (the 2 store-backed rows excluded); `sendCatalog`, unavailable on both engines,
is not exposed.
@@ -858,7 +859,7 @@ adapter boundary — none silently stubs.
| `sendCatalog` | lib | `AnyMessageContent` (`Types/Message.d.ts:166-210`) has only `{product}` (single product); the catalog CRUD nodes (`Socket/business.js:294-362`) mutate the catalog, they don't send it. |
| `votePoll` | lib | No vote-send helper at all; the library only _decrypts incoming_ votes (`decryptPollVote`). Sending needs a hand-built `proto.Message.PollUpdateMessage` with HMAC-SHA256 encryption keyed by the poll creation's `messageSecret`. |
-### 29.6.2 wwjs adapter (13 cells)
+### 29.6.2 wwjs adapter (14 cells)
| Method | Cause | What's missing (evidence) |
| -------------------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -875,6 +876,7 @@ adapter boundary — none silently stubs.
| `sendProduct` | lib | No outbound product content type. |
| `sendCatalog` | lib | No `Client.sendCatalog` in `index.d.ts` (0 hits). |
| `setGroupEphemeral` | lib | No disappearing-timer setter (0 hits for `ephemeral` in `index.d.ts`); only the create-time `messageTimer` option (`Client.js:2328`). |
+| `clickButton` | lib | No interactive button-reply send path; inbound buttons are not exposable as a clickable Client action. Baileys relays a response proto via `generateWAMessageFromContent` + `relayMessage`. |
## 29.7 Caveats on supported rows
@@ -956,9 +958,9 @@ adapter boundary — none silently stubs.
Recomputed from `engine-capability-matrix.ts`, `upstream-surface.snapshot.json`, and a scan of the
adapter sources — re-derive the same way when anything changes:
-- **112** interface methods → **224** adapter cells: **199 ✅** / **25 ❌** (2 adapter-gaps, 23
- library-limitations, 0 uncertain), spanning **24** methods.
-- Of the 199 ✅ cells, **10 wwjs cells carry an explicit patch dependency** (4 × 🔧² status send,
+- **113** interface methods → **226** adapter cells: **200 ✅** / **26 ❌** (2 adapter-gaps, 24
+ library-limitations, 0 uncertain), spanning **25** methods.
+- Of the 200 ✅ cells, **10 wwjs cells carry an explicit patch dependency** (4 × 🔧² status send,
1 × 🔧³ channel link preview, 1 × 🔧⁴ ready-sync, 3 × 🔧⁷ participant arity, 1 × 🔧⁹ group
description) and one baileys cell
does (1 × 🔧⁶ newsletter-create parse); the whole wwjs column additionally
diff --git a/sdk/README.md b/sdk/README.md
index 8c4d8e988..9e5c5dd6e 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, getConfig, updateConfig, getProxy, updateProxy, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, setOnlinePresence, stats |
-| `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 |
+| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, clickButton, 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, listBlocked |
| `groups` | list, get, create, joinGroup, joinInfo, add/remove/promote/demoteParticipants, setSubject, setDescription, get/updateGroupSettings, leave, getPicture, setPicture, deletePicture, inviteCode, revokeInviteCode, getMembershipRequests, approveMembershipRequests, rejectMembershipRequests |
| `webhooks` | list, listAll, deliveryFailures, get, create, update, delete, test |
diff --git a/sdk/go/chat_history_decode_test.go b/sdk/go/chat_history_decode_test.go
index 2007abdc8..150fd4a63 100644
--- a/sdk/go/chat_history_decode_test.go
+++ b/sdk/go/chat_history_decode_test.go
@@ -39,6 +39,22 @@ func TestChatHistoryMessageDecodesEngineFields(t *testing.T) {
}
}
+func TestChatHistoryMessageDecodesButtonReply(t *testing.T) {
+ raw := []byte(`{
+ "body":"Yes, notify me","type":"text","timestamp":1719312000,"fromMe":false,"isGroup":false,
+ "kind":"individual","button":{"id":"btn_yes","text":"Yes, notify me"}
+ }`)
+
+ var m ChatHistoryMessage
+ if err := json.Unmarshal(raw, &m); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if m.Button == nil || m.Button.ID != "btn_yes" || m.Button.Text != "Yes, notify me" {
+ t.Errorf("button = %+v, want {ID:btn_yes Text:Yes, notify me}", m.Button)
+ }
+}
+
func TestChatHistoryMessageLeavesAbsentFieldsEmpty(t *testing.T) {
raw := []byte(`{"id":"x","from":"a","to":"b","chatId":"c","body":"","type":"text",
"timestamp":1,"fromMe":false,"isGroup":false,"kind":"individual"}`)
@@ -47,8 +63,8 @@ func TestChatHistoryMessageLeavesAbsentFieldsEmpty(t *testing.T) {
if err := json.Unmarshal(raw, &m); err != nil {
t.Fatalf("unmarshal: %v", err)
}
- if m.Call != nil || m.Contact != nil || m.Font != nil {
- t.Errorf("absent optionals should stay nil: call=%v contact=%v font=%v", m.Call, m.Contact, m.Font)
+ if m.Call != nil || m.Contact != nil || m.Font != nil || m.Button != nil {
+ t.Errorf("absent optionals should stay nil: call=%v contact=%v font=%v button=%v", m.Call, m.Contact, m.Font, m.Button)
}
if m.EphemeralDuration != 0 || m.BackgroundColor != "" {
t.Errorf("absent scalars should stay zero: ephemeral=%d bg=%q", m.EphemeralDuration, m.BackgroundColor)
diff --git a/sdk/go/messages.go b/sdk/go/messages.go
index 9fb2e6edb..739d14cd9 100644
--- a/sdk/go/messages.go
+++ b/sdk/go/messages.go
@@ -85,6 +85,11 @@ func (s *MessagesService) Reply(ctx context.Context, sessionID string, body Repl
return s.send(ctx, sessionID, "reply", body)
}
+// ClickButton taps a choice on a WhatsApp Business prompt. Baileys only (whatsapp-web.js returns 501).
+func (s *MessagesService) ClickButton(ctx context.Context, sessionID string, body ClickButtonRequest) (*MessageResponse, error) {
+ return s.send(ctx, sessionID, "click-button", body)
+}
+
// Forward forwards a message between chats.
func (s *MessagesService) Forward(ctx context.Context, sessionID string, body ForwardMessageRequest) (*MessageResponse, error) {
return s.send(ctx, sessionID, "forward", body)
diff --git a/sdk/go/routing_test.go b/sdk/go/routing_test.go
index 8b08a56e7..2c062bf76 100644
--- a/sdk/go/routing_test.go
+++ b/sdk/go/routing_test.go
@@ -46,6 +46,7 @@ func TestRouting(t *testing.T) {
{"Messages.SendTemplate", func(c *Client) { c.Messages.SendTemplate(ctx, "s1", SendTemplateRequest{}) }, "POST", "/api/sessions/s1/messages/send-template"},
{"Messages.SendPoll", func(c *Client) { c.Messages.SendPoll(ctx, "s1", SendPollRequest{}) }, "POST", "/api/sessions/s1/messages/send-poll"},
{"Messages.Reply", func(c *Client) { c.Messages.Reply(ctx, "s1", ReplyMessageRequest{}) }, "POST", "/api/sessions/s1/messages/reply"},
+ {"Messages.ClickButton", func(c *Client) { c.Messages.ClickButton(ctx, "s1", ClickButtonRequest{}) }, "POST", "/api/sessions/s1/messages/click-button"},
{"Messages.Forward", func(c *Client) { c.Messages.Forward(ctx, "s1", ForwardMessageRequest{}) }, "POST", "/api/sessions/s1/messages/forward"},
{"Messages.React", func(c *Client) { c.Messages.React(ctx, "s1", ReactMessageRequest{}) }, "POST", "/api/sessions/s1/messages/react"},
{"Messages.Delete", func(c *Client) { c.Messages.Delete(ctx, "s1", DeleteMessageRequest{}) }, "POST", "/api/sessions/s1/messages/delete"},
diff --git a/sdk/go/types_message.go b/sdk/go/types_message.go
index 5ef22ac19..886588281 100644
--- a/sdk/go/types_message.go
+++ b/sdk/go/types_message.go
@@ -130,6 +130,14 @@ type ReplyMessageRequest struct {
Mentions []string `json:"mentions,omitempty"`
}
+// ClickButtonRequest taps a choice on a WhatsApp Business prompt. Baileys only.
+type ClickButtonRequest struct {
+ ChatID string `json:"chatId"`
+ MessageID string `json:"messageId"`
+ ButtonID string `json:"buttonId"`
+ Text string `json:"text,omitempty"`
+}
+
// ForwardMessageRequest forwards a message between chats.
type ForwardMessageRequest struct {
FromChatID string `json:"fromChatId"`
@@ -295,6 +303,8 @@ type ChatHistoryMessage struct {
Location *MessageLocation `json:"location,omitempty"`
Order *MessageOrder `json:"order,omitempty"`
Product *MessageProduct `json:"product,omitempty"`
+ Button *MessageButton `json:"button,omitempty"`
+ Buttons []MessageButtonChoice `json:"buttons,omitempty"`
}
// MessageOrder is the order block on a live history message, present on order messages only: the
@@ -313,6 +323,19 @@ type MessageProduct struct {
BusinessOwnerJID string `json:"businessOwnerJid,omitempty"`
}
+// MessageButton is the button/list reply block when the sender tapped a WhatsApp Business control.
+// Baileys only; ID is the stable handle, Text the visible label when WhatsApp still carries it.
+type MessageButton struct {
+ ID string `json:"id"`
+ Text string `json:"text,omitempty"`
+}
+
+// MessageButtonChoice is one choice on an inbound WhatsApp Business prompt (buttons or list rows).
+type MessageButtonChoice struct {
+ ID string `json:"id"`
+ Text string `json:"text"`
+}
+
// MessageCall is the call block on a live history message, present on call messages only.
type MessageCall struct {
Video bool `json:"video"`
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java
index 9af781364..7a9a6f063 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java
@@ -36,7 +36,9 @@ public record ChatHistoryMessage(
QuotedMessage quotedMessage,
Location location,
Order order,
- Product product) {
+ Product product,
+ Button button,
+ List<ButtonChoice> buttons) {
/** Attached media; {@code data} is absent when the payload was omitted (too large). */
public record Media(String mimetype, String filename, String data, Boolean omitted, Long sizeBytes) {}
@@ -57,6 +59,18 @@ public record ChatHistoryMessage(
/** Present on {@code product} messages only: the catalog product shared into the chat. */
public record Product(String productId, String title, String description, String businessOwnerJid) {}
+ /**
+ * Present when the sender tapped a WhatsApp Business button, template quick-reply, list row, or
+ * native-flow control. Baileys only; {@code id} is the stable handle, {@code text} the visible
+ * label when WhatsApp still carries it.
+ */
+ public record Button(String id, String text) {}
+
+ /**
+ * One choice on an inbound WhatsApp Business prompt (buttons or list rows). Baileys only.
+ */
+ public record ButtonChoice(String id, String text) {}
+
/**
* Sender contact info. History carries {@code pushName} only; the richer fields arrive on
* {@code message.received} when {@code WEBHOOK_CONTACT_DETAILS} is enabled.
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ClickButtonRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ClickButtonRequest.java
new file mode 100644
index 000000000..1c3d70f25
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ClickButtonRequest.java
@@ -0,0 +1,42 @@
+package com.rmyndharis.openwa.model;
+
+/**
+ * Request body for tapping a choice on a WhatsApp Business prompt. Baileys only —
+ * whatsapp-web.js answers 501.
+ */
+public record ClickButtonRequest(String chatId, String messageId, String buttonId, String text) {
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static final class Builder {
+ private String chatId;
+ private String messageId;
+ private String buttonId;
+ private String text;
+
+ public Builder chatId(String v) {
+ this.chatId = v;
+ return this;
+ }
+
+ public Builder messageId(String v) {
+ this.messageId = v;
+ return this;
+ }
+
+ public Builder buttonId(String v) {
+ this.buttonId = v;
+ return this;
+ }
+
+ public Builder text(String v) {
+ this.text = v;
+ return this;
+ }
+
+ public ClickButtonRequest build() {
+ return new ClickButtonRequest(chatId, messageId, buttonId, text);
+ }
+ }
+}
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 5c54d24bc..4c9e61334 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
@@ -19,6 +19,7 @@ import com.rmyndharis.openwa.model.PinMessageRequest;
import com.rmyndharis.openwa.model.ReactMessageRequest;
import com.rmyndharis.openwa.model.ReactionRecord;
import com.rmyndharis.openwa.model.ReplyMessageRequest;
+import com.rmyndharis.openwa.model.ClickButtonRequest;
import com.rmyndharis.openwa.model.SendBulkRequest;
import com.rmyndharis.openwa.model.SendContactRequest;
import com.rmyndharis.openwa.model.SendLocationRequest;
@@ -140,6 +141,19 @@ public final class MessagesResource {
MessageResponse.class);
}
+ /**
+ * Click a button on a WhatsApp Business prompt. Baileys only — whatsapp-web.js returns 501.
+ * Sends a structured reply proto quoted to the prompt, not a native UI tap.
+ */
+ public MessageResponse clickButton(String sessionId, ClickButtonRequest body) {
+ return client.request(
+ HttpMethod.POST,
+ "/api/sessions/" + encodeSegment(sessionId) + "/messages/click-button",
+ null,
+ body,
+ MessageResponse.class);
+ }
+
/** Forward a message to another chat. */
public MessageResponse forward(String sessionId, ForwardMessageRequest body) {
return client.request(
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 488548b0b..5cf8e378a 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
@@ -19,6 +19,7 @@ import com.rmyndharis.openwa.model.MessageHistoryQuery;
import com.rmyndharis.openwa.model.PinMessageRequest;
import com.rmyndharis.openwa.model.ReactMessageRequest;
import com.rmyndharis.openwa.model.ReplyMessageRequest;
+import com.rmyndharis.openwa.model.ClickButtonRequest;
import com.rmyndharis.openwa.model.SendBulkRequest;
import com.rmyndharis.openwa.model.SendContactRequest;
import com.rmyndharis.openwa.model.SendLocationRequest;
@@ -268,6 +269,22 @@ class MessagesResourceTest {
assertTrue(tx.lastRequest().body().contains("quoted-123"));
}
+ @Test
+ void clickButtonHitsClickButtonPath() {
+ tx.respond(200, MSG);
+ client.messages.clickButton(
+ "s",
+ ClickButtonRequest.builder()
+ .chatId("[email protected]")
+ .messageId("prompt-1")
+ .buttonId("yes")
+ .text("Sim")
+ .build());
+ assertEquals("http://h/api/sessions/s/messages/click-button", tx.lastRequest().url());
+ assertTrue(tx.lastRequest().body().contains("prompt-1"));
+ assertTrue(tx.lastRequest().body().contains("yes"));
+ }
+
@Test
void forwardHitsForwardPath() {
tx.respond(200, MSG);
diff --git a/sdk/javascript/src/resources/messages.ts b/sdk/javascript/src/resources/messages.ts
index b9ee8b114..3b17f3fe8 100644
--- a/sdk/javascript/src/resources/messages.ts
+++ b/sdk/javascript/src/resources/messages.ts
@@ -13,6 +13,7 @@ import type {
BatchStatusResponse,
BulkMessageResponse,
ChatHistoryMessage,
+ ClickButtonRequest,
DeleteMessageRequest,
EditMessageRequest,
ForwardMessageRequest,
@@ -129,6 +130,18 @@ export class MessagesResource {
});
}
+ /**
+ * Click a button on a WhatsApp Business prompt. Baileys only (whatsapp-web.js returns 501).
+ * Sends a structured reply proto quoted to the prompt — not a native UI tap.
+ */
+ clickButton(sessionId: string, body: ClickButtonRequest): Promise<MessageResponse> {
+ return this.client.request<MessageResponse>({
+ method: 'POST',
+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/click-button`,
+ body,
+ });
+ }
+
/** Forward a message to another chat. */
forward(sessionId: string, body: ForwardMessageRequest): Promise<MessageResponse> {
return this.client.request<MessageResponse>({
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index 8a7357105..5b8cf9587 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -331,6 +331,16 @@ export interface ReplyMessageRequest {
mentions?: string[];
}
+export interface ClickButtonRequest {
+ chatId: Jid;
+ /** WhatsApp id of the business prompt that offered the buttons. */
+ messageId: string;
+ /** Stable id of the choice (inbound `buttons[].id`). */
+ buttonId: string;
+ /** Visible label; resolved from the stored prompt when omitted. */
+ text?: string;
+}
+
export interface ForwardMessageRequest {
fromChatId: Jid;
toChatId: Jid;
@@ -599,6 +609,16 @@ export interface ChatHistoryMessage {
order?: { orderId: string; token?: string };
/** Present on `product` messages only: the catalog product shared into the chat. */
product?: { productId: string; title?: string; description?: string; businessOwnerJid?: Jid };
+ /**
+ * Present when the sender tapped a WhatsApp Business button, template quick-reply, list row, or
+ * native-flow control. **Baileys only.**
+ */
+ button?: { id: string; text?: string };
+ /**
+ * Present on an inbound WhatsApp Business prompt that offers buttons (or list rows). Distinct from
+ * `button`, which is set only when someone taps a choice. **Baileys only.**
+ */
+ buttons?: Array<{ id: string; text: string }>;
}
/** Paginated payload returned by `GET /sessions/:id/messages`. */
diff --git a/sdk/javascript/test/messages.test.ts b/sdk/javascript/test/messages.test.ts
index 8e93d4b85..1b224e7d8 100644
--- a/sdk/javascript/test/messages.test.ts
+++ b/sdk/javascript/test/messages.test.ts
@@ -167,6 +167,26 @@ describe('MessagesResource — exact paths', () => {
expect(t.lastCall!.url).toContain('/messages/delete');
});
+ it('clickButton posts to /messages/click-button', async () => {
+ const t = new MockTransport().on('POST', /\/messages\/click-button$/, {
+ body: { messageId: 'm2', timestamp: 9 },
+ });
+ const res = await client(t).messages.clickButton('s', {
+ chatId: '[email protected]',
+ messageId: 'prompt1',
+ buttonId: 'yes',
+ text: 'Sim',
+ });
+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/messages/click-button');
+ expect(t.lastCall!.body).toEqual({
+ chatId: '[email protected]',
+ messageId: 'prompt1',
+ buttonId: 'yes',
+ text: 'Sim',
+ });
+ expect(res.messageId).toBe('m2');
+ });
+
it('editMessage posts to /messages/edit and returns the MessageResponse shape', async () => {
const t = new MockTransport().on('POST', /\/messages\/edit$/, { body: { messageId: 'm1', timestamp: 4 } });
const res = await client(t).messages.editMessage('s', { chatId: '[email protected]', messageId: 'm1', body: 'edited' });
diff --git a/sdk/javascript/test/wire-contract.test-d.ts b/sdk/javascript/test/wire-contract.test-d.ts
index 9b9f070b8..1deb55133 100644
--- a/sdk/javascript/test/wire-contract.test-d.ts
+++ b/sdk/javascript/test/wire-contract.test-d.ts
@@ -141,6 +141,8 @@ interface WireChatHistoryMessage {
location?: { latitude: number; longitude: number; description?: string; address?: string; url?: string };
order?: { orderId: string; token?: string };
product?: { productId: string; title?: string; description?: string; businessOwnerJid?: string };
+ button?: { id: string; text?: string };
+ buttons?: Array<{ id: string; text: string }>;
}
/** `Catalog` — the control: this pair already agreed before #754 and must stay agreeing. */
diff --git a/sdk/php/src/Resources/MessagesResource.php b/sdk/php/src/Resources/MessagesResource.php
index 329caef96..9a9ca5d7c 100644
--- a/sdk/php/src/Resources/MessagesResource.php
+++ b/sdk/php/src/Resources/MessagesResource.php
@@ -123,6 +123,17 @@ class MessagesResource
return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/reply", [], $body);
}
+ /**
+ * Click a button on a WhatsApp Business prompt. Baileys only (whatsapp-web.js returns 501).
+ *
+ * @param array<string,mixed> $body chatId, messageId, buttonId; text optional.
+ * @return array<string,mixed>
+ */
+ public function clickButton(string $sessionId, array $body): array
+ {
+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/click-button", [], $body);
+ }
+
/** @return array<string,mixed> */
public function forward(string $sessionId, array $body): array
{
diff --git a/sdk/php/tests/MessagesTest.php b/sdk/php/tests/MessagesTest.php
index af6c5d391..1f1e94ed3 100644
--- a/sdk/php/tests/MessagesTest.php
+++ b/sdk/php/tests/MessagesTest.php
@@ -96,17 +96,20 @@ class MessagesTest extends TestCase
$backend = new MockBackend();
$backend->on(201, ['messageId' => 'm', 'timestamp' => 1]);
$backend->on(201, ['messageId' => 'm', 'timestamp' => 1]);
+ $backend->on(201, ['messageId' => 'm', 'timestamp' => 1]);
$backend->on(200, ['success' => true]);
$backend->on(200, ['success' => true]);
$client = $backend->makeClient();
$client->messages->reply('s', ['chatId' => '[email protected]', 'quotedMessageId' => 'q', 'text' => 'r']);
$this->assertStringContainsString('/messages/reply', $backend->calls()[0]['url']);
+ $client->messages->clickButton('s', ['chatId' => '[email protected]', 'messageId' => 'p', 'buttonId' => 'yes', 'text' => 'Sim']);
+ $this->assertStringContainsString('/messages/click-button', $backend->calls()[1]['url']);
$client->messages->forward('s', ['fromChatId' => '[email protected]', 'toChatId' => '[email protected]', 'messageId' => 'm']);
- $this->assertStringContainsString('/messages/forward', $backend->calls()[1]['url']);
+ $this->assertStringContainsString('/messages/forward', $backend->calls()[2]['url']);
$client->messages->react('s', ['chatId' => '[email protected]', 'messageId' => 'm', 'emoji' => '👍']);
- $this->assertStringContainsString('/messages/react', $backend->calls()[2]['url']);
+ $this->assertStringContainsString('/messages/react', $backend->calls()[3]['url']);
$client->messages->delete('s', ['chatId' => '[email protected]', 'messageId' => 'm']);
- $this->assertStringContainsString('/messages/delete', $backend->calls()[3]['url']);
+ $this->assertStringContainsString('/messages/delete', $backend->calls()[4]['url']);
}
/**
diff --git a/sdk/python/openwa/resources/messages.py b/sdk/python/openwa/resources/messages.py
index 9fe9c5103..cd25579c5 100644
--- a/sdk/python/openwa/resources/messages.py
+++ b/sdk/python/openwa/resources/messages.py
@@ -28,6 +28,7 @@ from ..types import (
ReactionRecord,
ReactMessageRequest,
ReplyMessageRequest,
+ ClickButtonRequest,
SendBulkRequest,
SendContactRequest,
SendLocationRequest,
@@ -87,6 +88,12 @@ class MessagesResource:
def reply(self, session_id: str, body: ReplyMessageRequest) -> MessageResponse:
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/reply", body=body)
+ def click_button(self, session_id: str, body: ClickButtonRequest) -> MessageResponse:
+ """Click a button on a WhatsApp Business prompt. Baileys only (whatsapp-web.js returns 501)."""
+ return self._http.request(
+ "POST", f"/api/sessions/{quote_segment(session_id)}/messages/click-button", body=body
+ )
+
def forward(self, session_id: str, body: ForwardMessageRequest) -> MessageResponse:
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/forward", body=body)
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index ed974b480..f9a6e3e6b 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -559,6 +559,21 @@ class MessageProduct(TypedDict):
businessOwnerJid: NotRequired[str]
+class MessageButton(TypedDict):
+ """Button/list reply block on a live history message when the sender tapped a WhatsApp Business
+ control. Baileys only; ``id`` is the stable handle, ``text`` the visible label when present."""
+
+ id: str
+ text: NotRequired[str]
+
+
+class MessageButtonChoice(TypedDict):
+ """One choice on an inbound WhatsApp Business prompt (buttons or list rows). Baileys only."""
+
+ id: str
+ text: str
+
+
class MessageContact(TypedDict, total=False):
"""Sender contact block. History carries ``pushName`` only; the richer fields arrive on
``message.received`` when ``WEBHOOK_CONTACT_DETAILS`` is enabled."""
@@ -609,6 +624,8 @@ ChatHistoryMessage = TypedDict(
"location": NotRequired[MessageLocation],
"order": NotRequired[MessageOrder],
"product": NotRequired[MessageProduct],
+ "button": NotRequired[MessageButton],
+ "buttons": NotRequired[list[MessageButtonChoice]],
},
)
@@ -1104,6 +1121,15 @@ class VotePollRequest(TypedDict):
options: list[str]
+class ClickButtonRequest(TypedDict):
+ """Click a choice on a WhatsApp Business prompt. Baileys only."""
+
+ chatId: str
+ messageId: str
+ buttonId: str
+ text: NotRequired[str]
+
+
class StarMessageRequest(TypedDict):
"""Star or unstar a message. Best-effort on whatsapp-web.js."""
diff --git a/src/engine/adapters/baileys-click-button.spec.ts b/src/engine/adapters/baileys-click-button.spec.ts
new file mode 100644
index 000000000..99c4da2af
--- /dev/null
+++ b/src/engine/adapters/baileys-click-button.spec.ts
@@ -0,0 +1,101 @@
+import type { WASocket } from '@whiskeysockets/baileys';
+import { BadRequestException } from '@nestjs/common';
+import { BaileysMessaging, type BaileysMessagingHost } from './baileys-messaging';
+import { MessageNotFoundError } from '../../common/errors/message-not-found.error';
+import { createLogger } from '../../common/services/logger.service';
+
+const logger = createLogger('baileys-click-button.spec');
+
+const PROMPT = {
+ key: { id: 'PROMPT-1', remoteJid: '[email protected]', fromMe: false },
+ message: {
+ buttonsMessage: {
+ contentText: 'Já é nosso cliente?',
+ buttons: [
+ { buttonId: 'yes', buttonText: { displayText: 'Sim' } },
+ { buttonId: 'no', buttonText: { displayText: 'Não' } },
+ ],
+ },
+ },
+};
+
+function makeMessaging(stored: unknown = PROMPT) {
+ const relayMessage = jest.fn().mockResolvedValue(undefined);
+ const sock = { relayMessage, sendMessage: jest.fn() };
+ const getStoredMessage = jest.fn().mockResolvedValue(stored);
+ const putStoredMessage = jest.fn();
+ const generateWAMessageFromContent = jest.fn().mockReturnValue({
+ key: { id: 'CLICK-1', remoteJid: '[email protected]' },
+ message: { templateButtonReplyMessage: { selectedId: 'yes' } },
+ messageTimestamp: 1700000000,
+ });
+ const host = {
+ ensureReady: jest.fn(),
+ sessionProxyUrl: () => undefined,
+ getSocket: () => sock as unknown as WASocket,
+ logger,
+ toNeutralJid: (j: string) => j.replace('@c.us', '@s.whatsapp.net'),
+ toEngineJid: (j: string) => j,
+ normalizedSelfJid: () => '[email protected]',
+ getEphemeralExpiration: () => undefined,
+ toUnixSeconds: (ts: number | { toNumber(): number } | null | undefined) =>
+ typeof ts === 'number' ? ts : ts && 'toNumber' in ts ? ts.toNumber() : 0,
+ loadLib: () =>
+ Promise.resolve({
+ normalizeMessageContent: (c: unknown) => c,
+ getContentType: () => 'buttonsMessage',
+ generateWAMessageFromContent,
+ } as never),
+ getStoredMessage,
+ putStoredMessage,
+ recordLidMapping: () => undefined,
+ getOnMessageCreate: () => undefined,
+ mapMessage: () => Promise.resolve({} as never),
+ } as unknown as BaileysMessagingHost;
+ return {
+ messaging: new BaileysMessaging(host),
+ relayMessage,
+ generateWAMessageFromContent,
+ getStoredMessage,
+ putStoredMessage,
+ };
+}
+
+describe('BaileysMessaging.clickButton', () => {
+ it('relays a response proto quoted to the stored prompt', async () => {
+ const { messaging, relayMessage, generateWAMessageFromContent, putStoredMessage } = makeMessaging();
+ const result = await messaging.clickButton('[email protected]', 'PROMPT-1', 'yes', 'Sim');
+ expect(generateWAMessageFromContent).toHaveBeenCalledWith(
+ {
+ buttonsResponseMessage: {
+ selectedButtonId: 'yes',
+ selectedDisplayText: 'Sim',
+ type: 1,
+ },
+ },
+ expect.objectContaining({ quoted: PROMPT }),
+ );
+ expect(relayMessage).toHaveBeenCalledWith(
+ { templateButtonReplyMessage: { selectedId: 'yes' } },
+ { messageId: 'CLICK-1' },
+ );
+ expect(putStoredMessage).toHaveBeenCalled();
+ expect(result).toEqual({ id: 'CLICK-1', timestamp: 1700000000 });
+ });
+
+ it('404s when the prompt is not in the store', async () => {
+ const { messaging } = makeMessaging(null);
+ await expect(messaging.clickButton('[email protected]', 'MISSING', 'yes')).rejects.toBeInstanceOf(
+ MessageNotFoundError,
+ );
+ });
+
+ it('400s when buttonId is not among the prompt choices', async () => {
+ const { messaging } = makeMessaging();
+ await expect(messaging.clickButton('[email protected]', 'PROMPT-1', 'maybe')).rejects.toBeInstanceOf(
+ BadRequestException,
+ );
+ });
+});
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.ts
index c2e3d3f29..e216fd4dd 100644
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@ -15,6 +15,8 @@ import {
import {
buildIncomingMessageFromBaileys,
extractBaileysBody,
+ extractBaileysButtonReply,
+ extractBaileysButtons,
extractBaileysCommerce,
extractBaileysContext,
extractBaileysLocation,
@@ -944,6 +946,10 @@ export class BaileysEvents {
// Commerce ids (order token, product id): the generic path sees an empty body and drops them,
// and they are the only handle a caller has on the order or the product.
const commerce = extractBaileysCommerce(normalized, contentType);
+ // Button / list / native-flow reply ids: body carries the visible label; this is the stable id.
+ const button = extractBaileysButtonReply(normalized, contentType);
+ // Prompt choices (Sim/Não, list rows, …) offered by a business interactive message.
+ const buttons = extractBaileysButtons(normalized, contentType);
return buildIncomingMessageFromBaileys(
{
@@ -962,6 +968,8 @@ export class BaileysEvents {
quotedMessage: context.quotedMessage,
order: commerce.order,
product: commerce.product,
+ button,
+ buttons,
isCatalogShare: isBaileysCatalogShare(normalized),
ephemeralDuration: context.ephemeralDuration,
mentionedJids: context.mentionedJids,
diff --git a/src/engine/adapters/baileys-history.ts b/src/engine/adapters/baileys-history.ts
index 8b5321ebb..996989d9d 100644
--- a/src/engine/adapters/baileys-history.ts
+++ b/src/engine/adapters/baileys-history.ts
@@ -4,6 +4,8 @@ import { EngineEventCallbacks, IncomingMessage } from '../interfaces/whatsapp-en
import {
buildIncomingMessageFromBaileys,
extractBaileysBody,
+ extractBaileysButtonReply,
+ extractBaileysButtons,
extractBaileysCommerce,
isBaileysCatalogShare,
} from './baileys-message-mapper';
@@ -150,6 +152,8 @@ export class BaileysHistory {
}
const body = extractBaileysBody(content);
const commerce = extractBaileysCommerce(content, contentType);
+ const button = extractBaileysButtonReply(content, contentType);
+ const buttons = extractBaileysButtons(content, contentType);
return buildIncomingMessageFromBaileys(
{
id: msg.key.id,
@@ -165,6 +169,8 @@ export class BaileysHistory {
// Same commerce mapping as the live path, so a whole-catalog share is `unknown` on both.
order: commerce.order,
product: commerce.product,
+ button,
+ buttons,
isCatalogShare: isBaileysCatalogShare(content),
// Populate the disappearing-messages timer using the same extraction the live path and the
// session-store cache share (`msg.ephemeralDuration` primary, `contextInfo.expiration` fallback),
diff --git a/src/engine/adapters/baileys-message-mapper.spec.ts b/src/engine/adapters/baileys-message-mapper.spec.ts
index dc79cedf3..01b9b60ac 100644
--- a/src/engine/adapters/baileys-message-mapper.spec.ts
+++ b/src/engine/adapters/baileys-message-mapper.spec.ts
@@ -2,6 +2,9 @@ import {
BaileysIncomingFields,
buildIncomingMessageFromBaileys,
extractBaileysBody,
+ extractBaileysButtonReply,
+ extractBaileysButtons,
+ resolveBaileysButtonClick,
extractBaileysCommerce,
extractBaileysContext,
isBaileysCatalogShare,
@@ -27,6 +30,10 @@ describe('mapBaileysMessageType (baileys content-type -> neutral MessageType)',
['buttonsMessage', false, 'text'],
['templateMessage', false, 'text'],
['interactiveResponseMessage', false, 'text'],
+ ['buttonsResponseMessage', false, 'text'],
+ ['templateButtonReplyMessage', false, 'text'],
+ ['listResponseMessage', false, 'text'],
+ ['listMessage', false, 'text'],
// Meta masks high-security business messages (enterprise OTPs) on linked/companion devices,
// delivering a bodyless `placeholderMessage` (PlaceholderType MASK_LINKED_DEVICES). Surface it as
// its own `masked` type so it is distinguishable from a genuinely unparseable message (#574).
@@ -171,6 +178,10 @@ describe('extractBaileysBody (inbound text/caption + interactive shapes)', () =>
'Track order',
);
});
+
+ it('extracts a list-row title the user selected', () => {
+ expect(extractBaileysBody({ listResponseMessage: { title: 'Express shipping' } })).toBe('Express shipping');
+ });
});
describe('extractBaileysContext (quoted body shares the live body extractor)', () => {
@@ -193,6 +204,16 @@ describe('extractBaileysContext (quoted body shares the live body extractor)', (
expect(quoted({ conversation: 'the original' })?.body).toBe('the original');
expect(quoted({ stickerMessage: {} })?.body).toBe('');
});
+
+ it('carries a quote from a button-reply contextInfo', () => {
+ expect(
+ extractBaileysContext({
+ buttonsResponseMessage: {
+ contextInfo: { stanzaId: 'wamid.prompt', quotedMessage: { conversation: 'Pick one' } },
+ },
+ }).quotedMessage,
+ ).toEqual({ id: 'wamid.prompt', body: 'Pick one' });
+ });
});
describe('buildIncomingMessageFromBaileys', () => {
@@ -364,6 +385,294 @@ describe('buildIncomingMessageFromBaileys', () => {
'unknown',
);
});
+
+ it('carries a button reply and types the reply content as text', () => {
+ const r = buildIncomingMessageFromBaileys({
+ ...base,
+ contentType: 'buttonsResponseMessage',
+ body: 'Yes, notify me',
+ button: { id: 'btn_yes', text: 'Yes, notify me' },
+ });
+ expect(r.type).toBe('text');
+ expect(r.button).toEqual({ id: 'btn_yes', text: 'Yes, notify me' });
+ });
+
+ it('fills body from the button label when the content body is empty', () => {
+ const r = buildIncomingMessageFromBaileys({
+ ...base,
+ contentType: 'interactiveResponseMessage',
+ body: '',
+ button: { id: 'qr_1', text: 'Confirm' },
+ });
+ expect(r.body).toBe('Confirm');
+ expect(r.button).toEqual({ id: 'qr_1', text: 'Confirm' });
+ });
+
+ it('carries prompt buttons on an inbound business message', () => {
+ const r = buildIncomingMessageFromBaileys({
+ ...base,
+ contentType: 'buttonsMessage',
+ body: 'Já é nosso cliente?',
+ buttons: [
+ { id: 'yes', text: 'Sim' },
+ { id: 'no', text: 'Não' },
+ ],
+ });
+ expect(r.type).toBe('text');
+ expect(r.buttons).toEqual([
+ { id: 'yes', text: 'Sim' },
+ { id: 'no', text: 'Não' },
+ ]);
+ });
+});
+
+describe('extractBaileysButtonReply (button / list / native-flow ids)', () => {
+ it('extracts a classic buttonsResponseMessage id and label', () => {
+ expect(
+ extractBaileysButtonReply(
+ {
+ buttonsResponseMessage: { selectedButtonId: 'btn_yes', selectedDisplayText: 'Yes, notify me' },
+ },
+ 'buttonsResponseMessage',
+ ),
+ ).toEqual({ id: 'btn_yes', text: 'Yes, notify me' });
+ });
+
+ it('extracts a templateButtonReplyMessage id and label', () => {
+ expect(
+ extractBaileysButtonReply(
+ {
+ templateButtonReplyMessage: { selectedId: 'track', selectedDisplayText: 'Track order' },
+ },
+ 'templateButtonReplyMessage',
+ ),
+ ).toEqual({ id: 'track', text: 'Track order' });
+ });
+
+ it('extracts a listResponseMessage row id and title', () => {
+ expect(
+ extractBaileysButtonReply(
+ {
+ listResponseMessage: {
+ title: 'Express shipping',
+ singleSelectReply: { selectedRowId: 'ship_express' },
+ },
+ },
+ 'listResponseMessage',
+ ),
+ ).toEqual({ id: 'ship_express', text: 'Express shipping' });
+ });
+
+ it('extracts a native-flow interactiveResponseMessage id from paramsJson', () => {
+ expect(
+ extractBaileysButtonReply(
+ {
+ interactiveResponseMessage: {
+ nativeFlowResponseMessage: {
+ name: 'quick_reply',
+ paramsJson: JSON.stringify({ id: 'qr_1', display_text: 'Confirm' }),
+ },
+ },
+ },
+ 'interactiveResponseMessage',
+ ),
+ ).toEqual({ id: 'qr_1', text: 'Confirm' });
+ });
+
+ it('accepts button_id / displayText aliases in native-flow params', () => {
+ expect(
+ extractBaileysButtonReply(
+ {
+ interactiveResponseMessage: {
+ nativeFlowResponseMessage: {
+ paramsJson: JSON.stringify({ button_id: 'alt', displayText: 'OK' }),
+ },
+ },
+ },
+ 'interactiveResponseMessage',
+ ),
+ ).toEqual({ id: 'alt', text: 'OK' });
+ });
+
+ it('yields nothing when the actionable id is missing or the JSON is malformed', () => {
+ expect(
+ extractBaileysButtonReply({ buttonsResponseMessage: { selectedDisplayText: 'Yes' } }, 'buttonsResponseMessage'),
+ ).toBeUndefined();
+ expect(
+ extractBaileysButtonReply(
+ { interactiveResponseMessage: { nativeFlowResponseMessage: { paramsJson: '{not-json' } } },
+ 'interactiveResponseMessage',
+ ),
+ ).toBeUndefined();
+ expect(
+ extractBaileysButtonReply(
+ {
+ interactiveResponseMessage: {
+ nativeFlowResponseMessage: { paramsJson: JSON.stringify({ display_text: 'OK' }) },
+ },
+ },
+ 'interactiveResponseMessage',
+ ),
+ ).toBeUndefined();
+ expect(extractBaileysButtonReply({}, 'conversation')).toBeUndefined();
+ });
+});
+
+describe('extractBaileysButtons (prompt choices Sim/Não / list rows)', () => {
+ it('extracts classic buttonsMessage choices', () => {
+ expect(
+ extractBaileysButtons(
+ {
+ buttonsMessage: {
+ buttons: [
+ { buttonId: 'yes', buttonText: { displayText: 'Sim' } },
+ { buttonId: 'no', buttonText: { displayText: 'Não' } },
+ ],
+ },
+ },
+ 'buttonsMessage',
+ ),
+ ).toEqual([
+ { id: 'yes', text: 'Sim' },
+ { id: 'no', text: 'Não' },
+ ]);
+ });
+
+ it('extracts interactiveMessage native-flow quick replies', () => {
+ expect(
+ extractBaileysButtons(
+ {
+ interactiveMessage: {
+ nativeFlowMessage: {
+ buttons: [
+ { name: 'quick_reply', buttonParamsJson: JSON.stringify({ id: 'yes', display_text: 'Sim' }) },
+ { name: 'quick_reply', buttonParamsJson: JSON.stringify({ id: 'no', display_text: 'Não' }) },
+ ],
+ },
+ },
+ },
+ 'interactiveMessage',
+ ),
+ ).toEqual([
+ { id: 'yes', text: 'Sim' },
+ { id: 'no', text: 'Não' },
+ ]);
+ });
+
+ it('extracts listMessage rows as buttons', () => {
+ expect(
+ extractBaileysButtons(
+ {
+ listMessage: {
+ sections: [{ rows: [{ rowId: 'ship_express', title: 'Express' }, { rowId: 'ship_std', title: 'Standard' }] }],
+ },
+ },
+ 'listMessage',
+ ),
+ ).toEqual([
+ { id: 'ship_express', text: 'Express' },
+ { id: 'ship_std', text: 'Standard' },
+ ]);
+ });
+
+ it('yields nothing for a non-prompt content type', () => {
+ expect(extractBaileysButtons({}, 'conversation')).toBeUndefined();
+ expect(extractBaileysButtons({ buttonsMessage: { buttons: [] } }, 'buttonsMessage')).toBeUndefined();
+ });
+});
+
+describe('resolveBaileysButtonClick (API click against a stored prompt)', () => {
+ it('builds a buttonsResponseMessage for a classic buttonsMessage prompt', () => {
+ const result = resolveBaileysButtonClick(
+ {
+ buttonsMessage: {
+ buttons: [
+ { buttonId: 'yes', buttonText: { displayText: 'Sim' } },
+ { buttonId: 'no', buttonText: { displayText: 'Não' } },
+ ],
+ },
+ },
+ 'buttonsMessage',
+ 'yes',
+ );
+ expect(result).toEqual({
+ ok: true,
+ payload: {
+ id: 'yes',
+ text: 'Sim',
+ index: 0,
+ message: {
+ buttonsResponseMessage: {
+ selectedButtonId: 'yes',
+ selectedDisplayText: 'Sim',
+ type: 1,
+ },
+ },
+ },
+ });
+ });
+
+ it('rejects an unknown buttonId and a non-prompt content type', () => {
+ expect(
+ resolveBaileysButtonClick(
+ { buttonsMessage: { buttons: [{ buttonId: 'yes', buttonText: { displayText: 'Sim' } }] } },
+ 'buttonsMessage',
+ 'nope',
+ ),
+ ).toEqual({ ok: false, error: 'unknown_button' });
+ expect(resolveBaileysButtonClick({}, 'conversation', 'yes')).toEqual({ ok: false, error: 'not_a_prompt' });
+ });
+
+ it('skips cta_url interactive buttons so only quick_reply is clickable', () => {
+ const result = resolveBaileysButtonClick(
+ {
+ interactiveMessage: {
+ nativeFlowMessage: {
+ buttons: [
+ {
+ name: 'cta_url',
+ buttonParamsJson: JSON.stringify({ id: 'docs', display_text: 'Docs', url: 'https://x' }),
+ },
+ {
+ name: 'quick_reply',
+ buttonParamsJson: JSON.stringify({ id: 'yes', display_text: 'Sim' }),
+ },
+ ],
+ },
+ },
+ },
+ 'interactiveMessage',
+ 'yes',
+ );
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ expect(result.payload.message).toEqual({
+ templateButtonReplyMessage: {
+ selectedId: 'yes',
+ selectedDisplayText: 'Sim',
+ selectedIndex: 0,
+ },
+ });
+ }
+ expect(
+ resolveBaileysButtonClick(
+ {
+ interactiveMessage: {
+ nativeFlowMessage: {
+ buttons: [
+ {
+ name: 'cta_url',
+ buttonParamsJson: JSON.stringify({ id: 'docs', display_text: 'Docs', url: 'https://x' }),
+ },
+ ],
+ },
+ },
+ },
+ 'interactiveMessage',
+ 'docs',
+ ),
+ ).toEqual({ ok: false, error: 'not_a_prompt' });
+ });
});
describe('extractBaileysCommerce (order / product ids)', () => {
diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.ts
index 6aba8cc29..19c475d3c 100644
--- a/src/engine/adapters/baileys-message-mapper.ts
+++ b/src/engine/adapters/baileys-message-mapper.ts
@@ -45,10 +45,16 @@ export function mapBaileysMessageType(
case 'interactiveMessage':
case 'buttonsMessage':
case 'templateMessage':
+ case 'listMessage':
case 'interactiveResponseMessage':
- // WhatsApp Business interactive shapes (OTP/verification codes, button/template prompts). They
- // carry display text that {@link extractBaileysBody} flattens into `body`, so they surface as
- // `text` instead of being dropped as `unknown` with an empty body (#562).
+ case 'buttonsResponseMessage':
+ case 'templateButtonReplyMessage':
+ case 'listResponseMessage':
+ // WhatsApp Business interactive shapes (OTP/verification codes, button/template prompts) and
+ // the replies when a user taps one. They carry display text that {@link extractBaileysBody}
+ // flattens into `body`, so they surface as `text` instead of being dropped as `unknown` with
+ // an empty body (#562). Prompt messages also populate {@link IncomingMessage.buttons}; replies
+ // populate {@link IncomingMessage.button}.
return 'text';
case 'orderMessage':
return 'order';
@@ -88,6 +94,8 @@ export interface BaileysBodyContent {
hydratedFourRowTemplate?: { hydratedContentText?: string | null } | null;
} | null;
interactiveResponseMessage?: { body?: { text?: string | null } | null } | null;
+ /** A business list prompt's description (or title when description is absent). */
+ listMessage?: { description?: string | null; title?: string | null } | null;
/** A poll's question; the wire bumps the content key across versions, all carry `name`. */
pollCreationMessage?: { name?: string | null } | null;
pollCreationMessageV2?: { name?: string | null } | null;
@@ -97,6 +105,8 @@ export interface BaileysBodyContent {
/** The user tapping a business message button: which visible label they pressed. */
buttonsResponseMessage?: { selectedDisplayText?: string | null } | null;
templateButtonReplyMessage?: { selectedDisplayText?: string | null } | null;
+ /** The user picking a row from a business list message. */
+ listResponseMessage?: { title?: string | null } | null;
/** A single shared contact card. */
contactMessage?: { vcard?: string | null } | null;
/** Several contact cards shared together; each carries its own vCard. */
@@ -117,11 +127,11 @@ export interface BaileysBodyContent {
* response) whose text was previously dropped — the OTP/verification text businesses send via these
* shapes (#562), then the text-shaped non-conversation content whose display text whatsapp-web.js
* already exposes as `body` and Baileys used to drop silently: a poll's question, a shared event's
- * name, which button label the user tapped, and a shared contact card's vCard(s). Multiple vCards
- * from a `contactsArrayMessage` are newline-joined; RFC 6350 allows concatenated vCards in one
- * stream, so this is a single valid multi-card body, not string mangling. Returns `''` when the
- * message carries no extractable text. Pass the NORMALIZED content (ephemeral/viewOnce/
- * documentWithCaption wrappers already unwrapped), as the adapter does.
+ * name, which button label the user tapped, a list row's title, and a shared contact card's
+ * vCard(s). Multiple vCards from a `contactsArrayMessage` are newline-joined; RFC 6350 allows
+ * concatenated vCards in one stream, so this is a single valid multi-card body, not string mangling.
+ * Returns `''` when the message carries no extractable text. Pass the NORMALIZED content
+ * (ephemeral/viewOnce/documentWithCaption wrappers already unwrapped), as the adapter does.
*/
export function extractBaileysBody(content: BaileysBodyContent): string {
return (
@@ -135,12 +145,15 @@ export function extractBaileysBody(content: BaileysBodyContent): string {
content.templateMessage?.hydratedTemplate?.hydratedContentText ??
content.templateMessage?.hydratedFourRowTemplate?.hydratedContentText ??
content.interactiveResponseMessage?.body?.text ??
+ content.listMessage?.description ??
+ content.listMessage?.title ??
content.pollCreationMessage?.name ??
content.pollCreationMessageV2?.name ??
content.pollCreationMessageV3?.name ??
content.eventMessage?.name ??
content.buttonsResponseMessage?.selectedDisplayText ??
content.templateButtonReplyMessage?.selectedDisplayText ??
+ content.listResponseMessage?.title ??
content.contactMessage?.vcard ??
extractContactsArrayVcards(content.contactsArrayMessage) ??
content.orderMessage?.message ??
@@ -225,6 +238,404 @@ export function extractBaileysCommerce(
return {};
}
+/**
+ * The inbound message-content subset the button-reply extractor reads. Declared structurally, as
+ * {@link BaileysBodyContent} is.
+ */
+export interface BaileysButtonReplyContent {
+ buttonsResponseMessage?: {
+ selectedButtonId?: string | null;
+ selectedDisplayText?: string | null;
+ } | null;
+ templateButtonReplyMessage?: {
+ selectedId?: string | null;
+ selectedDisplayText?: string | null;
+ } | null;
+ listResponseMessage?: {
+ title?: string | null;
+ singleSelectReply?: { selectedRowId?: string | null } | null;
+ } | null;
+ interactiveResponseMessage?: {
+ body?: { text?: string | null } | null;
+ nativeFlowResponseMessage?: {
+ name?: string | null;
+ paramsJson?: string | null;
+ } | null;
+ } | null;
+}
+
+/**
+ * Extract the stable id (and visible label) when the sender tapped a business button, template
+ * quick-reply, list row, or native-flow control. Returns `undefined` when the content is not a
+ * reply shape, or when WhatsApp omitted the id a caller would act on. Pass the NORMALIZED content,
+ * as the adapter does — a reply in a disappearing chat nests under `ephemeralMessage`.
+ */
+export function extractBaileysButtonReply(
+ content: BaileysButtonReplyContent,
+ contentType: string | undefined,
+): IncomingMessage['button'] {
+ if (contentType === 'buttonsResponseMessage') {
+ const id = content.buttonsResponseMessage?.selectedButtonId;
+ if (!id) {
+ return undefined;
+ }
+ return {
+ id,
+ text: content.buttonsResponseMessage?.selectedDisplayText ?? undefined,
+ };
+ }
+
+ if (contentType === 'templateButtonReplyMessage') {
+ const id = content.templateButtonReplyMessage?.selectedId;
+ if (!id) {
+ return undefined;
+ }
+ return {
+ id,
+ text: content.templateButtonReplyMessage?.selectedDisplayText ?? undefined,
+ };
+ }
+
+ if (contentType === 'listResponseMessage') {
+ const id = content.listResponseMessage?.singleSelectReply?.selectedRowId;
+ if (!id) {
+ return undefined;
+ }
+ return {
+ id,
+ text: content.listResponseMessage?.title ?? undefined,
+ };
+ }
+
+ if (contentType === 'interactiveResponseMessage') {
+ const flow = content.interactiveResponseMessage?.nativeFlowResponseMessage;
+ // Replies must carry a stable id — a display-text-only params payload is not actionable.
+ const fromParams = parseNativeFlowButtonParams(flow?.paramsJson, { requireId: true });
+ if (fromParams) {
+ return fromParams;
+ }
+ // Some clients echo only the body text without a native-flow params payload; without an id the
+ // reply is not actionable, so leave `button` unset and keep the text in `body`.
+ return undefined;
+ }
+
+ return undefined;
+}
+
+/**
+ * The inbound message-content subset the prompt-buttons extractor reads. Declared structurally, as
+ * {@link BaileysBodyContent} is.
+ */
+export interface BaileysButtonsPromptContent {
+ buttonsMessage?: {
+ buttons?: Array<{
+ buttonId?: string | null;
+ buttonText?: { displayText?: string | null } | null;
+ } | null> | null;
+ } | null;
+ interactiveMessage?: {
+ nativeFlowMessage?: {
+ buttons?: Array<{
+ name?: string | null;
+ buttonParamsJson?: string | null;
+ } | null> | null;
+ } | null;
+ } | null;
+ templateMessage?: {
+ hydratedTemplate?: {
+ hydratedButtons?: Array<{
+ quickReplyButton?: { id?: string | null; displayText?: string | null } | null;
+ urlButton?: { url?: string | null; displayText?: string | null } | null;
+ callButton?: { phoneNumber?: string | null; displayText?: string | null } | null;
+ } | null> | null;
+ } | null;
+ hydratedFourRowTemplate?: {
+ hydratedButtons?: Array<{
+ quickReplyButton?: { id?: string | null; displayText?: string | null } | null;
+ urlButton?: { url?: string | null; displayText?: string | null } | null;
+ callButton?: { phoneNumber?: string | null; displayText?: string | null } | null;
+ } | null> | null;
+ } | null;
+ } | null;
+ listMessage?: {
+ sections?: Array<{
+ rows?: Array<{
+ rowId?: string | null;
+ title?: string | null;
+ } | null> | null;
+ } | null> | null;
+ } | null;
+}
+
+/**
+ * Extract the choices offered by an inbound business prompt (buttons / native-flow quick replies /
+ * template hydrated buttons / list rows). Returns `undefined` when the content is not a prompt
+ * shape or carries no usable choices. Pass the NORMALIZED content, as the adapter does.
+ */
+export function extractBaileysButtons(
+ content: BaileysButtonsPromptContent,
+ contentType: string | undefined,
+): IncomingMessage['buttons'] {
+ if (contentType === 'buttonsMessage') {
+ return collectButtons(
+ (content.buttonsMessage?.buttons ?? []).map(button => {
+ const text = button?.buttonText?.displayText?.trim();
+ if (!text) return undefined;
+ const id = button?.buttonId?.trim() || text;
+ return { id, text };
+ }),
+ );
+ }
+
+ if (contentType === 'interactiveMessage') {
+ return collectButtons(
+ (content.interactiveMessage?.nativeFlowMessage?.buttons ?? []).map(button => {
+ const parsed = parseNativeFlowButtonParams(button?.buttonParamsJson);
+ if (!parsed) return undefined;
+ const text = (parsed.text ?? parsed.id).trim();
+ if (!text) return undefined;
+ return { id: parsed.id.trim() || text, text };
+ }),
+ );
+ }
+
+ if (contentType === 'templateMessage') {
+ const hydrated =
+ content.templateMessage?.hydratedTemplate?.hydratedButtons ??
+ content.templateMessage?.hydratedFourRowTemplate?.hydratedButtons ??
+ [];
+ return collectButtons(
+ hydrated.map(entry => {
+ const quick = entry?.quickReplyButton;
+ if (quick?.displayText?.trim()) {
+ const text = quick.displayText.trim();
+ return { id: quick.id?.trim() || text, text };
+ }
+ const url = entry?.urlButton;
+ if (url?.displayText?.trim()) {
+ const text = url.displayText.trim();
+ return { id: url.url?.trim() || text, text };
+ }
+ const call = entry?.callButton;
+ if (call?.displayText?.trim()) {
+ const text = call.displayText.trim();
+ return { id: call.phoneNumber?.trim() || text, text };
+ }
+ return undefined;
+ }),
+ );
+ }
+
+ if (contentType === 'listMessage') {
+ const rows = (content.listMessage?.sections ?? []).flatMap(section => section?.rows ?? []);
+ return collectButtons(
+ rows.map(row => {
+ const text = row?.title?.trim();
+ if (!text) return undefined;
+ return { id: row?.rowId?.trim() || text, text };
+ }),
+ );
+ }
+
+ return undefined;
+}
+
+function collectButtons(
+ entries: Array<{ id: string; text: string } | undefined>,
+): IncomingMessage['buttons'] {
+ const buttons = entries.filter((entry): entry is { id: string; text: string } => entry != null);
+ return buttons.length > 0 ? buttons : undefined;
+}
+
+const BUTTON_PROMPT_CONTENT_TYPES = new Set([
+ 'buttonsMessage',
+ 'templateMessage',
+ 'listMessage',
+ 'interactiveMessage',
+]);
+
+export type BaileysButtonClickError = 'not_a_prompt' | 'unknown_button';
+
+/**
+ * The proto `IMessage` fragment a button-click send relays, plus the resolved visible label.
+ * Declared structurally so it stays unit-testable without importing WAProto.
+ */
+export interface BaileysButtonClickPayload {
+ id: string;
+ text: string;
+ /** Index into template hydrated buttons when the prompt is a template; otherwise 0. */
+ index: number;
+ message: Record<string, unknown>;
+}
+
+/**
+ * Resolve a click against a stored business prompt: validate the content type and button id, fill
+ * in the display text when the caller omitted it, and build the response proto WhatsApp expects for
+ * that prompt shape. CTA url/call entries are not clickable — only quick-reply style choices and
+ * list rows.
+ */
+export function resolveBaileysButtonClick(
+ content: BaileysButtonsPromptContent,
+ contentType: string | undefined,
+ buttonId: string,
+ text?: string,
+): { ok: true; payload: BaileysButtonClickPayload } | { ok: false; error: BaileysButtonClickError } {
+ if (!contentType || !BUTTON_PROMPT_CONTENT_TYPES.has(contentType)) {
+ return { ok: false, error: 'not_a_prompt' };
+ }
+
+ const choices = extractBaileysClickableButtons(content, contentType);
+ if (!choices || choices.length === 0) {
+ return { ok: false, error: 'not_a_prompt' };
+ }
+
+ const trimmedId = buttonId.trim();
+ const matchIndex = choices.findIndex(choice => choice.id === trimmedId);
+ if (matchIndex < 0) {
+ return { ok: false, error: 'unknown_button' };
+ }
+
+ const match = choices[matchIndex];
+ const resolvedText = (text?.trim() || match.text || trimmedId).trim();
+ const payload: BaileysButtonClickPayload = {
+ id: trimmedId,
+ text: resolvedText,
+ index: matchIndex,
+ message: buildBaileysButtonClickMessage(contentType, trimmedId, resolvedText, matchIndex),
+ };
+ return { ok: true, payload };
+}
+
+/**
+ * Choices that can be answered with a structured reply proto. URL/call CTAs are excluded — the
+ * WhatsApp client opens them locally and there is no reply shape to fake.
+ */
+export function extractBaileysClickableButtons(
+ content: BaileysButtonsPromptContent,
+ contentType: string | undefined,
+): IncomingMessage['buttons'] {
+ if (contentType === 'interactiveMessage') {
+ return collectButtons(
+ (content.interactiveMessage?.nativeFlowMessage?.buttons ?? []).map(button => {
+ const name = button?.name ?? 'quick_reply';
+ if (name !== 'quick_reply' && name !== 'button_click') {
+ return undefined;
+ }
+ const parsed = parseNativeFlowButtonParams(button?.buttonParamsJson);
+ if (!parsed) return undefined;
+ const label = (parsed.text ?? parsed.id).trim();
+ if (!label) return undefined;
+ return { id: parsed.id.trim() || label, text: label };
+ }),
+ );
+ }
+
+ if (contentType === 'templateMessage') {
+ const hydrated =
+ content.templateMessage?.hydratedTemplate?.hydratedButtons ??
+ content.templateMessage?.hydratedFourRowTemplate?.hydratedButtons ??
+ [];
+ return collectButtons(
+ hydrated.map(entry => {
+ const quick = entry?.quickReplyButton;
+ if (!quick?.displayText?.trim()) return undefined;
+ const label = quick.displayText.trim();
+ return { id: quick.id?.trim() || label, text: label };
+ }),
+ );
+ }
+
+ return extractBaileysButtons(content, contentType);
+}
+
+function buildBaileysButtonClickMessage(
+ contentType: string,
+ buttonId: string,
+ text: string,
+ index: number,
+): Record<string, unknown> {
+ switch (contentType) {
+ case 'buttonsMessage':
+ return {
+ buttonsResponseMessage: {
+ selectedButtonId: buttonId,
+ selectedDisplayText: text,
+ type: 1, // DISPLAY_TEXT / RESPONSE — wire enum member
+ },
+ };
+ case 'listMessage':
+ return {
+ listResponseMessage: {
+ title: text,
+ listType: 1, // SINGLE_SELECT
+ singleSelectReply: { selectedRowId: buttonId },
+ },
+ };
+ case 'templateMessage':
+ return {
+ templateButtonReplyMessage: {
+ selectedId: buttonId,
+ selectedDisplayText: text,
+ selectedIndex: index,
+ },
+ };
+ case 'interactiveMessage':
+ default:
+ // Quick-reply taps commonly arrive as templateButtonReplyMessage on modern clients.
+ return {
+ templateButtonReplyMessage: {
+ selectedId: buttonId,
+ selectedDisplayText: text,
+ selectedIndex: index,
+ },
+ };
+ }
+}
+
+/**
+ * Reads `id` / `button_id` (and optional display text) out of a native-flow `paramsJson` /
+ * `buttonParamsJson` string. Returns `undefined` when the JSON is absent, malformed, or carries
+ * neither an id nor a visible label. Pass `requireId: true` for reply parsing so a display-text-only
+ * payload does not become a synthetic id.
+ */
+function parseNativeFlowButtonParams(
+ paramsJson: string | null | undefined,
+ opts?: { requireId?: boolean },
+): IncomingMessage['button'] {
+ if (!paramsJson) {
+ return undefined;
+ }
+ try {
+ const params = JSON.parse(paramsJson) as Record<string, unknown>;
+ const text = pickNonEmptyString(params, ['display_text', 'displayText', 'title']);
+ const id = pickNonEmptyString(params, ['id', 'button_id', 'buttonId']);
+ if (id) {
+ return { id, text: text ?? undefined };
+ }
+ if (opts?.requireId) {
+ return undefined;
+ }
+ // Prompt buttons sometimes carry only the visible label in paramsJson.
+ if (text) {
+ return { id: text, text };
+ }
+ return undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+
+function pickNonEmptyString(obj: Record<string, unknown>, keys: string[]): string | undefined {
+ for (const key of keys) {
+ const value = obj[key];
+ if (typeof value === 'string' && value.length > 0) {
+ return value;
+ }
+ }
+ return undefined;
+}
+
/**
* A catalog share arrives as a `productMessage` too, carrying the `catalog` arm instead of
* `product` (there is no `catalogMessage` content type). It names a whole catalog and carries no
@@ -305,6 +716,12 @@ export interface BaileysContextContent {
documentMessage?: BaileysContextCarrier | null;
stickerMessage?: BaileysContextCarrier | null;
locationMessage?: BaileysContextCarrier | null;
+ // Interactive replies carry `contextInfo` on their own sub-message (the original prompt they
+ // answer), so the quote/mentions/timer extractors must look there too.
+ buttonsResponseMessage?: BaileysContextCarrier | null;
+ templateButtonReplyMessage?: BaileysContextCarrier | null;
+ listResponseMessage?: BaileysContextCarrier | null;
+ interactiveResponseMessage?: BaileysContextCarrier | null;
}
/** Everything the context region of an inbound message yields — not just the quote. */
@@ -336,7 +753,11 @@ export function extractBaileysContext(content: BaileysContextContent): BaileysMe
content.audioMessage ??
content.documentMessage ??
content.stickerMessage ??
- content.locationMessage;
+ content.locationMessage ??
+ content.buttonsResponseMessage ??
+ content.templateButtonReplyMessage ??
+ content.listResponseMessage ??
+ content.interactiveResponseMessage;
// A text status's styling rides on the extended-text content (proto backgroundArgb/font) —
// surface it so the store/viewer can render the story the way it was posted.
const extText = content.extendedTextMessage;
@@ -414,6 +835,10 @@ export interface BaileysIncomingFields {
/** Pre-extracted commerce ids. Populated by the adapter for `orderMessage` / `productMessage`. */
order?: IncomingMessage['order'];
product?: IncomingMessage['product'];
+ /** Pre-extracted button/list reply. Populated by the adapter when the user tapped a control. */
+ button?: IncomingMessage['button'];
+ /** Pre-extracted prompt choices. Populated by the adapter for business button/list prompts. */
+ buttons?: IncomingMessage['buttons'];
/** A `productMessage` that shares the whole catalog rather than one product — see `isBaileysCatalogShare`. */
isCatalogShare?: boolean;
/** Ephemeral/disappearing-messages timer from `contextInfo.expiration` on the Baileys message. */
@@ -450,7 +875,9 @@ export function buildIncomingMessageFromBaileys(
from: fields.fromMe ? self : chatId,
to: fields.fromMe ? chatId : self,
chatId,
- body: fields.body,
+ // Native-flow replies sometimes put the visible label only in paramsJson (surfaced on `button`),
+ // not in `interactiveResponseMessage.body` — prefer an explicit body, else the button label.
+ body: fields.body || fields.button?.text || '',
type: mapBaileysMessageType(fields.contentType, fields.isPtt, fields.isCatalogShare),
timestamp: fields.timestamp,
fromMe: fields.fromMe,
@@ -510,6 +937,14 @@ export function buildIncomingMessageFromBaileys(
: fields.product;
}
+ if (fields.button) {
+ incoming.button = fields.button;
+ }
+
+ if (fields.buttons) {
+ incoming.buttons = fields.buttons;
+ }
+
// Ephemeral/disappearing-messages timer, when the chat has one set.
if (fields.ephemeralDuration && fields.ephemeralDuration > 0) {
incoming.ephemeralDuration = fields.ephemeralDuration;
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index f352f2357..99f4b1ca3 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -17,6 +17,7 @@ import {
} from '../interfaces/whatsapp-engine.interface';
import { toEngineParticipants } from './baileys-groups';
import { buildVCard } from './vcard';
+import { resolveBaileysButtonClick } from './baileys-message-mapper';
import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';
import { BadRequestException, InternalServerErrorException } from '@nestjs/common';
import { EngineRefusedError } from '../../common/errors/engine-refused.error';
@@ -475,6 +476,66 @@ export class BaileysMessaging {
return this.sendContent(chatId, { text, ...this.withMentions(mentions) }, { quoted });
}
+ /**
+ * Send a structured button/list reply against a stored business prompt. Relays the response proto
+ * (official Baileys has no buttonReply helper) quoted to the prompt message.
+ */
+ async clickButton(chatId: string, messageId: string, buttonId: string, text?: string): Promise<MessageResult> {
+ this.host.ensureReady();
+ const quoted = await this.requireStored(messageId);
+ this.assertStoredInChat(quoted, chatId, messageId);
+
+ const b = await this.host.loadLib();
+ const normalized = b.normalizeMessageContent(quoted.message ?? undefined) ?? quoted.message ?? {};
+ const contentType = b.getContentType(normalized);
+ const resolved = resolveBaileysButtonClick(normalized, contentType, buttonId, text);
+ if (!resolved.ok) {
+ if (resolved.error === 'unknown_button') {
+ throw new BadRequestException(
+ `buttonId "${buttonId}" is not among the clickable choices on message ${messageId}`,
+ );
+ }
+ throw new BadRequestException(
+ `message ${messageId} is not a WhatsApp Business button/list prompt that can be clicked`,
+ );
+ }
+
+ const jid = await this.toDeliverableJid(chatId);
+ const generated = b.generateWAMessageFromContent(
+ jid,
+ // Structural builder — cast at the relay boundary onto Baileys' proto.IMessage.
+ resolved.payload.message as Parameters<typeof b.generateWAMessageFromContent>[1],
+ {
+ quoted,
+ // MessageGenerationOptionsFromContent requires userJid: string (not optional).
+ userJid: this.host.normalizedSelfJid() || jid,
+ },
+ );
+ if (!generated?.message || !generated.key?.id) {
+ throw new InternalServerErrorException('Failed to build button-click message');
+ }
+
+ await this.sock().relayMessage(jid, generated.message, { messageId: generated.key.id });
+
+ // Stamp fromMe so the store / own-send echo treat this like any other API send.
+ const sent: WAMessage = {
+ ...generated,
+ key: { ...generated.key, fromMe: true, remoteJid: jid },
+ messageTimestamp: generated.messageTimestamp ?? Math.floor(Date.now() / 1000),
+ };
+ void this.host.putStoredMessage(sent)?.catch(err =>
+ this.host.logger.warn('Failed to persist button-click message to store', {
+ error: err instanceof Error ? err.message : String(err),
+ }),
+ );
+ void this.emitOwnSendEcho(sent);
+
+ return {
+ id: sent.key.id ?? '',
+ timestamp: this.host.toUnixSeconds(sent.messageTimestamp),
+ };
+ }
+
async forwardMessage(fromChatId: string, toChatId: string, messageId: string): Promise<MessageResult> {
this.host.ensureReady();
const forward = await this.requireStored(messageId);
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 84268c1f9..b768e7c6c 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -348,6 +348,10 @@ export class BaileysAdapter implements IWhatsAppEngine {
return this.messaging.unpinMessage(chatId, messageId);
}
+ async clickButton(chatId: string, messageId: string, buttonId: string, text?: string): Promise<MessageResult> {
+ return this.messaging.clickButton(chatId, messageId, buttonId, text);
+ }
+
async editMessage(chatId: string, messageId: string, body: string, mentions?: string[]): Promise<MessageResult> {
return this.messaging.editMessage(chatId, messageId, body, mentions);
}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 8442ffdb3..1694ee095 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -731,6 +731,15 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
return this.messaging.votePoll(chatId, pollMessageId, options);
}
+ clickButton(
+ _chatId: string,
+ _messageId: string,
+ _buttonId: string,
+ _text?: string,
+ ): Promise<MessageResult> {
+ throw new EngineNotSupportedError('clickButton');
+ }
+
unpinMessage(chatId: string, messageId: string): Promise<void> {
return this.messaging.unpinMessage(chatId, messageId);
}
diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.ts
index 8b3dc93b9..ac165ed25 100644
--- a/src/engine/engine-capability-matrix.ts
+++ b/src/engine/engine-capability-matrix.ts
@@ -418,6 +418,12 @@ export const CURATED_CAPABILITY_EXCEPTIONS: Record<string, MethodCapability> = {
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/process-message.d.ts), so sending needs a hand-built proto.Message.PollUpdateMessage with HMAC-SHA256 vote encryption keyed by the poll creation's messageSecret",
},
+ clickButton: {
+ wwjs: { status: 'not-available', rootCause: 'library-limitation' },
+ baileys: { status: 'supported' },
+ evidence:
+ 'wwjs has no interactive button-reply send path; baileys relays a buttonsResponseMessage / templateButtonReplyMessage / listResponseMessage / interactiveResponseMessage via generateWAMessageFromContent + relayMessage, quoting the stored prompt',
+ },
unpinMessage: {
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 6cd6b39d5..b757a0437 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -136,6 +136,25 @@ export interface IncomingMessage {
description?: string;
businessOwnerJid?: string;
};
+ /**
+ * Set when the sender tapped a WhatsApp Business button, template quick-reply, list row, or
+ * native-flow control. `id` is the stable handle the business defined on the button/row; `text`
+ * is the visible label when WhatsApp still carries it (also mirrored into `body`). **Baileys
+ * only** — whatsapp-web.js does not surface interactive replies as structured fields.
+ */
+ button?: {
+ id: string;
+ text?: string;
+ };
+ /**
+ * Set on an inbound WhatsApp Business prompt that offers buttons (or list rows flattened as
+ * buttons): the choices shown to the recipient. Distinct from {@link IncomingMessage.button},
+ * which is set only when someone *taps* a choice. **Baileys only.**
+ */
+ buttons?: Array<{
+ id: string;
+ text: string;
+ }>;
/**
* Set by the adapter when the sender is identified by a privacy id (e.g. a WhatsApp `@lid`) rather
* than a phone number, so engine-neutral code can decide whether to attempt phone resolution without
@@ -1026,6 +1045,18 @@ export interface MessageOperationsCapability {
*/
votePoll(chatId: string, pollMessageId: string, options: string[]): Promise<void>;
+ /**
+ * Reply to a WhatsApp Business button / list prompt as if the account tapped a choice.
+ * `buttonId` is the stable id from the prompt (see inbound `buttons[].id`); `text` is the visible
+ * label when known. **Baileys only** — whatsapp-web.js has no interactive-reply send path.
+ *
+ * The prompt must already be in the engine message store (received while the session was live).
+ * This sends a structured response proto quoted to that message; it is not a native UI click and
+ * WhatsApp may reject or treat it differently from a phone tap. URL/call CTA buttons are not
+ * clickable this way — only quick-reply style choices and list rows.
+ */
+ clickButton(chatId: string, messageId: string, buttonId: string, text?: string): Promise<MessageResult>;
+
/**
* 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 e02a487a2..a0f9e69df 100644
--- a/src/modules/message/dto/message-actions.dto.ts
+++ b/src/modules/message/dto/message-actions.dto.ts
@@ -287,6 +287,35 @@ export class VotePollDto {
options!: string[];
}
+export class ClickButtonDto {
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ chatId!: string;
+
+ @ApiProperty({ description: 'WhatsApp id of the business prompt message that offered the buttons.' })
+ @IsString()
+ @IsNotEmpty()
+ messageId!: string;
+
+ @ApiProperty({
+ description:
+ 'Stable id of the choice to tap (inbound `buttons[].id`). URL/call CTA buttons cannot be clicked this way.',
+ })
+ @IsString()
+ @IsNotEmpty()
+ buttonId!: string;
+
+ @ApiPropertyOptional({
+ description:
+ 'Visible label of the choice. When omitted, resolved from the stored prompt; falls back to buttonId.',
+ })
+ @IsOptional()
+ @IsString()
+ @IsNotEmpty()
+ text?: string;
+}
+
export class StarMessageDto {
@ApiProperty()
@IsString()
diff --git a/src/modules/message/message-send.service.ts b/src/modules/message/message-send.service.ts
index 5ec0cdb10..c13e82004 100644
--- a/src/modules/message/message-send.service.ts
+++ b/src/modules/message/message-send.service.ts
@@ -516,6 +516,32 @@ export class MessageSendService {
return this.persistSentState(message, result);
}
+ async clickButton(
+ sessionId: string,
+ dto: { chatId: string; messageId: string; buttonId: string; text?: string },
+ ): Promise<MessageResponseDto> {
+ const finalDto = await this.applySendingGate(sessionId, 'click-button', dto);
+ const engine = this.getEngine(sessionId);
+
+ const message = await this.saveOutgoingMessage(sessionId, {
+ chatId: finalDto.chatId,
+ body: finalDto.text || finalDto.buttonId,
+ type: 'text',
+ metadata: {
+ quotedMessage: { id: finalDto.messageId, body: '' },
+ button: { id: finalDto.buttonId, text: finalDto.text },
+ },
+ });
+
+ let result: MessageResult;
+ try {
+ result = await engine.clickButton(finalDto.chatId, finalDto.messageId, finalDto.buttonId, finalDto.text);
+ } catch (error) {
+ return this.failSend(sessionId, 'click-button', message, finalDto, error);
+ }
+ return this.persistSentState(message, result);
+ }
+
async forward(
sessionId: string,
dto: { fromChatId: string; toChatId: string; messageId: string },
diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.ts
index fdbf99498..44b3336f3 100644
--- a/src/modules/message/message.controller.ts
+++ b/src/modules/message/message.controller.ts
@@ -43,6 +43,7 @@ import {
PinMessageDto,
StarMessageDto,
VotePollDto,
+ ClickButtonDto,
UnpinMessageDto,
} from './dto/message-actions.dto';
import { RequireRole } from '../auth/decorators/auth.decorators';
@@ -359,6 +360,36 @@ export class MessageController {
return this.messageService.reply(sessionId, dto);
}
+ @Post('click-button')
+ @RequireRole(ApiKeyRole.OPERATOR)
+ @ApiOperation({
+ summary: 'Click a button on a WhatsApp Business prompt (Baileys only)',
+ description:
+ 'Sends a structured button/list reply quoted to a previously received prompt. Not a native UI ' +
+ 'tap — WhatsApp may reject or treat it differently. whatsapp-web.js returns 501. URL/call CTA ' +
+ 'buttons cannot be clicked this way.',
+ })
+ @ApiParam({ name: 'sessionId', description: 'Session ID' })
+ @ApiResponse({
+ status: 201,
+ description: 'Button reply sent',
+ type: MessageResponseDto,
+ })
+ @ApiResponse({
+ status: 400,
+ description: 'Session not active, prompt is not clickable, or buttonId is not among its choices',
+ })
+ @ApiResponse({ status: 404, description: MESSAGE_NOT_FOUND_404 })
+ @ApiResponse({ status: 501, description: ENGINE_NOT_SUPPORTED_501 })
+ @ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
+ @ApiResponse({ status: 400, description: RECIPIENT_UNREACHABLE_400 })
+ async clickButton(
+ @Param('sessionId') sessionId: string,
+ @Body() dto: ClickButtonDto,
+ ): Promise<MessageResponseDto> {
+ return this.messageService.clickButton(sessionId, dto);
+ }
+
@Post('forward')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Forward a message to another chat' })
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index 9ade97427..690952173 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -5,7 +5,7 @@ import { EngineRegistry } from '../../engine/engine-registry.service';
import { MessageProjector } from '../session/message-projector.service';
import { SendTextMessageDto, SendMediaMessageDto, SendAudioMessageDto, MessageResponseDto } from './dto';
import { SendTemplateMessageDto } from './dto/send-template.dto';
-import { ReplyMessageDto } from './dto/message-actions.dto';
+import { ReplyMessageDto, ClickButtonDto } from './dto/message-actions.dto';
import { Message, MessageDirection } from './entities/message.entity';
import { HookManager, applySendingGate } from '../../core/hooks';
import { SendPacingService } from './send-pacing.service';
@@ -239,6 +239,10 @@ export class MessageService implements PluginMessagePort {
return this.sender.reply(sessionId, dto);
}
+ clickButton(sessionId: string, dto: ClickButtonDto): Promise<MessageResponseDto> {
+ return this.sender.clickButton(sessionId, dto);
+ }
+
forward(
sessionId: string,
dto: { fromChatId: string; toChatId: string; messageId: string },
diff --git a/test/__mocks__/@whiskeysockets/baileys.ts b/test/__mocks__/@whiskeysockets/baileys.ts
index 310f9492e..e9edf8537 100644
--- a/test/__mocks__/@whiskeysockets/baileys.ts
+++ b/test/__mocks__/@whiskeysockets/baileys.ts
@@ -13,6 +13,8 @@ export default jest.fn();
export const useMultiFileAuthState = jest.fn();
export const fetchLatestBaileysVersion = jest.fn();
export const getContentType = jest.fn();
+export const normalizeMessageContent = jest.fn((c: unknown) => c);
+export const generateWAMessageFromContent = jest.fn();
export const DisconnectReason = { loggedOut: 401 };
/**