-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathwebhook-forwarder.ts
More file actions
68 lines (55 loc) · 1.7 KB
/
Copy pathwebhook-forwarder.ts
File metadata and controls
68 lines (55 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* Webhook Forwarder Example
*
* Forwards all WhatsApp messages to a webhook URL.
* Useful for integrating WhatsApp with other services (Zapier, n8n, etc.)
*
* Usage:
* WEBHOOK_URL=https://webhook.site/your-id npx tsx examples/webhook-forwarder.ts
*
* All incoming messages will be POSTed to the webhook URL as JSON.
*/
import { WaSP } from '../src';
const WEBHOOK_URL = process.env.WEBHOOK_URL || 'https://webhook.site/test';
async function main() {
const wasp = new WaSP();
console.log(`Webhook Forwarder - forwarding to: ${WEBHOOK_URL}\n`);
// Create session
await wasp.createSession('webhook-forwarder', 'BAILEYS');
// QR code
wasp.on('SESSION_QR', (event) => {
console.log('Scan QR code:\n', event.data.qr);
});
// Connected
wasp.on('SESSION_CONNECTED', (event) => {
console.log('✅ Connected as:', event.data.phone);
});
// Forward all messages to webhook
wasp.on('MESSAGE_RECEIVED', async (event) => {
const msg = event.data;
const payload = {
id: msg.id,
from: msg.from,
content: msg.content,
type: msg.type,
timestamp: msg.timestamp,
isGroup: msg.isGroup,
};
console.log(`📨 Forwarding message from ${msg.from} to webhook...`);
try {
const response = await fetch(WEBHOOK_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
if (response.ok) {
console.log(`✅ Forwarded successfully (${response.status})`);
} else {
console.error(`❌ Webhook error: ${response.status}`);
}
} catch (error) {
console.error('❌ Failed to forward:', error);
}
});
}
main().catch(console.error);