innovators-bot2 2.0.2 → 2.0.3

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
@@ -158,10 +158,20 @@ client.on('message-deleted', async (data) => {
158
158
  ```javascript
159
159
  // Get all groups
160
160
  const groups = await client.getAllGroups()
161
+ groups.forEach(g => console.log(g.subject, g.id, g.notify, g.participants.length))
161
162
 
162
- // Get group metadata (participants, name, description...)
163
+ // Get group metadata (participants, name, description, settings...)
163
164
  const metadata = await client.getGroupMetadata(groupId)
164
- console.log(metadata.id, metadata.subject, metadata.desc)
165
+ console.log(metadata.id, metadata.subject, metadata.desc, metadata.notify)
166
+ console.log('Owner:', metadata.owner, 'Created:', new Date(metadata.creation * 1000))
167
+ console.log('Announce:', metadata.announce, 'Restrict:', metadata.restrict)
168
+
169
+ // Access participants with roles and notify names
170
+ metadata.participants.forEach(p => {
171
+ const role = p.admin === 'superadmin' ? 'Super Admin'
172
+ : p.admin === 'admin' ? 'Admin' : 'Member'
173
+ console.log(`${p.id} - ${role} - Name: ${p.notify || 'N/A'}`)
174
+ })
165
175
 
166
176
  // Create a new group
167
177
  const newGroup = await client.createGroup('Group Name', ['1234567890@s.whatsapp.net'])
@@ -378,11 +388,72 @@ await client.SendList('1234567890@s.whatsapp.net', {
378
388
  ### 8. Message History
379
389
 
380
390
  ```javascript
381
- // Get chat history
382
- const messages = await client.loadMessages(chatId, 50)
391
+ ### 8. Message Store (History)
392
+
393
+ The library includes a robust message store to keep track of chat history, even across reloads.
394
+
395
+ #### Basic Store Operations
396
+ ```javascript
397
+ // Get all stored messages for a specific chat
398
+ const messages = client.getStoredMessages('1234567890@s.whatsapp.net');
383
399
 
384
- // Get specific message
385
- const message = await client.loadMessage(chatId, messageId)
400
+ // Get all stored messages across all chats
401
+ const allMessages = client.getAllStoredMessages();
402
+
403
+ // Get list of all chat JIDs in the store
404
+ const activeChats = client.getStoredChatIds();
405
+
406
+ // Get statistics about the message store
407
+ const stats = client.getStoreStats();
408
+ ```
409
+
410
+ #### Message Store Persistence
411
+
412
+ The message store can be saved to and loaded from a file for consistency across restarts:
413
+
414
+ ```javascript
415
+ // Initialize client with persistence configuration
416
+ const client = new WhatsAppClient({
417
+ sessionName: 'my-session',
418
+ messageStoreFilePath: './data/my-session/message-store.json', // Optional custom path
419
+ autoSaveInterval: 5 * 60 * 1000, // Auto-save every 5 minutes (default)
420
+ maxMessagesPerChat: 1000, // Maximum messages to keep per chat
421
+ messageTTL: 24 * 60 * 60 * 1000 // Message time-to-live (24 hours default)
422
+ });
423
+
424
+ // The store will automatically:
425
+ // - Load from file when connected
426
+ // - Save to file when disconnected
427
+ // - Auto-save periodically (every 5 minutes by default)
428
+
429
+ // Manual save/load operations
430
+ await client.saveMessageStore(); // Returns {success, path, messageCount, savedAt}
431
+ await client.loadMessageStore(); // Returns {success, messageCount, loadedFrom}
432
+ ```
433
+
434
+ **Features:**
435
+ - 💾 **Auto-save**: Automatically saves the store at regular intervals
436
+ - 🔄 **Auto-load**: Loads the store when connecting
437
+ - 🛡️ **Safe shutdown**: Saves the store before disconnecting
438
+ - 📊 **Change tracking**: Only saves when there are new messages
439
+ - 🗂️ **Custom paths**: Configure where to save the store file
440
+
441
+ #### Events
442
+ The message store emits events you can listen to:
443
+ - `message-stored`: Emitted when messages are added to the cache.
444
+ - `store-loaded`: Emitted when the store is loaded from file.
445
+ - `store-cleared`: Emitted when the entire store is cleared.
446
+ - `chat-store-cleared`: Emitted when a specific chat's history is cleared.
447
+
448
+ ```javascript
449
+ client.on('message-stored', (messages) => {
450
+ console.log('Messages cached:', messages.length);
451
+ });
452
+
453
+ client.on('store-loaded', (info) => {
454
+ console.log(`Loaded ${info.messageCount} messages from file`);
455
+ });
456
+ ```
386
457
  ```
387
458
 
388
459
  ## More Examples and Information
@@ -438,7 +509,7 @@ The library includes example bot commands that you can use:
438
509
  - `!revokeinvite` - Revoke current invite code and generate new one
439
510
  - `!leavegroup` - Leave the current group
440
511
  - `!joingroup <code>` - Join a group by invite code
441
- - `!groupinfo <code>` - Get group info by invite code without joining
512
+ - `!groupinfo [jid|code]` - Get full group details (use in-group, by JID, or by invite code) shows participants, roles, names, and group settings
442
513
  - `!joinrequests` - List pending join requests
443
514
  - `!approvejoin <number>` - Approve a join request
444
515
  - `!rejectjoin <number>` - Reject a join request
@@ -463,6 +534,11 @@ The library includes example bot commands that you can use:
463
534
  - `!list` - Display a scrollable list
464
535
  - `!logout` - Logout from current session
465
536
 
537
+ ### 💾 Message Store
538
+ - `!messages` - Get stored messages for current chat
539
+ - `!message <id>` - Get a specific message by ID
540
+ - `!stats` - View store capacity statistics
541
+
466
542
  ### 🛡️ Protection
467
543
  - `Anti-Delete` - Automatically tracks and emits events for deleted messages
468
544
 
@@ -908,6 +984,8 @@ For more detailed information about the LID system implementation, see:
908
984
  - [LID_STORE_GUIDE.md](./LID_STORE_GUIDE.md) - Complete implementation guide
909
985
  - [Baileys Migration Guide](https://baileys.wiki/docs/migration/to-v7.0.0/) - Official migration documentation
910
986
  - [example.js](./example.js) - Working examples with LID handling
987
+ - [Read Baileys Documentation](https://innovatorssoftpk.com/)
988
+ - [Deep Knowlege](https://deepwiki.com/innovatorssoft/Baileys)
911
989
 
912
990
  ## Contributing
913
991
 
@@ -0,0 +1,62 @@
1
+ ## Message Store Persistence Commands
2
+
3
+ The following commands have been added to demonstrate the message store persistence functionality:
4
+
5
+ ### !savestore
6
+ Manually saves the current message store to a JSON file.
7
+ - Creates/updates the file at the configured path (default: `{sessionName}/message-store.json`)
8
+ - Returns statistics about the save operation
9
+
10
+ **Usage:**
11
+ ```
12
+ !savestore
13
+ ```
14
+
15
+ **Example Response:**
16
+ ```
17
+ ✅ Store Saved Successfully
18
+
19
+ • Messages: 2547
20
+ • Path: auth_info_baileys/message-store.json
21
+ • Saved at: 2/17/2026, 11:15:30 AM
22
+ ```
23
+
24
+ ### !loadstore
25
+ Manually loads the message store from the saved JSON file.
26
+ - Clears current in-memory store
27
+ - Loads messages from the file
28
+ - Returns statistics about the load operation
29
+
30
+ **Usage:**
31
+ ```
32
+ !loadstore
33
+ ```
34
+
35
+ **Example Response:**
36
+ ```
37
+ ✅ Store Loaded Successfully
38
+
39
+ • Messages: 2547
40
+ • Loaded from: 2026-02-17T06:10:25.123Z
41
+ ```
42
+
43
+ ## Automatic Persistence
44
+
45
+ The message store automatically:
46
+ - **Loads** when the client connects
47
+ - **Saves** when the client disconnects
48
+ - **Auto-saves** every 5 minutes (configurable) if there are changes
49
+
50
+ ## Configuration
51
+
52
+ Configure persistence in the client initialization:
53
+
54
+ ```javascript
55
+ const client = new WhatsAppClient({
56
+ sessionName: 'my-session',
57
+ messageStoreFilePath: './data/my-session/message-store.json', // Optional
58
+ autoSaveInterval: 5 * 60 * 1000, // 5 minutes (default)
59
+ maxMessagesPerChat: 1000,
60
+ messageTTL: 24 * 60 * 60 * 1000
61
+ });
62
+ ```
package/example.js CHANGED
@@ -43,7 +43,12 @@ async function start() {
43
43
  const client = new WhatsAppClient({
44
44
  sessionName: sessionDir,
45
45
  authmethod: authMethod,
46
- pairingPhoneNumber: pairingPhoneNumber
46
+ pairingPhoneNumber: pairingPhoneNumber,
47
+ // Message store persistence configuration
48
+ messageStoreFilePath: path.join(sessionDir, 'message-store.json'),
49
+ autoSaveInterval: 5 * 60 * 1000, // Auto-save every 5 minutes
50
+ maxMessagesPerChat: 1000, // Keep last 1000 messages per chat
51
+ messageTTL: 24 * 60 * 60 * 1000 // Messages expire after 24 hours
47
52
  });
48
53
 
49
54
  console.log(`\n🚀 Initializing with ${authMethod} method...`);
@@ -94,7 +99,18 @@ async function start() {
94
99
  console.log(`\n🛡️ Message from ${data.jid} was deleted!`)
95
100
  await client.sendMessage(data.jid, '⚠️ I saw you deleted that message! I have it saved in my memory. 😉', { quoted: data.originalMessage });
96
101
  })
102
+ // Example of listening to the new events
103
+ client.on('message-stored', (messages) => {
104
+ //console.log(`${messages.length} messages were just cached in the store.`);
105
+ });
106
+
107
+ client.on('store-loaded', (info) => {
108
+ console.log(`\n💾 Message store loaded: ${info.messageCount} messages restored from file`);
109
+ });
97
110
 
111
+ client.on('store-cleared', () => {
112
+ console.log('Main message store has been purged.');
113
+ });
98
114
  // Handle message reactions
99
115
  client.on('message-reaction', async (reaction) => {
100
116
  console.log('\n👍 Message Reaction Received!')
@@ -382,7 +398,7 @@ async function start() {
382
398
  `• !revokeinvite - Revoke group invite code\n` +
383
399
  `• !leavegroup - Leave the group\n` +
384
400
  `• !joingroup <code> - Join group by invite code\n` +
385
- `• !groupinfo <code> - Get group info by invite code\n` +
401
+ `• !groupinfo [jid|code] - Full group details with participants\n` +
386
402
  `• !joinrequests - List pending join requests\n` +
387
403
  `• !approvejoin <number> - Approve join request\n` +
388
404
  `• !rejectjoin <number> - Reject join request\n` +
@@ -406,7 +422,13 @@ async function start() {
406
422
  `• !buttons - Button template\n` +
407
423
  `• !list - Scrollable list\n\n` +
408
424
 
409
- `*🔐 LID/PN/JID Management*\n` +
425
+ `*� Message Store*\n` +
426
+ `• !messages - Get stored messages for this chat\n` +
427
+ `• !allmessages - Get statistics for all stored chats\n` +
428
+ `• !message - Get a specific message by ID\n` +
429
+ `• !stats - Get store capacity statistics\n\n` +
430
+
431
+ `*�🔐 LID/PN/JID Management*\n` +
410
432
  `• !lid - Get your LID\n` +
411
433
  `• !pn <lid> - Get PN from LID\n` +
412
434
  `• !parse <jid> - Parse JID info\n` +
@@ -434,6 +456,7 @@ async function start() {
434
456
  groups.forEach((group, index) => {
435
457
  groupList += `${index + 1}. *${group.subject}*\n`
436
458
  groupList += ` ID: ${group.id}\n`
459
+ if (group.notify) groupList += ` Notify: ${group.notify}\n`
437
460
  groupList += ` Members: ${group.participants.length}\n`
438
461
  if (group.desc) groupList += ` Description: ${group.desc}\n`
439
462
  groupList += '\n'
@@ -448,6 +471,45 @@ async function start() {
448
471
  }
449
472
  break
450
473
 
474
+ case '!groupinfo':
475
+ try {
476
+ // Use provided group JID or current group
477
+ const groupJid = args.trim() || msg.raw.key.remoteJid
478
+ if (!groupJid || !groupJid.endsWith('@g.us')) {
479
+ await client.sendMessage(msg.from, '❌ Please provide a group JID or use this command in a group.\nUsage: !groupinfo <groupJid>')
480
+ break
481
+ }
482
+ const groupInfo = await client.getGroupMetadata(groupJid)
483
+ if (groupInfo) {
484
+ let groupList = `*Group Info:*\n\n` +
485
+ `ID: ${groupInfo.id}\n` +
486
+ `Notify: ${groupInfo.notify || 'N/A'}\n` +
487
+ `Subject: ${groupInfo.subject}\n` +
488
+ `Owner: ${groupInfo.owner || 'N/A'}\n` +
489
+ `Created: ${new Date(groupInfo.creation * 1000).toLocaleString()}\n` +
490
+ `Members: ${groupInfo.participants.length}\n` +
491
+ `Description: ${groupInfo.desc || 'N/A'}\n\n` +
492
+ `*👥 Participants:*\n\n`
493
+
494
+ groupInfo.participants.forEach((p, i) => {
495
+ const role = p.admin === 'superadmin' ? '👑 Super Admin'
496
+ : p.admin === 'admin' ? '🛡️ Admin'
497
+ : '👤 Member'
498
+ groupList += `${i + 1}. ${p.id}\n`
499
+ groupList += ` Role: ${role}\n`
500
+ if (p.notify) groupList += ` Name: ${p.notify}\n`
501
+ groupList += '\n'
502
+ })
503
+
504
+ await client.sendMessage(msg.from, groupList)
505
+ } else {
506
+ await client.sendMessage(msg.from, 'Group not found')
507
+ }
508
+ } catch (error) {
509
+ console.error('Error fetching group info:', error)
510
+ await client.sendMessage(msg.from, 'Failed to fetch group info')
511
+ }
512
+ break
451
513
  case '!logout':
452
514
  // Ask for confirmation before logging out
453
515
  await client.sendButtons(msg.from, {
@@ -831,22 +893,65 @@ async function start() {
831
893
 
832
894
  case '!groupinfo':
833
895
  try {
834
- if (!args) {
835
- await client.sendMessage(msg.from, '❌ Please provide an invite code.\nUsage: !groupinfo AbCdEfGhIjK');
836
- break;
896
+ const input = args.trim()
897
+ let groupInfoResult
898
+
899
+ if (!input) {
900
+ // No args: use current group
901
+ if (!msg.raw.key.remoteJid.endsWith('@g.us')) {
902
+ await client.sendMessage(msg.from, '❌ Use this command in a group, or provide a group JID / invite code.\nUsage:\n• !groupinfo (in a group)\n• !groupinfo 120363xxxxx@g.us\n• !groupinfo AbCdEfGhIjK')
903
+ break
904
+ }
905
+ groupInfoResult = await client.getGroupMetadata(msg.raw.key.remoteJid)
906
+ } else if (input.includes('@g.us')) {
907
+ // Argument is a group JID
908
+ groupInfoResult = await client.getGroupMetadata(input)
909
+ } else {
910
+ // Argument is an invite code (or full link)
911
+ groupInfoResult = await client.getGroupInfoByInviteCode(input)
912
+ }
913
+
914
+ if (!groupInfoResult) {
915
+ await client.sendMessage(msg.from, '❌ Group not found.')
916
+ break
837
917
  }
838
- const groupInfoResult = await client.getGroupInfoByInviteCode(args.trim());
839
- let infoText = `*📋 Group Info*\n\n`;
840
- infoText += `Name: *${groupInfoResult.subject || 'N/A'}*\n`;
841
- infoText += `ID: ${groupInfoResult.id || 'N/A'}\n`;
842
- infoText += `Creator: ${groupInfoResult.owner || 'N/A'}\n`;
843
- infoText += `Description: ${groupInfoResult.desc || 'No description'}\n`;
844
- infoText += `Members: ${groupInfoResult.size || groupInfoResult.participants?.length || 'N/A'}\n`;
845
- infoText += `Created: ${groupInfoResult.creation ? new Date(groupInfoResult.creation * 1000).toLocaleString() : 'N/A'}`;
846
- await client.sendMessage(msg.from, infoText);
918
+
919
+ // Build group info header
920
+ let infoText = `*📋 Group Info*\n\n`
921
+ infoText += `*Name:* ${groupInfoResult.subject || 'N/A'}\n`
922
+ infoText += `*ID:* ${groupInfoResult.id || 'N/A'}\n`
923
+ if (groupInfoResult.notify) infoText += `*Notify:* ${groupInfoResult.notify}\n`
924
+ infoText += `*Owner:* ${groupInfoResult.owner || 'N/A'}\n`
925
+ infoText += `*Created:* ${groupInfoResult.creation ? new Date(groupInfoResult.creation * 1000).toLocaleString() : 'N/A'}\n`
926
+ infoText += `*Size:* ${groupInfoResult.size || groupInfoResult.participants?.length || 'N/A'}\n`
927
+ infoText += `*Description:* ${groupInfoResult.desc || 'No description'}\n`
928
+ if (groupInfoResult.announce !== undefined) infoText += `*Announce:* ${groupInfoResult.announce ? 'Yes (admins only)' : 'No'}\n`
929
+ if (groupInfoResult.restrict !== undefined) infoText += `*Restricted:* ${groupInfoResult.restrict ? 'Yes (admins only edit info)' : 'No'}\n`
930
+ if (groupInfoResult.ephemeralDuration) infoText += `*Disappearing:* ${groupInfoResult.ephemeralDuration}s\n`
931
+ if (groupInfoResult.memberAddMode !== undefined) infoText += `*Member Add:* ${groupInfoResult.memberAddMode ? 'All members' : 'Admins only'}\n`
932
+ if (groupInfoResult.isCommunity) infoText += `*Community:* Yes\n`
933
+ if (groupInfoResult.linkedParent) infoText += `*Linked Parent:* ${groupInfoResult.linkedParent}\n`
934
+
935
+ // Build participants list if available
936
+ if (groupInfoResult.participants && groupInfoResult.participants.length > 0) {
937
+ infoText += `\n*👥 Participants (${groupInfoResult.participants.length}):*\n\n`
938
+ groupInfoResult.participants.forEach((p, i) => {
939
+ const role = p.admin === 'superadmin' ? '👑 Super Admin'
940
+ : p.admin === 'admin' ? '🛡️ Admin'
941
+ : '👤 Member'
942
+ infoText += `${i + 1}. ${p.id}\n`
943
+ infoText += ` Role: ${role}\n`
944
+ if (p.notify) infoText += ` Name: ${p.notify}\n`
945
+ if (p.lid) infoText += ` LID: ${p.lid}\n`
946
+ if (p.phoneNumber) infoText += ` Phone: ${p.phoneNumber}\n`
947
+ infoText += '\n'
948
+ })
949
+ }
950
+
951
+ await client.sendMessage(msg.from, infoText)
847
952
  } catch (error) {
848
- console.error('Error getting group info:', error);
849
- await client.sendMessage(msg.from, `❌ Failed to get group info: ${error.message}`);
953
+ console.error('Error getting group info:', error)
954
+ await client.sendMessage(msg.from, `❌ Failed to get group info: ${error.message}`)
850
955
  }
851
956
  break;
852
957
 
@@ -1155,6 +1260,72 @@ async function start() {
1155
1260
  await client.sendMessage(msg.from, `❌ Failed to update: ${error.message}`);
1156
1261
  }
1157
1262
  break;
1263
+
1264
+ case '!messages':
1265
+ const history = client.getStoredMessages(msg.from);
1266
+ let historyText = `*💾 Stored Messages for this chat (${history.length}):*\n\n`;
1267
+ history.slice(-10).forEach((m, i) => {
1268
+ const content = m.message.conversation || m.message.extendedTextMessage?.text || "[Media/Other]";
1269
+ historyText += `${i + 1}. ID: ${m.key.id}\n Text: ${content.substring(0, 50)}${content.length > 50 ? '...' : ''}\n\n`;
1270
+ });
1271
+ await client.sendMessage(msg.from, historyText);
1272
+ break;
1273
+
1274
+ case '!message':
1275
+ if (!args) {
1276
+ await client.sendMessage(msg.from, "❌ Please provide a message ID.");
1277
+ break;
1278
+ }
1279
+ const storedMsg = client.getStoredMessage({ remoteJid: msg.from, id: args.trim(), fromMe: false });
1280
+ if (storedMsg) {
1281
+ await client.sendMessage(msg.from, `✅ Found message!\n\nContent: ${JSON.stringify(storedMsg.message, null, 2).substring(0, 1000)}`);
1282
+ } else {
1283
+ await client.sendMessage(msg.from, "❌ Message not found in store.");
1284
+ }
1285
+ break;
1286
+
1287
+ case '!stats':
1288
+ const stats = client.getStoreStats();
1289
+ await client.sendMessage(msg.from, `*📊 Message Store Statistics*\n\n• Total Chats: ${stats.totalChats}\n• Total Messages: ${stats.totalMessages}\n• Total Deleted: ${stats.totalDeleted}`);
1290
+ break;
1291
+
1292
+ case '!allmessages':
1293
+ const allMsgs = client.getAllStoredMessages();
1294
+ const activeChats = client.getStoredChatIds();
1295
+ await client.sendMessage(msg.from, `*🌐 Global Message Store*\n\n• Total Messages Held: ${allMsgs.length}\n• Total Active Chats: ${activeChats.length}\n\n*Active JIDs:* \n${activeChats.join('\n')}`);
1296
+ break;
1297
+
1298
+ case '!savestore':
1299
+ await client.sendMessage(msg.from, '💾 Saving message store to file...');
1300
+ const saveResult = await client.saveMessageStore();
1301
+ if (saveResult.success) {
1302
+ await client.sendMessage(msg.from,
1303
+ `✅ *Store Saved Successfully*\n\n` +
1304
+ `• Messages: ${saveResult.messageCount}\n` +
1305
+ `• Path: ${saveResult.path}\n` +
1306
+ `• Saved at: ${saveResult.savedAt.toLocaleString()}`
1307
+ );
1308
+ } else {
1309
+ await client.sendMessage(msg.from, `❌ Failed to save store: ${saveResult.error}`);
1310
+ }
1311
+ break;
1312
+
1313
+ case '!loadstore':
1314
+ await client.sendMessage(msg.from, '📂 Loading message store from file...');
1315
+ const loadResult = await client.loadMessageStore();
1316
+ if (loadResult.success) {
1317
+ await client.sendMessage(msg.from,
1318
+ `✅ *Store Loaded Successfully*\n\n` +
1319
+ `• Messages: ${loadResult.messageCount}\n` +
1320
+ `• Loaded from: ${loadResult.loadedFrom}`
1321
+ );
1322
+ } else {
1323
+ await client.sendMessage(msg.from,
1324
+ `⚠️ Could not load store\n` +
1325
+ `Reason: ${loadResult.reason || loadResult.error}`
1326
+ );
1327
+ }
1328
+ break;
1158
1329
  }
1159
1330
  })
1160
1331
 
package/index.js CHANGED
@@ -38,6 +38,7 @@ class Group {
38
38
  constructor(client, groupData) {
39
39
  this.client = client
40
40
  this.id = groupData.id
41
+ this.notify = groupData.notify
41
42
  this.subject = groupData.subject
42
43
  this.creation = groupData.creation
43
44
  this.owner = groupData.owner
@@ -63,6 +64,14 @@ class WhatsAppClient extends EventEmitter {
63
64
  });
64
65
  // Initialize contacts cache
65
66
  this.contactsCache = new NodeCache({ stdTTL: 0, checkperiod: 20 }); // No TTL, manual cleanup on logout
67
+
68
+ // Message store persistence configuration
69
+ this.messageStoreFilePath = config.messageStoreFilePath || path.join(this.sessionName, 'message-store.json');
70
+ this.autoSaveInterval = config.autoSaveInterval || 5 * 60 * 1000; // Default: 5 minutes
71
+ this._autoSaveTimer = null;
72
+ this._storeChangeCount = 0;
73
+ this._pairingCodeTimer = null;
74
+ this._lastStoreSave = null;
66
75
  }
67
76
 
68
77
  /**
@@ -117,7 +126,7 @@ class WhatsAppClient extends EventEmitter {
117
126
  }
118
127
 
119
128
  const browserConfig = this.authmethod === 'pairing'
120
- ? Browsers.windows('chrome')
129
+ ? Browsers.iOS('chrome')
121
130
  : ["Innovators Soft", "chrome", "1000.26100.275.0"];
122
131
 
123
132
  const { version: baileysVersion, isLatest: baileysIsLatest } = await fetchLatestBaileysVersion();
@@ -134,6 +143,7 @@ class WhatsAppClient extends EventEmitter {
134
143
  logger,
135
144
  markOnlineOnConnect: false,
136
145
  syncFullHistory: true,
146
+ getMessage: async (key) => (this.messageStore.getOriginalMessage(key))?.message,
137
147
  generateHighQualityLinkPreview: true,
138
148
  linkPreviewImageThumbnailWidth: 192,
139
149
  emitOwnEvents: true,
@@ -157,8 +167,11 @@ class WhatsAppClient extends EventEmitter {
157
167
 
158
168
  this.store = this.sock.signalRepository.lidMapping;
159
169
 
160
- this.sock.ev.on('connection.update', async (update) => {
161
- const { connection, lastDisconnect, qr } = update;
170
+ this.sock.ev.on('connection.update', async ({ connection, lastDisconnect, qr }) => {
171
+ if (connection === 'close' && this._pairingCodeTimer) {
172
+ clearTimeout(this._pairingCodeTimer);
173
+ this._pairingCodeTimer = null;
174
+ }
162
175
 
163
176
  if (qr && this.authmethod === 'qr') {
164
177
  this.emit('qr', qr);
@@ -176,6 +189,12 @@ class WhatsAppClient extends EventEmitter {
176
189
  };
177
190
  this._connectionState = 'connected';
178
191
  this.emit('connected', userInfo);
192
+
193
+ // Load message store from file
194
+ await this.loadMessageStore();
195
+
196
+ // Start auto-save
197
+ this._startAutoSave();
179
198
  }
180
199
  }
181
200
  }
@@ -186,6 +205,13 @@ class WhatsAppClient extends EventEmitter {
186
205
  if (this._connectionState !== 'disconnected') {
187
206
  this.isConnected = false;
188
207
  this._connectionState = 'disconnected';
208
+
209
+ // Save message store before disconnecting
210
+ await this.saveMessageStore();
211
+
212
+ // Stop auto-save
213
+ this._stopAutoSave();
214
+
189
215
  this.emit('disconnected', lastDisconnect?.error);
190
216
  }
191
217
 
@@ -203,9 +229,20 @@ class WhatsAppClient extends EventEmitter {
203
229
  if (phoneNumber) {
204
230
  try {
205
231
  // Wait a bit for the connection to initialize properly
206
- setTimeout(async () => {
232
+ if (this._pairingCodeTimer) {
233
+ clearTimeout(this._pairingCodeTimer);
234
+ }
235
+
236
+ this._pairingCodeTimer = setTimeout(async () => {
207
237
  const customeCode = "INOVATOR";
208
238
  try {
239
+ if (!this.sock || this._connectionState === 'disconnected') {
240
+ const err = new Error('Socket is not available to request pairing code');
241
+ console.error('Error requesting pairing code:', err);
242
+ this.emit('error', err);
243
+ return;
244
+ }
245
+
209
246
  const code = await this.sock.requestPairingCode(phoneNumber, customeCode);
210
247
  if (code) {
211
248
  // Emit pairing code event so clients can handle it
@@ -216,6 +253,8 @@ class WhatsAppClient extends EventEmitter {
216
253
  } catch (error) {
217
254
  console.error('Error requesting pairing code:', error);
218
255
  this.emit('error', error);
256
+ } finally {
257
+ this._pairingCodeTimer = null;
219
258
  }
220
259
  }, 2000); // Wait 2 seconds before requesting pairing code
221
260
  } catch (error) {
@@ -234,7 +273,17 @@ class WhatsAppClient extends EventEmitter {
234
273
 
235
274
  this.sock.ev.on('messages.upsert', async (update) => {
236
275
  // 📝 Store message for the Anti-Delete system
237
- createMessageStoreHandler(this.messageStore)(update);
276
+ const storeHandler = createMessageStoreHandler(this.messageStore);
277
+ storeHandler(update);
278
+
279
+ // 📢 Emit event that messages were stored
280
+ this.emit('message-stored', update.messages);
281
+
282
+ // Increment change counter for auto-save
283
+ this._incrementStoreChangeCount();
284
+
285
+ // Save message store to file immediately
286
+ await this.saveMessageStore();
238
287
 
239
288
  try {
240
289
  if (update.type !== 'notify' || !update.messages?.length) return;
@@ -1535,6 +1584,254 @@ class WhatsAppClient extends EventEmitter {
1535
1584
  }
1536
1585
  }
1537
1586
 
1587
+ /**
1588
+ * Get all stored messages for a specific chat
1589
+ * @param {string} chatId - The JID of the chat
1590
+ * @returns {Array} Array of stored messages (WebMessageInfo)
1591
+ */
1592
+ getStoredMessages(chatId) {
1593
+ return this.messageStore.getChatMessages(chatId);
1594
+ }
1595
+
1596
+ /**
1597
+ * Get a specific stored message by its key
1598
+ * @param {object} key - The message key { remoteJid, id, fromMe }
1599
+ * @returns {object|undefined} The stored message (WebMessageInfo)
1600
+ */
1601
+ getStoredMessage(key) {
1602
+ return this.messageStore.getOriginalMessage(key);
1603
+ }
1604
+
1605
+ /**
1606
+ * Get statistics about the message store
1607
+ * @returns {object} Store statistics
1608
+ */
1609
+ getStoreStats() {
1610
+ return this.messageStore.getStats();
1611
+ }
1612
+
1613
+ /**
1614
+ * Get all stored messages from all chats
1615
+ * @returns {Array} Array of all stored messages
1616
+ */
1617
+ getAllStoredMessages() {
1618
+ return this.messageStore.getChatIds().flatMap(chatId => this.messageStore.getChatMessages(chatId));
1619
+ }
1620
+
1621
+ /**
1622
+ * Get IDs of all chats that have stored messages
1623
+ * @returns {Array<string>} Array of chat JIDs
1624
+ */
1625
+ getStoredChatIds() {
1626
+ return this.messageStore.getChatIds();
1627
+ }
1628
+
1629
+ /**
1630
+ * Clear the entire message store
1631
+ */
1632
+ clearMessageStore() {
1633
+ this.messageStore.clear();
1634
+ this.emit('store-cleared');
1635
+ }
1636
+
1637
+ /**
1638
+ * Clear stored messages for a specific chat
1639
+ * @param {string} chatId - The JID of the chat to clear
1640
+ */
1641
+ clearChatStore(chatId) {
1642
+ this.messageStore.clearChat(chatId);
1643
+ this.emit('chat-store-cleared', chatId);
1644
+ }
1645
+
1646
+ /**
1647
+ * Save the message store to a JSON file
1648
+ * @returns {Promise<{success: boolean, path: string, messageCount: number}>}
1649
+ */
1650
+ async saveMessageStore() {
1651
+ try {
1652
+ const rawAllMessages = this.messageStore.getAllMessages();
1653
+ const stats = this.messageStore.getStats();
1654
+
1655
+ let allMessages = [];
1656
+ if (Array.isArray(rawAllMessages)) {
1657
+ allMessages = rawAllMessages;
1658
+ } else if (rawAllMessages && typeof rawAllMessages[Symbol.iterator] === 'function') {
1659
+ allMessages = Array.from(rawAllMessages);
1660
+ } else if (rawAllMessages && typeof rawAllMessages === 'object') {
1661
+ allMessages = Object.values(rawAllMessages);
1662
+ } else {
1663
+ try {
1664
+ allMessages = this.messageStore.getChatIds().flatMap(chatId => this.messageStore.getChatMessages(chatId));
1665
+ } catch {
1666
+ allMessages = [];
1667
+ }
1668
+ }
1669
+
1670
+ // Serialize the store data
1671
+ const storeData = {
1672
+ version: '1.0.0',
1673
+ savedAt: new Date().toISOString(),
1674
+ sessionName: this.sessionName,
1675
+ stats: stats,
1676
+ messages: []
1677
+ };
1678
+
1679
+ // Convert Map structure to serializable array format
1680
+ for (const msg of allMessages) {
1681
+ try {
1682
+ storeData.messages.push({
1683
+ key: msg.key,
1684
+ message: msg.message,
1685
+ messageTimestamp: msg.messageTimestamp,
1686
+ pushName: msg.pushName,
1687
+ broadcast: msg.broadcast,
1688
+ isDeleted: msg.isDeleted
1689
+ });
1690
+ } catch (err) {
1691
+ console.error('Error serializing message:', err);
1692
+ }
1693
+ }
1694
+
1695
+ // Ensure directory exists
1696
+ const dir = path.dirname(this.messageStoreFilePath);
1697
+ if (!fs.existsSync(dir)) {
1698
+ fs.mkdirSync(dir, { recursive: true });
1699
+ }
1700
+
1701
+ // Write to file
1702
+ fs.writeFileSync(
1703
+ this.messageStoreFilePath,
1704
+ JSON.stringify(storeData, null, 2),
1705
+ 'utf8'
1706
+ );
1707
+
1708
+ this._lastStoreSave = new Date();
1709
+ this._storeChangeCount = 0;
1710
+
1711
+ // console.log(`[MessageStore] Saved ${storeData.messages.length} messages to ${this.messageStoreFilePath}`);
1712
+
1713
+ return {
1714
+ success: true,
1715
+ path: this.messageStoreFilePath,
1716
+ messageCount: storeData.messages.length,
1717
+ savedAt: this._lastStoreSave
1718
+ };
1719
+ } catch (error) {
1720
+ console.error('[MessageStore] Error saving store:', error);
1721
+ return {
1722
+ success: false,
1723
+ error: error.message
1724
+ };
1725
+ }
1726
+ }
1727
+
1728
+ /**
1729
+ * Load the message store from a JSON file
1730
+ * @returns {Promise<{success: boolean, messageCount: number}>}
1731
+ */
1732
+ async loadMessageStore() {
1733
+ try {
1734
+ if (!fs.existsSync(this.messageStoreFilePath)) {
1735
+ // console.log('[MessageStore] No saved store file found');
1736
+ return { success: false, reason: 'file_not_found' };
1737
+ }
1738
+
1739
+ const fileContent = fs.readFileSync(this.messageStoreFilePath, 'utf8');
1740
+ const storeData = JSON.parse(fileContent);
1741
+
1742
+ // Validate data structure
1743
+ if (!storeData.messages || !Array.isArray(storeData.messages)) {
1744
+ throw new Error('Invalid store file format');
1745
+ }
1746
+
1747
+ // Clear existing store
1748
+ this.messageStore.clear();
1749
+
1750
+ // Load messages into the store
1751
+ let loadedCount = 0;
1752
+ for (const msgData of storeData.messages) {
1753
+ try {
1754
+ // Use the message store's internal handler to properly store messages
1755
+ const storeHandler = createMessageStoreHandler(this.messageStore);
1756
+ storeHandler({
1757
+ messages: [{
1758
+ key: msgData.key,
1759
+ message: msgData.message,
1760
+ messageTimestamp: msgData.messageTimestamp,
1761
+ pushName: msgData.pushName,
1762
+ broadcast: msgData.broadcast
1763
+ }],
1764
+ type: 'append'
1765
+ });
1766
+ loadedCount++;
1767
+ } catch (err) {
1768
+ console.error('[MessageStore] Error loading message:', err);
1769
+ }
1770
+ }
1771
+
1772
+ this._lastStoreSave = new Date(storeData.savedAt);
1773
+ this._storeChangeCount = 0;
1774
+
1775
+ // console.log(`[MessageStore] Loaded ${loadedCount}/${storeData.messages.length} messages from ${this.messageStoreFilePath}`);
1776
+
1777
+ this.emit('store-loaded', { messageCount: loadedCount });
1778
+
1779
+ return {
1780
+ success: true,
1781
+ messageCount: loadedCount,
1782
+ loadedFrom: storeData.savedAt
1783
+ };
1784
+ } catch (error) {
1785
+ console.error('[MessageStore] Error loading store:', error);
1786
+ return {
1787
+ success: false,
1788
+ error: error.message
1789
+ };
1790
+ }
1791
+ }
1792
+
1793
+ /**
1794
+ * Start auto-save timer
1795
+ * @private
1796
+ */
1797
+ _startAutoSave() {
1798
+ if (this._autoSaveTimer) {
1799
+ clearInterval(this._autoSaveTimer);
1800
+ }
1801
+
1802
+ if (this.autoSaveInterval > 0) {
1803
+ this._autoSaveTimer = setInterval(async () => {
1804
+ // Only save if there have been changes
1805
+ if (this._storeChangeCount > 0) {
1806
+ // console.log(`[MessageStore] Auto-saving (${this._storeChangeCount} changes since last save)`);
1807
+ await this.saveMessageStore();
1808
+ }
1809
+ }, this.autoSaveInterval);
1810
+
1811
+ // console.log(`[MessageStore] Auto-save enabled (interval: ${this.autoSaveInterval}ms)`);
1812
+ }
1813
+ }
1814
+
1815
+ /**
1816
+ * Stop auto-save timer
1817
+ * @private
1818
+ */
1819
+ _stopAutoSave() {
1820
+ if (this._autoSaveTimer) {
1821
+ clearInterval(this._autoSaveTimer);
1822
+ this._autoSaveTimer = null;
1823
+ // console.log('[MessageStore] Auto-save disabled');
1824
+ }
1825
+ }
1826
+
1827
+ /**
1828
+ * Increment the store change counter (called when messages are added)
1829
+ * @private
1830
+ */
1831
+ _incrementStoreChangeCount() {
1832
+ this._storeChangeCount++;
1833
+ }
1834
+
1538
1835
  // ═══════════════════════════════════════════════════════════
1539
1836
  // 📁 GROUP MANAGEMENT METHODS
1540
1837
  // ═══════════════════════════════════════════════════════════
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "innovators-bot2",
3
- "version": "2.0.2",
3
+ "version": "2.0.3",
4
4
  "description": "WhatsApp API",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -30,7 +30,7 @@
30
30
  },
31
31
  "homepage": "https://github.com/innovatorssoft/WhatsAppAPI?tab=readme-ov-file#whatsapp-api",
32
32
  "dependencies": {
33
- "@innovatorssoft/baileys": "^7.4.0",
33
+ "@innovatorssoft/baileys": "latest",
34
34
  "figlet": "^1.8.0",
35
35
  "mime": "^3.0.0",
36
36
  "mime-types": "^2.1.35",
@@ -39,4 +39,4 @@
39
39
  "qrcode-terminal": "^0.12.0",
40
40
  "wa-sticker-formatter": "^4.4.4"
41
41
  }
42
- }
42
+ }