@realvare/based 2.5.2 → 2.5.5

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,829 +1,1194 @@
1
- <div align="center">
2
-
3
- # 🌌 Based - by Sam aka vare
4
-
5
-
6
- <p align="center">
7
-   <img src="https://img.shields.io/badge/Licenza-MIT-8a2be2.svg?style=for-the-badge&labelColor=2d1b69" alt="Licenza: MIT"/>
8
-   <img src="https://img.shields.io/github/stars/realvare/based?style=for-the-badge&color=8a2be2&labelColor=2d1b69" alt="GitHub stelle"/>
9
-   <img src="https://img.shields.io/github/forks/realvare/based?style=for-the-badge&color=8a2be2&labelColor=2d1b69" alt="GitHub Forks"/>
10
- </p>
11
- <div align="center">
12
- <p align="center">
13
-   <strong>💜 Una libreria WhatsApp Web API moderna, potente e veloce con supporto avanzato per LID/JID</strong>
14
- </p>
15
-
16
- <p align="center">
17
-   <a href="#-caratteristiche-principali">Caratteristiche</a> •
18
-   <a href="#-installazione">Installazione</a> •
19
-   <a href="#-guida-rapida">Guida Rapida</a> •
20
-   <a href="#-documentazione-api">Documentazione API</a>
21
-   <a href="#-messaggi-interattivi-e-bottoni">Messaggi Interattivi</a>
22
-   <a href="#-fix-lidjid">Fix LID/JID</a> •
23
-   <a href="#-configurazione-avanzata">Configurazione Avanzata</a> •
24
-   <a href="#-supporto-e-community">Supporto</a>
25
- </p>
26
-
27
- </div>
28
-
29
- ---
30
-
31
- ## Caratteristiche Principali
32
-
33
- Questa libreria, basata su Baileys con miglioramenti specifici, offre un'API intuitiva per interagire con WhatsApp Web. Ecco un riassunto delle funzionalità chiave:
34
-
35
- | Categoria | Dettagli |
36
- |-----------|----------|
37
- | **Core Features** | - 🔄 Mappatura intelligente `@lid` e `@s.whatsapp.net` (JID)<br>- 📱 Supporto multi-dispositivo completo<br>- 🔒 Crittografia End-to-End nativa (Protocollo Signal)<br>- ⚡ Codebase TypeScript moderna e ottimizzata |
38
- | **Messaggi e Interazioni** | - 💬 Gestione avanzata di messaggi testo, media e interattivi<br>- 🎛️ Supporto per bottoni, liste, carousel e template<br>- 🖼️ Invio di album, poll e reazioni |
39
- | **Developer Experience** | - 📡 Eventi real-time per connessioni e messaggi<br>- 🛡️ Tipizzazioni TypeScript complete<br>- 📖 Documentazione estesa con esempi<br>- 🔧 API semplici e estendibili |
40
-
41
- ---
42
-
43
- ## 🚀 Guida Rapida
44
-
45
- Inizia creando un bot semplice. Questa sezione include esempi base per l'autenticazione e la gestione delle connessioni.
46
-
47
- ### Esempio Base - Avvio Bot
48
-
49
- ```typescript
50
- import makeWASocket, { DisconnectReason, useMultiFileAuthState, getPerformanceConfig, setPerformanceConfig } from 'based';
51
-
52
- // Configura performance e cache
53
- setPerformanceConfig({
54
-     performance: {
55
-         enableCache: true,
56
-         enableMetrics: true
57
-     },
58
-     debug: {
59
-         enableLidLogging: true,
60
-         logLevel: 'info'
61
-     }
62
- });
63
-
64
- async function startBot() {
65
-   // 🔐 Setup autenticazione multi-file per sessioni persistenti
66
-   const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
67
-   
68
-   // 🌐 Creazione del socket con configurazione base
69
-   const sock = makeWASocket({
70
-     auth: state,
71
-     printQRInTerminal: true, // Stampa QR nel terminale per scansione
72
-     logger: console,
73
-     browser: ['VareBot', 'Chrome', '4.0.0'], // Simula un browser
74
-   });
75
-
76
-   // 📡 Gestione aggiornamenti connessione
77
-   conn.ev.on('connection.update', (update) => {
78
-     const { connection, lastDisconnect } = update;
79
-     
80
-     if (connection === 'close') {
81
-       const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
82
-       console.log('🔴 Connessione chiusa:', lastDisconnect?.error, 'Riconnessione:', shouldReconnect);
83
-       
84
-       if (shouldReconnect) {
85
-         startBot(); // Riconnessione automatica
86
-       }
87
-     } else if (connection === 'open') {
88
-       console.log('🟢 Connesso con successo!');
89
-     }
90
-   });
91
-
92
-   // 💾 Salva credenziali automaticamente
93
-   conn.ev.on('creds.update', saveCreds);
94
- }
95
-
96
- startBot().catch(console.error);
97
- ```
98
-
99
- ### Gestione Messaggi Base con LID/JID
100
-
101
- ```typescript
102
- import makeWASocket, { getSenderLid, toJid, getCacheStats, validateJid, Logger } from 'based';
103
-
104
- // ... (codice di creazione sock qui)
105
-
106
- conn.ev.on('messages.upsert', ({ messages }) => {
107
-   for (const msg of messages) {
108
-     // 🔍 Estrai LID del mittente con validazione
109
-     const info = getSenderLid(msg);
110
-     
111
-     // ✅ Valida JID prima di usarlo
112
-     const validation = validateJid(info.jid);
113
-     if (!validation.isValid) {
114
-       Logger.error('JID non valido:', validation.error);
115
-       continue;
116
-     }
117
-     
118
-     const jid = toJid(info.lid); // Normalizza in JID
119
-     
120
-     Logger.info('💬 Messaggio da:', jid, 'Valid:', info.isValid);
121
-     console.log('📝 Contenuto:', msg.message?.conversation);
122
-     
123
-     // Rispondi automaticamente solo se valido
124
-     if (info.isValid) {
125
-       conn.sendMessage(jid, { text: 'Messaggio ricevuto!' });
126
-     }
127
-   }
128
-   
129
-   // 📊 Monitora performance cache
130
-   const stats = getCacheStats();
131
-   Logger.performance('Cache stats:', stats);
132
- });
133
- ```
134
-
135
- ---
136
-
137
- ## 📚 Documentazione API
138
-
139
- Questa sezione espande i metodi principali, con esempi dettagliati e parametri. Tutti i metodi sono tipizzati in TypeScript per un'esperienza di sviluppo sicura.
140
-
141
- ### 🏗️ Metodi Fondamentali
142
-
143
- <details>
144
- <summary><strong>📡 makeWASocket(config)</strong></summary>
145
-
146
- Crea un'istanza del socket WhatsApp. È il punto di ingresso principale.
147
-
148
- **Parametri:**
149
- - `config`: Oggetto con opzioni (vedi sezione Configurazione Avanzata per dettagli completi).
150
-
151
- **Restituisce:** Istanza del socket con metodi come `sendMessage` e `ev` per eventi.
152
-
153
- **Esempio:**
154
- ```typescript
155
- const sock = makeWASocket({
156
-   auth: state,
157
-   printQRInTerminal: true,
158
-   logger: console,
159
-   browser: ['Varebot', 'Chrome', '4.0.0'],
160
- });
161
- ```
162
- </details>
163
-
164
- <details>
165
- <summary><strong>🔐 useMultiFileAuthState(folder)</strong></summary>
166
-
167
- Gestisce l'autenticazione persistente salvando credenziali in file multipli per sicurezza.
168
-
169
- **Parametri:**
170
- - `folder`: Stringa, path della cartella per i file di auth (es. 'auth_info').
171
-
172
- **Restituisce:**
173
- - `{ state, saveCreds }`: Stato autenticazione e funzione per salvare aggiornamenti.
174
-
175
- **Esempio:**
176
- ```typescript
177
- const { state, saveCreds } = await useMultiFileAuthState('auth_info');
178
- conn.ev.on('creds.update', saveCreds); // Integra nel socket
179
- ```
180
- </details>
181
-
182
- <details>
183
- <summary><strong>🔄 getSenderLid(message) & toJid(lid)</strong></summary>
184
-
185
- Utilità per gestire LID/JID, risolvendo problemi comuni in gruppi e multi-dispositivo.
186
-
187
- **getSenderLid(message):**
188
- - Estrae LID dal messaggio.
189
- - Restituisce: Oggetto con `lid` e altre info mittente.
190
-
191
- **toJid(lid):**
192
- - Converte LID in JID normalizzato (es. aggiunge `@s.whatsapp.net`).
193
-
194
- **Esempio:**
195
- ```typescript
196
- const info = getSenderLid(msg);
197
- const jid = toJid(info.lid);
198
- conn.sendMessage(jid, { text: 'Risposta personalizzata' });
199
- ```
200
- </details>
201
-
202
- <details>
203
- <summary><strong>📤 sendMessage(jid, content, options)</strong></summary>
204
-
205
- Invia messaggi di vari tipi. Supporta testo, media, interattivi.
206
-
207
- **Parametri:**
208
- - `jid`: Stringa JID del destinatario.
209
- - `content`: Oggetto messaggio (es. { text: 'Ciao' }).
210
- - `options`: Opzionale, include `quoted`, `mentions`, ecc.
211
-
212
- **Esempio Testo Semplice:**
213
- ```typescript
214
- await conn.sendMessage(jid, { text: 'Ciao Mondo!' });
215
- ```
216
- </details>
217
-
218
- ### 🎯 Eventi Principali
219
-
220
- | Evento              | Descrizione                          | Callback Signature          |
221
- |---------------------|--------------------------------------|-----------------------------|
222
- | `connection.update` | Aggiornamenti stato connessione     | `(update: Partial<ConnectionState>) => void` |
223
- | `creds.update`      | Aggiornamento credenziali           | `() => void`                |
224
- | `messages.upsert`   | Nuovi messaggi o aggiornamenti       | `({ messages: WAMessage[], type: MessageUpsertType }) => void` |
225
- | `messages.update`   | Modifiche a messaggi esistenti       | `(update: WAMessageUpdate[]) => void` |
226
- | `group-participants.update` | Cambiamenti partecipanti gruppo | `(update: GroupParticipantEvent) => void` |
227
-
228
- **Esempio Registrazione Evento:**
229
- ```typescript
230
- conn.ev.on('group-participants.update', (update) => {
231
-   console.log('Partecipante aggiornato:', update);
232
- });
233
- ```
234
-
235
- ---
236
-
237
- ## 🎪 Messaggi Interattivi e Bottoni
238
-
239
- ### Metodi per Messaggi Non Interattivi
240
-
241
- Questi metodi inviano contenuti semplici senza elementi cliccabili.
242
-
243
- #### Messaggi di Testo
244
- Invia un messaggio di testo semplice, con supporto per menzioni.
245
-
246
- ```typescript
247
- await conn.sendMessage(jid,
248
-   text: 'finchevedotuttoviolaviola', 
249
-   mentions: ['393476686131@s.whatsapp.net'] 
250
- });
251
- ```
252
-
253
- #### Messaggi Immagine
254
- Invia un'immagine con caption opzionale.
255
-
256
- ```typescript
257
- await conn.sendMessage(jid, { 
258
-   image: { url: 'https://i.ibb.co/hJW7Wwx/varebot.jpg' }, 
259
-   caption: 'out soon!' 
260
- });
261
- ```
262
-
263
- #### Messaggi Video
264
- Invia un video con caption e mimetype.
265
-
266
- ```typescript
267
- await conn.sendMessage(jid, { 
268
-   video: { url: 'https://example.com/video.mp4' }
269
-   caption: 'peak!', 
270
-   mimetype: 'video/mp4' 
271
- });
272
- ```
273
-
274
- #### Messaggi Audio
275
- Invia un file audio (nota vocale o file).
276
-
277
- ```typescript
278
- await conn.sendMessage(jid,
279
-   audio: { url: 'https://esempio.com/audio.ogg' }, 
280
-   mimetype: 'audio/ogg; codecs=opus' 
281
- });
282
- ```
283
-
284
- #### Messaggi Documento
285
- Invia un documento con titolo e descrizione.
286
-
287
- ```typescript
288
- await conn.sendMessage(jid, { 
289
-   document: { url: 'https://esempio.com/file.pdf' }, 
290
-   mimetype: 'application/pdf', 
291
-   fileName: 'documento.pdf', 
292
-   fileLength: 1024 
293
- });
294
- ```
295
-
296
- #### Messaggi Sticker
297
- Invia uno sticker (animato o statico).
298
-
299
- ```typescript
300
- await conn.sendMessage(jid,
301
-   sticker: { url: 'https://i.ibb.co/4nxpDtTS/shhh2.webp' }, 
302
-   mimetype: 'image/webp' 
303
- });
304
- ```
305
-
306
- #### Messaggi Posizione
307
- Invia una posizione geografica.
308
-
309
- ```typescript
310
- await conn.sendMessage(jid, { 
311
-   location: { 
312
-     degreesLatitude: 45.4642, 
313
-     degreesLongitude: 9.1900, 
314
-     name: 'Milano, Italia' 
315
-   } 
316
- });
317
- ```
318
-
319
- #### Messaggi Contatto
320
- Invia un vCard di un contatto.
321
-
322
- ```typescript
323
- await conn.sendMessage(jid,
324
-   contacts: { 
325
-     displayName: 'Sam aka vare', 
326
-     contacts: [{ vcard: 'BEGIN:VCARD\nVERSION:3.0\nFN:Sam\nTEL;waid=393476686131:+39 347 6686131\nEND:VCARD' }] 
327
-   } 
328
- });
329
- ```
330
-
331
- #### Messaggi Poll (Sondaggio)
332
- Invia un sondaggio con opzioni.
333
-
334
- ```typescript
335
- await conn.sendMessage(jid, { 
336
-   poll:
337
-     name: 'Anime preferito?', 
338
-     values: ['Aot', 'Bleach', 'Death note'], 
339
-     selectableCount: 1 // quante scelte possibili
340
-   } 
341
- });
342
- ```
343
-
344
- #### Reazioni ai Messaggi
345
- Aggiunge una reazione a un messaggio esistente.
346
-
347
- ```typescript
348
- await conn.sendMessage(jid, { 
349
-   react: { 
350
-     text: '🍥'
351
-     key: msg.key  // Key del messaggio da reagire
352
-   } 
353
- });
354
- ```
355
-
356
- #### Album (Multi-Media)
357
- Invia un album di immagini/video misti.
358
-
359
- ```typescript
360
- await conn.sendMessage(jid, {
361
-   album: [
362
-     { image: { url: 'img1.jpg' }, caption: 'Foto 1' },
363
-     { video: { url: 'vid1.mp4' }, caption: 'Video 1' },
364
-   ],
365
- });
366
- ```
367
-
368
- ### Metodi per Messaggi Interattivi
369
-
370
- Questi messaggi includono elementi interattivi come bottoni, liste e template.
371
-
372
- #### Messaggi con Bottoni Semplici
373
- Invia bottoni di risposta rapida.
374
-
375
- ```typescript
376
- await conn.sendMessage(jid, {
377
-   text: 'Scegli un\'opzione:',
378
-   footer: 'Footer',
379
-   buttons: [
380
-     { buttonId: 'cmd1', buttonText: { displayText: 'testo1' }, type: 1 },
381
-     { buttonId: 'cmd2', buttonText: { displayText: 'testo2' }, type: 1 },
382
-   ],
383
-   headerType: 1,
384
- });
385
- ```
386
-
387
- #### Messaggi con Bottoni e Immagine
388
- Combina immagine con bottoni.
389
-
390
- ```typescript
391
- await conn.sendMessage(jid, {
392
-   image: { url: 'https://i.ibb.co/hJW7Wwx/varebot.jpg' },
393
-   caption: 'Messaggio con bottoni e immagine',
394
-   footer: 'vare bot',
395
-   buttons: [
396
-     { buttonId: 'cmd', buttonText: { displayText: 'testo1' }, type: 1 },
397
-   ],
398
- });
399
- ```
400
-
401
- #### Messaggi Liste (Sezioni)
402
- Invia una lista di opzioni (solo in privato).
403
-
404
- ```typescript
405
- await conn.sendMessage(jid, {
406
-   text: 'Questa è una lista!',
407
-   footer: 'purplepurplepurple!',
408
-   title: 'Titolo Lista',
409
-   buttonText: 'Visualizza Lista',
410
-   sections: [
411
-     { 
412
-       title: 'Sezione 1', 
413
-       rows:
414
-         { title: 'Opzione 1', rowId: 'opt1' }
415
-         { title: 'Opzione 2', rowId: 'opt2', description: 'Descrizione' } 
416
-       ] 
417
-     },
418
-   ],
419
- });
420
- ```
421
-
422
- #### Messaggi Carousel (Cards)
423
- Invia un carousel di carte con bottoni URL.
424
-
425
- ```typescript
426
- await conn.sendMessage(jid, {
427
-   text: '〖 🌸 〗 Benvenuto in VareBot!',
428
-   title: '',
429
-   footer: '',
430
-   cards: [
431
-     {
432
-       image: { url: 'https://i.ibb.co/hJW7Wwx/varebot.jpg' },
433
-       title: 'by sam aka vare',
434
-       body: '〖 💫 〗 Esplora funzionalità\n〖 🚀 〗 Bot aggiornato',
435
-       footer: '˗ˏˋ ☾ 𝚟𝚊𝚛𝚎𝚋𝚘𝚝 ☽ ˎˊ˗',
436
-       buttons: [
437
-         { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: 'Sito VareBot', url: 'https://varebot.netlify.app' }) },
438
-         { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: '💻 GitHub', url: 'https://github.com/realvare' }) },
439
-         { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: '💬 WhatsApp', url: 'https://wa.me/393476686131' }) },
440
-         { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: '📸 Instagram', url: 'https://instagram.com/samakavare' }) },
441
-         { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: '📧 Email', url: 'mailto:samakavare1@gmail.com' }) },
442
-       ],
443
-     },
444
-   ],
445
- }, { quoted: m });
446
- ```
447
-
448
- > **Nota:** Per tutti i messaggi interattivi, assicurati di gestire le risposte nei listener `messages.upsert` verificando `msg.message.buttonsResponseMessage` o simili per estrarre le selezioni.
449
-
450
- ---
451
-
452
- ## 🔧 Fix LID/JID nel Proprio Main e Handler
453
-
454
- Il supporto LID/JID è un punto di forza di questa libreria, risolvendo problemi comuni come l'identificazione mittenti in gruppi e multi-dispositivo. Ecco come integrarlo nel tuo codice principale e handler, basandomi sui metodi estratti dai file forniti (main.js, handler.js e print.js).
455
-
456
- ### Best Practices per LID/JID
457
-
458
- - **decodeJid(jid)**: Funzione principale per normalizzare JID/LID. Gestisce:
459
- - Formati con `:\d+@` (usa `jidNormalizedUser`).
460
- - Decodifica user/server in `${user}@${server}`.
461
- - Converti `@lid` in `@s.whatsapp.net`.
462
-
463
- **Esempio di Implementazione (da main.js):**
464
- ```typescript
465
- decodeJid: (jid) => {
466
- if (!jid) return jid;
467
- let decoded = jid;
468
- if (/:\d+@/gi.test(jid)) {
469
- decoded = jidNormalizedUser(jid);
470
- }
471
- if (typeof decoded === 'object' && decoded.user && decoded.server) {
472
- decoded = `${decoded.user}@${decoded.server}`;
473
- }
474
- if (decoded.endsWith('@lid')) {
475
- decoded = decoded.replace('@lid', '@s.whatsapp.net');
476
- }
477
- return decoded;
478
- },
479
- ```
480
- Usa `conn.decodeJid(jid)` ovunque per normalizzare IDs (es. sender, participant, quoted).
481
-
482
- - **Monkey-Patch per groupParticipantsUpdate**: Corregge aggiornamenti partecipanti gruppo trovando il JID reale dal metadata.
483
-
484
- **Esempio (da handler.js):**
485
- ```typescript
486
- if (!this.originalGroupParticipantsUpdate) {
487
- this.originalGroupParticipantsUpdate = this.groupParticipantsUpdate;
488
- this.groupParticipantsUpdate = async function(chatId, users, action) {
489
- try {
490
- let metadata = global.groupCache.get(chatId);
491
- if (!metadata) {
492
- metadata = await fetchGroupMetadataWithRetry(this, chatId);
493
- if (metadata) global.groupCache.set(chatId, metadata);
494
- }
495
- if (!metadata) {
496
- console.error('[ERRORE] Nessun metadato del gruppo disponibile per un aggiornamento sicuro');
497
- return this.originalGroupParticipantsUpdate.call(this, chatId, users, action);
498
- }
499
-
500
- const correctedUsers = users.map(userJid => {
501
- const decoded = this.decodeJid(userJid);
502
- const phone = decoded.split('@')[0].split(':')[0];
503
- const participant = metadata.participants.find(p => {
504
- const pId = this.decodeJid(p.id || p.jid || '');
505
- const pPhone = pId.split('@')[0].split(':')[0];
506
- return pPhone === phone;
507
- });
508
- return participant ? participant.id : userJid; // Fallback all'originale se non trovato
509
- });
510
-
511
- return this.originalGroupParticipantsUpdate.call(this, chatId, correctedUsers, action);
512
- } catch (e) {
513
- console.error('[ERRORE] Errore in safeGroupParticipantsUpdate:', e);
514
- throw e;
515
- }
516
- };
517
- }
518
- ```
519
-
520
- - **Cache per Metadata Gruppo e Admin**: Usa NodeCache per memorizzare metadata e admin, normalizzando con `decodeJid`.
521
-
522
- **Esempio (da handler.js):**
523
- ```typescript
524
- global.groupCache = new NodeCache({ stdTTL: 5 * 60, useClones: false });
525
- global.adminCache = new NodeCache({ stdTTL: 5 * 60, useClones: false });
526
-
527
- // In participantsUpdate o groups.update:
528
- metadata.participants.forEach(u => {
529
- const normId = this.decodeJid(u.id);
530
- const jid = u.jid || normId;
531
- if (u.admin === 'admin' || u.admin === 'superadmin') {
532
- adminSet.add(jid);
533
- if (jid !== normId) adminSet.add(normId);
534
- }
535
- });
536
- metadata.admins = Array.from(adminSet);
537
- global.groupCache.set(update.id, metadata);
538
- ```
539
-
540
- - **Normalizzazione in Print/Log**: Rimuovi `:xx` dai numeri telefono per clean display.
541
-
542
- **Esempio (da print.js):**
543
- ```typescript
544
- function formatPhoneNumber(jid, name) {
545
- if (!jid) return 'Sconosciuto';
546
- let userPart = jid.split('@')[0];
547
- let cleanNumber = userPart.split(':')[0]; // Rimuovi la parte :xx per ottenere il numero reale
548
- try {
549
- const number = PhoneNumber('+' + cleanNumber).getNumber('international');
550
- return number + (name ? ` ~${name}` : '');
551
- } catch {
552
- return (cleanNumber || '') + (name ? ` ~${name}` : '');
553
- }
554
- }
555
- ```
556
-
557
- - **Problemi Comuni e Fix:**
558
- - **LID Mancante in Gruppi:** Usa `decodeJid` e cache metadata per trovare JID reali.
559
- - **Conversione JID:** Sempre applica `decodeJid` prima di `sendMessage` o query.
560
- - **Multi-Dispositivo:** Imposta `syncFullHistory: true` in config per sync LID.
561
- - **Errori in Mention/Quoted:** Normalizza con `decodeJid` in handler per quoted.sender e mentionedJid.
562
-
563
- ### Esempio Integrato in Main
564
-
565
- ```typescript
566
- // Nel tuo file main
567
- import makeWASocket, { getSenderLid, toJid } from 'based';
568
- // ... (autenticazione e creazione sock)
569
-
570
- conn.ev.on('messages.upsert', async ({ messages }) => {
571
-   const msg = messages[0];
572
-   if (!msg.message) return;
573
-
574
-   const info = getSenderLid(msg);
575
-   const senderJid = toJid(info.lid); // Fix LID -> JID
576
-
577
-   // Esempio: Rispondi solo se JID valido
578
-   if (senderJid.endsWith('@s.whatsapp.net')) {
579
-     await conn.sendMessage(senderJid, { text: `Ciao da ${senderJid}!` }, { quoted: msg });
580
-   }
581
- });
582
- ```
583
-
584
- ### Esempio Handler Personalizzato
585
-
586
- Crea un handler separato per modularità:
587
-
588
- ```typescript
589
- // handler.js
590
- export async function handleMessage(sock, msg) {
591
-   const info = getSenderLid(msg);
592
-   const jid = toJid(info.lid);
593
-   
594
-   // Log e risposta
595
-   console.log(`Messaggio da ${jid}`);
596
-   await conn.sendMessage(jid, { text: 'Handler attivato!' });
597
- }
598
-
599
- // Nel main: conn.ev.on('messages.upsert', ({ messages }) => handleMessage(sock, messages[0]));
600
- ```
601
-
602
- **Consiglio:** Testa in gruppi per verificare LID, poiché Baileys upstream ha migliorato il supporto nativo nel 2025, ma i fix personalizzati qui garantiscono retrocompatibilità.
603
-
604
- ---
605
-
606
- ## Nuove Funzionalità Performance (v2.5.0+)
607
-
608
- ### 🚀 Cache Intelligente LID/JID
609
-
610
- La libreria ora include un sistema di cache avanzato per ottimizzare le conversioni LID/JID:
611
-
612
- ```typescript
613
- import { getCacheStats, clearCache, setPerformanceConfig } from 'based';
614
-
615
- // Configura cache personalizzata
616
- setPerformanceConfig({
617
-     cache: {
618
-         lidCache: {
619
-             ttl: 10 * 60 * 1000, // 10 minuti
620
-             maxSize: 15000
621
-         }
622
-     }
623
- });
624
-
625
- // Monitora performance
626
- const stats = getCacheStats();
627
- console.log('Cache LID:', stats.lidCache.size, '/', stats.lidCache.maxSize);
628
-
629
- // Pulisci cache se necessario
630
- clearCache();
631
- ```
632
-
633
- ### 🛡️ Validazione JID Avanzata
634
-
635
- ```typescript
636
- import { validateJid, Logger } from 'based';
637
-
638
- const jid = '1234567890@s.whatsapp.net';
639
- const validation = validateJid(jid);
640
-
641
- if (validation.isValid) {
642
-     Logger.info('JID valido:', jid);
643
- } else {
644
-     Logger.error('JID non valido:', validation.error);
645
- }
646
- ```
647
-
648
- ### 📊 Logging Condizionale
649
-
650
- ```typescript
651
- import { Logger, setPerformanceConfig } from 'based';
652
-
653
- // Configura logging
654
- setPerformanceConfig({
655
-     debug: {
656
-         enableLidLogging: true,
657
-         enablePerformanceLogging: true,
658
-         logLevel: 'debug' // 'error', 'warn', 'info', 'debug'
659
-     }
660
- });
661
-
662
- // Usa logger condizionale
663
- Logger.debug('Debug info');
664
- Logger.performance('Performance metrics');
665
- Logger.error('Error occurred');
666
- ```
667
-
668
- ### 🔧 Configurazione Performance
669
-
670
- ```typescript
671
- import { setPerformanceConfig, getPerformanceConfig } from 'based';
672
-
673
- // Configurazione completa
674
- setPerformanceConfig({
675
-     performance: {
676
-         enableCache: true,
677
-         enableMetrics: true,
678
-         batchSize: 100,
679
-         maxRetries: 3
680
-     },
681
-     cache: {
682
-         lidCache: { ttl: 5 * 60 * 1000, maxSize: 10000 },
683
-         jidCache: { ttl: 5 * 60 * 1000, maxSize: 10000 }
684
-     },
685
-     debug: {
686
-         enableLidLogging: false,
687
-         logLevel: 'warn'
688
-     }
689
- });
690
-
691
- // Ottieni configurazione corrente
692
- const config = getPerformanceConfig();
693
- console.log('Cache abilitata:', config.performance.enableCache);
694
- ```
695
-
696
- ---
697
-
698
- ## 🧩 Eventi: LID e JID sempre disponibili (nuovo)
699
-
700
- Gli eventi emessi includono campi ausiliari sui messaggi per accedere facilmente sia al JID sia al LID del mittente/partecipante.
701
-
702
- ```typescript
703
- conn.ev.on('messages.upsert', ({ messages, type }) => {
704
- for (const msg of messages) {
705
- // Campi aggiuntivi su msg.key
706
- // - remoteJidNormalized: JID normalizzato (es. @s.whatsapp.net)
707
- // - remoteLid: LID equivalente del remoteJid
708
- // - participantLid: LID equivalente del participant (se presente)
709
- const jid = msg.key.remoteJidNormalized || msg.key.remoteJid;
710
- const remoteLid = msg.key.remoteLid;
711
- const participantLid = msg.key.participantLid;
712
-
713
- if (jid?.endsWith('@s.whatsapp.net')) {
714
- conn.sendMessage(jid, { text: `Ciao! LID: ${remoteLid || 'n/d'}` });
715
- }
716
- }
717
- });
718
- ```
719
-
720
- Questi campi eliminano ambiguità in gruppi e contesti multi-dispositivo dove alcuni eventi riportano LID, altri JID.
721
-
722
- ---
723
-
724
- ## ⚙️ Configurazione Avanzata
725
-
726
- Personalizza il socket per performance e comportamento.
727
-
728
- ### 🔧 Opzioni Complete per makeWASocket
729
-
730
- ```typescript
731
- const sock = makeWASocket({
732
-   // 🔐 Autenticazione
733
-   auth: state,
734
-   
735
-   // 🖥️ UI e Debug
736
-   printQRInTerminal: true,
737
-   logger: console, // Usa Pino per logging avanzato
738
-   browser: ['VareBot', 'Chrome', '4.0.0'],
739
-   
740
-   // ⏱️ Timeout e Connessione
741
-   defaultQueryTimeoutMs: 60000,
742
-   keepAliveIntervalMs: 30000,
743
-   connectTimeoutMs: 60000,
744
-   retryRequestDelayMs: 250,
745
-   maxMsgRetryCount: 5,
746
-   
747
-   // 🎛️ Comportamento
748
-   markOnlineOnConnect: true,
749
-   syncFullHistory: false, // Attiva per sync completo (consuma dati)
750
-   fireInitQueries: true,
751
-   generateHighQualityLinkPreview: true, // Anteprime link HD
752
- });
753
- ```
754
-
755
- ### 🛡️ Sicurezza e Crittografia
756
-
757
- | Caratteristica            | Descrizione                              |
758
- |---------------------------|------------------------------------------|
759
- | 🔐 End-to-End Encryption | Protocollo Signal per messaggi sicuri   |
760
- | 🔑 Key Management        | Generazione/rotazione automatica chiavi |
761
- | 🔍 Authentication        | Sicurezza tramite QR code o pairing code|
762
- | 🛡️ Data Protection       | Archiviazione sicura credenziali locali |
763
-
764
- ---
765
- <div align="center">
766
-
767
-
768
- ## 🌐 Supporto e Community
769
-
770
- Unisciti alla community per aiuto e contributi.
771
-
772
- ### 📞 Contatti e Risorse
773
-
774
- | Canale          | Link/Info                              |
775
- |-----------------|----------------------------------------|
776
- | **Email**       | [samakavare1@gmail.com](mailto:samakavare1@gmail.com) |
777
- | **GitHub Issues**| [Segnala Bug](https://github.com/realvare/based/issues) |
778
- | **PayPal**      | [Dona](https://www.paypal.me/samakavare) |
779
- | **Canale whatsapp**| [Canale](https://www.whatsapp.com/channel/0029VbB41Sa1Hsq1JhsC1Z1z) |
780
-
781
- ---
782
-
783
- ## 🙏 Ringraziamenti
784
-
785
- Grazie ai progetti che ispirano Based:
786
-
787
- | Progetto                  | Contributo                              |
788
- |---------------------------|-----------------------------------------|
789
- | [Baileys](https://github.com/WhiskeySockets/Baileys) | API WhatsApp Web originale             |
790
- | [Yupra](https://www.npmjs.com/package/@yupra/baileys) | Fix LID/JID avanzati                   |
791
- | [Signal Protocol](https://signal.org/) | Crittografia end-to-end                |
792
-
793
- ---
794
-
795
- ## ⚠️ Disclaimer & Licenza
796
-
797
- ### 📋 Nota Legale
798
-
799
- ⚠️ **Importante**: Non affiliato a WhatsApp Inc. o Meta. Uso educativo/sviluppo solo.
800
-
801
- 🛡️ **Uso Responsabile**: Evita spam, violazioni ToS WhatsApp. Rischio ban account.
802
-
803
- ### 📜 Licenza MIT
804
-
805
- MIT License © 2025 [realvare](https://github.com/realvare)
806
-
807
- Vedi [LICENSE](LICENSE) per dettagli.
808
-
809
- ---
810
-
811
- <div align="center">
812
-
813
- <img src="https://i.ibb.co/Cp0SQznC/sam2.png" width="160" height="160" alt="realvare profile picture"/>
814
-
815
- ### Creato da [realvare](https://github.com/realvare)
816
-
817
- <p>
818
-   <a href="https://github.com/realvare/based"><img src="https://img.shields.io/badge/⭐_Stella_il_Progetto-8a2be2?style=for-the-badge&logo=github&logoColor=white"/></a>
819
-   <a href="https://github.com/realvare/based/fork"><img src="https://img.shields.io/badge/🔄_Fork_Repository-8a2be2?style=for-the-badge&logo=github&logoColor=white"/></a>
820
- </p>
821
-
822
- <p>
823
-   <img src="https://img.shields.io/github/contributors/realvare/based?style=for-the-badge&color=8a2be2&labelColor=2d1b69" alt="Contributori"/>
824
-   <img src="https://img.shields.io/github/last-commit/realvare/based?style=for-the-badge&color=8a2be2&labelColor=2d1b69" alt="Ultimo Commit"/>
825
- </p>
826
-
827
- **Se ti è stato utile, valuta di lasciare una stella o di [donare](https://paypal.me/samakavare)!**
828
-
829
- </div>
1
+ <div align="center">
2
+
3
+ ![Wave](https://capsule-render.vercel.app/api?type=waving&color=gradient&customColorList=24&height=150&section=header&text=based&fontSize=60&fontColor=ffffff&animation=fadeIn&fontAlignY=35)
4
+ <img src="https://i.gifer.com/YdBN.gif" width="200">
5
+
6
+ ![Retro](https://readme-typing-svg.herokuapp.com?font=VT323&size=24&duration=2500&pause=10000&color=8A2BE2&center=true&vCenter=true&width=250&height=25&lines=$+by+Sam+aka+Vare)
7
+ <br>
8
+ <p align="center">
9
+ <img src="https://img.shields.io/npm/v/@realvare/based?style=for-the-badge&color=8a2be2&labelColor=2d1b69" alt="Versione NPM">
10
+ <img src="https://img.shields.io/npm/dm/@realvare/based?style=for-the-badge&color=8a2be2&labelColor=2d1b69" alt="Download NPM">
11
+ <img src="https://img.shields.io/badge/Licenza-MIT-8a2be2.svg?style=for-the-badge&labelColor=2d1b69" alt="Licenza MIT">
12
+ <img src="https://img.shields.io/github/stars/realvare/based?style=for-the-badge&color=8a2be2&labelColor=2d1b69" alt="GitHub Stelle">
13
+ <img src="https://img.shields.io/github/forks/realvare/based?style=for-the-badge&color=8a2be2&labelColor=2d1b69" alt="GitHub Forks">
14
+ </p>
15
+ <p align="center">
16
+ <a href="#-caratteristiche-principali"><img src="https://img.shields.io/badge/_Caratteristiche-8a2be2?style=flat-square&logo=github&logoColor=white"/></a>&nbsp;&nbsp;
17
+ <a href="#-installazione"><img src="https://img.shields.io/badge/_Installazione-8a2be2?style=flat-square&logo=npm&logoColor=white"/></a>&nbsp;&nbsp;
18
+ <a href="#-guida-rapida"><img src="https://img.shields.io/badge/_Guida_Rapida-8a2be2?style=flat-square&logo=rocket&logoColor=white"/></a>&nbsp;&nbsp;
19
+ <a href="#-documentazione-api"><img src="https://img.shields.io/badge/_Documentazione_API-8a2be2?style=flat-square&logo=book&logoColor=white"/></a>&nbsp;&nbsp;
20
+ <a href="#-supporto-e-community"><img src="https://img.shields.io/badge/_Supporto-8a2be2?style=flat-square&logo=teamspeak&logoColor=white"/></a>
21
+ </p>
22
+ <img src="https://readme-typing-svg.herokuapp.com?font=Fira+Code&weight=600&size=20&duration=4000&pause=2500&color=8A2BE2&center=true&vCenter=true&width=800&lines=💜+Una+libreria+WhatsApp+Web+API+moderna%2C+potente+e+veloce;🔄+Con+supporto+per+LID%2FJID+e+multi-dispositivo;">
23
+
24
+ ----
25
+
26
+ </div>
27
+
28
+ ## ✨ Caratteristiche Principali
29
+
30
+ <p align="center">
31
+ <img src="https://readme-typing-svg.herokuapp.com?font=Fira+Code&weight=600&size=18&duration=2500&pause=2500&color=8A2BE2&center=true&vCenter=true&width=600&lines=🚀+Potente+e+Intuitiva;🔧+Basata+su+Baileys+con+Miglioramenti" alt="Features">
32
+ </div>
33
+
34
+ <br>
35
+
36
+ Questa libreria, basata su Baileys con miglioramenti specifici, offre un'API intuitiva per interagire con WhatsApp Web. Ecco un riassunto delle funzionalità chiave:
37
+
38
+ <table align="center">
39
+ <tr>
40
+ <td align="center" width="25%">
41
+ <h3>🔄 Core Features</h3>
42
+ <p>• Mappatura intelligente LID/JID<br>• Supporto multi-dispositivo<br>• Crittografia E2E Signal<br>• TypeScript moderno</p>
43
+ </td>
44
+ <td align="center" width="25%">
45
+ <h3>💬 Messaggi</h3>
46
+ <p>• Testo, media, interattivi<br>• Bottoni, liste, carousel<br>• Album, poll, reazioni<br>• Template avanzati</p>
47
+ </td>
48
+ <td align="center" width="25%">
49
+ <h3>🛠️ Developer</h3>
50
+ <p>• Eventi real-time<br>• TypeScript completo<br>• Documentazione estesa<br>• API estendibili</p>
51
+ </td>
52
+ <td align="center" width="25%">
53
+ <h3>⚡ Performance</h3>
54
+ <p>• Riconnessione intelligente<br>• Cache avanzata TTL<br>• Monitoraggio prestazioni</p>
55
+ </td>
56
+ </tr>
57
+ </table>
58
+ <p align="center">
59
+ <img src="https://64.media.tumblr.com/13bc9e3c3b332dfc008cb4b9e8571558/2a577b39b15547dc-cc/s400x600/3db051b3117b695a61ad8e0b686f2774b971d210.gifv" width="800">
60
+
61
+
62
+ ## 🚀 Guida Rapida
63
+
64
+ - Questa sezione include esempi base per l'autenticazione e la gestione delle connessioni.
65
+
66
+ ### Esempio Base - Avvio Bot
67
+
68
+ ```typescript
69
+ import makeWASocket, { DisconnectReason, useMultiFileAuthState, getPerformanceConfig, setPerformanceConfig } from '@realvare/based';
70
+
71
+ // Configura performance e cache
72
+ setPerformanceConfig({
73
+ performance: {
74
+ enableCache: true,
75
+ enableMetrics: true
76
+ },
77
+ debug: {
78
+ enableLidLogging: true,
79
+ logLevel: 'info'
80
+ }
81
+ });
82
+
83
+ async function startBot() {
84
+ // 🔐 Setup autenticazione multi-file per sessioni persistenti
85
+ const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
86
+
87
+ // 🌐 Creazione del socket con configurazione base
88
+ const sock = makeWASocket({
89
+ auth: state,
90
+ printQRInTerminal: true,
91
+ logger: console,
92
+ browser: ['VareBot', 'Chrome', '4.0.0'],
93
+ });
94
+
95
+ // Sistema di riconnessione migliorato
96
+ let reconnectAttempts = 0;
97
+ const config = getPerformanceConfig();
98
+
99
+ sock.ev.on('connection.update', (update) => {
100
+ const { connection, lastDisconnect } = update;
101
+
102
+ if (connection === 'close') {
103
+ const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
104
+
105
+ if (shouldReconnect) {
106
+ reconnectAttempts++;
107
+ const delay = Math.min(
108
+ config.performance.retryDelay * Math.pow(
109
+ config.performance.retryBackoffMultiplier,
110
+ reconnectAttempts - 1
111
+ ),
112
+ config.performance.maxRetryDelay
113
+ );
114
+
115
+ console.log(`🔄 Tentativo di riconnessione ${reconnectAttempts}/${config.performance.maxRetries} tra ${delay}ms`);
116
+
117
+ if (reconnectAttempts <= config.performance.maxRetries) {
118
+ setTimeout(startBot, delay);
119
+ } else {
120
+ console.log(' Numero massimo di tentativi di riconnessione raggiunto');
121
+ }
122
+ }
123
+ } else if (connection === 'open') {
124
+ console.log('🟢 Connesso con successo!');
125
+ reconnectAttempts = 0;
126
+ }
127
+ });
128
+
129
+ sock.ev.on('creds.update', saveCreds);
130
+ }startBot().catch(console.error);
131
+ ```
132
+
133
+ ## 📊 Gestione Avanzata Cache
134
+
135
+ La libreria ora include un sistema di cache avanzato con gestione automatica della memoria e TTL configurabile:
136
+
137
+ ```typescript
138
+ import { CacheManager } from 'based/lib/Utils/cache-manager';
139
+
140
+ // Esempio di utilizzo della cache
141
+ const cache = CacheManager;
142
+
143
+ // Salva un valore nella cache
144
+ cache.set('lidCache', 'chiave', 'valore', 300); // TTL di 300 secondi
145
+
146
+ // Recupera un valore
147
+ const valore = cache.get('lidCache', 'chiave');
148
+
149
+ // Ottieni statistiche della cache
150
+ const stats = cache.getStats('lidCache');
151
+ console.log('Statistiche cache:', stats);
152
+ ```
153
+
154
+ ### Configurazione Cache Avanzata
155
+
156
+ La cache può essere configurata con varie opzioni per ottimizzare le prestazioni:
157
+
158
+ ```typescript
159
+ setPerformanceConfig({
160
+ cache: {
161
+ lidCache: {
162
+ ttl: 5 * 60 * 1000, // Tempo di vita delle entries
163
+ maxSize: 10000, // Numero massimo di entries
164
+ cleanupInterval: 2 * 60 * 1000 // Intervallo pulizia
165
+ }
166
+ },
167
+ performance: {
168
+ memoryThreshold: 0.85 // Soglia per pulizia automatica
169
+ }
170
+ });
171
+ ```
172
+ ## 🔍 Risoluzione Problemi
173
+
174
+ ### Problemi di Connessione
175
+ - La libreria ora implementa un sistema di retry con backoff esponenziale
176
+ - Monitoraggio automatico dello stato della connessione
177
+ - Tentativi di riconnessione configurabili
178
+
179
+ ### Gestione Memoria
180
+ - Monitoraggio automatico dell'uso della memoria
181
+ - Pulizia cache automatica quando necessario
182
+ - TTL configurabile per ogni tipo di cache
183
+
184
+ ### Logging Avanzato
185
+ ```typescript
186
+ setPerformanceConfig({
187
+ debug: {
188
+ enableLidLogging: true,
189
+ enablePerformanceLogging: true,
190
+ logLevel: 'debug'
191
+ }
192
+ });
193
+ ```
194
+
195
+ ### Gestione Messaggi Base con LID/JID
196
+
197
+ ```typescript
198
+ import makeWASocket, { getSenderLid, toJid, getCacheStats, validateJid, Logger } from '@realvare/based';
199
+
200
+ // ... (codice di creazione sock qui)
201
+
202
+ conn.ev.on('messages.upsert', ({ messages }) => {
203
+ for (const msg of messages) {
204
+ // 🔍 Estrai LID del mittente con validazione
205
+ const info = getSenderLid(msg);
206
+
207
+ // ✅ Valida JID prima di usarlo
208
+ const validation = validateJid(info.jid);
209
+ if (!validation.isValid) {
210
+ Logger.error('JID non valido:', validation.error);
211
+ continue;
212
+ }
213
+
214
+ const jid = toJid(info.lid); // Normalizza in JID
215
+
216
+ Logger.info('💬 Messaggio da:', jid, 'Valid:', info.isValid);
217
+ console.log('📝 Contenuto:', msg.message?.conversation);
218
+
219
+ // Rispondi automaticamente solo se valido
220
+ if (info.isValid) {
221
+ conn.sendMessage(jid, { text: 'Messaggio ricevuto!' });
222
+ }
223
+ }
224
+
225
+ // 📊 Monitora performance cache
226
+ const stats = getCacheStats();
227
+ Logger.performance('Cache stats:', stats);
228
+ });
229
+ ```
230
+
231
+ ---
232
+
233
+ ## 📚 Documentazione API
234
+
235
+ Questa sezione espande i metodi principali, con esempi dettagliati e parametri. Tutti i metodi sono tipizzati in TypeScript per un'esperienza di sviluppo sicura.
236
+
237
+ ### 🏗️ Metodi Fondamentali
238
+
239
+ <details>
240
+ <summary><strong>📡 makeWASocket(config)</strong></summary>
241
+
242
+ Crea un'istanza del socket WhatsApp. È il punto di ingresso principale.
243
+
244
+ **Parametri:**
245
+ - `config`: Oggetto con opzioni (vedi sezione Configurazione Avanzata per dettagli completi).
246
+
247
+ **Restituisce:** Istanza del socket con metodi come `sendMessage` e `ev` per eventi.
248
+
249
+ **Esempio:**
250
+ ```typescript
251
+ const sock = makeWASocket({
252
+ auth: state,
253
+ printQRInTerminal: true,
254
+ logger: console,
255
+ browser: ['Varebot', 'Chrome', '4.0.0'],
256
+ });
257
+ ```
258
+ </details>
259
+ <details>
260
+ <summary><strong>🔐 useMultiFileAuthState(folder)</strong></summary>
261
+
262
+ Gestisce l'autenticazione persistente salvando credenziali in file multipli per sicurezza.
263
+
264
+ **Parametri:**
265
+ - `folder`: Stringa, path della cartella per i file di auth (es. 'auth_info').
266
+
267
+ **Restituisce:**
268
+ - `{ state, saveCreds }`: Stato autenticazione e funzione per salvare aggiornamenti.
269
+
270
+ **Esempio:**
271
+ ```typescript
272
+ const { state, saveCreds } = await useMultiFileAuthState('auth_info');
273
+ conn.ev.on('creds.update', saveCreds); // Integra nel socket
274
+ ```
275
+ </details>
276
+
277
+ <details>
278
+ <summary><strong>🔄 getSenderLid(message) & toJid(lid)</strong></summary>
279
+
280
+ Utilità per gestire LID/JID, risolvendo problemi comuni in gruppi e multi-dispositivo.
281
+
282
+ **getSenderLid(message):**
283
+ - Estrae LID dal messaggio.
284
+ - Restituisce: Oggetto con `lid` e altre info mittente.
285
+
286
+ **toJid(lid):**
287
+ - Converte LID in JID normalizzato (es. prende pn e aggiunge `@s.whatsapp.net`).
288
+
289
+ **Esempio:**
290
+ ```typescript
291
+ const info = getSenderLid(msg);
292
+ const jid = toJid(info.lid);
293
+ conn.sendMessage(jid, { text: 'we ridin porsches in the rain' });
294
+ ```
295
+ </details>
296
+
297
+ <details>
298
+ <summary><strong>📤 sendMessage(jid, content, options)</strong></summary>
299
+
300
+ Invia messaggi di vari tipi. Supporta testo, media, interattivi.
301
+
302
+ **Parametri:**
303
+ - `jid`: Stringa JID del destinatario.
304
+ - `content`: Oggetto messaggio (es. { text: 'finche vedo tutto violaviola' }).
305
+ - `options`: Opzionale, include `quoted`, `mentions`, ecc.
306
+
307
+ **Esempio Testo Semplice:**
308
+ ```typescript
309
+ await conn.sendMessage(jid, { text: 'bankai!' });
310
+ ```
311
+ </details>
312
+
313
+ ### 🎯 Eventi Principali
314
+
315
+ | Evento | Descrizione | Callback Signature |
316
+ |---------------------|--------------------------------------|-------------------------------------|
317
+ | `connection.update` | Aggiornamenti stato connessione | `(update: Partial<ConnectionState>) => void` |
318
+ | `creds.update` | Aggiornamento credenziali | `() => void` |
319
+ | `messages.upsert` | Nuovi messaggi o aggiornamenti | `({ messages: WAMessage[], type: MessageUpsertType }) => void` |
320
+ | `messages.update` | Modifiche a messaggi esistenti | `(update: WAMessageUpdate[]) => void` |
321
+ | `group-participants.update` | Cambiamenti partecipanti gruppo | `(update: GroupParticipantEvent) => void` |
322
+
323
+ **Esempio Registrazione Evento:**
324
+ ```typescript
325
+ conn.ev.on('group-participants.update', (update) => {
326
+ console.log('Partecipante aggiornato:', update);
327
+ });
328
+ ```
329
+
330
+ ---
331
+
332
+ ## 🎪 Messaggi e Funzionalità Interattive
333
+
334
+ ### Messaggi Base
335
+
336
+ #### Testo con Formattazione
337
+ ```typescript
338
+ // Testo con formattazione e menzioni
339
+ await conn.sendMessage(jid, {
340
+ text: `*Bold* _italic_ ~strikethrough~ \`monospace\`\n@menzione`,
341
+ mentions: ['393476686131@s.whatsapp.net']
342
+ });
343
+ ```
344
+
345
+ #### Media Base
346
+ ```typescript
347
+ // Immagine
348
+ await conn.sendMessage(jid, {
349
+ image: { url: './media/varebot.jpg' }, // Supporta anche Buffer
350
+ caption: 'zwag'
351
+ });
352
+
353
+ // Video
354
+ await conn.sendMessage(jid, {
355
+ video: { url: './media/oppastoppa.mp4' },
356
+ caption: 'brrrr',
357
+ gifPlayback: false // true per riprodurre come GIF
358
+ });
359
+
360
+ // Audio
361
+ await conn.sendMessage(jid, {
362
+ audio: { url: './media/audio.mp3' },
363
+ mimetype: 'audio/mp4',
364
+ ptt: true // true per messaggio vocale, false per audio normale
365
+ });
366
+
367
+ // Documento
368
+ await conn.sendMessage(jid, {
369
+ document: { url: './media/doc.pdf' },
370
+ mimetype: 'application/pdf',
371
+ fileName: 'documento.pdf'
372
+ });
373
+ ```
374
+
375
+ #### Media Avanzati
376
+ ```typescript
377
+ // Album (Multiple immagini)
378
+ await conn.sendMessage(jid, {
379
+ album: imageBuffers.map(buffer => ({ image: buffer })),
380
+ caption: 'ts gettin real'
381
+ });
382
+
383
+ // Sticker
384
+ await conn.sendMessage(jid, {
385
+ sticker: { url: './stickers/sticker.webp' }
386
+ });
387
+
388
+ // Messaggio con posizione
389
+ await conn.sendMessage(jid, {
390
+ location: {
391
+ degreesLatitude: 45.4642,
392
+ degreesLongitude: 9.1900,
393
+ name: "Milano",
394
+ address: "Piazza del Duomo, Milano"
395
+ }
396
+ });
397
+ ```
398
+
399
+ #### Messaggi Interattivi
400
+ Questi messaggi includono elementi interattivi come bottoni, liste e template.
401
+
402
+ ##### Messaggi con Bottoni Semplici
403
+ Invia bottoni di risposta rapida.
404
+
405
+ ```typescript
406
+ await conn.sendMessage(jid, {
407
+ text: 'Scegli un\'opzione:',
408
+ footer: 'Footer',
409
+ buttons: [
410
+ { buttonId: 'cmd1', buttonText: { displayText: 'testo1' }, type: 1 },
411
+ { buttonId: 'cmd2', buttonText: { displayText: 'testo2' }, type: 1 },
412
+ ],
413
+ headerType: 1,
414
+ });
415
+ ```
416
+
417
+ ##### Messaggi con Bottoni e Immagine
418
+ Combina immagine con bottoni.
419
+
420
+ ```typescript
421
+ await conn.sendMessage(jid, {
422
+ image: { url: 'https://i.ibb.co/hJW7WwxV/varebot.jpg' },
423
+ caption: 'Messaggio con bottoni e immagine',
424
+ footer: 'vare ✧ bot',
425
+ buttons: [
426
+ { buttonId: 'cmd', buttonText: { displayText: 'testo1' }, type: 1 },
427
+ ],
428
+ });
429
+ ```
430
+
431
+ ##### Messaggi Liste
432
+ Invia una lista di opzioni (solo in privato).
433
+
434
+ ```typescript
435
+ await conn.sendMessage(jid, {
436
+ text: 'Questa è una lista!',
437
+ footer: 'purplepurplepurple!',
438
+ title: 'Titolo Lista',
439
+ buttonText: 'Visualizza Lista',
440
+ sections: [
441
+ {
442
+ title: 'Sezione 1',
443
+ rows: [
444
+ { title: 'Opzione 1', rowId: 'opt1',description: 'Descrizionex' },
445
+ { title: 'Opzione 2', rowId: 'opt2', description: 'Descrizioney' }
446
+ ]
447
+ },
448
+ ],
449
+ });
450
+ ```
451
+
452
+ ##### Carousel e Card Messages
453
+ Il carousel è un tipo speciale di messaggio che permette di mostrare una serie di card scorrevoli.
454
+ ```typescript
455
+ await conn.sendMessage(jid, {
456
+ text: '〖 🌸 Benvenuto in VareBot!',
457
+ title: '',
458
+ footer: '',
459
+ cards: [
460
+ {
461
+ image: { url: 'https://i.ibb.co/hJW7WwxV/varebot.jpg' },
462
+ title: 'by sam aka vare',
463
+ body: '〖 💫 Esplora funzionalità\n〖 🚀 〗 Bot aggiornato',
464
+ footer: '˗ˏˋ ☾ 𝚟𝚊𝚛𝚎𝚋𝚘𝚝 ☽ ˎˊ˗',
465
+ buttons: [
466
+ { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: 'Sito VareBot', url: 'https://varebot.netlify.app' }) },
467
+ { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: '💻 GitHub', url: 'https://github.com/realvare' }) },
468
+ { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: '💬 WhatsApp', url: 'https://wa.me/393476686131' }) },
469
+ { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: '📸 Instagram', url: 'https://instagram.com/samakavare' }) },
470
+ { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: '📧 Email', url: 'mailto:samakavare1@gmail.com' }) },
471
+ ],
472
+ },
473
+ ],
474
+ }, { quoted: m });
475
+ ```
476
+
477
+ #### Altri Messaggi
478
+ ```typescript
479
+ // Messaggio con citazione
480
+ await conn.sendMessage(jid, {
481
+ text: 'bang bang',
482
+ quoted: quotedMessage // Il messaggio da quotare/rispondere/citare
483
+ });
484
+
485
+ // Messaggi Contatto
486
+ await conn.sendMessage(jid, {
487
+ contacts: {
488
+ displayName: 'Sam aka vare',
489
+ contacts: [{ vcard: 'BEGIN:VCARD\nVERSION:3.0\nFN:Sam aka vare\nTEL;waid=393476686131:+39 347 6686131\nEND:VCARD' }]
490
+ }
491
+ });
492
+
493
+ // Messaggi Poll (Sondaggio)
494
+ await conn.sendMessage(jid, {
495
+ poll: {
496
+ name: 'Anime preferito?',
497
+ values: ['Aot', 'Bleach', 'Death note'],
498
+ selectableCount: 1 // quante scelte possibili
499
+ }
500
+ });
501
+
502
+ // Messaggi Ephemeral (Che si Autodistruggono)
503
+ await conn.sendMessage(jid, {
504
+ text: "Questo messaggio si autodistruggerà {speriamo come israele}"
505
+ }, {
506
+ ephemeralExpiration: 7 * 24 * 60 * 60
507
+ });
508
+
509
+ // Messaggi con Risposta a Visualizzazione
510
+ await conn.sendMessage(
511
+ jid,
512
+ {
513
+ video: { url: './media/hado90.mp4' },
514
+ viewOnce: true,
515
+ caption: 'tuff'
516
+ }
517
+ )
518
+
519
+ // Messaggi di Status (Stato)
520
+ await conn.sendMessage('status@broadcast', {
521
+ text: 'god forgive em'
522
+ }, {
523
+ statusJidList: contatti
524
+ });
525
+
526
+ // Invia uno stato con media (visibile solo a contatti selezionati)
527
+ await conn.sendMessage('status@broadcast', {
528
+ image: { url: './media/menu/menu.jpg' },
529
+ caption: 'all i need in this life of sin is-',
530
+ }, {
531
+ statusJidList: contatti
532
+ });
533
+
534
+ // Messaggi Newsletter
535
+ await conn.sendMessage('120363418582531215@newsletter', {
536
+ text: 'ay yo',
537
+ });
538
+
539
+ // Messaggi di Pagamento
540
+ await conn.sendMessage(jid, {
541
+ requestPayment: {
542
+ currency: 'EUR',
543
+ amount1000: 5000,
544
+ requestFrom: '393514357738@s.whatsapp.net',
545
+ note: 'js gimme my money' // https://paypal.me/samakavare
546
+ }
547
+ });
548
+
549
+ // Messaggi di Chiamata
550
+ await conn.sendMessage(jid, {
551
+ call: {
552
+ callKey: {
553
+ fromMe: true,
554
+ id: Date.now().toString(),
555
+ remoteJid: jid
556
+ },
557
+ type: 'ACCEPT' // 'MISSED', 'OFFER', 'ACCEPT', 'REJECT'..
558
+ }
559
+ });
560
+
561
+ // Messaggi con Live Location
562
+ await conn.sendMessage(jid, {
563
+ liveLocation: {
564
+ degreesLatitude: 45.4642,
565
+ degreesLongitude: 9.1900,
566
+ accuracyInMeters: 50,
567
+ speedInMps: 5,
568
+ degreesClockwiseFromMagneticNorth: 359,
569
+ caption: "kmt im mean kiss my teeth",
570
+ sequenceNumber: 21,
571
+ timeOffset: 2000,
572
+ }
573
+ });
574
+
575
+ // Messaggi di Ordini/Prodotti
576
+ await conn.sendMessage(jid, {
577
+ order: {
578
+ id: 'bysamakavare',
579
+ thumbnail: buffer, // immagine buffer
580
+ itemCount: 67,
581
+ surface: 'CATALOG',
582
+ title: 'heh',
583
+ text: 'gotta make it happen',
584
+ seller: '393514357738@s.whatsapp.net',
585
+ amount: 67000,
586
+ currency: 'EUR'
587
+ }
588
+ });
589
+
590
+ // Prodotto
591
+ await conn.sendMessage(jid, {
592
+ product: {
593
+ productImage: { url: './media/menu/menu.jpg' },
594
+ productId: 'prod123',
595
+ title: 'titolo',
596
+ description: 'Desc',
597
+ currency: 'EUR',
598
+ priceAmount1000: 67000,
599
+ retailerId: 'bysamakavare',
600
+ url: 'https://varebot.netlify.app',
601
+ },
602
+ businessOwnerJid: m.sender
603
+ });
604
+
605
+ // Messaggi con Intestazione Personalizzata
606
+ await conn.sendMessage(jid, {
607
+ text: 'dilemma',
608
+ contextInfo: {
609
+ externalAdReply: {
610
+ title: `titolo`,
611
+ body: `desc`,
612
+ thumbnailUrl: 'https://i.ibb.co/kVdFLyGL/sam.jpg', // immagine
613
+ sourceUrl: '', // sconsiglio di metterla
614
+ mediaType: 1,
615
+ renderLargerThumbnail: false // o true se la volete grande
616
+ }
617
+ }
618
+ });
619
+ > nota: non usate showAdAttribution o tenetela in false, poiche con essa attiva non viene visualizzato il messaggio
620
+ ```
621
+
622
+ ### Gestione delle Risposte
623
+
624
+ Per gestire le risposte ai messaggi interattivi, usa il listener `messages.upsert` e controlla il tipo di risposta:
625
+
626
+ ```typescript
627
+ conn.ev.on('messages.upsert', async ({ messages }) => {
628
+ const msg = messages[0];
629
+
630
+ // Risposta a bottoni
631
+ if (msg.message?.buttonsResponseMessage) {
632
+ const selectedId = msg.message.buttonsResponseMessage.selectedButtonId;
633
+ console.log(`Bottone selezionato: ${selectedId}`);
634
+ }
635
+
636
+ // Risposta a liste
637
+ if (msg.message?.listResponseMessage) {
638
+ const selectedId = msg.message.listResponseMessage.singleSelectReply.selectedRowId;
639
+ console.log(`Opzione selezionata: ${selectedId}`);
640
+ }
641
+
642
+ // Risposta a sondaggio
643
+ if (msg.message?.pollResponseMessage) {
644
+ const selectedOptions = msg.message.pollResponseMessage.selectedOptions;
645
+ console.log('Opzioni selezionate:', selectedOptions);
646
+ }
647
+ });
648
+ ```
649
+
650
+ ### 🎭 Funzionalità Gruppi
651
+
652
+ #### Gestione Base Gruppi
653
+
654
+ ```typescript
655
+ // Creazione gruppo - il jid sta per l'aggiunta di partecipanti
656
+ const group = await conn.groupCreate('Angels 🩸🕊️', ['user@s.whatsapp.net']);
657
+
658
+ // Ottenere info gruppo
659
+ const metadata = await conn.groupMetadata(jid);
660
+
661
+ // Ottenere codice invito
662
+ const code = await conn.groupInviteCode(jid);
663
+
664
+ // Revocare link invito
665
+ await conn.groupRevokeInvite(jid);
666
+
667
+ // Lasciare gruppo
668
+ await conn.groupLeave(jid);
669
+ ```
670
+
671
+ #### Gestione Partecipanti
672
+
673
+ ```typescript
674
+ // Aggiungere partecipanti
675
+ await conn.groupParticipantsUpdate(
676
+ jid,
677
+ ['user@s.whatsapp.net'],
678
+ 'add'
679
+ );
680
+
681
+ // Rimuovere partecipanti
682
+ await conn.groupParticipantsUpdate(
683
+ jid,
684
+ ['user@s.whatsapp.net'],
685
+ 'remove'
686
+ );
687
+
688
+ // Promuovere ad admin
689
+ await conn.groupParticipantsUpdate(
690
+ jid,
691
+ ['user@s.whatsapp.net'],
692
+ 'promote'
693
+ );
694
+
695
+ // Degradare da admin
696
+ await conn.groupParticipantsUpdate(
697
+ jid,
698
+ ['user@s.whatsapp.net'],
699
+ 'demote'
700
+ );
701
+ ```
702
+
703
+ #### Impostazioni Gruppo
704
+
705
+ ```typescript
706
+ // Modificare nome gruppo
707
+ await conn.groupUpdateSubject(jid, 'Nuovo Nome');
708
+
709
+ // Modificare descrizione
710
+ await conn.groupUpdateDescription(jid, 'Nuova descrizione');
711
+
712
+ // Modificare foto gruppo
713
+ await conn.updateProfilePicture(jid, { url: './img/group.jpg' });
714
+
715
+ // Rimuovere foto gruppo
716
+ await conn.removeProfilePicture(jid);
717
+
718
+ // Impostare gruppo come solo admin
719
+ await conn.groupSettingUpdate(jid, 'announcement');
720
+
721
+ // Impostare gruppo come aperto a tutti
722
+ await conn.groupSettingUpdate(jid, 'not_announcement');
723
+
724
+ // Impostare chi può modificare le info - solo admin
725
+ await conn.groupSettingUpdate(jid, 'locked');
726
+
727
+ // Impostare chi può modificare le info - tutti
728
+ await conn.groupSettingUpdate(jid, 'unlocked');
729
+
730
+ // Impostare chi può aggiungere membri - solo admin
731
+ await conn.groupMemberAddMode(jid, 'admin_add');
732
+
733
+ // Impostare chi può aggiungere membri - tutti
734
+ await conn.groupMemberAddMode(jid, 'all_member_add');
735
+
736
+ // Attivare/disattivare messaggi temporanei (24 ore)
737
+ await conn.groupToggleEphemeral(jid, 86400); // secondi
738
+
739
+ // Disattivare messaggi temporanei
740
+ await conn.groupToggleEphemeral(jid, 0);
741
+
742
+ // Attivare/disattivare modalità approvazione adesioni
743
+ await conn.groupJoinApprovalMode(jid, 'on'); // richiede approvazione
744
+ await conn.groupJoinApprovalMode(jid, 'off'); // aperta
745
+
746
+ // Ottenere tutti i gruppi
747
+ const groups = await conn.groupFetchAllParticipating();
748
+
749
+ // Ottenere inviti pendenti
750
+ const invites = await conn.groupGetInviteInfo(code);
751
+
752
+ // Accettare invito gruppo
753
+ await conn.groupAcceptInvite(code);
754
+
755
+ // Ottenere info gruppo da link
756
+ const groupInfo = await conn.groupGetInviteInfo('https://chat.whatsapp.com/ABC123');
757
+
758
+ ```
759
+
760
+ #### Messaggi Gruppo Avanzati
761
+
762
+ ```typescript
763
+ // Messaggio con menzione multipla
764
+ await conn.sendMessage(jid, {
765
+ text: '@user1 @user2 @user3',
766
+ mentions: [user1, user2, user3],
767
+ contextInfo: {
768
+ mentionedJid: [user1, user2, user3]
769
+ }
770
+ });
771
+
772
+ // Messaggio con ricerca google
773
+ await conn.sendMessage(jid, {
774
+ text: 'ZWAG',
775
+ contextInfo: {
776
+ forwardingScore: 999,
777
+ isForwarded: true
778
+ }
779
+ });
780
+
781
+ ```
782
+
783
+ // Ascolta modifiche impostazioni
784
+ conn.ev.on('group-settings.update', async ({ jid, announce, restrict }) => {
785
+ if(announce !== undefined) {
786
+ await conn.sendMessage(jid, {
787
+ text: `Il gruppo è stato impostato come ${announce ? 'solo admin' : 'tutti'}`
788
+ });
789
+ }
790
+ if(restrict !== undefined) {
791
+ await conn.sendMessage(jid, {
792
+ text: `Le info gruppo possono essere modificate da ${restrict ? 'solo admin' : 'tutti'}`
793
+ });
794
+ }
795
+ });
796
+ ```
797
+ ```
798
+ ---
799
+
800
+ ## 🔧 Fix LID/JID nel Proprio Main e Handler
801
+
802
+ *Il supporto LID/JID è un punto di forza di questa libreria, risolvendo problemi comuni come l'identificazione mittenti in gruppi e chat privata. Ecco come integrarlo nel tuo codice principale e handler.*
803
+
804
+ ### Best Practices per LID/JID
805
+
806
+ - **decodeJid(jid)**: Funzione principale per normalizzare JID/LID. Gestisce:
807
+ - Formati con `:\d+@` (usa `jidNormalizedUser`).
808
+ - Decodifica user/server in `${user}@${server}`.
809
+ - Converti `@lid` in `@s.whatsapp.net`.
810
+
811
+ **Esempio di Implementazione (da main.js):**
812
+ ```typescript
813
+ decodeJid: (jid) => {
814
+ if (!jid) return jid;
815
+ let decoded = jid;
816
+ if (/:\d+@/gi.test(jid)) {
817
+ decoded = jidNormalizedUser(jid);
818
+ }
819
+ if (typeof decoded === 'object' && decoded.user && decoded.server) {
820
+ decoded = `${decoded.user}@${decoded.server}`;
821
+ }
822
+ if (decoded.endsWith('@lid')) {
823
+ decoded = decoded.replace('@lid', '@s.whatsapp.net');
824
+ }
825
+ return decoded;
826
+ },
827
+ ```
828
+ Usa `conn.decodeJid(jid)` ovunque per normalizzare IDs (es. sender, participant, quoted).
829
+
830
+ - **Monkey-Patch per groupParticipantsUpdate**: Corregge aggiornamenti partecipanti gruppo trovando il JID reale dal metadata.
831
+
832
+ **Esempio (da handler.js):**
833
+ ```typescript
834
+ if (!this.originalGroupParticipantsUpdate) {
835
+ this.originalGroupParticipantsUpdate = this.groupParticipantsUpdate;
836
+ this.groupParticipantsUpdate = async function(chatId, users, action) {
837
+ try {
838
+ let metadata = global.groupCache.get(chatId);
839
+ if (!metadata) {
840
+ metadata = await fetchGroupMetadataWithRetry(this, chatId);
841
+ if (metadata) global.groupCache.set(chatId, metadata);
842
+ }
843
+ if (!metadata) {
844
+ console.error('[ERRORE] Nessun metadato del gruppo disponibile per un aggiornamento sicuro');
845
+ return this.originalGroupParticipantsUpdate.call(this, chatId, users, action);
846
+ }
847
+
848
+ const correctedUsers = users.map(userJid => {
849
+ const decoded = this.decodeJid(userJid);
850
+ const phone = decoded.split('@')[0].split(':')[0];
851
+ const participant = metadata.participants.find(p => {
852
+ const pId = this.decodeJid(p.id || p.jid || '');
853
+ const pPhone = pId.split('@')[0].split(':')[0];
854
+ return pPhone === phone;
855
+ });
856
+ return participant ? participant.id : userJid; // Fallback all'originale se non trovato
857
+ });
858
+
859
+ return this.originalGroupParticipantsUpdate.call(this, chatId, correctedUsers, action);
860
+ } catch (e) {
861
+ console.error('[ERRORE] Errore in safeGroupParticipantsUpdate:', e);
862
+ throw e;
863
+ }
864
+ };
865
+ }
866
+ ```
867
+
868
+ - **Cache per Metadata Gruppo**: Usa NodeCache per memorizzare metadata, normalizzando con `decodeJid`.
869
+
870
+ **Esempio (da handler.js):**
871
+ ```typescript
872
+ global.groupCache = new NodeCache({ stdTTL: 5 * 60, useClones: false });
873
+
874
+ // In participantsUpdate o groups.update:
875
+ metadata.participants.forEach(u => {
876
+ const normId = this.decodeJid(u.id);
877
+ const jid = u.jid || normId;
878
+ });
879
+ global.groupCache.set(update.id, metadata);
880
+ ```
881
+
882
+ - **Normalizzazione in Print/Log**: Rimuovi `:xx` dai numeri telefono per clean display.
883
+
884
+ **Esempio (da print.js):**
885
+ ```typescript
886
+ function formatPhoneNumber(jid, name) {
887
+ if (!jid) return 'Sconosciuto';
888
+ let userPart = jid.split('@')[0];
889
+ let cleanNumber = userPart.split(':')[0]; // Rimuovi la parte :xx per ottenere il numero reale
890
+ try {
891
+ const number = PhoneNumber('+' + cleanNumber).getNumber('international');
892
+ return number + (name ? ` ~${name}` : '');
893
+ } catch {
894
+ return (cleanNumber || '') + (name ? ` ~${name}` : '');
895
+ }
896
+ }
897
+ ```
898
+
899
+ - **Problemi Comuni e Fix:**
900
+ - **LID Mancante in Gruppi:** Usa `decodeJid` e cache metadata per trovare JID reali.
901
+ - **Conversione JID:** Sempre applica `decodeJid` prima di `sendMessage` o query.
902
+ - **Multi-Dispositivo:** Imposta `syncFullHistory: true` in config per sync LID.
903
+ - **Errori in Mention/Quoted:** Normalizza con `decodeJid` in handler per quoted.sender e mentionedJid.
904
+
905
+ ### Esempio Integrato in Main
906
+
907
+ ```typescript
908
+ // Nel tuo file main
909
+ import makeWASocket, { getSenderLid, toJid } from '@realvare/based';
910
+ // ... (autenticazione e creazione sock)
911
+
912
+ conn.ev.on('messages.upsert', async ({ messages }) => {
913
+ const msg = messages[0];
914
+ if (!msg.message) return;
915
+
916
+ const info = getSenderLid(msg);
917
+ const senderJid = toJid(info.lid); // Fix LID -> JID
918
+
919
+ // Esempio: Rispondi solo se JID valido
920
+ if (senderJid.endsWith('@s.whatsapp.net')) {
921
+ await conn.sendMessage(senderJid, { text: `Ciao da ${senderJid}!` }, { quoted: msg });
922
+ }
923
+ });
924
+ ```
925
+
926
+ ### Esempio Handler Personalizzato
927
+
928
+ Crea un handler separato per modularità:
929
+
930
+ ```typescript
931
+ // handler.js
932
+ export async function handleMessage(sock, msg) {
933
+ const info = getSenderLid(msg);
934
+ const jid = toJid(info.lid);
935
+
936
+ // Log e risposta
937
+ console.log(`Messaggio da ${jid}`);
938
+ await conn.sendMessage(jid, { text: 'Handler attivato!' });
939
+ }
940
+
941
+ // Nel main: conn.ev.on('messages.upsert', ({ messages }) => handleMessage(sock, messages[0]));
942
+ ```
943
+
944
+ **Consiglio:** Testa in gruppi per verificare LID, poiché Baileys upstream ha migliorato il supporto nativo nel 2025, ma i fix personalizzati qui garantiscono retrocompatibilità.
945
+
946
+ ---
947
+
948
+ ### 🚀 Cache Intelligente LID/JID
949
+
950
+ La libreria ora include un sistema di cache avanzato per ottimizzare le conversioni LID/JID:
951
+
952
+ ```typescript
953
+ import { getCacheStats, clearCache, setPerformanceConfig } from '@realvare/based';
954
+
955
+ // Configura cache personalizzata
956
+ setPerformanceConfig({
957
+ cache: {
958
+ lidCache: {
959
+ ttl: 10 * 60 * 1000, // 10 minuti
960
+ maxSize: 15000
961
+ }
962
+ }
963
+ });
964
+
965
+ // Monitora performance
966
+ const stats = getCacheStats();
967
+ console.log('Cache LID:', stats.lidCache.size, '/', stats.lidCache.maxSize);
968
+
969
+ // Pulisci cache se necessario
970
+ clearCache();
971
+ ```
972
+
973
+ ### 🛡️ Validazione JID Avanzata
974
+
975
+ ```typescript
976
+ import { validateJid, Logger } from '@realvare/based';
977
+
978
+ const jid = '1234567890@s.whatsapp.net';
979
+ const validation = validateJid(jid);
980
+
981
+ if (validation.isValid) {
982
+ Logger.info('JID valido:', jid);
983
+ } else {
984
+ Logger.error('JID non valido:', validation.error);
985
+ }
986
+ ```
987
+
988
+ ### 📊 Logging Condizionale
989
+
990
+ ```typescript
991
+ import { Logger, setPerformanceConfig } from '@realvare/based';
992
+
993
+ // Configura logging
994
+ setPerformanceConfig({
995
+ debug: {
996
+ enableLidLogging: true,
997
+ enablePerformanceLogging: true,
998
+ logLevel: 'debug' // 'error', 'warn', 'info', 'debug'
999
+ }
1000
+ });
1001
+
1002
+ // Usa logger condizionale
1003
+ Logger.debug('Debug info');
1004
+ Logger.performance('Performance metrics');
1005
+ Logger.error('Error occurred');
1006
+ ```
1007
+
1008
+ ### 🔧 Configurazione Performance
1009
+
1010
+ ```typescript
1011
+ import { setPerformanceConfig, getPerformanceConfig } from '@realvare/based';
1012
+
1013
+ // Configurazione completa
1014
+ setPerformanceConfig({
1015
+ performance: {
1016
+ enableCache: true,
1017
+ enableMetrics: true,
1018
+ batchSize: 100,
1019
+ maxRetries: 3
1020
+ },
1021
+ cache: {
1022
+ lidCache: { ttl: 5 * 60 * 1000, maxSize: 10000 },
1023
+ jidCache: { ttl: 5 * 60 * 1000, maxSize: 10000 }
1024
+ },
1025
+ debug: {
1026
+ enableLidLogging: false,
1027
+ logLevel: 'warn'
1028
+ }
1029
+ });
1030
+
1031
+ // Ottieni configurazione corrente
1032
+ const config = getPerformanceConfig();
1033
+ console.log('Cache abilitata:', config.performance.enableCache);
1034
+ ```
1035
+
1036
+ ---
1037
+
1038
+ ## 🧩 Eventi: LID e JID sempre disponibili (nuovo)
1039
+
1040
+ Gli eventi emessi includono campi ausiliari sui messaggi per accedere facilmente sia al JID sia al LID del mittente/partecipante.
1041
+
1042
+ ```typescript
1043
+ conn.ev.on('messages.upsert', ({ messages, type }) => {
1044
+ for (const msg of messages) {
1045
+ // Campi aggiuntivi su msg.key
1046
+ // - remoteJidNormalized: JID normalizzato (es. @s.whatsapp.net)
1047
+ // - remoteLid: LID equivalente del remoteJid
1048
+ // - participantLid: LID equivalente del participant (se presente)
1049
+ const jid = msg.key.remoteJidNormalized || msg.key.remoteJid;
1050
+ const remoteLid = msg.key.remoteLid;
1051
+ const participantLid = msg.key.participantLid;
1052
+
1053
+ if (jid?.endsWith('@s.whatsapp.net')) {
1054
+ conn.sendMessage(jid, { text: `Ciao! LID: ${remoteLid || 'n/d'}` });
1055
+ }
1056
+ }
1057
+ });
1058
+ ```
1059
+
1060
+ Questi campi eliminano ambiguità in gruppi e contesti multi-dispositivo dove alcuni eventi riportano LID, altri JID.
1061
+
1062
+ ---
1063
+
1064
+ ## ⚙️ Configurazione Avanzata
1065
+
1066
+ Personalizza il socket per performance e comportamento.
1067
+
1068
+ ### 🔧 Opzioni Complete per makeWASocket
1069
+
1070
+ ```typescript
1071
+ const sock = makeWASocket({
1072
+ // 🔐 Autenticazione
1073
+ auth: state,
1074
+
1075
+ // 🖥️ UI e Debug
1076
+ printQRInTerminal: true,
1077
+ logger: console,
1078
+ browser: ['VareBot', 'Chrome', '4.0.0'],
1079
+
1080
+ // ⏱️ Timeout e Connessione
1081
+ defaultQueryTimeoutMs: 60000,
1082
+ keepAliveIntervalMs: 30000,
1083
+ connectTimeoutMs: 60000,
1084
+ retryRequestDelayMs: 250,
1085
+ maxMsgRetryCount: 5,
1086
+
1087
+ // 🎛️ Comportamento
1088
+ markOnlineOnConnect: true,
1089
+ syncFullHistory: false, // Attiva per sync completo (consuma dati)
1090
+ fireInitQueries: true,
1091
+ generateHighQualityLinkPreview: true,
1092
+ });
1093
+ ```
1094
+ <div align="center">
1095
+
1096
+ ### 🛡️ Sicurezza e Crittografia
1097
+
1098
+ | Caratteristica | Descrizione |
1099
+ |---------------------------|------------------------------------------|
1100
+ | 🔐 End-to-End Encryption | Protocollo Signal per messaggi sicuri |
1101
+ | 🔑 Key Management | Generazione/rotazione automatica chiavi |
1102
+ | 🔍 Authentication | Sicurezza tramite QR code o pairing code |
1103
+ | 🛡️ Data Protection | Archiviazione sicura credenziali locali |
1104
+
1105
+ ---
1106
+
1107
+ ## 🌐 Supporto e Community
1108
+
1109
+ Unisciti alla community per aiuto e contributi.
1110
+
1111
+ ### 📞 Contatti e Risorse
1112
+
1113
+ | Canale | Link/Info |
1114
+ |------------------|------------------------------------------|
1115
+ | **Email** | [samakavare1@gmail.com](mailto:samakavare1@gmail.com) |
1116
+ | **GitHub Issues**| [Segnala Bug](https://github.com/realvare/based/issues) |
1117
+ | **PayPal** | [Dona](https://www.paypal.me/samakavare) |
1118
+ | **Canale whatsapp**| [Canale](https://www.whatsapp.com/channel/0029VbB41Sa1Hsq1JhsC1Z1z) |
1119
+
1120
+ ---
1121
+
1122
+ ## 🙏 Ringraziamenti
1123
+
1124
+ Grazie ai progetti che ispirano Based:
1125
+
1126
+ | Progetto | Contributo |
1127
+ |---------------------------|------------------------------------------|
1128
+ | [Baileys](https://github.com/WhiskeySockets/Baileys) | API WhatsApp Web originale |
1129
+ | [Yupra](https://www.npmjs.com/package/@yupra/baileys) | Fix LID/JID |
1130
+ | [Signal Protocol](https://signal.org/) | Crittografia end-to-end |
1131
+
1132
+ ---
1133
+
1134
+ ## ⚠️ Disclaimer & Licenza
1135
+
1136
+ ### 📋 Nota Legale
1137
+
1138
+ ⚠️ **Importante**: Non affiliato a WhatsApp Inc. o Meta. Uso educativo/sviluppo solo.
1139
+
1140
+ 🛡️ **Uso Responsabile**: Evita spam, violazioni ToS WhatsApp. Rischio ban account.
1141
+
1142
+ ### 📜 Licenza MIT
1143
+
1144
+ MIT License © 2025 [realvare](https://github.com/realvare)
1145
+
1146
+ Vedi [LICENSE](LICENSE) per dettagli.
1147
+
1148
+ ---
1149
+
1150
+ <div align="center">
1151
+ <table align="center">
1152
+ <tr>
1153
+ <td align="center">
1154
+ <img src="https://i.ibb.co/Cp0SQznC/sam2.png" width="120" height="120" alt="pfp" style="bysamakavare"/>
1155
+ <br><br>
1156
+ <h2>👨‍💻 Creato da <a href="https://github.com/realvare" style="color: #8a2be2; text-decoration: none;">realvare</a></h2>
1157
+ <p><em>sam aka vare</em></p>
1158
+ </td>
1159
+ </tr>
1160
+ </table>
1161
+
1162
+ <br>
1163
+ <p align="center">
1164
+ <a href="https://github.com/realvare/based">
1165
+ <img src="https://img.shields.io/badge/⭐_Stella_il_Progetto-8a2be2?style=for-the-badge&logo=github&logoColor=white&labelColor=2d1b69"/>
1166
+ </a>&nbsp;&nbsp;
1167
+ <a href="https://github.com/realvare/based/fork">
1168
+ <img src="https://img.shields.io/badge/🔄_Fork_Repository-8a2be2?style=for-the-badge&logo=github&logoColor=white&labelColor=2d1b69"/>
1169
+ </a>&nbsp;&nbsp;
1170
+ <a href="https://paypal.me/samakavare">
1171
+ <img src="https://img.shields.io/badge/💰_Dona-8a2be2?style=for-the-badge&logo=paypal&logoColor=white&labelColor=2d1b69"/>
1172
+ </a>
1173
+ </p>
1174
+ <p align="center">
1175
+ <a href="https://github.com/realvare">
1176
+ <img src="https://img.shields.io/badge/GitHub-100000?style=for-the-badge&logo=github&logoColor=white&color=8a2be2"/>
1177
+ </a>&nbsp;
1178
+ <a href="https://wa.me/393476686131">
1179
+ <img src="https://img.shields.io/badge/WhatsApp-25D366?style=for-the-badge&logo=whatsapp&logoColor=white&color=8a2be2"/>
1180
+ </a>&nbsp;
1181
+ <a href="https://instagram.com/samakavare">
1182
+ <img src="https://img.shields.io/badge/Instagram-E4405F?style=for-the-badge&logo=instagram&logoColor=white&color=8a2be2"/>
1183
+ </a>&nbsp;
1184
+ <a href="mailto:samakavare1@gmail.com">
1185
+ <img src="https://img.shields.io/badge/Email-D14836?style=for-the-badge&logo=gmail&logoColor=white&color=8a2be2"/>
1186
+ </a>
1187
+ </p>
1188
+ <div align="center">
1189
+ <p><strong>Se ti è stato utile, lascia una stella e/o considera una donazione! ✧</strong></p>
1190
+
1191
+ <br>
1192
+ <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"/>
1193
+
1194
+ </div>