@hdriel/whatsapp-socket 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +525 -11
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,23 +1,537 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @hdriel/whatsapp-socket
|
|
2
2
|
|
|
3
|
+
A TypeScript/JavaScript wrapper library for WhatsApp Web Socket communication, built on top of [@fadzzzslebew/baileys](https://github.com/fadzzzslebew/baileys). This package provides a simplified, high-level API for interacting with WhatsApp Web with support for multi-device connections.
|
|
3
4
|
|
|
4
|
-
##
|
|
5
|
+
## ⚠️ Disclaimer
|
|
5
6
|
|
|
6
|
-
This
|
|
7
|
+
This project is not affiliated, associated, authorized, endorsed by, or in any way officially connected with WhatsApp or any of its subsidiaries or affiliates. The official WhatsApp website can be found at [https://whatsapp.com](https://whatsapp.com). "WhatsApp" as well as related names, marks, emblems and images are registered trademarks of their respective owners.
|
|
7
8
|
|
|
8
|
-
|
|
9
|
+
**Use at your own risk.** WhatsApp does not allow bots or unofficial clients on their platform. Using this library may result in your WhatsApp account being banned.
|
|
9
10
|
|
|
10
|
-
|
|
11
|
+
## Features
|
|
11
12
|
|
|
12
|
-
|
|
13
|
+
- 🚀 WebSocket-based communication with WhatsApp Web (powered by Baileys)
|
|
14
|
+
- 📱 QR code authentication or pairing code authentication
|
|
15
|
+
- 💬 Send text messages
|
|
16
|
+
- 🔘 Send interactive button messages (URL, call, copy, email, reminder)
|
|
17
|
+
- 📝 Send reply buttons messages
|
|
18
|
+
- 🖼️ Send images with captions (up to 50MB)
|
|
19
|
+
- 🎥 Send videos (up to 100MB)
|
|
20
|
+
- 🎵 Send audio messages (up to 10MB)
|
|
21
|
+
- 📄 Send documents/files (up to 500MB)
|
|
22
|
+
- 🎨 Send stickers (WebP format, up to 5MB)
|
|
23
|
+
- 💾 Session persistence (file-based or MongoDB)
|
|
24
|
+
- 📝 Full TypeScript support
|
|
13
25
|
|
|
14
|
-
|
|
15
|
-
- [@adiwajshing/baileys-md](https://pokoke-01.github.io/owh/index.html)
|
|
16
|
-
- [Automating WhatsApp](https://medium.com/@elvisbrazil/automating-whatsapp-with-node-js-and-baileys-send-receive-and-broadcast-messages-with-code-0656c40bd928)
|
|
17
|
-
- [baileys-pro](https://www.npmjs.com/package/baileys-pro?activeTab=readme)
|
|
26
|
+
## ⚠️ Important: Server Requirements
|
|
18
27
|
|
|
28
|
+
**This service MUST run on a persistent server (e.g., VPS, dedicated server, or container) and NOT on serverless platforms like AWS Lambda, Google Cloud Functions, or Vercel Serverless Functions.**
|
|
29
|
+
|
|
30
|
+
The WhatsApp socket connection requires a persistent, stateful connection that stays alive and maintains session state. Serverless functions:
|
|
31
|
+
- Have short execution timeouts (typically 15-900 seconds)
|
|
32
|
+
- Cannot maintain long-lived WebSocket connections
|
|
33
|
+
- Restart frequently, losing connection state
|
|
34
|
+
- Will cause multiple connection attempts, which WhatsApp may flag as suspicious behavior
|
|
35
|
+
|
|
36
|
+
**Recommended hosting options:**
|
|
37
|
+
- VPS (DigitalOcean, Linode, Vultr)
|
|
38
|
+
- Dedicated servers
|
|
39
|
+
- Docker containers on persistent infrastructure
|
|
40
|
+
- AWS EC2/ECS, Google Compute Engine, or Azure VM (not Lambda/Cloud Functions)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
## Installation
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
npm install @hdriel/whatsapp-socket
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
or
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
yarn add @hdriel/whatsapp-socket
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
For MongoDB session storage (optional):
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
npm install mongodb
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Quick Start
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
import { WhatsappSocket } from '@hdriel/whatsapp-socket';
|
|
65
|
+
import path from 'path';
|
|
66
|
+
|
|
67
|
+
const client = new WhatsappSocket({
|
|
68
|
+
// File-based session storage (recommended for development)
|
|
69
|
+
fileAuthStateDirectoryPath: path.resolve(__dirname, './authState/my-profile'),
|
|
70
|
+
|
|
71
|
+
// Or use MongoDB for production (optional)
|
|
72
|
+
// mongoURL: 'mongodb://localhost:27017/whatsapp-sessions',
|
|
73
|
+
|
|
74
|
+
// logger, // Custom logger (npm stack-trace-logger) instance (optional)
|
|
75
|
+
|
|
76
|
+
// Print QR code in terminal
|
|
77
|
+
printQRInTerminal: true,
|
|
78
|
+
|
|
79
|
+
// Enable debug mode
|
|
80
|
+
debug: true,
|
|
81
|
+
|
|
82
|
+
// Connection status callback
|
|
83
|
+
onConnectionStatusChange: (status: 'open' | 'close' | 'connecting') => {
|
|
84
|
+
console.log('Connection status:', status);
|
|
85
|
+
},
|
|
86
|
+
|
|
87
|
+
// QR code callback
|
|
88
|
+
onQR: async (qr, qrCode) => {
|
|
89
|
+
console.log('QR Code received');
|
|
90
|
+
// Convert QR string to image
|
|
91
|
+
const qrImage = await WhatsappSocket.qrToImage(qr);
|
|
92
|
+
// Display qrImage to user for scanning
|
|
93
|
+
},
|
|
94
|
+
|
|
95
|
+
// Connection opened
|
|
96
|
+
onOpen: async () => {
|
|
97
|
+
console.log('WhatsApp connection opened!');
|
|
98
|
+
},
|
|
99
|
+
|
|
100
|
+
// Connection closed
|
|
101
|
+
onClose: async () => {
|
|
102
|
+
console.log('WhatsApp connection closed');
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
// Start the connection
|
|
107
|
+
await client.startConnection();
|
|
108
|
+
|
|
109
|
+
// Check if connected
|
|
110
|
+
if (client.isConnected()) {
|
|
111
|
+
// Send a text message
|
|
112
|
+
await client.sendTextMessage('050-000-0000', 'Hello World!');
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## API Reference
|
|
117
|
+
|
|
118
|
+
### Connection Management
|
|
119
|
+
|
|
120
|
+
#### `startConnection()`
|
|
121
|
+
Start the WhatsApp connection. This will trigger QR code generation if not authenticated.
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
await client.startConnection();
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
#### `closeConnection()`
|
|
128
|
+
Close the WhatsApp connection.
|
|
129
|
+
|
|
130
|
+
```typescript
|
|
131
|
+
await client.closeConnection();
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
#### `resetConnection(options?)`
|
|
135
|
+
Reset the connection and generate a new QR code or use phone pairing.
|
|
136
|
+
|
|
137
|
+
```typescript
|
|
138
|
+
// Generate new QR code
|
|
139
|
+
await client.resetConnection();
|
|
140
|
+
|
|
141
|
+
// Or use phone number pairing
|
|
142
|
+
await client.resetConnection({ pairingPhone: '050-000-0000' });
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
#### `isConnected()`
|
|
146
|
+
Check if the client is currently connected.
|
|
147
|
+
|
|
148
|
+
```typescript
|
|
149
|
+
const connected = client.isConnected();
|
|
150
|
+
console.log('Connected:', connected);
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### Messaging Methods
|
|
154
|
+
|
|
155
|
+
#### `sendTextMessage(jid, text)`
|
|
156
|
+
Send a plain text message.
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
await client.sendTextMessage(
|
|
160
|
+
'0500000000',// or 050-000-0000 converted to 972500000000 , or define DEFAULT_COUNTRY to change 972 to your country
|
|
161
|
+
'Hello, this is a test message!'
|
|
162
|
+
);
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
#### `sendButtonsMessage(jid, options)`
|
|
166
|
+
Send an interactive message with action buttons.
|
|
167
|
+
|
|
168
|
+
```typescript
|
|
169
|
+
await client.sendButtonsMessage('1234567890@s.whatsapp.net', {
|
|
170
|
+
title: 'Welcome to our service!',
|
|
171
|
+
subtitle: 'Please choose an action below',
|
|
172
|
+
buttons: [
|
|
173
|
+
{ label: 'Visit Website', url: 'https://example.com' },
|
|
174
|
+
{ label: 'Call Us', tel: '050-123-4567' },
|
|
175
|
+
{ label: 'Copy Code', copy: 'PROMO2024' },
|
|
176
|
+
// { label: 'Email Us', email: 'support@example.com' }, // not supported
|
|
177
|
+
// not supported
|
|
178
|
+
// {
|
|
179
|
+
// label: 'Set Reminder',
|
|
180
|
+
// reminderName: 'Follow up call',
|
|
181
|
+
// reminderOn: '20m' // or use reminderDate
|
|
182
|
+
// }
|
|
183
|
+
]
|
|
184
|
+
});
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
#### `sendReplyButtonsMessage(jid, options)`
|
|
188
|
+
Send a message with reply buttons (quick reply options).
|
|
189
|
+
|
|
190
|
+
```typescript
|
|
191
|
+
await client.sendReplyButtonsMessage('1234567890@s.whatsapp.net', {
|
|
192
|
+
title: 'Choose your preferred time',
|
|
193
|
+
subtitle: 'Click one of the options below',
|
|
194
|
+
buttons: [
|
|
195
|
+
'Morning (9-12)',
|
|
196
|
+
'Afternoon (12-5)',
|
|
197
|
+
'Evening (5-9)'
|
|
198
|
+
]
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
#### `sendImageMessage(jid, buffer, options?)`
|
|
203
|
+
Send an image message.
|
|
204
|
+
|
|
205
|
+
```typescript
|
|
206
|
+
import fs from 'fs';
|
|
207
|
+
|
|
208
|
+
const imageBuffer = fs.readFileSync('./photo.jpg');
|
|
209
|
+
await client.sendImageMessage('050-000-0000', imageBuffer, {
|
|
210
|
+
caption: 'Check out this photo!',
|
|
211
|
+
filename: 'photo.jpg'
|
|
212
|
+
});
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
#### `sendVideoMessage(jid, buffer, caption?)`
|
|
216
|
+
Send a video message.
|
|
217
|
+
|
|
218
|
+
```typescript
|
|
219
|
+
const videoBuffer = fs.readFileSync('./video.mp4');
|
|
220
|
+
await client.sendVideoMessage(
|
|
221
|
+
'050-000-0000',
|
|
222
|
+
videoBuffer,
|
|
223
|
+
{ caption: 'Amazing video!' }
|
|
224
|
+
);
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
#### `sendAudioMessage(jid, buffer, options?)`
|
|
228
|
+
Send an audio message.
|
|
229
|
+
|
|
230
|
+
```typescript
|
|
231
|
+
const audioBuffer = fs.readFileSync('./audio.mp3');
|
|
232
|
+
await client.sendAudioMessage('050-000-0000', audioBuffer, {
|
|
233
|
+
filename: 'audio.mp3',
|
|
234
|
+
mimetype: 'audio/mpeg'
|
|
235
|
+
});
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
#### `sendFileMessage(jid, buffer, options?)`
|
|
239
|
+
Send a document/file message.
|
|
240
|
+
|
|
241
|
+
```typescript
|
|
242
|
+
const fileBuffer = fs.readFileSync('./document.pdf');
|
|
243
|
+
await client.sendFileMessage('050-000-0000', fileBuffer, {
|
|
244
|
+
filename: 'document.pdf',
|
|
245
|
+
mimetype: 'application/pdf',
|
|
246
|
+
caption: 'Here is the requested document'
|
|
247
|
+
});
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
#### `sendStickerMessage(jid, buffer)`
|
|
251
|
+
Send a sticker message (must be WebP format).
|
|
252
|
+
|
|
253
|
+
```typescript
|
|
254
|
+
const stickerBuffer = fs.readFileSync('./sticker.webp');
|
|
255
|
+
await client.sendStickerMessage('050-000-0000', stickerBuffer);
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
### Utility Methods
|
|
259
|
+
|
|
260
|
+
#### `WhatsappSocket.qrToImage(qr)`
|
|
261
|
+
Convert QR code string to base64 image.
|
|
262
|
+
|
|
263
|
+
```typescript
|
|
264
|
+
const qrImage = await WhatsappSocket.qrToImage(qrString);
|
|
265
|
+
console.log(qrImage); // data:image/png;base64,...
|
|
266
|
+
// In client side <img src={qrImage} />
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
#### `WhatsappSocket.randomPairingCode(pattern)`
|
|
270
|
+
Generate a random pairing code.
|
|
271
|
+
|
|
272
|
+
```typescript
|
|
273
|
+
// Generate 6-digit numeric code
|
|
274
|
+
const code = WhatsappSocket.randomPairingCode('[0-9]');
|
|
275
|
+
|
|
276
|
+
// Generate alphanumeric code
|
|
277
|
+
const alphaCode = WhatsappSocket.randomPairingCode('[a-z0-9]');
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
## Phone Number Format
|
|
281
|
+
|
|
282
|
+
Support normal format and converters to expected format for example:
|
|
283
|
+
- Individual chats: 050-111-2222 || 0501112222 => `972501112222@s.whatsapp.net`
|
|
284
|
+
- Group chats: Not handle yet group chats implementations
|
|
285
|
+
|
|
286
|
+
Note: WhatsApp uses JID (Jabber ID) format for phone numbers
|
|
287
|
+
- Individual chats: `{phone_number}@s.whatsapp.net`
|
|
288
|
+
- Group chats: `{group_id}@g.us`
|
|
289
|
+
|
|
290
|
+
# Default Country Code
|
|
291
|
+
|
|
292
|
+
Changing the default country code it using on the static field like:
|
|
293
|
+
```typescript
|
|
294
|
+
WhatsappSocket.DEFAULT_COUNTRY_CODE = '510';
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
## Complete Express.js Example
|
|
298
|
+
|
|
299
|
+
Here's a complete example of an Express.js server with Socket.IO integration:
|
|
300
|
+
|
|
301
|
+
```typescript
|
|
302
|
+
import express from 'express';
|
|
303
|
+
import http from 'http';
|
|
304
|
+
import { Server as SocketIO } from 'socket.io';
|
|
305
|
+
import { WhatsappSocket } from '@hdriel/whatsapp-socket';
|
|
306
|
+
import path from 'path';
|
|
307
|
+
|
|
308
|
+
const app = express();
|
|
309
|
+
const server = http.createServer(app);
|
|
310
|
+
const io = new SocketIO(server);
|
|
311
|
+
|
|
312
|
+
app.use(express.json());
|
|
313
|
+
|
|
314
|
+
// Initialize WhatsApp client
|
|
315
|
+
const client = new WhatsappSocket({
|
|
316
|
+
fileAuthStateDirectoryPath: path.resolve(__dirname, './authState'),
|
|
317
|
+
printQRInTerminal: true,
|
|
318
|
+
debug: true,
|
|
319
|
+
onConnectionStatusChange: (status) => {
|
|
320
|
+
io.emit('connection-status', status);
|
|
321
|
+
},
|
|
322
|
+
onQR: async (qr, qrCode) => {
|
|
323
|
+
const qrImage = await WhatsappSocket.qrToImage(qr);
|
|
324
|
+
io.emit('qr', { qrImage, qrCode });
|
|
325
|
+
},
|
|
326
|
+
onOpen: () => io.emit('qr-connected'),
|
|
327
|
+
onClose: () => io.emit('qr-disconnected')
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
// Start connection on server start
|
|
331
|
+
client.startConnection();
|
|
332
|
+
|
|
333
|
+
// Socket.IO connection
|
|
334
|
+
io.on('connection', (socket) => {
|
|
335
|
+
console.log('Client connected');
|
|
336
|
+
socket.emit('connected');
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
// API Routes
|
|
340
|
+
app.post('/api/connect', async (req, res) => {
|
|
341
|
+
await client.startConnection();
|
|
342
|
+
res.json({ message: 'OK' });
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
app.post('/api/disconnect', async (req, res) => {
|
|
346
|
+
await client.closeConnection();
|
|
347
|
+
res.json({ message: 'OK' });
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
app.post('/api/generate-qr', async (req, res) => {
|
|
351
|
+
const { phone } = req.body;
|
|
352
|
+
await client.resetConnection({ pairingPhone: phone });
|
|
353
|
+
res.json({ message: 'OK' });
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
app.post('/api/send-message', async (req, res) => {
|
|
357
|
+
const { phoneTo, message } = req.body;
|
|
358
|
+
await client.sendTextMessage(phoneTo, message);
|
|
359
|
+
res.json({ message: 'OK' });
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
app.post('/api/send-buttons', async (req, res) => {
|
|
363
|
+
const { phoneTo, title, subtitle, buttons } = req.body;
|
|
364
|
+
await client.sendButtonsMessage(phoneTo, { title, subtitle, buttons });
|
|
365
|
+
res.json({ message: 'OK' });
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
server.listen(3000, () => {
|
|
369
|
+
console.log('Server running on port 3000');
|
|
370
|
+
});
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
## File Upload Example with Multer
|
|
374
|
+
|
|
375
|
+
```typescript
|
|
376
|
+
import multer from 'multer';
|
|
377
|
+
import bytes from 'bytes';
|
|
378
|
+
|
|
379
|
+
const storage = multer.memoryStorage();
|
|
380
|
+
|
|
381
|
+
const uploadImage = multer({
|
|
382
|
+
storage,
|
|
383
|
+
limits: { fileSize: bytes('50MB') },
|
|
384
|
+
fileFilter: (req, file, cb) => {
|
|
385
|
+
if (file.mimetype.startsWith('image/')) {
|
|
386
|
+
cb(null, true);
|
|
387
|
+
} else {
|
|
388
|
+
cb(new Error('Only image files are allowed'));
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
app.post('/api/upload-image', uploadImage.single('image'), async (req, res) => {
|
|
394
|
+
const imageFile = req.file;
|
|
395
|
+
if (!imageFile) {
|
|
396
|
+
return res.status(400).json({ message: 'No image file provided' });
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
const { phoneTo, caption } = req.body;
|
|
400
|
+
await client.sendImageMessage(phoneTo, imageFile.buffer, {
|
|
401
|
+
caption,
|
|
402
|
+
filename: imageFile.originalname
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
res.json({ message: 'OK' });
|
|
406
|
+
});
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
## Session Storage
|
|
410
|
+
|
|
411
|
+
### File-Based Storage (Recommended for Development)
|
|
412
|
+
|
|
413
|
+
```typescript
|
|
414
|
+
const client = new WhatsappSocket({
|
|
415
|
+
fileAuthStateDirectoryPath: path.resolve(__dirname, './authState/my-profile')
|
|
416
|
+
});
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
Session files will be stored in the specified directory and automatically loaded on subsequent connections.
|
|
420
|
+
|
|
421
|
+
### MongoDB Storage (Recommended for Production)
|
|
422
|
+
|
|
423
|
+
```typescript
|
|
424
|
+
const client = new WhatsappSocket({
|
|
425
|
+
mongoURL: 'mongodb://localhost:27017/whatsapp-sessions'
|
|
426
|
+
});
|
|
427
|
+
```
|
|
428
|
+
|
|
429
|
+
For MongoDB storage, install the peer dependency:
|
|
430
|
+
```bash
|
|
431
|
+
npm install mongodb
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
## Best Practices
|
|
435
|
+
|
|
436
|
+
1. **Session Management**: Always store session data securely. For production, use MongoDB or encrypted file storage.
|
|
437
|
+
|
|
438
|
+
2. **Rate Limiting**: Implement rate limiting to avoid sending too many messages in a short period, which could result in being banned.
|
|
439
|
+
|
|
440
|
+
3. **Error Handling**: Always wrap API calls in try-catch blocks:
|
|
441
|
+
```typescript
|
|
442
|
+
try {
|
|
443
|
+
await client.sendTextMessage(jid, message);
|
|
444
|
+
} catch (error) {
|
|
445
|
+
console.error('Failed to send message:', error);
|
|
446
|
+
}
|
|
447
|
+
```
|
|
448
|
+
4. **Testing**: Test with a secondary phone number before using with your primary account
|
|
449
|
+
|
|
450
|
+
## TypeScript Support
|
|
451
|
+
|
|
452
|
+
The library is written in TypeScript and includes complete type definitions:
|
|
453
|
+
|
|
454
|
+
```typescript
|
|
455
|
+
import { WhatsappSocket } from '@hdriel/whatsapp-socket';
|
|
456
|
+
|
|
457
|
+
// All methods and options are fully typed
|
|
458
|
+
const client: WhatsappSocket = new WhatsappSocket({
|
|
459
|
+
fileAuthStateDirectoryPath: './authState',
|
|
460
|
+
debug: true
|
|
461
|
+
});
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
## Troubleshooting
|
|
465
|
+
|
|
466
|
+
### QR Code Not Generating
|
|
467
|
+
- Ensure `printQRInTerminal` is set to `true` or handle the `onQR` callback
|
|
468
|
+
- Check that the session directory has write permissions
|
|
469
|
+
- Try calling `resetConnection()` to generate a new QR code
|
|
470
|
+
|
|
471
|
+
### Connection Keeps Dropping
|
|
472
|
+
- Check your internet connection
|
|
473
|
+
- Verify that session data is being saved correctly
|
|
474
|
+
- Ensure MongoDB is accessible if using MongoDB storage
|
|
475
|
+
- Check WhatsApp Web's status (sometimes WhatsApp blocks certain IPs)
|
|
476
|
+
|
|
477
|
+
### Messages Not Sending
|
|
478
|
+
- Verify the phone number format / default country set correctly
|
|
479
|
+
- Check if the number is registered on WhatsApp
|
|
480
|
+
- Ensure the connection is active using `isConnected()`
|
|
481
|
+
- Check for rate limiting
|
|
482
|
+
|
|
483
|
+
## Contributing
|
|
484
|
+
|
|
485
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
486
|
+
|
|
487
|
+
1. Fork the repository
|
|
488
|
+
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
|
|
489
|
+
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
|
|
490
|
+
4. Push to the branch (`git push origin feature/amazing-feature`)
|
|
491
|
+
5. Open a Pull Request
|
|
492
|
+
|
|
493
|
+
## License
|
|
494
|
+
|
|
495
|
+
MIT License - see the [LICENSE](LICENSE) file for details.
|
|
496
|
+
|
|
497
|
+
## Dependencies
|
|
498
|
+
|
|
499
|
+
- [@fadzzzslebew/baileys](https://github.com/fadzzzslebew/baileys) - Core WhatsApp Web API
|
|
500
|
+
- [qrcode](https://www.npmjs.com/package/qrcode) - QR code generation
|
|
501
|
+
- [pino](https://www.npmjs.com/package/pino) - Logging
|
|
502
|
+
- [music-metadata](https://www.npmjs.com/package/music-metadata) - Audio metadata extraction
|
|
503
|
+
- [ms](https://www.npmjs.com/package/ms) - Time string parsing
|
|
504
|
+
|
|
505
|
+
## Support
|
|
506
|
+
|
|
507
|
+
- 🐛 [Report Issues](https://github.com/hdriel/whatsapp-socket/issues)
|
|
508
|
+
- 💬 [Discussions](https://github.com/hdriel/whatsapp-socket/discussions)
|
|
509
|
+
- 📖 [Documentation](https://github.com/hdriel/whatsapp-socket#readme)
|
|
510
|
+
|
|
511
|
+
## Changelog
|
|
512
|
+
|
|
513
|
+
See [CHANGELOG.md](CHANGELOG.md) for version history and updates.
|
|
514
|
+
|
|
515
|
+
## Author
|
|
516
|
+
|
|
517
|
+
**Hadriel Benjo**
|
|
518
|
+
- GitHub: [@hdriel](https://github.com/hdriel)
|
|
519
|
+
- LinkedIn: [Hadriel Benjo](https://www.linkedin.com/in/hadriel-benjo/)
|
|
520
|
+
- YouTube: [@Just-Like-That](https://www.youtube.com/@Just-Like-That./playlists)
|
|
521
|
+
|
|
522
|
+
---
|
|
523
|
+
|
|
524
|
+
**Remember**: This is an unofficial library. Use responsibly and at your own risk. Always respect WhatsApp's Terms of Service.
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
[//]: # (## 🔗 Links)
|
|
528
|
+
[//]: # ()
|
|
529
|
+
[//]: # (- [GitHub WhiskeySockets/Baileys](https://github.com/WhiskeySockets/Baileys))
|
|
530
|
+
[//]: # (- [@adiwajshing/baileys-md](https://pokoke-01.github.io/owh/index.html))
|
|
531
|
+
[//]: # (- [Automating WhatsApp](https://medium.com/@elvisbrazil/automating-whatsapp-with-node-js-and-baileys-send-receive-and-broadcast-messages-with-code-0656c40bd928))
|
|
532
|
+
[//]: # (- [baileys-pro](https://www.npmjs.com/package/baileys-pro?activeTab=readme))
|
|
19
533
|
[//]: # (- [GitHub Demo Repository](https://github.com/hdriel/aws-utils-demo))
|
|
20
534
|
|
|
21
535
|
---
|
|
22
536
|
|
|
23
|
-
Made with ❤️ for developers who want powerful
|
|
537
|
+
Made with ❤️ for developers who want powerful Whatsapp Bot utilities without the complexity.
|
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var G=require('fs'),Q=require('@fadzzzslebew/baileys'),U=require('qrcode'),mongodb=require('mongodb'),X=require('pino'),Z=require('ms'),musicMetadata=require('music-metadata'),path=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var G__default=/*#__PURE__*/_interopDefault(G);var Q__default=/*#__PURE__*/_interopDefault(Q);var U__default=/*#__PURE__*/_interopDefault(U);var X__default=/*#__PURE__*/_interopDefault(X);var Z__default=/*#__PURE__*/_interopDefault(Z);var D={replacer:(o,e)=>Buffer.isBuffer(e)||e instanceof Uint8Array||e?.type==="Buffer"?{type:"Buffer",data:Buffer.from(e?.data||e).toString("base64")}:e,reviver:(o,e)=>{if(typeof e=="object"&&e&&(e.buffer===true||e.type==="Buffer")){let t=e.data||e.value;return typeof t=="string"?Buffer.from(t,"base64"):Buffer.from(t||[])}return e}},V=async o=>{let e=(s,a)=>{let i={$set:{...JSON.parse(JSON.stringify(s,D.replacer))}};return o.updateOne({_id:a},i,{upsert:true})},t=async s=>{try{let a=JSON.stringify(await o.findOne({_id:s}));return JSON.parse(a,D.reviver)}catch{return null}},n=async s=>{try{await o.deleteOne({_id:s});}catch{}},r=await t("creds")||Q.initAuthCreds();return {state:{creds:r,keys:{get:async(s,a)=>{let c={};return await Promise.all(a.map(async i=>{let g=await t(`${s}-${i}`);s==="app-state-sync-key"&&g&&(g=Q.WAProto.Message.AppStateSyncKeyData.fromObject(g)),c[i]=g;})),c},set:async s=>{let a=[];for(let c of Object.keys(s))for(let i of Object.keys(s[c])){let g=s[c][i],m=`${c}-${i}`;a.push(g?e(g,m):n(m));}await Promise.all(a);}}},saveCreds:()=>e(r,"creds")}},x=V;var F=X__default.default({level:"silent"}),S=class o{socket;fileAuthStateDirectoryPath;mongoURL;mongoCollection="whatsapp-auth";logger;debug;printQRInTerminal;pairingPhone;customPairingCode;allowUseLastVersion;onOpen;onClose;onQR;onConnectionStatusChange;onReceiveMessages;static DEFAULT_COUNTRY_CODE="972";static formatPhoneNumber(e,t=o.DEFAULT_COUNTRY_CODE){if(e.endsWith("@s.whatsapp.net"))return e;let n=e.replace(/[^0-9]/g,"");return n.startsWith("05")&&(n=n.substring(1)),n.startsWith(t)||(n=t+n),n}static formatPhoneNumberToWhatsappPattern(e,t=o.DEFAULT_COUNTRY_CODE){if(e.endsWith("@s.whatsapp.net"))return e;let n=o.formatPhoneNumber(e,t);return n=`${n}@s.whatsapp.net`,n}static getWhatsappPhoneLink({phone:e,message:t,countryCode:n=this.DEFAULT_COUNTRY_CODE}){let r=this.formatPhoneNumber(e,n),s={...t&&{text:encodeURI(t)}};return `https://wa.me/${r}?${s}`}static async qrToImage(e,t={}){return U__default.default.toDataURL(e,{errorCorrectionLevel:"H",width:400,margin:2,...t})}static async qrToTerminalString(e,t={}){return U__default.default.toString(e,{type:"terminal",small:true,...t})}static randomPairingCode(e,t=8){if(!e.includes("[")&&e.length===t)return e;let n="",r=[],s=c=>{let i=[];for(let g=0;g<c.length;g++)if(c[g+1]==="-"&&c[g+2]){let m=c.charCodeAt(g),p=c.charCodeAt(g+2);for(let l=m;l<=p;l++)i.push(String.fromCharCode(l));g+=2;}else i.push(c[g]);return i};for(let c=0;c<e.length&&n.length<t;c++){let i=e[c];if(i==="["){let g=e.indexOf("]",c),m=e.slice(c+1,g);r=s(m),c=g;}else n+=i;}for(;n.length<t&&r.length;)n+=r[Math.floor(Math.random()*r.length)];let a=n.toUpperCase();return a.padEnd(t,a)}constructor({fileAuthStateDirectoryPath:e,mongoURL:t,mongoCollection:n="whatsapp-auth",logger:r,onOpen:s,onClose:a,onQR:c,onReceiveMessages:i,onConnectionStatusChange:g,debug:m,printQRInTerminal:p,pairingPhone:l,customPairingCode:P,allowUseLastVersion:b=true}){this.mongoURL=t,this.fileAuthStateDirectoryPath=e,this.mongoCollection=n,this.logger=r,this.debug=m,this.printQRInTerminal=p,this.pairingPhone=l,this.customPairingCode=P,this.allowUseLastVersion=b,this.onConnectionStatusChange=g,this.socket=null,this.onReceiveMessages=i,this.onOpen=s,this.onClose=a,this.onQR=c;}async getAuthCollection(){if(!this.mongoURL)return [];let e=new mongodb.MongoClient(this.mongoURL);return await e.connect(),[e.db().collection(this.mongoCollection),e]}async authenticate(){if(!this.mongoURL&&!this.fileAuthStateDirectoryPath)throw new Error("fileAuthStateDirectoryPath/MongoURL is missing");if(!this.mongoURL){let{saveCreds:s,state:a}=await Q.useMultiFileAuthState(this.fileAuthStateDirectoryPath);return {auth:a,saveCreds:s}}let[e]=await this.getAuthCollection(),{state:t,saveCreds:n}=await x(e);return {auth:{creds:t.creds,keys:Q.makeCacheableSignalKeyStore(t.keys,F)},saveCreds:n}}async startConnection({options:e,connectionAttempts:t=3,onOpen:n=this.onOpen,onClose:r=this.onClose,onQR:s=this.onQR,onConnectionStatusChange:a=this.onConnectionStatusChange,pairingPhone:c,debug:i}={}){let g=c??this.pairingPhone,{saveCreds:m,auth:p}=await this.authenticate(),l=i===void 0?this.debug:i,{version:P,isLatest:b}=await Q.fetchLatestBaileysVersion();this.allowUseLastVersion&&!b&&l&&this.logger?.warn("WHATSAPP","current baileys service is not the latest version!",{version:P,isLatest:b});let W=()=>{let f=Q__default.default({version:this.allowUseLastVersion?P:[2,3e3,1027934701],logger:F,browser:["Ubuntu","Chrome","20.0.04"],syncFullHistory:false,shouldSyncHistoryMessage:()=>false,shouldIgnoreJid:h=>h.includes("@newsletter"),...e,printQRInTerminal:false,auth:p});return f.ev.on("connection.update",async h=>{let{connection:C,lastDisconnect:v,qr:w}=h;if(w){if(l&&this.logger?.info("WHATSAPP","QR Code received",{qr:w}),this.printQRInTerminal){let E=await o.qrToTerminalString(w,{small:true}).catch(()=>null);console.log(E);}this.customPairingCode?o.randomPairingCode(this.customPairingCode):void 0;let y=g?o.formatPhoneNumber(g):null,T=y?await f.requestPairingCode(y):null;l&&this.printQRInTerminal&&this.logger?.info("WHATSAPP","QR Pairing Code",{code:T,pairingPhone:y}),await s?.(w,T);}switch(C){case "connecting":{l&&this.logger?.debug("WHATSAPP","Connecting..."),a?.("connecting");break}case "open":{l&&this.logger?.info("WHATSAPP","Connection opened successfully!"),this.socket=f,await n?.(),a?.("open");break}case "close":{let R=t-- >0&&v?.error?.output?.statusCode!==Q.DisconnectReason.loggedOut,y=v?.error?.output?.statusCode,T=v?.error?.message;l&&this.logger?.info("WHATSAPP","Connection closed",{statusCode:y,errorMessage:T,shouldReconnect:R}),R&&t?(l&&this.logger?.info("WHATSAPP","Reconnecting..."),setTimeout(W,1e3)):(l&&this.logger?.warn("WHATSAPP","Logged out, clearing auth state"),await r?.(),this.socket=null),a?.("close");break}}}),f.ev.on("creds.update",m),this.onReceiveMessages&&typeof this.onReceiveMessages=="function"&&f.ev.on("messages.upsert",async({messages:h,type:C})=>{this.logger?.info("WHATSAPP","Received messages",{type:C,totalMessages:h.length}),this.onReceiveMessages?.(h,C);}),f};return W()}async closeConnection(){this.socket&&(this.debug&&this.logger?.info("WHATSAPP","Closing connection"),this.socket.end(void 0),this.socket=null);}async clearAuthState(){if(this.mongoURL){let[e,t]=await this.getAuthCollection();this.debug&&this.logger?.info("WHATSAPP","Deleting auth state, required to scanning QR again"),await e?.deleteMany({}),await t?.close();}else this.fileAuthStateDirectoryPath&&G__default.default.rmSync(this.fileAuthStateDirectoryPath,{recursive:true,force:true});}async resetConnection({pairingPhone:e}={}){await this.closeConnection(),await this.clearAuthState(),await new Promise(t=>setTimeout(t,2e3)),await this.startConnection({pairingPhone:e});}isConnected(){return this.socket!==null&&this.socket.user!==void 0}};var I=o=>Z__default.default(o)/1e3;async function d(o){let t=await(await fetch(o)).arrayBuffer();return Buffer.from(t)}async function oe(o,e){try{let t=await musicMetadata.parseStream(o,{mimeType:e||"audio/mpeg"});return Math.floor(t.format.duration||0)}catch(t){throw console.error("Error parsing stream:",t),t}finally{o.destroyed||o.destroy();}}async function re(o,e){try{let t=await musicMetadata.parseBuffer(o,e||"audio/mpeg").catch(()=>null);return t?Math.floor(t.format.duration||0):0}catch(t){throw console.error("Error parsing buffer:",t),t}}async function O(o,e){return o instanceof G.ReadStream?oe(o,e):re(o,e)}async function L(o){let e=[];for await(let t of o)e.push(t);return Buffer.concat(e)}function N(o){if(o.path){let e=o.path.toString();return path.basename(e)}}var k=class o extends S{static DEFAULT_COUNTRY_CODE="972";constructor(e){super(e);}async sendTextMessage(e,t,n){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let r=o.formatPhoneNumberToWhatsappPattern(e),s={...n&&{quoted:{key:{id:n}}}};return this.socket.sendMessage(r,{text:t},s)}async sendButtonsMessage(e,{subtitle:t,title:n,buttons:r}){if(!n||!r.length)throw new Error("sendButtonsMessage: No title or buttons required field found.");this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let s=o.formatPhoneNumberToWhatsappPattern(e),a=r?.map(i=>{let g={display_text:i.label},m;switch(true){case !!i.url:m="cta_url",g.url=i.url;break;case !!i.copy:m="cta_copy",g.copy_code=i.copy;break;case !!i.tel:m="cta_call",g.phone_number=i.tel;break;case !!i.email:m="cta_email",g.email=i.email;break;case !!(i.reminderOn||i.reminderDate):m="cta_reminder";let{reminderOn:p,reminderDate:l}=i;g.reminder_name=i.reminderName,g.reminder_timestamp=l?Math.floor(+new Date(l)/1e3):Math.floor(Date.now()/1e3)+I(p??"0s");break;default:m="";break}return {name:m,buttonParamsJson:JSON.stringify(g)}}).filter(i=>i.name),c=Q.generateWAMessageFromContent(s,{viewOnceMessage:{message:{interactiveMessage:Q.WAProto.Message.InteractiveMessage.create({...n&&{body:Q.WAProto.Message.InteractiveMessage.Body.create({text:n})},...t&&{footer:Q.WAProto.Message.InteractiveMessage.Footer.create({text:t})},...!!a?.length&&{nativeFlowMessage:Q.WAProto.Message.InteractiveMessage.NativeFlowMessage.create({buttons:a})}})}}},{userJid:s});return this.socket.relayMessage(s,c.message,{messageId:c.key.id})}async sendReplyButtonsMessage(e,{title:t,subtitle:n,buttons:r}){if(!t||!r.length)throw new Error("sendReplyButtonsMessage: No title or buttons required field found.");this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let s=o.formatPhoneNumberToWhatsappPattern(e);return this.socket.sendMessage(s,{text:t,...n&&{footer:n},buttons:r.filter(a=>a).map((a,c)=>({buttonId:`id${c}`,buttonText:{displayText:a},type:1}))})}};var B=class o extends k{static DEFAULT_COUNTRY_CODE="972";constructor(e){super(e);}async sendFileFromStream(e,t,n){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let r=o.formatPhoneNumberToWhatsappPattern(e),s=t instanceof Buffer?t:await this.streamToBuffer(t),a=n.mimetype||this.getMimetypeFromFilename(n.filename),c=await this.createFileMessage(s,a,n),i={...n.replyToMessageId&&{quoted:{key:{id:n.replyToMessageId}}}};return this.socket.sendMessage(r,c,i)}async streamToBuffer(e){return new Promise((t,n)=>{let r=[];e.on("data",s=>r.push(Buffer.from(s))),e.on("error",s=>n(s)),e.on("end",()=>t(Buffer.concat(r)));})}getMimetypeFromFilename(e){let t=e.split(".").pop()?.toLowerCase();return {jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",bmp:"image/bmp",svg:"image/svg+xml",mp4:"video/mp4",avi:"video/x-msvideo",mov:"video/quicktime",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",opus:"audio/opus",aac:"audio/aac",m4a:"audio/mp4",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed"}[t||""]||"application/octet-stream"}async createFileMessage(e,t,n){let[r]=t.split("/");switch(r){case "image":return {image:e,caption:n.caption,mimetype:t,fileName:n.filename};case "video":return {video:e,caption:n.caption,mimetype:t,fileName:n.filename,gifPlayback:n.gifPlayback||false,jpegThumbnail:n.jpegThumbnail,...n.seconds&&{seconds:n.seconds}};case "audio":return n.ptt?{audio:e,mimetype:"audio/ogg; codecs=opus",ptt:true,...n.seconds&&{seconds:n.seconds}}:{audio:e,mimetype:t,fileName:n.filename,...n.seconds&&{seconds:n.seconds}};default:return {document:e,mimetype:t,fileName:n.filename,caption:n.caption,jpegThumbnail:n.jpegThumbnail}}}async sendImage(e,t,n={}){return this.sendFileFromStream(e,t,{filename:n.filename||"image.jpg",mimetype:"image/jpeg",caption:n.caption,replyToMessageId:n.replyToMessageId})}async sendVideo(e,t,n={}){return this.sendFileFromStream(e,t,{filename:n.filename||"video.mp4",mimetype:"video/mp4",caption:n.caption,gifPlayback:n.gifPlayback,replyToMessageId:n.replyToMessageId,jpegThumbnail:n.jpegThumbnail})}async sendAudio(e,t,n={}){return this.sendFileFromStream(e,t,{filename:n.filename||"audio.mp3",mimetype:n.ptt?"audio/ogg; codecs=opus":"audio/mpeg",ptt:n.ptt,seconds:n.seconds,replyToMessageId:n.replyToMessageId})}async sendDocument(e,t,n){return this.sendFileFromStream(e,t,{filename:n.filename,mimetype:n.mimetype,caption:n.caption,replyToMessageId:n.replyToMessageId,jpegThumbnail:n.jpegThumbnail})}async sendVoiceNote(e,t,n={}){return this.sendAudio(e,t,{ptt:true,seconds:n.seconds,replyToMessageId:n.replyToMessageId})}async sendSticker(e,t,n={}){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let r=o.formatPhoneNumberToWhatsappPattern(e),s=t instanceof Buffer?t:await this.streamToBuffer(t),a={...n.replyToMessageId&&{quoted:{key:{id:n.replyToMessageId}}}};return this.socket.sendMessage(r,{sticker:s},a)}};var M=class o extends B{static DEFAULT_COUNTRY_CODE="972";constructor(e){super(e);}async sendImageMessage(e,t,{caption:n="",filename:r}={}){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let s=o.formatPhoneNumberToWhatsappPattern(e),a=typeof t=="string"?await d(t):t;return await super.sendImage(s,a,{caption:n,...r&&{filename:r}})}async sendVideoMessage(e,t,{caption:n="",filename:r,sendAsGifPlayback:s=false}={}){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let a=o.formatPhoneNumberToWhatsappPattern(e),c=typeof t=="string"?await d(t):t;return await super.sendVideo(a,c,{caption:n,gifPlayback:s,...r&&{filename:r}})}async sendFileMessage(e,t,{caption:n="",mimetype:r="application/vnd.openxmlformats-officedocument.wordprocessingml.document",replyToMessageId:s,jpegThumbnailSrc:a,filename:c}={}){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let i=o.formatPhoneNumberToWhatsappPattern(e),g=typeof t=="string"?await d(t):t,m;typeof a=="string"?m=await d(a):a instanceof G.ReadStream?m=await L(a):m=a;let p="mu-document";if(t instanceof G.ReadStream){let l=N(t);l&&(p=l);}else typeof t=="string"&&(p=path.basename(t));return await super.sendDocument(i,g,{caption:n,mimetype:r,filename:p,replyToMessageId:s,jpegThumbnail:m})}async sendAudioMessage(e,t,{filename:n,replyToMessageId:r,mimetype:s,seconds:a}={}){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let c=o.formatPhoneNumberToWhatsappPattern(e),i=typeof t=="string"?await d(t):t,g=a||await O(i,s).catch(()=>0);return await super.sendAudio(c,i,{...n&&{filename:n},...s&&{mimetype:s},...g&&{seconds:g},...r&&{replyToMessageId:r}})}async sendStickerMessage(e,t,{replyToMessageId:n}={}){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let r=o.formatPhoneNumberToWhatsappPattern(e),s=typeof t=="string"?await d(t):t;await super.sendSticker(r,s,{replyToMessageId:n});}};var H=class extends M{constructor(e){super(e);}};
|
|
2
|
-
exports.WhatsappSocket=
|
|
1
|
+
'use strict';var G=require('fs'),Q=require('@fadzzzslebew/baileys'),U=require('qrcode'),mongodb=require('mongodb'),X=require('pino'),Z=require('ms'),musicMetadata=require('music-metadata'),path=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var G__default=/*#__PURE__*/_interopDefault(G);var Q__default=/*#__PURE__*/_interopDefault(Q);var U__default=/*#__PURE__*/_interopDefault(U);var X__default=/*#__PURE__*/_interopDefault(X);var Z__default=/*#__PURE__*/_interopDefault(Z);var D={replacer:(r,e)=>Buffer.isBuffer(e)||e instanceof Uint8Array||e?.type==="Buffer"?{type:"Buffer",data:Buffer.from(e?.data||e).toString("base64")}:e,reviver:(r,e)=>{if(typeof e=="object"&&e&&(e.buffer===true||e.type==="Buffer")){let t=e.data||e.value;return typeof t=="string"?Buffer.from(t,"base64"):Buffer.from(t||[])}return e}},V=async r=>{let e=(s,a)=>{let i={$set:{...JSON.parse(JSON.stringify(s,D.replacer))}};return r.updateOne({_id:a},i,{upsert:true})},t=async s=>{try{let a=JSON.stringify(await r.findOne({_id:s}));return JSON.parse(a,D.reviver)}catch{return null}},n=async s=>{try{await r.deleteOne({_id:s});}catch{}},o=await t("creds")||Q.initAuthCreds();return {state:{creds:o,keys:{get:async(s,a)=>{let c={};return await Promise.all(a.map(async i=>{let g=await t(`${s}-${i}`);s==="app-state-sync-key"&&g&&(g=Q.WAProto.Message.AppStateSyncKeyData.fromObject(g)),c[i]=g;})),c},set:async s=>{let a=[];for(let c of Object.keys(s))for(let i of Object.keys(s[c])){let g=s[c][i],u=`${c}-${i}`;a.push(g?e(g,u):n(u));}await Promise.all(a);}}},saveCreds:()=>e(o,"creds")}},x=V;var F=X__default.default({level:"silent"}),w=class r{socket;fileAuthStateDirectoryPath;mongoURL;mongoCollection="whatsapp-auth";logger;debug;printQRInTerminal;pairingPhone;customPairingCode;allowUseLastVersion;onOpen;onClose;onQR;onConnectionStatusChange;onReceiveMessages;static DEFAULT_COUNTRY_CODE="972";static formatPhoneNumber(e,t=r.DEFAULT_COUNTRY_CODE){if(e.endsWith("@s.whatsapp.net"))return e;let n=e.replace(/[^0-9]/g,"");return n.startsWith("05")&&(n=n.substring(1)),n.startsWith(t)||(n=t+n),n}static formatPhoneNumberToWhatsappPattern(e,t=r.DEFAULT_COUNTRY_CODE){if(e.endsWith("@s.whatsapp.net"))return e;let n=r.formatPhoneNumber(e,t);return n=`${n}@s.whatsapp.net`,n}static getWhatsappPhoneLink({phone:e,message:t,countryCode:n=this.DEFAULT_COUNTRY_CODE}){let o=this.formatPhoneNumber(e,n),s={...t&&{text:encodeURI(t)}};return `https://wa.me/${o}?${s}`}static async qrToImage(e,t={}){return U__default.default.toDataURL(e,{errorCorrectionLevel:"H",width:400,margin:2,...t})}static async qrToTerminalString(e,t={}){return U__default.default.toString(e,{type:"terminal",small:true,...t})}static randomPairingCode(e,t=8){if(!e.includes("[")&&e.length===t)return e;let n="",o=[],s=c=>{let i=[];for(let g=0;g<c.length;g++)if(c[g+1]==="-"&&c[g+2]){let u=c.charCodeAt(g),l=c.charCodeAt(g+2);for(let m=u;m<=l;m++)i.push(String.fromCharCode(m));g+=2;}else i.push(c[g]);return i};for(let c=0;c<e.length&&n.length<t;c++){let i=e[c];if(i==="["){let g=e.indexOf("]",c),u=e.slice(c+1,g);o=s(u),c=g;}else n+=i;}for(;n.length<t&&o.length;)n+=o[Math.floor(Math.random()*o.length)];let a=n.toUpperCase();return a.padEnd(t,a)}constructor({fileAuthStateDirectoryPath:e,mongoURL:t,mongoCollection:n="whatsapp-auth",logger:o,onOpen:s,onClose:a,onQR:c,onReceiveMessages:i,onConnectionStatusChange:g,debug:u,printQRInTerminal:l,pairingPhone:m,customPairingCode:P,allowUseLastVersion:b=true}){this.mongoURL=t,this.fileAuthStateDirectoryPath=e,this.mongoCollection=n,this.logger=o,this.debug=u,this.printQRInTerminal=l,this.pairingPhone=m,this.customPairingCode=P,this.allowUseLastVersion=b,this.onConnectionStatusChange=g,this.socket=null,this.onReceiveMessages=i,this.onOpen=s,this.onClose=a,this.onQR=c;}async getAuthCollection(){if(!this.mongoURL)return [];let e=new mongodb.MongoClient(this.mongoURL);return await e.connect(),[e.db().collection(this.mongoCollection),e]}async authenticate(){if(!this.mongoURL&&!this.fileAuthStateDirectoryPath)throw new Error("fileAuthStateDirectoryPath/MongoURL is missing");if(!this.mongoURL){let{saveCreds:s,state:a}=await Q.useMultiFileAuthState(this.fileAuthStateDirectoryPath);return {auth:a,saveCreds:s}}let[e]=await this.getAuthCollection(),{state:t,saveCreds:n}=await x(e);return {auth:{creds:t.creds,keys:Q.makeCacheableSignalKeyStore(t.keys,F)},saveCreds:n}}async startConnection({options:e,connectionAttempts:t=3,onOpen:n=this.onOpen,onClose:o=this.onClose,onQR:s=this.onQR,onConnectionStatusChange:a=this.onConnectionStatusChange,pairingPhone:c,debug:i}={}){let g=c??this.pairingPhone,{saveCreds:u,auth:l}=await this.authenticate(),m=i===void 0?this.debug:i,{version:P,isLatest:b}=await Q.fetchLatestBaileysVersion();this.allowUseLastVersion&&!b&&m&&this.logger?.warn("WHATSAPP","current baileys service is not the latest version!",{version:P,isLatest:b});let W=()=>{let f=Q__default.default({version:this.allowUseLastVersion?P:[2,3e3,1027934701],logger:F,browser:["Ubuntu","Chrome","20.0.04"],syncFullHistory:false,shouldSyncHistoryMessage:()=>false,shouldIgnoreJid:h=>h.includes("@newsletter"),...e,printQRInTerminal:false,auth:l});return f.ev.on("connection.update",async h=>{let{connection:T,lastDisconnect:v,qr:A}=h;if(A){if(m&&this.logger?.info("WHATSAPP","QR Code received",{qr:A}),this.printQRInTerminal){let E=await r.qrToTerminalString(A,{small:true}).catch(()=>null);console.log(E);}this.customPairingCode?r.randomPairingCode(this.customPairingCode):void 0;let y=g?r.formatPhoneNumber(g):null,C=y?await f.requestPairingCode(y):null;m&&this.printQRInTerminal&&this.logger?.info("WHATSAPP","QR Pairing Code",{code:C,pairingPhone:y}),await s?.(A,C);}switch(T){case "connecting":{m&&this.logger?.debug("WHATSAPP","Connecting..."),a?.("connecting");break}case "open":{m&&this.logger?.info("WHATSAPP","Connection opened successfully!"),this.socket=f,await n?.(),a?.("open");break}case "close":{let R=t-- >0&&v?.error?.output?.statusCode!==Q.DisconnectReason.loggedOut,y=v?.error?.output?.statusCode,C=v?.error?.message;m&&this.logger?.info("WHATSAPP","Connection closed",{statusCode:y,errorMessage:C,shouldReconnect:R}),R&&t?(m&&this.logger?.info("WHATSAPP","Reconnecting..."),setTimeout(W,1e3)):(m&&this.logger?.warn("WHATSAPP","Logged out, clearing auth state"),await o?.(),this.socket=null),a?.("close");break}}}),f.ev.on("creds.update",u),this.onReceiveMessages&&typeof this.onReceiveMessages=="function"&&f.ev.on("messages.upsert",async({messages:h,type:T})=>{this.logger?.info("WHATSAPP","Received messages",{type:T,totalMessages:h.length}),this.onReceiveMessages?.(h,T);}),f};return W()}async closeConnection(){this.socket&&(this.debug&&this.logger?.info("WHATSAPP","Closing connection"),this.socket.end(void 0),this.socket=null);}async clearAuthState(){if(this.mongoURL){let[e,t]=await this.getAuthCollection();this.debug&&this.logger?.info("WHATSAPP","Deleting auth state, required to scanning QR again"),await e?.deleteMany({}),await t?.close();}else this.fileAuthStateDirectoryPath&&G__default.default.rmSync(this.fileAuthStateDirectoryPath,{recursive:true,force:true});}async resetConnection({pairingPhone:e}={}){await this.closeConnection(),await this.clearAuthState(),await new Promise(t=>setTimeout(t,2e3)),await this.startConnection({pairingPhone:e});}isConnected(){return this.socket!==null&&this.socket.user!==void 0}};var O=r=>Z__default.default(r)/1e3;async function p(r){let t=await(await fetch(r)).arrayBuffer();return Buffer.from(t)}async function oe(r,e){try{let t=await musicMetadata.parseStream(r,{mimeType:e||"audio/mpeg"});return Math.floor(t.format.duration||0)}catch(t){throw console.error("Error parsing stream:",t),t}finally{r.destroyed||r.destroy();}}async function re(r,e){try{let t=await musicMetadata.parseBuffer(r,e||"audio/mpeg").catch(()=>null);return t?Math.floor(t.format.duration||0):0}catch(t){throw console.error("Error parsing buffer:",t),t}}async function L(r,e){return r instanceof G.ReadStream?oe(r,e):re(r,e)}async function N(r){let e=[];for await(let t of r)e.push(t);return Buffer.concat(e)}function I(r){if(r.path){let e=r.path.toString();return path.basename(e)}}var k=class r extends w{static DEFAULT_COUNTRY_CODE="972";constructor(e){super(e);}async sendTextMessage(e,t,n){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let o=r.formatPhoneNumberToWhatsappPattern(e),s={...n&&{quoted:{key:{id:n}}}};return this.socket.sendMessage(o,{text:t},s)}async sendButtonsMessage(e,{subtitle:t,title:n,buttons:o}){if(!n||!o.length)throw new Error("sendButtonsMessage: No title or buttons required field found.");this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let s=r.formatPhoneNumberToWhatsappPattern(e),a=o?.map(i=>{let g={display_text:i.label},u;switch(true){case !!i.url:u="cta_url",g.url=i.url;break;case !!i.copy:u="cta_copy",g.copy_code=i.copy;break;case !!i.tel:u="cta_call",g.phone_number=i.tel;break;case !!i.email:u="cta_email",g.email=i.email;break;case !!(i.reminderOn||i.reminderDate):u="cta_reminder";let{reminderOn:l,reminderDate:m}=i;g.reminder_name=i.reminderName,g.reminder_timestamp=m?Math.floor(+new Date(m)/1e3):Math.floor(Date.now()/1e3)+O(l??"0s");break;default:u="";break}return {name:u,buttonParamsJson:JSON.stringify(g)}}).filter(i=>i.name),c=Q.generateWAMessageFromContent(s,{viewOnceMessage:{message:{interactiveMessage:Q.WAProto.Message.InteractiveMessage.create({...n&&{body:Q.WAProto.Message.InteractiveMessage.Body.create({text:n})},...t&&{footer:Q.WAProto.Message.InteractiveMessage.Footer.create({text:t})},...!!a?.length&&{nativeFlowMessage:Q.WAProto.Message.InteractiveMessage.NativeFlowMessage.create({buttons:a})}})}}},{userJid:s});return this.debug&&this.logger?.debug("WHATSAPP","send buttons message",{jid:s,footer:t,body:n,buttons:a}),this.socket.relayMessage(s,c.message,{messageId:c.key.id})}async sendReplyButtonsMessage(e,{title:t,subtitle:n,buttons:o}){if(!t||!o.length)throw new Error("sendReplyButtonsMessage: No title or buttons required field found.");this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let s=r.formatPhoneNumberToWhatsappPattern(e),a=o.filter(c=>c).map((c,i)=>({buttonId:`id${i}`,buttonText:{displayText:c},type:1}));return this.debug&&this.logger?.debug("WHATSAPP","send reply buttons message",{jid:s,text:t,footer:n,buttons:a}),this.socket.sendMessage(s,{text:t,...n&&{footer:n},buttons:a})}};var B=class r extends k{static DEFAULT_COUNTRY_CODE="972";constructor(e){super(e);}async sendFileFromStream(e,t,n){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let o=r.formatPhoneNumberToWhatsappPattern(e),s=t instanceof Buffer?t:await this.streamToBuffer(t),a=n.mimetype||this.getMimetypeFromFilename(n.filename),c=await this.createFileMessage(s,a,n),i={...n.replyToMessageId&&{quoted:{key:{id:n.replyToMessageId}}}};return this.socket.sendMessage(o,c,i)}async streamToBuffer(e){return new Promise((t,n)=>{let o=[];e.on("data",s=>o.push(Buffer.from(s))),e.on("error",s=>n(s)),e.on("end",()=>t(Buffer.concat(o)));})}getMimetypeFromFilename(e){let t=e.split(".").pop()?.toLowerCase();return {jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",bmp:"image/bmp",svg:"image/svg+xml",mp4:"video/mp4",avi:"video/x-msvideo",mov:"video/quicktime",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",opus:"audio/opus",aac:"audio/aac",m4a:"audio/mp4",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed"}[t||""]||"application/octet-stream"}async createFileMessage(e,t,n){let[o]=t.split("/");switch(o){case "image":return {image:e,caption:n.caption,mimetype:t,fileName:n.filename};case "video":return {video:e,caption:n.caption,mimetype:t,fileName:n.filename,gifPlayback:n.gifPlayback||false,jpegThumbnail:n.jpegThumbnail,...n.seconds&&{seconds:n.seconds}};case "audio":return n.ptt?{audio:e,mimetype:"audio/ogg; codecs=opus",ptt:true,...n.seconds&&{seconds:n.seconds}}:{audio:e,mimetype:t,fileName:n.filename,...n.seconds&&{seconds:n.seconds}};default:return {document:e,mimetype:t,fileName:n.filename,caption:n.caption,jpegThumbnail:n.jpegThumbnail}}}async sendImage(e,t,n={}){return this.sendFileFromStream(e,t,{filename:n.filename||"image.jpg",mimetype:"image/jpeg",caption:n.caption,replyToMessageId:n.replyToMessageId})}async sendVideo(e,t,n={}){return this.sendFileFromStream(e,t,{filename:n.filename||"video.mp4",mimetype:"video/mp4",caption:n.caption,gifPlayback:n.gifPlayback,replyToMessageId:n.replyToMessageId,jpegThumbnail:n.jpegThumbnail})}async sendAudio(e,t,n={}){return this.sendFileFromStream(e,t,{filename:n.filename||"audio.mp3",mimetype:n.ptt?"audio/ogg; codecs=opus":"audio/mpeg",ptt:n.ptt,seconds:n.seconds,replyToMessageId:n.replyToMessageId})}async sendDocument(e,t,n){return this.sendFileFromStream(e,t,{filename:n.filename,mimetype:n.mimetype,caption:n.caption,replyToMessageId:n.replyToMessageId,jpegThumbnail:n.jpegThumbnail})}async sendVoiceNote(e,t,n={}){return this.sendAudio(e,t,{ptt:true,seconds:n.seconds,replyToMessageId:n.replyToMessageId})}async sendSticker(e,t,n={}){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let o=r.formatPhoneNumberToWhatsappPattern(e),s=t instanceof Buffer?t:await this.streamToBuffer(t),a={...n.replyToMessageId&&{quoted:{key:{id:n.replyToMessageId}}}};return this.socket.sendMessage(o,{sticker:s},a)}};var M=class r extends B{static DEFAULT_COUNTRY_CODE="972";constructor(e){super(e);}async sendImageMessage(e,t,{caption:n="",filename:o}={}){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let s=r.formatPhoneNumberToWhatsappPattern(e),a=typeof t=="string"?await p(t):t;return this.debug&&this.logger?.debug("WHATSAPP","send image message",{jid:s,caption:n,filename:o}),await super.sendImage(s,a,{caption:n,...o&&{filename:o}})}async sendVideoMessage(e,t,{caption:n="",filename:o,sendAsGifPlayback:s=false}={}){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let a=r.formatPhoneNumberToWhatsappPattern(e),c=typeof t=="string"?await p(t):t;return this.debug&&this.logger?.debug("WHATSAPP","send video message",{jid:a,caption:n,filename:o,gifPlayback:s}),await super.sendVideo(a,c,{caption:n,gifPlayback:s,...o&&{filename:o}})}async sendFileMessage(e,t,{caption:n="",mimetype:o="application/vnd.openxmlformats-officedocument.wordprocessingml.document",replyToMessageId:s,jpegThumbnailSrc:a,filename:c}={}){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let i=r.formatPhoneNumberToWhatsappPattern(e),g=typeof t=="string"?await p(t):t,u;typeof a=="string"?u=await p(a):a instanceof G.ReadStream?u=await N(a):u=a;let l="mu-document";if(t instanceof G.ReadStream){let m=I(t);m&&(l=m);}else typeof t=="string"&&(l=path.basename(t));return this.debug&&this.logger?.debug("WHATSAPP","send file message",{jid:i,caption:n,mimetype:o,filename:l,replyToMessageId:s,includeJpegThumbnail:!!u}),await super.sendDocument(i,g,{caption:n,mimetype:o,filename:l,replyToMessageId:s,jpegThumbnail:u})}async sendAudioMessage(e,t,{filename:n,replyToMessageId:o,mimetype:s,seconds:a}={}){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let c=r.formatPhoneNumberToWhatsappPattern(e),i=typeof t=="string"?await p(t):t,g=a||await L(i,s).catch(()=>0);return this.debug&&this.logger?.debug("WHATSAPP","send audio message",{jid:c,mimetype:s,filename:n,seconds:g,replyToMessageId:o}),await super.sendAudio(c,i,{...n&&{filename:n},...s&&{mimetype:s},...g&&{seconds:g},...o&&{replyToMessageId:o}})}async sendStickerMessage(e,t,{replyToMessageId:n}={}){this.socket||(this.debug&&this.logger?.warn("WHATSAPP","Client not connected, attempting to connect..."),this.socket=await this.startConnection());let o=r.formatPhoneNumberToWhatsappPattern(e),s=typeof t=="string"?await p(t):t;this.debug&&this.logger?.debug("WHATSAPP","send sticker message",{jid:o,replyToMessageId:n}),await super.sendSticker(o,s,{replyToMessageId:n});}};var j=class extends M{constructor(e){super(e);}};
|
|
2
|
+
exports.WhatsappSocket=j;//# sourceMappingURL=index.cjs.map
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|