@realvare/based 2.5.8 → 2.6.0

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
@@ -25,6 +25,60 @@
25
25
 
26
26
  </div>
27
27
 
28
+ ## Indice
29
+
30
+ - [Indice](#indice)
31
+ - [✨ Caratteristiche Principali](#-caratteristiche-principali)
32
+ - [🚀 Guida Rapida](#-guida-rapida)
33
+ - [Esempio Base - Avvio Bot](#esempio-base---avvio-bot)
34
+ - [Esempio Anti-Ban - Configurazione consigliata per Evitare Ban](#esempio-anti-ban---configurazione-consigliata-per-evitare-ban)
35
+ - [📊 Gestione Avanzata Cache](#-gestione-avanzata-cache)
36
+ - [Configurazione Cache Avanzata](#configurazione-cache-avanzata)
37
+ - [🔍 Risoluzione Problemi](#-risoluzione-problemi)
38
+ - [Problemi di Connessione](#problemi-di-connessione)
39
+ - [Gestione Memoria](#gestione-memoria)
40
+ - [Logging Avanzato](#logging-avanzato)
41
+ - [Gestione Messaggi Base con LID/JID](#gestione-messaggi-base-con-lidjid)
42
+ - [📚 Documentazione API](#-documentazione-api)
43
+ - [🏗️ Metodi Fondamentali](#️-metodi-fondamentali)
44
+ - [🎯 Eventi Principali](#-eventi-principali)
45
+ - [🎪 Messaggi e Funzionalità Interattive](#-messaggi-e-funzionalità-interattive)
46
+ - [Messaggi Base](#messaggi-base)
47
+ - [Testo con Formattazione](#testo-con-formattazione)
48
+ - [Media Base](#media-base)
49
+ - [Media Avanzati](#media-avanzati)
50
+ - [Messaggi Interattivi](#messaggi-interattivi)
51
+ - [Messaggi con Bottoni Semplici](#messaggi-con-bottoni-semplici)
52
+ - [Messaggi con Bottoni e Immagine](#messaggi-con-bottoni-e-immagine)
53
+ - [Messaggi Liste](#messaggi-liste)
54
+ - [Altri Messaggi](#altri-messaggi)
55
+ - [Gestione delle Risposte](#gestione-delle-risposte)
56
+ - [🎭 Funzionalità Gruppi](#-funzionalità-gruppi)
57
+ - [Gestione Base Gruppi](#gestione-base-gruppi)
58
+ - [Gestione Partecipanti](#gestione-partecipanti)
59
+ - [Impostazioni Gruppo](#impostazioni-gruppo)
60
+ - [Messaggi Gruppo Avanzati](#messaggi-gruppo-avanzati)
61
+ - [🔧 Fix LID/JID nel Proprio Main e Handler](#-fix-lidjid-nel-proprio-main-e-handler)
62
+ - [Best Practices per LID/JID](#best-practices-per-lidjid)
63
+ - [Esempio Integrato in Main](#esempio-integrato-in-main)
64
+ - [Esempio Handler Personalizzato](#esempio-handler-personalizzato)
65
+ - [🚀 Cache Intelligente LID/JID](#-cache-intelligente-lidjid)
66
+ - [🛡️ Validazione JID Avanzata](#️-validazione-jid-avanzata)
67
+ - [📊 Logging Condizionale](#-logging-condizionale)
68
+ - [🔧 Configurazione Performance](#-configurazione-performance)
69
+ - [🧩 Eventi: LID e JID sempre disponibili (nuovo)](#-eventi-lid-e-jid-sempre-disponibili-nuovo)
70
+ - [⚙️ Configurazione Avanzata](#️-configurazione-avanzata)
71
+ - [🔧 Opzioni Complete per makeWASocket](#-opzioni-complete-per-makewasocket)
72
+ - [🛡️ Sicurezza e Crittografia](#️-sicurezza-e-crittografia)
73
+ - [🌐 Supporto e Community](#-supporto-e-community)
74
+ - [📞 Contatti e Risorse](#-contatti-e-risorse)
75
+ - [🙏 Ringraziamenti](#-ringraziamenti)
76
+ - [⚠️ Disclaimer \& Licenza](#️-disclaimer--licenza)
77
+ - [📋 Nota Legale](#-nota-legale)
78
+ - [📜 Licenza MIT](#-licenza-mit)
79
+
80
+ ----
81
+
28
82
  ## ✨ Caratteristiche Principali
29
83
 
30
84
  <p align="center">
@@ -43,7 +97,7 @@ Questa libreria, basata su Baileys con miglioramenti specifici, offre un'API int
43
97
  </td>
44
98
  <td align="center" width="25%">
45
99
  <h3>💬 Messaggi</h3>
46
- <p>• Testo, media, interattivi<br>• Bottoni, liste, carousel<br>• Album, poll, reazioni<br>• Template avanzati</p>
100
+ <p>• Testo, media, interattivi<br>• Bottoni, liste, album<br>• Poll, reazioni<br>• Template avanzati</p>
47
101
  </td>
48
102
  <td align="center" width="25%">
49
103
  <h3>🛠️ Developer</h3>
@@ -330,79 +384,20 @@ Questa sezione espande i metodi principali, con esempi dettagliati e parametri.
330
384
 
331
385
  ### 🏗️ Metodi Fondamentali
332
386
 
333
- <details>
334
- <summary><strong>📡 makeWASocket(config)</strong></summary>
335
-
336
- Crea un'istanza del socket WhatsApp. È il punto di ingresso principale.
337
-
338
- **Parametri:**
339
- - `config`: Oggetto con opzioni (vedi sezione Configurazione Avanzata per dettagli completi).
340
-
341
- **Restituisce:** Istanza del socket con metodi come `sendMessage` e `ev` per eventi.
342
-
343
- **Esempio:**
344
- ```typescript
345
- const sock = makeWASocket({
346
- auth: state,
347
- printQRInTerminal: true,
348
- logger: console,
349
- browser: ['Varebot', 'Chrome', '4.0.0'],
350
- });
351
- ```
352
- </details>
353
- <details>
354
- <summary><strong>🔐 useMultiFileAuthState(folder)</strong></summary>
355
-
356
- Gestisce l'autenticazione persistente salvando credenziali in file multipli per sicurezza.
357
-
358
- **Parametri:**
359
- - `folder`: Stringa, path della cartella per i file di auth (es. 'auth_info').
360
-
361
- **Restituisce:**
362
- - `{ state, saveCreds }`: Stato autenticazione e funzione per salvare aggiornamenti.
363
-
364
- **Esempio:**
365
- ```typescript
366
- const { state, saveCreds } = await useMultiFileAuthState('auth_info');
367
- conn.ev.on('creds.update', saveCreds); // Integra nel socket
368
- ```
369
- </details>
370
-
371
- <details>
372
- <summary><strong>🔄 getSenderLid(message) & toJid(lid)</strong></summary>
373
-
374
- Utilità per gestire LID/JID, risolvendo problemi comuni in gruppi e multi-dispositivo.
375
-
376
- **getSenderLid(message):**
377
- - Estrae LID dal messaggio.
378
- - Restituisce: Oggetto con `lid` e altre info mittente.
379
-
380
- **toJid(lid):**
381
- - Converte LID in JID normalizzato (es. prende pn e aggiunge `@s.whatsapp.net`).
382
-
383
- **Esempio:**
384
- ```typescript
385
- const info = getSenderLid(msg);
386
- const jid = toJid(info.lid);
387
- conn.sendMessage(jid, { text: 'we ridin porsches in the rain' });
388
- ```
389
- </details>
390
-
391
- <details>
392
- <summary><strong>📤 sendMessage(jid, content, options)</strong></summary>
387
+ | Metodo | Descrizione | Import |
388
+ |--------|-------------|--------|
389
+ | `makeWASocket(config)` | **Core**: Crea socket WhatsApp | ✅ Incluso |
390
+ | `useMultiFileAuthState(folder)` | **Auth**: Gestione credenziali persistenti | Incluso |
391
+ | `getSenderLid(msg)` | **LID**: Estrae LID dal messaggio | ✅ Incluso |
392
+ | `toJid(lid)` | **JID**: Converte LID → JID | ✅ Incluso |
393
+ | `validateJid(jid)` | **Validazione**: Verifica JID | Incluso |
394
+ | `getCacheStats()` | **Performance**: Statistiche cache | ✅ Incluso |
395
+ | `clearCache()` | **Pulizia**: Svuota cache | Incluso |
396
+ | `setPerformanceConfig(config)` | **Config**: Personalizza performance | ✅ Incluso |
393
397
 
394
- Invia messaggi di vari tipi. Supporta testo, media, interattivi.
398
+ **🔥 Nota**: Tutti i metodi sopra sono **già pronti all'uso** e mostrati nella Guida Rapida. Passa direttamente alle sezioni avanzate per funzionalità specifiche!
395
399
 
396
- **Parametri:**
397
- - `jid`: Stringa JID del destinatario.
398
- - `content`: Oggetto messaggio (es. { text: 'finche vedo tutto violaviola' }).
399
- - `options`: Opzionale, include `quoted`, `mentions`, ecc.
400
-
401
- **Esempio Testo Semplice:**
402
- ```typescript
403
- await conn.sendMessage(jid, { text: 'bankai!' });
404
- ```
405
- </details>
400
+ ---
406
401
 
407
402
  ### 🎯 Eventi Principali
408
403
 
@@ -543,31 +538,6 @@ await conn.sendMessage(jid, {
543
538
  });
544
539
  ```
545
540
 
546
- ##### Carousel e Card Messages
547
- Il carousel è un tipo speciale di messaggio che permette di mostrare una serie di card scorrevoli.
548
- ```typescript
549
- await conn.sendMessage(jid, {
550
- text: '〖 🌸 〗 Benvenuto in VareBot!',
551
- title: '',
552
- footer: '',
553
- cards: [
554
- {
555
- image: { url: 'https://i.ibb.co/hJW7WwxV/varebot.jpg' },
556
- title: 'by sam aka vare',
557
- body: '〖 💫 〗 Esplora funzionalità\n〖 🚀 〗 Bot aggiornato',
558
- footer: '˗ˏˋ ☾ 𝚟𝚊𝚛𝚎𝚋𝚘𝚝 ☽ ˎˊ˗',
559
- buttons: [
560
- { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: 'Sito VareBot', url: 'https://varebot.netlify.app' }) },
561
- { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: '💻 GitHub', url: 'https://github.com/realvare' }) },
562
- { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: '💬 WhatsApp', url: 'https://wa.me/393476686131' }) },
563
- { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: '📸 Instagram', url: 'https://instagram.com/samakavare' }) },
564
- { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: '📧 Email', url: 'mailto:samakavare1@gmail.com' }) },
565
- ],
566
- },
567
- ],
568
- }, { quoted: m });
569
- ```
570
-
571
541
  #### Altri Messaggi
572
542
  ```typescript
573
543
  // Messaggio con citazione
@@ -849,6 +819,15 @@ await conn.groupAcceptInvite(code);
849
819
  // Ottenere info gruppo da link
850
820
  const groupInfo = await conn.groupGetInviteInfo('https://chat.whatsapp.com/ABC123');
851
821
 
822
+ // Ascolta modifiche impostazioni
823
+ conn.ev.on('group-settings.update', async ({ id, announce, restrict }) => {
824
+ if (announce !== undefined) {
825
+ await conn.sendMessage(id, { text: `Il gruppo è stato impostato come ${announce ? 'solo admin' : 'tutti'}` });
826
+ }
827
+ if (restrict !== undefined) {
828
+ await conn.sendMessage(id, { text: `Le info gruppo possono essere modificate da ${restrict ? 'solo admin' : 'tutti'}` });
829
+ }
830
+ });
852
831
  ```
853
832
 
854
833
  #### Messaggi Gruppo Avanzati
@@ -871,24 +850,8 @@ await conn.sendMessage(jid, {
871
850
  isForwarded: true
872
851
  }
873
852
  });
874
-
875
853
  ```
876
854
 
877
- // Ascolta modifiche impostazioni
878
- conn.ev.on('group-settings.update', async ({ jid, announce, restrict }) => {
879
- if(announce !== undefined) {
880
- await conn.sendMessage(jid, {
881
- text: `Il gruppo è stato impostato come ${announce ? 'solo admin' : 'tutti'}`
882
- });
883
- }
884
- if(restrict !== undefined) {
885
- await conn.sendMessage(jid, {
886
- text: `Le info gruppo possono essere modificate da ${restrict ? 'solo admin' : 'tutti'}`
887
- });
888
- }
889
- });
890
- ```
891
- ```
892
855
  ---
893
856
 
894
857
  ## 🔧 Fix LID/JID nel Proprio Main e Handler
@@ -1019,8 +982,6 @@ conn.ev.on('messages.upsert', async ({ messages }) => {
1019
982
 
1020
983
  ### Esempio Handler Personalizzato
1021
984
 
1022
- Crea un handler separato per modularità:
1023
-
1024
985
  ```typescript
1025
986
  // handler.js
1026
987
  export async function handleMessage(sock, msg) {
@@ -1285,4 +1246,4 @@ Vedi [LICENSE](LICENSE) per dettagli.
1285
1246
  <br>
1286
1247
  <img src="https://capsule-render.vercel.app/api?type=waving&color=gradient&customColorList=24&height=120&section=footer&text=&fontSize=30&fontColor=ffffff&animation=fadeIn&fontAlignY=35"/>
1287
1248
 
1288
- </div>
1249
+ </div>
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": [2, 3000, 1023888953]
3
- }
2
+ "version": [2, 3000, 1029001831]
3
+ }
@@ -42,7 +42,17 @@ const sender_key_record_1 = require("./Group/sender-key-record");
42
42
  const Group_1 = require("./Group");
43
43
  function makeLibSignalRepository(auth) {
44
44
  const storage = signalStorage(auth);
45
+ const lidMapping = {
46
+ get: async (lid) => {
47
+ const { [lid]: pn } = await auth.keys.get('lid-mapping', [lid]);
48
+ return pn;
49
+ },
50
+ set: (lid, pn) => {
51
+ return auth.keys.set({ 'lid-mapping': { [lid]: pn } });
52
+ }
53
+ };
45
54
  return {
55
+ lidMapping,
46
56
  decryptGroupMessage({ group, authorJid, msg }) {
47
57
  const senderName = jidToSignalSenderKeyName(group, authorJid);
48
58
  const cipher = new Group_1.GroupCipher(storage, senderName);
@@ -107,6 +117,17 @@ function makeLibSignalRepository(auth) {
107
117
  },
108
118
  jidToSignalProtocolAddress(jid) {
109
119
  return jidToSignalProtocolAddress(jid).toString();
120
+ },
121
+ getLidAddress(jid) {
122
+ const { user, device } = (0, WABinary_1.jidDecode)(jid);
123
+ return new libsignal.ProtocolAddress(user, device || 0);
124
+ },
125
+ getDeviceCanHandleLid() {
126
+ const { platform, pushname, verifiedName } = auth.creds;
127
+ if (platform === 'android' || platform === 'ios' || platform === 'smba' || platform === 'smbi') {
128
+ return true;
129
+ }
130
+ return false;
110
131
  }
111
132
  };
112
133
  }
@@ -640,12 +640,25 @@ const makeMessagesRecvSocket = (config) => {
640
640
  }
641
641
  }
642
642
  else {
643
+ // Log ACK status changes for monitoring
644
+ ids.forEach(id => {
645
+ const statusName = Object.keys(WAProto_1.proto.WebMessageInfo.Status)[status] || `UNKNOWN_${status}`;
646
+ logger.debug({ remoteJid, id, status: statusName }, 'ACK status update');
647
+ });
643
648
  ev.emit('messages.update', ids.map(id => ({
644
649
  key: { ...key, id },
645
650
  update: { status }
646
651
  })));
647
652
  }
648
653
  }
654
+ // Emit SERVER_ACK for error status to fix stuck ACKs
655
+ if (status === WAProto_1.proto.WebMessageInfo.Status.ERROR) {
656
+ ev.emit('messages.update', ids.map(id => ({
657
+ key: { ...key, id },
658
+ update: { status: WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK }
659
+ })));
660
+ }
661
+
649
662
  if (attrs.type === 'retry') {
650
663
  // correctly set who is asking for the retry
651
664
  key.participant = key.participant || attrs.from;
@@ -1041,6 +1054,22 @@ const makeMessagesRecvSocket = (config) => {
1041
1054
  logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1042
1055
  }
1043
1056
  });
1057
+
1058
+ // Retry logic for stuck pending messages
1059
+ ev.on('messages.update', (updates) => {
1060
+ updates.forEach(update => {
1061
+ if (update.update.status === WAProto_1.proto.WebMessageInfo.Status.PENDING &&
1062
+ Date.now() - (update.update.timestamp || 0) > 30000) { // 30 seconds
1063
+ logger.debug({ key: update.key }, 'retrying stuck pending message');
1064
+ // Retry by re-sending the message
1065
+ getMessage(update.key).then(msg => {
1066
+ if (msg) {
1067
+ relayMessage(update.key.remoteJid, msg, { messageId: update.key.id });
1068
+ }
1069
+ }).catch(err => logger.error({ err, key: update.key }, 'failed to retry stuck message'));
1070
+ }
1071
+ });
1072
+ });
1044
1073
  return {
1045
1074
  ...sock,
1046
1075
  sendMessageAck,
@@ -15,6 +15,7 @@ const link_preview_1 = require("../Utils/link-preview");
15
15
  const WABinary_1 = require("../WABinary");
16
16
  const WAUSync_1 = require("../WAUSync");
17
17
  const newsletter_1 = require("./newsletter");
18
+ const rate_limiter_1 = __importDefault(require("../Utils/rate-limiter"));
18
19
  const makeMessagesSocket = (config) => {
19
20
  const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, } = config;
20
21
  const sock = (0, newsletter_1.makeNewsletterSocket)(config);
@@ -23,6 +24,9 @@ const makeMessagesSocket = (config) => {
23
24
  stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
24
25
  useClones: false
25
26
  });
27
+
28
+ // Initialize rate limiter for anti-ban protection
29
+ const rateLimiter = new rate_limiter_1.default(1); // 1 message per second default
26
30
  let mediaConn;
27
31
  const refreshMediaConn = async (forceGet = false) => {
28
32
  const media = await mediaConn;
@@ -1074,7 +1078,7 @@ const makeMessagesSocket = (config) => {
1074
1078
  const results = [];
1075
1079
  for (const adminJid of adminJids) {
1076
1080
  try {
1077
- const result = await sendMessageInternal(adminJid, contentCopy, options);
1081
+ const result = await rateLimiter.add(() => sendMessageInternal(adminJid, contentCopy, options));
1078
1082
  results.push(result);
1079
1083
  } catch (error) {
1080
1084
  console.warn(`Failed to send admin-only message to ${adminJid}:`, error);
@@ -1392,7 +1396,7 @@ const makeMessagesSocket = (config) => {
1392
1396
  }
1393
1397
 
1394
1398
 
1395
- await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, statusJidList: options.statusJidList });
1399
+ await rateLimiter.add(() => relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, statusJidList: options.statusJidList }));
1396
1400
  if (config.emitOwnEvents) {
1397
1401
  process.nextTick(() => {
1398
1402
  processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));