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