Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(groups): set this account's member label in a group on Baileys

Yudhi Armyndharis417deea6ac19
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 84534333f..f09f9d9ea 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Add a session switcher to the dashboard Chats page that lists every session with its state, picture, push name and number, and lets only a ready one be selected. Thanks @rjsebening.
- Add a contact info panel to the dashboard chat room with the contact's picture, name, number and copyable chat id. Thanks @rjsebening.
- Add Today, Yesterday and date separators to the dashboard chat thread. Thanks @rjsebening.
+- Add `PUT /api/sessions/{sessionId}/groups/{groupId}/member-label` to set this account's member label in a group on Baileys; whatsapp-web.js answers `501` (#1918). Thanks @xwork1 for the report.
### Changed
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 1e9b4946d..7c303cbec 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -3223,6 +3223,47 @@ No `@HttpCode`; PUT default is `200`.
**Errors:** `400` validation (`description` missing / not a string) / session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role, or the engine refused (admin rights required) · `404` no such group · `409` conflict or engine not ready (retryable) · `503` session not ready or dependency unavailable (retryable); on Baileys, also when WhatsApp rate-limits or times out the request (code 429 or 408): retry after a pause
+#### PUT /api/sessions/:sessionId/groups/:groupId/member-label
+
+Set this account's own member label in the group: the per-group tag WhatsApp shows beside its name, so
+one number can carry a different label in each group. An empty string clears the label.
+
+**Auth:** API key (OPERATOR) · **Engines:** Baileys only; whatsapp-web.js returns `501`
+
+A key restricted to selected chats reaches only the groups on its list.
+
+**Path parameters**
+
+| Name | Type | Description |
+| --------- | ------ | --------------------------------------------- |
+| sessionId | string | Session ID |
+| groupId | string | Group ID (`<id>@g.us`); any other id is `400` |
+
+**Request body**: `GroupMemberLabelDto`
+
+| Field | Type | Required | Constraints | Description |
+| ----- | ------ | -------- | ------------------------------------------------------ | -------------------------------------------------------------------- |
+| label | string | Yes | `@IsString` (no `@IsNotEmpty`), ≤ 30 UTF-16 code units | Must be present and a string, but `""` is valid and clears the label |
+
+The 30 is counted in UTF-16 code units, the unit Baileys cuts the label at, so an emoji outside the
+Basic Multilingual Plane takes two of them. A longer label is refused rather than shortened.
+
+```json
+{ "label": "Site A Management" }
+```
+
+**Response** `200`
+
+The label message was handed to WhatsApp. Baileys sends it to the group as a protocol message, so
+there is no per-request confirmation, and group metadata does not carry the label, so it cannot be
+read back through this API.
+
+```json
+{ "success": true, "message": "Group member label sent" }
+```
+
+**Errors:** `400` validation (`label` missing / not a string / too long), the id does not name a group, or session not started · `401` missing/invalid `X-API-Key` · `403` key lacks OPERATOR role or the group is outside a chat-restricted key's list, or WhatsApp refused the group lookup the label message depends on (for example, the account is no longer a member) · `404` no such group · `409` conflict or engine not ready (retryable) · `501` whatsapp-web.js, which has no member-label setter · `503` WhatsApp did not answer within the request budget, so the label may or may not have been sent; on Baileys, also when WhatsApp rate-limits or times out the request (code 429 or 408): retry after a pause
+
#### POST /api/sessions/:sessionId/groups/:groupId/leave
Leave a group.
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 51a759a67..1784ff15c 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -800,6 +800,17 @@ curl -X PUT "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/descr
-d '{ "description": "Internal coordination group." }'
```
+#### PUT /api/sessions/:sessionId/groups/:groupId/member-label
+
+Set this account's member label in the group, up to 30 characters; an empty string clears it (OPERATOR, Baileys only: whatsapp-web.js answers `501`).
+
+```bash
+curl -X PUT "$BASE/api/sessions/$SESSION_ID/groups/[email protected]/member-label" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{ "label": "Site A Management" }'
+```
+
#### POST /api/sessions/:sessionId/groups/:groupId/leave
Leave a group (OPERATOR).
diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.md
index 5fabf0882..d78e148fb 100644
--- a/docs/18-sdk-design.md
+++ b/docs/18-sdk-design.md
@@ -28,24 +28,24 @@ OpenWA ships five official, hand-written client libraries for the REST API. They
All five SDKs expose the same fluent 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, clickButton, 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, joinInfo, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, getGroupSettings, updateGroupSettings, leave, getPicture, setPicture, deletePicture, inviteCode, revokeInviteCode, getMembershipRequests, approveMembershipRequests, rejectMembershipRequests |
-| `webhooks` | list, listAll, deliveryFailures, redriveDeliveryFailures, get, create, update, delete, test |
-| `chats` | list, subscribePresence, getPresence, markRead, markUnread, archive, pin, mute, clearMessages, delete, sendState |
-| `labels` | list, get, chats, upsert, delete, forChat, addToChat, removeFromChat _(WhatsApp Business)_ |
-| `channels` | list, get, messages, create, delete, mute, subscribe, unsubscribe, demoteAdmin, transferOwnership _(Newsletters)_ |
-| `catalog` | info, products, product, sendProduct _(WhatsApp Business)_ |
-| `status` | list, fromContact, media, sendText, sendImage, sendVideo, sendVoice, delete _(Stories)_ |
-| `search` | search |
-| `templates` | list, get, create, update, delete |
-| `profile` | setProfileName, setProfileStatus, setProfilePicture, deleteProfilePicture |
-| `calls` | rejectCall, createLink |
-| `media` | conversionStatus, convertVoice _(OPERATOR)_, convertVideo _(OPERATOR)_ |
-| `health` | check, live, ready |
+| 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, clickButton, 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, joinInfo, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, setMemberLabel, getGroupSettings, updateGroupSettings, leave, getPicture, setPicture, deletePicture, inviteCode, revokeInviteCode, getMembershipRequests, approveMembershipRequests, rejectMembershipRequests |
+| `webhooks` | list, listAll, deliveryFailures, redriveDeliveryFailures, get, create, update, delete, test |
+| `chats` | list, subscribePresence, getPresence, markRead, markUnread, archive, pin, mute, clearMessages, delete, sendState |
+| `labels` | list, get, chats, upsert, delete, forChat, addToChat, removeFromChat _(WhatsApp Business)_ |
+| `channels` | list, get, messages, create, delete, mute, subscribe, unsubscribe, demoteAdmin, transferOwnership _(Newsletters)_ |
+| `catalog` | info, products, product, sendProduct _(WhatsApp Business)_ |
+| `status` | list, fromContact, media, sendText, sendImage, sendVideo, sendVoice, delete _(Stories)_ |
+| `search` | search |
+| `templates` | list, get, create, update, delete |
+| `profile` | setProfileName, setProfileStatus, setProfilePicture, deleteProfilePicture |
+| `calls` | rejectCall, createLink |
+| `media` | conversionStatus, convertVoice _(OPERATOR)_, convertVideo _(OPERATOR)_ |
+| `health` | check, live, ready |
The twelve single-recipient send methods (text, image, video, audio, document, sticker, location, contact, template, poll, reply and forward) take an optional per-call idempotency key: a trailing argument in JavaScript, PHP and Java, `idempotency_key=` in Python and `openwa.WithIdempotencyKey(ctx, key)` in Go. A retry of the same logical send reuses its key; see each SDK's README.
@@ -217,6 +217,7 @@ Media bodies share the `SendMediaRequest` shape: `{ chatId, url? | base64?, mime
| `demoteParticipants` | `demoteParticipants(sessionId, groupId, participants)` | Demote participants from group admin. **OPERATOR** |
| `setSubject` | `setSubject(sessionId, groupId, subject)` | Update the group subject (name). **OPERATOR** |
| `setDescription` | `setDescription(sessionId, groupId, description)` | Update the group description (empty clears it). **OPERATOR** |
+| `setMemberLabel` | `setMemberLabel(sessionId, groupId, label)` | Set this account's member label in the group (empty clears it; Baileys only, whatsapp-web.js answers 501). **OPERATOR** |
| `getGroupSettings` | `getGroupSettings(sessionId, groupId)` | Get the group settings (announce / locked / ephemeral timer / who may add members). |
| `updateGroupSettings` | `updateGroupSettings(sessionId, groupId, body)` | Update the group settings (at least one field required). **OPERATOR** |
| `leave` | `leave(sessionId, groupId)` | Leave a group. **OPERATOR** |
@@ -595,6 +596,7 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All
| `demote_participants` | `demote_participants(session_id, group_id, participants) -> ParticipantsResult` | Demote from admin. A partial refusal still answers 200, so check `results`. **OPERATOR** |
| `set_subject` | `set_subject(session_id, group_id, subject) -> SuccessResult` | Set group subject. **OPERATOR** |
| `set_description` | `set_description(session_id, group_id, description) -> SuccessResult` | Set group description. **OPERATOR** |
+| `set_member_label` | `set_member_label(session_id, group_id, label) -> SuccessResult` | Set this account's member label in the group (empty clears it; Baileys only). **OPERATOR** |
| `get_group_settings` | `get_group_settings(session_id, group_id) -> GroupSettings` | Get the group settings (announce / locked / ephemeral timer / who may add members). |
| `update_group_settings` | `update_group_settings(session_id, group_id, body) -> SuccessResult` | Update the group settings (at least one field required). **OPERATOR** |
| `leave` | `leave(session_id, group_id) -> SuccessResult` | Leave the group. **OPERATOR** |
@@ -948,6 +950,7 @@ All payloads are associative arrays; all listed methods are synchronous and retu
| `demoteParticipants` | `demoteParticipants(string $sessionId, string $groupId, array $participants): array` | Demote admins. **OPERATOR** |
| `setSubject` | `setSubject(string $sessionId, string $groupId, string $subject): array` | Update the group subject. **OPERATOR** |
| `setDescription` | `setDescription(string $sessionId, string $groupId, string $description): array` | Update the group description. **OPERATOR** |
+| `setMemberLabel` | `setMemberLabel(string $sessionId, string $groupId, string $label): array` | Set this account's member label in the group (empty clears it; Baileys only). **OPERATOR** |
| `getGroupSettings` | `getGroupSettings(string $sessionId, string $groupId): array` | Get the group settings (only the ones the active engine supports are present). |
| `updateGroupSettings` | `updateGroupSettings(string $sessionId, string $groupId, array $settings): array` | Update the group settings (at least one of `announce`, `locked`, `ephemeralSeconds`, `memberAddMode`). **OPERATOR** |
| `leave` | `leave(string $sessionId, string $groupId): array` | Leave the group. **OPERATOR** |
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index f3296835d..14a873571 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 113 `IWhatsAppEngine` methods (29.4), **all 152
+the installed library. Coverage is total: all 114 `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
13 install-time patches (29.3). If it exists upstream or in OpenWA, it has a row here.
@@ -26,7 +26,7 @@ Statuses used in the tables:
Two complementary views:
-- **29.4, the OpenWA contract view.** Rows are the 113 `IWhatsAppEngine` methods; use it to see
+- **29.4, the OpenWA contract view.** Rows are the 114 `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**,
@@ -38,14 +38,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 (113 methods +
+instance behind the neutral `IWhatsAppEngine` interface (114 methods +
`EngineEventCallbacks`), and all modules go through it:
```mermaid
flowchart LR
subgraph OpenWA["OpenWA"]
API["REST API controllers"] --> SVC["Modules / services"]
- SVC --> IF["IWhatsAppEngine - 113 methods"]
+ SVC --> IF["IWhatsAppEngine - 114 methods"]
IF --> WA["WhatsAppWebJsAdapter"]
IF --> BA["BaileysAdapter"]
SVC --> STORE["OpenWA-side stores"]
@@ -216,7 +216,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 (113 methods)
+## 29.4 Full capability matrix: the OpenWA contract view (114 methods)
Legend recap: **✅** supported · **✅🔧ⁿ** supported via OpenWA patch `🔧ⁿ` (29.3) ·
**❌ gap** adapter-gap · **❌ lib** library-limitation. Column headers carry the engine-wide
@@ -337,6 +337,7 @@ socket is caught by the transport instead. No REST route: the session watchdog p
| `setGroupInfoAdminsOnly` | ✅ | ✅ | ✅ |
| `setGroupMemberAddMode` | ✅ | ✅ | ✅ |
| `setGroupEphemeral` | ✅ | ❌ lib | ⚠️ baileys only |
+| `setGroupMemberLabel` | ✅ | ❌ lib | ⚠️ baileys only |
### 29.4.7 Channels
@@ -409,9 +410,9 @@ answers 501.
| `rejectCall` | ✅ | ❌ lib | ⚠️ baileys only |
| `createCallLink` | ✅ | ✅ | ✅ |
-**Totals:** 113 methods → 226 adapter cells: **199 ✅, 27 ❌** (2 adapter-gaps, 25
-library-limitations, 0 uncertain) across 26 methods. From the REST caller's side: **89** methods
-work on any engine (87 fully supported + 2 store-backed status reads), **14** are Baileys-only,
+**Totals:** 114 methods → 228 adapter cells: **200 ✅, 28 ❌** (2 adapter-gaps, 26
+library-limitations, 0 uncertain) across 27 methods. From the REST caller's side: **89** methods
+work on any engine (87 fully supported + 2 store-backed status reads), **15** are Baileys-only,
**9** are wwjs-only (the 2 store-backed rows excluded); `sendCatalog`, unavailable on both engines,
is not exposed. Three of the 89 (`probeLiveness`, `getPhoneNumber`, `getPushName`) are ⚙️ internal and
have no route.
@@ -568,7 +569,7 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at
| `addMessageLabel` | ❌ **not exposed** |
| `removeChatLabel` | ✅ `removeLabelFromChat` |
| `removeMessageLabel` | ❌ **not exposed** |
-| `updateMemberLabel` | ❌ **not exposed** |
+| `updateMemberLabel` | ✅ `setGroupMemberLabel` |
**Privacy & account settings** (13)
@@ -850,7 +851,7 @@ OpenWA consumes events by normalizing them into `EngineEventCallbacks`; anything
| `group_leave` | ✅ | | `group_update` | ✅ |
| `group_membership_request` | ✅ | | | |
-## 29.6 The 27 not-available cells in detail
+## 29.6 The 28 not-available cells in detail
Every ❌ in 29.4, with the exact library symbol inspected (full evidence strings:
`engine-capability-matrix.ts`). All of these throw `EngineNotSupportedError` → HTTP 501 at the
@@ -873,7 +874,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 (15 cells)
+### 29.6.2 wwjs adapter (16 cells)
| Method | Cause | What's missing (evidence) |
| -------------------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -891,6 +892,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`). |
+| `setGroupMemberLabel` | lib | No member-label setter (0 hits for `memberLabel` or member tag in `index.d.ts` and `src/`). Baileys relays it with `updateMemberLabel` (`Socket/messages-send.js:274`). |
| `clickButton` | lib | No interactive button-reply send path; inbound buttons are not exposable as a clickable Client action. Baileys uses `sendMessage({buttonReply})` / `sendMessage({listReply})` for classic prompts. Native-flow `interactiveMessage` replies are unverified. |
## 29.7 Caveats on supported rows
@@ -1045,19 +1047,19 @@ 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:
-- **113** interface methods → **226** adapter cells: **199 ✅** / **27 ❌** (2 adapter-gaps, 25
- library-limitations, 0 uncertain), spanning **26** methods.
-- Of the 199 ✅ cells, **10 wwjs cells carry an explicit patch dependency** (4 × 🔧² status send,
+- **114** interface methods → **228** adapter cells: **200 ✅** / **28 ❌** (2 adapter-gaps, 26
+ library-limitations, 0 uncertain), spanning **27** 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
depends on 🔧¹, the whole Baileys column on 🔧⁵ — so every row rests on a patch on each side,
even though no row carries a row-level mark on both.
-- REST caller's view: **89** engine-neutral (87 + 2 store-backed status reads), **14** Baileys-only,
+- REST caller's view: **89** engine-neutral (87 + 2 store-backed status reads), **15** Baileys-only,
**9** wwjs-only; `sendCatalog` (unavailable on both engines) is not exposed; three of the 89
(`probeLiveness`, `getPhoneNumber`, `getPushName`) are ⚙️ internal and have no route.
- Full engine inventory (29.5), split by the exposure legend rather than lumped: Baileys **152**
- socket methods — 48 wired into interface methods, 5 internal wiring, 29 plumbing, **70 ❌ not
+ socket methods — 49 wired into interface methods, 5 internal wiring, 29 plumbing, **69 ❌ not
exposed** (incl. the whole 23-method community cluster); wwjs **81** Client methods — 41 wired,
4 internal wiring, 1 class plumbing, **35 ❌ not exposed** (27 real capabilities + 8
session/transport settings that are not WhatsApp capabilities). The backlog is the ❌ rows minus
diff --git a/openapi.json b/openapi.json
index 7a989dbd1..93cac5685 100644
--- a/openapi.json
+++ b/openapi.json
@@ -11233,6 +11233,128 @@
]
}
},
+ "/api/sessions/{sessionId}/groups/{groupId}/member-label": {
+ "put": {
+ "description": "Sets the per-group label WhatsApp shows beside this account's name in the group; an empty string clears it. Baileys only: whatsapp-web.js has no member-label setter and answers 501.",
+ "operationId": "GroupController_setMemberLabel",
+ "parameters": [
+ {
+ "name": "sessionId",
+ "required": true,
+ "in": "path",
+ "description": "Session ID",
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "groupId",
+ "required": true,
+ "in": "path",
+ "description": "Group ID",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GroupMemberLabelDto"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "The label message was handed to WhatsApp. Baileys sends it to the group as a protocol message with no per-request confirmation, and group metadata does not carry the label, so it cannot be read back.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GroupAckResponseDto"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "The body failed validation (`label` missing, not a string, or longer than 30 UTF-16 code units), the id does not name a group, or the session is not started (no engine is running for it).",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "The API key is missing, unknown, revoked, or expired",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "WhatsApp refused the group lookup the label message depends on, for example because the account is no longer a member of the group. Also returned when the API key's role, session or chat scope, or IP allow-list does not allow this operation.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "No such group — the id is unknown.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "The session is not connected: an engine exists for it but is not `ready`, meaning disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it, and for those few seconds the answer is a `409` naming the reload; retry shortly.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "501": {
+ "description": "Not supported by the active engine: whatsapp-web.js has no member-label setter, so this is Baileys-only.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "503": {
+ "description": "WhatsApp did not answer within the request budget. The label may or may not have been sent; the gateway stopped waiting for the send to finish. On Baileys, also answered when WhatsApp rate-limits or times out the request (code 429 or 408); retry after a pause.",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ },
+ "summary": "Set this account's member label in a group",
+ "tags": [
+ "groups"
+ ]
+ }
+ },
"/api/sessions/{sessionId}/groups/{groupId}/leave": {
"post": {
"operationId": "GroupController_leave",
@@ -23923,6 +24045,20 @@
"description"
]
},
+ "GroupMemberLabelDto": {
+ "type": "object",
+ "properties": {
+ "label": {
+ "type": "string",
+ "description": "This account's label in the group, shown beside its name (may be empty to clear it). Counted in UTF-16 code units, so an emoji outside the Basic Multilingual Plane takes two of the 30.",
+ "maxLength": 30,
+ "example": "Site A Management"
+ }
+ },
+ "required": [
+ "label"
+ ]
+ },
"GroupPictureResponseDto": {
"type": "object",
"properties": {
diff --git a/scripts/check-contract-shapes.mjs b/scripts/check-contract-shapes.mjs
index 3b86095d6..b159b60cd 100644
--- a/scripts/check-contract-shapes.mjs
+++ b/scripts/check-contract-shapes.mjs
@@ -95,6 +95,7 @@ const MAPPINGS = {
EditMessageRequest: 'EditMessageDto',
ForwardMessageRequest: 'ForwardMessageDto',
GroupDescriptionRequest: 'GroupDescriptionDto',
+ GroupMemberLabelRequest: 'GroupMemberLabelDto',
GroupInfo: 'GroupInfoDto',
GroupJoinInfo: 'GroupJoinInfoDto',
GroupMembershipRequest: 'GroupMembershipRequestDto',
@@ -614,6 +615,7 @@ const JAVA_MAPPING = {
EditMessageRequest: 'EditMessageDto',
ForwardMessageRequest: 'ForwardMessageDto',
GroupDescriptionRequest: 'GroupDescriptionDto',
+ GroupMemberLabelRequest: 'GroupMemberLabelDto',
GroupInfo: 'GroupInfoDto',
GroupJoinInfo: 'GroupJoinInfoDto',
GroupMembershipRequest: 'GroupMembershipRequestDto',
diff --git a/sdk/README.md b/sdk/README.md
index cead96cbc..bdb92374d 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -26,25 +26,25 @@ resource methods; the PHP SDK has no types layer and returns plain arrays.
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, 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, redriveDeliveryFailures, get, create, update, delete, test |
-| `chats` | list, markRead, markUnread, archive, pin, mute, clearMessages, delete, sendState, subscribePresence, getPresence |
-| `labels` | list, get, chats, forChat, upsert, delete, addToChat, removeFromChat _(WhatsApp Business)_ |
-| `channels` | list, get, messages, create, delete, mute, subscribe, unsubscribe, demoteAdmin, transferOwnership _(Newsletters)_ |
-| `catalog` | info, products, product, sendProduct _(WhatsApp Business)_ |
-| `status` | list, fromContact, media, sendText, sendImage, sendVideo, sendVoice, delete _(Stories)_ |
-| `search` | search _(Operator)_ |
-| `templates` | list, get, create, update, delete |
-| `profile` | setProfileName, setProfileStatus, setProfilePicture, deleteProfilePicture _(OPERATOR)_ |
-| `calls` | rejectCall, createLink _(OPERATOR)_ |
-| `media` | conversionStatus, convertVoice _(OPERATOR)_, convertVideo _(OPERATOR)_ |
-| `health` | check, live, ready |
-| `auth` | validate (`client.auth()`; `client.Auth.Validate` in Go) |
+| 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, 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, setMemberLabel, get/updateGroupSettings, leave, getPicture, setPicture, deletePicture, inviteCode, revokeInviteCode, getMembershipRequests, approveMembershipRequests, rejectMembershipRequests |
+| `webhooks` | list, listAll, deliveryFailures, redriveDeliveryFailures, get, create, update, delete, test |
+| `chats` | list, markRead, markUnread, archive, pin, mute, clearMessages, delete, sendState, subscribePresence, getPresence |
+| `labels` | list, get, chats, forChat, upsert, delete, addToChat, removeFromChat _(WhatsApp Business)_ |
+| `channels` | list, get, messages, create, delete, mute, subscribe, unsubscribe, demoteAdmin, transferOwnership _(Newsletters)_ |
+| `catalog` | info, products, product, sendProduct _(WhatsApp Business)_ |
+| `status` | list, fromContact, media, sendText, sendImage, sendVideo, sendVoice, delete _(Stories)_ |
+| `search` | search _(Operator)_ |
+| `templates` | list, get, create, update, delete |
+| `profile` | setProfileName, setProfileStatus, setProfilePicture, deleteProfilePicture _(OPERATOR)_ |
+| `calls` | rejectCall, createLink _(OPERATOR)_ |
+| `media` | conversionStatus, convertVoice _(OPERATOR)_, convertVideo _(OPERATOR)_ |
+| `health` | check, live, ready |
+| `auth` | validate (`client.auth()`; `client.Auth.Validate` in Go) |
> ⚠️ Endpoints requiring an `OPERATOR`-level API key are noted in the inline
> docs. Deliberately **not** exposed, matching `docs/18-sdk-design.md` exactly:
diff --git a/sdk/go/groups.go b/sdk/go/groups.go
index 233110190..f0872e6f3 100644
--- a/sdk/go/groups.go
+++ b/sdk/go/groups.go
@@ -141,6 +141,19 @@ func (s *GroupsService) SetDescription(ctx context.Context, sessionID, groupID,
return &out, nil
}
+// SetMemberLabel sets this account's member label in the group; an empty label clears it.
+// Baileys only: whatsapp-web.js answers 501. A 200 means the label message was handed to
+// WhatsApp; it cannot be read back.
+func (s *GroupsService) SetMemberLabel(ctx context.Context, sessionID, groupID, label string) (*SuccessResult, error) {
+ var out SuccessResult
+ body := map[string]string{"label": label}
+ err := s.client.do(ctx, "PUT", s.base(sessionID)+"/"+pathEscape(groupID)+"/member-label", nil, body, &out)
+ if err != nil {
+ return nil, err
+ }
+ return &out, nil
+}
+
// Leave leaves a group.
func (s *GroupsService) Leave(ctx context.Context, sessionID, groupID string) (*SuccessResult, error) {
var out SuccessResult
diff --git a/sdk/go/routing_test.go b/sdk/go/routing_test.go
index adbe37923..640e59a2e 100644
--- a/sdk/go/routing_test.go
+++ b/sdk/go/routing_test.go
@@ -84,6 +84,7 @@ func TestRouting(t *testing.T) {
{"Groups.DemoteParticipants", func(c *Client) { c.Groups.DemoteParticipants(ctx, "s1", "g1", nil) }, "POST", "/api/sessions/s1/groups/g1/participants/demote"},
{"Groups.SetSubject", func(c *Client) { c.Groups.SetSubject(ctx, "s1", "g1", "x") }, "PUT", "/api/sessions/s1/groups/g1/subject"},
{"Groups.SetDescription", func(c *Client) { c.Groups.SetDescription(ctx, "s1", "g1", "x") }, "PUT", "/api/sessions/s1/groups/g1/description"},
+ {"Groups.SetMemberLabel", func(c *Client) { c.Groups.SetMemberLabel(ctx, "s1", "g1", "x") }, "PUT", "/api/sessions/s1/groups/g1/member-label"},
{"Groups.Leave", func(c *Client) { c.Groups.Leave(ctx, "s1", "g1") }, "POST", "/api/sessions/s1/groups/g1/leave"},
{"Groups.InviteCode", func(c *Client) { c.Groups.InviteCode(ctx, "s1", "g1") }, "GET", "/api/sessions/s1/groups/g1/invite-code"},
{"Groups.RevokeInviteCode", func(c *Client) { c.Groups.RevokeInviteCode(ctx, "s1", "g1") }, "POST", "/api/sessions/s1/groups/g1/invite-code/revoke"},
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupMemberLabelRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupMemberLabelRequest.java
new file mode 100644
index 000000000..c325bf87c
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupMemberLabelRequest.java
@@ -0,0 +1,22 @@
+package com.rmyndharis.openwa.model;
+
+/** Request body for setting this account's member label in a group. */
+public record GroupMemberLabelRequest(String label) {
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static final class Builder {
+ private String label;
+
+ /** The label, at most 30 UTF-16 code units. May be empty to clear it. */
+ public Builder label(String v) {
+ this.label = v;
+ return this;
+ }
+
+ public GroupMemberLabelRequest build() {
+ return new GroupMemberLabelRequest(label);
+ }
+ }
+}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.java
index 56d7f733a..c96015cef 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/GroupsResource.java
@@ -6,6 +6,7 @@ import com.rmyndharis.openwa.OpenWAClient;
import com.rmyndharis.openwa.http.HttpMethod;
import com.rmyndharis.openwa.model.CreateGroupRequest;
import com.rmyndharis.openwa.model.GroupDescriptionRequest;
+import com.rmyndharis.openwa.model.GroupMemberLabelRequest;
import com.rmyndharis.openwa.model.GroupInfo;
import com.rmyndharis.openwa.model.GroupJoinInfo;
import com.rmyndharis.openwa.model.GroupMembershipRequest;
@@ -149,6 +150,20 @@ public final class GroupsResource {
SuccessResult.class);
}
+ /**
+ * Set this account's member label in the group (empty string clears it). Baileys only;
+ * whatsapp-web.js answers 501. A 200 means the label message was handed to WhatsApp; it cannot
+ * be read back.
+ */
+ public SuccessResult setMemberLabel(String sessionId, String groupId, String label) {
+ return client.request(
+ HttpMethod.PUT,
+ "/api/sessions/" + encodeSegment(sessionId) + "/groups/" + encodeSegment(groupId) + "/member-label",
+ null,
+ new GroupMemberLabelRequest(label),
+ SuccessResult.class);
+ }
+
/** Get the group settings (announce / locked / ephemeral timer / member-add mode). */
public GroupSettings getGroupSettings(String sessionId, String groupId) {
return client.request(
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/GroupsResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/GroupsResourceTest.java
index e0f18085e..4f2b014fc 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/GroupsResourceTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/GroupsResourceTest.java
@@ -110,6 +110,15 @@ class GroupsResourceTest {
assertTrue(tx.lastRequest().body().contains("A description"));
}
+ @Test
+ void setMemberLabelSendsBody() {
+ tx.respond(200, "{\"success\":true}");
+ client.groups.setMemberLabel("s", "[email protected]", "Site A");
+ assertEquals("http://h/api/sessions/s/groups/[email protected]/member-label", tx.lastRequest().url());
+ assertEquals(HttpMethod.PUT, tx.lastRequest().method());
+ assertTrue(tx.lastRequest().body().contains("\"label\":\"Site A\""));
+ }
+
@Test
void joinGroupHitsJoinPath() {
tx.respond(200, "{\"success\":true,\"groupId\":\"[email protected]\"}");
diff --git a/sdk/javascript/src/resources/groups.ts b/sdk/javascript/src/resources/groups.ts
index a994385e0..1ad371977 100644
--- a/sdk/javascript/src/resources/groups.ts
+++ b/sdk/javascript/src/resources/groups.ts
@@ -140,6 +140,18 @@ export class GroupsResource {
});
}
+ /**
+ * Set this account's member label in the group (empty string clears it). Baileys only; whatsapp-web.js
+ * answers 501. A 200 means the label message was handed to WhatsApp; it cannot be read back.
+ */
+ setMemberLabel(sessionId: string, groupId: string, label: string): Promise<SuccessResult> {
+ return this.client.request<SuccessResult>({
+ method: 'PUT',
+ path: `/api/sessions/${encodeSegment(sessionId)}/groups/${encodeSegment(groupId)}/member-label`,
+ body: { label },
+ });
+ }
+
/** Get the group settings (announce / locked / ephemeral timer / member-add mode). */
getGroupSettings(sessionId: string, groupId: string): Promise<GroupSettingsResponse> {
return this.client.request<GroupSettingsResponse>({
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index d9ff97c21..6ff099c74 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -879,6 +879,11 @@ export interface GroupDescriptionRequest {
description: string;
}
+export interface GroupMemberLabelRequest {
+ /** At most 30 UTF-16 code units (an astral emoji counts as two). May be empty to clear. */
+ label: string;
+}
+
export interface InviteCodeResponse {
inviteCode: string;
inviteLink: string;
diff --git a/sdk/javascript/test/resources.test.ts b/sdk/javascript/test/resources.test.ts
index 562b39efa..0222fbaff 100644
--- a/sdk/javascript/test/resources.test.ts
+++ b/sdk/javascript/test/resources.test.ts
@@ -59,6 +59,14 @@ describe('GroupsResource — exact paths and bodies', () => {
expect(t.lastCall!.url).toContain('/invite-code/revoke');
});
+ it('setMemberLabel PUTs the label to the group', async () => {
+ const t = new MockTransport().on('PUT', /\/member-label$/, { body: { success: true } });
+ await client(t).groups.setMemberLabel('s', '[email protected]', 'Site A');
+ expect(t.lastCall!.method).toBe('PUT');
+ expect(t.lastCall!.url).toContain('/api/sessions/s/groups/[email protected]/member-label');
+ expect(t.lastCall!.body).toEqual({ label: 'Site A' });
+ });
+
it('membership requests — list, approve, reject', async () => {
const t = new MockTransport()
.on('GET', /\/membership-requests$/, { body: [{ participantId: '[email protected]', method: 'invite_link' }] })
diff --git a/sdk/php/src/Resources/GroupsResource.php b/sdk/php/src/Resources/GroupsResource.php
index 935b5a5a4..3187191cc 100644
--- a/sdk/php/src/Resources/GroupsResource.php
+++ b/sdk/php/src/Resources/GroupsResource.php
@@ -105,6 +105,18 @@ class GroupsResource
return $this->http->request('PUT', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/{$this->http->encodeSegment($groupId)}/description", [], ['description' => $description]);
}
+ /**
+ * Set this account's member label in the group (an empty string clears it).
+ * Baileys only; whatsapp-web.js answers 501. A 200 means the label message
+ * was handed to WhatsApp; it cannot be read back.
+ *
+ * @return array<string,mixed>
+ */
+ public function setMemberLabel(string $sessionId, string $groupId, string $label): array
+ {
+ return $this->http->request('PUT', "/api/sessions/{$this->http->encodeSegment($sessionId)}/groups/{$this->http->encodeSegment($groupId)}/member-label", [], ['label' => $label]);
+ }
+
/**
* Get group settings. Only the settings the active engine supports are
* present: any of {announce, locked, ephemeralSeconds, memberAddMode} may
diff --git a/sdk/php/tests/ResourcesTest.php b/sdk/php/tests/ResourcesTest.php
index 6f2898019..282dfa200 100644
--- a/sdk/php/tests/ResourcesTest.php
+++ b/sdk/php/tests/ResourcesTest.php
@@ -137,6 +137,16 @@ class ResourcesTest extends TestCase
$this->assertStringContainsString('/revoke', $backend->calls()[4]['url']);
}
+ public function testGroupSetMemberLabel(): void
+ {
+ $backend = new MockBackend();
+ $backend->on(200, ['success' => true]);
+ $client = $backend->makeClient();
+ $client->groups->setMemberLabel('s', '[email protected]', 'Site A');
+ $this->assertRequest($backend, 'PUT', '/api/sessions/s/groups/[email protected]/member-label');
+ $this->assertSame(['label' => 'Site A'], $backend->lastCall()['body']);
+ }
+
public function testGroupJoinAndSettings(): void
{
$backend = new MockBackend();
diff --git a/sdk/python/openwa/resources/groups.py b/sdk/python/openwa/resources/groups.py
index 6c8be2873..b85010c44 100644
--- a/sdk/python/openwa/resources/groups.py
+++ b/sdk/python/openwa/resources/groups.py
@@ -85,6 +85,17 @@ class GroupsResource:
body={"description": description},
)
+ def set_member_label(self, session_id: str, group_id: str, label: str) -> SuccessResult:
+ """Set this account's member label in the group (empty string clears it).
+
+ Baileys only; whatsapp-web.js answers 501. A 200 means the label message was
+ handed to WhatsApp; it cannot be read back.
+ """
+ return self._http.request(
+ "PUT", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}/member-label",
+ body={"label": label},
+ )
+
def leave(self, session_id: str, group_id: str) -> SuccessResult:
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/groups/{quote_segment(group_id)}/leave")
diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py
index 1ce6f6c4d..8c4240904 100644
--- a/sdk/python/tests/test_sdk.py
+++ b/sdk/python/tests/test_sdk.py
@@ -878,6 +878,13 @@ class TestGroups:
client.groups.revoke_invite_code("s", "g")
assert "/revoke" in backend.calls[-1].url
+ def test_set_member_label(self):
+ backend = MockBackend().on("PUT", "/member-label", body={"success": True})
+ make_client(backend).groups.set_member_label("s", "[email protected]", "Site A")
+ assert backend.last_call.method == "PUT"
+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s/groups/[email protected]/member-label"
+ assert backend.last_call.body == {"label": "Site A"}
+
def test_join_group(self):
backend = MockBackend().on("POST", "/groups/join", body={"success": True, "groupId": "[email protected]"})
diff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.ts
index 7803e39fe..9726b3f0e 100644
--- a/src/engine/adapters/baileys-groups.ts
+++ b/src/engine/adapters/baileys-groups.ts
@@ -554,6 +554,17 @@ export class BaileysGroups {
);
}
+ /**
+ * Not an IQ: `updateMemberLabel` relays a GROUP_MEMBER_LABEL_CHANGE protocol message to the group and
+ * resolves with its message id once sent, so a 4xx here is the group lookup the relay depends on.
+ */
+ async setGroupMemberLabel(groupId: string, label: string): Promise<void> {
+ this.host.ensureReady();
+ await this.groupWrite(groupId, 'Setting the member label', () =>
+ this.confirmed(this.sock().updateMemberLabel(groupId, label), 'the member label change'),
+ );
+ }
+
async getGroupMembershipRequests(groupId: string): Promise<GroupMembershipRequest[]> {
this.host.ensureReady();
const raw = await this.groupWrite(groupId, 'Listing the membership requests', () =>
diff --git a/src/engine/adapters/baileys-write-deadline.spec.ts b/src/engine/adapters/baileys-write-deadline.spec.ts
index 80bdc10d2..a99fa2240 100644
--- a/src/engine/adapters/baileys-write-deadline.spec.ts
+++ b/src/engine/adapters/baileys-write-deadline.spec.ts
@@ -73,6 +73,8 @@ describe('group writes report an unconfirmed write rather than success', () => {
(g: BaileysGroups) => g.setGroupMemberAddMode('[email protected]', 'admins'),
],
['setGroupEphemeral', 'groupToggleEphemeral', (g: BaileysGroups) => g.setGroupEphemeral('[email protected]', 604800)],
+ // A relayed message rather than an IQ, but the group lookup and device fetch before the relay can stall.
+ ['setGroupMemberLabel', 'updateMemberLabel', (g: BaileysGroups) => g.setGroupMemberLabel('[email protected]', 'Site A')],
])('%s', async (_name, sockMethod, call) => {
await expect(call(groups({ [sockMethod]: stub() }, 15))).rejects.toBeInstanceOf(EngineTransportError);
});
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index b2e71c3c1..0156ef73c 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -64,6 +64,8 @@ class FakeSock extends EventEmitter {
public groupAcceptInvite = jest.fn();
public groupSettingUpdate = jest.fn().mockResolvedValue(undefined);
public groupToggleEphemeral = jest.fn().mockResolvedValue(undefined);
+ // Resolves with the relayed protocol message's id.
+ public updateMemberLabel = jest.fn().mockResolvedValue('3EB0LABEL');
public groupGetInviteInfo = jest.fn();
public groupMemberAddMode = jest.fn().mockResolvedValue(undefined);
public profilePictureUrl = jest.fn();
@@ -5848,6 +5850,12 @@ describe('BaileysAdapter group management', () => {
['revokeGroupInviteCode', (a: BaileysAdapter) => a.revokeGroupInviteCode('[email protected]'), 'groupRevokeInvite'],
// Was the one group write with no refusal mapping: a refused leave answered an opaque 500.
['leaveGroup', (a: BaileysAdapter) => a.leaveGroup('[email protected]'), 'groupLeave'],
+ // A relayed message, not an IQ: the refusal is the group lookup the relay runs first.
+ [
+ 'setGroupMemberLabel',
+ (a: BaileysAdapter) => a.setGroupMemberLabel('[email protected]', 'Site A'),
+ 'updateMemberLabel',
+ ],
])('%s maps an admin-refused operation to EngineRefusedError (403)', async (_name, call, sockMethod) => {
(fakeSock as unknown as Record<string, jest.Mock>)[sockMethod].mockRejectedValueOnce(
Object.assign(new Error('not-authorized'), { data: 401 }),
@@ -5881,6 +5889,11 @@ describe('BaileysAdapter group management', () => {
'groupMemberAddMode',
],
['setGroupEphemeral', (a: BaileysAdapter) => a.setGroupEphemeral('[email protected]', 86400), 'groupToggleEphemeral'],
+ [
+ 'setGroupMemberLabel',
+ (a: BaileysAdapter) => a.setGroupMemberLabel('[email protected]', 'Site A'),
+ 'updateMemberLabel',
+ ],
['getGroupInviteCode', (a: BaileysAdapter) => a.getGroupInviteCode('[email protected]'), 'groupInviteCode'],
['revokeGroupInviteCode', (a: BaileysAdapter) => a.revokeGroupInviteCode('[email protected]'), 'groupRevokeInvite'],
['leaveGroup', (a: BaileysAdapter) => a.leaveGroup('[email protected]'), 'groupLeave'],
@@ -6074,6 +6087,30 @@ describe('BaileysAdapter group management', () => {
expect(fakeSock.groupToggleEphemeral).toHaveBeenCalledWith('[email protected]', 0);
});
+ it('setGroupMemberLabel relays the label to the group jid (empty clears) and resolves void', async () => {
+ const adapter = await ready();
+ await expect(adapter.setGroupMemberLabel('[email protected]', 'Site A Management')).resolves.toBeUndefined();
+ expect(fakeSock.updateMemberLabel).toHaveBeenCalledWith('[email protected]', 'Site A Management');
+ await adapter.setGroupMemberLabel('[email protected]', '');
+ expect(fakeSock.updateMemberLabel).toHaveBeenLastCalledWith('[email protected]', '');
+ });
+
+ it.each([
+ [429, EngineThrottledError],
+ [408, EngineTransportError],
+ ])('setGroupMemberLabel maps WhatsApp code %i to a retryable 503', async (code, errorClass) => {
+ fakeSock.updateMemberLabel.mockRejectedValueOnce(Object.assign(new Error('throttled'), { data: code }));
+ const adapter = await ready();
+ await expect(adapter.setGroupMemberLabel('[email protected]', 'Site A')).rejects.toBeInstanceOf(errorClass);
+ });
+
+ it('setGroupMemberLabel lets a dead socket propagate rather than report a refusal', async () => {
+ const connectionClosed = new Boom('Connection Closed', { statusCode: 428 });
+ fakeSock.updateMemberLabel.mockRejectedValueOnce(connectionClosed);
+ const adapter = await ready();
+ await expect(adapter.setGroupMemberLabel('[email protected]', 'Site A')).rejects.toBe(connectionClosed);
+ });
+
it('getGroupInfo populates announce/locked/ephemeralSeconds from the metadata', async () => {
fakeSock.groupMetadata.mockResolvedValueOnce({
...META,
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 7cf880204..a33242383 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -478,6 +478,10 @@ export class BaileysAdapter implements IWhatsAppEngine {
return this.groups.setGroupEphemeral(groupId, durationSec);
}
+ async setGroupMemberLabel(groupId: string, label: string): Promise<void> {
+ return this.groups.setGroupMemberLabel(groupId, label);
+ }
+
async getGroupMembershipRequests(groupId: string): Promise<GroupMembershipRequest[]> {
return this.groups.getGroupMembershipRequests(groupId);
}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 92c307fea..8922c7b53 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -7788,6 +7788,16 @@ describe('WhatsAppWebJsAdapter group join + settings + own profile', () => {
});
});
+ describe('setGroupMemberLabel (no wwjs 1.34.7 API → honest 501)', () => {
+ it('rejects with EngineNotSupportedError (501)', async () => {
+ const err = await readyAdapter({})
+ .setGroupMemberLabel('[email protected]', 'Site A')
+ .catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(EngineNotSupportedError);
+ expect((err as EngineNotSupportedError).getStatus()).toBe(501);
+ });
+ });
+
describe('setProfileName / setProfileStatus', () => {
it('setProfileName resolves when the engine accepts', async () => {
const setDisplayName = jest.fn().mockResolvedValue(true);
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 580761369..614833dec 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -840,6 +840,10 @@ export class WhatsAppWebJsAdapter implements IWhatsAppEngine {
return this.groups.setGroupEphemeral(groupId, durationSec);
}
+ setGroupMemberLabel(groupId: string, label: string): Promise<void> {
+ return this.groups.setGroupMemberLabel(groupId, label);
+ }
+
getGroupMembershipRequests(groupId: string): Promise<GroupMembershipRequest[]> {
return this.groups.getGroupMembershipRequests(groupId);
}
diff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.ts
index c2b82792b..8562be0e1 100644
--- a/src/engine/adapters/wwebjs-groups.ts
+++ b/src/engine/adapters/wwebjs-groups.ts
@@ -596,6 +596,14 @@ export class WwebjsGroups {
throw new EngineNotSupportedError('setGroupEphemeral');
}
+ // whatsapp-web.js 1.34.7 has no member-label setter (no memberLabel or member tag symbol in index.d.ts
+ // or src/), so this is an honest 501 rather than a no-op.
+ // eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars
+ async setGroupMemberLabel(_groupId: string, _label: string): Promise<void> {
+ this.host.ensureReady();
+ throw new EngineNotSupportedError('setGroupMemberLabel');
+ }
+
async getGroupMembershipRequests(groupId: string): Promise<GroupMembershipRequest[]> {
// Resolved first, like every other group operation in this file. Without it an unknown id or a
// non-group jid answered 200 with an empty list, which reads as "this group has no pending
diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.ts
index 6fcefc17e..e80ea4f0b 100644
--- a/src/engine/engine-capability-matrix.ts
+++ b/src/engine/engine-capability-matrix.ts
@@ -360,6 +360,12 @@ export const CURATED_CAPABILITY_EXCEPTIONS: Record<string, MethodCapability> = {
evidence:
'wwjs 1.34.7 exposes NO ephemeral setter — 0 hits for ephemeral in index.d.ts; only a create-time messageTimer option (Client.js:2328); adapter throws EngineNotSupportedError; baileys groupToggleEphemeral(jid, ephemeralExpiration) (Socket/groups.d.ts:40)',
},
+ setGroupMemberLabel: {
+ wwjs: { status: 'not-available', rootCause: 'library-limitation' },
+ baileys: { status: 'supported' },
+ evidence:
+ 'wwjs 1.34.7 exposes NO member-label setter: 0 hits for memberLabel or member tag in index.d.ts and src/; adapter throws EngineNotSupportedError; baileys updateMemberLabel(jid, memberLabel) (Socket/messages-send.d.ts:34) relays a GROUP_MEMBER_LABEL_CHANGE protocol message to the group with the label cut by slice(0, 30) (messages-send.js:274-295)',
+ },
setGroupInfoAdminsOnly: {
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 c1099c669..b71f76a36 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -1439,6 +1439,13 @@ export interface GroupCapability {
*/
setGroupEphemeral(groupId: string, durationSec: number): Promise<void>;
+ /**
+ * Set this account's own member label in the group (the per-group tag shown beside its name); an empty
+ * string clears it. Resolves once the label message is handed to WhatsApp: it travels as a group
+ * protocol message with no per-request confirmation, and group metadata does not carry the label back.
+ */
+ setGroupMemberLabel(groupId: string, label: string): Promise<void>;
+
/**
* Pending join requests for a group with join-approval turned on. Admin-only on both engines;
* a non-admin's read is refused by the engine and surfaced as-is.
diff --git a/src/modules/group/dto/group.dto.spec.ts b/src/modules/group/dto/group.dto.spec.ts
index ddc577769..b341753f3 100644
--- a/src/modules/group/dto/group.dto.spec.ts
+++ b/src/modules/group/dto/group.dto.spec.ts
@@ -6,6 +6,7 @@ import {
CreateGroupDto,
GroupSubjectDto,
GroupDescriptionDto,
+ GroupMemberLabelDto,
JoinGroupDto,
GroupSettingsDto,
MembershipRequestActionDto,
@@ -93,6 +94,38 @@ describe('group DTO validation', () => {
expect((await errorsFor(GroupDescriptionDto, { description: 'a'.repeat(1025) })).length).toBeGreaterThan(0);
});
+ it('bounds the member label at 30 characters, and an empty one clears it', async () => {
+ expect(await errorsFor(GroupMemberLabelDto, { label: '' })).toHaveLength(0);
+ expect(await errorsFor(GroupMemberLabelDto, { label: 'a'.repeat(30) })).toHaveLength(0);
+ expect((await errorsFor(GroupMemberLabelDto, { label: 'a'.repeat(31) })).map(e => e.property)).toEqual(['label']);
+ });
+
+ // Baileys sends label.slice(0, 30), which counts UTF-16 code units. @MaxLength would take both of these,
+ // and Baileys would then drop the tail behind a 200, the second one through the middle of an emoji.
+ it('counts the member label in UTF-16 code units, the unit Baileys cuts it at', async () => {
+ expect(await errorsFor(GroupMemberLabelDto, { label: '😀'.repeat(15) })).toHaveLength(0);
+ expect((await errorsFor(GroupMemberLabelDto, { label: '😀'.repeat(16) })).length).toBeGreaterThan(0);
+ expect((await errorsFor(GroupMemberLabelDto, { label: 'a' + '😀'.repeat(15) })).length).toBeGreaterThan(0);
+ });
+
+ // A number is read as its decimal string, as on every @ToStrictString field.
+ it.each([
+ ['missing', {}],
+ ['a boolean', { label: true }],
+ ['an object', { label: { text: 'Site A' } }],
+ ['null', { label: null }],
+ ['an array', { label: ['Site A'] }],
+ ])('refuses a member label that is %s', async (_name, payload) => {
+ expect((await errorsFor(GroupMemberLabelDto, payload)).map(e => e.property)).toEqual(['label']);
+ });
+
+ it('publishes the member label cap in the contract', () => {
+ const published = Reflect.getMetadata('swagger/apiModelProperties', GroupMemberLabelDto.prototype, 'label') as {
+ maxLength?: number;
+ };
+ expect(published.maxLength).toBe(30);
+ });
+
it('requires a non-empty invite code on JoinGroupDto', async () => {
expect(await errorsFor(JoinGroupDto, { inviteCode: 'AbCdEfGhIjKl' })).toHaveLength(0);
expect((await errorsFor(JoinGroupDto, { inviteCode: '' })).length).toBeGreaterThan(0);
diff --git a/src/modules/group/dto/group.dto.ts b/src/modules/group/dto/group.dto.ts
index 336c2660d..71d43a6c8 100644
--- a/src/modules/group/dto/group.dto.ts
+++ b/src/modules/group/dto/group.dto.ts
@@ -23,6 +23,7 @@ import { stripBase64DataUri } from '../../message/media-cap.util';
// so MCP and REST enforce the same limits on the equivalent operations.
export const GROUP_NAME_MAX_LENGTH = 100;
export const GROUP_DESCRIPTION_MAX_LENGTH = 1024;
+export const GROUP_MEMBER_LABEL_MAX_LENGTH = 30;
/**
* Max participants accepted in one group-create or participant-batch request. The engine works the
@@ -109,6 +110,24 @@ export class GroupDescriptionDto {
description!: string;
}
+export class GroupMemberLabelDto {
+ @ApiProperty({
+ description:
+ "This account's label in the group, shown beside its name (may be empty to clear it). Counted in " +
+ 'UTF-16 code units, so an emoji outside the Basic Multilingual Plane takes two of the 30.',
+ maxLength: GROUP_MEMBER_LABEL_MAX_LENGTH,
+ example: 'Site A Management',
+ })
+ @ToStrictString()
+ @IsString()
+ // Not @MaxLength: it counts an astral emoji once, while Baileys cuts the label with slice(0, 30), so a label
+ // it passes could be shortened behind a 200, mid-emoji. No `u` flag, so each match is one code unit.
+ @Matches(new RegExp(`^[\\s\\S]{0,${GROUP_MEMBER_LABEL_MAX_LENGTH}}$`), {
+ message: `label must be shorter than or equal to ${GROUP_MEMBER_LABEL_MAX_LENGTH} UTF-16 code units`,
+ })
+ label!: string;
+}
+
export class JoinGroupDto {
@ApiProperty({
description: 'Group invite code (the token from a https://chat.whatsapp.com/<code> link)',
diff --git a/src/modules/group/group.controller.spec.ts b/src/modules/group/group.controller.spec.ts
index c91150042..e0e91e131 100644
--- a/src/modules/group/group.controller.spec.ts
+++ b/src/modules/group/group.controller.spec.ts
@@ -53,6 +53,15 @@ describe('GroupController join + settings', () => {
);
});
+ it('PUT :groupId/member-label forwards the label and returns the success envelope', async () => {
+ const { controller, service } = build({ setGroupMemberLabel: jest.fn().mockResolvedValue(undefined) });
+ await expect(controller.setMemberLabel('s1', '[email protected]', { label: 'Site A' })).resolves.toEqual({
+ success: true,
+ message: 'Group member label sent',
+ });
+ expect(service.setGroupMemberLabel).toHaveBeenCalledWith('s1', '[email protected]', 'Site A');
+ });
+
it('PUT :groupId/settings propagates a service rejection (empty patch / 501 passthrough)', async () => {
const { controller } = build({
updateGroupSettings: jest
diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.ts
index 8db46dfc6..464108f3d 100644
--- a/src/modules/group/group.controller.ts
+++ b/src/modules/group/group.controller.ts
@@ -20,6 +20,7 @@ import {
ParticipantsDto,
GroupSubjectDto,
GroupDescriptionDto,
+ GroupMemberLabelDto,
JoinGroupDto,
GroupSettingsDto,
MembershipRequestActionDto,
@@ -527,6 +528,60 @@ export class GroupController {
return { success: true, message: 'Group description updated' };
}
+ @ChatScoped('fenced')
+ @Put(':groupId/member-label')
+ @RequireRole(ApiKeyRole.OPERATOR)
+ @ApiOperation({
+ summary: "Set this account's member label in a group",
+ description:
+ "Sets the per-group label WhatsApp shows beside this account's name in the group; an empty string clears " +
+ 'it. Baileys only: whatsapp-web.js has no member-label setter and answers 501.',
+ })
+ @ApiParam({ name: 'sessionId', description: 'Session ID' })
+ @ApiParam({ name: 'groupId', description: 'Group ID' })
+ @ApiBody({ type: GroupMemberLabelDto })
+ @ApiResponse({
+ status: 200,
+ description:
+ 'The label message was handed to WhatsApp. Baileys sends it to the group as a protocol message with no ' +
+ 'per-request confirmation, and group metadata does not carry the label, so it cannot be read back.',
+ type: GroupAckResponseDto,
+ })
+ @ApiResponse({
+ status: 400,
+ description:
+ 'The body failed validation (`label` missing, not a string, or longer than 30 UTF-16 code units), the id ' +
+ 'does not name a group, or the session is not started (no engine is running for it).',
+ })
+ @ApiResponse({
+ status: 403,
+ description:
+ 'WhatsApp refused the group lookup the label message depends on, for example because the account is ' +
+ 'no longer a member of the group',
+ })
+ @ApiResponse({ status: 404, description: GROUP_NOT_FOUND_404 })
+ @ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
+ @ApiResponse({
+ status: 501,
+ description:
+ 'Not supported by the active engine: whatsapp-web.js has no member-label setter, so this is Baileys-only.',
+ })
+ @ApiResponse({
+ status: 503,
+ description:
+ 'WhatsApp did not answer within the request budget. The label may or may not have been sent; the ' +
+ 'gateway stopped waiting for the send to finish.' +
+ THROTTLED_503,
+ })
+ async setMemberLabel(
+ @Param('sessionId') sessionId: string,
+ @Param('groupId') groupId: string,
+ @Body() dto: GroupMemberLabelDto,
+ ) {
+ await this.groupService.setGroupMemberLabel(sessionId, groupId, dto.label);
+ return { success: true, message: 'Group member label sent' };
+ }
+
@ChatScoped('fenced')
@Post(':groupId/leave')
@RequireRole(ApiKeyRole.OPERATOR)
diff --git a/src/modules/group/group.service.spec.ts b/src/modules/group/group.service.spec.ts
index ec0a1f51d..18cabdd85 100644
--- a/src/modules/group/group.service.spec.ts
+++ b/src/modules/group/group.service.spec.ts
@@ -78,6 +78,43 @@ describe('GroupService', () => {
});
});
+ // Baileys relays the label as a message to whatever jid it is handed, so a 1:1 id would put a group
+ // protocol message in a person's chat.
+ describe('setGroupMemberLabel', () => {
+ it.each([
+ ['a 1:1 jid', '[email protected]'],
+ ['a lid', '99887766@lid'],
+ ['a channel', '120363000000000000@newsletter'],
+ ])('refuses %s before it reaches the engine', (_label, id) => {
+ const setGroupMemberLabel = jest.fn().mockResolvedValue(undefined);
+ const svc = makeService({ setGroupMemberLabel });
+
+ expect(() => svc.setGroupMemberLabel('s1', id, 'Site A')).toThrow(BadRequestException);
+ expect(setGroupMemberLabel).not.toHaveBeenCalled();
+ });
+
+ it('forwards a group id and the label, an empty one included', async () => {
+ const setGroupMemberLabel = jest.fn().mockResolvedValue(undefined);
+ const svc = makeService({ setGroupMemberLabel });
+
+ await svc.setGroupMemberLabel('s1', '[email protected]', 'Site A Management');
+ await svc.setGroupMemberLabel('s1', '[email protected]', '');
+
+ expect(setGroupMemberLabel).toHaveBeenNthCalledWith(1, '[email protected]', 'Site A Management');
+ expect(setGroupMemberLabel).toHaveBeenNthCalledWith(2, '[email protected]', '');
+ });
+
+ it('lets the whatsapp-web.js 501 through', async () => {
+ const svc = makeService({
+ setGroupMemberLabel: jest.fn().mockRejectedValue(new EngineNotSupportedError('setGroupMemberLabel')),
+ });
+
+ await expect(svc.setGroupMemberLabel('s1', '[email protected]', 'Site A')).rejects.toBeInstanceOf(
+ EngineNotSupportedError,
+ );
+ });
+ });
+
// The service is the only enforcer of these body rules: SetGroupPictureDto.mimetype is optional, and a
// plugin send or a hook rewrite reaches the service without the DTO's url check.
describe('setGroupPicture checks its media body', () => {
diff --git a/src/modules/group/group.service.ts b/src/modules/group/group.service.ts
index 6c4fd8376..c69b2778d 100644
--- a/src/modules/group/group.service.ts
+++ b/src/modules/group/group.service.ts
@@ -163,6 +163,11 @@ export class GroupService {
return this.getEngine(sessionId).setGroupDescription(groupId, description);
}
+ setGroupMemberLabel(sessionId: string, groupId: string, label: string): Promise<void> {
+ this.assertGroupId(groupId);
+ return this.getEngine(sessionId).setGroupMemberLabel(groupId, label);
+ }
+
leaveGroup(sessionId: string, groupId: string) {
return this.getEngine(sessionId).leaveGroup(groupId);
}
@@ -207,6 +212,9 @@ export class GroupService {
* belongs replaced or permanently deleted the account's own avatar and answered 200, while
* whatsapp-web.js refused the same input through requireGroupChat. Guarded here rather than in either
* adapter so both engines agree, and so no engine ever sees the wrong kind of id.
+ *
+ * The member label uses it too: Baileys relays that label as a message to whatever jid it is given, so
+ * a 1:1 id would send a group protocol message to a person.
*/
private assertGroupId(groupId: string): void {
if (chatKind(groupId) !== 'group') {