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: whatsmeow ack event support (#362)

Aldino Kemal437744a28910
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.md
index bc5d9b05..10ca67dd 100644
--- a/docs/webhook-payload.md
+++ b/docs/webhook-payload.md
@@ -1,10 +1,12 @@
# Webhook Payload Documentation
-This document provides comprehensive documentation for the webhook payload structure used by the Go WhatsApp Web Multidevice application.
+This document provides comprehensive documentation for the webhook payload structure used by the Go WhatsApp Web
+Multidevice application.
## Overview
-The webhook system sends HTTP POST requests to configured URLs whenever WhatsApp events occur. Each webhook request includes event data in JSON format and security headers for verification.
+The webhook system sends HTTP POST requests to configured URLs whenever WhatsApp events occur. Each webhook request
+includes event data in JSON format and security headers for verification.
## Security
@@ -27,7 +29,7 @@ function verifyWebhookSignature(payload, signature, secret) {
.createHmac('sha256', secret)
.update(payload, 'utf8')
.digest('hex');
-
+
const receivedSignature = signature.replace('sha256=', '');
return crypto.timingSafeEqual(
Buffer.from(expectedSignature, 'hex'),
@@ -57,13 +59,13 @@ def verify_webhook_signature(payload, signature, secret):
All webhook payloads share these common fields:
-| **Field** | **Type** | **Description** |
-|----------------|----------|------------------------------------------------------------------------|
-| `sender_id` | string | User part of sender JID (phone number, without `@s.whatsapp.net`) |
-| `chat_id` | string | User part of chat JID |
-| `from` | string | Full JID of the sender (e.g., `[email protected]`) |
-| `timestamp` | string | RFC3339 formatted timestamp (e.g., `2023-10-15T10:30:00Z`) |
-| `pushname` | string | Display name of the sender |
+| **Field** | **Type** | **Description** |
+|-------------|----------|-------------------------------------------------------------------|
+| `sender_id` | string | User part of sender JID (phone number, without `@s.whatsapp.net`) |
+| `chat_id` | string | User part of chat JID |
+| `from` | string | Full JID of the sender (e.g., `[email protected]`) |
+| `timestamp` | string | RFC3339 formatted timestamp (e.g., `2023-10-15T10:30:00Z`) |
+| `pushname` | string | Display name of the sender |
## Message Events
@@ -71,17 +73,17 @@ All webhook payloads share these common fields:
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "[email protected]",
- "timestamp": "2023-10-15T10:30:00Z",
- "pushname": "John Doe",
- "message": {
- "text": "Hello, how are you?",
- "id": "3EB0C127D7BACC83D6A1",
- "replied_id": "",
- "quoted_message": ""
- }
+ "sender_id": "628123456789",
+ "chat_id": "628987654321",
+ "from": "[email protected]",
+ "timestamp": "2023-10-15T10:30:00Z",
+ "pushname": "John Doe",
+ "message": {
+ "text": "Hello, how are you?",
+ "id": "3EB0C127D7BACC83D6A1",
+ "replied_id": "",
+ "quoted_message": ""
+ }
}
```
@@ -89,17 +91,17 @@ All webhook payloads share these common fields:
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "[email protected]",
- "timestamp": "2023-10-15T10:35:00Z",
- "pushname": "John Doe",
- "message": {
- "text": "I'm doing great, thanks!",
- "id": "3EB0C127D7BACC83D6A2",
- "replied_id": "3EB0C127D7BACC83D6A1",
- "quoted_message": "Hello, how are you?"
- }
+ "sender_id": "628123456789",
+ "chat_id": "628987654321",
+ "from": "[email protected]",
+ "timestamp": "2023-10-15T10:35:00Z",
+ "pushname": "John Doe",
+ "message": {
+ "text": "I'm doing great, thanks!",
+ "id": "3EB0C127D7BACC83D6A2",
+ "replied_id": "3EB0C127D7BACC83D6A1",
+ "quoted_message": "Hello, how are you?"
+ }
}
```
@@ -107,46 +109,106 @@ All webhook payloads share these common fields:
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "[email protected]",
- "timestamp": "2023-10-15T10:40:00Z",
- "pushname": "John Doe",
- "reaction": {
- "message": "👍",
- "id": "3EB0C127D7BACC83D6A1"
- },
- "message": {
- "text": "",
- "id": "88760C69D1F35FEB239102699AE9XXXX",
- "replied_id": "",
- "quoted_message": ""
- }
+ "sender_id": "628123456789",
+ "chat_id": "628987654321",
+ "from": "[email protected]",
+ "timestamp": "2023-10-15T10:40:00Z",
+ "pushname": "John Doe",
+ "reaction": {
+ "message": "👍",
+ "id": "3EB0C127D7BACC83D6A1"
+ },
+ "message": {
+ "text": "",
+ "id": "88760C69D1F35FEB239102699AE9XXXX",
+ "replied_id": "",
+ "quoted_message": ""
+ }
+}
+```
+
+## Receipt Events
+
+Receipt events are triggered when messages receive acknowledgments such as delivery confirmations and read receipts.
+These events use the `message.ack` event type and provide information about message status changes.
+
+### Message Delivered
+
+Triggered when a message is successfully delivered to the recipient's device.
+
+```json
+{
+ "event": "message.ack",
+ "payload": {
+ "chat_id": "[email protected]",
+ "ids": [
+ "3EB00106E8BE0F407E88EC"
+ ],
+ "receipt_type": "delivered",
+ "receipt_type_description": "means the message was delivered to the device (but the user might not have noticed).",
+ "sender_id": "[email protected]"
+ },
+ "timestamp": "2025-07-18T22:44:20Z"
+}
+```
+
+### Message Read
+
+Triggered when a message is read by the recipient (they opened the chat and saw the message).
+
+```json
+{
+ "event": "message.ack",
+ "payload": {
+ "chat_id": "[email protected]",
+ "ids": [
+ "3EB00106E8BE0F407E88EC"
+ ],
+ "receipt_type": "read",
+ "receipt_type_description": "the user opened the chat and saw the message.",
+ "sender_id": "[email protected]"
+ },
+ "timestamp": "2025-07-18T22:44:44Z"
}
```
+### Receipt Event Fields
+
+| **Field** | **Type** | **Description** |
+|------------------------------------|----------|-----------------------------------------------------------|
+| `event` | string | Always `"message.ack"` for receipt events |
+| `payload.chat_id` | string | Chat identifier (group or individual chat) |
+| `payload.from` | string | Sender information with chat context |
+| `payload.ids` | array | Array of message IDs that received the acknowledgment |
+| `payload.receipt_type` | string | Type of receipt: `"delivered"`, `"read"`, etc. |
+| `payload.receipt_type_description` | string | Human-readable description of the receipt type |
+| `payload.sender_id` | string | JID of the message sender |
+| `timestamp` | string | RFC3339 formatted timestamp when the receipt was received |
+
## Media Messages
### Image Message
```json
{
- "sender_id": "628123456789",
- "chat_id": "628123456789",
- "from": "[email protected]",
- "timestamp": "2025-07-13T11:05:51Z",
- "pushname": "John Doe",
- "message": {
- "text": "",
- "id": "********************", // masked
- "replied_id": "",
- "quoted_message": ""
- },
- "image": {
- "media_path": "statics/media/1752404751-ad9e37ac-c658-4fe5-8d25-ba4a3f4d58fd.jpe",
- "mime_type": "image/jpeg",
- "caption": "gijg"
- }
+ "sender_id": "628123456789",
+ "chat_id": "628123456789",
+ "from": "[email protected]",
+ "timestamp": "2025-07-13T11:05:51Z",
+ "pushname": "John Doe",
+ "message": {
+ "text": "",
+ "id": "********************",
+ "replied_id": "",
+ "quoted_message": ""
+ },
+ "image": {
+ "media_path": "statics/media/1752404751-ad9e37ac-c658-4fe5-8d25-ba4a3f4d58fd.jpe",
+ "mime_type": "image/jpeg",
+ "caption": "gijg"
+ }
}
```
@@ -154,22 +216,22 @@ All webhook payloads share these common fields:
```json
{
- "sender_id": "628123456789",
- "chat_id": "628123456789",
- "from": "[email protected]",
- "timestamp": "2025-07-13T11:07:24Z",
- "pushname": "Notification System",
- "message": {
- "text": "",
- "id": "********************", // masked
- "replied_id": "",
- "quoted_message": ""
- },
- "video": {
- "media_path": "statics/media/1752404845-b9393cd1-8546-4df9-8a60-ee3276036aba.m4v",
- "mime_type": "video/mp4",
- "caption": "okk"
- }
+ "sender_id": "628123456789",
+ "chat_id": "628123456789",
+ "from": "[email protected]",
+ "timestamp": "2025-07-13T11:07:24Z",
+ "pushname": "Notification System",
+ "message": {
+ "text": "",
+ "id": "********************",
+ "replied_id": "",
+ "quoted_message": ""
+ },
+ "video": {
+ "media_path": "statics/media/1752404845-b9393cd1-8546-4df9-8a60-ee3276036aba.m4v",
+ "mime_type": "video/mp4",
+ "caption": "okk"
+ }
}
```
@@ -177,22 +239,22 @@ All webhook payloads share these common fields:
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "[email protected]",
- "timestamp": "2023-10-15T10:55:00Z",
- "pushname": "John Doe",
- "message": {
- "text": "",
- "id": "3EB0C127D7BACC83D6A5",
- "replied_id": "",
- "quoted_message": ""
- },
- "audio": {
- "media_path": "statics/media/1752404905-b9393cd1-8546-4df9-8a60-ee3276036aba.m4v",
- "mime_type": "audio/ogg",
- "caption": "okk"
- }
+ "sender_id": "628123456789",
+ "chat_id": "628987654321",
+ "from": "[email protected]",
+ "timestamp": "2023-10-15T10:55:00Z",
+ "pushname": "John Doe",
+ "message": {
+ "text": "",
+ "id": "3EB0C127D7BACC83D6A5",
+ "replied_id": "",
+ "quoted_message": ""
+ },
+ "audio": {
+ "media_path": "statics/media/1752404905-b9393cd1-8546-4df9-8a60-ee3276036aba.m4v",
+ "mime_type": "audio/ogg",
+ "caption": "okk"
+ }
}
```
@@ -200,22 +262,22 @@ All webhook payloads share these common fields:
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "[email protected]",
- "timestamp": "2023-10-15T11:00:00Z",
- "pushname": "John Doe",
- "message": {
- "text": "",
- "id": "3EB0C127D7BACC83D6A6",
- "replied_id": "",
- "quoted_message": ""
- },
- "document": {
- "media_path": "statics/media/1752404965-b9393cd1-8546-4df9-8a60-ee3276036aba.m4v",
- "mime_type": "application/pdf",
- "caption": "okk"
- }
+ "sender_id": "628123456789",
+ "chat_id": "628987654321",
+ "from": "[email protected]",
+ "timestamp": "2023-10-15T11:00:00Z",
+ "pushname": "John Doe",
+ "message": {
+ "text": "",
+ "id": "3EB0C127D7BACC83D6A6",
+ "replied_id": "",
+ "quoted_message": ""
+ },
+ "document": {
+ "media_path": "statics/media/1752404965-b9393cd1-8546-4df9-8a60-ee3276036aba.m4v",
+ "mime_type": "application/pdf",
+ "caption": "okk"
+ }
}
```
@@ -223,22 +285,22 @@ All webhook payloads share these common fields:
```json
{
- "chat_id": "628968XXXXXXXX",
- "from": "[email protected]",
- "message": {
- "text": "",
- "id": "446AC2BAF2061B53E24CA526DBDFBD4E",
- "replied_id": "",
- "quoted_message": ""
- },
- "pushname": "Aldino Kemal",
- "sender_id": "628968XXXXXXXX",
- "sticker": {
- "media_path": "statics/media/1752404986-ff2464a6-c54c-4e6c-afde-c4c925ce3573.webp",
- "mime_type": "image/webp",
- "caption": ""
- },
- "timestamp": "2025-07-13T11:09:45Z"
+ "chat_id": "628968XXXXXXXX",
+ "from": "[email protected]",
+ "message": {
+ "text": "",
+ "id": "446AC2BAF2061B53E24CA526DBDFBD4E",
+ "replied_id": "",
+ "quoted_message": ""
+ },
+ "pushname": "Aldino Kemal",
+ "sender_id": "628968XXXXXXXX",
+ "sticker": {
+ "media_path": "statics/media/1752404986-ff2464a6-c54c-4e6c-afde-c4c925ce3573.webp",
+ "mime_type": "image/webp",
+ "caption": ""
+ },
+ "timestamp": "2025-07-13T11:09:45Z"
}
```
@@ -248,30 +310,30 @@ All webhook payloads share these common fields:
```json
{
- "chat_id": "6289XXXXXXXXX",
- "contact": {
- "displayName": "3Care",
- "vcard": "BEGIN:VCARD\nVERSION:3.0\nN:;3Care;;;\nFN:3Care\nTEL;type=Mobile:+62 132\nEND:VCARD",
- "contextInfo": {
- "expiration": 7776000,
- "ephemeralSettingTimestamp": 1751808692,
- "disappearingMode": {
- "initiator": 0,
- "trigger": 1,
- "initiatedByMe": true
- }
- }
- },
- "from": "[email protected]",
- "message": {
- "text": "",
- "id": "56B3DFF4994284634E7AAFEEF6F1A0A2",
- "replied_id": "",
- "quoted_message": ""
- },
- "pushname": "Aldino Kemal",
- "sender_id": "6289XXXXXXXXX",
- "timestamp": "2025-07-13T11:10:19Z"
+ "chat_id": "6289XXXXXXXXX",
+ "contact": {
+ "displayName": "3Care",
+ "vcard": "BEGIN:VCARD\nVERSION:3.0\nN:;3Care;;;\nFN:3Care\nTEL;type=Mobile:+62 132\nEND:VCARD",
+ "contextInfo": {
+ "expiration": 7776000,
+ "ephemeralSettingTimestamp": 1751808692,
+ "disappearingMode": {
+ "initiator": 0,
+ "trigger": 1,
+ "initiatedByMe": true
+ }
+ }
+ },
+ "from": "[email protected]",
+ "message": {
+ "text": "",
+ "id": "56B3DFF4994284634E7AAFEEF6F1A0A2",
+ "replied_id": "",
+ "quoted_message": ""
+ },
+ "pushname": "Aldino Kemal",
+ "sender_id": "6289XXXXXXXXX",
+ "timestamp": "2025-07-13T11:10:19Z"
}
```
@@ -279,23 +341,23 @@ All webhook payloads share these common fields:
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "John Doe",
- "timestamp": "2023-10-15T11:15:00Z",
- "pushname": "John Doe",
- "message": {
- "text": "",
- "id": "3EB0C127D7BACC83D6A9",
- "replied_id": "",
- "quoted_message": ""
- },
- "location": {
- "degreesLatitude": -6.2088,
- "degreesLongitude": 106.8456,
- "name": "Jakarta, Indonesia",
- "address": "Central Jakarta, DKI Jakarta, Indonesia"
- }
+ "sender_id": "628123456789",
+ "chat_id": "628987654321",
+ "from": "John Doe",
+ "timestamp": "2023-10-15T11:15:00Z",
+ "pushname": "John Doe",
+ "message": {
+ "text": "",
+ "id": "3EB0C127D7BACC83D6A9",
+ "replied_id": "",
+ "quoted_message": ""
+ },
+ "location": {
+ "degreesLatitude": -6.2088,
+ "degreesLongitude": 106.8456,
+ "name": "Jakarta, Indonesia",
+ "address": "Central Jakarta, DKI Jakarta, Indonesia"
+ }
}
```
@@ -303,31 +365,31 @@ All webhook payloads share these common fields:
```json
{
- "chat_id": "6289XXXXXXXXX",
- "from": "[email protected]",
- "location": {
- "degreesLatitude": -7.8050297,
- "degreesLongitude": 110.4549165,
- "JPEGThumbnail": "base64_image_thumbnail",
- "contextInfo": {
- "expiration": 7776000,
- "ephemeralSettingTimestamp": 1751808692,
- "disappearingMode": {
- "initiator": 0,
- "trigger": 1,
- "initiatedByMe": true
- }
- }
- },
- "message": {
- "text": "",
- "id": "94D13237B4D7F33EE4A63228BBD79EC0",
- "replied_id": "",
- "quoted_message": ""
- },
- "pushname": "Aldino Kemal",
- "sender_id": "6289685024091",
- "timestamp": "2025-07-13T11:11:22Z"
+ "chat_id": "6289XXXXXXXXX",
+ "from": "[email protected]",
+ "location": {
+ "degreesLatitude": -7.8050297,
+ "degreesLongitude": 110.4549165,
+ "JPEGThumbnail": "base64_image_thumbnail",
+ "contextInfo": {
+ "expiration": 7776000,
+ "ephemeralSettingTimestamp": 1751808692,
+ "disappearingMode": {
+ "initiator": 0,
+ "trigger": 1,
+ "initiatedByMe": true
+ }
+ }
+ },
+ "message": {
+ "text": "",
+ "id": "94D13237B4D7F33EE4A63228BBD79EC0",
+ "replied_id": "",
+ "quoted_message": ""
+ },
+ "pushname": "Aldino Kemal",
+ "sender_id": "6289685XXXXXX",
+ "timestamp": "2025-07-13T11:11:22Z"
}
```
@@ -337,21 +399,21 @@ All webhook payloads share these common fields:
```json
{
- "action": "message_revoked",
- "chat_id": "6289XXXXXXXXX",
- "from": "[email protected]",
- "message": {
- "text": "",
- "id": "F4062F2BBCB19B7432195AD7080DA4E2",
- "replied_id": "",
- "quoted_message": ""
- },
- "pushname": "Aldino Kemal",
- "revoked_chat": "[email protected]",
- "revoked_from_me": true,
- "revoked_message_id": "94D13237B4D7F33EE4A63228BBD79EC0",
- "sender_id": "6289XXXXXXXXX",
- "timestamp": "2025-07-13T11:13:30Z"
+ "action": "message_revoked",
+ "chat_id": "6289XXXXXXXXX",
+ "from": "[email protected]",
+ "message": {
+ "text": "",
+ "id": "F4062F2BBCB19B7432195AD7080DA4E2",
+ "replied_id": "",
+ "quoted_message": ""
+ },
+ "pushname": "Aldino Kemal",
+ "revoked_chat": "[email protected]",
+ "revoked_from_me": true,
+ "revoked_message_id": "94D13237B4D7F33EE4A63228BBD79EC0",
+ "sender_id": "6289XXXXXXXXX",
+ "timestamp": "2025-07-13T11:13:30Z"
}
```
@@ -359,19 +421,19 @@ All webhook payloads share these common fields:
```json
{
- "action": "message_edited",
- "chat_id": "6289XXXXXXXXX",
- "edited_text": "hhhiawww",
- "from": "[email protected]",
- "message": {
- "text": "hhhiawww",
- "id": "D6271D8223A05B4DA6AE9FE3CD632543",
- "replied_id": "",
- "quoted_message": ""
- },
- "pushname": "Aldino Kemal",
- "sender_id": "6289XXXXXXXXX",
- "timestamp": "2025-07-13T11:14:19Z"
+ "action": "message_edited",
+ "chat_id": "6289XXXXXXXXX",
+ "edited_text": "hhhiawww",
+ "from": "[email protected]",
+ "message": {
+ "text": "hhhiawww",
+ "id": "D6271D8223A05B4DA6AE9FE3CD632543",
+ "replied_id": "",
+ "quoted_message": ""
+ },
+ "pushname": "Aldino Kemal",
+ "sender_id": "6289XXXXXXXXX",
+ "timestamp": "2025-07-13T11:14:19Z"
}
```
@@ -381,23 +443,23 @@ All webhook payloads share these common fields:
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "John Doe",
- "timestamp": "2023-10-15T11:40:00Z",
- "pushname": "John Doe",
- "message": {
- "text": "",
- "id": "3EB0C127D7BACC83D6B2",
- "replied_id": "",
- "quoted_message": ""
- },
- "image": {
- "media_path": "statics/media/1752405060-b9393cd1-8546-4df9-8a60-ee3276036aba.m4v",
- "mime_type": "image/jpeg",
- "caption": "okk"
- },
- "view_once": true
+ "sender_id": "628123456789",
+ "chat_id": "628987654321",
+ "from": "John Doe",
+ "timestamp": "2023-10-15T11:40:00Z",
+ "pushname": "John Doe",
+ "message": {
+ "text": "",
+ "id": "3EB0C127D7BACC83D6B2",
+ "replied_id": "",
+ "quoted_message": ""
+ },
+ "image": {
+ "media_path": "statics/media/1752405060-b9393cd1-8546-4df9-8a60-ee3276036aba.m4v",
+ "mime_type": "image/jpeg",
+ "caption": "okk"
+ },
+ "view_once": true
}
```
@@ -405,18 +467,18 @@ All webhook payloads share these common fields:
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "John Doe",
- "timestamp": "2023-10-15T11:45:00Z",
- "pushname": "John Doe",
- "message": {
- "text": "This is a forwarded message",
- "id": "3EB0C127D7BACC83D6B3",
- "replied_id": "",
- "quoted_message": ""
- },
- "forwarded": true
+ "sender_id": "628123456789",
+ "chat_id": "628987654321",
+ "from": "John Doe",
+ "timestamp": "2023-10-15T11:45:00Z",
+ "pushname": "John Doe",
+ "message": {
+ "text": "This is a forwarded message",
+ "id": "3EB0C127D7BACC83D6B3",
+ "replied_id": "",
+ "quoted_message": ""
+ },
+ "forwarded": true
}
```
@@ -449,7 +511,7 @@ const express = require('express');
const crypto = require('crypto');
const app = express();
-app.use(express.raw({ type: 'application/json' }));
+app.use(express.raw({type: 'application/json'}));
app.post('/webhook', (req, res) => {
const signature = req.headers['x-hub-signature-256'];
@@ -466,7 +528,13 @@ app.post('/webhook', (req, res) => {
console.log('Received webhook:', data);
// Handle different event types
- if (data.action === 'message_deleted_for_me') {
+ if (data.event === 'message.ack') {
+ console.log(`Message ${data.payload.receipt_type}:`, {
+ chat_id: data.payload.chat_id,
+ message_ids: data.payload.ids,
+ description: data.payload.receipt_type_description
+ });
+ } else if (data.action === 'message_deleted_for_me') {
console.log('Message deleted:', data.deleted_message_id);
} else if (data.action === 'message_revoked') {
console.log('Message revoked:', data.revoked_message_id);
@@ -482,7 +550,7 @@ function verifyWebhookSignature(payload, signature, secret) {
.createHmac('sha256', secret)
.update(payload, 'utf8')
.digest('hex');
-
+
const receivedSignature = signature.replace('sha256=', '');
return crypto.timingSafeEqual(
Buffer.from(expectedSignature, 'hex'),
@@ -553,24 +621,24 @@ WHATSAPP_WEBHOOK_SECRET=your-super-secret-key
### Common Issues
1. **Webhook not receiving events**:
- - Check webhook URL is accessible from the internet
- - Verify webhook configuration
- - Check firewall and network settings
+ - Check webhook URL is accessible from the internet
+ - Verify webhook configuration
+ - Check firewall and network settings
2. **Signature verification fails**:
- - Ensure webhook secret matches configuration
- - Use raw request body for signature calculation
- - Check HMAC implementation
+ - Ensure webhook secret matches configuration
+ - Use raw request body for signature calculation
+ - Check HMAC implementation
3. **Timeouts**:
- - Optimize webhook processing speed
- - Implement asynchronous processing
- - Return response quickly, process in background
+ - Optimize webhook processing speed
+ - Implement asynchronous processing
+ - Return response quickly, process in background
4. **Missing media files**:
- - Check media storage path configuration
- - Ensure sufficient disk space
- - Verify file permissions
+ - Check media storage path configuration
+ - Ensure sufficient disk space
+ - Verify file permissions
### Debug Logging
diff --git a/readme.md b/readme.md
index 6fe9c59e..3e4df460 100644
--- a/readme.md
+++ b/readme.md
@@ -37,8 +37,9 @@ Download:
- For MCP mode, you need to run `<binary> mcp`
- for example: `./whatsapp mcp`
- `v7`
- - Starting version 7.x we are using goreleaser to build the binary, so you can download the binary from [release](https://github.com/aldinokemal/go-whatsapp-web-multidevice/releases/latest)
-
+ - Starting version 7.x we are using goreleaser to build the binary, so you can download the binary
+ from [release](https://github.com/aldinokemal/go-whatsapp-web-multidevice/releases/latest)
+
## Feature
- Send WhatsApp message via http API, [docs/openapi.yml](./docs/openapi.yaml) for more details
@@ -71,7 +72,8 @@ Download:
You may modify this by using the option below:
- `--webhook-secret="secret"`
- **Webhook Payload Documentation**
- For detailed webhook payload schemas, security implementation, and integration examples, see [Webhook Payload Documentation](./docs/webhook-payload.md)
+ For detailed webhook payload schemas, security implementation, and integration examples,
+ see [Webhook Payload Documentation](./docs/webhook-payload.md)
## Configuration
diff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.go
index d3b03c70..da143577 100644
--- a/src/infrastructure/chatstorage/sqlite_repository.go
+++ b/src/infrastructure/chatstorage/sqlite_repository.go
@@ -519,15 +519,28 @@ func (r *SQLiteRepository) CreateMessage(ctx context.Context, evt *events.Messag
// Get appropriate chat name using pushname if available
chatName := r.GetChatNameWithPushName(evt.Info.Chat, chatJID, evt.Info.Sender.User, evt.Info.PushName)
- // Extract ephemeral expiration
+ // Get existing chat to preserve ephemeral_expiration if needed
+ existingChat, err := r.GetChat(chatJID)
+ if err != nil {
+ return fmt.Errorf("failed to get existing chat: %w", err)
+ }
+
+ // Extract ephemeral expiration from incoming message
ephemeralExpiration := utils.ExtractEphemeralExpiration(evt.Message)
// Create or update chat
chat := &domainChatStorage.Chat{
- JID: chatJID,
- Name: chatName,
- LastMessageTime: evt.Info.Timestamp,
- EphemeralExpiration: ephemeralExpiration,
+ JID: chatJID,
+ Name: chatName,
+ LastMessageTime: evt.Info.Timestamp,
+ }
+
+ // Set ephemeral expiration: use incoming message value if > 0, otherwise preserve existing
+ if ephemeralExpiration > 0 {
+ chat.EphemeralExpiration = ephemeralExpiration
+ } else if existingChat != nil {
+ // Preserve existing ephemeral_expiration if incoming message doesn't have one
+ chat.EphemeralExpiration = existingChat.EphemeralExpiration
}
// Store or update the chat
@@ -641,13 +654,24 @@ func (r *SQLiteRepository) StoreSentMessageWithContext(ctx context.Context, mess
default:
}
- // Store or update chat
+ // Get existing chat to preserve ephemeral_expiration
+ existingChat, err := r.GetChat(chatJID)
+ if err != nil {
+ return fmt.Errorf("failed to get existing chat: %w", err)
+ }
+
+ // Store or update chat, preserving existing ephemeral_expiration
chat := &domainChatStorage.Chat{
JID: chatJID,
Name: chatName,
LastMessageTime: timestamp,
}
+ // Preserve existing ephemeral_expiration if chat exists
+ if existingChat != nil {
+ chat.EphemeralExpiration = existingChat.EphemeralExpiration
+ }
+
if err := r.StoreChat(chat); err != nil {
return fmt.Errorf("failed to store chat: %w", err)
}
diff --git a/src/infrastructure/whatsapp/event_delete.go b/src/infrastructure/whatsapp/event_delete.go
new file mode 100644
index 00000000..a2b31764
--- /dev/null
+++ b/src/infrastructure/whatsapp/event_delete.go
@@ -0,0 +1,61 @@
+package whatsapp
+
+import (
+ "context"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+// 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)
+ payload, err := createDeletePayload(ctx, evt, message)
+ if err != nil {
+ return err
+ }
+
+ for _, url := range config.WhatsappWebhook {
+ if err = submitWebhook(ctx, payload, url); err != nil {
+ return err
+ }
+ }
+
+ logrus.Info("Delete event forwarded to webhook")
+ return nil
+}
+
+// createDeletePayload creates a webhook payload for delete events
+func createDeletePayload(_ context.Context, evt *events.DeleteForMe, message *domainChatStorage.Message) (map[string]any, error) {
+ body := make(map[string]any)
+
+ // Basic delete event information
+ body["action"] = "event.delete_for_me"
+ body["deleted_message_id"] = evt.MessageID
+ body["sender_id"] = evt.SenderJID.User
+ body["timestamp"] = time.Now().Format(time.RFC3339)
+
+ // Include original message information if available
+ if message != nil {
+ body["chat_id"] = message.ChatJID
+ body["original_content"] = message.Content
+ body["original_sender"] = message.Sender
+ body["original_timestamp"] = message.Timestamp.Format(time.RFC3339)
+ body["was_from_me"] = message.IsFromMe
+
+ if message.MediaType != "" {
+ body["original_media_type"] = message.MediaType
+ body["original_filename"] = message.Filename
+ }
+ }
+
+ // Parse sender JID for proper formatting
+ if evt.SenderJID.Server != "" {
+ body["from"] = evt.SenderJID.String()
+ }
+
+ return body, nil
+}
diff --git a/src/infrastructure/whatsapp/event_message.go b/src/infrastructure/whatsapp/event_message.go
new file mode 100644
index 00000000..e2cdf06f
--- /dev/null
+++ b/src/infrastructure/whatsapp/event_message.go
@@ -0,0 +1,206 @@
+package whatsapp
+
+import (
+ "context"
+ "fmt"
+ "regexp"
+ "strings"
+ "time"
+
+ "go.mau.fi/whatsmeow/types"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+// 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)
+ payload, err := createMessagePayload(ctx, evt)
+ if err != nil {
+ return err
+ }
+
+ for _, url := range config.WhatsappWebhook {
+ if err = submitWebhook(ctx, payload, url); err != nil {
+ return err
+ }
+ }
+
+ logrus.Info("Message event forwarded to webhook")
+ return nil
+}
+
+func createMessagePayload(ctx context.Context, evt *events.Message) (map[string]any, error) {
+ message := utils.BuildEventMessage(evt)
+ waReaction := utils.BuildEventReaction(evt)
+ forwarded := utils.BuildForwarded(evt)
+
+ body := make(map[string]any)
+
+ body["sender_id"] = evt.Info.Sender.User
+ body["chat_id"] = evt.Info.Chat.User
+
+ if from := evt.Info.SourceString(); from != "" {
+ body["from"] = from
+
+ from_user, from_group := from, ""
+ if strings.Contains(from, " in ") {
+ from_user = strings.Split(from, " in ")[0]
+ from_group = strings.Split(from, " in ")[1]
+ }
+
+ if strings.HasSuffix(from_user, "@lid") {
+ body["from_lid"] = from_user
+ lid, err := types.ParseJID(from_user)
+ if err != nil {
+ logrus.Errorf("Error when parse jid: %v", err)
+ } else {
+ pn, err := cli.Store.LIDs.GetPNForLID(ctx, lid)
+ if err != nil {
+ logrus.Errorf("Error when get pn for lid %s: %v", lid.String(), err)
+ }
+ if !pn.IsEmpty() {
+ if from_group != "" {
+ body["from"] = fmt.Sprintf("%s in %s", pn.String(), from_group)
+ } else {
+ body["from"] = pn.String()
+ }
+ }
+ }
+ }
+ }
+ if message.ID != "" {
+ tags := regexp.MustCompile(`\B@\w+`).FindAllString(message.Text, -1)
+ tagsMap := make(map[string]bool)
+ for _, tag := range tags {
+ tagsMap[tag] = true
+ }
+ for tag := range tagsMap {
+ lid, err := types.ParseJID(tag[1:] + "@lid")
+ if err != nil {
+ logrus.Errorf("Error when parse jid: %v", err)
+ } else {
+ pn, err := cli.Store.LIDs.GetPNForLID(ctx, lid)
+ if err != nil {
+ logrus.Errorf("Error when get pn for lid %s: %v", lid.String(), err)
+ }
+ if !pn.IsEmpty() {
+ message.Text = strings.Replace(message.Text, tag, fmt.Sprintf("@%s", pn.User), -1)
+ }
+ }
+ }
+ body["message"] = message
+ }
+ if pushname := evt.Info.PushName; pushname != "" {
+ body["pushname"] = pushname
+ }
+ if waReaction.Message != "" {
+ body["reaction"] = waReaction
+ }
+ if evt.IsViewOnce {
+ body["view_once"] = evt.IsViewOnce
+ }
+ if forwarded {
+ body["forwarded"] = forwarded
+ }
+ if timestamp := evt.Info.Timestamp.Format(time.RFC3339); timestamp != "" {
+ body["timestamp"] = timestamp
+ }
+
+ // Handle protocol messages (revoke, etc.)
+ if protocolMessage := evt.Message.GetProtocolMessage(); protocolMessage != nil {
+ protocolType := protocolMessage.GetType().String()
+
+ switch protocolType {
+ case "REVOKE":
+ body["action"] = "message_revoked"
+ if key := protocolMessage.GetKey(); key != nil {
+ body["revoked_message_id"] = key.GetID()
+ body["revoked_from_me"] = key.GetFromMe()
+ if key.GetRemoteJID() != "" {
+ body["revoked_chat"] = key.GetRemoteJID()
+ }
+ }
+ case "MESSAGE_EDIT":
+ body["action"] = "message_edited"
+ if editedMessage := protocolMessage.GetEditedMessage(); editedMessage != nil {
+ if editedText := editedMessage.GetExtendedTextMessage(); editedText != nil {
+ body["edited_text"] = editedText.GetText()
+ } else if editedConv := editedMessage.GetConversation(); editedConv != "" {
+ body["edited_text"] = editedConv
+ }
+ }
+ }
+ }
+
+ if audioMedia := evt.Message.GetAudioMessage(); audioMedia != nil {
+ path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, audioMedia)
+ if err != nil {
+ logrus.Errorf("Failed to download audio from %s: %v", evt.Info.SourceString(), err)
+ return nil, pkgError.WebhookError(fmt.Sprintf("Failed to download audio: %v", err))
+ }
+ body["audio"] = path
+ }
+
+ if contactMessage := evt.Message.GetContactMessage(); contactMessage != nil {
+ body["contact"] = contactMessage
+ }
+
+ if documentMedia := evt.Message.GetDocumentMessage(); documentMedia != nil {
+ path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, documentMedia)
+ if err != nil {
+ logrus.Errorf("Failed to download document from %s: %v", evt.Info.SourceString(), err)
+ return nil, pkgError.WebhookError(fmt.Sprintf("Failed to download document: %v", err))
+ }
+ body["document"] = path
+ }
+
+ if imageMedia := evt.Message.GetImageMessage(); imageMedia != nil {
+ path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, imageMedia)
+ if err != nil {
+ logrus.Errorf("Failed to download image from %s: %v", evt.Info.SourceString(), err)
+ return nil, pkgError.WebhookError(fmt.Sprintf("Failed to download image: %v", err))
+ }
+ body["image"] = path
+ }
+
+ if listMessage := evt.Message.GetListMessage(); listMessage != nil {
+ body["list"] = listMessage
+ }
+
+ if liveLocationMessage := evt.Message.GetLiveLocationMessage(); liveLocationMessage != nil {
+ body["live_location"] = liveLocationMessage
+ }
+
+ if locationMessage := evt.Message.GetLocationMessage(); locationMessage != nil {
+ body["location"] = locationMessage
+ }
+
+ if orderMessage := evt.Message.GetOrderMessage(); orderMessage != nil {
+ body["order"] = orderMessage
+ }
+
+ if stickerMedia := evt.Message.GetStickerMessage(); stickerMedia != nil {
+ path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, stickerMedia)
+ if err != nil {
+ logrus.Errorf("Failed to download sticker from %s: %v", evt.Info.SourceString(), err)
+ return nil, pkgError.WebhookError(fmt.Sprintf("Failed to download sticker: %v", err))
+ }
+ body["sticker"] = path
+ }
+
+ if videoMedia := evt.Message.GetVideoMessage(); videoMedia != nil {
+ path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, videoMedia)
+ if err != nil {
+ logrus.Errorf("Failed to download video from %s: %v", evt.Info.SourceString(), err)
+ return nil, pkgError.WebhookError(fmt.Sprintf("Failed to download video: %v", err))
+ }
+ body["video"] = path
+ }
+
+ return body, nil
+}
diff --git a/src/infrastructure/whatsapp/event_receipt.go b/src/infrastructure/whatsapp/event_receipt.go
new file mode 100644
index 00000000..0e49c4a7
--- /dev/null
+++ b/src/infrastructure/whatsapp/event_receipt.go
@@ -0,0 +1,84 @@
+package whatsapp
+
+import (
+ "context"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+func getReceiptTypeDescription(evt types.ReceiptType) string {
+ switch evt {
+ case types.ReceiptTypeDelivered:
+ return "means the message was delivered to the device (but the user might not have noticed)."
+ case types.ReceiptTypeSender:
+ return "sent by your other devices when a message you sent is delivered to them."
+ case types.ReceiptTypeRetry:
+ return "the message was delivered to the device, but decrypting the message failed."
+ case types.ReceiptTypeRead:
+ return "the user opened the chat and saw the message."
+ case types.ReceiptTypeReadSelf:
+ return "the current user read a message from a different device, and has read receipts disabled in privacy settings."
+ case types.ReceiptTypePlayed:
+ return `This is dispatched for both incoming and outgoing messages when played. If the current user opened the media,
+ it means the media should be removed from all devices. If a recipient opened the media, it's just a notification
+ for the sender that the media was viewed.`
+ case types.ReceiptTypePlayedSelf:
+ return `probably means the current user opened a view-once media message from a different device,
+ and has read receipts disabled in privacy settings.`
+ default:
+ return "unknown receipt type"
+ }
+}
+
+// createReceiptPayload creates a webhook payload for message acknowledgement (receipt) events
+func createReceiptPayload(evt *events.Receipt) map[string]any {
+ body := make(map[string]any)
+
+ // Create payload structure matching the expected format
+ payload := make(map[string]any)
+
+ // Add message ID (use first message ID if multiple)
+ if len(evt.MessageIDs) > 0 {
+ payload["ids"] = evt.MessageIDs
+ }
+
+ // Add from field (the chat where the message was sent)
+ payload["chat_id"] = evt.Chat
+ payload["sender_id"] = evt.Sender
+ payload["from"] = evt.SourceString()
+
+ if evt.Type == types.ReceiptTypeDelivered {
+ payload["receipt_type"] = "delivered"
+ } else {
+ payload["receipt_type"] = evt.Type
+ }
+ payload["receipt_type_description"] = getReceiptTypeDescription(evt.Type)
+
+ // Wrap in payload structure
+ body["payload"] = payload
+
+ // Add metadata for webhook processing
+ body["event"] = "message.ack"
+ body["timestamp"] = evt.Timestamp.Format(time.RFC3339)
+
+ return body
+}
+
+// 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)
+ payload := createReceiptPayload(evt)
+
+ for _, url := range config.WhatsappWebhook {
+ if err := submitWebhook(ctx, payload, url); err != nil {
+ return err
+ }
+ }
+
+ logrus.Info("Message ack event forwarded to webhook")
+ return nil
+}
diff --git a/src/infrastructure/whatsapp/init.go b/src/infrastructure/whatsapp/init.go
index 04ac7245..916cdb8b 100644
--- a/src/infrastructure/whatsapp/init.go
+++ b/src/infrastructure/whatsapp/init.go
@@ -4,13 +4,14 @@ import (
"context"
"encoding/json"
"fmt"
- "go.mau.fi/whatsmeow/proto/waHistorySync"
"os"
"path/filepath"
"strings"
"sync/atomic"
"time"
+ "go.mau.fi/whatsmeow/proto/waHistorySync"
+
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
@@ -595,19 +596,31 @@ func handleWebhookForward(ctx context.Context, evt *events.Message) {
if len(config.WhatsappWebhook) > 0 &&
!strings.Contains(evt.Info.SourceString(), "broadcast") {
go func(evt *events.Message) {
- if err := forwardToWebhook(ctx, evt); err != nil {
+ if err := forwardMessageToWebhook(ctx, evt); err != nil {
logrus.Error("Failed forward to webhook: ", err)
}
}(evt)
}
}
-func handleReceipt(_ context.Context, evt *events.Receipt) {
+func handleReceipt(ctx context.Context, evt *events.Receipt) {
+ sendReceipt := false
switch evt.Type {
case types.ReceiptTypeRead, types.ReceiptTypeReadSelf:
- log.Infof("%v was read by %s at %s", evt.MessageIDs, evt.SourceString(), evt.Timestamp)
+ sendReceipt = true
+ log.Infof("%v was read by %s at %s: %+v", evt.MessageIDs, evt.SourceString(), evt.Timestamp, evt)
case types.ReceiptTypeDelivered:
- log.Infof("%s was delivered to %s at %s", evt.MessageIDs[0], evt.SourceString(), evt.Timestamp)
+ sendReceipt = true
+ log.Infof("%s was delivered to %s at %s: %+v", evt.MessageIDs[0], evt.SourceString(), evt.Timestamp, evt)
+ }
+
+ // Forward receipt (ack) event to webhook if configured
+ if len(config.WhatsappWebhook) > 0 && sendReceipt {
+ go func(e *events.Receipt) {
+ if err := forwardReceiptToWebhook(ctx, e); err != nil {
+ logrus.Errorf("Failed to forward ack event to webhook: %v", err)
+ }
+ }(evt)
}
}
diff --git a/src/infrastructure/whatsapp/webhook.go b/src/infrastructure/whatsapp/webhook.go
index 8dc4f2c5..fd25706e 100644
--- a/src/infrastructure/whatsapp/webhook.go
+++ b/src/infrastructure/whatsapp/webhook.go
@@ -6,210 +6,15 @@ import (
"encoding/json"
"fmt"
"net/http"
- "regexp"
- "strings"
"time"
- "go.mau.fi/whatsmeow/types"
-
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
- domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/sirupsen/logrus"
- "go.mau.fi/whatsmeow/types/events"
)
-// forwardToWebhook is a helper function to forward event to webhook url
-func forwardToWebhook(ctx context.Context, evt *events.Message) error {
- logrus.Info("Forwarding event to webhook:", config.WhatsappWebhook)
- payload, err := createPayload(ctx, evt)
- if err != nil {
- return err
- }
-
- for _, url := range config.WhatsappWebhook {
- if err = submitWebhook(payload, url); err != nil {
- return err
- }
- }
-
- logrus.Info("Event forwarded to webhook")
- return nil
-}
-
-func createPayload(ctx context.Context, evt *events.Message) (map[string]any, error) {
- message := utils.BuildEventMessage(evt)
- waReaction := utils.BuildEventReaction(evt)
- forwarded := utils.BuildForwarded(evt)
-
- body := make(map[string]any)
-
- body["sender_id"] = evt.Info.Sender.User
- body["chat_id"] = evt.Info.Chat.User
-
- if from := evt.Info.SourceString(); from != "" {
- body["from"] = from
-
- from_user, from_group := from, ""
- if strings.Contains(from, " in ") {
- from_user = strings.Split(from, " in ")[0]
- from_group = strings.Split(from, " in ")[1]
- }
-
- if strings.HasSuffix(from_user, "@lid") {
- body["from_lid"] = from_user
- lid, err := types.ParseJID(from_user)
- if err != nil {
- logrus.Errorf("Error when parse jid: %v", err)
- } else {
- pn, err := cli.Store.LIDs.GetPNForLID(ctx, lid)
- if err != nil {
- logrus.Errorf("Error when get pn for lid %s: %v", lid.String(), err)
- }
- if !pn.IsEmpty() {
- if from_group != "" {
- body["from"] = fmt.Sprintf("%s in %s", pn.String(), from_group)
- } else {
- body["from"] = pn.String()
- }
- }
- }
- }
- }
- if message.ID != "" {
- tags := regexp.MustCompile(`\B@\w+`).FindAllString(message.Text, -1)
- tagsMap := make(map[string]bool)
- for _, tag := range tags {
- tagsMap[tag] = true
- }
- for tag := range tagsMap {
- lid, err := types.ParseJID(tag[1:] + "@lid")
- if err != nil {
- logrus.Errorf("Error when parse jid: %v", err)
- } else {
- pn, err := cli.Store.LIDs.GetPNForLID(ctx, lid)
- if err != nil {
- logrus.Errorf("Error when get pn for lid %s: %v", lid.String(), err)
- }
- if !pn.IsEmpty() {
- message.Text = strings.Replace(message.Text, tag, fmt.Sprintf("@%s", pn.User), -1)
- }
- }
- }
- body["message"] = message
- }
- if pushname := evt.Info.PushName; pushname != "" {
- body["pushname"] = pushname
- }
- if waReaction.Message != "" {
- body["reaction"] = waReaction
- }
- if evt.IsViewOnce {
- body["view_once"] = evt.IsViewOnce
- }
- if forwarded {
- body["forwarded"] = forwarded
- }
- if timestamp := evt.Info.Timestamp.Format(time.RFC3339); timestamp != "" {
- body["timestamp"] = timestamp
- }
-
- // Handle protocol messages (revoke, etc.)
- if protocolMessage := evt.Message.GetProtocolMessage(); protocolMessage != nil {
- protocolType := protocolMessage.GetType().String()
-
- switch protocolType {
- case "REVOKE":
- body["action"] = "message_revoked"
- if key := protocolMessage.GetKey(); key != nil {
- body["revoked_message_id"] = key.GetID()
- body["revoked_from_me"] = key.GetFromMe()
- if key.GetRemoteJID() != "" {
- body["revoked_chat"] = key.GetRemoteJID()
- }
- }
- case "MESSAGE_EDIT":
- body["action"] = "message_edited"
- if editedMessage := protocolMessage.GetEditedMessage(); editedMessage != nil {
- if editedText := editedMessage.GetExtendedTextMessage(); editedText != nil {
- body["edited_text"] = editedText.GetText()
- } else if editedConv := editedMessage.GetConversation(); editedConv != "" {
- body["edited_text"] = editedConv
- }
- }
- }
- }
-
- if audioMedia := evt.Message.GetAudioMessage(); audioMedia != nil {
- path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, audioMedia)
- if err != nil {
- logrus.Errorf("Failed to download audio from %s: %v", evt.Info.SourceString(), err)
- return nil, pkgError.WebhookError(fmt.Sprintf("Failed to download audio: %v", err))
- }
- body["audio"] = path
- }
-
- if contactMessage := evt.Message.GetContactMessage(); contactMessage != nil {
- body["contact"] = contactMessage
- }
-
- if documentMedia := evt.Message.GetDocumentMessage(); documentMedia != nil {
- path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, documentMedia)
- if err != nil {
- logrus.Errorf("Failed to download document from %s: %v", evt.Info.SourceString(), err)
- return nil, pkgError.WebhookError(fmt.Sprintf("Failed to download document: %v", err))
- }
- body["document"] = path
- }
-
- if imageMedia := evt.Message.GetImageMessage(); imageMedia != nil {
- path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, imageMedia)
- if err != nil {
- logrus.Errorf("Failed to download image from %s: %v", evt.Info.SourceString(), err)
- return nil, pkgError.WebhookError(fmt.Sprintf("Failed to download image: %v", err))
- }
- body["image"] = path
- }
-
- if listMessage := evt.Message.GetListMessage(); listMessage != nil {
- body["list"] = listMessage
- }
-
- if liveLocationMessage := evt.Message.GetLiveLocationMessage(); liveLocationMessage != nil {
- body["live_location"] = liveLocationMessage
- }
-
- if locationMessage := evt.Message.GetLocationMessage(); locationMessage != nil {
- body["location"] = locationMessage
- }
-
- if orderMessage := evt.Message.GetOrderMessage(); orderMessage != nil {
- body["order"] = orderMessage
- }
-
- if stickerMedia := evt.Message.GetStickerMessage(); stickerMedia != nil {
- path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, stickerMedia)
- if err != nil {
- logrus.Errorf("Failed to download sticker from %s: %v", evt.Info.SourceString(), err)
- return nil, pkgError.WebhookError(fmt.Sprintf("Failed to download sticker: %v", err))
- }
- body["sticker"] = path
- }
-
- if videoMedia := evt.Message.GetVideoMessage(); videoMedia != nil {
- path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, videoMedia)
- if err != nil {
- logrus.Errorf("Failed to download video from %s: %v", evt.Info.SourceString(), err)
- return nil, pkgError.WebhookError(fmt.Sprintf("Failed to download video: %v", err))
- }
- body["video"] = path
- }
-
- return body, nil
-}
-
-func submitWebhook(payload map[string]any, url string) error {
+func submitWebhook(_ context.Context, payload map[string]any, url string) error {
client := &http.Client{Timeout: 10 * time.Second}
postBody, err := json.Marshal(payload)
@@ -247,53 +52,3 @@ func submitWebhook(payload map[string]any, url string) error {
return pkgError.WebhookError(fmt.Sprintf("error when submit webhook after %d attempts: %v", attempt, err))
}
-
-// 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)
- payload, err := createDeletePayload(ctx, evt, message)
- if err != nil {
- return err
- }
-
- for _, url := range config.WhatsappWebhook {
- if err = submitWebhook(payload, url); err != nil {
- return err
- }
- }
-
- logrus.Info("Delete event forwarded to webhook")
- return nil
-}
-
-// createDeletePayload creates a webhook payload for delete events
-func createDeletePayload(_ context.Context, evt *events.DeleteForMe, message *domainChatStorage.Message) (map[string]any, error) {
- body := make(map[string]any)
-
- // Basic delete event information
- body["action"] = "message_deleted_for_me"
- body["deleted_message_id"] = evt.MessageID
- body["sender_id"] = evt.SenderJID.User
- body["timestamp"] = time.Now().Format(time.RFC3339)
-
- // Include original message information if available
- if message != nil {
- body["chat_id"] = message.ChatJID
- body["original_content"] = message.Content
- body["original_sender"] = message.Sender
- body["original_timestamp"] = message.Timestamp.Format(time.RFC3339)
- body["was_from_me"] = message.IsFromMe
-
- if message.MediaType != "" {
- body["original_media_type"] = message.MediaType
- body["original_filename"] = message.Filename
- }
- }
-
- // Parse sender JID for proper formatting
- if evt.SenderJID.Server != "" {
- body["from"] = evt.SenderJID.String()
- }
-
- return body, nil
-}
diff --git a/src/usecase/send.go b/src/usecase/send.go
index 7151ccde..782e8745 100644
--- a/src/usecase/send.go
+++ b/src/usecase/send.go
@@ -100,6 +100,8 @@ func (service serviceSend) SendText(ctx context.Context, request domainSend.Mess
// Set disappearing message duration if provided
if request.BaseRequest.Duration != nil && *request.BaseRequest.Duration > 0 {
msg.ExtendedTextMessage.ContextInfo.Expiration = proto.Uint32(uint32(*request.BaseRequest.Duration))
+ } else {
+ msg.ExtendedTextMessage.ContextInfo.Expiration = proto.Uint32(service.getDefaultEphemeralExpiration(request.BaseRequest.Phone))
}
parsedMentions := service.getMentionFromText(ctx, request.Message)
@@ -137,6 +139,8 @@ func (service serviceSend) SendText(ctx context.Context, request domainSend.Mess
// Preserve disappearing message duration if provided
if request.BaseRequest.Duration != nil && *request.BaseRequest.Duration > 0 {
ctxInfo.Expiration = proto.Uint32(uint32(*request.BaseRequest.Duration))
+ } else {
+ ctxInfo.Expiration = proto.Uint32(service.getDefaultEphemeralExpiration(participantJID))
}
// Preserve mentions
@@ -902,3 +906,21 @@ func (service serviceSend) uploadMedia(ctx context.Context, mediaType whatsmeow.
}
return uploaded, err
}
+
+func (service serviceSend) getDefaultEphemeralExpiration(jid string) (expiration uint32) {
+ expiration = 0
+ if jid == "" {
+ return expiration
+ }
+
+ chat, err := service.chatStorageRepo.GetChat(jid)
+ if err != nil {
+ return expiration
+ }
+
+ if chat.EphemeralExpiration != 0 {
+ expiration = chat.EphemeralExpiration
+ }
+
+ return expiration
+}