Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(sdk): align webhook filter types and close method coverage gaps across all SDKs (#947)

Yudhi Armyndhariseb4f84badc8a
diff --git a/sdk/README.md b/sdk/README.md
index a897ca24f..754f903d6 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -25,15 +25,15 @@ All five SDKs expose the same fluent resource surface:
| Resource | Methods |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sessions` | list, get, create, delete, start, stop, forceKill, getQrCode, requestPairingCode, stats |
-| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, reply, forward, react, delete, editMessage, history, reactions, sendBulk, batchStatus, cancelBatch |
-| `contacts` | list, get, check, profilePicture, phone, block, unblock |
+| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, 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 |
| `chats` | list, markRead, markUnread, delete, sendState |
| `labels` | list, get, forChat, addToChat, removeFromChat _(WhatsApp Business)_ |
| `channels` | list, get, messages, subscribe, unsubscribe _(Newsletters)_ |
| `catalog` | info, products, product, sendProduct, sendCatalog _(WhatsApp Business)_ |
-| `status` | list, fromContact, sendText, sendImage, sendVideo, delete _(Stories)_ |
+| `status` | list, fromContact, media, sendText, sendImage, sendVideo, delete _(Stories)_ |
| `search` | search _(Operator)_ |
| `templates`| list, get, create, update, delete |
| `profile` | setProfileName, setProfileStatus, setProfilePicture _(OPERATOR)_ |
diff --git a/sdk/go/client.go b/sdk/go/client.go
index f6ef1e5fb..e9810eb92 100644
--- a/sdk/go/client.go
+++ b/sdk/go/client.go
@@ -185,17 +185,49 @@ func warnIfInsecure(cfg *config) {
// Do issues a raw request against the API and decodes the JSON response into
// out (pass nil to ignore the body). It is the escape hatch for endpoints the
// typed services do not cover. path must begin with "/".
+//
+// A 2xx body is assigned verbatim when out is a *[]byte, and a non-JSON 2xx
+// body falls back to the raw text when out is a *string — mirroring the
+// JS/Python/PHP transports, which return the raw text instead of failing.
+// Any other out type still requires a JSON body.
func (c *Client) Do(ctx context.Context, method, path string, query url.Values, body, out any) error {
return c.do(ctx, method, path, query, body, out)
}
func (c *Client) do(ctx context.Context, method, path string, query url.Values, body, out any) error {
+ data, _, err := c.doRaw(ctx, method, path, query, body)
+ if err != nil {
+ return err
+ }
+ if out == nil || len(data) == 0 {
+ return nil
+ }
+ // A *[]byte target always takes the body verbatim (media bytes are not JSON).
+ if raw, ok := out.(*[]byte); ok {
+ *raw = data
+ return nil
+ }
+ if err := json.Unmarshal(data, out); err != nil {
+ // A *string target accepts a non-JSON 2xx body as raw text rather than
+ // failing to decode.
+ if text, ok := out.(*string); ok {
+ *text = string(data)
+ return nil
+ }
+ return fmt.Errorf("openwa: decoding response: %w", err)
+ }
+ return nil
+}
+
+// doRaw performs the request and returns the response body and Content-Type.
+// Any non-2xx status (including an unfollowed 3xx) is an error.
+func (c *Client) doRaw(ctx context.Context, method, path string, query url.Values, body any) ([]byte, string, error) {
var bodyBytes []byte
var reader io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
- return fmt.Errorf("openwa: encoding request body: %w", err)
+ return nil, "", fmt.Errorf("openwa: encoding request body: %w", err)
}
bodyBytes = b
reader = bytes.NewReader(b)
@@ -208,7 +240,7 @@ func (c *Client) do(ctx context.Context, method, path string, query url.Values,
req, err := http.NewRequestWithContext(ctx, method, rawURL, reader)
if err != nil {
- return fmt.Errorf("openwa: building request: %w", err)
+ return nil, "", fmt.Errorf("openwa: building request: %w", err)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
@@ -222,28 +254,22 @@ func (c *Client) do(ctx context.Context, method, path string, query url.Values,
resp, err := c.httpClient.Do(req)
if err != nil {
if isTimeout(err) {
- return &TimeoutError{Timeout: c.timeout, Err: err}
+ return nil, "", &TimeoutError{Timeout: c.timeout, Err: err}
}
- return fmt.Errorf("openwa: %s %s: %w", method, path, err)
+ return nil, "", fmt.Errorf("openwa: %s %s: %w", method, path, err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
- return fmt.Errorf("openwa: reading response body: %w", err)
+ return nil, "", fmt.Errorf("openwa: reading response body: %w", err)
}
// Any non-2xx (including an unfollowed 3xx) is an error.
if resp.StatusCode >= 300 {
- return parseAPIError(resp.StatusCode, data, method+" "+path)
- }
- if out == nil || resp.StatusCode == http.StatusNoContent || len(data) == 0 {
- return nil
+ return nil, "", parseAPIError(resp.StatusCode, data, method+" "+path)
}
- if err := json.Unmarshal(data, out); err != nil {
- return fmt.Errorf("openwa: decoding response: %w", err)
- }
- return nil
+ return data, resp.Header.Get("Content-Type"), nil
}
func isTimeout(err error) bool {
diff --git a/sdk/go/client_test.go b/sdk/go/client_test.go
index 9b8decdc4..d52487bd9 100644
--- a/sdk/go/client_test.go
+++ b/sdk/go/client_test.go
@@ -1047,3 +1047,229 @@ func TestCallReceivedPayloadDecodes(t *testing.T) {
t.Fatalf("call decode: %+v", p)
}
}
+
+func TestSendTextForwardsMentions(t *testing.T) {
+ rt := &recordTransport{status: 200, body: `{"messageId":"m1","timestamp":1}`}
+ c := newTestClient(t, rt)
+
+ if _, err := c.Messages.SendText(context.Background(), "s1", SendTextRequest{
+ ChatID: "[email protected]",
+ Text: "hi @628123",
+ Mentions: []string{"[email protected]"},
+ }); err != nil {
+ t.Fatalf("SendText: %v", err)
+ }
+
+ var sent map[string]any
+ if err := json.Unmarshal(rt.lastRaw, &sent); err != nil {
+ t.Fatalf("body not JSON: %v", err)
+ }
+ mentions, ok := sent["mentions"].([]any)
+ if !ok || len(mentions) != 1 || mentions[0] != "[email protected]" {
+ t.Fatalf("sent body = %v", sent)
+ }
+}
+
+func TestSendPollHitsCorrectPath(t *testing.T) {
+ rt := &recordTransport{status: 200, body: `{"messageId":"m2","timestamp":2}`}
+ c := newTestClient(t, rt)
+
+ res, err := c.Messages.SendPoll(context.Background(), "s1", SendPollRequest{
+ ChatID: "[email protected]",
+ Name: "Where?",
+ Options: []string{"Park", "Beach"},
+ AllowMultipleAnswers: Ptr(true),
+ })
+ if err != nil {
+ t.Fatalf("SendPoll: %v", err)
+ }
+ if res.MessageID != "m2" {
+ t.Fatalf("unexpected response: %+v", res)
+ }
+
+ wantPath := "/api/sessions/s1/messages/send-poll"
+ if got := rt.lastReq.URL.Path; got != wantPath {
+ t.Fatalf("path = %q, want %q", got, wantPath)
+ }
+ if rt.lastReq.Method != "POST" {
+ t.Fatalf("method = %q, want POST", rt.lastReq.Method)
+ }
+
+ var sent map[string]any
+ if err := json.Unmarshal(rt.lastRaw, &sent); err != nil {
+ t.Fatalf("body not JSON: %v", err)
+ }
+ if sent["name"] != "Where?" || sent["allowMultipleAnswers"] != true {
+ t.Fatalf("sent body = %v", sent)
+ }
+ options, ok := sent["options"].([]any)
+ if !ok || len(options) != 2 || options[0] != "Park" || options[1] != "Beach" {
+ t.Fatalf("sent options = %v", sent["options"])
+ }
+}
+
+func TestProfilePicturesBatchQuery(t *testing.T) {
+ rt := &recordTransport{status: 200, body: `{"pictures":{"[email protected]":"http://p/a","[email protected]":null}}`}
+ c := newTestClient(t, rt)
+
+ res, err := c.Contacts.ProfilePictures(context.Background(), "s1", []string{"[email protected]", "[email protected]"})
+ if err != nil {
+ t.Fatalf("ProfilePictures: %v", err)
+ }
+
+ if rt.lastReq.Method != "GET" {
+ t.Fatalf("method = %q, want GET", rt.lastReq.Method)
+ }
+ wantPath := "/api/sessions/s1/contacts/profile-pictures"
+ if got := rt.lastReq.URL.Path; got != wantPath {
+ t.Fatalf("path = %q, want %q", got, wantPath)
+ }
+ if got := rt.lastReq.URL.Query().Get("ids"); got != "[email protected],[email protected]" {
+ t.Fatalf("ids query = %q", got)
+ }
+
+ if res.Pictures["[email protected]"] == nil || *res.Pictures["[email protected]"] != "http://p/a" {
+ t.Fatalf("pictures[[email protected]] = %v", res.Pictures["[email protected]"])
+ }
+ if url, present := res.Pictures["[email protected]"]; !present || url != nil {
+ t.Fatalf("pictures[[email protected]] should decode as an explicit null, got %v (present=%v)", url, present)
+ }
+}
+
+func TestStatusMediaReturnsBytes(t *testing.T) {
+ rt := &recordTransport{
+ status: 200,
+ body: "PNG_BYTES",
+ header: http.Header{"Content-Type": []string{"image/png"}},
+ }
+ c := newTestClient(t, rt)
+
+ media, err := c.Status.Media(context.Background(), "s1", "w1")
+ if err != nil {
+ t.Fatalf("Media: %v", err)
+ }
+ if string(media.Data) != "PNG_BYTES" || media.ContentType != "image/png" {
+ t.Fatalf("media = %q (%q)", media.Data, media.ContentType)
+ }
+
+ wantPath := "/api/sessions/s1/status/w1/media"
+ if got := rt.lastReq.URL.Path; got != wantPath {
+ t.Fatalf("path = %q, want %q", got, wantPath)
+ }
+ if rt.lastReq.Method != "GET" {
+ t.Fatalf("method = %q, want GET", rt.lastReq.Method)
+ }
+}
+
+// A status with no stored media surfaces as 404.
+func TestStatusMediaNotFound(t *testing.T) {
+ rt := &recordTransport{
+ status: 404,
+ body: `{"statusCode":404,"message":"Status media not found or expired","error":"Not Found"}`,
+ }
+ c := newTestClient(t, rt)
+
+ _, err := c.Status.Media(context.Background(), "s1", "w1")
+ if !errors.Is(err, ErrNotFound) {
+ t.Fatalf("errors.Is ErrNotFound = false for %v", err)
+ }
+}
+
+// The escape hatch mirrors the JS/Python/PHP raw-text fallback for non-JSON
+// 2xx bodies: *[]byte takes the body verbatim, *string falls back to raw text,
+// and a typed target still requires JSON.
+func TestDoRawFallbacks(t *testing.T) {
+ ctx := context.Background()
+
+ t.Run("bytes take the body verbatim", func(t *testing.T) {
+ rt := &recordTransport{status: 200, body: "PNG_BYTES", header: http.Header{"Content-Type": []string{"image/png"}}}
+ c := newTestClient(t, rt)
+ var raw []byte
+ if err := c.Do(ctx, "GET", "/api/x", nil, nil, &raw); err != nil {
+ t.Fatalf("Do: %v", err)
+ }
+ if string(raw) != "PNG_BYTES" {
+ t.Fatalf("raw = %q", raw)
+ }
+ })
+
+ t.Run("string falls back to raw text on non-JSON", func(t *testing.T) {
+ rt := &recordTransport{status: 200, body: "plain text"}
+ c := newTestClient(t, rt)
+ var s string
+ if err := c.Do(ctx, "GET", "/api/x", nil, nil, &s); err != nil {
+ t.Fatalf("Do: %v", err)
+ }
+ if s != "plain text" {
+ t.Fatalf("s = %q", s)
+ }
+ })
+
+ t.Run("string still decodes a JSON string body", func(t *testing.T) {
+ rt := &recordTransport{status: 200, body: `"quoted"`}
+ c := newTestClient(t, rt)
+ var s string
+ if err := c.Do(ctx, "GET", "/api/x", nil, nil, &s); err != nil {
+ t.Fatalf("Do: %v", err)
+ }
+ if s != "quoted" {
+ t.Fatalf("s = %q", s)
+ }
+ })
+
+ t.Run("typed target still requires JSON", func(t *testing.T) {
+ rt := &recordTransport{status: 200, body: "plain text"}
+ c := newTestClient(t, rt)
+ var out MessageResponse
+ if err := c.Do(ctx, "GET", "/api/x", nil, nil, &out); err == nil {
+ t.Fatal("expected a decode error for a non-JSON body into a typed target")
+ }
+ })
+}
+
+// The filter value is polymorphic on the wire: a string for text fields, a
+// string array for id/enum fields, a bool for boolean fields, plus the
+// caseSensitive flag — all must serialize verbatim.
+func TestWebhookFiltersPolymorphicWireShape(t *testing.T) {
+ rt := &recordTransport{status: 200, body: `{"id":"w1"}`}
+ c := newTestClient(t, rt)
+
+ _, err := c.Webhooks.Create(context.Background(), "s1", CreateWebhookRequest{
+ URL: "https://example.com/hook",
+ Events: []string{EventMessageReceived},
+ Filters: &WebhookFilters{
+ Conditions: []WebhookFilterCondition{
+ {Field: "sender", Operator: "is", Value: []string{"[email protected]"}},
+ {Field: "body", Operator: "contains", Value: "invoice", CaseSensitive: Ptr(true)},
+ {Field: "isGroup", Operator: "is", Value: false},
+ },
+ },
+ })
+ if err != nil {
+ t.Fatalf("Create: %v", err)
+ }
+
+ var sent map[string]any
+ if err := json.Unmarshal(rt.lastRaw, &sent); err != nil {
+ t.Fatalf("body not JSON: %v", err)
+ }
+ conditions := sent["filters"].(map[string]any)["conditions"].([]any)
+ if len(conditions) != 3 {
+ t.Fatalf("conditions = %v", conditions)
+ }
+ first := conditions[0].(map[string]any)
+ if values, ok := first["value"].([]any); !ok || len(values) != 1 || values[0] != "[email protected]" {
+ t.Fatalf("id condition value = %v", first["value"])
+ }
+ second := conditions[1].(map[string]any)
+ if second["value"] != "invoice" || second["caseSensitive"] != true {
+ t.Fatalf("text condition = %v", second)
+ }
+ third := conditions[2].(map[string]any)
+ if third["value"] != false {
+ t.Fatalf("boolean condition value = %v", third["value"])
+ }
+ if _, present := first["caseSensitive"]; present {
+ t.Fatal("caseSensitive should be omitted when unset")
+ }
+}
diff --git a/sdk/go/contacts.go b/sdk/go/contacts.go
index 24891b769..334996861 100644
--- a/sdk/go/contacts.go
+++ b/sdk/go/contacts.go
@@ -1,6 +1,10 @@
package openwa
-import "context"
+import (
+ "context"
+ "net/url"
+ "strings"
+)
// ContactsService looks up and manages contacts.
// Backed by src/modules/contact/contact.controller.ts.
@@ -47,6 +51,19 @@ func (s *ContactsService) ProfilePicture(ctx context.Context, sessionID, contact
return &out, nil
}
+// ProfilePictures batch-resolves profile picture URLs for up to 50 contacts
+// in one request. The result maps each requested id to its URL (nil when the
+// lookup failed).
+func (s *ContactsService) ProfilePictures(ctx context.Context, sessionID string, ids []string) (*ProfilePicturesResponse, error) {
+ var out ProfilePicturesResponse
+ q := url.Values{"ids": []string{strings.Join(ids, ",")}}
+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/profile-pictures", q, nil, &out)
+ if err != nil {
+ return nil, err
+ }
+ return &out, nil
+}
+
// Phone resolves a contact's phone number.
func (s *ContactsService) Phone(ctx context.Context, sessionID, contactID string) (*ContactPhoneResponse, error) {
var out ContactPhoneResponse
diff --git a/sdk/go/messages.go b/sdk/go/messages.go
index 24f9bfa78..f1b2cbd74 100644
--- a/sdk/go/messages.go
+++ b/sdk/go/messages.go
@@ -66,6 +66,11 @@ func (s *MessagesService) SendTemplate(ctx context.Context, sessionID string, bo
return s.send(ctx, sessionID, "send-template", body)
}
+// SendPoll sends a native WhatsApp poll (2–12 options).
+func (s *MessagesService) SendPoll(ctx context.Context, sessionID string, body SendPollRequest) (*MessageResponse, error) {
+ return s.send(ctx, sessionID, "send-poll", body)
+}
+
func (s *MessagesService) send(ctx context.Context, sessionID, segment string, body any) (*MessageResponse, error) {
var out MessageResponse
err := s.client.do(ctx, "POST", s.base(sessionID)+"/"+segment, nil, body, &out)
diff --git a/sdk/go/routing_test.go b/sdk/go/routing_test.go
index 9e2a3aa3b..6c360cd77 100644
--- a/sdk/go/routing_test.go
+++ b/sdk/go/routing_test.go
@@ -38,6 +38,7 @@ func TestRouting(t *testing.T) {
{"Messages.SendLocation", func(c *Client) { c.Messages.SendLocation(ctx, "s1", SendLocationRequest{}) }, "POST", "/api/sessions/s1/messages/send-location"},
{"Messages.SendContact", func(c *Client) { c.Messages.SendContact(ctx, "s1", SendContactRequest{}) }, "POST", "/api/sessions/s1/messages/send-contact"},
{"Messages.SendTemplate", func(c *Client) { c.Messages.SendTemplate(ctx, "s1", SendTemplateRequest{}) }, "POST", "/api/sessions/s1/messages/send-template"},
+ {"Messages.SendPoll", func(c *Client) { c.Messages.SendPoll(ctx, "s1", SendPollRequest{}) }, "POST", "/api/sessions/s1/messages/send-poll"},
{"Messages.Reply", func(c *Client) { c.Messages.Reply(ctx, "s1", ReplyMessageRequest{}) }, "POST", "/api/sessions/s1/messages/reply"},
{"Messages.Forward", func(c *Client) { c.Messages.Forward(ctx, "s1", ForwardMessageRequest{}) }, "POST", "/api/sessions/s1/messages/forward"},
{"Messages.React", func(c *Client) { c.Messages.React(ctx, "s1", ReactMessageRequest{}) }, "POST", "/api/sessions/s1/messages/react"},
@@ -53,6 +54,7 @@ func TestRouting(t *testing.T) {
{"Contacts.Get", func(c *Client) { c.Contacts.Get(ctx, "s1", "u1") }, "GET", "/api/sessions/s1/contacts/u1"},
{"Contacts.Check", func(c *Client) { c.Contacts.Check(ctx, "s1", "628") }, "GET", "/api/sessions/s1/contacts/check/628"},
{"Contacts.ProfilePicture", func(c *Client) { c.Contacts.ProfilePicture(ctx, "s1", "u1") }, "GET", "/api/sessions/s1/contacts/u1/profile-picture"},
+ {"Contacts.ProfilePictures", func(c *Client) { c.Contacts.ProfilePictures(ctx, "s1", []string{"u1"}) }, "GET", "/api/sessions/s1/contacts/profile-pictures"},
{"Contacts.Phone", func(c *Client) { c.Contacts.Phone(ctx, "s1", "u1") }, "GET", "/api/sessions/s1/contacts/u1/phone"},
{"Contacts.Block", func(c *Client) { c.Contacts.Block(ctx, "s1", "u1") }, "POST", "/api/sessions/s1/contacts/u1/block"},
{"Contacts.Unblock", func(c *Client) { c.Contacts.Unblock(ctx, "s1", "u1") }, "DELETE", "/api/sessions/s1/contacts/u1/block"},
@@ -88,6 +90,7 @@ 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"},
+ {"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"},
{"Status.SendImage", func(c *Client) { c.Status.SendImage(ctx, "s1", SendImageStatusRequest{}) }, "POST", "/api/sessions/s1/status/send-image"},
{"Status.SendVideo", func(c *Client) { c.Status.SendVideo(ctx, "s1", SendVideoStatusRequest{}) }, "POST", "/api/sessions/s1/status/send-video"},
diff --git a/sdk/go/status.go b/sdk/go/status.go
index 66d174d23..0ee973a9c 100644
--- a/sdk/go/status.go
+++ b/sdk/go/status.go
@@ -27,6 +27,16 @@ func (s *StatusService) FromContact(ctx context.Context, sessionID, contactID st
return out.Statuses, err
}
+// Media fetches the stored media bytes for a status update. The server
+// answers 404 when no media is stored (text status, omitted, or expired).
+func (s *StatusService) Media(ctx context.Context, sessionID, statusID string) (*StatusMedia, error) {
+ data, contentType, err := s.client.doRaw(ctx, "GET", s.base(sessionID)+"/"+pathEscape(statusID)+"/media", nil, nil)
+ if err != nil {
+ return nil, err
+ }
+ return &StatusMedia{Data: data, ContentType: contentType}, nil
+}
+
// SendText posts a text status.
func (s *StatusService) SendText(ctx context.Context, sessionID string, body SendTextStatusRequest) (*StatusResult, error) {
return s.send(ctx, sessionID, "/send-text", body)
diff --git a/sdk/go/types_contact.go b/sdk/go/types_contact.go
index 86b8cdb1c..5e3ce8ee3 100644
--- a/sdk/go/types_contact.go
+++ b/sdk/go/types_contact.go
@@ -24,6 +24,12 @@ type ProfilePictureResponse struct {
URL *string `json:"url,omitempty"`
}
+// ProfilePicturesResponse is a batch profile-picture lookup: a map of contact
+// id → picture URL (null when the lookup failed).
+type ProfilePicturesResponse struct {
+ Pictures map[string]*string `json:"pictures"`
+}
+
// ContactPhoneResponse resolves a contact's phone number.
type ContactPhoneResponse struct {
ContactID string `json:"contactId"`
diff --git a/sdk/go/types_message.go b/sdk/go/types_message.go
index bf6ed5566..08048cadd 100644
--- a/sdk/go/types_message.go
+++ b/sdk/go/types_message.go
@@ -12,6 +12,9 @@ type MessageResponse struct {
type SendTextRequest struct {
ChatID string `json:"chatId"`
Text string `json:"text"`
+ // Mentions lists WIDs to @mention (e.g. ["[email protected]"]). The text must
+ // also contain the @<number> token.
+ Mentions []string `json:"mentions,omitempty"`
}
// SendMediaRequest sends image/video/document/sticker media. Provide exactly
@@ -62,6 +65,17 @@ type SendTemplateRequest struct {
Vars map[string]string `json:"vars,omitempty"`
}
+// SendPollRequest sends a native WhatsApp poll. Options holds the choices to
+// vote on (WhatsApp allows between 2 and 12).
+type SendPollRequest struct {
+ ChatID string `json:"chatId"`
+ // Name is the poll question / title (max 255 chars).
+ Name string `json:"name"`
+ Options []string `json:"options"`
+ // AllowMultipleAnswers lets voters pick several options (default single choice).
+ AllowMultipleAnswers *bool `json:"allowMultipleAnswers,omitempty"`
+}
+
// ReplyMessageRequest replies to a quoted message.
type ReplyMessageRequest struct {
ChatID string `json:"chatId"`
diff --git a/sdk/go/types_status.go b/sdk/go/types_status.go
index b332d71f7..8bf8ec3c3 100644
--- a/sdk/go/types_status.go
+++ b/sdk/go/types_status.go
@@ -39,6 +39,14 @@ type StatusResult struct {
ExpiresAt time.Time `json:"expiresAt,omitempty"`
}
+// StatusMedia is the one non-JSON shape on the wire: the raw bytes of a stored
+// status media file plus the Content-Type the server served them as. Returned
+// by StatusService.Media; a 404 surfaces when no media is stored.
+type StatusMedia struct {
+ Data []byte
+ ContentType string
+}
+
// SendTextStatusRequest posts a text status. Recipients is required on the Baileys
// engine only (absent/empty → 400 there); whatsapp-web.js ignores it — leave nil.
type SendTextStatusRequest struct {
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
index 1729589e2..c3016f7e5 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
@@ -1,8 +1,10 @@
package com.rmyndharis.openwa;
import com.google.gson.Gson;
+import com.google.gson.JsonParseException;
import com.rmyndharis.openwa.errors.OpenWAApiError;
import com.rmyndharis.openwa.errors.OpenWAError;
+import com.rmyndharis.openwa.http.BinaryResponse;
import com.rmyndharis.openwa.http.DefaultHttpTransport;
import com.rmyndharis.openwa.http.Http;
import com.rmyndharis.openwa.http.HttpMethod;
@@ -27,6 +29,7 @@ import com.rmyndharis.openwa.resources.TemplatesResource;
import com.rmyndharis.openwa.resources.WebhooksResource;
import java.io.IOException;
import java.lang.reflect.Array;
+import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
@@ -80,25 +83,56 @@ public final class OpenWAClient {
// ── Internal request API used by all resources ─────────────────────
- /** Issue a request and deserialize a single object (or {@code null} for 204/empty). */
+ /**
+ * Issue a request and deserialize a single object (or {@code null} for 204/empty).
+ *
+ * <p>A {@code String} target receives a non-JSON 2xx body as raw text — the same
+ * fallback the JS/Python/PHP transports apply. For any other target the body must
+ * be JSON; a non-JSON body surfaces as a tidy {@link OpenWAError}, never a raw
+ * Gson exception.
+ */
+ @SuppressWarnings("unchecked")
public <T> T request(HttpMethod method, String path, Object query, Object body, Class<T> type) {
HttpResponseData res = execute(method, path, query, body);
- if (res.status() == 204 || res.body() == null || res.body().isEmpty()) {
+ String text = utf8(res.body());
+ if (res.status() == 204 || text.isEmpty()) {
return null;
}
- return gson.fromJson(res.body(), type);
+ if (type == String.class) {
+ // A String target mirrors the JS/Python/PHP raw-text fallback: decode a
+ // JSON string body, accept a non-JSON 2xx body as the raw text.
+ try {
+ T parsed = gson.fromJson(text, type);
+ if (parsed != null) {
+ return parsed;
+ }
+ } catch (JsonParseException ignore) {
+ // fall through to the raw text
+ }
+ return (T) text;
+ }
+ try {
+ return gson.fromJson(text, type);
+ } catch (JsonParseException e) {
+ throw new OpenWAError("Non-JSON response — " + method + " " + path);
+ }
}
/** Issue a request and deserialize a JSON array into a {@code List} (empty for 204/empty). */
@SuppressWarnings("unchecked")
public <T> List<T> requestList(HttpMethod method, String path, Object query, Object body, Class<T> elementType) {
HttpResponseData res = execute(method, path, query, body);
- if (res.status() == 204 || res.body() == null || res.body().isEmpty()) {
+ String text = utf8(res.body());
+ if (res.status() == 204 || text.isEmpty()) {
return List.of();
}
Class<T[]> arrayType = (Class<T[]>) Array.newInstance(elementType, 0).getClass();
- T[] arr = gson.fromJson(res.body(), arrayType);
- return arr == null ? List.of() : List.of(arr);
+ try {
+ T[] arr = gson.fromJson(text, arrayType);
+ return arr == null ? List.of() : List.of(arr);
+ } catch (JsonParseException e) {
+ throw new OpenWAError("Non-JSON response — " + method + " " + path);
+ }
}
/** Issue a request that returns no body. */
@@ -106,6 +140,30 @@ public final class OpenWAClient {
execute(method, path, query, body);
}
+ /**
+ * Issue a request for a non-JSON (binary) 2xx body — e.g. stored status media —
+ * and return the raw bytes plus the served Content-Type. A 204/empty body yields
+ * empty data and a {@code null} content type.
+ */
+ public BinaryResponse requestBytes(HttpMethod method, String path, Object query) {
+ HttpResponseData res = execute(method, path, query, null);
+ if (res.status() == 204 || res.body() == null || res.body().length == 0) {
+ return new BinaryResponse(new byte[0], null);
+ }
+ String contentType = null;
+ for (Map.Entry<String, List<String>> e : res.headers().entrySet()) {
+ if ("content-type".equalsIgnoreCase(e.getKey()) && !e.getValue().isEmpty()) {
+ contentType = e.getValue().get(0);
+ break;
+ }
+ }
+ return new BinaryResponse(res.body(), contentType);
+ }
+
+ private static String utf8(byte[] body) {
+ return body == null ? "" : new String(body, StandardCharsets.UTF_8);
+ }
+
private HttpResponseData execute(HttpMethod method, String path, Object query, Object body) {
String url = Http.buildUrl(config.baseUrl, path, query, gson);
Map<String, String> headers = Http.mergeHeaders(config.defaultHeaders, null, config.apiKey);
@@ -126,7 +184,7 @@ public final class OpenWAClient {
throw new OpenWAError("Invalid request — " + method + " " + path + ": " + e.getMessage());
}
if (res.status() < 200 || res.status() >= 300) {
- throw OpenWAApiError.fromResponse(res.status(), "", res.body(), method + " " + path);
+ throw OpenWAApiError.fromResponse(res.status(), "", utf8(res.body()), method + " " + path);
}
return res;
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/http/BinaryResponse.java b/sdk/java/src/main/java/com/rmyndharis/openwa/http/BinaryResponse.java
new file mode 100644
index 000000000..ee09d422d
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/http/BinaryResponse.java
@@ -0,0 +1,8 @@
+package com.rmyndharis.openwa.http;
+
+/**
+ * A binary (non-JSON) 2xx body, e.g. the stored status media bytes: the raw
+ * payload plus the Content-Type the server served it as ({@code null} when the
+ * response carried no Content-Type header or was empty).
+ */
+public record BinaryResponse(byte[] data, String contentType) {}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/http/DefaultHttpTransport.java b/sdk/java/src/main/java/com/rmyndharis/openwa/http/DefaultHttpTransport.java
index 2ef808724..8d42adb59 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/http/DefaultHttpTransport.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/http/DefaultHttpTransport.java
@@ -24,7 +24,7 @@ public final class DefaultHttpTransport implements HttpTransport {
.method(req.method().name(), pub);
req.headers().forEach(b::header);
try {
- HttpResponse<String> res = client.send(b.build(), HttpResponse.BodyHandlers.ofString());
+ HttpResponse<byte[]> res = client.send(b.build(), HttpResponse.BodyHandlers.ofByteArray());
return new HttpResponseData(res.statusCode(), res.headers().map(), res.body());
} catch (HttpTimeoutException e) {
throw new OpenWATimeoutError(req.timeout().toMillis());
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/http/HttpResponseData.java b/sdk/java/src/main/java/com/rmyndharis/openwa/http/HttpResponseData.java
index 92fd017c1..0c970a831 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/http/HttpResponseData.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/http/HttpResponseData.java
@@ -3,5 +3,10 @@ package com.rmyndharis.openwa.http;
import java.util.List;
import java.util.Map;
-/** A raw response: status, headers, and the undecoded body text. */
-public record HttpResponseData(int status, Map<String, List<String>> headers, String body) {}
+/**
+ * A raw response: status, headers, and the undecoded body bytes. Bytes (not a
+ * decoded String) so binary payloads — e.g. a stored status media stream —
+ * survive the transport without charset corruption; the client decodes UTF-8
+ * only on the JSON/text paths.
+ */
+public record HttpResponseData(int status, Map<String, List<String>> headers, byte[] body) {}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ProfilePicturesResponse.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ProfilePicturesResponse.java
new file mode 100644
index 000000000..aa8c755bb
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ProfilePicturesResponse.java
@@ -0,0 +1,6 @@
+package com.rmyndharis.openwa.model;
+
+import java.util.Map;
+
+/** Batch profile-picture lookup: a map of contact id → picture URL (null when the lookup failed). */
+public record ProfilePicturesResponse(Map<String, String> pictures) {}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendPollRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendPollRequest.java
new file mode 100644
index 000000000..06f5dc833
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendPollRequest.java
@@ -0,0 +1,44 @@
+package com.rmyndharis.openwa.model;
+
+import java.util.List;
+
+/** Request body for sending a native WhatsApp poll (2–12 options). */
+public record SendPollRequest(String chatId, String name, List<String> options, Boolean allowMultipleAnswers) {
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static final class Builder {
+ private String chatId;
+ private String name;
+ private List<String> options;
+ private Boolean allowMultipleAnswers;
+
+ public Builder chatId(String v) {
+ this.chatId = v;
+ return this;
+ }
+
+ /** Poll question / title (max 255 chars). */
+ public Builder name(String v) {
+ this.name = v;
+ return this;
+ }
+
+ /** Options to vote on (WhatsApp allows between 2 and 12). */
+ public Builder options(List<String> v) {
+ this.options = v;
+ return this;
+ }
+
+ /** Allow voters to pick several options (default single choice). */
+ public Builder allowMultipleAnswers(Boolean v) {
+ this.allowMultipleAnswers = v;
+ return this;
+ }
+
+ public SendPollRequest build() {
+ return new SendPollRequest(chatId, name, options, allowMultipleAnswers);
+ }
+ }
+}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTextRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTextRequest.java
index d1b7e523f..10952204d 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTextRequest.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTextRequest.java
@@ -1,7 +1,14 @@
package com.rmyndharis.openwa.model;
+import java.util.List;
+
/** Request body for sending a text message. */
-public record SendTextRequest(String chatId, String text) {
+public record SendTextRequest(String chatId, String text, List<String> mentions) {
+ /** Back-compatible constructor without mentions. */
+ public SendTextRequest(String chatId, String text) {
+ this(chatId, text, null);
+ }
+
public static Builder builder() {
return new Builder();
}
@@ -9,6 +16,7 @@ public record SendTextRequest(String chatId, String text) {
public static final class Builder {
private String chatId;
private String text;
+ private List<String> mentions;
public Builder chatId(String v) {
this.chatId = v;
@@ -21,8 +29,14 @@ public record SendTextRequest(String chatId, String text) {
return this;
}
+ /** WIDs to @mention (e.g. {@code ["[email protected]"]}). The text must also contain the {@code @<number>} token. */
+ public Builder mentions(List<String> v) {
+ this.mentions = v;
+ return this;
+ }
+
public SendTextRequest build() {
- return new SendTextRequest(chatId, text);
+ return new SendTextRequest(chatId, text, mentions);
}
}
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookFilterCondition.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookFilterCondition.java
index c2170001c..79fc7784e 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookFilterCondition.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookFilterCondition.java
@@ -2,5 +2,17 @@ package com.rmyndharis.openwa.model;
import java.util.List;
-/** A single condition evaluated against an event before delivery. */
-public record WebhookFilterCondition(String field, String operator, List<String> value) {}
+/**
+ * A single condition evaluated against an event before delivery.
+ *
+ * <p>{@code value} is polymorphic per field kind: a {@link String} (text fields),
+ * a {@code List<String>} (id/idArray/enum fields), or a {@link Boolean} (boolean
+ * fields). {@code caseSensitive} only applies to text fields
+ * ({@code contains}/{@code equals}) and defaults to false when {@code null}.
+ */
+public record WebhookFilterCondition(String field, String operator, Object value, Boolean caseSensitive) {
+ /** Back-compatible constructor: id/enum value list, no caseSensitivity. */
+ public WebhookFilterCondition(String field, String operator, List<String> value) {
+ this(field, operator, (Object) value, null);
+ }
+}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ContactsResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ContactsResource.java
index f12d5eed8..2cb3ea508 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ContactsResource.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ContactsResource.java
@@ -9,8 +9,10 @@ import com.rmyndharis.openwa.model.ContactPhoneResponse;
import com.rmyndharis.openwa.model.ContactRecord;
import com.rmyndharis.openwa.model.ListContactsQuery;
import com.rmyndharis.openwa.model.ProfilePictureResponse;
+import com.rmyndharis.openwa.model.ProfilePicturesResponse;
import com.rmyndharis.openwa.model.SuccessResult;
import java.util.List;
+import java.util.Map;
/** Contacts resource — contact lookup and management. */
public final class ContactsResource {
@@ -60,6 +62,19 @@ public final class ContactsResource {
ProfilePictureResponse.class);
}
+ /**
+ * Batch-resolve profile picture URLs for up to 50 contacts in one request.
+ * Returns a map of contact id → URL (null when a lookup fails).
+ */
+ public ProfilePicturesResponse profilePictures(String sessionId, List<String> ids) {
+ return client.request(
+ HttpMethod.GET,
+ "/api/sessions/" + encodeSegment(sessionId) + "/contacts/profile-pictures",
+ Map.of("ids", String.join(",", ids)),
+ null,
+ ProfilePicturesResponse.class);
+ }
+
/** Resolve a contact id (e.g. a {@code @lid}) to a phone number. */
public ContactPhoneResponse phone(String sessionId, String contactId) {
return client.request(
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 2f2176831..0c698ab79 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
@@ -22,6 +22,7 @@ import com.rmyndharis.openwa.model.SendContactRequest;
import com.rmyndharis.openwa.model.SendLocationRequest;
import com.rmyndharis.openwa.model.SendMediaRequest;
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.SuccessResult;
@@ -114,6 +115,16 @@ public final class MessagesResource {
MessageResponse.class);
}
+ /** Send a native WhatsApp poll (2–12 options). */
+ public MessageResponse sendPoll(String sessionId, SendPollRequest body) {
+ return client.request(
+ HttpMethod.POST,
+ "/api/sessions/" + encodeSegment(sessionId) + "/messages/send-poll",
+ null,
+ body,
+ MessageResponse.class);
+ }
+
/** Reply to a specific message. */
public MessageResponse reply(String sessionId, ReplyMessageRequest body) {
return client.request(
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/StatusResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/StatusResource.java
index a08f8547e..a5520396c 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/StatusResource.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/StatusResource.java
@@ -3,6 +3,7 @@ package com.rmyndharis.openwa.resources;
import static com.rmyndharis.openwa.http.Http.encodeSegment;
import com.rmyndharis.openwa.OpenWAClient;
+import com.rmyndharis.openwa.http.BinaryResponse;
import com.rmyndharis.openwa.http.HttpMethod;
import com.rmyndharis.openwa.model.SendImageStatusRequest;
import com.rmyndharis.openwa.model.SendTextStatusRequest;
@@ -42,6 +43,14 @@ public final class StatusResource {
StatusListResult.class);
}
+ /** Fetch the stored media bytes for a status update (404 when there is no stored media). */
+ public BinaryResponse media(String sessionId, String statusId) {
+ return client.requestBytes(
+ HttpMethod.GET,
+ "/api/sessions/" + encodeSegment(sessionId) + "/status/" + encodeSegment(statusId) + "/media",
+ null);
+ }
+
/** Post a text status update. */
public StatusResult sendText(String sessionId, SendTextStatusRequest body) {
return client.request(
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/ClientTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/ClientTest.java
index af2fd9483..b27afa282 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/ClientTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/ClientTest.java
@@ -1,14 +1,20 @@
package com.rmyndharis.openwa;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import com.rmyndharis.openwa.errors.OpenWAError;
import com.rmyndharis.openwa.errors.OpenWANotFoundError;
+import com.rmyndharis.openwa.http.BinaryResponse;
import com.rmyndharis.openwa.http.HttpMethod;
import com.rmyndharis.openwa.model.SuccessResult;
import com.rmyndharis.openwa.support.MockTransport;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
import org.junit.jupiter.api.Test;
class ClientTest {
@@ -55,4 +61,40 @@ class ClientTest {
SuccessResult r = client.request(HttpMethod.DELETE, "/api/x", null, null, SuccessResult.class);
assertNull(r);
}
+
+ @Test
+ void nonJson2xxFallsBackToRawTextForStringTargets() {
+ tx.respond(200, "plain text");
+ String r = client.request(HttpMethod.GET, "/api/x", null, null, String.class);
+ assertEquals("plain text", r);
+ }
+
+ @Test
+ void nonJson2xxForTypedTargetsThrowsTidySdkError() {
+ tx.respond(200, "plain text");
+ // Must surface the SDK's own error type — a raw Gson JsonSyntaxException
+ // leaking to callers is the bug this guards.
+ OpenWAError e = assertThrows(OpenWAError.class,
+ () -> client.request(HttpMethod.GET, "/api/x", null, null, SuccessResult.class));
+ assertEquals(OpenWAError.class, e.getClass());
+ }
+
+ @Test
+ void requestBytesReturnsRawBodyAndContentType() {
+ tx.respondRaw(
+ 200,
+ "PNG_BYTES".getBytes(StandardCharsets.UTF_8),
+ Map.of("content-type", List.of("image/png")));
+ BinaryResponse r = client.requestBytes(HttpMethod.GET, "/api/x", null);
+ assertArrayEquals("PNG_BYTES".getBytes(StandardCharsets.UTF_8), r.data());
+ assertEquals("image/png", r.contentType());
+ }
+
+ @Test
+ void requestBytes204ReturnsEmptyData() {
+ tx.respond(204, "");
+ BinaryResponse r = client.requestBytes(HttpMethod.GET, "/api/x", null);
+ assertEquals(0, r.data().length);
+ assertNull(r.contentType());
+ }
}
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ContactsResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ContactsResourceTest.java
index 191399031..f443ea8c0 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ContactsResourceTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ContactsResourceTest.java
@@ -1,12 +1,16 @@
package com.rmyndharis.openwa.resources;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.rmyndharis.openwa.ClientConfig;
import com.rmyndharis.openwa.OpenWAClient;
import com.rmyndharis.openwa.http.HttpMethod;
import com.rmyndharis.openwa.model.ListContactsQuery;
+import com.rmyndharis.openwa.model.ProfilePicturesResponse;
import com.rmyndharis.openwa.support.MockTransport;
+import java.util.List;
import org.junit.jupiter.api.Test;
class ContactsResourceTest {
@@ -54,6 +58,19 @@ class ContactsResourceTest {
assertEquals(HttpMethod.GET, tx.lastRequest().method());
}
+ @Test
+ void profilePicturesBatchResolvesIdsQuery() {
+ tx.respond(200, "{\"pictures\":{\"[email protected]\":\"http://p/a\",\"[email protected]\":null}}");
+ ProfilePicturesResponse res = client.contacts.profilePictures("s", List.of("[email protected]", "[email protected]"));
+ assertEquals(
+ "http://h/api/sessions/s/contacts/profile-pictures?ids=a%40c.us%2Cb%40c.us",
+ tx.lastRequest().url());
+ assertEquals(HttpMethod.GET, tx.lastRequest().method());
+ assertEquals("http://p/a", res.pictures().get("[email protected]"));
+ assertTrue(res.pictures().containsKey("[email protected]"));
+ assertNull(res.pictures().get("[email protected]"));
+ }
+
@Test
void phoneHitsPath() {
tx.respond(200, "{\"contactId\":\"a@lid\",\"phone\":null}");
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 d421aeef7..0326a5768 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
@@ -21,6 +21,7 @@ import com.rmyndharis.openwa.model.SendContactRequest;
import com.rmyndharis.openwa.model.SendLocationRequest;
import com.rmyndharis.openwa.model.SendMediaRequest;
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.support.MockTransport;
@@ -59,6 +60,37 @@ class MessagesResourceTest {
assertTrue(tx.lastRequest().body().contains("hello-text"));
}
+ @Test
+ void sendTextForwardsMentionsVerbatim() {
+ tx.respond(200, MSG);
+ client.messages.sendText(
+ "s",
+ SendTextRequest.builder()
+ .chatId("[email protected]")
+ .text("hi @628123")
+ .mentions(List.of("[email protected]"))
+ .build());
+ assertTrue(tx.lastRequest().body().contains("\"mentions\":[\"[email protected]\"]"));
+ }
+
+ @Test
+ void sendPollResolvesToSendPollPath() {
+ tx.respond(200, MSG);
+ client.messages.sendPoll(
+ "s",
+ SendPollRequest.builder()
+ .chatId("[email protected]")
+ .name("Where?")
+ .options(List.of("Park", "Beach"))
+ .allowMultipleAnswers(true)
+ .build());
+ assertEquals("http://h/api/sessions/s/messages/send-poll", tx.lastRequest().url());
+ assertEquals(HttpMethod.POST, tx.lastRequest().method());
+ assertTrue(tx.lastRequest().body().contains("\"name\":\"Where?\""));
+ assertTrue(tx.lastRequest().body().contains("\"options\":[\"Park\",\"Beach\"]"));
+ assertTrue(tx.lastRequest().body().contains("\"allowMultipleAnswers\":true"));
+ }
+
@Test
void sendImageResolvesToSendImagePath() {
tx.respond(200, MSG);
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/StatusResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/StatusResourceTest.java
index b4a89b8ec..eb219449f 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/StatusResourceTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/StatusResourceTest.java
@@ -1,10 +1,14 @@
package com.rmyndharis.openwa.resources;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.rmyndharis.openwa.ClientConfig;
import com.rmyndharis.openwa.OpenWAClient;
+import com.rmyndharis.openwa.errors.OpenWANotFoundError;
+import com.rmyndharis.openwa.http.BinaryResponse;
import com.rmyndharis.openwa.http.HttpMethod;
import com.rmyndharis.openwa.model.SendImageStatusRequest;
import com.rmyndharis.openwa.model.SendTextStatusRequest;
@@ -12,7 +16,9 @@ import com.rmyndharis.openwa.model.SendVideoStatusRequest;
import com.rmyndharis.openwa.model.StatusMediaInput;
import com.rmyndharis.openwa.model.StatusRecord;
import com.rmyndharis.openwa.support.MockTransport;
+import java.nio.charset.StandardCharsets;
import java.util.List;
+import java.util.Map;
import org.junit.jupiter.api.Test;
class StatusResourceTest {
@@ -118,4 +124,23 @@ class StatusResourceTest {
assertEquals("http://h/api/sessions/s/status/status%2F1", tx.lastRequest().url());
assertEquals(HttpMethod.DELETE, tx.lastRequest().method());
}
+
+ @Test
+ void mediaReturnsStoredBytes() {
+ tx.respondRaw(
+ 200,
+ "PNG_BYTES".getBytes(StandardCharsets.UTF_8),
+ Map.of("content-type", List.of("image/png")));
+ BinaryResponse media = status.media("s", "w1");
+ assertEquals("http://h/api/sessions/s/status/w1/media", tx.lastRequest().url());
+ assertEquals(HttpMethod.GET, tx.lastRequest().method());
+ assertArrayEquals("PNG_BYTES".getBytes(StandardCharsets.UTF_8), media.data());
+ assertEquals("image/png", media.contentType());
+ }
+
+ @Test
+ void media404MapsToNotFoundError() {
+ tx.respond(404, "{\"statusCode\":404,\"message\":\"Status media not found or expired\",\"error\":\"Not Found\"}");
+ assertThrows(OpenWANotFoundError.class, () -> status.media("s", "w1"));
+ }
}
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/WebhooksResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/WebhooksResourceTest.java
index 8d7db31d8..01194034b 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/WebhooksResourceTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/WebhooksResourceTest.java
@@ -9,6 +9,8 @@ import com.rmyndharis.openwa.http.HttpMethod;
import com.rmyndharis.openwa.model.CreateWebhookRequest;
import com.rmyndharis.openwa.model.UpdateWebhookRequest;
import com.rmyndharis.openwa.model.WebhookEvent;
+import com.rmyndharis.openwa.model.WebhookFilterCondition;
+import com.rmyndharis.openwa.model.WebhookFilters;
import com.rmyndharis.openwa.support.MockTransport;
import java.util.List;
import org.junit.jupiter.api.Test;
@@ -95,4 +97,26 @@ class WebhooksResourceTest {
assertTrue(tx.lastRequest().body().contains("group.update"));
assertTrue(tx.lastRequest().body().contains("call.received"));
}
+
+ @Test
+ void createSerializesPolymorphicFilterValues() {
+ tx.respond(200, WEBHOOK_JSON);
+ // The filter value is polymorphic on the wire: string list (id/enum
+ // fields), single string (text fields, optionally caseSensitive), and
+ // boolean (boolean fields).
+ client.webhooks.create(
+ "s",
+ CreateWebhookRequest.builder()
+ .url("https://example.test/hook")
+ .filters(new WebhookFilters(List.of(
+ new WebhookFilterCondition("sender", "is", List.of("[email protected]")),
+ new WebhookFilterCondition("body", "contains", "invoice", true),
+ new WebhookFilterCondition("isGroup", "is", false, null))))
+ .build());
+ String body = tx.lastRequest().body();
+ assertTrue(body.contains("\"value\":[\"[email protected]\"]"), body);
+ assertTrue(body.contains("\"value\":\"invoice\""), body);
+ assertTrue(body.contains("\"caseSensitive\":true"), body);
+ assertTrue(body.contains("\"value\":false"), body);
+ }
}
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/support/MockTransport.java b/sdk/java/src/test/java/com/rmyndharis/openwa/support/MockTransport.java
index bbcc8dbd6..138b6644e 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/support/MockTransport.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/support/MockTransport.java
@@ -3,6 +3,7 @@ package com.rmyndharis.openwa.support;
import com.rmyndharis.openwa.http.HttpRequestData;
import com.rmyndharis.openwa.http.HttpResponseData;
import com.rmyndharis.openwa.http.HttpTransport;
+import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
@@ -10,11 +11,21 @@ import java.util.Map;
public final class MockTransport implements HttpTransport {
private HttpRequestData last;
private int status = 200;
- private String body = "";
+ private byte[] body = new byte[0];
+ private Map<String, List<String>> headers = Map.of();
public MockTransport respond(int status, String jsonBody) {
this.status = status;
- this.body = jsonBody;
+ this.body = jsonBody.getBytes(StandardCharsets.UTF_8);
+ this.headers = Map.of();
+ return this;
+ }
+
+ /** Respond with a raw (non-JSON) body and explicit headers — e.g. a binary media stream. */
+ public MockTransport respondRaw(int status, byte[] body, Map<String, List<String>> headers) {
+ this.status = status;
+ this.body = body;
+ this.headers = headers;
return this;
}
@@ -25,6 +36,6 @@ public final class MockTransport implements HttpTransport {
@Override
public HttpResponseData send(HttpRequestData request) {
this.last = request;
- return new HttpResponseData(status, Map.<String, List<String>>of(), body);
+ return new HttpResponseData(status, headers, body);
}
}
diff --git a/sdk/javascript/src/client.ts b/sdk/javascript/src/client.ts
index 96a513a30..caaa43d6e 100644
--- a/sdk/javascript/src/client.ts
+++ b/sdk/javascript/src/client.ts
@@ -23,7 +23,7 @@
* @packageDocumentation
*/
-import { request, encodeSegment, warnIfInsecureHttpUrl, type ClientConfig, type FetchLike, type RequestOptions } from './http.js';
+import { request, requestBytes, encodeSegment, warnIfInsecureHttpUrl, type BinaryResponse, type ClientConfig, type FetchLike, type RequestOptions } from './http.js';
import { CallsResource } from './resources/calls.js';
import { CatalogResource } from './resources/catalog.js';
import { ChannelsResource } from './resources/channels.js';
@@ -104,6 +104,11 @@ export class OpenWAClient {
return request<T>(this.config, options);
}
+ /** Issue a raw request expecting a non-JSON (binary) body. (Public for advanced use.) */
+ requestBytes(options: RequestOptions): Promise<BinaryResponse> {
+ return requestBytes(this.config, options);
+ }
+
/**
* Shared transport helper for image/video/audio/document/sticker sends. Public resource methods
* expose the narrower per-route request types (including audio-only `ptt`).
diff --git a/sdk/javascript/src/http.ts b/sdk/javascript/src/http.ts
index db1438278..eafbe8fe2 100644
--- a/sdk/javascript/src/http.ts
+++ b/sdk/javascript/src/http.ts
@@ -75,6 +75,54 @@ export function buildUrl(baseUrl: string, path: string, query?: object): string
export async function request<T>(
config: Required<Omit<ClientConfig, 'fetch'>> & { fetch: FetchLike },
options: RequestOptions,
+): Promise<T> {
+ return send(config, options, async res => {
+ if (res.status === 204) {
+ return null as T;
+ }
+ const text = await res.text();
+ if (!text) return null as T;
+ try {
+ return JSON.parse(text) as T;
+ } catch {
+ return text as unknown as T;
+ }
+ });
+}
+
+/** A binary (non-JSON) 2xx body, e.g. the stored status media bytes. */
+export interface BinaryResponse {
+ data: Uint8Array;
+ contentType: string | null;
+}
+
+/**
+ * Like {@link request}, but for endpoints that stream raw bytes instead of
+ * JSON (e.g. status media). Returns the body verbatim plus the served
+ * Content-Type; a 204/empty body resolves to zero-length data.
+ */
+export async function requestBytes(
+ config: Required<Omit<ClientConfig, 'fetch'>> & { fetch: FetchLike },
+ options: RequestOptions,
+): Promise<BinaryResponse> {
+ return send(config, options, async res => {
+ if (res.status === 204) {
+ return { data: new Uint8Array(0), contentType: null };
+ }
+ return { data: new Uint8Array(await res.arrayBuffer()), contentType: res.headers.get('content-type') };
+ });
+}
+
+/**
+ * Shared transport for {@link request} and {@link requestBytes}: builds the
+ * URL/headers, performs the fetch under the per-request timeout, translates a
+ * non-2xx into a typed error, then hands the response to `consume` — still
+ * inside the timeout window, so a stalled body read aborts too.
+ */
+async function send<T>(
+ config: Required<Omit<ClientConfig, 'fetch'>> & { fetch: FetchLike },
+ options: RequestOptions,
+ consume: (res: Response) => Promise<T>,
): Promise<T> {
const url = buildUrl(config.baseUrl, options.path, options.query);
const timeoutMs = options.timeoutMs ?? config.timeoutMs;
@@ -110,16 +158,7 @@ export async function request<T>(
throw classifyApiError(apiError.status, apiError.message, apiError.body, apiError.errorKind);
}
- if (res.status === 204) {
- return null as T;
- }
- const text = await res.text();
- if (!text) return null as T;
- try {
- return JSON.parse(text) as T;
- } catch {
- return text as unknown as T;
- }
+ return await consume(res);
} catch (err) {
if (err instanceof Error && err.name === 'AbortError') {
throw new OpenWATimeoutError(timeoutMs);
diff --git a/sdk/javascript/src/index.ts b/sdk/javascript/src/index.ts
index 7fb9f92ed..dd0a1829b 100644
--- a/sdk/javascript/src/index.ts
+++ b/sdk/javascript/src/index.ts
@@ -28,5 +28,5 @@ export { default } from './client.js';
export type { OpenWAClientOptions } from './client.js';
export * from './errors.js';
export type * from './types.js';
-export type { ClientConfig, FetchLike, HttpMethod, RequestOptions } from './http.js';
+export type { BinaryResponse, ClientConfig, FetchLike, HttpMethod, RequestOptions } from './http.js';
export { buildUrl, warnIfInsecureHttpUrl } from './http.js';
diff --git a/sdk/javascript/src/resources/contacts.ts b/sdk/javascript/src/resources/contacts.ts
index def86c3b2..ea2557ffa 100644
--- a/sdk/javascript/src/resources/contacts.ts
+++ b/sdk/javascript/src/resources/contacts.ts
@@ -12,6 +12,7 @@ import type {
ContactPhoneResponse,
ContactRecord,
ProfilePictureResponse,
+ ProfilePicturesResponse,
SuccessResult,
} from '../types.js';
@@ -56,6 +57,18 @@ export class ContactsResource {
});
}
+ /**
+ * Batch-resolve profile picture URLs for up to 50 contacts in one request.
+ * Returns a map of contact id → URL (null when a lookup fails).
+ */
+ profilePictures(sessionId: string, ids: string[]): Promise<ProfilePicturesResponse> {
+ return this.client.request<ProfilePicturesResponse>({
+ method: 'GET',
+ path: `/api/sessions/${encodeSegment(sessionId)}/contacts/profile-pictures`,
+ query: { ids: ids.join(',') },
+ });
+ }
+
/** Resolve a contact id (e.g. a `@lid`) to a phone number. */
phone(sessionId: string, contactId: string): Promise<ContactPhoneResponse> {
return this.client.request<ContactPhoneResponse>({
diff --git a/sdk/javascript/src/resources/messages.ts b/sdk/javascript/src/resources/messages.ts
index 5892ba88c..7ef4ffedd 100644
--- a/sdk/javascript/src/resources/messages.ts
+++ b/sdk/javascript/src/resources/messages.ts
@@ -27,6 +27,7 @@ import type {
SendLocationRequest,
SendAudioRequest,
SendMediaRequest,
+ SendPollRequest,
SendTemplateRequest,
SendTextRequest,
SuccessResult,
@@ -105,6 +106,15 @@ export class MessagesResource {
});
}
+ /** Send a native WhatsApp poll (2–12 options). */
+ sendPoll(sessionId: string, body: SendPollRequest): Promise<MessageResponse> {
+ return this.client.request<MessageResponse>({
+ method: 'POST',
+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/send-poll`,
+ body,
+ });
+ }
+
/** Reply to a specific message. */
reply(sessionId: string, body: ReplyMessageRequest): Promise<MessageResponse> {
return this.client.request<MessageResponse>({
diff --git a/sdk/javascript/src/resources/status.ts b/sdk/javascript/src/resources/status.ts
index d75b2123e..1e578049c 100644
--- a/sdk/javascript/src/resources/status.ts
+++ b/sdk/javascript/src/resources/status.ts
@@ -7,6 +7,7 @@
*/
import { encodeSegment } from '../http.js';
+import type { BinaryResponse } from '../http.js';
import type { OpenWAClient } from '../client.js';
import type {
SendImageStatusRequest,
@@ -35,6 +36,14 @@ export class StatusResource {
});
}
+ /** Fetch the stored media bytes for a status update (404 when there is no stored media). */
+ media(sessionId: string, statusId: string): Promise<BinaryResponse> {
+ return this.client.requestBytes({
+ method: 'GET',
+ path: `/api/sessions/${encodeSegment(sessionId)}/status/${encodeSegment(statusId)}/media`,
+ });
+ }
+
/** Post a text status update. */
sendText(sessionId: string, body: SendTextStatusRequest): Promise<StatusResult> {
return this.client.request<StatusResult>({
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index dc1dc080e..6524ae682 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -92,6 +92,8 @@ export interface SendTextRequest {
chatId: Jid;
/** Max 4096 chars. */
text: string;
+ /** WIDs to @mention (e.g. `["[email protected]"]`). The text must also contain the `@<number>` token. */
+ mentions?: string[];
}
export interface SendMediaRequest {
@@ -179,6 +181,16 @@ export interface SendTemplateRequest {
vars?: Record<string, string>;
}
+export interface SendPollRequest {
+ chatId: Jid;
+ /** Poll question / title (max 255 chars). */
+ name: string;
+ /** Options to vote on (WhatsApp allows between 2 and 12). */
+ options: string[];
+ /** Allow voters to pick several options (default single choice). */
+ allowMultipleAnswers?: boolean;
+}
+
export interface ListMessagesQuery {
chatId?: Jid;
from?: Jid;
@@ -364,6 +376,11 @@ export interface ProfilePictureResponse {
url: string | null;
}
+/** Batch profile-picture lookup: a map of contact id → picture URL (null when the lookup failed). */
+export interface ProfilePicturesResponse {
+ pictures: Record<string, string | null>;
+}
+
export interface ContactPhoneResponse {
contactId: Jid;
phone: string | null;
@@ -502,7 +519,13 @@ export type WebhookEvent =
export interface WebhookFilterCondition {
field: string;
operator: string;
- value: string[];
+ /**
+ * Polymorphic per field kind: a single string (text fields), a string array
+ * (id/idArray/enum fields), or a boolean (boolean fields).
+ */
+ value: string | string[] | boolean;
+ /** Only meaningful for text fields (`contains`/`equals`). Defaults to false. */
+ caseSensitive?: boolean;
}
export interface WebhookFilters {
diff --git a/sdk/javascript/test/helpers.ts b/sdk/javascript/test/helpers.ts
index 938ff3e42..02d6f07ea 100644
--- a/sdk/javascript/test/helpers.ts
+++ b/sdk/javascript/test/helpers.ts
@@ -16,6 +16,8 @@ export interface MockResponseSpec {
status?: number;
body?: unknown;
text?: string;
+ /** Overrides the default `application/json` response content type. */
+ contentType?: string;
}
/** A scripted mock transport. Throws if a call doesn't match a route. */
@@ -97,7 +99,7 @@ export class MockTransport {
const responseBody: BodyInit | null = noBody
? null
: (spec.text ?? (spec.body === undefined ? '' : JSON.stringify(spec.body)));
- const resHeaders: Record<string, string> = noBody ? {} : { 'content-type': 'application/json' };
+ const resHeaders: Record<string, string> = noBody ? {} : { 'content-type': spec.contentType ?? 'application/json' };
return new Response(responseBody, { status, headers: resHeaders });
}) as FetchLike;
}
diff --git a/sdk/javascript/test/messages.test.ts b/sdk/javascript/test/messages.test.ts
index c499e92dd..8afad9c4d 100644
--- a/sdk/javascript/test/messages.test.ts
+++ b/sdk/javascript/test/messages.test.ts
@@ -14,6 +14,30 @@ describe('MessagesResource — exact paths', () => {
expect(t.lastCall!.body).toEqual({ chatId: '[email protected]', text: 'hi' });
});
+ it('sendText forwards mentions verbatim', async () => {
+ const t = new MockTransport().on('POST', /send-text$/, { body: { messageId: 'm1', timestamp: 1 } });
+ await client(t).messages.sendText('s1', { chatId: '[email protected]', text: 'hi @628123', mentions: ['[email protected]'] });
+ expect(t.lastCall!.body).toEqual({ chatId: '[email protected]', text: 'hi @628123', mentions: ['[email protected]'] });
+ });
+
+ it('sendPoll posts to /messages/send-poll', async () => {
+ const t = new MockTransport().on('POST', /send-poll$/, { body: { messageId: 'm2', timestamp: 2 } });
+ const res = await client(t).messages.sendPoll('s1', {
+ chatId: '[email protected]',
+ name: 'Where?',
+ options: ['Park', 'Beach'],
+ allowMultipleAnswers: true,
+ });
+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s1/messages/send-poll');
+ expect(t.lastCall!.body).toEqual({
+ chatId: '[email protected]',
+ name: 'Where?',
+ options: ['Park', 'Beach'],
+ allowMultipleAnswers: true,
+ });
+ expect(res.messageId).toBe('m2');
+ });
+
it('sendImage posts to /messages/send-image', async () => {
const t = new MockTransport().on('POST', /send-image$/, { body: { messageId: 'm', timestamp: 2 } });
await client(t).messages.sendImage('s', { chatId: '[email protected]', url: 'http://img' });
diff --git a/sdk/javascript/test/resources.test.ts b/sdk/javascript/test/resources.test.ts
index 4cb914964..f30d3370c 100644
--- a/sdk/javascript/test/resources.test.ts
+++ b/sdk/javascript/test/resources.test.ts
@@ -144,6 +144,16 @@ describe('ContactsResource — exact paths', () => {
await c.contacts.unblock('s', '[email protected]');
expect(t.lastCall!.method).toBe('DELETE');
});
+
+ it('profilePictures batch-resolves ids via the ids query param', async () => {
+ const t = new MockTransport().on('GET', /\/contacts\/profile-pictures$/, {
+ body: { pictures: { '[email protected]': 'http://p/a', '[email protected]': null } },
+ });
+ const res = await client(t).contacts.profilePictures('s', ['[email protected]', '[email protected]']);
+ expect(t.lastCall!.method).toBe('GET');
+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/contacts/profile-pictures?ids=a%40c.us%2Cb%40c.us');
+ expect(res.pictures).toEqual({ '[email protected]': 'http://p/a', '[email protected]': null });
+ });
});
describe('WebhooksResource — exact paths', () => {
@@ -176,6 +186,21 @@ describe('WebhooksResource — exact paths', () => {
await c.webhooks.test('s', 'w1');
expect(t.lastCall!.url).toContain('/webhooks/w1/test');
});
+
+ it('create forwards polymorphic filter values (string, string[], boolean) verbatim', async () => {
+ const t = new MockTransport().on('POST', /\/webhooks$/, {
+ body: { id: 'w1', sessionId: 's', url: 'u', events: ['*'], active: true, createdAt: '', updatedAt: '' },
+ });
+ const filters = {
+ conditions: [
+ { field: 'sender', operator: 'is', value: ['[email protected]'] },
+ { field: 'body', operator: 'contains', value: 'invoice', caseSensitive: true },
+ { field: 'isGroup', operator: 'is', value: false },
+ ],
+ };
+ await client(t).webhooks.create('s', { url: 'u', events: ['message.received'], filters });
+ expect(t.lastCall!.body).toEqual({ url: 'u', events: ['message.received'], filters });
+ });
});
describe('StatusResource — nested media bodies', () => {
@@ -189,6 +214,15 @@ describe('StatusResource — nested media bodies', () => {
await c.status.sendVideo('s', { video: { url: 'http://vid' }, recipients: ['[email protected]'] });
expect(t.lastCall!.body).toEqual({ video: { url: 'http://vid' }, recipients: ['[email protected]'] });
});
+
+ it('media fetches the stored status bytes with their content type', async () => {
+ const t = new MockTransport().on('GET', /\/status\/w1\/media$/, { text: 'PNG_BYTES', contentType: 'image/png' });
+ const res = await client(t).status.media('s', 'w1');
+ expect(t.lastCall!.method).toBe('GET');
+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/status/w1/media');
+ expect(new TextDecoder().decode(res.data)).toBe('PNG_BYTES');
+ expect(res.contentType).toBe('image/png');
+ });
});
describe('ChatsResource — exact paths', () => {
diff --git a/sdk/php/src/Http/HttpExecutor.php b/sdk/php/src/Http/HttpExecutor.php
index 1547e1c21..c3d430079 100644
--- a/sdk/php/src/Http/HttpExecutor.php
+++ b/sdk/php/src/Http/HttpExecutor.php
@@ -75,6 +75,51 @@ class HttpExecutor
* @throws OpenWATimeoutException On timeout.
*/
public function request(string $method, string $path, array $query = [], $body = null)
+ {
+ $response = $this->send($method, $path, $query, $body);
+
+ $text = (string) $response->getBody();
+ if ($response->getStatusCode() === 204 || $text === '') {
+ return null;
+ }
+
+ $decoded = json_decode($text, true);
+ return $decoded === null && json_last_error() !== JSON_ERROR_NONE ? $text : $decoded;
+ }
+
+ /**
+ * Perform one request for a non-JSON (binary) 2xx body — e.g. stored
+ * status media — and return it as ['data' => raw bytes, 'contentType' =>
+ * ?string]. A 204/empty body yields empty data and a null content type.
+ *
+ * @param string $method HTTP method.
+ * @param string $path Path beginning with /.
+ * @param array<string,mixed> $query Query parameters (null values skipped).
+ *
+ * @return array{data: string, contentType: ?string}
+ *
+ * @throws OpenWAApiException On any non-2xx response (typed subclass).
+ * @throws OpenWATimeoutException On timeout.
+ */
+ public function requestBinary(string $method, string $path, array $query = []): array
+ {
+ $response = $this->send($method, $path, $query, null);
+ if ($response->getStatusCode() === 204) {
+ return ['data' => '', 'contentType' => null];
+ }
+ $contentType = $response->getHeaderLine('Content-Type');
+ return ['data' => (string) $response->getBody(), 'contentType' => $contentType === '' ? null : $contentType];
+ }
+
+ /**
+ * Shared transport for {@see request()} and {@see requestBinary()}:
+ * builds options, performs the Guzzle call, and maps a non-2xx (including
+ * an unfollowed 3xx) to a typed SDK exception.
+ *
+ * @param array<string,mixed> $query
+ * @param mixed|null $body
+ */
+ private function send(string $method, string $path, array $query, $body): ResponseInterface
{
// Auth/JSON headers are applied per-request so they are correct whether
// a default or injected client is used (and never leak Guzzle exceptions:
@@ -125,14 +170,7 @@ class HttpExecutor
if ($status >= 300) {
throw $this->buildApiException($response, $method, $path);
}
-
- $text = (string) $response->getBody();
- if ($status === 204 || $text === '') {
- return null;
- }
-
- $decoded = json_decode($text, true);
- return $decoded === null && json_last_error() !== JSON_ERROR_NONE ? $text : $decoded;
+ return $response;
}
private function buildApiException(ResponseInterface $response, string $method, string $path): OpenWAApiException
diff --git a/sdk/php/src/Resources/ContactsResource.php b/sdk/php/src/Resources/ContactsResource.php
index 03d2f235a..18a3142f0 100644
--- a/sdk/php/src/Resources/ContactsResource.php
+++ b/sdk/php/src/Resources/ContactsResource.php
@@ -47,6 +47,21 @@ class ContactsResource
return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/contacts/{$this->http->encodeSegment($contactId)}/profile-picture");
}
+ /**
+ * Batch-resolve profile picture URLs for up to 50 contacts in one request.
+ *
+ * @param list<string> $ids
+ * @return array{pictures: array<string,?string>} Map of contact id → URL (null when a lookup fails).
+ */
+ public function profilePictures(string $sessionId, array $ids): array
+ {
+ return $this->http->request(
+ 'GET',
+ "/api/sessions/{$this->http->encodeSegment($sessionId)}/contacts/profile-pictures",
+ ['ids' => implode(',', $ids)]
+ );
+ }
+
/** @return array<string,mixed> */
public function phone(string $sessionId, string $contactId): array
{
diff --git a/sdk/php/src/Resources/MessagesResource.php b/sdk/php/src/Resources/MessagesResource.php
index d04dfbfcb..10c6932a1 100644
--- a/sdk/php/src/Resources/MessagesResource.php
+++ b/sdk/php/src/Resources/MessagesResource.php
@@ -101,6 +101,17 @@ class MessagesResource
return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-template", [], $body);
}
+ /**
+ * Send a native WhatsApp poll (2–12 options).
+ *
+ * @param array<string,mixed> $body {chatId, name, options, allowMultipleAnswers?}
+ * @return array<string,mixed>
+ */
+ public function sendPoll(string $sessionId, array $body): array
+ {
+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-poll", [], $body);
+ }
+
/** @return array<string,mixed> */
public function reply(string $sessionId, array $body): array
{
diff --git a/sdk/php/src/Resources/StatusResource.php b/sdk/php/src/Resources/StatusResource.php
index 0ce65b10e..8c377fb93 100644
--- a/sdk/php/src/Resources/StatusResource.php
+++ b/sdk/php/src/Resources/StatusResource.php
@@ -33,6 +33,16 @@ class StatusResource
return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/status/{$this->http->encodeSegment($contactId)}") ?? [];
}
+ /**
+ * Fetch the stored media bytes for a status update (404 when there is no stored media).
+ *
+ * @return array{data: string, contentType: ?string}
+ */
+ public function media(string $sessionId, string $statusId): array
+ {
+ return $this->http->requestBinary('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/status/{$this->http->encodeSegment($statusId)}/media");
+ }
+
/**
* @param array<string,mixed> $body Body may include a `recipients` key (list<string> of JIDs).
* Required on the Baileys engine (absent/empty -> 400 there);
diff --git a/sdk/php/tests/MessagesTest.php b/sdk/php/tests/MessagesTest.php
index 936411829..13497c0df 100644
--- a/sdk/php/tests/MessagesTest.php
+++ b/sdk/php/tests/MessagesTest.php
@@ -21,6 +21,36 @@ class MessagesTest extends TestCase
$this->assertSame(['chatId' => '[email protected]', 'text' => 'hi'], $call['body']);
}
+ public function testSendTextForwardsMentionsVerbatim(): void
+ {
+ $backend = (new MockBackend())->on(201, ['messageId' => 'm1', 'timestamp' => 1]);
+ $client = $backend->makeClient();
+ $client->messages->sendText('s1', ['chatId' => '[email protected]', 'text' => 'hi @628123', 'mentions' => ['[email protected]']]);
+ $this->assertSame(
+ ['chatId' => '[email protected]', 'text' => 'hi @628123', 'mentions' => ['[email protected]']],
+ $backend->lastCall()['body']
+ );
+ }
+
+ public function testSendPollUsesSendPollPath(): void
+ {
+ $backend = (new MockBackend())->on(201, ['messageId' => 'm2', 'timestamp' => 2]);
+ $client = $backend->makeClient();
+ $res = $client->messages->sendPoll('s1', [
+ 'chatId' => '[email protected]',
+ 'name' => 'Where?',
+ 'options' => ['Park', 'Beach'],
+ 'allowMultipleAnswers' => true,
+ ]);
+ $call = $backend->lastCall();
+ $this->assertSame('/api/sessions/s1/messages/send-poll', $call['path']);
+ $this->assertSame(
+ ['chatId' => '[email protected]', 'name' => 'Where?', 'options' => ['Park', 'Beach'], 'allowMultipleAnswers' => true],
+ $call['body']
+ );
+ $this->assertSame('m2', $res['messageId']);
+ }
+
public function testListReturnsMessagesPageEnvelope(): void
{
// The server responds with a {messages, total} page, not a flat array. Pin the shape so a
diff --git a/sdk/php/tests/MockBackend.php b/sdk/php/tests/MockBackend.php
index 719c6ca45..767a72587 100644
--- a/sdk/php/tests/MockBackend.php
+++ b/sdk/php/tests/MockBackend.php
@@ -46,6 +46,16 @@ class MockBackend
return $this;
}
+ /**
+ * Queue a raw (non-JSON) response body for the next matching call — e.g.
+ * the binary stream of a stored status media.
+ */
+ public function onRaw(int $status, string $body, array $headers = []): self
+ {
+ $this->mock->append(new Response($status, $headers, $body));
+ return $this;
+ }
+
public function httpClient(): GuzzleClient
{
// Record at the handler layer (innermost). The handler always sees the
diff --git a/sdk/php/tests/ResourcesTest.php b/sdk/php/tests/ResourcesTest.php
index 8568b4cc4..88246c5c0 100644
--- a/sdk/php/tests/ResourcesTest.php
+++ b/sdk/php/tests/ResourcesTest.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace OpenWA\Tests;
+use OpenWA\Exceptions\OpenWANotFoundException;
use PHPUnit\Framework\TestCase;
class ResourcesTest extends TestCase
@@ -158,6 +159,18 @@ class ResourcesTest extends TestCase
$this->assertSame('DELETE', $backend->calls()[1]['method']);
}
+ public function testProfilePicturesBatchResolvesIdsQuery(): void
+ {
+ $backend = (new MockBackend())->on(200, ['pictures' => ['[email protected]' => 'http://p/a', '[email protected]' => null]]);
+ $client = $backend->makeClient();
+ $res = $client->contacts->profilePictures('s', ['[email protected]', '[email protected]']);
+ $call = $backend->lastCall();
+ $this->assertSame('GET', $call['method']);
+ $this->assertSame('/api/sessions/s/contacts/profile-pictures', $call['path']);
+ $this->assertSame('ids=a%40c.us%2Cb%40c.us', $call['query']);
+ $this->assertSame(['[email protected]' => 'http://p/a', '[email protected]' => null], $res['pictures']);
+ }
+
// ── Webhooks ──────────────────────────────────────────────────────
public function testWebhookCrudTest(): void
@@ -182,6 +195,26 @@ class ResourcesTest extends TestCase
$this->assertStringContainsString('/webhooks/w1/test', $backend->calls()[5]['url']);
}
+ public function testWebhookCreateForwardsPolymorphicFilterValuesVerbatim(): void
+ {
+ $backend = (new MockBackend())->on(201, ['id' => 'w1']);
+ $client = $backend->makeClient();
+ // The filter value is polymorphic on the wire: string (text fields),
+ // string list (id/enum fields), bool (boolean fields) + caseSensitive.
+ $filters = [
+ 'conditions' => [
+ ['field' => 'sender', 'operator' => 'is', 'value' => ['[email protected]']],
+ ['field' => 'body', 'operator' => 'contains', 'value' => 'invoice', 'caseSensitive' => true],
+ ['field' => 'isGroup', 'operator' => 'is', 'value' => false],
+ ],
+ ];
+ $client->webhooks->create('s', ['url' => 'u', 'events' => ['message.received'], 'filters' => $filters]);
+ $this->assertSame(
+ ['url' => 'u', 'events' => ['message.received'], 'filters' => $filters],
+ $backend->lastCall()['body']
+ );
+ }
+
// ── Chats & Health ────────────────────────────────────────────────
public function testChats(): void
@@ -220,6 +253,29 @@ class ResourcesTest extends TestCase
$this->assertSame(['video' => ['url' => 'http://vid'], 'recipients' => ['[email protected]']], $backend->lastCall()['body']);
}
+ public function testStatusMediaReturnsStoredBytes(): void
+ {
+ $backend = (new MockBackend())->onRaw(200, 'PNG_BYTES', ['Content-Type' => 'image/png']);
+ $client = $backend->makeClient();
+ $media = $client->status->media('s', 'w1');
+ $call = $backend->lastCall();
+ $this->assertSame('GET', $call['method']);
+ $this->assertSame('/api/sessions/s/status/w1/media', $call['path']);
+ $this->assertSame('PNG_BYTES', $media['data']);
+ $this->assertSame('image/png', $media['contentType']);
+ }
+
+ public function testStatusMedia404MapsToNotFoundException(): void
+ {
+ $backend = (new MockBackend())->on(404, [
+ 'statusCode' => 404,
+ 'message' => 'Status media not found or expired',
+ 'error' => 'Not Found',
+ ]);
+ $this->expectException(OpenWANotFoundException::class);
+ $backend->makeClient()->status->media('s', 'w1');
+ }
+
public function testHealthAndAuth(): void
{
$backend = new MockBackend();
diff --git a/sdk/python/openwa/_http.py b/sdk/python/openwa/_http.py
index 7a80cf568..c5cf1f357 100644
--- a/sdk/python/openwa/_http.py
+++ b/sdk/python/openwa/_http.py
@@ -97,6 +97,30 @@ class HttpExecutor:
def request(self, method: HttpMethod, path: str, *, query: Mapping[str, Any] | None = None, body: Any = None) -> Any:
"""Perform one request and return the parsed JSON (or ``None`` for 204)."""
+ res = self._send(method, path, query=query, body=body)
+ if res.status_code == 204 or not res.content:
+ return None
+ try:
+ return res.json()
+ except ValueError:
+ # A 2xx body that isn't JSON surfaces as text rather than a raw
+ # JSONDecodeError (mirrors the JS and PHP transports).
+ return res.text
+
+ def request_bytes(
+ self, method: HttpMethod, path: str, *, query: Mapping[str, Any] | None = None
+ ) -> tuple[bytes, str | None]:
+ """Perform one request for a non-JSON (binary) 2xx body — e.g. stored
+ status media — and return ``(body bytes, content type)``. A 204/empty
+ body yields empty bytes and ``None``."""
+ res = self._send(method, path, query=query, body=None)
+ if res.status_code == 204:
+ return b"", None
+ return res.content, res.headers.get("content-type")
+
+ def _send(self, method: HttpMethod, path: str, *, query: Mapping[str, Any] | None, body: Any) -> httpx.Response:
+ """Shared transport for :meth:`request` and :meth:`request_bytes`: builds
+ the URL, performs the request, and translates a non-2xx into a typed error."""
url = build_url("", path, query)
try:
res = self._client.request(method, url, json=body if body is not None else None)
@@ -108,11 +132,4 @@ class HttpExecutor:
if res.status_code >= 300:
context = f"{method} {path}"
raise OpenWAApiError.from_response(res.status_code, res.text, context)
- if res.status_code == 204 or not res.content:
- return None
- try:
- return res.json()
- except ValueError:
- # A 2xx body that isn't JSON surfaces as text rather than a raw
- # JSONDecodeError (mirrors the JS and PHP transports).
- return res.text
+ return res
diff --git a/sdk/python/openwa/resources/contacts.py b/sdk/python/openwa/resources/contacts.py
index 02acac8a3..7af29c4d5 100644
--- a/sdk/python/openwa/resources/contacts.py
+++ b/sdk/python/openwa/resources/contacts.py
@@ -13,6 +13,7 @@ from ..types import (
ContactPhoneResponse,
ContactRecord,
ProfilePictureResponse,
+ ProfilePicturesResponse,
SuccessResult,
)
@@ -43,6 +44,13 @@ class ContactsResource:
"GET", f"/api/sessions/{quote_segment(session_id)}/contacts/{quote_segment(contact_id)}/profile-picture"
)
+ def profile_pictures(self, session_id: str, ids: list[str]) -> ProfilePicturesResponse:
+ """Batch-resolve profile picture URLs for up to 50 contacts in one request.
+ Returns a map of contact id → URL (None when a lookup fails)."""
+ return self._http.request(
+ "GET", f"/api/sessions/{quote_segment(session_id)}/contacts/profile-pictures", query={"ids": ",".join(ids)}
+ )
+
def phone(self, session_id: str, contact_id: str) -> ContactPhoneResponse:
return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/contacts/{quote_segment(contact_id)}/phone")
diff --git a/sdk/python/openwa/resources/messages.py b/sdk/python/openwa/resources/messages.py
index 369cbca71..73e8278bb 100644
--- a/sdk/python/openwa/resources/messages.py
+++ b/sdk/python/openwa/resources/messages.py
@@ -28,6 +28,7 @@ from ..types import (
SendLocationRequest,
SendAudioRequest,
SendMediaRequest,
+ SendPollRequest,
SendTemplateRequest,
SendTextRequest,
SuccessResult,
@@ -74,6 +75,10 @@ class MessagesResource:
def send_template(self, session_id: str, body: SendTemplateRequest) -> MessageResponse:
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-template", body=body)
+ def send_poll(self, session_id: str, body: SendPollRequest) -> MessageResponse:
+ """Send a native WhatsApp poll (2–12 options)."""
+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-poll", body=body)
+
def reply(self, session_id: str, body: ReplyMessageRequest) -> MessageResponse:
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/reply", body=body)
diff --git a/sdk/python/openwa/resources/status.py b/sdk/python/openwa/resources/status.py
index e02eacf40..033c1b278 100644
--- a/sdk/python/openwa/resources/status.py
+++ b/sdk/python/openwa/resources/status.py
@@ -13,6 +13,7 @@ from ..types import (
SendImageStatusRequest,
SendTextStatusRequest,
SendVideoStatusRequest,
+ StatusMedia,
StatusRecord,
StatusResult,
)
@@ -31,6 +32,13 @@ class StatusResource:
def from_contact(self, session_id: str, contact_id: str) -> dict[str, list[StatusRecord]]:
return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/status/{quote_segment(contact_id)}")
+ def media(self, session_id: str, status_id: str) -> StatusMedia:
+ """Fetch the stored media bytes for a status update (404 when there is no stored media)."""
+ data, content_type = self._http.request_bytes(
+ "GET", f"/api/sessions/{quote_segment(session_id)}/status/{quote_segment(status_id)}/media"
+ )
+ return {"data": data, "contentType": content_type}
+
def send_text(self, session_id: str, body: SendTextStatusRequest) -> StatusResult:
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/status/send-text", body=body)
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index fb2aaa595..1812f8fdd 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -94,9 +94,12 @@ class MessageResponse(TypedDict):
timestamp: int
-class SendTextRequest(TypedDict):
+class SendTextRequest(TypedDict, total=False):
+ # chatId/text required; mentions optional.
chatId: Jid
text: str
+ # WIDs to @mention (e.g. ["[email protected]"]). The text must also contain the @<number> token.
+ mentions: list[str]
class SendMediaRequest(TypedDict, total=False):
@@ -178,6 +181,16 @@ class SendTemplateRequest(TypedDict, total=False):
vars: dict[str, str]
+class SendPollRequest(TypedDict, total=False):
+ # chatId/name/options required; allowMultipleAnswers optional (default single choice).
+ chatId: Jid
+ # Poll question / title (max 255 chars).
+ name: str
+ # Options to vote on (WhatsApp allows between 2 and 12).
+ options: list[str]
+ allowMultipleAnswers: bool
+
+
# ``from`` is a Python keyword, so use the functional TypedDict form.
ListMessagesQuery = TypedDict(
"ListMessagesQuery",
@@ -385,6 +398,11 @@ class ProfilePictureResponse(TypedDict):
url: str | None
+class ProfilePicturesResponse(TypedDict):
+ # Map of contact id → picture URL (None when the lookup failed).
+ pictures: dict[str, str | None]
+
+
class ContactPhoneResponse(TypedDict):
contactId: Jid
phone: str | None
@@ -479,10 +497,14 @@ class SetProfilePictureRequest(TypedDict, total=False):
# ── Webhook ───────────────────────────────────────────────────────
-class WebhookFilterCondition(TypedDict):
+class WebhookFilterCondition(TypedDict, total=False):
+ # field/operator/value required; caseSensitive optional (text fields only, default false).
field: str
operator: str
- value: list[str]
+ # Polymorphic per field kind: a single string (text fields), a list of
+ # strings (id/idArray/enum fields), or a bool (boolean fields).
+ value: str | list[str] | bool
+ caseSensitive: bool
class WebhookFilters(TypedDict):
@@ -589,6 +611,13 @@ class StatusResult(TypedDict, total=False):
expiresAt: str
+class StatusMedia(TypedDict):
+ """A stored status media file: raw bytes plus the served content type."""
+
+ data: bytes
+ contentType: str | None
+
+
class SendTextStatusRequest(TypedDict, total=False):
# text always required; recipients required on the Baileys engine only.
text: str
diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py
index 5905418f0..621b0c404 100644
--- a/sdk/python/tests/test_sdk.py
+++ b/sdk/python/tests/test_sdk.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import httpx
import pytest
from openwa import OpenWAClient, OpenWAApiError, OpenWANotFoundError
@@ -124,6 +125,22 @@ class TestMessages:
assert backend.last_call.url == "http://localhost:2785/api/sessions/s1/messages/send-text"
assert backend.last_call.body == {"chatId": "[email protected]", "text": "hi"}
+ def test_send_text_forwards_mentions_verbatim(self):
+ backend = MockBackend().on("POST", "/send-text", body={"messageId": "m1", "timestamp": 1})
+ make_client(backend).messages.send_text("s1", {"chatId": "[email protected]", "text": "hi @628123", "mentions": ["[email protected]"]})
+ assert backend.last_call.body == {"chatId": "[email protected]", "text": "hi @628123", "mentions": ["[email protected]"]}
+
+ def test_send_poll_uses_send_poll_path(self):
+ backend = MockBackend().on("POST", "/send-poll", body={"messageId": "m2", "timestamp": 2})
+ res = make_client(backend).messages.send_poll("s1", {
+ "chatId": "[email protected]", "name": "Where?", "options": ["Park", "Beach"], "allowMultipleAnswers": True,
+ })
+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s1/messages/send-poll"
+ assert backend.last_call.body == {
+ "chatId": "[email protected]", "name": "Where?", "options": ["Park", "Beach"], "allowMultipleAnswers": True,
+ }
+ assert res["messageId"] == "m2"
+
@pytest.mark.parametrize("method,segment", [
("send_image", "send-image"),
("send_video", "send-video"),
@@ -419,6 +436,15 @@ class TestContacts:
client.contacts.unblock("s", "[email protected]")
assert backend.calls[-1].method == "DELETE"
+ def test_profile_pictures_batch_resolves_ids_query(self):
+ backend = MockBackend().on("GET", "/contacts/profile-pictures", body={
+ "pictures": {"[email protected]": "http://p/a", "[email protected]": None}
+ })
+ res = make_client(backend).contacts.profile_pictures("s", ["[email protected]", "[email protected]"])
+ assert backend.last_call.method == "GET"
+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s/contacts/profile-pictures?ids=a%40c.us%2Cb%40c.us"
+ assert res["pictures"] == {"[email protected]": "http://p/a", "[email protected]": None}
+
class TestWebhooks:
def test_crud_test(self):
@@ -442,6 +468,18 @@ class TestWebhooks:
client.webhooks.test("s", "w1")
assert "/webhooks/w1/test" in backend.calls[-1].url
+ def test_create_forwards_polymorphic_filter_values_verbatim(self):
+ backend = MockBackend().on("POST", "/webhooks", body={"id": "w1"})
+ filters = {
+ "conditions": [
+ {"field": "sender", "operator": "is", "value": ["[email protected]"]},
+ {"field": "body", "operator": "contains", "value": "invoice", "caseSensitive": True},
+ {"field": "isGroup", "operator": "is", "value": False},
+ ]
+ }
+ make_client(backend).webhooks.create("s", {"url": "u", "events": ["message.received"], "filters": filters})
+ assert backend.last_call.body == {"url": "u", "events": ["message.received"], "filters": filters}
+
class TestStatus:
def test_send_image_video_forward_nested_media_body(self):
@@ -456,6 +494,22 @@ 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_media_fetches_stored_status_bytes(self):
+ backend = MockBackend()
+ backend.fallback = lambda _: httpx.Response(200, content=b"PNG_BYTES", headers={"content-type": "image/png"})
+ res = make_client(backend).status.media("s", "w1")
+ assert backend.last_call.method == "GET"
+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s/status/w1/media"
+ assert res == {"data": b"PNG_BYTES", "contentType": "image/png"}
+
+ def test_media_404_maps_to_not_found_error(self):
+ backend = MockBackend()
+ backend.fallback = lambda _: httpx.Response(
+ 404, content=b'{"statusCode": 404, "message": "Status media not found or expired"}'
+ )
+ with pytest.raises(OpenWANotFoundError):
+ make_client(backend).status.media("s", "w1")
+
class TestChatsAndHealth:
def test_chats(self):