wa-multi-mongodb 3.9.1 → 3.9.2
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/package.json +2 -2
- package/readme.md +449 -444
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wa-multi-mongodb",
|
|
3
|
-
"version": "3.9.
|
|
3
|
+
"version": "3.9.2",
|
|
4
4
|
"description": "Multi Session Whatsapp Library with MongoDB Integration",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"dependencies": {
|
|
18
18
|
"@adiwajshing/keyed-db": "^0.2.4",
|
|
19
19
|
"@hapi/boom": "^10.0.1",
|
|
20
|
-
"baileys": "^6.7.
|
|
20
|
+
"baileys": "^6.7.17",
|
|
21
21
|
"dotenv": "^16.5.0",
|
|
22
22
|
"link-preview-js": "^3.0.14",
|
|
23
23
|
"mime": "^3.0.0",
|
package/readme.md
CHANGED
|
@@ -1,444 +1,449 @@
|
|
|
1
|
-
# WhatsApp Multi MongoDB - Multi Session WhatsApp with MongoDB
|
|
2
|
-
|
|
3
|
-
## ⚠️ Important Note
|
|
4
|
-
This repository is a modified version of [@mimamch/wa-multi-session](https://github.com/mimamch/wa-multi-session) with MongoDB session management integration. The original repository uses file-based session storage, while this version uses MongoDB for better scalability and session management.
|
|
5
|
-
|
|
6
|
-
Lightweight library for WhatsApp with MongoDB integration. No Selenium or browser required.
|
|
7
|
-
|
|
8
|
-
Built on [Baileys](https://github.com/WhiskeySockets/Baileys) Library.
|
|
9
|
-
|
|
10
|
-
## Features
|
|
11
|
-
- Multi-session WhatsApp (multiple numbers simultaneously)
|
|
12
|
-
- State (auth) storage in MongoDB instead of files
|
|
13
|
-
- Automatic loading of all sessions from the database at startup
|
|
14
|
-
- No need to scan QR again as long as MongoDB data is preserved
|
|
15
|
-
- Automatic timeout handling for long-running operations
|
|
16
|
-
- Auto-reconnect when connection is lost
|
|
17
|
-
- Better group chat support
|
|
18
|
-
- Automatic retry for failed message deliveries
|
|
19
|
-
- Automatic group chat detection (v3.9.0+)
|
|
20
|
-
|
|
21
|
-
## Installation
|
|
22
|
-
|
|
23
|
-
Install package using npm:
|
|
24
|
-
|
|
25
|
-
```bash
|
|
26
|
-
npm install wa-multi-mongodb@latest
|
|
27
|
-
```
|
|
28
|
-
|
|
29
|
-
Then import into your code:
|
|
30
|
-
|
|
31
|
-
```typescript
|
|
32
|
-
// Using ES modules
|
|
33
|
-
import * as whatsapp from "wa-multi-mongodb";
|
|
34
|
-
|
|
35
|
-
// Or using CommonJS
|
|
36
|
-
const whatsapp = require("wa-multi-mongodb");
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
## Environment Setup
|
|
40
|
-
|
|
41
|
-
For secure MongoDB URI management, we recommend using environment variables:
|
|
42
|
-
|
|
43
|
-
1. Create a `.env` file in your project root (copy from `.env.example`):
|
|
44
|
-
```
|
|
45
|
-
# MongoDB Configuration
|
|
46
|
-
MONGODB_URI=mongodb://username:password@hostname:port/database
|
|
47
|
-
|
|
48
|
-
# Optional database settings
|
|
49
|
-
WA_DB_NAME=wa_session
|
|
50
|
-
WA_COLLECTION_NAME=auth
|
|
51
|
-
```
|
|
52
|
-
|
|
53
|
-
2. Install and use the dotenv package:
|
|
54
|
-
```javascript
|
|
55
|
-
// Load environment variables
|
|
56
|
-
require('dotenv').config();
|
|
57
|
-
|
|
58
|
-
// Use in your code
|
|
59
|
-
const MONGODB_URI = process.env.MONGODB_URI;
|
|
60
|
-
if (!MONGODB_URI) {
|
|
61
|
-
console.error('Error: MONGODB_URI not found in environment variables');
|
|
62
|
-
process.exit(1);
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
// Initialize WhatsApp with MongoDB
|
|
66
|
-
await whatsapp.setMongoURI(MONGODB_URI);
|
|
67
|
-
```
|
|
68
|
-
|
|
69
|
-
3. Make sure to add `.env` to your `.gitignore` file to prevent exposing sensitive credentials
|
|
70
|
-
|
|
71
|
-
## MongoDB Configuration
|
|
72
|
-
|
|
73
|
-
### Setup MongoDB Connection
|
|
74
|
-
1. Make sure MongoDB is running (local/cloud)
|
|
75
|
-
2. Configure the connection using one of these methods:
|
|
76
|
-
|
|
77
|
-
**Using environment variables (recommended):**
|
|
78
|
-
```javascript
|
|
79
|
-
require('dotenv').config();
|
|
80
|
-
await whatsapp.setMongoURI(process.env.MONGODB_URI);
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
**Directly in code (not recommended for production):**
|
|
84
|
-
```javascript
|
|
85
|
-
await whatsapp.setMongoURI("mongodb+srv://username:password@host/db?options");
|
|
86
|
-
```
|
|
87
|
-
|
|
88
|
-
3. Optionally customize the database and collection names:
|
|
89
|
-
```javascript
|
|
90
|
-
// Default values are "wa_session" and "auth"
|
|
91
|
-
whatsapp.setMongoDBNames("custom_database_name", "custom_collection_name");
|
|
92
|
-
```
|
|
93
|
-
|
|
94
|
-
## Basic Usage
|
|
95
|
-
|
|
96
|
-
### Session Management
|
|
97
|
-
|
|
98
|
-
```javascript
|
|
99
|
-
// Start a new session
|
|
100
|
-
const session = await whatsapp.startSession("mysession");
|
|
101
|
-
|
|
102
|
-
// Start with options
|
|
103
|
-
await whatsapp.startSession("mysession2", {
|
|
104
|
-
printQR: true,
|
|
105
|
-
onConnected: () => console.log("Connected!"),
|
|
106
|
-
onDisconnected: () => console.log("Disconnected!"),
|
|
107
|
-
onQRUpdated: (qr) => console.log("New QR:", qr)
|
|
108
|
-
});
|
|
109
|
-
|
|
110
|
-
// Get all active sessions
|
|
111
|
-
const sessions = await whatsapp.getAllSession();
|
|
112
|
-
|
|
113
|
-
// Get data for a specific session
|
|
114
|
-
const sessionData = whatsapp.getSession("mysession");
|
|
115
|
-
|
|
116
|
-
// Load all saved sessions from MongoDB
|
|
117
|
-
await whatsapp.loadSessionsFromMongo();
|
|
118
|
-
```
|
|
119
|
-
|
|
120
|
-
### Sending Messages
|
|
121
|
-
|
|
122
|
-
```javascript
|
|
123
|
-
// Send text message
|
|
124
|
-
await whatsapp.sendTextMessage({
|
|
125
|
-
sessionId: "mysession",
|
|
126
|
-
to: "6281234567890", // always include country code
|
|
127
|
-
text: "Hello from wa-multi-mongodb!"
|
|
128
|
-
// isGroup parameter is optional (v3.9.0+)
|
|
129
|
-
// The library will automatically detect if the destination is a group
|
|
130
|
-
});
|
|
131
|
-
|
|
132
|
-
// Send to a group (automatic detection in v3.9.0+)
|
|
133
|
-
await whatsapp.sendTextMessage({
|
|
134
|
-
sessionId: "mysession",
|
|
135
|
-
to: "120363152682073800", // group ID
|
|
136
|
-
text: "Hello group!"
|
|
137
|
-
// No need for isGroup: true parameter in v3.9.0+
|
|
138
|
-
});
|
|
139
|
-
|
|
140
|
-
// Send to a group (compatible with older versions)
|
|
141
|
-
await whatsapp.sendTextMessage({
|
|
142
|
-
sessionId: "mysession",
|
|
143
|
-
to: "120363152682073800", // group ID
|
|
144
|
-
text: "Hello group!",
|
|
145
|
-
isGroup: true // still works but optional in v3.9.0+
|
|
146
|
-
});
|
|
147
|
-
|
|
148
|
-
// Send media (unified function)
|
|
149
|
-
await whatsapp.sendMedia({
|
|
150
|
-
sessionId: "mysession",
|
|
151
|
-
to: "6281234567890",
|
|
152
|
-
type: "image", // options: image, video, pdf, doc, docx, xls, xlsx, zip, mp3
|
|
153
|
-
media: fs.readFileSync("./image.jpg"), // or URL string
|
|
154
|
-
caption: "Image caption",
|
|
155
|
-
fileName: "image.jpg", // required for documents
|
|
156
|
-
// isGroup parameter is optional (v3.9.0+)
|
|
157
|
-
});
|
|
158
|
-
|
|
159
|
-
// Send voice note
|
|
160
|
-
await whatsapp.sendVoiceNote({
|
|
161
|
-
sessionId: "mysession",
|
|
162
|
-
to: "6281234567890",
|
|
163
|
-
media: fs.readFileSync("./audio.mp3"),
|
|
164
|
-
// isGroup parameter is optional (v3.9.0+)
|
|
165
|
-
});
|
|
166
|
-
|
|
167
|
-
// Mark message as read
|
|
168
|
-
await whatsapp.readMessage({
|
|
169
|
-
sessionId: "mysession",
|
|
170
|
-
key: msg.key,
|
|
171
|
-
});
|
|
172
|
-
|
|
173
|
-
// Send typing indicator
|
|
174
|
-
await whatsapp.sendTyping({
|
|
175
|
-
sessionId: "mysession",
|
|
176
|
-
to: "6281234567890", // or group ID
|
|
177
|
-
duration: 3000, // milliseconds
|
|
178
|
-
// isGroup parameter is optional (v3.9.0+)
|
|
179
|
-
});
|
|
180
|
-
```
|
|
181
|
-
|
|
182
|
-
### Event Listeners
|
|
183
|
-
|
|
184
|
-
```javascript
|
|
185
|
-
// Incoming messages
|
|
186
|
-
whatsapp.onMessageReceived((msg) => {
|
|
187
|
-
console.log(`Message from ${msg.key.remoteJid}:`, msg);
|
|
188
|
-
});
|
|
189
|
-
|
|
190
|
-
// QR code updates
|
|
191
|
-
whatsapp.onQRUpdated(({ sessionId, qr }) => {
|
|
192
|
-
console.log(`QR Code for ${sessionId}:`, qr);
|
|
193
|
-
// You can display this QR in a UI or save it to a file
|
|
194
|
-
});
|
|
195
|
-
|
|
196
|
-
// Connection events
|
|
197
|
-
whatsapp.onConnected((sessionId) => {
|
|
198
|
-
console.log(`Session ${sessionId} connected`);
|
|
199
|
-
});
|
|
200
|
-
|
|
201
|
-
whatsapp.onDisconnected((sessionId) => {
|
|
202
|
-
console.log(`Session ${sessionId} disconnected`);
|
|
203
|
-
});
|
|
204
|
-
```
|
|
205
|
-
|
|
206
|
-
### Handling Media in Incoming Messages
|
|
207
|
-
|
|
208
|
-
```javascript
|
|
209
|
-
whatsapp.onMessageReceived(async (msg) => {
|
|
210
|
-
if (msg.message?.imageMessage) {
|
|
211
|
-
await msg.saveImage("./saved-image.jpg");
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
if (msg.message?.videoMessage) {
|
|
215
|
-
await msg.saveVideo("./saved-video.mp4");
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
if (msg.message?.documentMessage) {
|
|
219
|
-
await msg.saveDocument("./saved-document"); // extension will be added automatically
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
if (msg.message?.audioMessage) {
|
|
223
|
-
await msg.saveAudio("./saved-audio.mp3");
|
|
224
|
-
}
|
|
225
|
-
});
|
|
226
|
-
```
|
|
227
|
-
|
|
228
|
-
## Utility Functions
|
|
229
|
-
|
|
230
|
-
```javascript
|
|
231
|
-
// Create a delay
|
|
232
|
-
import { createDelay } from "wa-multi-mongodb";
|
|
233
|
-
await createDelay(2000); // wait 2 seconds
|
|
234
|
-
|
|
235
|
-
// Execute with timeout
|
|
236
|
-
import { withTimeout } from "wa-multi-mongodb";
|
|
237
|
-
try {
|
|
238
|
-
const result = await withTimeout(
|
|
239
|
-
functionThatMightTakeTooLong(),
|
|
240
|
-
10000, // timeout in ms
|
|
241
|
-
"Operation timed out" // error message if timeout occurs
|
|
242
|
-
);
|
|
243
|
-
} catch (error) {
|
|
244
|
-
console.error(error.message);
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
// Attempt to reconnect a session
|
|
248
|
-
import { reconnect } from "wa-multi-mongodb";
|
|
249
|
-
try {
|
|
250
|
-
const reconnected = await reconnect("mysession");
|
|
251
|
-
console.log("Reconnect successful:", reconnected);
|
|
252
|
-
} catch (error) {
|
|
253
|
-
console.error("Reconnect failed:", error);
|
|
254
|
-
}
|
|
255
|
-
```
|
|
256
|
-
|
|
257
|
-
## Complete Example: Auto-Reconnect Application
|
|
258
|
-
|
|
259
|
-
```javascript
|
|
260
|
-
import * as whatsapp from "wa-multi-mongodb";
|
|
261
|
-
import { withTimeout } from "wa-multi-mongodb";
|
|
262
|
-
require('dotenv').config();
|
|
263
|
-
|
|
264
|
-
// Store connection status
|
|
265
|
-
const sessionStatus = {};
|
|
266
|
-
|
|
267
|
-
// Function to check and reconnect if disconnected
|
|
268
|
-
async function checkAndReconnect(sessionId) {
|
|
269
|
-
if (sessionStatus[sessionId] === 'disconnected') {
|
|
270
|
-
try {
|
|
271
|
-
const reconnected = await whatsapp.reconnect(sessionId);
|
|
272
|
-
if (reconnected) {
|
|
273
|
-
sessionStatus[sessionId] = 'connected';
|
|
274
|
-
console.log(`Session ${sessionId} reconnected`);
|
|
275
|
-
}
|
|
276
|
-
} catch (error) {
|
|
277
|
-
console.error(`Error during reconnect: ${error.message}`);
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
async function startApp() {
|
|
283
|
-
// MongoDB Configuration
|
|
284
|
-
await whatsapp.setMongoURI(process.env.MONGODB_URI);
|
|
285
|
-
|
|
286
|
-
// Event listeners
|
|
287
|
-
whatsapp.onQRUpdated(({ sessionId, qr }) => {
|
|
288
|
-
console.log(`QR Code for session ${sessionId}:`, qr);
|
|
289
|
-
});
|
|
290
|
-
|
|
291
|
-
whatsapp.onConnected((sessionId) => {
|
|
292
|
-
console.log(`Session ${sessionId} connected!`);
|
|
293
|
-
sessionStatus[sessionId] = 'connected';
|
|
294
|
-
});
|
|
295
|
-
|
|
296
|
-
whatsapp.onDisconnected((sessionId) => {
|
|
297
|
-
console.log(`Session ${sessionId} disconnected!`);
|
|
298
|
-
sessionStatus[sessionId] = 'disconnected';
|
|
299
|
-
|
|
300
|
-
// Try to reconnect after a few seconds
|
|
301
|
-
setTimeout(() => checkAndReconnect(sessionId), 10000);
|
|
302
|
-
});
|
|
303
|
-
|
|
304
|
-
// Message handler with error handling and group detection
|
|
305
|
-
whatsapp.onMessageReceived(async (msg) => {
|
|
306
|
-
try {
|
|
307
|
-
if (msg.key.fromMe || msg.key.remoteJid.includes("status")) return;
|
|
308
|
-
|
|
309
|
-
const messageContent = msg.message?.conversation ||
|
|
310
|
-
msg.message?.extendedTextMessage?.text ||
|
|
311
|
-
"";
|
|
312
|
-
|
|
313
|
-
// Detect if message is from a group
|
|
314
|
-
const isGroup = msg.key.remoteJid.endsWith('@g.us');
|
|
315
|
-
|
|
316
|
-
// Mark message as read
|
|
317
|
-
try {
|
|
318
|
-
await whatsapp.readMessage({
|
|
319
|
-
sessionId: msg.sessionId,
|
|
320
|
-
key: msg.key,
|
|
321
|
-
});
|
|
322
|
-
} catch (error) {
|
|
323
|
-
if (error.message.includes('Connection Closed')) {
|
|
324
|
-
sessionStatus[msg.sessionId] = 'disconnected';
|
|
325
|
-
setTimeout(() => checkAndReconnect(msg.sessionId), 5000);
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
// Reply to messages containing "hello"
|
|
330
|
-
if (messageContent.toLowerCase().includes("hello")) {
|
|
331
|
-
// Show typing indicator (works in both private and group chats since v3.9.1+)
|
|
332
|
-
await whatsapp.sendTyping({
|
|
333
|
-
sessionId: msg.sessionId,
|
|
334
|
-
to: msg.key.remoteJid,
|
|
335
|
-
duration: 2000,
|
|
336
|
-
});
|
|
337
|
-
|
|
338
|
-
// Use different timeouts for groups vs private chats
|
|
339
|
-
const timeoutMs = isGroup ? 60000 : 30000;
|
|
340
|
-
|
|
341
|
-
try {
|
|
342
|
-
await withTimeout(
|
|
343
|
-
whatsapp.sendTextMessage({
|
|
344
|
-
sessionId: msg.sessionId,
|
|
345
|
-
to: msg.key.remoteJid,
|
|
346
|
-
text: "Hello! How can I help you?",
|
|
347
|
-
answering: msg,
|
|
348
|
-
// isGroup parameter is optional (v3.9.0+)
|
|
349
|
-
}),
|
|
350
|
-
timeoutMs,
|
|
351
|
-
"Message sending timed out"
|
|
352
|
-
);
|
|
353
|
-
} catch (error) {
|
|
354
|
-
console.error("Error sending message:", error.message);
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
} catch (error) {
|
|
358
|
-
// Prevent application crash
|
|
359
|
-
console.error("Error processing message:", error.message);
|
|
360
|
-
}
|
|
361
|
-
});
|
|
362
|
-
|
|
363
|
-
// Load all sessions from MongoDB
|
|
364
|
-
await whatsapp.loadSessionsFromMongo();
|
|
365
|
-
|
|
366
|
-
// Create a main session if it doesn't exist
|
|
367
|
-
const mainSession = "main_session";
|
|
368
|
-
const existingSessions = await whatsapp.getAllSession();
|
|
369
|
-
if (!existingSessions.includes(mainSession)) {
|
|
370
|
-
await whatsapp.startSession(mainSession);
|
|
371
|
-
} else {
|
|
372
|
-
sessionStatus[mainSession] = 'connected';
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
// Check connections periodically
|
|
376
|
-
setInterval(() => {
|
|
377
|
-
Object.keys(sessionStatus).forEach(sid => {
|
|
378
|
-
checkAndReconnect(sid);
|
|
379
|
-
});
|
|
380
|
-
}, 5 * 60 * 1000); // check every 5 minutes
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
startApp().catch(err => {
|
|
384
|
-
console.error("Failed to start application:", err);
|
|
385
|
-
process.exit(1);
|
|
386
|
-
});
|
|
387
|
-
```
|
|
388
|
-
|
|
389
|
-
## Best Practices for Group Chats
|
|
390
|
-
|
|
391
|
-
1. **Auto Group Detection**: Since v3.9.0, the library automatically detects if a chat is a group based on its JID format
|
|
392
|
-
2. **Typing Indicators**: Typing indicators now work in both private and group chats (v3.9.1+)
|
|
393
|
-
3. **Longer Timeouts**: Use longer timeouts when sending media to groups (60+ seconds)
|
|
394
|
-
4. **Handle Errors**: Implement retry mechanisms for failed group messages
|
|
395
|
-
5. **Announcement Channels**: Groups with announcement channels may trigger `MessageCounterError` (handled automatically in v3.9.1+)
|
|
396
|
-
6. **Retry Strategy**: For announcement channel groups, the library will automatically retry sending messages up to 3 times with increasing delays
|
|
397
|
-
|
|
398
|
-
## WhatsApp Limitations
|
|
399
|
-
|
|
400
|
-
1. **Media Transfer**: Large media files to groups may take longer or timeout
|
|
401
|
-
2. **Connection Stability**: Auto-reconnect may be needed in production apps
|
|
402
|
-
3. **Announcement Channels**: Some groups with announcement channels may still fail after multiple retries
|
|
403
|
-
|
|
404
|
-
## Changelog
|
|
405
|
-
|
|
406
|
-
### v3.9.
|
|
407
|
-
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
-
|
|
411
|
-
-
|
|
412
|
-
-
|
|
413
|
-
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
-
|
|
418
|
-
-
|
|
419
|
-
-
|
|
420
|
-
|
|
421
|
-
### v3.8.
|
|
422
|
-
-
|
|
423
|
-
-
|
|
424
|
-
-
|
|
425
|
-
|
|
426
|
-
### v3.
|
|
427
|
-
-
|
|
428
|
-
-
|
|
429
|
-
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
-
|
|
434
|
-
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
- [
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
1
|
+
# WhatsApp Multi MongoDB - Multi Session WhatsApp with MongoDB
|
|
2
|
+
|
|
3
|
+
## ⚠️ Important Note
|
|
4
|
+
This repository is a modified version of [@mimamch/wa-multi-session](https://github.com/mimamch/wa-multi-session) with MongoDB session management integration. The original repository uses file-based session storage, while this version uses MongoDB for better scalability and session management.
|
|
5
|
+
|
|
6
|
+
Lightweight library for WhatsApp with MongoDB integration. No Selenium or browser required.
|
|
7
|
+
|
|
8
|
+
Built on [Baileys](https://github.com/WhiskeySockets/Baileys) Library.
|
|
9
|
+
|
|
10
|
+
## Features
|
|
11
|
+
- Multi-session WhatsApp (multiple numbers simultaneously)
|
|
12
|
+
- State (auth) storage in MongoDB instead of files
|
|
13
|
+
- Automatic loading of all sessions from the database at startup
|
|
14
|
+
- No need to scan QR again as long as MongoDB data is preserved
|
|
15
|
+
- Automatic timeout handling for long-running operations
|
|
16
|
+
- Auto-reconnect when connection is lost
|
|
17
|
+
- Better group chat support
|
|
18
|
+
- Automatic retry for failed message deliveries
|
|
19
|
+
- Automatic group chat detection (v3.9.0+)
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
Install package using npm:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
npm install wa-multi-mongodb@latest
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Then import into your code:
|
|
30
|
+
|
|
31
|
+
```typescript
|
|
32
|
+
// Using ES modules
|
|
33
|
+
import * as whatsapp from "wa-multi-mongodb";
|
|
34
|
+
|
|
35
|
+
// Or using CommonJS
|
|
36
|
+
const whatsapp = require("wa-multi-mongodb");
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Environment Setup
|
|
40
|
+
|
|
41
|
+
For secure MongoDB URI management, we recommend using environment variables:
|
|
42
|
+
|
|
43
|
+
1. Create a `.env` file in your project root (copy from `.env.example`):
|
|
44
|
+
```
|
|
45
|
+
# MongoDB Configuration
|
|
46
|
+
MONGODB_URI=mongodb://username:password@hostname:port/database
|
|
47
|
+
|
|
48
|
+
# Optional database settings
|
|
49
|
+
WA_DB_NAME=wa_session
|
|
50
|
+
WA_COLLECTION_NAME=auth
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
2. Install and use the dotenv package:
|
|
54
|
+
```javascript
|
|
55
|
+
// Load environment variables
|
|
56
|
+
require('dotenv').config();
|
|
57
|
+
|
|
58
|
+
// Use in your code
|
|
59
|
+
const MONGODB_URI = process.env.MONGODB_URI;
|
|
60
|
+
if (!MONGODB_URI) {
|
|
61
|
+
console.error('Error: MONGODB_URI not found in environment variables');
|
|
62
|
+
process.exit(1);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Initialize WhatsApp with MongoDB
|
|
66
|
+
await whatsapp.setMongoURI(MONGODB_URI);
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
3. Make sure to add `.env` to your `.gitignore` file to prevent exposing sensitive credentials
|
|
70
|
+
|
|
71
|
+
## MongoDB Configuration
|
|
72
|
+
|
|
73
|
+
### Setup MongoDB Connection
|
|
74
|
+
1. Make sure MongoDB is running (local/cloud)
|
|
75
|
+
2. Configure the connection using one of these methods:
|
|
76
|
+
|
|
77
|
+
**Using environment variables (recommended):**
|
|
78
|
+
```javascript
|
|
79
|
+
require('dotenv').config();
|
|
80
|
+
await whatsapp.setMongoURI(process.env.MONGODB_URI);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
**Directly in code (not recommended for production):**
|
|
84
|
+
```javascript
|
|
85
|
+
await whatsapp.setMongoURI("mongodb+srv://username:password@host/db?options");
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
3. Optionally customize the database and collection names:
|
|
89
|
+
```javascript
|
|
90
|
+
// Default values are "wa_session" and "auth"
|
|
91
|
+
whatsapp.setMongoDBNames("custom_database_name", "custom_collection_name");
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Basic Usage
|
|
95
|
+
|
|
96
|
+
### Session Management
|
|
97
|
+
|
|
98
|
+
```javascript
|
|
99
|
+
// Start a new session
|
|
100
|
+
const session = await whatsapp.startSession("mysession");
|
|
101
|
+
|
|
102
|
+
// Start with options
|
|
103
|
+
await whatsapp.startSession("mysession2", {
|
|
104
|
+
printQR: true,
|
|
105
|
+
onConnected: () => console.log("Connected!"),
|
|
106
|
+
onDisconnected: () => console.log("Disconnected!"),
|
|
107
|
+
onQRUpdated: (qr) => console.log("New QR:", qr)
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
// Get all active sessions
|
|
111
|
+
const sessions = await whatsapp.getAllSession();
|
|
112
|
+
|
|
113
|
+
// Get data for a specific session
|
|
114
|
+
const sessionData = whatsapp.getSession("mysession");
|
|
115
|
+
|
|
116
|
+
// Load all saved sessions from MongoDB
|
|
117
|
+
await whatsapp.loadSessionsFromMongo();
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Sending Messages
|
|
121
|
+
|
|
122
|
+
```javascript
|
|
123
|
+
// Send text message
|
|
124
|
+
await whatsapp.sendTextMessage({
|
|
125
|
+
sessionId: "mysession",
|
|
126
|
+
to: "6281234567890", // always include country code
|
|
127
|
+
text: "Hello from wa-multi-mongodb!"
|
|
128
|
+
// isGroup parameter is optional (v3.9.0+)
|
|
129
|
+
// The library will automatically detect if the destination is a group
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
// Send to a group (automatic detection in v3.9.0+)
|
|
133
|
+
await whatsapp.sendTextMessage({
|
|
134
|
+
sessionId: "mysession",
|
|
135
|
+
to: "120363152682073800", // group ID
|
|
136
|
+
text: "Hello group!"
|
|
137
|
+
// No need for isGroup: true parameter in v3.9.0+
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
// Send to a group (compatible with older versions)
|
|
141
|
+
await whatsapp.sendTextMessage({
|
|
142
|
+
sessionId: "mysession",
|
|
143
|
+
to: "120363152682073800", // group ID
|
|
144
|
+
text: "Hello group!",
|
|
145
|
+
isGroup: true // still works but optional in v3.9.0+
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
// Send media (unified function)
|
|
149
|
+
await whatsapp.sendMedia({
|
|
150
|
+
sessionId: "mysession",
|
|
151
|
+
to: "6281234567890",
|
|
152
|
+
type: "image", // options: image, video, pdf, doc, docx, xls, xlsx, zip, mp3
|
|
153
|
+
media: fs.readFileSync("./image.jpg"), // or URL string
|
|
154
|
+
caption: "Image caption",
|
|
155
|
+
fileName: "image.jpg", // required for documents
|
|
156
|
+
// isGroup parameter is optional (v3.9.0+)
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
// Send voice note
|
|
160
|
+
await whatsapp.sendVoiceNote({
|
|
161
|
+
sessionId: "mysession",
|
|
162
|
+
to: "6281234567890",
|
|
163
|
+
media: fs.readFileSync("./audio.mp3"),
|
|
164
|
+
// isGroup parameter is optional (v3.9.0+)
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
// Mark message as read
|
|
168
|
+
await whatsapp.readMessage({
|
|
169
|
+
sessionId: "mysession",
|
|
170
|
+
key: msg.key,
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
// Send typing indicator
|
|
174
|
+
await whatsapp.sendTyping({
|
|
175
|
+
sessionId: "mysession",
|
|
176
|
+
to: "6281234567890", // or group ID
|
|
177
|
+
duration: 3000, // milliseconds
|
|
178
|
+
// isGroup parameter is optional (v3.9.0+)
|
|
179
|
+
});
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
### Event Listeners
|
|
183
|
+
|
|
184
|
+
```javascript
|
|
185
|
+
// Incoming messages
|
|
186
|
+
whatsapp.onMessageReceived((msg) => {
|
|
187
|
+
console.log(`Message from ${msg.key.remoteJid}:`, msg);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
// QR code updates
|
|
191
|
+
whatsapp.onQRUpdated(({ sessionId, qr }) => {
|
|
192
|
+
console.log(`QR Code for ${sessionId}:`, qr);
|
|
193
|
+
// You can display this QR in a UI or save it to a file
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
// Connection events
|
|
197
|
+
whatsapp.onConnected((sessionId) => {
|
|
198
|
+
console.log(`Session ${sessionId} connected`);
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
whatsapp.onDisconnected((sessionId) => {
|
|
202
|
+
console.log(`Session ${sessionId} disconnected`);
|
|
203
|
+
});
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
### Handling Media in Incoming Messages
|
|
207
|
+
|
|
208
|
+
```javascript
|
|
209
|
+
whatsapp.onMessageReceived(async (msg) => {
|
|
210
|
+
if (msg.message?.imageMessage) {
|
|
211
|
+
await msg.saveImage("./saved-image.jpg");
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (msg.message?.videoMessage) {
|
|
215
|
+
await msg.saveVideo("./saved-video.mp4");
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (msg.message?.documentMessage) {
|
|
219
|
+
await msg.saveDocument("./saved-document"); // extension will be added automatically
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (msg.message?.audioMessage) {
|
|
223
|
+
await msg.saveAudio("./saved-audio.mp3");
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## Utility Functions
|
|
229
|
+
|
|
230
|
+
```javascript
|
|
231
|
+
// Create a delay
|
|
232
|
+
import { createDelay } from "wa-multi-mongodb";
|
|
233
|
+
await createDelay(2000); // wait 2 seconds
|
|
234
|
+
|
|
235
|
+
// Execute with timeout
|
|
236
|
+
import { withTimeout } from "wa-multi-mongodb";
|
|
237
|
+
try {
|
|
238
|
+
const result = await withTimeout(
|
|
239
|
+
functionThatMightTakeTooLong(),
|
|
240
|
+
10000, // timeout in ms
|
|
241
|
+
"Operation timed out" // error message if timeout occurs
|
|
242
|
+
);
|
|
243
|
+
} catch (error) {
|
|
244
|
+
console.error(error.message);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Attempt to reconnect a session
|
|
248
|
+
import { reconnect } from "wa-multi-mongodb";
|
|
249
|
+
try {
|
|
250
|
+
const reconnected = await reconnect("mysession");
|
|
251
|
+
console.log("Reconnect successful:", reconnected);
|
|
252
|
+
} catch (error) {
|
|
253
|
+
console.error("Reconnect failed:", error);
|
|
254
|
+
}
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
## Complete Example: Auto-Reconnect Application
|
|
258
|
+
|
|
259
|
+
```javascript
|
|
260
|
+
import * as whatsapp from "wa-multi-mongodb";
|
|
261
|
+
import { withTimeout } from "wa-multi-mongodb";
|
|
262
|
+
require('dotenv').config();
|
|
263
|
+
|
|
264
|
+
// Store connection status
|
|
265
|
+
const sessionStatus = {};
|
|
266
|
+
|
|
267
|
+
// Function to check and reconnect if disconnected
|
|
268
|
+
async function checkAndReconnect(sessionId) {
|
|
269
|
+
if (sessionStatus[sessionId] === 'disconnected') {
|
|
270
|
+
try {
|
|
271
|
+
const reconnected = await whatsapp.reconnect(sessionId);
|
|
272
|
+
if (reconnected) {
|
|
273
|
+
sessionStatus[sessionId] = 'connected';
|
|
274
|
+
console.log(`Session ${sessionId} reconnected`);
|
|
275
|
+
}
|
|
276
|
+
} catch (error) {
|
|
277
|
+
console.error(`Error during reconnect: ${error.message}`);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async function startApp() {
|
|
283
|
+
// MongoDB Configuration
|
|
284
|
+
await whatsapp.setMongoURI(process.env.MONGODB_URI);
|
|
285
|
+
|
|
286
|
+
// Event listeners
|
|
287
|
+
whatsapp.onQRUpdated(({ sessionId, qr }) => {
|
|
288
|
+
console.log(`QR Code for session ${sessionId}:`, qr);
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
whatsapp.onConnected((sessionId) => {
|
|
292
|
+
console.log(`Session ${sessionId} connected!`);
|
|
293
|
+
sessionStatus[sessionId] = 'connected';
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
whatsapp.onDisconnected((sessionId) => {
|
|
297
|
+
console.log(`Session ${sessionId} disconnected!`);
|
|
298
|
+
sessionStatus[sessionId] = 'disconnected';
|
|
299
|
+
|
|
300
|
+
// Try to reconnect after a few seconds
|
|
301
|
+
setTimeout(() => checkAndReconnect(sessionId), 10000);
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
// Message handler with error handling and group detection
|
|
305
|
+
whatsapp.onMessageReceived(async (msg) => {
|
|
306
|
+
try {
|
|
307
|
+
if (msg.key.fromMe || msg.key.remoteJid.includes("status")) return;
|
|
308
|
+
|
|
309
|
+
const messageContent = msg.message?.conversation ||
|
|
310
|
+
msg.message?.extendedTextMessage?.text ||
|
|
311
|
+
"";
|
|
312
|
+
|
|
313
|
+
// Detect if message is from a group
|
|
314
|
+
const isGroup = msg.key.remoteJid.endsWith('@g.us');
|
|
315
|
+
|
|
316
|
+
// Mark message as read
|
|
317
|
+
try {
|
|
318
|
+
await whatsapp.readMessage({
|
|
319
|
+
sessionId: msg.sessionId,
|
|
320
|
+
key: msg.key,
|
|
321
|
+
});
|
|
322
|
+
} catch (error) {
|
|
323
|
+
if (error.message.includes('Connection Closed')) {
|
|
324
|
+
sessionStatus[msg.sessionId] = 'disconnected';
|
|
325
|
+
setTimeout(() => checkAndReconnect(msg.sessionId), 5000);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// Reply to messages containing "hello"
|
|
330
|
+
if (messageContent.toLowerCase().includes("hello")) {
|
|
331
|
+
// Show typing indicator (works in both private and group chats since v3.9.1+)
|
|
332
|
+
await whatsapp.sendTyping({
|
|
333
|
+
sessionId: msg.sessionId,
|
|
334
|
+
to: msg.key.remoteJid,
|
|
335
|
+
duration: 2000,
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
// Use different timeouts for groups vs private chats
|
|
339
|
+
const timeoutMs = isGroup ? 60000 : 30000;
|
|
340
|
+
|
|
341
|
+
try {
|
|
342
|
+
await withTimeout(
|
|
343
|
+
whatsapp.sendTextMessage({
|
|
344
|
+
sessionId: msg.sessionId,
|
|
345
|
+
to: msg.key.remoteJid,
|
|
346
|
+
text: "Hello! How can I help you?",
|
|
347
|
+
answering: msg,
|
|
348
|
+
// isGroup parameter is optional (v3.9.0+)
|
|
349
|
+
}),
|
|
350
|
+
timeoutMs,
|
|
351
|
+
"Message sending timed out"
|
|
352
|
+
);
|
|
353
|
+
} catch (error) {
|
|
354
|
+
console.error("Error sending message:", error.message);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
} catch (error) {
|
|
358
|
+
// Prevent application crash
|
|
359
|
+
console.error("Error processing message:", error.message);
|
|
360
|
+
}
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
// Load all sessions from MongoDB
|
|
364
|
+
await whatsapp.loadSessionsFromMongo();
|
|
365
|
+
|
|
366
|
+
// Create a main session if it doesn't exist
|
|
367
|
+
const mainSession = "main_session";
|
|
368
|
+
const existingSessions = await whatsapp.getAllSession();
|
|
369
|
+
if (!existingSessions.includes(mainSession)) {
|
|
370
|
+
await whatsapp.startSession(mainSession);
|
|
371
|
+
} else {
|
|
372
|
+
sessionStatus[mainSession] = 'connected';
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// Check connections periodically
|
|
376
|
+
setInterval(() => {
|
|
377
|
+
Object.keys(sessionStatus).forEach(sid => {
|
|
378
|
+
checkAndReconnect(sid);
|
|
379
|
+
});
|
|
380
|
+
}, 5 * 60 * 1000); // check every 5 minutes
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
startApp().catch(err => {
|
|
384
|
+
console.error("Failed to start application:", err);
|
|
385
|
+
process.exit(1);
|
|
386
|
+
});
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
## Best Practices for Group Chats
|
|
390
|
+
|
|
391
|
+
1. **Auto Group Detection**: Since v3.9.0, the library automatically detects if a chat is a group based on its JID format
|
|
392
|
+
2. **Typing Indicators**: Typing indicators now work in both private and group chats (v3.9.1+)
|
|
393
|
+
3. **Longer Timeouts**: Use longer timeouts when sending media to groups (60+ seconds)
|
|
394
|
+
4. **Handle Errors**: Implement retry mechanisms for failed group messages
|
|
395
|
+
5. **Announcement Channels**: Groups with announcement channels may trigger `MessageCounterError` (handled automatically in v3.9.1+)
|
|
396
|
+
6. **Retry Strategy**: For announcement channel groups, the library will automatically retry sending messages up to 3 times with increasing delays
|
|
397
|
+
|
|
398
|
+
## WhatsApp Limitations
|
|
399
|
+
|
|
400
|
+
1. **Media Transfer**: Large media files to groups may take longer or timeout
|
|
401
|
+
2. **Connection Stability**: Auto-reconnect may be needed in production apps
|
|
402
|
+
3. **Announcement Channels**: Some groups with announcement channels may still fail after multiple retries
|
|
403
|
+
|
|
404
|
+
## Changelog
|
|
405
|
+
|
|
406
|
+
### v3.9.2 (Current)
|
|
407
|
+
- Updated Baileys dependency to v6.7.17 for improved stability and compatibility
|
|
408
|
+
|
|
409
|
+
### v3.9.1
|
|
410
|
+
- Added special handling for `MessageCounterError` in group chats with announcement channels
|
|
411
|
+
- Implemented automatic retry mechanism for messages to announcement channels
|
|
412
|
+
- Enhanced error reporting for group chat issues
|
|
413
|
+
- Fixed typing indicators to work properly in group chats
|
|
414
|
+
|
|
415
|
+
### v3.9.0
|
|
416
|
+
- Added automatic group chat detection - no need to specify `isGroup: true` parameter
|
|
417
|
+
- Improved message sending reliability for group chats
|
|
418
|
+
- Enhanced error handling with better timeout management
|
|
419
|
+
- Implemented automatic format detection for group IDs
|
|
420
|
+
|
|
421
|
+
### v3.8.1
|
|
422
|
+
- Updated baileys to v6.7.16
|
|
423
|
+
- Improved MongoDB integration
|
|
424
|
+
- Enhanced error handling and connection stability
|
|
425
|
+
|
|
426
|
+
### v3.8.0
|
|
427
|
+
- Package renamed from wa-multi-session to wa-multi-mongodb
|
|
428
|
+
- Added MongoDB session management
|
|
429
|
+
- Fixed connection and authentication issues
|
|
430
|
+
|
|
431
|
+
### v3.7.0
|
|
432
|
+
- Upgraded to baileys v6.7.9
|
|
433
|
+
- Fixed phone number validation
|
|
434
|
+
- Removed registered phone number validation requirement
|
|
435
|
+
|
|
436
|
+
## Links
|
|
437
|
+
|
|
438
|
+
- [GitHub Repository](https://github.com/wahdalo/wa-multi-mongodb)
|
|
439
|
+
- [Issue Tracker](https://github.com/wahdalo/wa-multi-mongodb/issues)
|
|
440
|
+
- [Original wa-multi-session](https://github.com/mimamch/wa-multi-session)
|
|
441
|
+
- [Baileys Library](https://github.com/WhiskeySockets/Baileys)
|
|
442
|
+
|
|
443
|
+
## Author
|
|
444
|
+
|
|
445
|
+
- [@wahdalo](https://github.com/wahdalo)
|
|
446
|
+
|
|
447
|
+
## License
|
|
448
|
+
|
|
449
|
+
ISC
|