GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.
Go botgogolanggolang-whatsappgolang-whatsapp-apirestrest-apiwhatsappwhatsapp-apiwhatsapp-api-gowhatsapp-multi-devicewhatsapp-web-multi-device
Forward WhatsApp label appstate events to webhooks (#659)
Zayed Adel Al-Meklahfi2ebe12092d24
diff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.goindex 51a17478..9dca001a 100644--- a/src/infrastructure/whatsapp/event_handler.go+++ b/src/infrastructure/whatsapp/event_handler.go@@ -56,7 +56,7 @@ func handler(ctx context.Context, instance *DeviceInstance, rawEvt any) {case *events.HistorySync:handleHistorySync(ctx, evt, chatStorageRepo, client)case *events.AppState:- handleAppState(ctx, evt)+ handleAppState(ctx, evt, instance.JID(), client)case *events.GroupInfo:handleGroupInfo(ctx, evt, instance.JID(), client)case *events.JoinedGroup:@@ -250,8 +250,18 @@ func handlePresence(_ context.Context, evt *events.Presence) {}}-func handleAppState(_ context.Context, evt *events.AppState) {+func handleAppState(_ context.Context, evt *events.AppState, deviceID string, client *whatsmeow.Client) {log.Debugf("App state event: %+v / %+v", evt.Index, evt.SyncActionValue)++ if len(config.WhatsappWebhook) > 0 && isLabelAppState(evt) {+ go func(e *events.AppState, c *whatsmeow.Client) {+ webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ if err := forwardLabelAppStateToWebhook(webhookCtx, e, deviceID, c); err != nil {+ logrus.Errorf("Failed to forward label appstate event to webhook: %v", err)+ }+ }(evt, client)+ }}func handleGroupInfo(ctx context.Context, evt *events.GroupInfo, deviceID string, client *whatsmeow.Client) {diff --git a/src/infrastructure/whatsapp/event_label.go b/src/infrastructure/whatsapp/event_label.gonew file mode 100644index 00000000..c4cd8f62--- /dev/null+++ b/src/infrastructure/whatsapp/event_label.go@@ -0,0 +1,134 @@+package whatsapp++import (+ "context"+ "time"++ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/appstate"+ "go.mau.fi/whatsmeow/proto/waSyncAction"+ "go.mau.fi/whatsmeow/types"+ "go.mau.fi/whatsmeow/types/events"+)++const (+ eventTypeLabelEdit = "label.edit"+ eventTypeLabelAssociation = "label.association"+)++func isLabelAppState(evt *events.AppState) bool {+ if evt == nil || len(evt.Index) == 0 {+ return false+ }++ // Note: IndexLabelAssociationMessage (per-message label) is intentionally excluded.+ // Only chat-level associations and label edits are forwarded.+ return evt.Index[0] == appstate.IndexLabelEdit || evt.Index[0] == appstate.IndexLabelAssociationChat+}++func forwardLabelAppStateToWebhook(ctx context.Context, evt *events.AppState, deviceID string, client *whatsmeow.Client) error {+ eventName, payload := buildLabelAppStatePayload(ctx, evt, client)+ if eventName == "" {+ return nil+ }++ body := map[string]any{+ "event": eventName,+ "timestamp": labelAppStateTimestamp(evt),+ "payload": payload,+ }+ if deviceID != "" {+ body["device_id"] = deviceID+ }++ return forwardPayloadToConfiguredWebhooks(ctx, body, eventName)+}++func buildLabelAppStatePayload(ctx context.Context, evt *events.AppState, client *whatsmeow.Client) (string, map[string]any) {+ if evt == nil || evt.SyncActionValue == nil || len(evt.Index) == 0 {+ return "", nil+ }++ switch evt.Index[0] {+ case appstate.IndexLabelEdit:+ if len(evt.Index) < 2 || evt.LabelEditAction == nil {+ return "", nil+ }++ payload := map[string]any{"label_id": evt.Index[1]}+ addLabelEditActionFields(payload, evt.LabelEditAction)++ return eventTypeLabelEdit, payload+ case appstate.IndexLabelAssociationChat:+ if len(evt.Index) < 3 || evt.LabelAssociationAction == nil {+ return "", nil+ }++ payload := map[string]any{+ "label_id": evt.Index[1],+ "labeled": evt.LabelAssociationAction.GetLabeled(),+ }+ addLabelChatFields(ctx, client, payload, evt.Index[2])++ return eventTypeLabelAssociation, payload+ default:+ return "", nil+ }+}++func addLabelEditActionFields(payload map[string]any, action *waSyncAction.LabelEditAction) {+ if action.Name != nil {+ payload["name"] = action.GetName()+ }+ if action.Color != nil {+ payload["color"] = action.GetColor()+ }+ if action.PredefinedID != nil {+ payload["predefined_id"] = action.GetPredefinedID()+ }+ if action.Deleted != nil {+ payload["deleted"] = action.GetDeleted()+ }+ if action.OrderIndex != nil {+ payload["order_index"] = action.GetOrderIndex()+ }+ if action.IsActive != nil {+ payload["is_active"] = action.GetIsActive()+ }+ if action.Type != nil {+ payload["type"] = action.GetType().String()+ }+ if action.IsImmutable != nil {+ payload["is_immutable"] = action.GetIsImmutable()+ }+ if action.MuteEndTimeMS != nil {+ payload["mute_end_time_ms"] = action.GetMuteEndTimeMS()+ }+}++func addLabelChatFields(ctx context.Context, client *whatsmeow.Client, payload map[string]any, rawJID string) {+ jid, err := types.ParseJID(rawJID)+ if err != nil {+ payload["chat_id"] = rawJID++ return+ }++ chatJID := jid.ToNonAD()+ if chatJID.Server == "lid" {+ payload["chat_lid"] = chatJID.String()+ if client != nil {+ chatJID = NormalizeJIDFromLID(ctx, chatJID, client).ToNonAD()+ }+ }++ payload["chat_id"] = chatJID.String()+}++func labelAppStateTimestamp(evt *events.AppState) string {+ if ts := evt.GetTimestamp(); ts > 0 {+ return time.UnixMilli(ts).UTC().Format(time.RFC3339)+ }++ return time.Now().UTC().Format(time.RFC3339)+}diff --git a/src/infrastructure/whatsapp/event_label_test.go b/src/infrastructure/whatsapp/event_label_test.gonew file mode 100644index 00000000..ccb4938d--- /dev/null+++ b/src/infrastructure/whatsapp/event_label_test.go@@ -0,0 +1,248 @@+package whatsapp++import (+ "context"+ "reflect"+ "testing"+ "time"++ "go.mau.fi/whatsmeow/proto/waSyncAction"+ "go.mau.fi/whatsmeow/types/events"+ "google.golang.org/protobuf/proto"+)++func TestBuildLabelAppStatePayload(t *testing.T) {+ tests := []struct {+ name string+ evt *events.AppState+ eventName string+ payload map[string]any+ }{+ {+ name: "label edit",+ evt: &events.AppState{+ Index: []string{"label_edit", "9"},+ SyncActionValue: &waSyncAction.SyncActionValue{+ LabelEditAction: &waSyncAction.LabelEditAction{+ Name: proto.String("Accounts"),+ Color: proto.Int32(8),+ Deleted: proto.Bool(false),+ OrderIndex: proto.Int32(9),+ IsActive: proto.Bool(true),+ IsImmutable: proto.Bool(false),+ Type: waSyncAction.LabelEditAction_CUSTOM.Enum(),+ },+ },+ },+ eventName: eventTypeLabelEdit,+ payload: map[string]any{+ "label_id": "9",+ "name": "Accounts",+ "color": int32(8),+ "deleted": false,+ "order_index": int32(9),+ "is_active": true,+ "is_immutable": false,+ "type": "CUSTOM",+ },+ },+ {+ name: "label association",+ evt: &events.AppState{+ Index: []string{"label_jid", "9", "[email protected]"},+ SyncActionValue: &waSyncAction.SyncActionValue{+ LabelAssociationAction: &waSyncAction.LabelAssociationAction{+ Labeled: proto.Bool(true),+ },+ },+ },+ eventName: eventTypeLabelAssociation,+ payload: map[string]any{+ "label_id": "9",+ "labeled": true,+ "chat_id": "[email protected]",+ },+ },+ {+ name: "label association with lid",+ evt: &events.AppState{+ Index: []string{"label_jid", "9", "223754944819424@lid"},+ SyncActionValue: &waSyncAction.SyncActionValue{+ LabelAssociationAction: &waSyncAction.LabelAssociationAction{+ Labeled: proto.Bool(false),+ },+ },+ },+ eventName: eventTypeLabelAssociation,+ payload: map[string]any{+ "label_id": "9",+ "labeled": false,+ "chat_id": "223754944819424@lid",+ "chat_lid": "223754944819424@lid",+ },+ },+ {+ name: "label association with unparsable chat id",+ evt: &events.AppState{+ Index: []string{"label_jid", "9", "invalid-chat-id"},+ SyncActionValue: &waSyncAction.SyncActionValue{+ LabelAssociationAction: &waSyncAction.LabelAssociationAction{+ Labeled: proto.Bool(true),+ },+ },+ },+ eventName: eventTypeLabelAssociation,+ payload: map[string]any{+ "label_id": "9",+ "labeled": true,+ "chat_id": "invalid-chat-id",+ },+ },+ {+ name: "unrelated appstate",+ evt: &events.AppState{+ Index: []string{"mute", "[email protected]"},+ SyncActionValue: &waSyncAction.SyncActionValue{+ LabelAssociationAction: &waSyncAction.LabelAssociationAction{+ Labeled: proto.Bool(true),+ },+ },+ },+ },+ // Defensive guard cases+ {+ name: "nil evt",+ evt: nil,+ },+ {+ name: "nil SyncActionValue",+ evt: &events.AppState{+ Index: []string{"label_edit", "9"},+ SyncActionValue: nil,+ },+ },+ {+ name: "label edit with short index",+ evt: &events.AppState{+ Index: []string{"label_edit"},+ SyncActionValue: &waSyncAction.SyncActionValue{+ LabelEditAction: &waSyncAction.LabelEditAction{+ Name: proto.String("Test"),+ },+ },+ },+ },+ {+ name: "label edit with nil LabelEditAction",+ evt: &events.AppState{+ Index: []string{"label_edit", "9"},+ SyncActionValue: &waSyncAction.SyncActionValue{+ LabelEditAction: nil,+ },+ },+ },+ {+ name: "label association with short index",+ evt: &events.AppState{+ Index: []string{"label_jid", "9"},+ SyncActionValue: &waSyncAction.SyncActionValue{+ LabelAssociationAction: &waSyncAction.LabelAssociationAction{+ Labeled: proto.Bool(true),+ },+ },+ },+ },+ {+ name: "label association with nil LabelAssociationAction",+ evt: &events.AppState{+ Index: []string{"label_jid", "9", "[email protected]"},+ SyncActionValue: &waSyncAction.SyncActionValue{+ LabelAssociationAction: nil,+ },+ },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ eventName, payload := buildLabelAppStatePayload(context.Background(), tt.evt, nil)+ if eventName != tt.eventName {+ t.Fatalf("expected event %q, got %q", tt.eventName, eventName)+ }+ assertPayloadEqual(t, payload, tt.payload)+ })+ }+}++func TestIsLabelAppState(t *testing.T) {+ if !isLabelAppState(&events.AppState{Index: []string{"label_edit", "9"}}) {+ t.Fatal("expected label_edit to be recognized")+ }+ if !isLabelAppState(&events.AppState{Index: []string{"label_jid", "9", "[email protected]"}}) {+ t.Fatal("expected label_jid to be recognized")+ }+ if isLabelAppState(&events.AppState{Index: []string{"mute", "[email protected]"}}) {+ t.Fatal("expected unrelated appstate to be ignored")+ }+}++func TestLabelAppStateTimestamp(t *testing.T) {+ t.Run("nil evt falls back to now", func(t *testing.T) {+ before := time.Now().UTC().Truncate(time.Second)+ result := labelAppStateTimestamp(&events.AppState{})+ parsed, err := time.Parse(time.RFC3339, result)+ if err != nil {+ t.Fatalf("expected RFC3339 timestamp, got %q: %v", result, err)+ }+ if parsed.Before(before) {+ t.Fatalf("expected fallback timestamp to be >= %v, got %v", before, parsed)+ }+ })++ t.Run("zero timestamp falls back to now", func(t *testing.T) {+ before := time.Now().UTC().Truncate(time.Second)+ result := labelAppStateTimestamp(&events.AppState{+ SyncActionValue: &waSyncAction.SyncActionValue{+ Timestamp: proto.Int64(0),+ },+ })+ parsed, err := time.Parse(time.RFC3339, result)+ if err != nil {+ t.Fatalf("expected RFC3339 timestamp, got %q: %v", result, err)+ }+ if parsed.Before(before) {+ t.Fatalf("expected fallback timestamp to be >= %v, got %v", before, parsed)+ }+ })++ t.Run("valid ms timestamp is formatted correctly", func(t *testing.T) {+ // 2024-01-15T10:30:00Z in milliseconds+ ms := int64(1705314600000)+ expected := "2024-01-15T10:30:00Z"+ result := labelAppStateTimestamp(&events.AppState{+ SyncActionValue: &waSyncAction.SyncActionValue{+ Timestamp: proto.Int64(ms),+ },+ })+ if result != expected {+ t.Fatalf("expected %q, got %q", expected, result)+ }+ })+}++func assertPayloadEqual(t *testing.T, actual map[string]any, expected map[string]any) {+ t.Helper()++ if len(actual) != len(expected) {+ t.Fatalf("expected payload length %d, got %d: %#v", len(expected), len(actual), actual)+ }+ for key, expectedValue := range expected {+ actualValue, ok := actual[key]+ if !ok {+ t.Fatalf("expected payload key %q", key)+ }+ if !reflect.DeepEqual(actualValue, expectedValue) {+ t.Fatalf("expected payload[%q] to be %#v, got %#v", key, expectedValue, actualValue)+ }+ }+}