Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

fix(message): store and render WhatsApp Business messages (#857)

Aldino Kemal35d2e463aad8
diff --git a/docs/chatwoot.md b/docs/chatwoot.md
index bd6fcd30..2bedcfa1 100644
--- a/docs/chatwoot.md
+++ b/docs/chatwoot.md
@@ -519,6 +519,8 @@ Text formatting is translated in both directions so emphasis survives the bridge
| `_italic_` | `*italic*` |
| `~strike~` | `~~strike~~` |
+As in WhatsApp, a WhatsApp-side pair only counts at word boundaries and never inside links, so URLs such as `/_docs_/` or `?utm_source=wa&utm_medium=cta` and `snake_case` ids reach Chatwoot unchanged.
+
### Edits & deletions
- **Edits**: when a WhatsApp user edits a message, the new text is mirrored into Chatwoot as a threaded `✏️ **Edited:** …` note (controlled by `CHATWOOT_FORWARD_EDITS`, default on).
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.md
index 72da552f..a5d4e07d 100644
--- a/docs/webhook-payload.md
+++ b/docs/webhook-payload.md
@@ -1246,6 +1246,91 @@ When a user shares multiple contacts at once (via WhatsApp's multi-contact share
> **Note:** WhatsApp uses `ContactMessage` (field 4) for a single contact and `ContactsArrayMessage` (field 13) for multiple contacts. A single contact produces `"contact"`, while multiple contacts produce `"contacts_array"`.
+### Business Template Message
+
+Sent by WhatsApp Business / Cloud API senders (order confirmations, OTPs, booking updates):
+
+```json
+{
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
+ "id": "3EB0A1B2C3D4E5F60718",
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "Acme Store",
+ "timestamp": "2026-09-25T10:00:00Z",
+ "body": "Order confirmed\nHi John, your order #1234 has shipped.\nAcme Store\n🔗 Track order: https://acme.example/track/1234\n📞 Call us: +15550100\n[Stop updates]",
+ "template": {
+ "title": "Order confirmed",
+ "body": "Hi John, your order #1234 has shipped.",
+ "footer": "Acme Store",
+ "template_id": "order_confirmed",
+ "buttons": [
+ { "type": "url", "text": "Track order", "url": "https://acme.example/track/1234" },
+ { "type": "call", "text": "Call us", "phone_number": "+15550100" },
+ { "type": "quick_reply", "text": "Stop updates", "id": "stop" }
+ ]
+ }
+ }
+}
+```
+
+- `body` is the whole message as plain text: title, body and footer, then one line per button. Chat storage keeps the same text, and Chatwoot receives it with its usual WhatsApp-to-Markdown conversion. A template with no text gets `Template message`.
+- `buttons[].type` is `url`, `call`, `quick_reply` or `copy` (`code` holds the value to copy). Other native-flow buttons keep their name as the type.
+- A `single_select` button lists its options in `rows` (`id`, `title`, `description`).
+- `header_type` is set when the header is media: `image`, `video`, `document`, `location` or `product`. The header media itself is not included.
+- Templates wrapping an interactive message use the same shape, plus `subtitle`, and `cards` for carousels. Their `body` is rendered like an interactive message (`[quick_reply] Stop updates`, `Card 1: …`, and `Interactive message` when empty).
+- Interactive, list and order messages keep their `interactive` (the same text as `body`), `list` and `order` (raw WhatsApp message fields) keys, and get a plain-text `body` too: `List: <title>` or `Order: <title>` first, then the remaining text and list rows.
+
+### Buttons Message
+
+Same shape as a template, under `buttons`. `body` renders it the same way (`Buttons message` when there is no text):
+
+```json
+"buttons": {
+ "title": "Support",
+ "body": "Please choose the service",
+ "footer": "Reply with a button",
+ "buttons": [
+ { "type": "quick_reply", "text": "Sales", "id": "sales" },
+ { "type": "quick_reply", "text": "Support", "id": "support" }
+ ]
+}
+```
+
+### Product Message
+
+Prices are in WhatsApp's unit (amount × 1000). `body` is `Product: <title> (<currency> <price>)` with the price in major units, e.g. `Product: Weekend package (IDR 3500.00)`, using the sale price when set, followed by the message body and footer:
+
+```json
+"product": {
+ "product_id": "p-77",
+ "title": "Weekend package",
+ "description": "2 nights, breakfast included",
+ "currency_code": "IDR",
+ "price_amount_1000": 3500000,
+ "catalog_title": "Packages",
+ "business_owner_jid": "[email protected]"
+}
+```
+
+### List / Button Reply
+
+A tap on a list row, a button, a template quick reply or a native-flow button. `selected_id` matches the list row's `rowID` or the button `id`:
+
+```json
+"selection": {
+ "kind": "list",
+ "text": "Void PNR",
+ "description": "Cancel the booking",
+ "selected_id": "row-void-pnr"
+}
+```
+
+- `kind` is `list`, `buttons`, `template` or `interactive` (native-flow replies, whose `selected_id` comes from the reply's `id` param).
+- `body` is the selected text, falling back to `description`. Recent clients often send replies with only the id; `body` is then `Selected option <selected_id>`, or `Selection message` when there is nothing at all.
+
### Location Message
```json
diff --git a/src/infrastructure/whatsapp/chatwoot_content_test.go b/src/infrastructure/whatsapp/chatwoot_content_test.go
index b7ad259b..6ee7183a 100644
--- a/src/infrastructure/whatsapp/chatwoot_content_test.go
+++ b/src/infrastructure/whatsapp/chatwoot_content_test.go
@@ -6,6 +6,7 @@ import (
"testing"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"go.mau.fi/whatsmeow/proto/waE2E"
"google.golang.org/protobuf/proto"
)
@@ -1054,7 +1055,7 @@ func TestFormatInteractiveMessageSummary(t *testing.T) {
},
}
want := "Promo\nConfira nossa oferta\nEquipe Vendas\n🔗 Visitar site: https://example.com"
- if got := formatInteractiveMessageSummary(im); got != want {
+ if got := utils.FormatInteractiveMessageSummary(im); got != want {
t.Fatalf("got %q, want %q", got, want)
}
})
@@ -1073,7 +1074,7 @@ func TestFormatInteractiveMessageSummary(t *testing.T) {
},
}
want := "📞 Ligar agora: +5511999999999"
- if got := formatInteractiveMessageSummary(im); got != want {
+ if got := utils.FormatInteractiveMessageSummary(im); got != want {
t.Fatalf("got %q, want %q", got, want)
}
})
@@ -1094,7 +1095,7 @@ func TestFormatInteractiveMessageSummary(t *testing.T) {
},
}
want := "[cta_url] Visitar site"
- if got := formatInteractiveMessageSummary(im); got != want {
+ if got := utils.FormatInteractiveMessageSummary(im); got != want {
t.Fatalf("got %q, want %q", got, want)
}
})
@@ -1113,7 +1114,7 @@ func TestFormatInteractiveMessageSummary(t *testing.T) {
},
}
want := "[single_select] Choose an option"
- if got := formatInteractiveMessageSummary(im); got != want {
+ if got := utils.FormatInteractiveMessageSummary(im); got != want {
t.Fatalf("got %q, want %q", got, want)
}
})
@@ -1129,7 +1130,7 @@ func TestFormatInteractiveMessageSummary(t *testing.T) {
},
}
want := "[review_and_pay]"
- if got := formatInteractiveMessageSummary(im); got != want {
+ if got := utils.FormatInteractiveMessageSummary(im); got != want {
t.Fatalf("got %q, want %q", got, want)
}
})
@@ -1148,7 +1149,7 @@ func TestFormatInteractiveMessageSummary(t *testing.T) {
},
}
want := "📋 Copy: SAVE10"
- if got := formatInteractiveMessageSummary(im); got != want {
+ if got := utils.FormatInteractiveMessageSummary(im); got != want {
t.Fatalf("got %q, want %q", got, want)
}
})
@@ -1161,7 +1162,7 @@ func TestFormatInteractiveMessageSummary(t *testing.T) {
},
}
want := "Promo\nOnly this week"
- if got := formatInteractiveMessageSummary(im); got != want {
+ if got := utils.FormatInteractiveMessageSummary(im); got != want {
t.Fatalf("got %q, want %q", got, want)
}
})
@@ -1176,7 +1177,7 @@ func TestFormatInteractiveMessageSummary(t *testing.T) {
},
}
want := "Summer sale\nNew arrivals, 20% off"
- if got := formatInteractiveMessageSummary(im); got != want {
+ if got := utils.FormatInteractiveMessageSummary(im); got != want {
t.Fatalf("got %q, want %q", got, want)
}
})
@@ -1195,7 +1196,7 @@ func TestFormatInteractiveMessageSummary(t *testing.T) {
},
}
want := "[single_select] Choose a plan"
- if got := formatInteractiveMessageSummary(im); got != want {
+ if got := utils.FormatInteractiveMessageSummary(im); got != want {
t.Fatalf("got %q, want %q", got, want)
}
})
@@ -1225,7 +1226,7 @@ func TestFormatInteractiveMessageSummary(t *testing.T) {
},
}
want := "Check our products\nCard 1: Shoes\n🔗 Buy: https://example.com/shoes"
- if got := formatInteractiveMessageSummary(im); got != want {
+ if got := utils.FormatInteractiveMessageSummary(im); got != want {
t.Fatalf("got %q, want %q", got, want)
}
})
@@ -1233,48 +1234,8 @@ func TestFormatInteractiveMessageSummary(t *testing.T) {
t.Run("no header, body, footer, or buttons yields generic sentinel", func(t *testing.T) {
im := &waE2E.InteractiveMessage{}
want := "Interactive message"
- if got := formatInteractiveMessageSummary(im); got != want {
+ if got := utils.FormatInteractiveMessageSummary(im); got != want {
t.Fatalf("got %q, want %q", got, want)
}
})
}
-
-// TestExtractStructuredMessageContentInteractive covers the data["interactive"]
-// dispatch branch in extractStructuredMessageContent. Unlike the other
-// structured branches in this file, buildOtherMessageTypes pre-renders
-// InteractiveMessage to a plain string at construction time (via
-// formatInteractiveMessageSummary) instead of storing the raw proto, so this
-// value survives the JSON round-trip the Chatwoot forward retry queue
-// performs — see the comment at that call site in event_message.go.
-func TestExtractStructuredMessageContentInteractive(t *testing.T) {
- t.Run("pre-rendered string is returned as-is", func(t *testing.T) {
- got := extractStructuredMessageContent(map[string]any{"interactive": "Hello"})
- if got != "Hello" {
- t.Fatalf("got %q", got)
- }
- })
-
- t.Run("non-string value falls through to empty string", func(t *testing.T) {
- // Would only happen from a bug elsewhere (buildOtherMessageTypes
- // always stores a string) — falling through to the caller's own
- // placeholder logic is safer than guessing at a sentinel here.
- got := extractStructuredMessageContent(map[string]any{"interactive": 42})
- if got != "" {
- t.Fatalf("got %q", got)
- }
- })
-
- t.Run("empty string falls through to empty string", func(t *testing.T) {
- got := extractStructuredMessageContent(map[string]any{"interactive": ""})
- if got != "" {
- t.Fatalf("got %q", got)
- }
- })
-
- t.Run("nil interactive value falls through to empty string", func(t *testing.T) {
- got := extractStructuredMessageContent(map[string]any{"interactive": nil})
- if got != "" {
- t.Fatalf("got %q", got)
- }
- })
-}
diff --git a/src/infrastructure/whatsapp/event_business_message_test.go b/src/infrastructure/whatsapp/event_business_message_test.go
new file mode 100644
index 00000000..2d7a85c0
--- /dev/null
+++ b/src/infrastructure/whatsapp/event_business_message_test.go
@@ -0,0 +1,179 @@
+package whatsapp
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+ "google.golang.org/protobuf/proto"
+)
+
+func businessEvent(id string, msg *waE2E.Message) *events.Message {
+ return &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{
+ Chat: types.NewJID("628123456789", types.DefaultUserServer),
+ Sender: types.NewJID("628123456789", types.DefaultUserServer),
+ },
+ ID: id,
+ Timestamp: time.Date(2026, time.September, 25, 10, 0, 0, 0, time.UTC),
+ },
+ Message: msg,
+ }
+}
+
+func businessOrderTemplate() *waE2E.TemplateMessage {
+ return &waE2E.TemplateMessage{
+ TemplateID: proto.String("order_confirmed"),
+ HydratedTemplate: &waE2E.TemplateMessage_HydratedFourRowTemplate{
+ Title: &waE2E.TemplateMessage_HydratedFourRowTemplate_HydratedTitleText{HydratedTitleText: "Order confirmed"},
+ HydratedContentText: proto.String("Hi John, your order #1234 has shipped."),
+ HydratedFooterText: proto.String("Acme Store"),
+ HydratedButtons: []*waE2E.HydratedTemplateButton{
+ {HydratedButton: &waE2E.HydratedTemplateButton_UrlButton{UrlButton: &waE2E.HydratedTemplateButton_HydratedURLButton{
+ DisplayText: proto.String("Track order"), URL: proto.String("https://acme.example/track/1234")}}},
+ },
+ },
+ }
+}
+
+func TestBuildEventPayloadTemplateCarriesStructuredFieldsAndBody(t *testing.T) {
+ _, payload, err := buildEventPayload(context.Background(), nil, businessEvent("TPL1", &waE2E.Message{TemplateMessage: businessOrderTemplate()}))
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ template, ok := payload["template"].(utils.BusinessMessage)
+ if !ok {
+ t.Fatalf("expected template payload, got %T", payload["template"])
+ }
+ if template.Title != "Order confirmed" || template.TemplateID != "order_confirmed" || len(template.Buttons) != 1 {
+ t.Fatalf("template not kept: %+v", template)
+ }
+ want := "Order confirmed\nHi John, your order #1234 has shipped.\nAcme Store\n🔗 Track order: https://acme.example/track/1234"
+ if payload["body"] != want {
+ t.Fatalf("body = %q, want %q", payload["body"], want)
+ }
+}
+
+func TestBuildEventPayloadListReplyWithoutTitle(t *testing.T) {
+ reply := &waE2E.ListResponseMessage{
+ SingleSelectReply: &waE2E.ListResponseMessage_SingleSelectReply{SelectedRowID: proto.String("row-void-pnr")},
+ }
+ _, payload, err := buildEventPayload(context.Background(), nil, businessEvent("LR1", &waE2E.Message{ListResponseMessage: reply}))
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ selection, ok := payload["selection"].(utils.BusinessSelection)
+ if !ok || selection.Kind != "list" || selection.SelectedID != "row-void-pnr" {
+ t.Fatalf("selected row not kept: %#v", payload["selection"])
+ }
+ if payload["body"] != "Selected option row-void-pnr" {
+ t.Fatalf("unexpected body %q", payload["body"])
+ }
+}
+
+func TestBusinessMessagesAreRecognized(t *testing.T) {
+ for name, msg := range map[string]*waE2E.Message{
+ "interactive": {InteractiveMessage: &waE2E.InteractiveMessage{}},
+ "template": {TemplateMessage: businessOrderTemplate()},
+ "buttons": {ButtonsMessage: &waE2E.ButtonsMessage{}},
+ "product": {ProductMessage: &waE2E.ProductMessage{}},
+ "list reply": {ListResponseMessage: &waE2E.ListResponseMessage{}},
+ "buttons reply": {ButtonsResponseMessage: &waE2E.ButtonsResponseMessage{}},
+ "template reply": {TemplateButtonReplyMessage: &waE2E.TemplateButtonReplyMessage{}},
+ "native reply": {InteractiveResponseMessage: &waE2E.InteractiveResponseMessage{}},
+ } {
+ if !hasRecognizedMessageType(msg) {
+ t.Errorf("%s should be a recognized message type", name)
+ }
+ }
+}
+
+// Runs each message the way Chatwoot receives it, live and after the retry
+// queue's JSON round-trip.
+func TestChatwootContentForBusinessMessages(t *testing.T) {
+ tests := []struct {
+ name string
+ msg *waE2E.Message
+ want string
+ }{
+ {
+ name: "template",
+ msg: &waE2E.Message{TemplateMessage: businessOrderTemplate()},
+ want: "Order confirmed\nHi John, your order #1234 has shipped.\nAcme Store\n🔗 Track order: https://acme.example/track/1234",
+ },
+ {
+ // The interactive summary skips the markdown pass, so the
+ // underscores in the URL stay intact.
+ name: "interactive with header, footer and cta_url",
+ msg: &waE2E.Message{InteractiveMessage: &waE2E.InteractiveMessage{
+ Header: &waE2E.InteractiveMessage_Header{Title: proto.String("Support")},
+ Body: &waE2E.InteractiveMessage_Body{Text: proto.String("How can we help?")},
+ Footer: &waE2E.InteractiveMessage_Footer{Text: proto.String("Acme Support")},
+ InteractiveMessage: &waE2E.InteractiveMessage_NativeFlowMessage_{NativeFlowMessage: &waE2E.InteractiveMessage_NativeFlowMessage{
+ Buttons: []*waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton{{
+ Name: proto.String("cta_url"),
+ ButtonParamsJSON: proto.String(`{"display_text":"Visit site","url":"https://acme.example/help?utm_source=wa&utm_medium=cta"}`),
+ }},
+ }},
+ }},
+ want: "Support\nHow can we help?\nAcme Support\n🔗 Visit site: https://acme.example/help?utm_source=wa&utm_medium=cta",
+ },
+ {
+ name: "product",
+ msg: &waE2E.Message{ProductMessage: &waE2E.ProductMessage{Product: &waE2E.ProductMessage_ProductSnapshot{
+ Title: proto.String("Weekend package"), CurrencyCode: proto.String("IDR"), PriceAmount1000: proto.Int64(3500000),
+ }}},
+ want: "Product: Weekend package (IDR 3500.00)",
+ },
+ {
+ name: "list reply with only a row id",
+ msg: &waE2E.Message{ListResponseMessage: &waE2E.ListResponseMessage{
+ SingleSelectReply: &waE2E.ListResponseMessage_SingleSelectReply{SelectedRowID: proto.String("opt_book_now")},
+ }},
+ want: "Selected option opt_book_now",
+ },
+ {
+ // Template text goes through the markdown pass: *bold* converts,
+ // but the URL's underscores must not turn into italics.
+ name: "template with formatting and a UTM link",
+ msg: &waE2E.Message{TemplateMessage: &waE2E.TemplateMessage{HydratedTemplate: &waE2E.TemplateMessage_HydratedFourRowTemplate{
+ HydratedContentText: proto.String("Your order *#1234* has shipped."),
+ HydratedButtons: []*waE2E.HydratedTemplateButton{
+ {HydratedButton: &waE2E.HydratedTemplateButton_UrlButton{UrlButton: &waE2E.HydratedTemplateButton_HydratedURLButton{
+ DisplayText: proto.String("Track"), URL: proto.String("https://acme.example/t?utm_source=wa&utm_medium=tpl")}}},
+ },
+ }}},
+ want: "Your order **#1234** has shipped.\n🔗 Track: https://acme.example/t?utm_source=wa&utm_medium=tpl",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ _, payload, err := buildEventPayload(context.Background(), nil, businessEvent("CW1", tt.msg))
+ if err != nil {
+ t.Fatalf("buildEventPayload: %v", err)
+ }
+ if live, _ := buildChatwootMessageContent(payload, false, ""); live != tt.want {
+ t.Fatalf("live content = %q, want %q", live, tt.want)
+ }
+
+ raw, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ var replayed map[string]any
+ if err := json.Unmarshal(raw, &replayed); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if retried, _ := buildChatwootMessageContent(replayed, false, ""); retried != tt.want {
+ t.Fatalf("retried content = %q, want %q", retried, tt.want)
+ }
+ })
+ }
+}
diff --git a/src/infrastructure/whatsapp/event_message.go b/src/infrastructure/whatsapp/event_message.go
index b37c4c00..8d02a6f0 100644
--- a/src/infrastructure/whatsapp/event_message.go
+++ b/src/infrastructure/whatsapp/event_message.go
@@ -181,8 +181,8 @@ func buildEventPayload(ctx context.Context, client *whatsmeow.Client, evt *event
if payloadHasNoRenderableContent(payload) && !hasRecognizedMessageType(msg) {
// Neither a recognized message type nor any renderable payload field:
- // this is genuinely an unhandled kind (e.g. templates, interactive/
- // native-flow messages, polls, group invites, payment requests).
+ // this is genuinely an unhandled kind (e.g. group invites, payment
+ // requests).
// Downstream (Chatwoot) will render it as "(Unsupported message
// type)" with no way to tell which WhatsApp message kind caused it.
// Log which proto field is populated — never its value, since that
@@ -209,6 +209,7 @@ func payloadHasNoRenderableContent(payload map[string]any) bool {
"body",
"image", "audio", "video", "video_note", "document", "sticker",
"contact", "contacts_array", "list", "live_location", "location", "order",
+ "template", "buttons", "product", "selection", "interactive",
}
for _, key := range renderableKeys {
if _, ok := payload[key]; ok {
@@ -236,7 +237,15 @@ func hasRecognizedMessageType(msg *waE2E.Message) bool {
msg.GetListMessage() != nil,
msg.GetLiveLocationMessage() != nil,
msg.GetLocationMessage() != nil,
- msg.GetOrderMessage() != nil:
+ msg.GetOrderMessage() != nil,
+ msg.GetInteractiveMessage() != nil,
+ msg.GetTemplateMessage() != nil,
+ msg.GetButtonsMessage() != nil,
+ msg.GetProductMessage() != nil,
+ msg.GetListResponseMessage() != nil,
+ msg.GetButtonsResponseMessage() != nil,
+ msg.GetTemplateButtonReplyMessage() != nil,
+ msg.GetInteractiveResponseMessage() != nil:
return true
default:
return false
@@ -566,20 +575,31 @@ func buildOtherMessageTypes(msg *waE2E.Message, payload map[string]any) {
payload["order"] = orderMessage
}
+ if template := utils.BuildTemplatePayload(msg); template != nil {
+ payload["template"] = *template
+ }
+ if buttons := utils.BuildButtonsPayload(msg); buttons != nil {
+ payload["buttons"] = *buttons
+ }
+ if product := utils.BuildProductPayload(msg); product != nil {
+ payload["product"] = *product
+ }
+ if selection := utils.BuildSelectionPayload(msg); selection != nil {
+ payload["selection"] = *selection
+ }
+
if interactiveMessage := msg.GetInteractiveMessage(); interactiveMessage != nil {
// Business/Cloud API messages with native buttons (cta_url "visit
// website", cta_call, single/multi-select, etc.) arrive as this type
- // instead of Conversation/ExtendedTextMessage, so they carried no
- // body text and rendered as "(Unsupported message type)" in Chatwoot.
+ // instead of Conversation/ExtendedTextMessage. body carries the same
+ // summary, but buildChatwootMessageContent forwards this copy without
+ // its markdown pass.
//
// Rendered to a string here, not stored as the raw proto: a failed
// live forward gets re-marshaled through JSON for the retry queue
// (see enqueueChatwootForwardRetry/replayChatwootForwardEvent), which
- // turns *waE2E.InteractiveMessage into a generic map[string]any —
- // the type assertion in extractStructuredMessageContent would then
- // miss on retry and silently downgrade to the generic sentinel,
- // losing the CTA label/URL/phone/code the live path just extracted.
- payload["interactive"] = formatInteractiveMessageSummary(interactiveMessage)
+ // turns *waE2E.InteractiveMessage into a generic map[string]any.
+ payload["interactive"] = utils.FormatInteractiveMessageSummary(interactiveMessage)
}
}
diff --git a/src/infrastructure/whatsapp/history_sync_test.go b/src/infrastructure/whatsapp/history_sync_test.go
index 5bedd2f2..10cc1e56 100644
--- a/src/infrastructure/whatsapp/history_sync_test.go
+++ b/src/infrastructure/whatsapp/history_sync_test.go
@@ -225,6 +225,68 @@ func TestProcessConversationMessagesOnDemandPreservesNewerChatMetadata(t *testin
}
}
+// History sync delivers messages still wrapped (e.g. in disappearing-message
+// chats). A wrapped captioned image must keep its media columns, or re-syncing
+// a row the live path stored would wipe them, and a wrapped business template
+// must not be skipped.
+func TestProcessConversationMessagesUnwrapsHistoryMessages(t *testing.T) {
+ originalLog := log
+ log = waLog.Noop
+ defer func() { log = originalLog }()
+
+ deviceID := "[email protected]"
+ chatJID := "[email protected]"
+ repo := &historyMessageBatchRepoSpy{}
+ ctx := ContextWithDevice(context.Background(), NewDeviceInstance(deviceID, nil, nil))
+ syncType := waHistorySync.HistorySync_ON_DEMAND
+ timestamp := uint64(time.Date(2026, time.September, 1, 8, 0, 0, 0, time.UTC).Unix())
+ ephemeral := func(id string, inner *waE2E.Message) *waHistorySync.HistorySyncMsg {
+ return &waHistorySync.HistorySyncMsg{Message: &waWeb.WebMessageInfo{
+ Key: &waCommon.MessageKey{RemoteJID: proto.String(chatJID), FromMe: proto.Bool(false), ID: proto.String(id)},
+ Message: &waE2E.Message{EphemeralMessage: &waE2E.FutureProofMessage{Message: inner}},
+ MessageTimestamp: &timestamp,
+ }}
+ }
+ data := &waHistorySync.HistorySync{
+ SyncType: &syncType,
+ Conversations: []*waHistorySync.Conversation{{
+ ID: proto.String(chatJID),
+ Messages: []*waHistorySync.HistorySyncMsg{
+ ephemeral("img-1", &waE2E.Message{ImageMessage: &waE2E.ImageMessage{
+ Caption: proto.String("look at this"),
+ DirectPath: proto.String("/v/t62/abc"),
+ MediaKey: []byte{1, 2, 3},
+ }}),
+ ephemeral("tpl-1", &waE2E.Message{TemplateMessage: &waE2E.TemplateMessage{
+ HydratedTemplate: &waE2E.TemplateMessage_HydratedFourRowTemplate{
+ Title: &waE2E.TemplateMessage_HydratedFourRowTemplate_HydratedTitleText{HydratedTitleText: "Order confirmed"},
+ HydratedContentText: proto.String("Your order #42 has shipped"),
+ },
+ }}),
+ },
+ }},
+ }
+
+ if err := processConversationMessages(ctx, data, repo, nil); err != nil {
+ t.Fatalf("processConversationMessages: %v", err)
+ }
+
+ if len(repo.lastBatch) != 2 {
+ t.Fatalf("expected both wrapped messages to be stored, got %d", len(repo.lastBatch))
+ }
+ image, template := repo.lastBatch[0], repo.lastBatch[1]
+ if image.MediaType != "image" || image.DirectPath != "/v/t62/abc" || len(image.MediaKey) == 0 || image.Content != "look at this" {
+ t.Fatalf("wrapped image lost its media: %+v", image)
+ }
+ if template.Content != "Order confirmed\nYour order #42 has shipped" {
+ t.Fatalf("unexpected template content %q", template.Content)
+ }
+ // On main this chat had no storable message, so it was never created.
+ if repo.lastStoredChat == nil || repo.lastStoredChat.JID != chatJID {
+ t.Fatalf("expected the chat to be stored, got %+v", repo.lastStoredChat)
+ }
+}
+
type historyMessageBatchRepoSpy struct {
domainChatStorage.IChatStorageRepository
storeMessagesBatchCalls int
diff --git a/src/infrastructure/whatsapp/webhook_forward.go b/src/infrastructure/whatsapp/webhook_forward.go
index d943599c..def1b888 100644
--- a/src/infrastructure/whatsapp/webhook_forward.go
+++ b/src/infrastructure/whatsapp/webhook_forward.go
@@ -15,7 +15,6 @@ import (
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/sirupsen/logrus"
- "go.mau.fi/whatsmeow/proto/waE2E"
"go.mau.fi/whatsmeow/types"
)
@@ -559,7 +558,11 @@ func buildChatwootMessageContent(data map[string]any, isGroup bool, fromName str
}
prefixGroupSender := isGroup && !fromMe && senderLabel != ""
- if body, ok := data["body"].(string); ok && body != "" {
+ // Interactive messages carry the same summary as body, but it has always
+ // been forwarded without the markdown pass below.
+ if interactive, ok := data["interactive"].(string); ok && interactive != "" {
+ content = interactive
+ } else if body, ok := data["body"].(string); ok && body != "" {
// Translate WhatsApp formatting (*bold*, _italic_, ~strike~) into the
// GitHub-flavored markdown Chatwoot renders so emphasis survives the hop.
content = utils.WhatsAppToChatwootMarkdown(body)
@@ -777,157 +780,9 @@ func extractStructuredMessageContent(data map[string]any) string {
return "Order message"
}
- if interactive, ok := data["interactive"].(string); ok && interactive != "" {
- // Pre-rendered by buildOtherMessageTypes at construction time (not
- // stored as the raw proto) so it survives the JSON round-trip on the
- // Chatwoot forward retry path; see the comment at that call site.
- return interactive
- }
-
return ""
}
-// formatInteractiveMessageSummary renders an InteractiveMessage (business/
-// Cloud API messages with native buttons: cta_url, cta_call, single/multi
-// select, etc.) as plain text, since Chatwoot has no native concept of a
-// WhatsApp interactive button. Buttons are described in buttonParamsJSON as
-// a per-button-type JSON blob (undocumented, reverse-engineered from
-// traffic), so only the fields relevant to rendering are decoded and
-// anything unrecognized still shows the button's raw name.
-func formatInteractiveMessageSummary(im *waE2E.InteractiveMessage) string {
- var parts []string
-
- if header := im.GetHeader(); header != nil {
- if title := header.GetTitle(); title != "" {
- parts = append(parts, title)
- }
- if subtitle := header.GetSubtitle(); subtitle != "" {
- parts = append(parts, subtitle)
- }
- // Media captions on interactive headers never reach payload["body"]
- // (ExtractMediaCaption only handles top-level Get*Message() cases,
- // not InteractiveMessage.Header) — surface them here instead of
- // silently dropping them, since collectInteractiveMedia forwards the
- // file itself but nothing else carries the caption text.
- if caption := interactiveHeaderMediaCaption(header); caption != "" {
- parts = append(parts, caption)
- }
- }
- if body := im.GetBody(); body != nil {
- if text := body.GetText(); text != "" {
- parts = append(parts, text)
- }
- }
- if footer := im.GetFooter(); footer != nil {
- if text := footer.GetText(); text != "" {
- parts = append(parts, text)
- }
- }
-
- for _, button := range im.GetNativeFlowMessage().GetButtons() {
- if line := formatNativeFlowButton(button); line != "" {
- parts = append(parts, line)
- }
- }
-
- // Carousels put their CTA/quick-reply buttons on each card rather than on
- // the top-level NativeFlowMessage, so the loop above sees none of them —
- // summarize each card (itself a full InteractiveMessage) separately.
- if carousel := im.GetCarouselMessage(); carousel != nil {
- for i, card := range carousel.GetCards() {
- if cardSummary := formatInteractiveMessageSummary(card); cardSummary != "" && cardSummary != "Interactive message" {
- parts = append(parts, fmt.Sprintf("Card %d: %s", i+1, cardSummary))
- }
- }
- }
-
- if len(parts) == 0 {
- return "Interactive message"
- }
- return strings.Join(parts, "\n")
-}
-
-// interactiveHeaderMediaCaption returns the caption on whichever media type
-// (if any) an InteractiveMessage header carries. Mirrors utils.ExtractMediaCaption's
-// per-type checks, scoped to the Header oneof instead of top-level Get*Message().
-func interactiveHeaderMediaCaption(header *waE2E.InteractiveMessage_Header) string {
- if header == nil {
- return ""
- }
- if img := header.GetImageMessage(); img != nil {
- return img.GetCaption()
- }
- if vid := header.GetVideoMessage(); vid != nil {
- return vid.GetCaption()
- }
- if doc := header.GetDocumentMessage(); doc != nil {
- return doc.GetCaption()
- }
- return ""
-}
-
-// nativeFlowButtonParams covers the fields used by the button types this
-// forwarder renders specially (cta_url, cta_call, cta_copy). Other button
-// names (e.g. single_select, review_and_pay) fall through to displaying the
-// raw button name, since their params carry structured picker/payment data
-// that doesn't reduce to a single line of text.
-type nativeFlowButtonParams struct {
- DisplayText string `json:"display_text"`
- URL string `json:"url"`
- PhoneNumber string `json:"phone_number"`
- Copy string `json:"copy_code"`
- // Title is the visible label field used by picker-style buttons (e.g.
- // single_select's {"title":...,"sections":...}), which don't set
- // display_text at all.
- Title string `json:"title"`
-}
-
-func formatNativeFlowButton(button *waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton) string {
- if button == nil {
- return ""
- }
- name := button.GetName()
-
- var params nativeFlowButtonParams
- _ = json.Unmarshal([]byte(button.GetButtonParamsJSON()), &params)
-
- switch name {
- case "cta_url":
- label := params.DisplayText
- if label == "" {
- label = "Link"
- }
- if params.URL != "" {
- return fmt.Sprintf("🔗 %s: %s", label, params.URL)
- }
- case "cta_call":
- label := params.DisplayText
- if label == "" {
- label = "Call"
- }
- if params.PhoneNumber != "" {
- return fmt.Sprintf("📞 %s: %s", label, params.PhoneNumber)
- }
- case "cta_copy":
- label := params.DisplayText
- if label == "" {
- label = "Copy code"
- }
- if params.Copy != "" {
- return fmt.Sprintf("📋 %s: %s", label, params.Copy)
- }
- }
-
- label := params.DisplayText
- if label == "" {
- label = params.Title
- }
- if label != "" {
- return fmt.Sprintf("[%s] %s", name, label)
- }
- return fmt.Sprintf("[%s]", name)
-}
-
func extractContactDetails(contact any) (name string, phone string, ok bool) {
switch c := contact.(type) {
case webhookContactPayload:
diff --git a/src/pkg/utils/business_message.go b/src/pkg/utils/business_message.go
new file mode 100644
index 00000000..8c28ea19
--- /dev/null
+++ b/src/pkg/utils/business_message.go
@@ -0,0 +1,524 @@
+package utils
+
+import (
+ "cmp"
+ "encoding/json"
+ "fmt"
+ "strings"
+
+ "go.mau.fi/whatsmeow/proto/waE2E"
+)
+
+// WhatsApp Business / Cloud API senders put their text in template, buttons,
+// interactive, list, product and order messages instead of Conversation or
+// ExtendedTextMessage. The Build*Payload helpers expose them to webhooks as
+// plain structs (not protos, so they survive a JSON round-trip), and
+// extractBusinessMessageText renders the same data as the text used for the
+// webhook body, stored message content and Chatwoot.
+
+type BusinessButton struct {
+ Type string `json:"type"` // quick_reply, url, call, copy, or the native-flow name
+ Text string `json:"text,omitempty"`
+ ID string `json:"id,omitempty"`
+ URL string `json:"url,omitempty"`
+ Phone string `json:"phone_number,omitempty"`
+ Code string `json:"code,omitempty"`
+ Rows []BusinessButtonRow `json:"rows,omitempty"` // single_select options
+}
+
+type BusinessButtonRow struct {
+ ID string `json:"id"`
+ Title string `json:"title,omitempty"`
+ Description string `json:"description,omitempty"`
+}
+
+// BusinessMessage is a template or buttons message for webhooks.
+type BusinessMessage struct {
+ Title string `json:"title,omitempty"`
+ Subtitle string `json:"subtitle,omitempty"`
+ HeaderType string `json:"header_type,omitempty"` // image, video, document, location, product
+ Body string `json:"body,omitempty"`
+ Footer string `json:"footer,omitempty"`
+ TemplateID string `json:"template_id,omitempty"`
+ Buttons []BusinessButton `json:"buttons,omitempty"`
+ Cards []BusinessMessage `json:"cards,omitempty"`
+}
+
+// BusinessProduct is a ProductMessage for webhooks. Prices are in WhatsApp's
+// unit (amount x 1000).
+type BusinessProduct struct {
+ ProductID string `json:"product_id,omitempty"`
+ Title string `json:"title,omitempty"`
+ Description string `json:"description,omitempty"`
+ CurrencyCode string `json:"currency_code,omitempty"`
+ PriceAmount1000 int64 `json:"price_amount_1000,omitempty"`
+ SalePriceAmount1000 int64 `json:"sale_price_amount_1000,omitempty"`
+ RetailerID string `json:"retailer_id,omitempty"`
+ URL string `json:"url,omitempty"`
+ CatalogTitle string `json:"catalog_title,omitempty"`
+ Body string `json:"body,omitempty"`
+ Footer string `json:"footer,omitempty"`
+ BusinessOwnerJID string `json:"business_owner_jid,omitempty"`
+}
+
+// BusinessSelection is a tap on a list row, button, template quick reply or
+// native-flow button. SelectedID matches the row or button id of the original
+// message.
+type BusinessSelection struct {
+ Kind string `json:"kind"` // list, buttons, template, interactive
+ Text string `json:"text,omitempty"`
+ Description string `json:"description,omitempty"`
+ SelectedID string `json:"selected_id,omitempty"`
+}
+
+// templateMessage returns the template carried by msg. Legacy senders wrap
+// it in a HighlyStructuredMessage; only the hydrated form carries text.
+func templateMessage(msg *waE2E.Message) *waE2E.TemplateMessage {
+ return cmp.Or(msg.GetTemplateMessage(), msg.GetHighlyStructuredMessage().GetHydratedHsm())
+}
+
+// BuildTemplatePayload returns the template (or hydrated HSM) in msg as a
+// webhook struct, or nil.
+func BuildTemplatePayload(msg *waE2E.Message) *BusinessMessage {
+ tm := templateMessage(msg)
+ if tm == nil {
+ return nil
+ }
+ hydrated := cmp.Or(tm.GetHydratedTemplate(), tm.GetHydratedFourRowTemplate())
+ templateID := cmp.Or(tm.GetTemplateID(), hydrated.GetTemplateID())
+ if im := tm.GetInteractiveMessageTemplate(); im != nil {
+ out := interactiveAsBusinessMessage(im)
+ out.TemplateID = templateID
+ return out
+ }
+ if hydrated != nil {
+ out := &BusinessMessage{
+ Title: hydrated.GetHydratedTitleText(),
+ HeaderType: templateHeaderType(hydrated),
+ Body: hydrated.GetHydratedContentText(),
+ Footer: hydrated.GetHydratedFooterText(),
+ TemplateID: templateID,
+ }
+ for _, button := range hydrated.GetHydratedButtons() {
+ if b, ok := hydratedTemplateButton(button); ok {
+ out.Buttons = append(out.Buttons, b)
+ }
+ }
+ return out
+ }
+ // A non-hydrated four-row template only has HSM element names.
+ if templateID != "" {
+ return &BusinessMessage{TemplateID: templateID}
+ }
+ return nil
+}
+
+func templateHeaderType(t *waE2E.TemplateMessage_HydratedFourRowTemplate) string {
+ switch {
+ case t.GetImageMessage() != nil:
+ return "image"
+ case t.GetVideoMessage() != nil:
+ return "video"
+ case t.GetDocumentMessage() != nil:
+ return "document"
+ case t.GetLocationMessage() != nil:
+ return "location"
+ }
+ return ""
+}
+
+func hydratedTemplateButton(button *waE2E.HydratedTemplateButton) (BusinessButton, bool) {
+ switch {
+ case button.GetQuickReplyButton() != nil:
+ quick := button.GetQuickReplyButton()
+ return BusinessButton{Type: "quick_reply", Text: quick.GetDisplayText(), ID: quick.GetID()}, true
+ case button.GetUrlButton() != nil:
+ link := button.GetUrlButton()
+ return BusinessButton{Type: "url", Text: link.GetDisplayText(), URL: link.GetURL()}, true
+ case button.GetCallButton() != nil:
+ call := button.GetCallButton()
+ return BusinessButton{Type: "call", Text: call.GetDisplayText(), Phone: call.GetPhoneNumber()}, true
+ }
+ return BusinessButton{}, false
+}
+
+// BuildButtonsPayload returns the ButtonsMessage in msg as a webhook struct,
+// or nil.
+func BuildButtonsPayload(msg *waE2E.Message) *BusinessMessage {
+ bm := msg.GetButtonsMessage()
+ if bm == nil {
+ return nil
+ }
+ out := &BusinessMessage{
+ Title: bm.GetText(),
+ Body: bm.GetContentText(),
+ Footer: bm.GetFooterText(),
+ }
+ switch {
+ case bm.GetImageMessage() != nil:
+ out.HeaderType = "image"
+ case bm.GetVideoMessage() != nil:
+ out.HeaderType = "video"
+ case bm.GetDocumentMessage() != nil:
+ out.HeaderType = "document"
+ case bm.GetLocationMessage() != nil:
+ out.HeaderType = "location"
+ }
+ for _, button := range bm.GetButtons() {
+ if info := button.GetNativeFlowInfo(); info != nil {
+ out.Buttons = append(out.Buttons, nativeFlowAsButton(info.GetName(), info.GetParamsJSON(), button.GetButtonID()))
+ continue
+ }
+ out.Buttons = append(out.Buttons, BusinessButton{
+ Type: "quick_reply",
+ Text: button.GetButtonText().GetDisplayText(),
+ ID: button.GetButtonID(),
+ })
+ }
+ return out
+}
+
+// interactiveAsBusinessMessage maps an InteractiveMessage wrapped in a
+// template onto the same shape. Carousel cards are mapped recursively.
+func interactiveAsBusinessMessage(im *waE2E.InteractiveMessage) *BusinessMessage {
+ header := im.GetHeader()
+ out := &BusinessMessage{
+ Title: header.GetTitle(),
+ Subtitle: header.GetSubtitle(),
+ HeaderType: interactiveHeaderType(header),
+ Body: im.GetBody().GetText(),
+ Footer: im.GetFooter().GetText(),
+ }
+ for _, button := range im.GetNativeFlowMessage().GetButtons() {
+ out.Buttons = append(out.Buttons, nativeFlowAsButton(button.GetName(), button.GetButtonParamsJSON(), ""))
+ }
+ for _, card := range im.GetCarouselMessage().GetCards() {
+ out.Cards = append(out.Cards, *interactiveAsBusinessMessage(card))
+ }
+ return out
+}
+
+func interactiveHeaderType(h *waE2E.InteractiveMessage_Header) string {
+ switch {
+ case h.GetImageMessage() != nil:
+ return "image"
+ case h.GetVideoMessage() != nil:
+ return "video"
+ case h.GetDocumentMessage() != nil:
+ return "document"
+ case h.GetLocationMessage() != nil:
+ return "location"
+ case h.GetProductMessage() != nil:
+ return "product"
+ }
+ return ""
+}
+
+func nativeFlowAsButton(name, paramsJSON, fallbackID string) BusinessButton {
+ var params nativeFlowButtonParams
+ _ = json.Unmarshal([]byte(paramsJSON), &params)
+ text := cmp.Or(params.DisplayText, params.Title)
+ switch name {
+ case "cta_url":
+ return BusinessButton{Type: "url", Text: text, URL: params.URL}
+ case "cta_call":
+ return BusinessButton{Type: "call", Text: text, Phone: params.PhoneNumber}
+ case "cta_copy":
+ return BusinessButton{Type: "copy", Text: text, Code: params.Copy}
+ }
+ button := BusinessButton{Type: name, Text: text, ID: cmp.Or(params.ID, fallbackID)}
+ for _, section := range params.Sections {
+ for _, row := range section.Rows {
+ button.Rows = append(button.Rows, BusinessButtonRow{ID: row.ID, Title: row.Title, Description: row.Description})
+ }
+ }
+ return button
+}
+
+// BuildProductPayload returns the ProductMessage in msg as a webhook struct,
+// or nil.
+func BuildProductPayload(msg *waE2E.Message) *BusinessProduct {
+ pm := msg.GetProductMessage()
+ if pm == nil {
+ return nil
+ }
+ product := pm.GetProduct()
+ return &BusinessProduct{
+ ProductID: product.GetProductID(),
+ Title: product.GetTitle(),
+ Description: product.GetDescription(),
+ CurrencyCode: product.GetCurrencyCode(),
+ PriceAmount1000: product.GetPriceAmount1000(),
+ SalePriceAmount1000: product.GetSalePriceAmount1000(),
+ RetailerID: product.GetRetailerID(),
+ URL: product.GetURL(),
+ CatalogTitle: pm.GetCatalog().GetTitle(),
+ Body: pm.GetBody(),
+ Footer: pm.GetFooter(),
+ BusinessOwnerJID: pm.GetBusinessOwnerJID(),
+ }
+}
+
+// BuildSelectionPayload returns the list, buttons, template or native-flow
+// reply in msg, or nil.
+func BuildSelectionPayload(msg *waE2E.Message) *BusinessSelection {
+ switch {
+ case msg.GetListResponseMessage() != nil:
+ reply := msg.GetListResponseMessage()
+ return &BusinessSelection{
+ Kind: "list",
+ Text: reply.GetTitle(),
+ Description: reply.GetDescription(),
+ SelectedID: reply.GetSingleSelectReply().GetSelectedRowID(),
+ }
+ case msg.GetButtonsResponseMessage() != nil:
+ reply := msg.GetButtonsResponseMessage()
+ return &BusinessSelection{Kind: "buttons", Text: reply.GetSelectedDisplayText(), SelectedID: reply.GetSelectedButtonID()}
+ case msg.GetTemplateButtonReplyMessage() != nil:
+ reply := msg.GetTemplateButtonReplyMessage()
+ return &BusinessSelection{Kind: "template", Text: reply.GetSelectedDisplayText(), SelectedID: reply.GetSelectedID()}
+ case msg.GetInteractiveResponseMessage() != nil:
+ reply := msg.GetInteractiveResponseMessage()
+ var params nativeFlowButtonParams
+ _ = json.Unmarshal([]byte(reply.GetNativeFlowResponseMessage().GetParamsJSON()), &params)
+ return &BusinessSelection{Kind: "interactive", Text: reply.GetBody().GetText(), SelectedID: params.ID}
+ }
+ return nil
+}
+
+// extractBusinessMessageText renders a business message, or a reply to one,
+// as plain text. Messages without any text get a placeholder so they still
+// show up in the chat instead of being skipped by storage.
+func extractBusinessMessageText(msg *waE2E.Message) string {
+ if tm := templateMessage(msg); tm != nil {
+ if im := tm.GetInteractiveMessageTemplate(); im != nil {
+ return FormatInteractiveMessageSummary(im)
+ }
+ return cmp.Or(businessMessageLines(BuildTemplatePayload(msg)), "Template message")
+ }
+ if im := msg.GetInteractiveMessage(); im != nil {
+ return FormatInteractiveMessageSummary(im)
+ }
+ if buttons := BuildButtonsPayload(msg); buttons != nil {
+ return cmp.Or(businessMessageLines(buttons), "Buttons message")
+ }
+ if list := msg.GetListMessage(); list != nil {
+ title := list.GetTitle()
+ if title != "" {
+ title = "List: " + title
+ }
+ rendered := &BusinessMessage{Title: title, Body: list.GetDescription(), Footer: list.GetFooterText()}
+ for _, section := range list.GetSections() {
+ for _, row := range section.GetRows() {
+ rendered.Buttons = append(rendered.Buttons, BusinessButton{Text: row.GetTitle()})
+ }
+ }
+ return cmp.Or(businessMessageLines(rendered), "List message")
+ }
+ if product := BuildProductPayload(msg); product != nil {
+ line := "Product"
+ if product.Title != "" {
+ line += ": " + product.Title
+ }
+ if price := cmp.Or(product.SalePriceAmount1000, product.PriceAmount1000); price > 0 && product.CurrencyCode != "" {
+ line += fmt.Sprintf(" (%s %.2f)", product.CurrencyCode, float64(price)/1000)
+ }
+ return joinNonEmptyLines(line, product.Body, product.Footer)
+ }
+ if order := msg.GetOrderMessage(); order != nil {
+ title := order.GetOrderTitle()
+ if title != "" {
+ title = "Order: " + title
+ }
+ return cmp.Or(joinNonEmptyLines(title, order.GetMessage()), "Order message")
+ }
+ if selection := BuildSelectionPayload(msg); selection != nil {
+ text := cmp.Or(selection.Text, selection.Description)
+ // Recent clients send list and native-flow replies with only the id.
+ if text == "" && selection.SelectedID != "" {
+ text = "Selected option " + selection.SelectedID
+ }
+ return cmp.Or(text, "Selection message")
+ }
+ return ""
+}
+
+// businessMessageLines renders the rows, then one line per button: the same
+// 🔗/📞/📋 lines as FormatInteractiveMessageSummary, other buttons as [label].
+func businessMessageLines(message *BusinessMessage) string {
+ if message == nil {
+ return ""
+ }
+ parts := []string{message.Title, message.Body, message.Footer}
+ for _, button := range message.Buttons {
+ switch {
+ case button.Type == "url" && button.URL != "":
+ parts = append(parts, fmt.Sprintf("🔗 %s: %s", cmp.Or(button.Text, "Link"), button.URL))
+ case button.Type == "call" && button.Phone != "":
+ parts = append(parts, fmt.Sprintf("📞 %s: %s", cmp.Or(button.Text, "Call"), button.Phone))
+ case button.Type == "copy" && button.Code != "":
+ parts = append(parts, fmt.Sprintf("📋 %s: %s", cmp.Or(button.Text, "Copy code"), button.Code))
+ case button.Text != "" || button.Type != "":
+ parts = append(parts, fmt.Sprintf("[%s]", cmp.Or(button.Text, button.Type)))
+ }
+ }
+ return joinNonEmptyLines(parts...)
+}
+
+func joinNonEmptyLines(values ...string) string {
+ var lines []string
+ for _, value := range values {
+ if value != "" {
+ lines = append(lines, value)
+ }
+ }
+ return strings.Join(lines, "\n")
+}
+
+// FormatInteractiveMessageSummary renders an InteractiveMessage (business/
+// Cloud API messages with native buttons: cta_url, cta_call, single/multi
+// select, etc.) as plain text, since neither chat storage nor Chatwoot has a
+// native concept of a WhatsApp interactive button. Buttons are described in
+// buttonParamsJSON as a per-button-type JSON blob (undocumented,
+// reverse-engineered from traffic), so only the fields relevant to rendering
+// are decoded and anything unrecognized still shows the button's raw name.
+func FormatInteractiveMessageSummary(im *waE2E.InteractiveMessage) string {
+ var parts []string
+
+ if header := im.GetHeader(); header != nil {
+ if title := header.GetTitle(); title != "" {
+ parts = append(parts, title)
+ }
+ if subtitle := header.GetSubtitle(); subtitle != "" {
+ parts = append(parts, subtitle)
+ }
+ // ExtractMediaCaption only handles top-level Get*Message() cases, not
+ // InteractiveMessage.Header — surface header captions here, since
+ // collectInteractiveMedia forwards the file itself but nothing else
+ // carries the caption text.
+ if caption := interactiveHeaderMediaCaption(header); caption != "" {
+ parts = append(parts, caption)
+ }
+ }
+ if body := im.GetBody(); body != nil {
+ if text := body.GetText(); text != "" {
+ parts = append(parts, text)
+ }
+ }
+ if footer := im.GetFooter(); footer != nil {
+ if text := footer.GetText(); text != "" {
+ parts = append(parts, text)
+ }
+ }
+
+ for _, button := range im.GetNativeFlowMessage().GetButtons() {
+ if line := formatNativeFlowButton(button); line != "" {
+ parts = append(parts, line)
+ }
+ }
+
+ // Carousels put their CTA/quick-reply buttons on each card rather than on
+ // the top-level NativeFlowMessage, so the loop above sees none of them —
+ // summarize each card (itself a full InteractiveMessage) separately.
+ if carousel := im.GetCarouselMessage(); carousel != nil {
+ for i, card := range carousel.GetCards() {
+ if cardSummary := FormatInteractiveMessageSummary(card); cardSummary != "" && cardSummary != "Interactive message" {
+ parts = append(parts, fmt.Sprintf("Card %d: %s", i+1, cardSummary))
+ }
+ }
+ }
+
+ if len(parts) == 0 {
+ return "Interactive message"
+ }
+ return strings.Join(parts, "\n")
+}
+
+// interactiveHeaderMediaCaption returns the caption on whichever media type
+// (if any) an InteractiveMessage header carries. Mirrors ExtractMediaCaption's
+// per-type checks, scoped to the Header oneof instead of top-level Get*Message().
+func interactiveHeaderMediaCaption(header *waE2E.InteractiveMessage_Header) string {
+ if header == nil {
+ return ""
+ }
+ if img := header.GetImageMessage(); img != nil {
+ return img.GetCaption()
+ }
+ if vid := header.GetVideoMessage(); vid != nil {
+ return vid.GetCaption()
+ }
+ if doc := header.GetDocumentMessage(); doc != nil {
+ return doc.GetCaption()
+ }
+ return ""
+}
+
+// nativeFlowButtonParams covers the fields used by the button types rendered
+// specially (cta_url, cta_call, cta_copy), plus the id and single_select rows
+// that nativeFlowAsButton exposes to webhooks. Other button names (e.g.
+// review_and_pay) fall through to displaying the raw button name, since their
+// params carry structured payment data that doesn't reduce to a single line.
+type nativeFlowButtonParams struct {
+ DisplayText string `json:"display_text"`
+ URL string `json:"url"`
+ PhoneNumber string `json:"phone_number"`
+ Copy string `json:"copy_code"`
+ ID string `json:"id"`
+ Sections []struct {
+ Rows []struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ } `json:"rows"`
+ } `json:"sections"`
+ // Title is the visible label field used by picker-style buttons (e.g.
+ // single_select's {"title":...,"sections":...}), which don't set
+ // display_text at all.
+ Title string `json:"title"`
+}
+
+func formatNativeFlowButton(button *waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton) string {
+ if button == nil {
+ return ""
+ }
+ name := button.GetName()
+
+ var params nativeFlowButtonParams
+ _ = json.Unmarshal([]byte(button.GetButtonParamsJSON()), &params)
+
+ switch name {
+ case "cta_url":
+ label := params.DisplayText
+ if label == "" {
+ label = "Link"
+ }
+ if params.URL != "" {
+ return fmt.Sprintf("🔗 %s: %s", label, params.URL)
+ }
+ case "cta_call":
+ label := params.DisplayText
+ if label == "" {
+ label = "Call"
+ }
+ if params.PhoneNumber != "" {
+ return fmt.Sprintf("📞 %s: %s", label, params.PhoneNumber)
+ }
+ case "cta_copy":
+ label := params.DisplayText
+ if label == "" {
+ label = "Copy code"
+ }
+ if params.Copy != "" {
+ return fmt.Sprintf("📋 %s: %s", label, params.Copy)
+ }
+ }
+
+ label := params.DisplayText
+ if label == "" {
+ label = params.Title
+ }
+ if label != "" {
+ return fmt.Sprintf("[%s] %s", name, label)
+ }
+ return fmt.Sprintf("[%s]", name)
+}
diff --git a/src/pkg/utils/business_message_test.go b/src/pkg/utils/business_message_test.go
new file mode 100644
index 00000000..9bac1349
--- /dev/null
+++ b/src/pkg/utils/business_message_test.go
@@ -0,0 +1,451 @@
+package utils
+
+import (
+ "reflect"
+ "testing"
+
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+ "google.golang.org/protobuf/proto"
+)
+
+func hydratedOrderTemplate() *waE2E.TemplateMessage {
+ return &waE2E.TemplateMessage{
+ TemplateID: proto.String("order_confirmed"),
+ HydratedTemplate: &waE2E.TemplateMessage_HydratedFourRowTemplate{
+ Title: &waE2E.TemplateMessage_HydratedFourRowTemplate_HydratedTitleText{HydratedTitleText: "Order confirmed"},
+ HydratedContentText: proto.String("Hi John, your order #1234 has shipped."),
+ HydratedFooterText: proto.String("Acme Store"),
+ HydratedButtons: []*waE2E.HydratedTemplateButton{
+ {HydratedButton: &waE2E.HydratedTemplateButton_UrlButton{UrlButton: &waE2E.HydratedTemplateButton_HydratedURLButton{
+ DisplayText: proto.String("Track order"), URL: proto.String("https://acme.example/track/1234")}}},
+ {HydratedButton: &waE2E.HydratedTemplateButton_CallButton{CallButton: &waE2E.HydratedTemplateButton_HydratedCallButton{
+ DisplayText: proto.String("Call us"), PhoneNumber: proto.String("+15550100")}}},
+ {HydratedButton: &waE2E.HydratedTemplateButton_QuickReplyButton{QuickReplyButton: &waE2E.HydratedTemplateButton_HydratedQuickReplyButton{
+ DisplayText: proto.String("Stop updates"), ID: proto.String("stop")}}},
+ },
+ },
+ }
+}
+
+const hydratedOrderTemplateText = "Order confirmed\nHi John, your order #1234 has shipped.\nAcme Store\n" +
+ "🔗 Track order: https://acme.example/track/1234\n📞 Call us: +15550100\n[Stop updates]"
+
+func interactiveCopyCodeMessage() *waE2E.InteractiveMessage {
+ return &waE2E.InteractiveMessage{
+ Header: &waE2E.InteractiveMessage_Header{Title: proto.String("Promo")},
+ Body: &waE2E.InteractiveMessage_Body{Text: proto.String("20% off today")},
+ InteractiveMessage: &waE2E.InteractiveMessage_NativeFlowMessage_{NativeFlowMessage: &waE2E.InteractiveMessage_NativeFlowMessage{
+ Buttons: []*waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton{{
+ Name: proto.String("cta_copy"),
+ ButtonParamsJSON: proto.String(`{"display_text":"Copy code","copy_code":"SAVE20"}`),
+ }},
+ }},
+ }
+}
+
+// A template may carry a hydrated fallback next to its interactive form; the
+// text and the webhook payload must describe the same one.
+func interactiveTemplateWithHydratedFallback() *waE2E.Message {
+ return &waE2E.Message{TemplateMessage: &waE2E.TemplateMessage{
+ HydratedTemplate: &waE2E.TemplateMessage_HydratedFourRowTemplate{HydratedContentText: proto.String("fallback"), TemplateID: proto.String("promo")},
+ Format: &waE2E.TemplateMessage_InteractiveMessageTemplate{InteractiveMessageTemplate: interactiveCopyCodeMessage()},
+ }}
+}
+
+// A native-flow tap can carry its choice only in paramsJSON.
+func nativeFlowReplyWithoutBody() *waE2E.Message {
+ return &waE2E.Message{InteractiveResponseMessage: &waE2E.InteractiveResponseMessage{
+ InteractiveResponseMessage: &waE2E.InteractiveResponseMessage_NativeFlowResponseMessage_{
+ NativeFlowResponseMessage: &waE2E.InteractiveResponseMessage_NativeFlowResponseMessage{
+ Name: proto.String("quick_reply"), ParamsJSON: proto.String(`{"id":"book_2"}`),
+ },
+ },
+ }}
+}
+
+func listReplyWithoutTitle() *waE2E.Message {
+ return &waE2E.Message{ListResponseMessage: &waE2E.ListResponseMessage{
+ ListType: waE2E.ListResponseMessage_SINGLE_SELECT.Enum(),
+ SingleSelectReply: &waE2E.ListResponseMessage_SingleSelectReply{SelectedRowID: proto.String("row-void-pnr")},
+ }}
+}
+
+func TestExtractMessageTextFromProtoBusinessMessages(t *testing.T) {
+ tests := []struct {
+ name string
+ msg *waE2E.Message
+ want string
+ }{
+ {
+ name: "HydratedTemplateKeepsEveryRowAndButton",
+ msg: &waE2E.Message{TemplateMessage: hydratedOrderTemplate()},
+ want: hydratedOrderTemplateText,
+ },
+ {
+ name: "HydratedFourRowTemplateOneof",
+ msg: &waE2E.Message{TemplateMessage: &waE2E.TemplateMessage{Format: &waE2E.TemplateMessage_HydratedFourRowTemplate_{
+ HydratedFourRowTemplate: &waE2E.TemplateMessage_HydratedFourRowTemplate{HydratedContentText: proto.String("Your code is 482913")},
+ }}},
+ want: "Your code is 482913",
+ },
+ {
+ // History sync delivers the raw, still-wrapped message.
+ name: "EphemeralWrappedTemplate",
+ msg: &waE2E.Message{EphemeralMessage: &waE2E.FutureProofMessage{Message: &waE2E.Message{TemplateMessage: hydratedOrderTemplate()}}},
+ want: hydratedOrderTemplateText,
+ },
+ {
+ name: "TemplateWithOnlyMediaHeaderGetsPlaceholder",
+ msg: &waE2E.Message{TemplateMessage: &waE2E.TemplateMessage{HydratedTemplate: &waE2E.TemplateMessage_HydratedFourRowTemplate{
+ Title: &waE2E.TemplateMessage_HydratedFourRowTemplate_ImageMessage{ImageMessage: &waE2E.ImageMessage{}},
+ }}},
+ want: "Template message",
+ },
+ {
+ name: "NonHydratedFourRowTemplateGetsPlaceholder",
+ msg: &waE2E.Message{TemplateMessage: &waE2E.TemplateMessage{
+ TemplateID: proto.String("otp"),
+ Format: &waE2E.TemplateMessage_FourRowTemplate_{FourRowTemplate: &waE2E.TemplateMessage_FourRowTemplate{}},
+ }},
+ want: "Template message",
+ },
+ {
+ name: "TemplateWrappingInteractiveRendersLikeInteractive",
+ msg: interactiveTemplateWithHydratedFallback(),
+ want: "Promo\n20% off today\n📋 Copy code: SAVE20",
+ },
+ {
+ name: "HydratedHighlyStructuredMessage",
+ msg: &waE2E.Message{HighlyStructuredMessage: &waE2E.HighlyStructuredMessage{
+ ElementName: proto.String("order_confirmation"),
+ HydratedHsm: &waE2E.TemplateMessage{HydratedTemplate: &waE2E.TemplateMessage_HydratedFourRowTemplate{
+ HydratedContentText: proto.String("Thanks for your order"),
+ }},
+ }},
+ want: "Thanks for your order",
+ },
+ {
+ // A non-hydrated HSM only carries an element name and params.
+ name: "NonHydratedHighlyStructuredMessageStaysEmpty",
+ msg: &waE2E.Message{HighlyStructuredMessage: &waE2E.HighlyStructuredMessage{
+ ElementName: proto.String("order_confirmation"),
+ Params: []string{"42"},
+ }},
+ want: "",
+ },
+ {
+ name: "InteractiveMessage",
+ msg: &waE2E.Message{InteractiveMessage: &waE2E.InteractiveMessage{
+ Header: &waE2E.InteractiveMessage_Header{Title: proto.String("Support")},
+ Body: &waE2E.InteractiveMessage_Body{Text: proto.String("How can we help?")},
+ Footer: &waE2E.InteractiveMessage_Footer{Text: proto.String("Acme Support")},
+ InteractiveMessage: &waE2E.InteractiveMessage_NativeFlowMessage_{NativeFlowMessage: &waE2E.InteractiveMessage_NativeFlowMessage{
+ Buttons: []*waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton{{
+ Name: proto.String("cta_url"),
+ ButtonParamsJSON: proto.String(`{"display_text":"Visit site","url":"https://acme.example"}`),
+ }},
+ }},
+ }},
+ want: "Support\nHow can we help?\nAcme Support\n🔗 Visit site: https://acme.example",
+ },
+ {
+ name: "ViewOnceWrappedInteractive",
+ msg: &waE2E.Message{ViewOnceMessage: &waE2E.FutureProofMessage{Message: &waE2E.Message{InteractiveMessage: &waE2E.InteractiveMessage{
+ Body: &waE2E.InteractiveMessage_Body{Text: proto.String("How can we help?")},
+ }}}},
+ want: "How can we help?",
+ },
+ {
+ name: "InteractiveResponse",
+ msg: &waE2E.Message{InteractiveResponseMessage: &waE2E.InteractiveResponseMessage{
+ Body: &waE2E.InteractiveResponseMessage_Body{Text: proto.String("Track my order")},
+ }},
+ want: "Track my order",
+ },
+ {
+ name: "NativeFlowReplyWithOnlyAnID",
+ msg: nativeFlowReplyWithoutBody(),
+ want: "Selected option book_2",
+ },
+ {
+ name: "EmptySelectionReplyGetsPlaceholder",
+ msg: &waE2E.Message{ListResponseMessage: &waE2E.ListResponseMessage{}},
+ want: "Selection message",
+ },
+ {
+ name: "ButtonsMessage",
+ msg: &waE2E.Message{ButtonsMessage: &waE2E.ButtonsMessage{
+ Header: &waE2E.ButtonsMessage_Text{Text: "Travel desk"},
+ ContentText: proto.String("Please choose the service"),
+ FooterText: proto.String("Reply with a button"),
+ Buttons: []*waE2E.ButtonsMessage_Button{
+ {ButtonID: proto.String("sales"), ButtonText: &waE2E.ButtonsMessage_Button_ButtonText{DisplayText: proto.String("Sales")}},
+ {ButtonID: proto.String("support"), ButtonText: &waE2E.ButtonsMessage_Button_ButtonText{DisplayText: proto.String("Support")}},
+ },
+ }},
+ want: "Travel desk\nPlease choose the service\nReply with a button\n[Sales]\n[Support]",
+ },
+ {
+ name: "ButtonsMessageWithoutTextGetsPlaceholder",
+ msg: &waE2E.Message{ButtonsMessage: &waE2E.ButtonsMessage{}},
+ want: "Buttons message",
+ },
+ {
+ name: "ListMessage",
+ msg: &waE2E.Message{ListMessage: &waE2E.ListMessage{
+ Title: proto.String("Menu"),
+ Description: proto.String("Choose a product"),
+ FooterText: proto.String("Acme"),
+ Sections: []*waE2E.ListMessage_Section{{Rows: []*waE2E.ListMessage_Row{
+ {Title: proto.String("Mug"), RowID: proto.String("mug")},
+ {RowID: proto.String("untitled")},
+ {Title: proto.String("Shirt"), RowID: proto.String("shirt")},
+ }}},
+ }},
+ want: "List: Menu\nChoose a product\nAcme\n[Mug]\n[Shirt]",
+ },
+ {
+ name: "ListMessageWithoutTextGetsPlaceholder",
+ msg: &waE2E.Message{ListMessage: &waE2E.ListMessage{}},
+ want: "List message",
+ },
+ {
+ name: "ProductMessagePrefersSalePrice",
+ msg: &waE2E.Message{ProductMessage: &waE2E.ProductMessage{
+ Body: proto.String("Limited offer"),
+ Product: &waE2E.ProductMessage_ProductSnapshot{
+ Title: proto.String("Weekend package"), CurrencyCode: proto.String("IDR"),
+ PriceAmount1000: proto.Int64(3500000), SalePriceAmount1000: proto.Int64(2900000),
+ },
+ }},
+ want: "Product: Weekend package (IDR 2900.00)\nLimited offer",
+ },
+ {
+ name: "ProductMessageWithoutText",
+ msg: &waE2E.Message{ProductMessage: &waE2E.ProductMessage{}},
+ want: "Product",
+ },
+ {
+ name: "OrderMessage",
+ msg: &waE2E.Message{OrderMessage: &waE2E.OrderMessage{
+ Message: proto.String("2 items - $30.00"),
+ OrderTitle: proto.String("Order #42"),
+ }},
+ want: "Order: Order #42\n2 items - $30.00",
+ },
+ {
+ name: "OrderMessageWithoutTextGetsPlaceholder",
+ msg: &waE2E.Message{OrderMessage: &waE2E.OrderMessage{}},
+ want: "Order message",
+ },
+ {
+ name: "ListReplyTitle",
+ msg: &waE2E.Message{ListResponseMessage: &waE2E.ListResponseMessage{
+ Title: proto.String("Void PNR"),
+ SingleSelectReply: &waE2E.ListResponseMessage_SingleSelectReply{SelectedRowID: proto.String("row-void-pnr")},
+ }},
+ want: "Void PNR",
+ },
+ {
+ name: "ListReplyWithOnlyRowID",
+ msg: listReplyWithoutTitle(),
+ want: "Selected option row-void-pnr",
+ },
+ {
+ name: "ButtonsReply",
+ msg: &waE2E.Message{ButtonsResponseMessage: &waE2E.ButtonsResponseMessage{
+ SelectedButtonID: proto.String("support"),
+ Response: &waE2E.ButtonsResponseMessage_SelectedDisplayText{SelectedDisplayText: "Support"},
+ }},
+ want: "Support",
+ },
+ {
+ name: "TemplateButtonReply",
+ msg: &waE2E.Message{TemplateButtonReplyMessage: &waE2E.TemplateButtonReplyMessage{
+ SelectedID: proto.String("stop"), SelectedDisplayText: proto.String("Stop updates"),
+ }},
+ want: "Stop updates",
+ },
+ {
+ name: "UnknownTypeStaysEmpty",
+ msg: &waE2E.Message{ReactionMessage: &waE2E.ReactionMessage{Text: proto.String("👍")}},
+ want: "",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := ExtractMessageTextFromProto(tt.msg); got != tt.want {
+ t.Fatalf("ExtractMessageTextFromProto() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+// The webhook body carries the business text too, replies included.
+func TestBuildEventMessageUsesBusinessText(t *testing.T) {
+ tests := []struct {
+ name string
+ msg *waE2E.Message
+ want string
+ }{
+ {"template", &waE2E.Message{TemplateMessage: hydratedOrderTemplate()}, hydratedOrderTemplateText},
+ {"list reply", listReplyWithoutTitle(), "Selected option row-void-pnr"},
+ {"buttons reply", &waE2E.Message{ButtonsResponseMessage: &waE2E.ButtonsResponseMessage{
+ Response: &waE2E.ButtonsResponseMessage_SelectedDisplayText{SelectedDisplayText: "Support"},
+ }}, "Support"},
+ {"template reply", &waE2E.Message{TemplateButtonReplyMessage: &waE2E.TemplateButtonReplyMessage{
+ SelectedDisplayText: proto.String("Stop updates"),
+ }}, "Stop updates"},
+ }
+ for _, tt := range tests {
+ if got := BuildEventMessage(&events.Message{Info: types.MessageInfo{ID: "MSG1"}, Message: tt.msg}).Text; got != tt.want {
+ t.Errorf("%s: BuildEventMessage().Text = %q, want %q", tt.name, got, tt.want)
+ }
+ }
+}
+
+func TestExtractMediaInfoUnwrapsWrappers(t *testing.T) {
+ msg := &waE2E.Message{EphemeralMessage: &waE2E.FutureProofMessage{Message: &waE2E.Message{ImageMessage: &waE2E.ImageMessage{
+ Caption: proto.String("look at this"),
+ DirectPath: proto.String("/v/t62/abc"),
+ }}}}
+ mediaType, _, _, directPath, _, _, _, _ := ExtractMediaInfo(msg)
+ if mediaType != "image" || directPath != "/v/t62/abc" {
+ t.Fatalf("wrapped image lost its media info: type=%q direct_path=%q", mediaType, directPath)
+ }
+}
+
+func TestBuildTemplatePayloadKeepsAllRows(t *testing.T) {
+ template := BuildTemplatePayload(&waE2E.Message{TemplateMessage: hydratedOrderTemplate()})
+ if template == nil {
+ t.Fatal("expected template payload")
+ }
+ if template.Title != "Order confirmed" || template.Body != "Hi John, your order #1234 has shipped." ||
+ template.Footer != "Acme Store" || template.TemplateID != "order_confirmed" {
+ t.Fatalf("rows not kept: %+v", template)
+ }
+ want := []BusinessButton{
+ {Type: "url", Text: "Track order", URL: "https://acme.example/track/1234"},
+ {Type: "call", Text: "Call us", Phone: "+15550100"},
+ {Type: "quick_reply", Text: "Stop updates", ID: "stop"},
+ }
+ if !reflect.DeepEqual(template.Buttons, want) {
+ t.Fatalf("buttons = %+v, want %+v", template.Buttons, want)
+ }
+}
+
+func TestBuildTemplatePayloadWrappingInteractive(t *testing.T) {
+ template := BuildTemplatePayload(interactiveTemplateWithHydratedFallback())
+ if template.Title != "Promo" || template.Body != "20% off today" || template.TemplateID != "promo" {
+ t.Fatalf("interactive rows not kept: %+v", template)
+ }
+ if want := []BusinessButton{{Type: "copy", Text: "Copy code", Code: "SAVE20"}}; !reflect.DeepEqual(template.Buttons, want) {
+ t.Fatalf("buttons = %+v, want %+v", template.Buttons, want)
+ }
+}
+
+func TestBuildTemplatePayloadCarouselKeepsCardsAndQuickReplyIDs(t *testing.T) {
+ card := func(body, id string) *waE2E.InteractiveMessage {
+ return &waE2E.InteractiveMessage{
+ Header: &waE2E.InteractiveMessage_Header{Title: proto.String("Offer"), Subtitle: proto.String("Today only"),
+ Media: &waE2E.InteractiveMessage_Header_ImageMessage{ImageMessage: &waE2E.ImageMessage{}}},
+ Body: &waE2E.InteractiveMessage_Body{Text: proto.String(body)},
+ InteractiveMessage: &waE2E.InteractiveMessage_NativeFlowMessage_{NativeFlowMessage: &waE2E.InteractiveMessage_NativeFlowMessage{
+ Buttons: []*waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton{{
+ Name: proto.String("quick_reply"),
+ ButtonParamsJSON: proto.String(`{"display_text":"Book","id":"` + id + `"}`),
+ }},
+ }},
+ }
+ }
+ template := BuildTemplatePayload(&waE2E.Message{TemplateMessage: &waE2E.TemplateMessage{Format: &waE2E.TemplateMessage_InteractiveMessageTemplate{
+ InteractiveMessageTemplate: &waE2E.InteractiveMessage{
+ Body: &waE2E.InteractiveMessage_Body{Text: proto.String("Pick a package")},
+ InteractiveMessage: &waE2E.InteractiveMessage_CarouselMessage_{CarouselMessage: &waE2E.InteractiveMessage_CarouselMessage{
+ Cards: []*waE2E.InteractiveMessage{card("Two nights", "book-2"), card("Four nights", "book-4")},
+ }},
+ },
+ }}})
+ if len(template.Cards) != 2 {
+ t.Fatalf("expected 2 cards, got %+v", template.Cards)
+ }
+ second := template.Cards[1]
+ if second.Body != "Four nights" || second.Subtitle != "Today only" || second.HeaderType != "image" {
+ t.Fatalf("card rows not kept: %+v", second)
+ }
+ if len(second.Buttons) != 1 || second.Buttons[0].ID != "book-4" {
+ t.Fatalf("quick reply id not kept: %+v", second.Buttons)
+ }
+}
+
+func TestBuildButtonsPayload(t *testing.T) {
+ buttons := BuildButtonsPayload(&waE2E.Message{ButtonsMessage: &waE2E.ButtonsMessage{
+ Header: &waE2E.ButtonsMessage_Text{Text: "Travel desk"},
+ ContentText: proto.String("Please choose the service"),
+ Buttons: []*waE2E.ButtonsMessage_Button{
+ {ButtonID: proto.String("support"), ButtonText: &waE2E.ButtonsMessage_Button_ButtonText{DisplayText: proto.String("Support")}},
+ {ButtonID: proto.String("menu"), NativeFlowInfo: &waE2E.ButtonsMessage_Button_NativeFlowInfo{
+ Name: proto.String("single_select"), ParamsJSON: proto.String(`{"title":"Choose"}`),
+ }},
+ },
+ }})
+ if buttons.Title != "Travel desk" || buttons.Body != "Please choose the service" {
+ t.Fatalf("rows not kept: %+v", buttons)
+ }
+ want := []BusinessButton{
+ {Type: "quick_reply", Text: "Support", ID: "support"},
+ {Type: "single_select", Text: "Choose", ID: "menu"},
+ }
+ if !reflect.DeepEqual(buttons.Buttons, want) {
+ t.Fatalf("buttons = %+v, want %+v", buttons.Buttons, want)
+ }
+}
+
+func TestBuildProductPayload(t *testing.T) {
+ product := BuildProductPayload(&waE2E.Message{ProductMessage: &waE2E.ProductMessage{
+ Product: &waE2E.ProductMessage_ProductSnapshot{
+ ProductID: proto.String("p-77"), Title: proto.String("Weekend package"),
+ CurrencyCode: proto.String("IDR"), PriceAmount1000: proto.Int64(3500000),
+ },
+ BusinessOwnerJID: proto.String("[email protected]"),
+ Catalog: &waE2E.ProductMessage_CatalogSnapshot{Title: proto.String("Packages")},
+ }})
+ if product.ProductID != "p-77" || product.PriceAmount1000 != 3500000 || product.CatalogTitle != "Packages" ||
+ product.BusinessOwnerJID != "[email protected]" {
+ t.Fatalf("product not kept: %+v", product)
+ }
+}
+
+func TestBuildSelectionPayloadListReplyWithoutTitle(t *testing.T) {
+ selection := BuildSelectionPayload(listReplyWithoutTitle())
+ if selection == nil || selection.Kind != "list" || selection.SelectedID != "row-void-pnr" {
+ t.Fatalf("selected row not kept: %+v", selection)
+ }
+}
+
+func TestBuildSelectionPayloadNativeFlowReply(t *testing.T) {
+ selection := BuildSelectionPayload(nativeFlowReplyWithoutBody())
+ if selection == nil || selection.Kind != "interactive" || selection.SelectedID != "book_2" {
+ t.Fatalf("native-flow reply not kept: %+v", selection)
+ }
+}
+
+func TestNativeFlowAsButtonKeepsSingleSelectRows(t *testing.T) {
+ button := nativeFlowAsButton("single_select", `{"title":"Choose","sections":[{"title":"Services","rows":[{"id":"void","title":"Void PNR"},{"id":"status","title":"Booking status","description":"By PNR"}]}]}`, "")
+ want := BusinessButton{Type: "single_select", Text: "Choose", Rows: []BusinessButtonRow{
+ {ID: "void", Title: "Void PNR"},
+ {ID: "status", Title: "Booking status", Description: "By PNR"},
+ }}
+ if !reflect.DeepEqual(button, want) {
+ t.Fatalf("button = %+v, want %+v", button, want)
+ }
+}
+
+func TestBusinessMessageLinesFallsBackToButtonType(t *testing.T) {
+ if got := businessMessageLines(&BusinessMessage{Buttons: []BusinessButton{{Type: "review_and_pay"}}}); got != "[review_and_pay]" {
+ t.Fatalf("unexpected lines %q", got)
+ }
+}
diff --git a/src/pkg/utils/chatwoot.go b/src/pkg/utils/chatwoot.go
index c85cb18c..4db6c2df 100644
--- a/src/pkg/utils/chatwoot.go
+++ b/src/pkg/utils/chatwoot.go
@@ -63,21 +63,29 @@ func IsNewsletterJID(jid string) bool {
//
// The transforms use paired, non-greedy delimiters, so a lone unmatched
// delimiter (e.g. "2 * 3") is left alone — exactly the inputs WhatsApp and
-// Chatwoot themselves decline to format. Sentinel runes guard the bold pass
-// from being re-matched by the italic pass.
+// Chatwoot themselves decline to format. Like WhatsApp, the WhatsApp-side
+// pairs only count at word boundaries and never inside links, so URLs
+// (/_docs_/, ?utm_source=a&utm_medium=b) and snake_case ids pass through
+// untouched. Sentinel runes guard the bold pass from being re-matched by the
+// italic pass.
const (
mdBoldSentinel = "\x01"
mdStrikeSentinel = "\x02"
+ mdLinkSentinel = "\x03"
)
var (
reCwBold = regexp.MustCompile(`\*\*(.+?)\*\*`)
reCwStrike = regexp.MustCompile(`~~(.+?)~~`)
reCwItalic = regexp.MustCompile(`\*(.+?)\*`)
- reWaBold = regexp.MustCompile(`\*(.+?)\*`)
- reWaItalic = regexp.MustCompile(`_(.+?)_`)
- reWaStrike = regexp.MustCompile(`~(.+?)~`)
+ // The link sentinel counts as a word character: a link starts with one.
+ reWaBold = regexp.MustCompile(`(^|[^\p{L}\p{N}*\x03])\*([^\s*](?:[^*\n]*[^\s*])?)\*($|[^\p{L}\p{N}*\x03])`)
+ reWaItalic = regexp.MustCompile(`(^|[^\p{L}\p{N}_\x03])_([^\s_](?:[^_\n]*[^\s_])?)_($|[^\p{L}\p{N}_\x03])`)
+ reWaStrike = regexp.MustCompile(`(^|[^\p{L}\p{N}~\x03])~([^\s~](?:[^~\n]*[^\s~])?)~($|[^\p{L}\p{N}~\x03])`)
+ // A trailing delimiter or punctuation stays outside the link, so
+ // "*https://x.com*!" still pairs.
+ reWaLink = regexp.MustCompile(`(?i:https?://|www\.)\S*[^\s*_~.,;:!?)\]'"]`)
)
// stripMarkdownSentinels removes any pre-existing guard runes from input so
@@ -85,10 +93,10 @@ var (
// into markdown. Real WhatsApp/Chatwoot message text never contains these
// control runes, so this is purely defensive.
func stripMarkdownSentinels(s string) string {
- if !strings.ContainsAny(s, mdBoldSentinel+mdStrikeSentinel) {
+ if !strings.ContainsAny(s, mdBoldSentinel+mdStrikeSentinel+mdLinkSentinel) {
return s
}
- return strings.NewReplacer(mdBoldSentinel, "", mdStrikeSentinel, "").Replace(s)
+ return strings.NewReplacer(mdBoldSentinel, "", mdStrikeSentinel, "", mdLinkSentinel, "").Replace(s)
}
// ChatwootToWhatsAppMarkdown rewrites Chatwoot/GFM markdown to WhatsApp's
@@ -117,13 +125,37 @@ func WhatsAppToChatwootMarkdown(s string) string {
return s
}
s = stripMarkdownSentinels(s)
+ // Hide links behind a sentinel so their delimiters are never paired.
+ links := reWaLink.FindAllString(s, -1)
+ s = reWaLink.ReplaceAllLiteralString(s, mdLinkSentinel)
// Hide bold asterisks behind a sentinel, convert italic underscores to
// asterisks, then expand the sentinel to a double asterisk. Doing it in
// this order keeps the freshly-created italic asterisks from being seen
// as bold.
- s = reWaBold.ReplaceAllString(s, mdBoldSentinel+"$1"+mdBoldSentinel)
- s = reWaItalic.ReplaceAllString(s, "*$1*")
- s = reWaStrike.ReplaceAllString(s, "~~$1~~")
+ s = replaceWhatsAppPairs(reWaBold, s, mdBoldSentinel)
+ s = replaceWhatsAppPairs(reWaItalic, s, "*")
+ s = replaceWhatsAppPairs(reWaStrike, s, mdStrikeSentinel)
s = strings.ReplaceAll(s, mdBoldSentinel, "**")
- return s
+ s = strings.ReplaceAll(s, mdStrikeSentinel, "~~")
+ if len(links) == 0 {
+ return s
+ }
+ var b strings.Builder
+ for i, part := range strings.Split(s, mdLinkSentinel) {
+ b.WriteString(part)
+ if i < len(links) {
+ b.WriteString(links[i])
+ }
+ }
+ return b.String()
+}
+
+// replaceWhatsAppPairs swaps the delimiters of every re match for marker. It
+// runs twice because adjacent pairs ("*a* *b*") share the boundary character
+// between them, which a single pass consumes. It must not loop until stable:
+// each extra pass unwraps another nesting level, so crafted input would cost
+// one pass per level.
+func replaceWhatsAppPairs(re *regexp.Regexp, s, marker string) string {
+ repl := "${1}" + marker + "${2}" + marker + "${3}"
+ return re.ReplaceAllString(re.ReplaceAllString(s, repl), repl)
}
diff --git a/src/pkg/utils/chatwoot_test.go b/src/pkg/utils/chatwoot_test.go
index 8639746f..8e8b4963 100644
--- a/src/pkg/utils/chatwoot_test.go
+++ b/src/pkg/utils/chatwoot_test.go
@@ -362,6 +362,76 @@ func TestWhatsAppToChatwootMarkdown(t *testing.T) {
in: "\x01*bold*\x02",
want: "**bold**",
},
+ {
+ // WhatsApp only formats at word boundaries, so URL query params
+ // and snake_case ids must come through as typed.
+ name: "URLWithUnderscoresUnchanged",
+ in: "🔗 Track: https://acme.example/t?utm_source=wa&utm_medium=tpl",
+ want: "🔗 Track: https://acme.example/t?utm_source=wa&utm_medium=tpl",
+ },
+ {
+ // Links are never formatted, even where a path segment is
+ // wrapped in delimiters.
+ name: "LinkPathsUnchanged",
+ in: "Docs: https://acme.example/_docs_/ and www.acme.example/~john/~doc~",
+ want: "Docs: https://acme.example/_docs_/ and www.acme.example/~john/~doc~",
+ },
+ {
+ name: "FormattingAroundLinks",
+ in: "*https://acme.example* _see https://x.example/a_b_c now_",
+ want: "**https://acme.example** *see https://x.example/a_b_c now*",
+ },
+ {
+ // Punctuation after the closing delimiter is not part of the link.
+ name: "FormattedLinkBeforePunctuation",
+ in: "Kunjungi *https://acme.id/promo*! (_www.acme.id/faq_), ~https://old.acme.id~;",
+ want: "Kunjungi **https://acme.id/promo**! (*www.acme.id/faq*), ~~https://old.acme.id~~;",
+ },
+ {
+ // A link starts with a letter, so it is no boundary for a pair.
+ name: "PairTouchingLinkUnchanged",
+ in: "*Link:*https://acme.id _note_www.acme.id",
+ want: "*Link:*https://acme.id _note_www.acme.id",
+ },
+ {
+ name: "CapitalizedLinkPathsUnchanged",
+ in: "Www.toko.id/_toko_ HTTPS://ACME.ID/_PROMO_",
+ want: "Www.toko.id/_toko_ HTTPS://ACME.ID/_PROMO_",
+ },
+ {
+ name: "SnakeCaseUnchanged",
+ in: "Selected option opt_book_now [review_and_pay]",
+ want: "Selected option opt_book_now [review_and_pay]",
+ },
+ {
+ name: "MidWordDelimitersUnchanged",
+ in: "2*3*4 and a~b~c",
+ want: "2*3*4 and a~b~c",
+ },
+ {
+ // Adjacent pairs share the boundary character between them.
+ name: "AdjacentPairs",
+ in: "*a* *b* _c_ _d_ ~e~ ~f~",
+ want: "**a** **b** *c* *d* ~~e~~ ~~f~~",
+ },
+ {
+ // Passes are capped at two: an unbounded loop unwraps one nesting
+ // level per pass, so a crafted 64KB message burned ~50s of CPU.
+ name: "NestingBeyondTwoPassesStops",
+ in: "*a *b *c* d* e*",
+ want: "*a **b **c** d** e*",
+ },
+ {
+ // A doubled delimiter is not a WhatsApp pair; leave it as typed.
+ name: "DoubledDelimitersUnchanged",
+ in: "**x** ~~y~~ __init__",
+ want: "**x** ~~y~~ __init__",
+ },
+ {
+ name: "PunctuationBoundaries",
+ in: "(*Order #42*), _today_!",
+ want: "(**Order #42**), *today*!",
+ },
}
for _, tt := range tests {
diff --git a/src/pkg/utils/whatsapp.go b/src/pkg/utils/whatsapp.go
index f99e6c0a..fa8a68f5 100644
--- a/src/pkg/utils/whatsapp.go
+++ b/src/pkg/utils/whatsapp.go
@@ -178,6 +178,10 @@ func ExtractMessageTextFromProto(msg *waE2E.Message) string {
return ""
}
+ // History sync passes raw messages, still inside the ephemeral/view-once
+ // wrappers that whatsmeow strips from live events.
+ msg = UnwrapMessage(msg)
+
// Check for regular text message
if text := msg.GetConversation(); text != "" {
return text
@@ -210,19 +214,10 @@ func ExtractMessageTextFromProto(msg *waE2E.Message) string {
return doc.GetCaption()
}
- // Check for buttons response message
- if buttonsResponse := msg.GetButtonsResponseMessage(); buttonsResponse != nil {
- return buttonsResponse.GetSelectedDisplayText()
- }
-
- // Check for list response message
- if listResponse := msg.GetListResponseMessage(); listResponse != nil {
- return listResponse.GetTitle()
- }
-
- // Check for template button reply
- if templateButtonReply := msg.GetTemplateButtonReplyMessage(); templateButtonReply != nil {
- return templateButtonReply.GetSelectedDisplayText()
+ // Check for business messages (template, interactive, buttons, list,
+ // product, order) and the button/list replies to them
+ if text := extractBusinessMessageText(msg); text != "" {
+ return text
}
// Check for shared contact card
@@ -306,6 +301,10 @@ func ExtractMediaInfo(msg *waE2E.Message) (mediaType string, filename string, me
return "", "", "", "", nil, nil, nil, 0
}
+ // Unwrap like ExtractMessageTextFromProto, so a wrapped captioned media
+ // message is never stored as caption-only text.
+ msg = UnwrapMessage(msg)
+
// Check for image message
if img := msg.GetImageMessage(); img != nil {
filename = GenerateMediaFilename("image", "jpg", img.GetCaption())
@@ -1142,6 +1141,10 @@ func BuildEventMessage(evt *events.Message) (message EvtMessage) {
}
}
+ if message.Text == "" {
+ message.Text = extractBusinessMessageText(msg)
+ }
+
if ci := ExtractContextInfo(msg); ci != nil {
message.RepliedId = ci.GetStanzaID()
message.QuotedMessage = ExtractMessageTextFromProto(ci.GetQuotedMessage())