Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(messages): pin and unpin messages on both engines

Yudhi Armyndharis558f48d0092a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dbad45d86..c79b43189 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Messages can be pinned and unpinned, on both engines:** `POST /api/sessions/:sessionId/messages/pin`
+ and `.../messages/unpin`. `durationSeconds` is `86400` (24h, the default), `604800` (7d) or
+ `2592000` (30d) — WhatsApp recognises no others, so anything else is a `400` here rather than a
+ silent no-op at the engine. In a group only admins may pin; that refusal surfaces as `403`, and a
+ message the engine cannot locate as `404`. Available in all five SDKs as `messages.pin` /
+ `messages.unpin`.
+
+ Nothing is stored locally: a pin is chat state owned by WhatsApp and expires on its clock, so a
+ mirrored copy in the message row would go stale silently. As with react/delete/edit, the target
+ must be within whatsapp-web.js's 100-message fetch window for the chat, or in the Baileys
+ adapter's message store.
+
- **Chat media can now be archived to the file store and fetched back after delivery, via
`GET /api/sessions/:sessionId/messages/:chatId/:messageId/media`.** Media has always been
persisted as base64 inline on the message row, which makes it part of every row read and ties its
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 798e7603f..0c799d451 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -926,6 +926,44 @@ Returns a bare array of `MessageReaction`:
**Errors:** `400` session not active · `401` missing/invalid API key · `500` engine error
+#### POST /api/sessions/:sessionId/messages/pin
+
+Pin a message in its chat for a bounded window.
+
+**Auth:** API key (OPERATOR)
+
+**Body**
+
+| Field | Type | Required | Description |
+| --- | --- | --- | --- |
+| chatId | string | yes | Chat containing the message |
+| messageId | string | yes | Message to pin |
+| durationSeconds | number | no | `86400` (24h), `604800` (7d) or `2592000` (30d). Defaults to `86400`. Any other value is rejected with `400` — WhatsApp recognises no others. |
+
+**Response** `200` — `{ "success": true }`
+
+**Errors:** `400` session not active, or `durationSeconds` outside the three accepted values · `401` missing/invalid API key · `403` the engine refused the pin (in a group only admins may pin) · `404` message not found in the chat
+
+> On whatsapp-web.js the message must be within the 100-message fetch window for the chat, the same
+> limit that applies to react/delete/edit. On Baileys it must be in the adapter's message store.
+
+#### POST /api/sessions/:sessionId/messages/unpin
+
+Remove a message's pin. Takes no duration.
+
+**Auth:** API key (OPERATOR)
+
+**Body**
+
+| Field | Type | Required | Description |
+| --- | --- | --- | --- |
+| chatId | string | yes | Chat containing the message |
+| messageId | string | yes | Message to unpin |
+
+**Response** `200` — `{ "success": true }`
+
+**Errors:** `400` session not active · `401` missing/invalid API key · `403` the engine refused the unpin (in a group only admins may unpin) · `404` message not found in the chat
+
#### GET /api/sessions/:sessionId/messages/:chatId/:messageId/media
Download a message's **archived** media bytes.
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 5738f5474..0dd1db8bc 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -255,6 +255,24 @@ curl "$BASE/api/sessions/$SESSION_ID/messages/[email protected]/true_62812345678
-H "X-API-Key: $API_KEY"
```
+#### POST /api/sessions/:sessionId/messages/pin
+
+Pin a message for 24h (default), 7d or 30d.
+
+```bash
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/pin" \
+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
+ -d '{"chatId":"[email protected]","messageId":"[email protected]_3EB0ABCD","durationSeconds":604800}'
+```
+
+#### POST /api/sessions/:sessionId/messages/unpin
+
+```bash
+curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/unpin" \
+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
+ -d '{"chatId":"[email protected]","messageId":"[email protected]_3EB0ABCD"}'
+```
+
#### GET /api/sessions/:sessionId/messages/:chatId/:messageId/media
Download a message's archived media. Requires `CHAT_MEDIA_ARCHIVE_ENABLED=true` to have been set
diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.md
index d7c6ad222..493772eb7 100644
--- a/docs/18-sdk-design.md
+++ b/docs/18-sdk-design.md
@@ -29,7 +29,7 @@ All five SDKs expose the same fluent surface:
| Resource | Methods |
| --- | --- |
| `sessions` | list, get, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, stats |
-| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, sendBulk, batchStatus, cancelBatch |
+| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, sendBulk, batchStatus, cancelBatch |
| `contacts` | list, get, check, profilePicture, profilePictures, phone, block, unblock |
| `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, getGroupSettings, updateGroupSettings, leave, inviteCode, revokeInviteCode |
| `webhooks` | list, get, create, update, delete, test |
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index cf038741c..6cfd16efb 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -164,7 +164,18 @@ These are honestly out of reach of a clean adapter wiring because the installed
## Snapshot summary
-- **80** interface methods, **160** adapter-cells (80 × 2 engines).
-- **139** supported cells; **21** not-available cells across **16** methods.
-- Of the 21 not-available cells: **6 adapter-gaps** (fixable) + **15 library-limitations** + **0 uncertain**.
-- **0 phantom-support rows** — every `not-available` row now throws at the adapter boundary, so the drift gate's throw-heuristic covers the full matrix.
+These are hand-maintained and had drifted from the source before this pass; they are now recomputed
+from `engine-capability-matrix.ts` rather than adjusted by hand. Re-derive them the same way when
+adding a method, instead of incrementing the previous figure.
+
+- **82** interface methods, **164** adapter-cells (82 × 2 engines).
+- **147** supported cells; **17** not-available cells across **16** methods.
+- Of the 17 not-available cells: **2 adapter-gaps** (fixable) + **15 library-limitations** + **0 uncertain**.
+- **0 phantom-support rows** — every `not-available` row throws at the adapter boundary.
+
+ Note that the drift gate does **not** verify that for whatsapp-web.js. `engine-parity.spec.ts`
+ detects a throw with `Class.prototype.method.toString()`, and the wwjs adapter's methods are thin
+ forwarders whose throws live in delegate modules (`wwebjs-catalog.ts` and friends), so the scan
+ sees no throwing method on that adapter at all — its `supported ⇒ does not throw` invariant is
+ vacuously true. Baileys is unaffected: its unavailable methods call `this.unsupported(...)` inline
+ on the adapter. Until that is addressed, the wwjs column is guarded by review, not by the gate.
diff --git a/openapi.json b/openapi.json
index 51ff603f7..9f501e6ac 100644
--- a/openapi.json
+++ b/openapi.json
@@ -2145,6 +2145,94 @@
]
}
},
+ "/api/sessions/{sessionId}/messages/pin": {
+ "post": {
+ "operationId": "MessageController_pinMessage",
+ "parameters": [
+ {
+ "name": "sessionId",
+ "required": true,
+ "in": "path",
+ "description": "Session ID",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PinMessageDto"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Message pinned"
+ },
+ "400": {
+ "description": "Session not active, or durationSeconds is not one of 86400 / 604800 / 2592000"
+ },
+ "403": {
+ "description": "The engine refused the pin — in a group only admins may pin"
+ },
+ "404": {
+ "description": "Message not found in the chat"
+ }
+ },
+ "summary": "Pin a message in its chat",
+ "tags": [
+ "messages"
+ ]
+ }
+ },
+ "/api/sessions/{sessionId}/messages/unpin": {
+ "post": {
+ "operationId": "MessageController_unpinMessage",
+ "parameters": [
+ {
+ "name": "sessionId",
+ "required": true,
+ "in": "path",
+ "description": "Session ID",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UnpinMessageDto"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Message unpinned"
+ },
+ "400": {
+ "description": "Session not active"
+ },
+ "403": {
+ "description": "The engine refused the unpin — in a group only admins may unpin"
+ },
+ "404": {
+ "description": "Message not found in the chat"
+ }
+ },
+ "summary": "Remove a message’s pin",
+ "tags": [
+ "messages"
+ ]
+ }
+ },
"/api/sessions/{sessionId}/messages/edit": {
"post": {
"operationId": "MessageController_edit",
@@ -7114,6 +7202,46 @@
"messageId"
]
},
+ "PinMessageDto": {
+ "type": "object",
+ "properties": {
+ "chatId": {
+ "type": "string"
+ },
+ "messageId": {
+ "type": "string"
+ },
+ "durationSeconds": {
+ "type": "number",
+ "description": "Pin duration in seconds: 86400 (24h), 604800 (7d) or 2592000 (30d). Defaults to 24h.",
+ "enum": [
+ 86400,
+ 604800,
+ 2592000
+ ],
+ "default": 86400
+ }
+ },
+ "required": [
+ "chatId",
+ "messageId"
+ ]
+ },
+ "UnpinMessageDto": {
+ "type": "object",
+ "properties": {
+ "chatId": {
+ "type": "string"
+ },
+ "messageId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "chatId",
+ "messageId"
+ ]
+ },
"EditMessageDto": {
"type": "object",
"properties": {
diff --git a/sdk/README.md b/sdk/README.md
index 6faf03eaa..f7f520fc8 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -25,7 +25,7 @@ All five SDKs expose the same fluent resource surface:
| Resource | Methods |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sessions` | list, get, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, stats |
-| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, sendBulk, batchStatus, cancelBatch |
+| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, sendBulk, batchStatus, cancelBatch |
| `contacts` | list, get, check, profilePicture, profilePictures, phone, block, unblock |
| `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, get/updateGroupSettings, leave, inviteCode, revokeInviteCode |
| `webhooks` | list, get, create, update, delete, test |
diff --git a/sdk/go/messages.go b/sdk/go/messages.go
index bd77e12cb..e831c064c 100644
--- a/sdk/go/messages.go
+++ b/sdk/go/messages.go
@@ -137,6 +137,24 @@ func (s *MessagesService) Reactions(ctx context.Context, sessionID, chatID, mess
return out, err
}
+// Pin pins a message in its chat for a bounded window.
+func (s *MessagesService) Pin(ctx context.Context, sessionID string, body PinMessageRequest) (*SuccessResult, error) {
+ var out SuccessResult
+ if err := s.client.do(ctx, "POST", s.base(sessionID)+"/pin", nil, body, &out); err != nil {
+ return nil, err
+ }
+ return &out, nil
+}
+
+// Unpin removes a message's pin.
+func (s *MessagesService) Unpin(ctx context.Context, sessionID string, body UnpinMessageRequest) (*SuccessResult, error) {
+ var out SuccessResult
+ if err := s.client.do(ctx, "POST", s.base(sessionID)+"/unpin", nil, body, &out); err != nil {
+ return nil, err
+ }
+ return &out, nil
+}
+
// Media fetches a message's archived media bytes. The server answers 404 when
// nothing is archived for the message (archiving off when it arrived, no media,
// over the archive cap, or cleared by retention).
diff --git a/sdk/go/routing_test.go b/sdk/go/routing_test.go
index 1813d57e1..644602542 100644
--- a/sdk/go/routing_test.go
+++ b/sdk/go/routing_test.go
@@ -91,6 +91,8 @@ func TestRouting(t *testing.T) {
{"Status.List", func(c *Client) { c.Status.List(ctx, "s1") }, "GET", "/api/sessions/s1/status"},
{"Status.FromContact", func(c *Client) { c.Status.FromContact(ctx, "s1", "u1") }, "GET", "/api/sessions/s1/status/u1"},
+ {"Messages.Pin", func(c *Client) { c.Messages.Pin(ctx, "s1", PinMessageRequest{}) }, "POST", "/api/sessions/s1/messages/pin"},
+ {"Messages.Unpin", func(c *Client) { c.Messages.Unpin(ctx, "s1", UnpinMessageRequest{}) }, "POST", "/api/sessions/s1/messages/unpin"},
{"Messages.Media", func(c *Client) { c.Messages.Media(ctx, "s1", "c1", "m1") }, "GET", "/api/sessions/s1/messages/c1/m1/media"},
{"Status.Media", func(c *Client) { c.Status.Media(ctx, "s1", "st1") }, "GET", "/api/sessions/s1/status/st1/media"},
{"Status.SendText", func(c *Client) { c.Status.SendText(ctx, "s1", SendTextStatusRequest{}) }, "POST", "/api/sessions/s1/status/send-text"},
diff --git a/sdk/go/types_message.go b/sdk/go/types_message.go
index f7610d83a..277e6e925 100644
--- a/sdk/go/types_message.go
+++ b/sdk/go/types_message.go
@@ -326,3 +326,17 @@ type MessageMedia struct {
Data []byte
ContentType string
}
+
+// PinMessageRequest pins a message in its chat. DurationSeconds must be 86400
+// (24h), 604800 (7d) or 2592000 (30d); omit it to take the server default of 24h.
+type PinMessageRequest struct {
+ ChatID string `json:"chatId"`
+ MessageID string `json:"messageId"`
+ DurationSeconds int `json:"durationSeconds,omitempty"`
+}
+
+// UnpinMessageRequest removes a message's pin.
+type UnpinMessageRequest struct {
+ ChatID string `json:"chatId"`
+ MessageID string `json:"messageId"`
+}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/PinMessageRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/PinMessageRequest.java
new file mode 100644
index 000000000..1ef8b4de2
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/PinMessageRequest.java
@@ -0,0 +1,34 @@
+package com.rmyndharis.openwa.model;
+
+/** Request body for pinning a message in its chat. */
+public record PinMessageRequest(String chatId, String messageId, Integer durationSeconds) {
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static final class Builder {
+ private String chatId;
+ private String messageId;
+ private Integer durationSeconds;
+
+ public Builder chatId(String v) {
+ this.chatId = v;
+ return this;
+ }
+
+ public Builder messageId(String v) {
+ this.messageId = v;
+ return this;
+ }
+
+ /** 86400 (24h), 604800 (7d) or 2592000 (30d). Defaults to 24h when omitted. */
+ public Builder durationSeconds(Integer v) {
+ this.durationSeconds = v;
+ return this;
+ }
+
+ public PinMessageRequest build() {
+ return new PinMessageRequest(chatId, messageId, durationSeconds);
+ }
+ }
+}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/UnpinMessageRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/UnpinMessageRequest.java
new file mode 100644
index 000000000..a31f127e2
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/UnpinMessageRequest.java
@@ -0,0 +1,27 @@
+package com.rmyndharis.openwa.model;
+
+/** Request body for removing a message's pin. */
+public record UnpinMessageRequest(String chatId, String messageId) {
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static final class Builder {
+ private String chatId;
+ private String messageId;
+
+ public Builder chatId(String v) {
+ this.chatId = v;
+ return this;
+ }
+
+ public Builder messageId(String v) {
+ this.messageId = v;
+ return this;
+ }
+
+ public UnpinMessageRequest build() {
+ return new UnpinMessageRequest(chatId, messageId);
+ }
+ }
+}
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 03bb39b9c..1059063b6 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
@@ -15,6 +15,7 @@ import com.rmyndharis.openwa.model.ListMessagesQuery;
import com.rmyndharis.openwa.model.MessageHistoryQuery;
import com.rmyndharis.openwa.model.MessageListResponse;
import com.rmyndharis.openwa.model.MessageResponse;
+import com.rmyndharis.openwa.model.PinMessageRequest;
import com.rmyndharis.openwa.model.ReactMessageRequest;
import com.rmyndharis.openwa.model.ReactionRecord;
import com.rmyndharis.openwa.model.ReplyMessageRequest;
@@ -27,6 +28,7 @@ import com.rmyndharis.openwa.model.SendPollRequest;
import com.rmyndharis.openwa.model.SendTemplateRequest;
import com.rmyndharis.openwa.model.SendTextRequest;
import com.rmyndharis.openwa.model.SuccessResult;
+import com.rmyndharis.openwa.model.UnpinMessageRequest;
import java.util.List;
/**
@@ -156,6 +158,29 @@ public final class MessagesResource {
SuccessResult.class);
}
+ /**
+ * Pin a message in its chat. durationSeconds must be 86400 (24h), 604800 (7d) or 2592000 (30d);
+ * omit it for the server default of 24h. In a group only admins may pin.
+ */
+ public SuccessResult pin(String sessionId, PinMessageRequest body) {
+ return client.request(
+ HttpMethod.POST,
+ "/api/sessions/" + encodeSegment(sessionId) + "/messages/pin",
+ null,
+ body,
+ SuccessResult.class);
+ }
+
+ /** Remove a message's pin. */
+ public SuccessResult unpin(String sessionId, UnpinMessageRequest body) {
+ return client.request(
+ HttpMethod.POST,
+ "/api/sessions/" + encodeSegment(sessionId) + "/messages/unpin",
+ null,
+ body,
+ SuccessResult.class);
+ }
+
/** Edit the text of a message sent by this account. 404 when the message is not found. */
public MessageResponse editMessage(String sessionId, EditMessageRequest 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 803584218..813e51a43 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
@@ -16,6 +16,7 @@ import com.rmyndharis.openwa.model.EditMessageRequest;
import com.rmyndharis.openwa.model.ForwardMessageRequest;
import com.rmyndharis.openwa.model.ListMessagesQuery;
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.SendBulkRequest;
@@ -26,6 +27,7 @@ import com.rmyndharis.openwa.model.SendAudioRequest;
import com.rmyndharis.openwa.model.SendPollRequest;
import com.rmyndharis.openwa.model.SendTemplateRequest;
import com.rmyndharis.openwa.model.SendTextRequest;
+import com.rmyndharis.openwa.model.UnpinMessageRequest;
import com.rmyndharis.openwa.support.MockTransport;
import java.nio.charset.StandardCharsets;
import java.util.List;
@@ -278,4 +280,17 @@ class MessagesResourceTest {
assertArrayEquals("PNG_BYTES".getBytes(StandardCharsets.UTF_8), media.data());
assertEquals("image/png", media.contentType());
}
+
+ @Test
+ void pinAndUnpinPostToTheirRoutes() {
+ tx.respond(200, "{\"success\":true}");
+ client.messages.pin("s", PinMessageRequest.builder().chatId("c1").messageId("m1").build());
+ assertEquals("http://h/api/sessions/s/messages/pin", tx.lastRequest().url());
+ assertEquals(HttpMethod.POST, tx.lastRequest().method());
+
+ tx.respond(200, "{\"success\":true}");
+ client.messages.unpin("s", UnpinMessageRequest.builder().chatId("c1").messageId("m1").build());
+ assertEquals("http://h/api/sessions/s/messages/unpin", tx.lastRequest().url());
+ assertEquals(HttpMethod.POST, tx.lastRequest().method());
+ }
}
diff --git a/sdk/javascript/src/resources/messages.ts b/sdk/javascript/src/resources/messages.ts
index 2b4abd877..5423210ae 100644
--- a/sdk/javascript/src/resources/messages.ts
+++ b/sdk/javascript/src/resources/messages.ts
@@ -20,6 +20,7 @@ import type {
MessageHistoryQuery,
MessageListResponse,
MessageResponse,
+ PinMessageRequest,
ReactionRecord,
ReactMessageRequest,
ReplyMessageRequest,
@@ -28,6 +29,7 @@ import type {
SendLocationRequest,
SendAudioRequest,
SendMediaRequest,
+ UnpinMessageRequest,
SendPollRequest,
SendTemplateRequest,
SendTextRequest,
@@ -178,6 +180,27 @@ export class MessagesResource {
});
}
+ /**
+ * Pin a message in its chat. `durationSeconds` must be 86400 (24h), 604800 (7d) or 2592000
+ * (30d); it defaults to 24h server-side. In a group only admins may pin.
+ */
+ pin(sessionId: string, body: PinMessageRequest): Promise<SuccessResult> {
+ return this.client.request<SuccessResult>({
+ method: 'POST',
+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/pin`,
+ body,
+ });
+ }
+
+ /** Remove a message's pin. */
+ unpin(sessionId: string, body: UnpinMessageRequest): Promise<SuccessResult> {
+ return this.client.request<SuccessResult>({
+ method: 'POST',
+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/unpin`,
+ body,
+ });
+ }
+
/**
* Fetch a message's archived media bytes. Requires chat-media archiving to have been enabled on
* the gateway when the message arrived; 404 otherwise.
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index e8e7f84eb..8246f1c23 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -178,6 +178,21 @@ export interface DeleteMessageRequest {
forEveryone?: boolean;
}
+/** Pin windows WhatsApp recognises, in seconds: 24h, 7d, 30d. */
+export type PinDurationSeconds = 86400 | 604800 | 2592000;
+
+export interface PinMessageRequest {
+ chatId: Jid;
+ messageId: string;
+ /** Defaults to 86400 (24h) server-side. */
+ durationSeconds?: PinDurationSeconds;
+}
+
+export interface UnpinMessageRequest {
+ chatId: Jid;
+ messageId: string;
+}
+
export interface EditMessageRequest {
chatId: Jid;
messageId: string;
diff --git a/sdk/javascript/test/resources.test.ts b/sdk/javascript/test/resources.test.ts
index 95937c553..84485b277 100644
--- a/sdk/javascript/test/resources.test.ts
+++ b/sdk/javascript/test/resources.test.ts
@@ -215,6 +215,16 @@ describe('StatusResource — nested media bodies', () => {
expect(t.lastCall!.body).toEqual({ video: { url: 'http://vid' }, recipients: ['[email protected]'] });
});
+ it('pin and unpin post to their own routes', async () => {
+ const t = new MockTransport().on('POST', /\/messages\/(un)?pin$/, { body: { success: true } });
+ const c = client(t);
+ await c.messages.pin('s', { chatId: 'c1', messageId: 'm1', durationSeconds: 604800 });
+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/messages/pin');
+ expect(t.lastCall!.body).toEqual({ chatId: 'c1', messageId: 'm1', durationSeconds: 604800 });
+ await c.messages.unpin('s', { chatId: 'c1', messageId: 'm1' });
+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/messages/unpin');
+ });
+
it('message media fetches the archived bytes with their content type', async () => {
const t = new MockTransport().on('GET', /\/messages\/c1\/m1\/media$/, {
text: 'PNG_BYTES',
diff --git a/sdk/php/src/Resources/MessagesResource.php b/sdk/php/src/Resources/MessagesResource.php
index 3b52dab6d..7dcf58f34 100644
--- a/sdk/php/src/Resources/MessagesResource.php
+++ b/sdk/php/src/Resources/MessagesResource.php
@@ -163,6 +163,27 @@ class MessagesResource
return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/{$this->http->encodeSegment($chatId)}/{$this->http->encodeSegment($messageId)}/reactions") ?? [];
}
+ /**
+ * Pin a message in its chat.
+ *
+ * @param array<string,mixed> $body chatId, messageId and an optional durationSeconds of
+ * 86400 (24h), 604800 (7d) or 2592000 (30d); defaults to 24h.
+ * @return array<string,mixed>
+ */
+ public function pin(string $sessionId, array $body): array
+ {
+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/pin", [], $body) ?? [];
+ }
+
+ /**
+ * @param array<string,mixed> $body
+ * @return array<string,mixed>
+ */
+ public function unpin(string $sessionId, array $body): array
+ {
+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/unpin", [], $body) ?? [];
+ }
+
/**
* Fetch a message's archived media bytes (404 when nothing is archived for it).
*
diff --git a/sdk/php/tests/ResourcesTest.php b/sdk/php/tests/ResourcesTest.php
index f57bc387c..42a6e337c 100644
--- a/sdk/php/tests/ResourcesTest.php
+++ b/sdk/php/tests/ResourcesTest.php
@@ -256,6 +256,20 @@ class ResourcesTest extends TestCase
$this->assertSame(['video' => ['url' => 'http://vid'], 'recipients' => ['[email protected]']], $backend->lastCall()['body']);
}
+ public function testPinAndUnpinPostToTheirRoutes(): void
+ {
+ $backend = new MockBackend();
+ // Queue responses in CALL order: pin, unpin.
+ $backend->on(200, ['success' => true]);
+ $backend->on(200, ['success' => true]);
+ $client = $backend->makeClient();
+ $client->messages->pin('s', ['chatId' => 'c1', 'messageId' => 'm1', 'durationSeconds' => 604800]);
+ $this->assertSame('/api/sessions/s/messages/pin', $backend->lastCall()['path']);
+ $this->assertSame('POST', $backend->lastCall()['method']);
+ $client->messages->unpin('s', ['chatId' => 'c1', 'messageId' => 'm1']);
+ $this->assertSame('/api/sessions/s/messages/unpin', $backend->lastCall()['path']);
+ }
+
public function testMessageMediaReturnsArchivedBytes(): void
{
$backend = (new MockBackend())->onRaw(200, 'PNG_BYTES', ['Content-Type' => 'image/png']);
diff --git a/sdk/python/openwa/resources/messages.py b/sdk/python/openwa/resources/messages.py
index 642cce1fe..3e521d5a3 100644
--- a/sdk/python/openwa/resources/messages.py
+++ b/sdk/python/openwa/resources/messages.py
@@ -11,6 +11,8 @@ from typing import TYPE_CHECKING
from .._http import quote_segment
from ..types import (
MessageMedia,
+ PinMessageRequest,
+ UnpinMessageRequest,
BatchStatusResponse,
BulkMessageResponse,
ChatHistoryMessage,
@@ -108,6 +110,13 @@ class MessagesResource:
"GET", f"/api/sessions/{quote_segment(session_id)}/messages/{quote_segment(chat_id)}/{quote_segment(message_id)}/reactions"
)
+ def pin(self, session_id: str, body: PinMessageRequest) -> SuccessResult:
+ """Pin a message. ``durationSeconds`` must be 86400, 604800 or 2592000; defaults to 24h."""
+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/pin", body=body)
+
+ def unpin(self, session_id: str, body: UnpinMessageRequest) -> SuccessResult:
+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/unpin", body=body)
+
def media(self, session_id: str, chat_id: str, message_id: str) -> MessageMedia:
"""Fetch a message's archived media bytes (404 when nothing is archived for it)."""
data, content_type = self._http.request_bytes(
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index d35f23e79..e496ddd71 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -630,6 +630,19 @@ class StatusMedia(TypedDict):
contentType: str | None
+class PinMessageRequest(TypedDict, total=False):
+ """Pin a message. ``durationSeconds`` is 86400 (24h), 604800 (7d) or 2592000 (30d)."""
+
+ chatId: str
+ messageId: str
+ durationSeconds: int
+
+
+class UnpinMessageRequest(TypedDict):
+ chatId: str
+ messageId: str
+
+
class MessageMedia(TypedDict):
"""A message's archived media file: raw bytes plus the served content type."""
diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py
index eb05f026e..cf91c14c1 100644
--- a/sdk/python/tests/test_sdk.py
+++ b/sdk/python/tests/test_sdk.py
@@ -497,6 +497,16 @@ class TestStatus:
client.status.send_video("s", {"video": {"url": "http://vid"}, "recipients": ["[email protected]"]})
assert backend.calls[-1].body == {"video": {"url": "http://vid"}, "recipients": ["[email protected]"]}
+ def test_pin_and_unpin_post_to_their_routes(self):
+ backend = MockBackend().on("POST", "/messages/pin", body={"success": True})
+ backend.on("POST", "/messages/unpin", body={"success": True})
+ client = make_client(backend)
+ client.messages.pin("s", {"chatId": "c1", "messageId": "m1", "durationSeconds": 604800})
+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s/messages/pin"
+ assert backend.last_call.method == "POST"
+ client.messages.unpin("s", {"chatId": "c1", "messageId": "m1"})
+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s/messages/unpin"
+
def test_message_media_fetches_archived_bytes(self):
backend = MockBackend()
backend.fallback = lambda _: httpx.Response(200, content=b"PNG_BYTES", headers={"content-type": "image/png"})
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index 78a7231e9..0db1dfd4c 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -1,5 +1,7 @@
import type * as BaileysLib from '@whiskeysockets/baileys';
import type { AnyMessageContent, MiscMessageGenerationOptions, WAMessage, WASocket } from '@whiskeysockets/baileys';
+// Runtime (not type-only): the pin message type is a wire-format enum value, not just a type.
+import { proto } from '@whiskeysockets/baileys';
import {
ChatState,
ContactCard,
@@ -406,4 +408,27 @@ export class BaileysMessaging {
}
return found;
}
+
+ /**
+ * Pin/unpin a message IN THE CHAT. Deliberately not `chatModify({pin})` — that pins the chat
+ * itself in the chat list, a different feature that happens to share the word.
+ */
+ async pinMessage(chatId: string, messageId: string, durationSeconds: number): Promise<void> {
+ this.host.ensureReady();
+ const target = await this.requireStored(messageId);
+ await this.sock().sendMessage(chatId, {
+ pin: target.key,
+ type: proto.PinInChat.Type.PIN_FOR_ALL,
+ // WhatsApp recognises only these three windows; the DTO rejects anything else before we
+ // get here, so the cast documents the contract rather than widening it.
+ time: durationSeconds as 86400 | 604800 | 2592000,
+ });
+ }
+
+ async unpinMessage(chatId: string, messageId: string): Promise<void> {
+ this.host.ensureReady();
+ const target = await this.requireStored(messageId);
+ // `time` is meaningless for an unpin and is omitted rather than sent as a dummy value.
+ await this.sock().sendMessage(chatId, { pin: target.key, type: proto.PinInChat.Type.UNPIN_FOR_ALL });
+ }
}
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 966104bc2..6215d5b7b 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -104,6 +104,8 @@ jest.mock('@whiskeysockets/baileys', () => ({
Type: { REVOKE: 0, MESSAGE_EDIT: 14 },
},
},
+ // namespace proto.PinInChat { enum Type } — WAProto/index.d.ts:10355-10361
+ PinInChat: { Type: { UNKNOWN_TYPE: 0, PIN_FOR_ALL: 1, UNPIN_FOR_ALL: 2 } },
},
}));
@@ -2503,6 +2505,38 @@ describe('BaileysAdapter store-backed ops', () => {
});
});
+ it('pinMessage pins IN CHAT via the stored key, with the requested window', async () => {
+ fakeStore.getMessage.mockResolvedValue(stored);
+ const adapter = await ready();
+ await adapter.pinMessage('[email protected]', 'TARGET', 604800);
+ // PIN_FOR_ALL (1) on a sendMessage — NOT chatModify({pin}), which pins the CHAT in the chat
+ // list. The two are entirely different features that happen to share the word "pin".
+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {
+ pin: stored.key,
+ type: 1,
+ time: 604800,
+ });
+ expect(fakeSock.chatModify).not.toHaveBeenCalled();
+ });
+
+ it('unpinMessage sends UNPIN_FOR_ALL and omits the meaningless duration', async () => {
+ fakeStore.getMessage.mockResolvedValue(stored);
+ const adapter = await ready();
+ await adapter.unpinMessage('[email protected]', 'TARGET');
+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {
+ pin: stored.key,
+ type: 2,
+ });
+ });
+
+ it('pinMessage 404s when the message is not in the store', async () => {
+ fakeStore.getMessage.mockResolvedValue(undefined);
+ const adapter = await ready();
+ await expect(adapter.pinMessage('[email protected]', 'GONE', 86400)).rejects.toBeInstanceOf(
+ MessageNotFoundError,
+ );
+ });
+
it('deleteMessage revokes via the stored key', async () => {
fakeStore.getMessage.mockResolvedValue(stored);
const adapter = await ready();
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 8c15ee8f5..130b01011 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -338,6 +338,14 @@ export class BaileysAdapter implements IWhatsAppEngine {
return this.messaging.deleteMessage(chatId, messageId, forEveryone);
}
+ async pinMessage(chatId: string, messageId: string, durationSeconds: number): Promise<void> {
+ return this.messaging.pinMessage(chatId, messageId, durationSeconds);
+ }
+
+ async unpinMessage(chatId: string, messageId: string): Promise<void> {
+ return this.messaging.unpinMessage(chatId, messageId);
+ }
+
async editMessage(chatId: string, messageId: string, body: string): Promise<MessageResult> {
return this.messaging.editMessage(chatId, messageId, body);
}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index dfb63f56a..4e710a0f6 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -3532,6 +3532,65 @@ describe('editMessage', () => {
});
});
+describe('pinMessage / unpinMessage', () => {
+ const ready = (client: unknown): WhatsAppWebJsAdapter => {
+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });
+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.READY;
+ (adapter as unknown as { client: unknown }).client = client;
+ return adapter;
+ };
+ const chatWith = (messages: unknown[]) => ({
+ getChatById: jest.fn().mockResolvedValue({ fetchMessages: jest.fn().mockResolvedValue(messages) }),
+ });
+
+ it('pins a message found by _serialized id, passing the duration through', async () => {
+ const pin = jest.fn().mockResolvedValue(true);
+ const adapter = ready(chatWith([{ id: { _serialized: 'M1', id: 'RAW1' }, pin }]));
+ await adapter.pinMessage('[email protected]', 'M1', 604800);
+ expect(pin).toHaveBeenCalledWith(604800);
+ });
+
+ it('also matches the bare id.id fallback (like deleteMessage)', async () => {
+ const pin = jest.fn().mockResolvedValue(true);
+ const adapter = ready(chatWith([{ id: { _serialized: '[email protected]_RAW1', id: 'RAW1' }, pin }]));
+ await adapter.pinMessage('[email protected]', 'RAW1', 86400);
+ expect(pin).toHaveBeenCalledWith(86400);
+ });
+
+ it('treats a false pin result as a refusal (EngineRefusedError, 403), not a phantom success', async () => {
+ // The page-side helper returns false for every refusal — non-admin, unresolvable message, or a
+ // duration WhatsApp will not accept — so a truthiness check is the ONLY signal there is.
+ const pin = jest.fn().mockResolvedValue(false);
+ const adapter = ready(chatWith([{ id: { _serialized: 'M1' }, pin }]));
+ const err = await adapter.pinMessage('[email protected]', 'M1', 86400).catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(EngineRefusedError);
+ expect((err as Error).message).toMatch(/was rejected/);
+ });
+
+ it('throws MessageNotFoundError when the message is outside the fetch window', async () => {
+ const adapter = ready(chatWith([]));
+ await expect(adapter.pinMessage('[email protected]', 'GONE', 86400)).rejects.toBeInstanceOf(MessageNotFoundError);
+ });
+
+ it('throws MessageNotFoundError when the chat id itself is unknown (getChatById resolves undefined)', async () => {
+ const adapter = ready({ getChatById: jest.fn().mockResolvedValue(undefined) });
+ await expect(adapter.pinMessage('[email protected]', 'M1', 86400)).rejects.toBeInstanceOf(MessageNotFoundError);
+ });
+
+ it('unpins without passing any duration', async () => {
+ const unpin = jest.fn().mockResolvedValue(true);
+ const adapter = ready(chatWith([{ id: { _serialized: 'M1' }, unpin }]));
+ await adapter.unpinMessage('[email protected]', 'M1');
+ expect(unpin).toHaveBeenCalledWith();
+ });
+
+ it('treats a false unpin result as a refusal too', async () => {
+ const unpin = jest.fn().mockResolvedValue(false);
+ const adapter = ready(chatWith([{ id: { _serialized: 'M1' }, unpin }]));
+ await expect(adapter.unpinMessage('[email protected]', 'M1')).rejects.toBeInstanceOf(EngineRefusedError);
+ });
+});
+
describe('LID mapping persistence to LidMappingStore (#583 R3)', () => {
const readyWithStore = (client: unknown, lidMappingStore: unknown): WhatsAppWebJsAdapter => {
const adapter = new WhatsAppWebJsAdapter({
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 030f64031..13bf6eea5 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -1433,6 +1433,14 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
}
// Delete Message
+ pinMessage(chatId: string, messageId: string, durationSeconds: number): Promise<void> {
+ return this.messaging.pinMessage(chatId, messageId, durationSeconds);
+ }
+
+ unpinMessage(chatId: string, messageId: string): Promise<void> {
+ return this.messaging.unpinMessage(chatId, messageId);
+ }
+
deleteMessage(chatId: string, messageId: string, forEveryone: boolean = true): Promise<void> {
return this.messaging.deleteMessage(chatId, messageId, forEveryone);
}
diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.ts
index e39b843da..3208cc369 100644
--- a/src/engine/adapters/wwebjs-messaging.ts
+++ b/src/engine/adapters/wwebjs-messaging.ts
@@ -655,4 +655,48 @@ export class WwebjsMessaging {
this.host.logger.log(`Edited message ${messageId} in chat ${chatId}`);
return toMessageResult(edited);
}
+
+ /**
+ * Locate a message in the 100-message fetch window shared by react/delete/edit — and now pin.
+ * Deliberately NOT applied to the existing call sites: they differ in whether they tolerate an
+ * unknown chat, and rewriting them is not this change's business.
+ *
+ * As with those sites, chatId is NOT lid-resolved: the pin acts on the found message's own key,
+ * so resolving would only risk missing a message stored under the pre-migration @c.us chat.
+ */
+ private async findInFetchWindow(chatId: string, messageId: string): Promise<Message> {
+ const chat = await this.client().getChatById(chatId);
+ // getChatById RESOLVES undefined for an unknown chat rather than throwing, which is the same
+ // client-facing outcome as a message outside the window — a 404, not a TypeError-driven 500.
+ if (!chat) throw new MessageNotFoundError(messageId, chatId);
+ const messages = await chat.fetchMessages({ limit: 100 });
+ const message = messages.find(m => m.id._serialized === messageId || m.id.id === messageId);
+ if (!message) throw new MessageNotFoundError(messageId, chatId);
+ return message;
+ }
+
+ async pinMessage(chatId: string, messageId: string, durationSeconds: number): Promise<void> {
+ this.host.ensureReady();
+ const message = await this.findInFetchWindow(chatId, messageId);
+ // The page-side helper returns false rather than throwing for every refusal — a non-number
+ // duration, a message it cannot resolve, or a send WhatsApp rejected (Injected/Utils.js:1670).
+ // Surface that as a refusal instead of reporting a pin that never happened.
+ if (!(await message.pin(durationSeconds))) {
+ throw new EngineRefusedError(
+ `the pin of message ${messageId} was rejected — in a group only admins may pin, and the duration must be 24h, 7d or 30d`,
+ );
+ }
+ this.host.logger.log(`Pinned message ${messageId} in chat ${chatId} for ${durationSeconds}s`);
+ }
+
+ async unpinMessage(chatId: string, messageId: string): Promise<void> {
+ this.host.ensureReady();
+ const message = await this.findInFetchWindow(chatId, messageId);
+ // unpin() passes duration 0 itself, so the injected non-number guard cannot bite here; a false
+ // return means WhatsApp refused the unpin (e.g. not an admin).
+ if (!(await message.unpin())) {
+ throw new EngineRefusedError(`the unpin of message ${messageId} was rejected — in a group only admins may unpin`);
+ }
+ this.host.logger.log(`Unpinned message ${messageId} in chat ${chatId}`);
+ }
}
diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.ts
index b4d9ca6c9..b1fa10f89 100644
--- a/src/engine/engine-capability-matrix.ts
+++ b/src/engine/engine-capability-matrix.ts
@@ -178,6 +178,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {
leaveGroup: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
logout: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
markUnread: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
+ pinMessage: {
+ wwjs: { status: 'supported' },
+ baileys: { status: 'supported' },
+ evidence:
+ 'wwjs Message.pin(duration) → boolean (index.d.ts:1340); the injected helper returns false for a non-number duration and for an unknown message (Injected/Utils.js:1670-1696), so the adapter maps false → EngineRefusedError; baileys sendMessage(jid,{pin:key,type:PinInChat.Type.PIN_FOR_ALL,time}) (Types/Message.d.ts:196-201) — NOT chatModify({pin}), which pins the CHAT in the chat list',
+ },
postImageStatus: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
postTextStatus: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
postVideoStatus: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
@@ -283,6 +289,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {
"wwjs Client.subscribeToChannel(channelId) → boolean (index.d.ts:71; Client.js:2533) takes a CHANNEL id, not the interface's invite code, and getChannelByInviteCode(inviteCode) (index.d.ts:103; Client.js:1707) is the invite→channel bridge — the adapter used to pass the invite code straight in and fabricate a Channel from the returned boolean; now an honest EngineNotSupportedError pending a verified two-step wiring; baileys newsletterMetadata('invite', code) + newsletterFollow (Socket/newsletter.d.ts)",
},
unblockContact: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
+ unpinMessage: {
+ wwjs: { status: 'supported' },
+ baileys: { status: 'supported' },
+ evidence:
+ 'wwjs Message.unpin() → boolean (index.d.ts:1342); it passes duration 0 explicitly (Message.js:738-742), so the injected non-number guard does not bite — false → EngineRefusedError; baileys sendMessage(jid,{pin:key,type:PinInChat.Type.UNPIN_FOR_ALL}) — `time` is ignored when unpinning',
+ },
unsubscribeFromChannel: {
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 ef1a50041..4f7b5bacc 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -694,6 +694,15 @@ export interface IWhatsAppEngine {
* non-text or foreign messages at their own layer — the engine's error is surfaced as-is.
*/
editMessage(chatId: string, messageId: string, body: 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
+ * required rather than defaulted here so neither adapter has to invent a value. In a group only
+ * admins may pin; the engines surface their own refusal.
+ */
+ pinMessage(chatId: string, messageId: string, durationSeconds: number): Promise<void>;
+ /** Remove a message's pin. Unpinning takes no duration — an existing pin's window is irrelevant. */
+ unpinMessage(chatId: string, messageId: string): Promise<void>;
/**
* Read a chat's recent messages, newest first. When `includeMedia` downloads blobs, an optional
* `mediaMaxBytes` tightens the declared-size pre-gate below the global MEDIA_DOWNLOAD_MAX_BYTES —
diff --git a/src/modules/message/dto/message-actions.dto.ts b/src/modules/message/dto/message-actions.dto.ts
index 6a4aed8c7..20d53a2f1 100644
--- a/src/modules/message/dto/message-actions.dto.ts
+++ b/src/modules/message/dto/message-actions.dto.ts
@@ -10,6 +10,7 @@ import {
ArrayMinSize,
ArrayMaxSize,
MaxLength,
+ IsIn,
} from 'class-validator';
import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-boolean';
import { MESSAGE_TEXT_MAX_LENGTH } from './send-message.dto';
@@ -191,6 +192,50 @@ export class DeleteMessageDto {
forEveryone?: boolean;
}
+/**
+ * The only pin windows WhatsApp recognises, in seconds. Anything else is rejected page-side by
+ * whatsapp-web.js (a silent `false`) and is not representable in the Baileys pin payload, so it is
+ * refused here with a 400 rather than turned into an engine-level mystery.
+ */
+export const PIN_DURATIONS_SECONDS = [86400, 604800, 2592000] as const;
+
+export class PinMessageDto {
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ chatId: string;
+
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ messageId: string;
+
+ @ApiPropertyOptional({
+ description: 'Pin duration in seconds: 86400 (24h), 604800 (7d) or 2592000 (30d). Defaults to 24h.',
+ enum: PIN_DURATIONS_SECONDS,
+ default: 86400,
+ })
+ // Strict conversion for the same reason as DeleteMessageDto.forEveryone: under the pipe's
+ // implicit conversion a non-numeric string would arrive as NaN and slip past IsIn as a
+ // "different" value rather than being rejected outright.
+ @ToStrictNumber()
+ @IsOptional()
+ @IsIn(PIN_DURATIONS_SECONDS)
+ durationSeconds?: number;
+}
+
+export class UnpinMessageDto {
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ chatId: string;
+
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ messageId: string;
+}
+
export class EditMessageDto {
@ApiProperty()
@IsString()
diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.ts
index eb2420452..c1444765b 100644
--- a/src/modules/message/message.controller.ts
+++ b/src/modules/message/message.controller.ts
@@ -15,6 +15,8 @@ import {
ReactMessageDto,
DeleteMessageDto,
EditMessageDto,
+ PinMessageDto,
+ UnpinMessageDto,
} from './dto/message-actions.dto';
import { RequireRole } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
@@ -404,6 +406,40 @@ export class MessageController {
return { success: true };
}
+ // ========== Pin / Unpin ==========
+
+ @Post('pin')
+ @HttpCode(HttpStatus.OK)
+ @RequireRole(ApiKeyRole.OPERATOR)
+ @ApiOperation({ summary: 'Pin a message in its chat' })
+ @ApiParam({ name: 'sessionId', description: 'Session ID' })
+ @ApiResponse({ status: 200, description: 'Message pinned' })
+ @ApiResponse({
+ status: 400,
+ description: 'Session not active, or durationSeconds is not one of 86400 / 604800 / 2592000',
+ })
+ @ApiResponse({ status: 403, description: 'The engine refused the pin — in a group only admins may pin' })
+ @ApiResponse({ status: 404, description: 'Message not found in the chat' })
+ async pinMessage(@Param('sessionId') sessionId: string, @Body() dto: PinMessageDto): Promise<{ success: boolean }> {
+ return this.messageService.pinMessage(sessionId, dto);
+ }
+
+ @Post('unpin')
+ @HttpCode(HttpStatus.OK)
+ @RequireRole(ApiKeyRole.OPERATOR)
+ @ApiOperation({ summary: 'Remove a message’s pin' })
+ @ApiParam({ name: 'sessionId', description: 'Session ID' })
+ @ApiResponse({ status: 200, description: 'Message unpinned' })
+ @ApiResponse({ status: 400, description: 'Session not active' })
+ @ApiResponse({ status: 403, description: 'The engine refused the unpin — in a group only admins may unpin' })
+ @ApiResponse({ status: 404, description: 'Message not found in the chat' })
+ async unpinMessage(
+ @Param('sessionId') sessionId: string,
+ @Body() dto: UnpinMessageDto,
+ ): Promise<{ success: boolean }> {
+ return this.messageService.unpinMessage(sessionId, dto);
+ }
+
// ========== Edit Message ==========
@Post('edit')
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index 18d764fa8..17792262e 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -32,6 +32,8 @@ function createMockEngine() {
reactToMessage: jest.fn().mockResolvedValue(undefined),
getMessageReactions: jest.fn().mockResolvedValue([]),
deleteMessage: jest.fn().mockResolvedValue(undefined),
+ pinMessage: jest.fn().mockResolvedValue(undefined),
+ unpinMessage: jest.fn().mockResolvedValue(undefined),
editMessage: jest.fn().mockResolvedValue(mockEngineResult),
getChatHistory: jest.fn().mockResolvedValue([]),
sendChatState: jest.fn().mockResolvedValue(undefined),
@@ -1427,6 +1429,31 @@ describe('MessageService', () => {
expect(repository.delete).not.toHaveBeenCalled();
});
});
+ // ── pin / unpin ───────────────────────────────────────────────────
+
+ describe('pinMessage / unpinMessage', () => {
+ it('defaults the pin window to 24h when the caller does not choose one', async () => {
+ await service.pinMessage('sess-1', { chatId: '[email protected]', messageId: 'M1' });
+ expect(mockEngine.pinMessage).toHaveBeenCalledWith('[email protected]', 'M1', 86400);
+ });
+
+ it('passes an explicit window through untouched', async () => {
+ await service.pinMessage('sess-1', { chatId: '[email protected]', messageId: 'M1', durationSeconds: 2592000 });
+ expect(mockEngine.pinMessage).toHaveBeenCalledWith('[email protected]', 'M1', 2592000);
+ });
+
+ it('unpins without a duration', async () => {
+ await service.unpinMessage('sess-1', { chatId: '[email protected]', messageId: 'M1' });
+ expect(mockEngine.unpinMessage).toHaveBeenCalledWith('[email protected]', 'M1');
+ });
+
+ it('does not touch the stored message row — a pin is WhatsApp-owned chat state that expires', async () => {
+ (repository.update as jest.Mock).mockClear();
+ await service.pinMessage('sess-1', { chatId: '[email protected]', messageId: 'M1' });
+ expect(repository.update).not.toHaveBeenCalled();
+ });
+ });
+
// ── archived chat media (read path) ───────────────────────────────
describe('getChatMedia', () => {
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index a632f4e4b..cc20d99c7 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -34,6 +34,9 @@ export interface GetMessagesOptions {
/** Default cap on a rendered template's final text; overridable via TEMPLATE_RENDER_MAX_CHARS. */
export const DEFAULT_TEMPLATE_RENDER_MAX_CHARS = 64 * 1024;
+/** Pin window applied when the caller does not choose one — WhatsApp's own default of 24h. */
+export const DEFAULT_PIN_DURATION_SECONDS = 86400;
+
/**
* Mimetypes an archived chat-media file may be served as. Everything else — documents, and notably
* `image/svg+xml`, which is scriptable despite the `image/` prefix — is served as inert
@@ -784,6 +787,23 @@ export class MessageService {
// ========== Delete Message ==========
+ /**
+ * Pin a message for a bounded window. Nothing is persisted locally: a pin is chat state owned by
+ * WhatsApp, not a property of our message row, and it expires on WhatsApp's clock — a mirrored
+ * copy here would silently go stale.
+ */
+ async pinMessage(sessionId: string, dto: { chatId: string; messageId: string; durationSeconds?: number }) {
+ const engine = this.getEngine(sessionId);
+ await engine.pinMessage(dto.chatId, dto.messageId, dto.durationSeconds ?? DEFAULT_PIN_DURATION_SECONDS);
+ return { success: true };
+ }
+
+ async unpinMessage(sessionId: string, dto: { chatId: string; messageId: string }) {
+ const engine = this.getEngine(sessionId);
+ await engine.unpinMessage(dto.chatId, dto.messageId);
+ return { success: true };
+ }
+
async deleteMessage(
sessionId: string,
dto: { chatId: string; messageId: string; forEveryone?: boolean },
diff --git a/test/__mocks__/@whiskeysockets/baileys.ts b/test/__mocks__/@whiskeysockets/baileys.ts
index e3df0b27c..310f9492e 100644
--- a/test/__mocks__/@whiskeysockets/baileys.ts
+++ b/test/__mocks__/@whiskeysockets/baileys.ts
@@ -15,6 +15,17 @@ export const fetchLatestBaileysVersion = jest.fn();
export const getContentType = jest.fn();
export const DisconnectReason = { loggedOut: 401 };
+/**
+ * Protocol constants the adapter reads at RUNTIME (not just as types), mirrored from
+ * WAProto/index.d.ts. Values are wire-format enum members, so they are fixed by the protocol
+ * rather than by the library version — but keep them in step with the real proto if more are
+ * added here.
+ */
+export const proto = {
+ // namespace proto.PinInChat { enum Type } — WAProto/index.d.ts:10355-10361
+ PinInChat: { Type: { UNKNOWN_TYPE: 0, PIN_FOR_ALL: 1, UNPIN_FOR_ALL: 2 } },
+};
+
// Inline implementation mirrored from @whiskeysockets/baileys/lib/Utils/generics.js
// (the package is pure ESM; ts-jest runs CJS, so the mock owns the serialisation helpers)