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.

feat: implement webhook support for group participant events (#375)

Aldino Kemal847dcb85e4cc
diff --git a/.claude/agents/golang-code-reviewer.md b/.claude/agents/golang-code-reviewer.md
new file mode 100644
index 00000000..df1025e8
--- /dev/null
+++ b/.claude/agents/golang-code-reviewer.md
@@ -0,0 +1,169 @@
+---
+name: golang-code-reviewer
+description: Use this agent when you need expert-level review of Go code for bugs, memory/goroutine leaks, race conditions, and API compatibility. Examples: <example>Context: The user has just written a new Go function that handles concurrent operations. user: 'I just wrote this function to process multiple files concurrently: func processFiles(files []string) error { var wg sync.WaitGroup for _, file := range files { wg.Add(1) go func(f string) { defer wg.Done() // process file }(file) } wg.Wait() return nil }' assistant: 'Let me use the golang-code-reviewer agent to analyze this concurrent code for potential issues.' <commentary>Since the user has written Go code involving concurrency, use the golang-code-reviewer agent to check for race conditions, goroutine leaks, and other Go-specific issues.</commentary></example> <example>Context: User has modified an existing API structure in Go. user: 'I updated our User struct to include more fields: type User struct { ID int Name string Email string CreatedAt time.Time }' assistant: 'I'll use the golang-code-reviewer agent to check if this change maintains backward compatibility.' <commentary>Since the user modified a Go struct that could be part of an API, use the golang-code-reviewer agent to assess backward compatibility and potential breaking changes.</commentary></example>
+color: cyan
+---
+
+You are a Golang Software Reviewer Expert with deep expertise in Go best practices, performance optimization, and enterprise-grade code quality. Your primary mission is to prevent bugs, detect leaks, ensure non-breaking changes, and identify security vulnerabilities in Go codebases.
+
+## Core Review Focus Areas
+
+**Bug Prevention & Detection:**
+
+- Identify race conditions and concurrency issues
+- Detect nil pointer dereferences and panic scenarios
+- Find off-by-one errors and slice bounds violations
+- Catch unsafe type assertions and interface misuse
+- Identify improper error handling patterns
+- Spot resource ordering issues (acquire semaphore before consuming tokens)
+
+**Leak Prevention:**
+
+- Memory leaks (unclosed resources, circular references, slice retention)
+- Goroutine leaks (missing context cancellation, unbounded goroutines)
+- File descriptor leaks (unclosed files, network connections)
+- Channel leaks (unbuffered channels without proper closure)
+- **Rate limiter token leaks** (consuming tokens before resource acquisition)
+- Context leaks (unused contexts, improper cancellation)
+
+**Security Vulnerabilities:**
+
+- Sensitive data exposure in logs (URLs, tokens, credentials)
+- Improper input validation and sanitization
+- Insecure random number generation
+- Path traversal vulnerabilities
+- SQL injection risks in query building
+- Timing attack vulnerabilities
+
+**Non-Breaking Changes:**
+
+- API compatibility analysis for public interfaces
+- Interface contract preservation
+- Backward compatibility validation
+- Semantic versioning compliance assessment
+
+**Resource Management Patterns:**
+
+- HTTP request body reuse issues in retry logic
+- Context propagation for timeout/cancellation
+- Proper response body closing and error handling
+- Database connection management and pooling
+
+## Critical Patterns to Always Flag
+
+1. **Goroutine Leaks**: Infinite loops without exit conditions, missing context cancellation
+2. **Resource Leaks**: Missing defer statements for file/connection cleanup
+3. **Race Conditions**: Unsynchronized access to shared variables
+4. **Breaking Changes**: Field renames, method signature changes, interface modifications
+5. **Error Ignoring**: Using blank identifier to discard errors
+6. **Token Leaks**: Consuming rate limit tokens before acquiring necessary resources
+7. **Security Exposures**: Logging sensitive information (URLs, credentials, tokens)
+8. **Context Misuse**: Ignoring context parameters or improper propagation
+9. **HTTP Body Issues**: Request body reuse without proper handling
+10. **Resource Ordering**: Acquiring expensive resources before checking cheaper constraints
+
+## Review Response Format
+
+Structure your reviews as:
+
+```markdown
+## πŸ” Go Code Review
+
+### βœ… Strengths
+[Highlight well-implemented patterns and good practices]
+
+### 🚨 Critical Issues
+[High-priority bugs, leaks, or breaking changes with code examples]
+
+### ⚠️ Warnings
+[Medium-priority improvements and potential issues]
+
+### πŸ’‘ Suggestions
+[Best practice recommendations with code examples]
+
+### πŸ”„ Compatibility Assessment
+[Analysis of breaking changes and migration impact]
+
+### πŸ§ͺ Testing Recommendations
+[Specific test cases to add, including race detection]
+```
+
+## Go-Specific Guidelines
+
+**Concurrency**: Always check for proper context usage, mutex patterns, and channel operations. Look for unbounded goroutine creation and missing rate limiting. Recommend `go run -race` for race detection.
+
+**Memory Management**: Look for slice capacity optimization opportunities, proper string building, and avoid memory retention in closures. Check for HTTP response body leaks and unclosed resources.
+
+**Error Handling**: Ensure comprehensive error wrapping with context, proper error type definitions, and no silent error ignoring. Verify error collection patterns don't fail fast when multiple attempts should be made.
+
+**Resource Management**: Verify defer statements for cleanup, context timeouts, and connection pooling patterns. **Critical**: Check resource acquisition order - acquire cheap resources (semaphores) before expensive ones (rate limit tokens).
+
+**Security Analysis**: Scrutinize all logging statements for sensitive data exposure (URLs, API keys, tokens). Verify input sanitization and output encoding. Check for timing attack vulnerabilities in authentication code.
+
+**HTTP Client Patterns**: Examine HTTP request body reuse in retry logic, proper context propagation for timeouts, response body closing, and status code validation. Look for connection pooling configuration.
+
+**Rate Limiting**: Analyze rate limiter implementations for token leaks, proper resource ordering, and cleanup patterns. Ensure tokens are only consumed after successfully acquiring all prerequisites.
+
+**API Design**: Check interface segregation, backward compatibility, proper struct embedding, and method receiver consistency. Verify public API changes don't break existing consumers.
+
+## Deep Analysis Methodology
+
+When reviewing code, perform these checks systematically:
+
+1. **Line-by-line analysis**: Examine each function for resource leaks, error handling, and security issues
+2. **Resource flow tracking**: Follow resource acquisition and release patterns throughout the call stack
+3. **Error path analysis**: Trace all error conditions to ensure proper cleanup and no resource leaks
+4. **Security pattern recognition**: Identify logging statements, input handling, and credential management
+5. **Concurrency safety**: Check for race conditions, proper synchronization, and goroutine lifecycle management
+
+Provide specific code examples for both problematic patterns and recommended fixes. Always consider the broader impact on system reliability and maintainability. If you identify potential performance issues, suggest profiling commands and optimization strategies.
+
+## Examples of Critical Issues to Catch
+
+**Rate Limiter Token Leak**:
+
+```go
+// PROBLEMATIC - token consumed before semaphore check
+if err := limiter.Wait(ctx); err != nil { return false }
+select {
+case semaphore <- struct{}{}: return true
+default: return false // TOKEN LEAKED!
+}
+
+// CORRECT - semaphore first, then token
+select {
+case semaphore <- struct{}{}:
+ if err := limiter.Wait(ctx); err != nil {
+ <-semaphore // cleanup
+ return false
+ }
+ return true
+default: return false
+}
+```
+
+**Security Log Exposure**:
+
+```go
+// PROBLEMATIC - exposes sensitive URLs
+log.Info("Forwarding to webhook:", webhookURLs)
+
+// CORRECT - counts only
+log.Infof("Forwarding to %d webhook(s)", len(webhookURLs))
+```
+
+**HTTP Body Reuse**:
+
+```go
+// PROBLEMATIC - body consumed after first attempt
+req := http.NewRequest("POST", url, bytes.NewBuffer(data))
+for i := 0; i < retries; i++ {
+ client.Do(req) // FAILS after first attempt
+}
+
+// CORRECT - new body for each attempt
+for i := 0; i < retries; i++ {
+ req.Body = io.NopCloser(bytes.NewBuffer(data))
+ client.Do(req)
+}
+```
diff --git a/.claude/commands/review-code.md b/.claude/commands/review-code.md
new file mode 100644
index 00000000..842d7463
--- /dev/null
+++ b/.claude/commands/review-code.md
@@ -0,0 +1 @@
+Use the subagent golang-code-reviewer to examine all of the changes by comparing them to the main branch. You must verify that every commit and stage on this branch is present, compare them to the main branch, and report back to me the review's outcome.
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.md
index 10ca67dd..3b420a43 100644
--- a/docs/webhook-payload.md
+++ b/docs/webhook-payload.md
@@ -187,6 +187,93 @@ Triggered when a message is read by the recipient (they opened the chat and saw
| `payload.sender_id` | string | JID of the message sender |
| `timestamp` | string | RFC3339 formatted timestamp when the receipt was received |
+## Group Events
+
+Group events are triggered when group metadata changes, including member join/leave events, admin promotions/demotions, and group settings updates. These events use the `group.participants` event type and provide comprehensive information about group changes.
+
+### Group Member Join
+
+Triggered when users join or are added to a group.
+
+```json
+{
+ "event": "group.participants",
+ "payload": {
+ "chat_id": "[email protected]",
+ "type": "join",
+ "jids": [
+ ]
+ },
+ "timestamp": "2025-07-28T10:30:00Z"
+}
+```
+
+### Group Member Leave
+
+Triggered when users leave or are removed from a group.
+
+```json
+{
+ "event": "group.participants",
+ "payload": {
+ "chat_id": "[email protected]",
+ "type": "leave",
+ "jids": [
+ ]
+ },
+ "timestamp": "2025-07-28T10:32:00Z"
+}
+```
+
+### Group Member Promotion
+
+Triggered when users are promoted to admin.
+
+```json
+{
+ "event": "group.participants",
+ "payload": {
+ "chat_id": "[email protected]",
+ "type": "promote",
+ "jids": [
+ ]
+ },
+ "timestamp": "2025-07-28T10:33:00Z"
+}
+```
+
+### Group Member Demotion
+
+Triggered when users are demoted from admin.
+
+```json
+{
+ "event": "group.participants",
+ "payload": {
+ "chat_id": "[email protected]",
+ "type": "demote",
+ "jids": [
+ ]
+ },
+ "timestamp": "2025-07-28T10:34:00Z"
+}
+```
+
+### Group Event Fields
+
+| **Field** | **Type** | **Description** |
+|-------------------|----------|--------------------------------------------------------------|
+| `event` | string | Always `"group.participants"` for group events |
+| `payload.chat_id` | string | Group identifier (e.g., `"[email protected]"`) |
+| `payload.type` | string | Action type: `"join"`, `"leave"`, `"promote"`, or `"demote"` |
+| `payload.jids` | array | Array of user JIDs affected by this action |
+| `timestamp` | string | RFC3339 formatted timestamp when the group event occurred |
+
## Media Messages
### Image Message
@@ -534,6 +621,35 @@ app.post('/webhook', (req, res) => {
message_ids: data.payload.ids,
description: data.payload.receipt_type_description
});
+ } else if (data.event === 'group.participants') {
+ console.log(`Group ${data.payload.type} event:`, {
+ chat_id: data.payload.chat_id,
+ type: data.payload.type,
+ affected_users: data.payload.jids
+ });
+
+ // Handle specific group actions
+ switch (data.payload.type) {
+ case 'join':
+ console.log(`${data.payload.jids.length} users joined group ${data.payload.chat_id}`);
+ // Auto-greet new members
+ data.payload.jids.forEach(jid => {
+ console.log(`Welcome ${jid} to the group!`);
+ });
+ break;
+ case 'leave':
+ console.log(`${data.payload.jids.length} users left group ${data.payload.chat_id}`);
+ // Update member database
+ break;
+ case 'promote':
+ console.log(`${data.payload.jids.length} users promoted in group ${data.payload.chat_id}`);
+ // Notify about new admins
+ break;
+ case 'demote':
+ console.log(`${data.payload.jids.length} users demoted in group ${data.payload.chat_id}`);
+ // Handle admin removal
+ break;
+ }
} else if (data.action === 'message_deleted_for_me') {
console.log('Message deleted:', data.deleted_message_id);
} else if (data.action === 'message_revoked') {
diff --git a/src/go.mod b/src/go.mod
index 7b246db3..9e9256b8 100644
--- a/src/go.mod
+++ b/src/go.mod
@@ -23,6 +23,7 @@ require (
go.mau.fi/libsignal v0.2.0
go.mau.fi/whatsmeow v0.0.0-20250723174453-937d77661333
golang.org/x/image v0.29.0
+ golang.org/x/time v0.9.0
google.golang.org/protobuf v1.36.6
)
diff --git a/src/go.sum b/src/go.sum
index e1f36a2a..24212b90 100644
--- a/src/go.sum
+++ b/src/go.sum
@@ -4,8 +4,6 @@ github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7Oputl
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
github.com/PuerkitoBio/goquery v1.10.3 h1:pFYcNSqHxBD06Fpj/KsbStFRsgRATgnf3LeXiUkhzPo=
github.com/PuerkitoBio/goquery v1.10.3/go.mod h1:tMUX0zDMHXYlAQk6p35XxQMqMweEKB7iK7iLNd4RH4Y=
-github.com/aldinokemal/whatsmeow v0.0.0-20250708124515-f4ddac1a8e75 h1:2ZWi8KT/DuzZWUJjJU8pBMUIaYEsAS2ptpWLxN2ZX+U=
-github.com/aldinokemal/whatsmeow v0.0.0-20250708124515-f4ddac1a8e75/go.mod h1:bEyyFvXlwr/18B2pOkdX1vWAx1+y1NJX+sCXVyw01UA=
github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=
github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM=
@@ -31,13 +29,9 @@ github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-ozzo/ozzo-validation/v4 v4.3.0 h1:byhDUpfEwjsVQb1vBunvIjh2BHQ9ead57VkAEY4V+Es=
github.com/go-ozzo/ozzo-validation/v4 v4.3.0/go.mod h1:2NKgrcHl3z6cJs+3Oo940FPRiTzuqKbvfrL2RxCj6Ew=
-github.com/go-viper/mapstructure/v2 v2.3.0 h1:27XbWsHIqhbdR5TIC911OfYvgSaW93HM+dX7970Q7jk=
-github.com/go-viper/mapstructure/v2 v2.3.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
-github.com/gofiber/fiber/v2 v2.52.8 h1:xl4jJQ0BV5EJTA2aWiKw/VddRpHrKeZLF0QPUxqn0x4=
-github.com/gofiber/fiber/v2 v2.52.8/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=
github.com/gofiber/fiber/v2 v2.52.9 h1:YjKl5DOiyP3j0mO61u3NTmK7or8GzzWzCFzkboyP5cw=
github.com/gofiber/fiber/v2 v2.52.9/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=
github.com/gofiber/template v1.8.3 h1:hzHdvMwMo/T2kouz2pPCA0zGiLCeMnoGsQZBTSYgZxc=
@@ -64,10 +58,6 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
-github.com/mark3labs/mcp-go v0.33.0 h1:naxhjnTIs/tyPZmWUZFuG0lDmdA6sUyYGGf3gsHvTCc=
-github.com/mark3labs/mcp-go v0.33.0/go.mod h1:rXqOudj/djTORU/ThxYx8fqEVj/5pvTuuebQ2RC7uk4=
-github.com/mark3labs/mcp-go v0.34.0 h1:eWy7WBGvhk6EyAAyVzivTCprE52iXJwNtvHV6Cv3bR0=
-github.com/mark3labs/mcp-go v0.34.0/go.mod h1:rXqOudj/djTORU/ThxYx8fqEVj/5pvTuuebQ2RC7uk4=
github.com/mark3labs/mcp-go v0.35.0 h1:eh5bJGGVkNEaehCbPmAFqFgk/SB18YvxmsR2rnPm8BQ=
github.com/mark3labs/mcp-go v0.35.0/go.mod h1:rXqOudj/djTORU/ThxYx8fqEVj/5pvTuuebQ2RC7uk4=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
@@ -79,14 +69,10 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
-github.com/mattn/go-sqlite3 v1.14.28 h1:ThEiQrnbtumT+QMknw63Befp/ce/nUPgBPMlRFEum7A=
-github.com/mattn/go-sqlite3 v1.14.28/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mattn/go-sqlite3 v1.14.29 h1:1O6nRLJKvsi1H2Sj0Hzdfojwt8GiGKm+LOfLaBFaouQ=
github.com/mattn/go-sqlite3 v1.14.29/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
-github.com/petermattis/goid v0.0.0-20250508124226-395b08cebbdb h1:3PrKuO92dUTMrQ9dx0YNejC6U/Si6jqKmyQ9vWjwqR4=
-github.com/petermattis/goid v0.0.0-20250508124226-395b08cebbdb/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4=
github.com/petermattis/goid v0.0.0-20250721140440-ea1c0173183e h1:D0bJD+4O3G4izvrQUmzCL80zazlN7EwJ0PPDhpJWC/I=
github.com/petermattis/goid v0.0.0-20250721140440-ea1c0173183e/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
@@ -118,7 +104,6 @@ github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE=
github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
-github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.7 h1:vN6T9TfwStFPFM5XzjsvmzZkLuaLX+HS+0SeFLRgU6M=
github.com/spf13/pflag v1.0.7/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
@@ -133,8 +118,6 @@ github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
-github.com/valyala/fasthttp v1.63.0 h1:DisIL8OjB7ul2d7cBaMRcKTQDYnrGy56R4FCiuDP0Ns=
-github.com/valyala/fasthttp v1.63.0/go.mod h1:REc4IeW+cAEyLrRPa5A81MIjvz0QE1laoTX2EaPHKJM=
github.com/valyala/fasthttp v1.64.0 h1:QBygLLQmiAyiXuRhthf0tuRkqAFcrC42dckN2S+N3og=
github.com/valyala/fasthttp v1.64.0/go.mod h1:dGmFxwkWXSK0NbOSJuF7AMVzU+lkHz0wQVvVITv2UQA=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
@@ -146,10 +129,6 @@ go.mau.fi/libsignal v0.2.0 h1:oRXj3OHhEJq51BFEM8/50UZblmWiTYH93hsNTPcbk90=
go.mau.fi/libsignal v0.2.0/go.mod h1:tvjoDsMejgT38CXTXwqaYu8itBiY8O2Mb6biWvZBb9k=
go.mau.fi/util v0.8.8 h1:OnuEEc/sIJFhnq4kFggiImUpcmnmL/xpvQMRu5Fiy5c=
go.mau.fi/util v0.8.8/go.mod h1:Y/kS3loxTEhy8Vill513EtPXr+CRDdae+Xj2BXXMy/c=
-go.mau.fi/whatsmeow v0.0.0-20250709212552-0b8557ee0860 h1:0AdAzM/QtzgUKiJ2oyVfiSiZq/fIjxadUtepPy2lZwk=
-go.mau.fi/whatsmeow v0.0.0-20250709212552-0b8557ee0860/go.mod h1:bEyyFvXlwr/18B2pOkdX1vWAx1+y1NJX+sCXVyw01UA=
-go.mau.fi/whatsmeow v0.0.0-20250717084138-aecc878ab213 h1:CYkW6OUQk0uvzMa3wN7RtGd7H8DxYdYqw/DoFobTK2w=
-go.mau.fi/whatsmeow v0.0.0-20250717084138-aecc878ab213/go.mod h1:ltDTXUgOAT7LcFKp11H+5S7UY7+xHBMGzNJcv3dLHGk=
go.mau.fi/whatsmeow v0.0.0-20250723174453-937d77661333 h1:wZnqbIembr69yyUeWWEjxNxeofhYg3PDEx1BRRvHdWM=
go.mau.fi/whatsmeow v0.0.0-20250723174453-937d77661333/go.mod h1:ltDTXUgOAT7LcFKp11H+5S7UY7+xHBMGzNJcv3dLHGk=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
@@ -160,19 +139,11 @@ golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliY
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
-golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM=
-golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U=
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
-golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
-golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
-golang.org/x/exp v0.0.0-20250711185948-6ae5c78190dc h1:TS73t7x3KarrNd5qAipmspBDS1rkMcgVG/fS1aRb4Rc=
-golang.org/x/exp v0.0.0-20250711185948-6ae5c78190dc/go.mod h1:A+z0yzpGtvnG90cToK5n2tu8UJVP2XUATh+r+sfOOOc=
golang.org/x/exp v0.0.0-20250718183923-645b1fa84792 h1:R9PFI6EUdfVKgwKjZef7QIwGcBKu86OEFpJ9nUEP2l4=
golang.org/x/exp v0.0.0-20250718183923-645b1fa84792/go.mod h1:A+z0yzpGtvnG90cToK5n2tu8UJVP2XUATh+r+sfOOOc=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
-golang.org/x/image v0.28.0 h1:gdem5JW1OLS4FbkWgLO+7ZeFzYtL3xClb97GaUzYMFE=
-golang.org/x/image v0.28.0/go.mod h1:GUJYXtnGKEUgggyzh+Vxt+AviiCcyiwpsl8iQ8MvwGY=
golang.org/x/image v0.29.0 h1:HcdsyR4Gsuys/Axh0rDEmlBmB68rW1U9BUdB3UVHsas=
golang.org/x/image v0.29.0/go.mod h1:RVJROnf3SLK8d26OW91j4FrIHGbsJ8QnbEocVTOWQDA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
@@ -189,8 +160,6 @@ golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
-golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
-golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -214,8 +183,6 @@ golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
-golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
-golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
@@ -236,10 +203,10 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
-golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
-golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
+golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY=
+golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
diff --git a/src/infrastructure/whatsapp/event_delete.go b/src/infrastructure/whatsapp/event_delete.go
index a2b31764..ba428c30 100644
--- a/src/infrastructure/whatsapp/event_delete.go
+++ b/src/infrastructure/whatsapp/event_delete.go
@@ -12,7 +12,7 @@ import (
// forwardDeleteToWebhook sends a delete event to webhook
func forwardDeleteToWebhook(ctx context.Context, evt *events.DeleteForMe, message *domainChatStorage.Message) error {
- logrus.Info("Forwarding delete event to webhook:", config.WhatsappWebhook)
+ logrus.Infof("Forwarding delete event to %d configured webhook(s)", len(config.WhatsappWebhook))
payload, err := createDeletePayload(ctx, evt, message)
if err != nil {
return err
diff --git a/src/infrastructure/whatsapp/event_group.go b/src/infrastructure/whatsapp/event_group.go
new file mode 100644
index 00000000..1a812704
--- /dev/null
+++ b/src/infrastructure/whatsapp/event_group.go
@@ -0,0 +1,98 @@
+package whatsapp
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+// createGroupInfoPayload creates a webhook payload for group information events
+func createGroupInfoPayload(evt *events.GroupInfo, actionType string, jids []types.JID) map[string]any {
+ body := make(map[string]any)
+
+ // Create payload structure matching the expected format
+ payload := make(map[string]any)
+
+ // Add group chat ID
+ payload["chat_id"] = evt.JID.String()
+
+ // Add action type and affected users
+ payload["type"] = actionType
+ payload["jids"] = jidsToStrings(jids)
+
+ // Wrap in payload structure
+ body["payload"] = payload
+
+ // Add metadata for webhook processing
+ body["event"] = "group.participants"
+ body["timestamp"] = evt.Timestamp.Format(time.RFC3339)
+
+ return body
+}
+
+// jidsToStrings converts a slice of JIDs to a slice of strings
+func jidsToStrings(jids []types.JID) []string {
+ if len(jids) == 0 {
+ return []string{} // Return empty array instead of nil for consistent JSON
+ }
+
+ result := make([]string, len(jids))
+ for i, jid := range jids {
+ result[i] = jid.String()
+ }
+ return result
+}
+
+// forwardGroupInfoToWebhook forwards group information events to the configured webhook URLs
+func forwardGroupInfoToWebhook(ctx context.Context, evt *events.GroupInfo) error {
+ logrus.Infof("Forwarding group info event to %d configured webhook(s)", len(config.WhatsappWebhook))
+
+ // Send separate webhook events for each action type
+ actions := []struct {
+ actionType string
+ jids []types.JID
+ }{
+ {"join", evt.Join},
+ {"leave", evt.Leave},
+ {"promote", evt.Promote},
+ {"demote", evt.Demote},
+ }
+
+ for _, action := range actions {
+ if len(action.jids) > 0 {
+ payload := createGroupInfoPayload(evt, action.actionType, action.jids)
+
+ // Collect errors from all webhook URLs instead of failing fast
+ var errors []error
+ for _, url := range config.WhatsappWebhook {
+ if err := submitWebhook(ctx, payload, url); err != nil {
+ errors = append(errors, fmt.Errorf("webhook %s failed: %w", url, err))
+ }
+ }
+
+ // If all webhooks failed, return combined error
+ if len(errors) == len(config.WhatsappWebhook) && len(errors) > 0 {
+ var errMessages []string
+ for _, err := range errors {
+ errMessages = append(errMessages, err.Error())
+ }
+ return fmt.Errorf("all webhook URLs failed: %s", strings.Join(errMessages, "; "))
+ }
+
+ // Log partial failures
+ if len(errors) > 0 {
+ logrus.Warnf("Some webhook URLs failed for group %s event: %v", action.actionType, errors)
+ }
+
+ logrus.Infof("Group %s event forwarded to webhook: %d users %s", action.actionType, len(action.jids), action.actionType)
+ }
+ }
+
+ return nil
+}
diff --git a/src/infrastructure/whatsapp/event_message.go b/src/infrastructure/whatsapp/event_message.go
index e2cdf06f..d5c8b451 100644
--- a/src/infrastructure/whatsapp/event_message.go
+++ b/src/infrastructure/whatsapp/event_message.go
@@ -18,7 +18,7 @@ import (
// forwardMessageToWebhook is a helper function to forward message event to webhook url
func forwardMessageToWebhook(ctx context.Context, evt *events.Message) error {
- logrus.Info("Forwarding message event to webhook:", config.WhatsappWebhook)
+ logrus.Infof("Forwarding message event to %d configured webhook(s)", len(config.WhatsappWebhook))
payload, err := createMessagePayload(ctx, evt)
if err != nil {
return err
diff --git a/src/infrastructure/whatsapp/event_receipt.go b/src/infrastructure/whatsapp/event_receipt.go
index 0e49c4a7..925194d7 100644
--- a/src/infrastructure/whatsapp/event_receipt.go
+++ b/src/infrastructure/whatsapp/event_receipt.go
@@ -70,7 +70,7 @@ func createReceiptPayload(evt *events.Receipt) map[string]any {
// forwardReceiptToWebhook forwards message acknowledgement events to the configured webhook URLs
func forwardReceiptToWebhook(ctx context.Context, evt *events.Receipt) error {
- logrus.Info("Forwarding message ack event to webhook:", config.WhatsappWebhook)
+ logrus.Infof("Forwarding message ack event to %d configured webhook(s)", len(config.WhatsappWebhook))
payload := createReceiptPayload(evt)
for _, url := range config.WhatsappWebhook {
diff --git a/src/infrastructure/whatsapp/init.go b/src/infrastructure/whatsapp/init.go
index 916cdb8b..9998da3e 100644
--- a/src/infrastructure/whatsapp/init.go
+++ b/src/infrastructure/whatsapp/init.go
@@ -368,6 +368,8 @@ func handler(ctx context.Context, rawEvt any, chatStorageRepo domainChatStorage.
handleHistorySync(ctx, evt, chatStorageRepo)
case *events.AppState:
handleAppState(ctx, evt)
+ case *events.GroupInfo:
+ handleGroupInfo(ctx, evt)
}
}
@@ -615,6 +617,7 @@ func handleReceipt(ctx context.Context, evt *events.Receipt) {
}
// Forward receipt (ack) event to webhook if configured
+ // Note: Receipt events are not rate limited as they are critical for message delivery status
if len(config.WhatsappWebhook) > 0 && sendReceipt {
go func(e *events.Receipt) {
if err := forwardReceiptToWebhook(ctx, e); err != nil {
@@ -879,3 +882,36 @@ func processPushNames(_ context.Context, data *waHistorySync.HistorySync, chatSt
return nil
}
+
+func handleGroupInfo(ctx context.Context, evt *events.GroupInfo) {
+ // Only process events that have actual changes
+ hasChanges := len(evt.Join) > 0 || len(evt.Leave) > 0 || len(evt.Promote) > 0 || len(evt.Demote) > 0 ||
+ evt.Name != nil || evt.Topic != nil || evt.Locked != nil || evt.Announce != nil
+
+ if !hasChanges {
+ return
+ }
+
+ // Log group events for debugging
+ if len(evt.Join) > 0 {
+ log.Infof("Group %s: %d users joined at %s", evt.JID, len(evt.Join), evt.Timestamp)
+ }
+ if len(evt.Leave) > 0 {
+ log.Infof("Group %s: %d users left at %s", evt.JID, len(evt.Leave), evt.Timestamp)
+ }
+ if len(evt.Promote) > 0 {
+ log.Infof("Group %s: %d users promoted at %s", evt.JID, len(evt.Promote), evt.Timestamp)
+ }
+ if len(evt.Demote) > 0 {
+ log.Infof("Group %s: %d users demoted at %s", evt.JID, len(evt.Demote), evt.Timestamp)
+ }
+
+ // Forward group info event to webhook if configured
+ if len(config.WhatsappWebhook) > 0 {
+ go func(e *events.GroupInfo) {
+ if err := forwardGroupInfoToWebhook(ctx, e); err != nil {
+ logrus.Errorf("Failed to forward group info event to webhook: %v", err)
+ }
+ }(evt)
+ }
+}
diff --git a/src/infrastructure/whatsapp/webhook.go b/src/infrastructure/whatsapp/webhook.go
index fd25706e..3f980b9b 100644
--- a/src/infrastructure/whatsapp/webhook.go
+++ b/src/infrastructure/whatsapp/webhook.go
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
+ "io"
"net/http"
"time"
@@ -14,7 +15,7 @@ import (
"github.com/sirupsen/logrus"
)
-func submitWebhook(_ context.Context, payload map[string]any, url string) error {
+func submitWebhook(ctx context.Context, payload map[string]any, url string) error {
client := &http.Client{Timeout: 10 * time.Second}
postBody, err := json.Marshal(payload)
@@ -22,7 +23,7 @@ func submitWebhook(_ context.Context, payload map[string]any, url string) error
return pkgError.WebhookError(fmt.Sprintf("Failed to marshal body: %v", err))
}
- req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(postBody))
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil)
if err != nil {
return pkgError.WebhookError(fmt.Sprintf("error when create http object %v", err))
}
@@ -41,13 +42,22 @@ func submitWebhook(_ context.Context, payload map[string]any, url string) error
var sleepDuration = 1 * time.Second
for attempt = 0; attempt < maxAttempts; attempt++ {
- if _, err = client.Do(req); err == nil {
- logrus.Infof("Successfully submitted webhook on attempt %d", attempt+1)
- return nil
+ // Create new request body for each attempt
+ req.Body = io.NopCloser(bytes.NewBuffer(postBody))
+ resp, err := client.Do(req)
+ if err == nil {
+ defer resp.Body.Close()
+ if resp.StatusCode >= 200 && resp.StatusCode < 300 {
+ logrus.Infof("Successfully submitted webhook on attempt %d", attempt+1)
+ return nil
+ }
+ err = fmt.Errorf("webhook returned status %d", resp.StatusCode)
}
logrus.Warnf("Attempt %d to submit webhook failed: %v", attempt+1, err)
- time.Sleep(sleepDuration)
- sleepDuration *= 2
+ if attempt < maxAttempts-1 {
+ time.Sleep(sleepDuration)
+ sleepDuration *= 2
+ }
}
return pkgError.WebhookError(fmt.Sprintf("error when submit webhook after %d attempts: %v", attempt, err))