wa-multi-mongodb 3.8.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.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/dist/Defaults/index.d.ts +21 -0
  3. package/dist/Defaults/index.d.ts.map +1 -0
  4. package/dist/Defaults/index.js +31 -0
  5. package/dist/Error/index.d.ts +5 -0
  6. package/dist/Error/index.d.ts.map +1 -0
  7. package/dist/Error/index.js +14 -0
  8. package/dist/Messaging/index.d.ts +25 -0
  9. package/dist/Messaging/index.d.ts.map +1 -0
  10. package/dist/Messaging/index.js +335 -0
  11. package/dist/Profile/index.d.ts +9 -0
  12. package/dist/Profile/index.d.ts.map +1 -0
  13. package/dist/Profile/index.js +34 -0
  14. package/dist/Socket/index.d.ts +68 -0
  15. package/dist/Socket/index.d.ts.map +1 -0
  16. package/dist/Socket/index.js +527 -0
  17. package/dist/Types/index.d.ts +70 -0
  18. package/dist/Types/index.d.ts.map +1 -0
  19. package/dist/Types/index.js +2 -0
  20. package/dist/Types/profile.d.ts +5 -0
  21. package/dist/Types/profile.d.ts.map +1 -0
  22. package/dist/Types/profile.js +2 -0
  23. package/dist/Utils/create-delay.d.ts +17 -0
  24. package/dist/Utils/create-delay.d.ts.map +1 -0
  25. package/dist/Utils/create-delay.js +38 -0
  26. package/dist/Utils/error.d.ts +4 -0
  27. package/dist/Utils/error.d.ts.map +1 -0
  28. package/dist/Utils/error.js +8 -0
  29. package/dist/Utils/index.d.ts +4 -0
  30. package/dist/Utils/index.d.ts.map +1 -0
  31. package/dist/Utils/index.js +21 -0
  32. package/dist/Utils/is-exist.d.ts +6 -0
  33. package/dist/Utils/is-exist.d.ts.map +1 -0
  34. package/dist/Utils/is-exist.js +53 -0
  35. package/dist/Utils/message-status.d.ts +4 -0
  36. package/dist/Utils/message-status.d.ts.map +1 -0
  37. package/dist/Utils/message-status.js +18 -0
  38. package/dist/Utils/mongo-auth-state.d.ts +15 -0
  39. package/dist/Utils/mongo-auth-state.d.ts.map +1 -0
  40. package/dist/Utils/mongo-auth-state.js +109 -0
  41. package/dist/Utils/phone-to-jid.d.ts +5 -0
  42. package/dist/Utils/phone-to-jid.d.ts.map +1 -0
  43. package/dist/Utils/phone-to-jid.js +30 -0
  44. package/dist/Utils/save-media.d.ts +6 -0
  45. package/dist/Utils/save-media.d.ts.map +1 -0
  46. package/dist/Utils/save-media.js +55 -0
  47. package/dist/index.d.ts +8 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +46 -0
  50. package/package.json +37 -0
  51. package/readme.md +423 -0
package/readme.md ADDED
@@ -0,0 +1,423 @@
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