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
package whatsapp
import (
"context"
"fmt"
"strings"
"time"
"unicode"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/proto/waE2E"
"go.mau.fi/whatsmeow/types"
"go.mau.fi/whatsmeow/types/events"
)
func handleMessage(ctx context.Context, evt *events.Message, chatStorageRepo domainChatStorage.IChatStorageRepository, client *whatsmeow.Client) {
// Log message metadata. Message ID, sender name, JID and body are escaped so
// a newline in sender-controlled fields cannot forge a second log line.
metaParts := buildMessageMetaParts(evt)
log.Infof("Received message %s from %s (%s): %s",
sanitizeLogText(evt.Info.ID),
sanitizeLogText(evt.Info.SourceString()),
sanitizeLogText(strings.Join(metaParts, ", ")),
logMessageBody{evt.Message},
)
// Materialize SecretEncryptedMessage{MESSAGE_EDIT} envelope (sent by recent
// LID-migrated WhatsApp clients) into the legacy ProtocolMessage{MESSAGE_EDIT}
// form, so chat storage, webhook, and auto-reply all use the existing
// edit-handling paths unchanged. No-op when the envelope is absent or when
// decryption fails.
evt = materializeSecretEditMessage(ctx, evt, client)
pollPayload := preparePollWebhookPayload(ctx, client, chatStorageRepo, evt)
if isReactionMessage(evt) {
if err := chatStorageRepo.CreateReaction(ctx, evt); err != nil {
log.Errorf("Failed to store incoming reaction %s: %v", sanitizeLogText(evt.Info.ID), err)
}
handleWebhookForward(ctx, evt, client, pollPayload)
return
}
if err := chatStorageRepo.CreateMessage(ctx, evt); err != nil {
// Log storage errors to avoid silent failures that could lead to data loss
log.Errorf("Failed to store incoming message %s: %v", sanitizeLogText(evt.Info.ID), err)
}
// Handle image message if present
handleImageMessage(ctx, evt, client)
// Auto-mark message as read if configured
handleAutoMarkRead(ctx, evt, client)
// Handle auto-reply if configured
handleAutoReply(ctx, evt, chatStorageRepo, client)
// Forward to webhook if configured
handleWebhookForward(ctx, evt, client, pollPayload)
}
func buildMessageMetaParts(evt *events.Message) []string {
metaParts := []string{
fmt.Sprintf("pushname: %s", sanitizeLogText(evt.Info.PushName)),
fmt.Sprintf("timestamp: %s", evt.Info.Timestamp),
}
if evt.Info.Type != "" {
metaParts = append(metaParts, fmt.Sprintf("type: %s", evt.Info.Type))
}
if evt.Info.Category != "" {
metaParts = append(metaParts, fmt.Sprintf("category: %s", evt.Info.Category))
}
if evt.IsViewOnce {
metaParts = append(metaParts, "view once")
}
return metaParts
}
// sanitizeLogText escapes control characters (C0, DEL, C1) and the Unicode
// line and paragraph separators so one log record stays one line.
func sanitizeLogText(s string) string {
if !strings.ContainsFunc(s, isLogControl) {
return s
}
var b strings.Builder
b.Grow(len(s) + 8)
for _, r := range s {
switch r {
case '\n':
b.WriteString(`\n`)
case '\r':
b.WriteString(`\r`)
case '\t':
b.WriteString(`\t`)
default:
if r < 0x20 || r == 0x7f {
fmt.Fprintf(&b, `\x%02x`, r)
} else if isLogControl(r) {
fmt.Fprintf(&b, `\u%04x`, r)
} else {
b.WriteRune(r)
}
}
}
return b.String()
}
func isLogControl(r rune) bool {
return unicode.IsControl(r) || r == '\u2028' || r == '\u2029'
}
// logMessageBody formats a message only when the log level prints it. The
// protobuf text format escapes control characters but keeps U+2028/U+2029.
type logMessageBody struct{ msg *waE2E.Message }
func (b logMessageBody) String() string {
return sanitizeLogText(fmt.Sprintf("%+v", b.msg))
}
func shouldIgnoreImageDownload(autoDownloadMedia, ignoreStatusMedia bool, chatJID types.JID) bool {
if !autoDownloadMedia {
return true
}
// Match on the JID's shape rather than struct equality: whatsmeow's
// broadcast branch assigns source.Chat without ToNonAD(), so a
// device-qualified status JID would not compare equal to
// types.StatusBroadcastJID. IsBroadcastList() is defined as "broadcast
// server and user != status", so negating it selects exactly status.
if ignoreStatusMedia && chatJID.Server == types.BroadcastServer && !chatJID.IsBroadcastList() {
return true
}
return false
}
func handleImageMessage(ctx context.Context, evt *events.Message, client *whatsmeow.Client) {
if shouldIgnoreImageDownload(config.WhatsappAutoDownloadMedia, config.WhatsappIgnoreStatusMedia, evt.Info.Chat) {
return
}
if client == nil {
return
}
if img := evt.Message.GetImageMessage(); img != nil {
if extracted, err := utils.ExtractMedia(ctx, client, config.PathStorages, img); err != nil {
log.Errorf("Failed to download image: %v", err)
} else {
log.Infof("Image downloaded to %s", extracted.MediaPath)
}
}
}
func handleAutoMarkRead(ctx context.Context, evt *events.Message, client *whatsmeow.Client) {
// Only mark read if auto-mark read is enabled and message is incoming
if !config.WhatsappAutoMarkRead || evt.Info.IsFromMe {
return
}
if client == nil {
return
}
// Mark the message as read
messageIDs := []types.MessageID{evt.Info.ID}
timestamp := time.Now()
chat := evt.Info.Chat
sender := evt.Info.Sender
if err := client.MarkRead(ctx, messageIDs, timestamp, chat, sender); err != nil {
log.Warnf("Failed to mark message %s as read: %v", sanitizeLogText(evt.Info.ID), err)
} else {
log.Debugf("Marked message %s as read", sanitizeLogText(evt.Info.ID))
}
}
// materializeSecretEditMessage decrypts a SecretEncryptedMessage{MESSAGE_EDIT}
// envelope into its inner ProtocolMessage{MESSAGE_EDIT} form so downstream
// consumers (chat storage, webhook payload builder, auto-reply) can rely on
// the legacy edit-handling code paths unchanged. Returns the original event
// when no envelope is present, when the client is nil, or when decryption
// fails — preserving existing behavior in every other case.
func materializeSecretEditMessage(ctx context.Context, evt *events.Message, client *whatsmeow.Client) *events.Message {
if evt == nil || evt.Message == nil || client == nil {
return evt
}
msg := utils.UnwrapMessage(evt.Message)
sem := msg.GetSecretEncryptedMessage()
if sem == nil || sem.GetSecretEncType() != waE2E.SecretEncryptedMessage_MESSAGE_EDIT {
return evt
}
decrypted, err := client.DecryptSecretEncryptedMessage(ctx, evt)
if err != nil {
targetID := ""
if k := sem.GetTargetMessageKey(); k != nil {
targetID = k.GetID()
}
log.Warnf("Failed to decrypt SecretEncryptedMessage(MESSAGE_EDIT) for %s (target=%s): %v", sanitizeLogText(evt.Info.ID), sanitizeLogText(targetID), err)
return evt
}
if decrypted == nil {
return evt
}
cloned := *evt
cloned.Message = decrypted
return &cloned
}
func handleWebhookForward(ctx context.Context, evt *events.Message, client *whatsmeow.Client, preparedPoll ...*webhookPollPayload) {
// Skip webhook for protocol messages that are internal sync messages
if protocolMessage := evt.Message.GetProtocolMessage(); protocolMessage != nil {
protocolType := protocolMessage.GetType().String()
// Only allow REVOKE and MESSAGE_EDIT through - skip all other protocol messages
// (HISTORY_SYNC_NOTIFICATION, APP_STATE_SYNC_KEY_SHARE, EPHEMERAL_SYNC_RESPONSE, etc.)
switch protocolType {
case "REVOKE", "MESSAGE_EDIT":
// These are meaningful user actions, allow webhook
default:
log.Debugf("Skipping webhook for protocol message type: %s", protocolType)
return
}
}
// Broadcast/status messages are never forwarded, regardless of Chatwoot:
// the Chatwoot pipeline rejects status@broadcast (a relayed status post
// would only spawn a noise "Status" contact), and plain webhook consumers
// must not receive broadcast noise just because Chatwoot is enabled.
if strings.Contains(evt.Info.SourceString(), "broadcast") {
return
}
// Forward to webhook if any webhook is configured (global or per-device)
// The forwardPayloadToConfiguredWebhooks function itself handles the no-op case
var pollPayload *webhookPollPayload
if len(preparedPoll) > 0 {
pollPayload = preparedPoll[0]
}
go func(e *events.Message, c *whatsmeow.Client, poll *webhookPollPayload) {
webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if err := forwardMessageToWebhook(webhookCtx, c, e, poll); err != nil {
logrus.Error("Failed forward to webhook: ", err)
}
}(evt, client, pollPayload)
}