-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathwebhook-types-example.js
More file actions
611 lines (527 loc) Β· 16.7 KB
/
webhook-types-example.js
File metadata and controls
611 lines (527 loc) Β· 16.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/**
* Comprehensive Webhook Types Example
*
* This example demonstrates how to use the comprehensive webhook types and utilities
* to handle different message types in WhatsApp webhooks with full TypeScript support.
*
* Features demonstrated:
* - Complete webhook payload type safety
* - Message type discovery using discoverMessageType()
* - Handling all supported message types
* - Type-safe access to message properties
* - S3 and Base64 media handling
*/
import express from "express";
import WuzapiClient, {
discoverMessageType,
MessageType,
WebhookEventType,
hasS3Media,
hasBase64Media,
hasBothMedia,
isWebhookEventType,
} from "wuzapi";
const app = express();
app.use(express.json({ limit: "50mb" })); // Large limit for media payloads
const client = new WuzapiClient({
apiUrl: "http://localhost:8080",
token: "your-token-here",
});
/**
* Comprehensive webhook handler with full type safety
*/
app.post("/webhook", async (req, res) => {
try {
const webhookPayload = req.body;
// Validate payload structure
if (
!webhookPayload.token ||
!webhookPayload.type ||
!webhookPayload.event
) {
return res
.status(400)
.json({ error: "Invalid webhook payload structure" });
}
// Type-safe event type validation
if (!isWebhookEventType(webhookPayload.type)) {
console.warn(`Unknown webhook event type: ${webhookPayload.type}`);
return res
.status(200)
.json({ success: true, message: "Unknown event type" });
}
// Security: Verify token
if (webhookPayload.token !== "your-expected-token") {
return res.status(401).json({ error: "Invalid webhook token" });
}
console.log(`\nπ¨ Received webhook event: ${webhookPayload.type}`);
// Handle media if present
if (hasS3Media(webhookPayload)) {
console.log("π S3 Media detected:", {
url: webhookPayload.s3.url,
fileName: webhookPayload.s3.fileName,
mimeType: webhookPayload.s3.mimeType,
size: webhookPayload.s3.size,
});
}
if (hasBase64Media(webhookPayload)) {
console.log("π Base64 Media detected:", {
mimeType: webhookPayload.mimeType,
fileName: webhookPayload.fileName,
size: webhookPayload.base64?.length || 0,
});
}
if (hasBothMedia(webhookPayload)) {
console.log(
"π Both S3 and Base64 media present - using S3 for efficiency"
);
}
const { event } = webhookPayload;
// Handle different webhook event types
switch (webhookPayload.type) {
case WebhookEventType.MESSAGE:
await handleMessageEvent(event, webhookPayload);
break;
case WebhookEventType.READ_RECEIPT:
await handleReadReceiptEvent(event);
break;
case WebhookEventType.QR:
await handleQREvent(event, webhookPayload);
break;
case WebhookEventType.CONNECTED:
await handleConnectedEvent(event);
break;
case WebhookEventType.HISTORY_SYNC:
await handleHistorySyncEvent(event);
break;
default:
console.log(`π Unhandled event type: ${webhookPayload.type}`);
console.log("Event data:", JSON.stringify(event, null, 2));
}
res.json({ success: true });
} catch (error) {
console.error("β Webhook error:", error);
res.status(500).json({ error: error.message });
}
});
/**
* Handle Message webhook events with comprehensive message type support
*/
async function handleMessageEvent(event, webhookPayload) {
if (!event.Message || !event.Info) {
console.warn("β οΈ Incomplete message event");
return;
}
const messageInfo = event.Info;
const from = messageInfo.Sender.replace("@s.whatsapp.net", "");
const isFromMe = messageInfo.IsFromMe;
const isGroup = messageInfo.IsGroup;
const chat = messageInfo.Chat;
console.log(`π¬ Message from: ${from} (${isFromMe ? "me" : "contact"})`);
console.log(`π Chat: ${isGroup ? "Group" : "Private"} - ${chat}`);
console.log(`β° Timestamp: ${messageInfo.Timestamp}`);
// Discover message type using our utility
const messageType = discoverMessageType(event.Message);
console.log(`π Message type discovered: ${messageType}`);
// Handle different message types with full type safety
switch (messageType) {
case MessageType.EXTENDED_TEXT:
await handleTextMessage(event.Message.extendedTextMessage, from);
break;
case MessageType.IMAGE:
await handleImageMessage(
event.Message.imageMessage,
from,
webhookPayload
);
break;
case MessageType.VIDEO:
await handleVideoMessage(
event.Message.videoMessage,
from,
webhookPayload
);
break;
case MessageType.AUDIO:
await handleAudioMessage(
event.Message.audioMessage,
from,
webhookPayload
);
break;
case MessageType.DOCUMENT:
await handleDocumentMessage(
event.Message.documentMessage,
from,
webhookPayload
);
break;
case MessageType.CONTACT:
await handleContactMessage(event.Message.contactMessage, from);
break;
case MessageType.LOCATION:
await handleLocationMessage(event.Message.locationMessage, from);
break;
case MessageType.POLL_CREATION:
await handlePollMessage(event.Message.pollCreationMessageV3, from);
break;
case MessageType.STICKER:
await handleStickerMessage(
event.Message.stickerMessage,
from,
webhookPayload
);
break;
case MessageType.REACTION:
await handleReactionMessage(event.Message.reactionMessage, from);
break;
case MessageType.EDITED:
await handleEditedMessage(event.Message.editedMessage, from);
break;
case MessageType.PROTOCOL:
await handleProtocolMessage(event.Message.protocolMessage, from);
break;
case MessageType.DEVICE_SENT:
console.log("π± Device sent message - analyzing nested message...");
const nestedMessageType = discoverMessageType(
event.Message.deviceSentMessage.message
);
console.log(`π Nested message type: ${nestedMessageType}`);
// Could recursively handle the nested message here
break;
case MessageType.UNKNOWN:
default:
console.log("β Unknown message type");
console.log("Raw message:", JSON.stringify(event.Message, null, 2));
}
}
/**
* Handle text messages
*/
async function handleTextMessage(textMessage, from) {
console.log(`π Text Message: "${textMessage.text}"`);
// Check for context info (replies, disappearing messages, etc.)
if (textMessage.contextInfo) {
console.log("π Context info present:", {
expiration: textMessage.contextInfo.expiration,
isForwarded: textMessage.contextInfo.isForwarded,
});
}
// Auto-reply example
const text = textMessage.text.toLowerCase();
if (text.includes("hello") || text.includes("hi")) {
await client.chat.sendText({
Phone: from,
Body: "Hello! π How can I help you today?",
});
} else if (text.includes("help")) {
await client.chat.sendText({
Phone: from,
Body: "I can help you with:\nβ’ Text messages\nβ’ Images & media\nβ’ Location sharing\nβ’ Contacts\nβ’ Polls",
});
}
}
/**
* Handle image messages with media support
*/
async function handleImageMessage(imageMessage, from, webhookPayload) {
console.log(`πΌοΈ Image Message:`, {
mimetype: imageMessage.mimetype,
size: imageMessage.fileLength,
dimensions: `${imageMessage.width}x${imageMessage.height}`,
hasThumb: !!imageMessage.JPEGThumbnail,
});
// Handle S3 or base64 media
let mediaUrl = null;
if (hasS3Media(webhookPayload)) {
mediaUrl = webhookPayload.s3.url;
console.log("π Image available at S3:", mediaUrl);
} else if (hasBase64Media(webhookPayload)) {
console.log(
"π Image available as base64 (length:",
webhookPayload.base64?.length,
")"
);
}
// Send a response
await client.chat.sendText({
Phone: from,
Body: "πΈ Nice photo! I received your image successfully.",
});
}
/**
* Handle video messages
*/
async function handleVideoMessage(videoMessage, from, webhookPayload) {
const isGif = videoMessage.gifPlayback;
const mediaType = isGif ? "GIF" : "video";
console.log(`π₯ ${mediaType.toUpperCase()} Message:`, {
mimetype: videoMessage.mimetype,
size: videoMessage.fileLength,
duration: `${videoMessage.seconds}s`,
dimensions: `${videoMessage.width}x${videoMessage.height}`,
caption: videoMessage.caption || "No caption",
isGif: isGif,
gifAttribution: videoMessage.gifAttribution,
});
const attributionText =
videoMessage.gifAttribution === 1
? " from Giphy"
: videoMessage.gifAttribution === 2
? " from Tenor"
: "";
await client.chat.sendText({
Phone: from,
Body: `π¬ Thanks for the ${mediaType}${attributionText}! Duration: ${videoMessage.seconds} seconds`,
});
}
/**
* Handle audio messages (including voice messages)
*/
async function handleAudioMessage(audioMessage, from, webhookPayload) {
const isVoiceMessage = audioMessage.ptt || audioMessage.PTT;
console.log(`π΅ ${isVoiceMessage ? "Voice" : "Audio"} Message:`, {
mimetype: audioMessage.mimetype,
size: audioMessage.fileLength,
duration: `${audioMessage.seconds}s`,
hasWaveform: !!audioMessage.waveform,
});
await client.chat.sendText({
Phone: from,
Body: isVoiceMessage
? "π€ Voice message received!"
: "π΅ Audio message received!",
});
}
/**
* Handle document messages
*/
async function handleDocumentMessage(documentMessage, from, webhookPayload) {
console.log(`π Document Message:`, {
fileName: documentMessage.fileName,
title: documentMessage.title,
mimetype: documentMessage.mimetype,
size: documentMessage.fileLength,
pages: documentMessage.pageCount || "Unknown",
});
await client.chat.sendText({
Phone: from,
Body: `π Document received: "${documentMessage.fileName}"${
documentMessage.pageCount ? ` (${documentMessage.pageCount} pages)` : ""
}`,
});
}
/**
* Handle contact messages
*/
async function handleContactMessage(contactMessage, from) {
console.log(`π€ Contact Message:`, {
displayName: contactMessage.displayName,
vcard: contactMessage.vcard.substring(0, 100) + "...",
});
await client.chat.sendText({
Phone: from,
Body: `π Contact received: ${contactMessage.displayName}`,
});
}
/**
* Handle location messages
*/
async function handleLocationMessage(locationMessage, from) {
console.log(`π Location Message:`, {
latitude: locationMessage.degreesLatitude,
longitude: locationMessage.degreesLongitude,
hasThumb: !!locationMessage.JPEGThumbnail,
});
// Create Google Maps link
const mapsLink = `https://maps.google.com/?q=${locationMessage.degreesLatitude},${locationMessage.degreesLongitude}`;
await client.chat.sendText({
Phone: from,
Body: `π Location received!\nπ View on Maps: ${mapsLink}`,
});
}
/**
* Handle poll creation messages
*/
async function handlePollMessage(pollMessage, from) {
console.log(`π³οΈ Poll Message:`, {
question: pollMessage.name,
optionsCount: pollMessage.options.length,
multiSelect: pollMessage.selectableOptionsCount > 0,
});
const options = pollMessage.options
.map((opt) => `β’ ${opt.optionName}`)
.join("\n");
await client.chat.sendText({
Phone: from,
Body: `π³οΈ Poll created: "${pollMessage.name}"\nOptions:\n${options}`,
});
}
/**
* Handle edited messages
*/
async function handleEditedMessage(editedMessage, from) {
console.log(`βοΈ Message Edited:`, {
editedMessageID: editedMessage.editedMessageID,
timestamp: editedMessage.timestampMS,
});
await client.chat.sendText({
Phone: from,
Body: "βοΈ I noticed you edited a message!",
});
}
/**
* Handle sticker messages
*/
async function handleStickerMessage(stickerMessage, from, webhookPayload) {
console.log(`π Sticker Message:`, {
mimetype: stickerMessage.mimetype,
size: stickerMessage.fileLength,
dimensions: `${stickerMessage.width}x${stickerMessage.height}`,
isAnimated: stickerMessage.isAnimated,
isLottie: stickerMessage.isLottie,
isAiSticker: stickerMessage.isAiSticker,
isAvatar: stickerMessage.isAvatar,
});
// Handle S3 or base64 media
let mediaUrl = null;
if (hasS3Media(webhookPayload)) {
mediaUrl = webhookPayload.s3.url;
console.log("π Sticker available at S3:", mediaUrl);
} else if (hasBase64Media(webhookPayload)) {
console.log("π Sticker available as base64");
}
const stickerType = stickerMessage.isAnimated ? "animated" : "static";
const stickerSource = stickerMessage.isAiSticker ? " (AI-generated)" : "";
await client.chat.sendText({
Phone: from,
Body: `π Nice ${stickerType} sticker${stickerSource}!`,
});
}
/**
* Handle reaction messages
*/
async function handleReactionMessage(reactionMessage, from) {
console.log(`β€οΈ Reaction Message:`, {
emoji: reactionMessage.text,
targetMessageId: reactionMessage.key.ID,
fromOriginalSender: reactionMessage.key.fromMe,
timestamp: reactionMessage.senderTimestampMS,
});
await client.chat.sendText({
Phone: from,
Body: `Thanks for the ${reactionMessage.text || "reaction"}! π`,
});
}
/**
* Handle protocol messages (system messages)
*/
async function handleProtocolMessage(protocolMessage, from) {
console.log(`π§ Protocol Message:`, {
type: protocolMessage.type,
hasHistorySync: !!protocolMessage.historySyncNotification,
hasEditedMessage: !!protocolMessage.editedMessage,
});
if (protocolMessage.historySyncNotification) {
console.log("π History sync notification received");
}
if (protocolMessage.editedMessage) {
console.log("βοΈ Message edit detected in protocol message");
// The edited message content is nested in protocolMessage.editedMessage
const nestedMessageType = discoverMessageType(
protocolMessage.editedMessage
);
console.log(`π Edited message type: ${nestedMessageType}`);
await client.chat.sendText({
Phone: from,
Body: "βοΈ I noticed you edited a message!",
});
}
}
/**
* Handle ReadReceipt events
*/
async function handleReadReceiptEvent(event) {
console.log(`π Read Receipt:`, {
sender: event.Sender,
chat: event.Chat,
type: event.Type,
messageCount: event.MessageIDs?.length || 0,
timestamp: event.Timestamp,
});
}
/**
* Handle QR code events
*/
async function handleQREvent(event, webhookPayload) {
console.log("π± QR Code event received");
if (webhookPayload.qrCodeBase64) {
console.log("π± QR Code available as base64 data URL");
// You could save this to a file or display it
// const qrCode = webhookPayload.qrCodeBase64;
// fs.writeFileSync('qr.png', qrCode.replace('data:image/png;base64,', ''), 'base64');
}
}
/**
* Handle Connected events
*/
async function handleConnectedEvent(event) {
console.log("β
WhatsApp connected successfully!");
// Send a welcome message to yourself or admin
// await client.chat.sendText({
// Phone: "your-admin-number",
// Body: "π€ Bot is now connected and ready to receive messages!",
// });
}
/**
* Handle HistorySync events
*/
async function handleHistorySyncEvent(event) {
console.log(`π History Sync event:`, {
syncType: event.Data?.syncType,
chunkOrder: event.Data?.chunkOrder,
progress: event.Data?.progress,
hasConversations: !!event.Data?.conversations,
hasStatusMessages: !!event.Data?.statusV3Messages,
hasParticipants: !!event.Data?.pastParticipants,
hasStickers: !!event.Data?.recentStickers,
});
}
/**
* Start the webhook server
*/
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`π Webhook server running on port ${PORT}`);
console.log(`π‘ Webhook URL: http://localhost:${PORT}/webhook`);
console.log("\nπ§ Setup your WuzAPI webhook:");
console.log(
` webhook.setWebhook("http://localhost:${PORT}/webhook", ["Message", "ReadReceipt", "Connected", "QR"])`
);
});
/**
* Setup WuzAPI connection and webhook (uncomment to auto-setup)
*/
async function setupWuzapi() {
try {
// Connect to WhatsApp
await client.session.connect({
Subscribe: ["Message", "ReadReceipt", "Connected", "QR", "HistorySync"],
Immediate: false,
});
// Set webhook
await client.webhook.setWebhook(`http://localhost:${PORT}/webhook`, [
"Message",
"ReadReceipt",
"Connected",
"QR",
"HistorySync",
]);
console.log("β
WuzAPI setup complete!");
} catch (error) {
console.error("β Setup error:", error);
}
}
// Uncomment to auto-setup WuzAPI
// setupWuzapi();
export default app;