@realvare/based 2.5.7 β†’ 2.5.71

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,1544 +1,1237 @@
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
- ## Indice
29
-
30
- - [✨ Caratteristiche Principali](#-caratteristiche-principali)
31
- - [πŸš€ Guida Rapida](#-guida-rapida)
32
- - [πŸ“Š Gestione Avanzata Cache](#-gestione-avanzata-cache)
33
- - [πŸ” Risoluzione Problemi](#-risoluzione-problemi)
34
- - [πŸ“š Documentazione API](#-documentazione-api)
35
- - [πŸ—οΈ Metodi Fondamentali](#-metodi-fondamentali)
36
- - [🎯 Eventi Principali](#-eventi-principali)
37
- - [πŸŽͺ Messaggi e FunzionalitΓ  Interattive](#-messaggi-e-funzionalit-interattive)
38
- - [Messaggi Base](#messaggi-base)
39
- - [Media Base](#media-base)
40
- - [Media Avanzati](#media-avanzati)
41
- - [Messaggi Interattivi](#messaggi-interattivi)
42
- - [Altri Messaggi](#altri-messaggi)
43
- - [Gestione delle Risposte](#gestione-delle-risposte)
44
- - [🎭 Funzionalità Gruppi](#-funzionalit-gruppi)
45
- - [Gestione Base Gruppi](#gestione-base-gruppi)
46
- - [Gestione Partecipanti](#gestione-partecipanti)
47
- - [Impostazioni Gruppo](#impostazioni-gruppo)
48
- - [Messaggi Gruppo Avanzati](#messaggi-gruppo-avanzati)
49
- - [πŸ”§ Fix LID/JID nel Proprio Main e Handler](#-fix-lidjid-nel-proprio-main-e-handler)
50
- - [Best Practices per LID/JID](#best-practices-per-lidjid)
51
- - [Esempio Integrato in Main](#esempio-integrato-in-main)
52
- - [Esempio Handler Personalizzato](#esempio-handler-personalizzato)
53
- - [πŸš€ Cache Intelligente LID/JID](#-cache-intelligente-lidjid)
54
- - [πŸ›‘οΈ Validazione JID Avanzata](#-validazione-jid-avanzata)
55
- - [πŸ“Š Logging Condizionale](#-logging-condizionale)
56
- - [πŸ”§ Configurazione Performance](#-configurazione-performance)
57
- - [🧩 Eventi: LID e JID sempre disponibili (nuovo)](#-eventi-lid-e-jid-sempre-disponibili-nuovo)
58
- - [βš™οΈ Configurazione Avanzata](#-configurazione-avanzata)
59
- - [πŸ”§ Opzioni Complete per makeWASocket](#-opzioni-complete-per-makewasocket)
60
- - [πŸ›‘οΈ Sicurezza e Crittografia](#-sicurezza-e-crittografia)
61
- - [🌐 Supporto e Community](#-supporto-e-community)
62
- - [πŸ“ž Contatti e Risorse](#-contatti-e-risorse)
63
- - [πŸ™ Ringraziamenti](#-ringraziamenti)
64
- - [⚠️ Disclaimer & Licenza](#-disclaimer--licenza)
65
- - [πŸ“‹ Nota Legale](#-nota-legale)
66
- - [πŸ“œ Licenza MIT](#-licenza-mit)
67
-
68
- ----
69
-
70
- ## ✨ Caratteristiche Principali
71
-
72
- <p align="center">
73
- <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">
74
- </div>
75
-
76
- <br>
77
-
78
- Questa libreria, basata su Baileys con miglioramenti specifici, offre un'API intuitiva per interagire con WhatsApp Web. Ecco un riassunto delle funzionalitΓ  chiave:
79
-
80
- <table align="center">
81
- <tr>
82
- <td align="center" width="25%">
83
- <h3>πŸ”„ Core Features</h3>
84
- <p>β€’ Mappatura intelligente LID/JID<br>β€’ Supporto multi-dispositivo<br>β€’ Crittografia E2E Signal<br>β€’ TypeScript moderno</p>
85
- </td>
86
- <td align="center" width="25%">
87
- <h3>πŸ’¬ Messaggi</h3>
88
- <p>β€’ Testo, media, interattivi<br>β€’ Bottoni, liste, carousel<br>β€’ Album, poll, reazioni<br>β€’ Template avanzati</p>
89
- </td>
90
- <td align="center" width="25%">
91
- <h3>πŸ› οΈ Developer</h3>
92
- <p>β€’ Eventi real-time<br>β€’ TypeScript completo<br>β€’ Documentazione estesa<br>β€’ API estendibili</p>
93
- </td>
94
- <td align="center" width="25%">
95
- <h3>⚑ Performance</h3>
96
- <p>β€’ Riconnessione intelligente<br>β€’ Cache avanzata TTL<br>β€’ Monitoraggio prestazioni</p>
97
- </td>
98
- </tr>
99
- </table>
100
- <p align="center">
101
- <img src="https://64.media.tumblr.com/13bc9e3c3b332dfc008cb4b9e8571558/2a577b39b15547dc-cc/s400x600/3db051b3117b695a61ad8e0b686f2774b971d210.gifv" width="800">
102
-
103
-
104
- ## πŸš€ Guida Rapida
105
-
106
- - Questa sezione include esempi base per l'autenticazione e la gestione delle connessioni.
107
-
108
- ### Esempio Base - Avvio Bot
109
-
110
- ```typescript
111
- import makeWASocket, { DisconnectReason, useMultiFileAuthState, getPerformanceConfig, setPerformanceConfig } from '@realvare/based';
112
-
113
- // Configura performance e cache
114
- setPerformanceConfig({
115
- performance: {
116
- enableCache: true,
117
- enableMetrics: true
118
- },
119
- debug: {
120
- enableLidLogging: true,
121
- logLevel: 'info'
122
- }
123
- });
124
-
125
- async function startBot() {
126
- // πŸ” Setup autenticazione multi-file per sessioni persistenti
127
- const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
128
-
129
- // 🌐 Creazione del socket con configurazione base
130
- const sock = makeWASocket({
131
- auth: state,
132
- printQRInTerminal: true,
133
- logger: console,
134
- browser: ['VareBot', 'Chrome', '4.0.0'],
135
- });
136
-
137
- // Sistema di riconnessione migliorato
138
- let reconnectAttempts = 0;
139
- const config = getPerformanceConfig();
140
-
141
- sock.ev.on('connection.update', (update) => {
142
- const { connection, lastDisconnect } = update;
143
-
144
- if (connection === 'close') {
145
- const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
146
-
147
- if (shouldReconnect) {
148
- reconnectAttempts++;
149
- const delay = Math.min(
150
- config.performance.retryDelay * Math.pow(
151
- config.performance.retryBackoffMultiplier,
152
- reconnectAttempts - 1
153
- ),
154
- config.performance.maxRetryDelay
155
- );
156
-
157
- console.log(`πŸ”„ Tentativo di riconnessione ${reconnectAttempts}/${config.performance.maxRetries} tra ${delay}ms`);
158
-
159
- if (reconnectAttempts <= config.performance.maxRetries) {
160
- setTimeout(startBot, delay);
161
- } else {
162
- console.log('❌ Numero massimo di tentativi di riconnessione raggiunto');
163
- }
164
- }
165
- } else if (connection === 'open') {
166
- console.log('🟒 Connesso con successo!');
167
- reconnectAttempts = 0;
168
- }
169
- });
170
-
171
- sock.ev.on('creds.update', saveCreds);
172
- }startBot().catch(console.error);
173
- ```
174
-
175
- ### Esempio Anti-Ban - Configurazione consigliata per Evitare Ban
176
-
177
- ```typescript
178
- import makeWASocket, { DisconnectReason, useMultiFileAuthState, getPerformanceConfig, setPerformanceConfig, getSenderLid, validateJid } from '@realvare/based';
179
-
180
- // Configurazione anti-ban per ridurre rischi ban da acks impropri
181
- setPerformanceConfig({
182
- performance: {
183
- enableCache: true, // Abilita cache TTL per ridurre chiamate API
184
- enableMetrics: true, // Monitora performance per evitare sovraccarico
185
- batchSize: 50, // Elabora messaggi in batch piΓΉ piccoli per simulare velocitΓ  umana
186
- maxRetries: 5, // Limita tentativi retry per evitare comportamento aggressivo
187
- retryDelay: 5000, // Ritardo base in ms per riconnessioni
188
- retryBackoffMultiplier: 1.5,// Backoff esponenziale per spaziare retry
189
- maxRetryDelay: 60000, // Ritardo massimo per evitare riconnessioni rapide
190
- maxMsgRetryCount: 3 // Limita tentativi rispedizione messaggi
191
- }
192
- });
193
-
194
- async function startBot() {
195
- const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
196
-
197
- const sock = makeWASocket({
198
- auth: state,
199
- printQRInTerminal: true,
200
- logger: console,
201
- browser: ['YourBotName', 'Chrome', '4.0.0'], // Personalizza fingerprint browser
202
- markOnlineOnConnect: false, // Cruciale: Previene apparire sempre online, riduce rischio ban
203
- syncFullHistory: false // Evita sync dati non necessari che potrebbero segnalare attivitΓ 
204
- });
205
-
206
- let reconnectAttempts = 0;
207
- const config = getPerformanceConfig();
208
-
209
- sock.ev.on('connection.update', (update) => {
210
- const { connection, lastDisconnect } = update;
211
-
212
- if (connection === 'close') {
213
- const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
214
-
215
- if (shouldReconnect) {
216
- reconnectAttempts++;
217
- const delay = Math.min(
218
- config.performance.retryDelay * Math.pow(
219
- config.performance.retryBackoffMultiplier,
220
- reconnectAttempts - 1
221
- ),
222
- config.performance.maxRetryDelay
223
- );
224
-
225
- console.log(`Reconnecting attempt ${reconnectAttempts}/${config.performance.maxRetries} in ${delay}ms`);
226
-
227
- if (reconnectAttempts <= config.performance.maxRetries) {
228
- setTimeout(startBot, delay);
229
- } else {
230
- console.log('Max reconnection attempts reached');
231
- }
232
- }
233
- } else if (connection === 'open') {
234
- console.log('Connected successfully!');
235
- reconnectAttempts = 0;
236
- }
237
- });
238
-
239
- // Monitora acks tramite aggiornamenti messaggi per garantire gestione corretta
240
- sock.ev.on('messages.update', (updates) => {
241
- for (const update of updates) {
242
- if (update.update.status) {
243
- console.log(`Message ${update.key.id} status: ${update.update.status}`); // Traccia acks (1=sent, 2=delivered, 3=read)
244
- // Aggiungi logica personalizzata se necessaria, ma evita override predefiniti per prevenire detection
245
- }
246
- }
247
- });
248
-
249
- // UtilitΓ  LID/JID avanzate per stabilitΓ  acks
250
- sock.ev.on('messages.upsert', ({ messages }) => {
251
- for (const msg of messages) {
252
- const info = getSenderLid(msg);
253
- const validation = validateJid(info.jid);
254
- if (validation.isValid) {
255
- // Elabora e ack in sicurezza
256
- console.log(`Valid JID: ${info.jid}, LID: ${info.lid}`);
257
- } else {
258
- console.warn(`Invalid JID detected: ${info.jid}`);
259
- }
260
- }
261
- });
262
-
263
- sock.ev.on('creds.update', saveCreds);
264
- }
265
-
266
- startBot().catch(console.error);
267
- ```
268
-
269
- ## πŸ“Š Gestione Avanzata Cache
270
-
271
- La libreria ora include un sistema di cache avanzato con gestione automatica della memoria e TTL configurabile:
272
-
273
- ```typescript
274
- import { CacheManager } from 'based/lib/Utils/cache-manager';
275
-
276
- // Esempio di utilizzo della cache
277
- const cache = CacheManager;
278
-
279
- // Salva un valore nella cache
280
- cache.set('lidCache', 'chiave', 'valore', 300); // TTL di 300 secondi
281
-
282
- // Recupera un valore
283
- const valore = cache.get('lidCache', 'chiave');
284
-
285
- // Ottieni statistiche della cache
286
- const stats = cache.getStats('lidCache');
287
- console.log('Statistiche cache:', stats);
288
- ```
289
-
290
- ### Configurazione Cache Avanzata
291
-
292
- La cache puΓ² essere configurata con varie opzioni per ottimizzare le prestazioni:
293
-
294
- ```typescript
295
- setPerformanceConfig({
296
- cache: {
297
- lidCache: {
298
- ttl: 5 * 60 * 1000, // Tempo di vita delle entries
299
- maxSize: 10000, // Numero massimo di entries
300
- cleanupInterval: 2 * 60 * 1000 // Intervallo pulizia
301
- }
302
- },
303
- performance: {
304
- memoryThreshold: 0.85 // Soglia per pulizia automatica
305
- }
306
- });
307
- ```
308
- ## πŸ” Risoluzione Problemi
309
-
310
- ### Problemi di Connessione
311
- - La libreria ora implementa un sistema di retry con backoff esponenziale
312
- - Monitoraggio automatico dello stato della connessione
313
- - Tentativi di riconnessione configurabili
314
-
315
- ### Gestione Memoria
316
- - Monitoraggio automatico dell'uso della memoria
317
- - Pulizia cache automatica quando necessario
318
- - TTL configurabile per ogni tipo di cache
319
-
320
- ### Logging Avanzato
321
- ```typescript
322
- setPerformanceConfig({
323
- debug: {
324
- enableLidLogging: true,
325
- enablePerformanceLogging: true,
326
- logLevel: 'debug'
327
- }
328
- });
329
- ```
330
-
331
- ### Gestione Messaggi Base con LID/JID
332
-
333
- ```typescript
334
- import makeWASocket, { getSenderLid, toJid, getCacheStats, validateJid, Logger } from '@realvare/based';
335
-
336
- // ... (codice di creazione sock qui)
337
-
338
- conn.ev.on('messages.upsert', ({ messages }) => {
339
- for (const msg of messages) {
340
- // πŸ” Estrai LID del mittente con validazione
341
- const info = getSenderLid(msg);
342
-
343
- // βœ… Valida JID prima di usarlo
344
- const validation = validateJid(info.jid);
345
- if (!validation.isValid) {
346
- Logger.error('JID non valido:', validation.error);
347
- continue;
348
- }
349
-
350
- const jid = toJid(info.lid); // Normalizza in JID
351
-
352
- Logger.info('πŸ’¬ Messaggio da:', jid, 'Valid:', info.isValid);
353
- console.log('πŸ“ Contenuto:', msg.message?.conversation);
354
-
355
- // Rispondi automaticamente solo se valido
356
- if (info.isValid) {
357
- conn.sendMessage(jid, { text: 'Messaggio ricevuto!' });
358
- }
359
- }
360
-
361
- // πŸ“Š Monitora performance cache
362
- const stats = getCacheStats();
363
- Logger.performance('Cache stats:', stats);
364
- });
365
- ```
366
-
367
- ---
368
-
369
- ## πŸ“š Documentazione API
370
-
371
- Questa sezione espande i metodi principali, con esempi dettagliati e parametri. Tutti i metodi sono tipizzati in TypeScript per un'esperienza di sviluppo sicura.
372
-
373
- ### πŸ—οΈ Metodi Fondamentali
374
-
375
- <details>
376
- <summary><strong>πŸ“‘ makeWASocket(config)</strong></summary>
377
-
378
- Crea un'istanza del socket WhatsApp. È il punto di ingresso principale.
379
-
380
- **Parametri:**
381
- - `config`: Oggetto con opzioni (vedi sezione Configurazione Avanzata per dettagli completi).
382
-
383
- **Restituisce:** Istanza del socket con metodi come `sendMessage` e `ev` per eventi.
384
-
385
- **Esempio:**
386
- ```typescript
387
- const sock = makeWASocket({
388
- auth: state,
389
- printQRInTerminal: true,
390
- logger: console,
391
- browser: ['Varebot', 'Chrome', '4.0.0'],
392
- });
393
- ```
394
- </details>
395
- <details>
396
- <summary><strong>πŸ” useMultiFileAuthState(folder)</strong></summary>
397
-
398
- Gestisce l'autenticazione persistente salvando credenziali in file multipli per sicurezza.
399
-
400
- **Parametri:**
401
- - `folder`: Stringa, path della cartella per i file di auth (es. 'auth_info').
402
-
403
- **Restituisce:**
404
- - `{ state, saveCreds }`: Stato autenticazione e funzione per salvare aggiornamenti.
405
-
406
- **Esempio:**
407
- ```typescript
408
- const { state, saveCreds } = await useMultiFileAuthState('auth_info');
409
- conn.ev.on('creds.update', saveCreds); // Integra nel socket
410
- ```
411
- </details>
412
-
413
- <details>
414
- <summary><strong>πŸ”„ getSenderLid(message) & toJid(lid)</strong></summary>
415
-
416
- UtilitΓ  per gestire LID/JID, risolvendo problemi comuni in gruppi e multi-dispositivo.
417
-
418
- **getSenderLid(message):**
419
- - Estrae LID dal messaggio.
420
- - Restituisce: Oggetto con `lid` e altre info mittente.
421
-
422
- **toJid(lid):**
423
- - Converte LID in JID normalizzato (es. prende pn e aggiunge `@s.whatsapp.net`).
424
-
425
- **Esempio:**
426
- ```typescript
427
- const info = getSenderLid(msg);
428
- const jid = toJid(info.lid);
429
- conn.sendMessage(jid, { text: 'we ridin porsches in the rain' });
430
- ```
431
- </details>
432
-
433
- <details>
434
- <summary><strong>πŸ“€ sendMessage(jid, content, options)</strong></summary>
435
-
436
- Invia messaggi di vari tipi. Supporta testo, media, interattivi.
437
-
438
- **Parametri:**
439
- - `jid`: Stringa JID del destinatario.
440
- - `content`: Oggetto messaggio (es. { text: 'finche vedo tutto violaviola' }).
441
- - `options`: Opzionale, include `quoted`, `mentions`, ecc.
442
-
443
- **Esempio Testo Semplice:**
444
- ```typescript
445
- await conn.sendMessage(jid, { text: 'bankai!' });
446
- ```
447
- </details>
448
-
449
- <details>
450
- <summary><strong>πŸ“€ sendMessage(jid, content, options) - External Ad Reply (sendNyanCat)</strong></summary>
451
-
452
- Invia un messaggio con contesto esterno (ad esempio, un'anteprima).
453
-
454
- **Parametri:**
455
- - `jid`: JID del destinatario.
456
- - `content`: Oggetto con `externalAdReply` e `text`.
457
- - `options`: Opzioni aggiuntive.
458
-
459
- **Esempio:**
460
- ```typescript
461
- await conn.sendMessage(jid, {
462
- text: 'Testo del messaggio',
463
- externalAdReply: {
464
- title: 'Titolo dell\'anteprima',
465
- body: 'Corpo dell\'anteprima',
466
- thumbnailUrl: 'https://example.com/thumbnail.jpg',
467
- sourceUrl: 'https://example.com',
468
- mediaType: 1,
469
- showAdAttribution: false,
470
- renderLargerThumbnail: false
471
- }
472
- });
473
- ```
474
- </details>
475
-
476
- <details>
477
- <summary><strong>πŸ“€ sendMessage(jid, content, options) - Payment Request (sendPayment)</strong></summary>
478
-
479
- Invia un messaggio di richiesta pagamento.
480
-
481
- **Parametri:**
482
- - `jid`: JID del destinatario.
483
- - `content`: Oggetto con `payment`.
484
- - `options`: Opzioni aggiuntive.
485
-
486
- **Esempio:**
487
- ```typescript
488
- await conn.sendMessage(jid, {
489
- payment: {
490
- currency: 'EUR',
491
- amount1000: 5000, // 50.00 EUR
492
- requestFrom: 'your-jid@s.whatsapp.net',
493
- text: 'Pagamento richiesto per il servizio',
494
- expiryTimestamp: Date.now() + 86400000 // 24 ore
495
- }
496
- });
497
- ```
498
- </details>
499
-
500
- <details>
501
- <summary><strong>πŸ“€ sendMessage(jid, content, options) - File Download (getFile)</strong></summary>
502
-
503
- Ottiene un file da path, URL o buffer, con tipo MIME.
504
-
505
- **Parametri:**
506
- - `PATH`: Path, URL o buffer.
507
- - `saveToFile`: Booleano per salvare su file.
508
-
509
- **Restituisce:** Oggetto con res, filename, mime, ext, data.
510
-
511
- **Esempio:**
512
- ```typescript
513
- const file = await conn.getFile('https://example.com/image.jpg');
514
- ```
515
- </details>
516
-
517
- <details>
518
- <summary><strong>πŸ“€ sendMessage(jid, content, options) - Forward Message (relayWAMessage)</strong></summary>
519
-
520
- Inoltra un messaggio WA con presenza di composizione/registrazione.
521
-
522
- **Parametri:**
523
- - `jid`: JID destinatario.
524
- - `content`: Oggetto con `forward` contenente il messaggio da inoltrare.
525
-
526
- **Esempio:**
527
- ```typescript
528
- await conn.sendMessage(jid, {
529
- forward: messageToForward
530
- });
531
- ```
532
- </details>
533
-
534
- <details>
535
- <summary><strong>πŸ“€ sendMessage(jid, content, options) - Send File/Media (sendFile)</strong></summary>
536
-
537
- Invia un file/media con rilevamento automatico del tipo.
538
-
539
- **Parametri:**
540
- - `jid`: JID destinatario.
541
- - `content`: Oggetto con tipo media (image, video, document, audio) e URL/path.
542
-
543
- **Esempio:**
544
- ```typescript
545
- await conn.sendMessage(jid, {
546
- image: { url: './image.jpg' },
547
- caption: 'Caption'
548
- });
549
- ```
550
- </details>
551
-
552
- <details>
553
- <summary><strong>πŸ“€ sendMessage(jid, content, options) - Send Contact (sendContact)</strong></summary>
554
-
555
- Invia uno o piΓΉ contatti.
556
-
557
- **Parametri:**
558
- - `jid`: JID destinatario.
559
- - `content`: Oggetto con `contacts`.
560
-
561
- **Esempio:**
562
- ```typescript
563
- await conn.sendMessage(jid, {
564
- contacts: {
565
- displayName: 'Nome Contatto',
566
- contacts: [{ vcard: 'BEGIN:VCARD\nVERSION:3.0\nFN:Nome\nTEL;waid=1234567890:+1 234 567 890\nEND:VCARD' }]
567
- }
568
- });
569
- ```
570
- </details>
571
-
572
- <details>
573
- <summary><strong>πŸ“€ sendMessage(jid, content, options) - Reply (reply)</strong></summary>
574
-
575
- Rispondi a un messaggio.
576
-
577
- **Parametri:**
578
- - `jid`: JID chat.
579
- - `content`: Testo o oggetto media.
580
- - `options`: Oggetto con `quoted` contenente il messaggio da quotare.
581
-
582
- **Esempio:**
583
- ```typescript
584
- await conn.sendMessage(jid, {
585
- text: 'Risposta al messaggio'
586
- }, {
587
- quoted: messageToReplyTo
588
- });
589
- ```
590
- </details>
591
-
592
- <details>
593
- <summary><strong>πŸ“€ sendMessage(jid, content, options) - Send Button (sendButton)</strong></summary>
594
-
595
- Invia un messaggio con bottoni interattivi.
596
-
597
- **Parametri:**
598
- - `jid`: JID destinatario.
599
- - `content`: Oggetto con `text`, `footer`, `buttons`.
600
-
601
- **Esempio:**
602
- ```typescript
603
- await conn.sendMessage(jid, {
604
- text: 'Scegli un\'opzione:',
605
- footer: 'Footer',
606
- buttons: [
607
- { buttonId: 'opt1', buttonText: { displayText: 'Opzione 1' }, type: 1 },
608
- { buttonId: 'opt2', buttonText: { displayText: 'Opzione 2' }, type: 1 }
609
- ]
610
- });
611
- ```
612
- </details>
613
-
614
- <details>
615
- <summary><strong>πŸ“€ sendMessage(jid, content, options) - Send Album (sendAlbumMessage)</strong></summary>
616
-
617
- Invia un album di immagini/video.
618
-
619
- **Parametri:**
620
- - `jid`: JID destinatario.
621
- - `content`: Oggetto con `album` contenente array di media.
622
-
623
- **Esempio:**
624
- ```typescript
625
- await conn.sendMessage(jid, {
626
- album: [
627
- { image: buffer1, caption: 'Prima immagine' },
628
- { image: buffer2, caption: 'Seconda immagine' }
629
- ]
630
- });
631
- ```
632
- </details>
633
-
634
- <details>
635
- <summary><strong>πŸ“€ sendMessage(jid, content, options) - Send Carousel (sendNCarousel/sendCarousel)</strong></summary>
636
-
637
- Invia un carousel di card.
638
-
639
- **Parametri:**
640
- - `jid`: JID destinatario.
641
- - `content`: Oggetto con `cards` contenente array di card.
642
-
643
- **Esempio:**
644
- ```typescript
645
- await conn.sendMessage(jid, {
646
- text: 'Scegli una categoria:',
647
- footer: 'Footer carousel',
648
- cards: [
649
- {
650
- image: { url: 'https://example.com/image1.jpg' },
651
- title: 'Card 1',
652
- body: 'Descrizione card 1',
653
- buttons: [
654
- { name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: 'Seleziona', id: 'card1' }) }
655
- ]
656
- },
657
- {
658
- image: { url: 'https://example.com/image2.jpg' },
659
- title: 'Card 2',
660
- body: 'Descrizione card 2',
661
- buttons: [
662
- { name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: 'Seleziona', id: 'card2' }) }
663
- ]
664
- }
665
- ]
666
- });
667
- ```
668
- </details>
669
-
670
- ### 🎯 Eventi Principali
671
-
672
- | Evento | Descrizione | Callback Signature |
673
- |---------------------|--------------------------------------|-------------------------------------|
674
- | `connection.update` | Aggiornamenti stato connessione | `(update: Partial<ConnectionState>) => void` |
675
- | `creds.update` | Aggiornamento credenziali | `() => void` |
676
- | `messages.upsert` | Nuovi messaggi o aggiornamenti | `({ messages: WAMessage[], type: MessageUpsertType }) => void` |
677
- | `messages.update` | Modifiche a messaggi esistenti | `(update: WAMessageUpdate[]) => void` |
678
- | `group-participants.update` | Cambiamenti partecipanti gruppo | `(update: GroupParticipantEvent) => void` |
679
-
680
- **Esempio Registrazione Evento:**
681
- ```typescript
682
- conn.ev.on('group-participants.update', (update) => {
683
- console.log('Partecipante aggiornato:', update);
684
- });
685
- ```
686
-
687
- ---
688
-
689
- ## πŸŽͺ Messaggi e FunzionalitΓ  Interattive
690
-
691
- ### Messaggi Base
692
-
693
- #### Testo con Formattazione
694
- ```typescript
695
- // Testo con formattazione e menzioni
696
- await conn.sendMessage(jid, {
697
- text: `*Bold* _italic_ ~strikethrough~ \`monospace\`\n@menzione`,
698
- mentions: ['393476686131@s.whatsapp.net']
699
- });
700
- ```
701
-
702
- #### Media Base
703
- ```typescript
704
- // Immagine
705
- await conn.sendMessage(jid, {
706
- image: { url: './media/varebot.jpg' }, // Supporta anche Buffer
707
- caption: 'zwag'
708
- });
709
-
710
- // Video
711
- await conn.sendMessage(jid, {
712
- video: { url: './media/oppastoppa.mp4' },
713
- caption: 'brrrr',
714
- gifPlayback: false // true per riprodurre come GIF
715
- });
716
-
717
- // Audio
718
- await conn.sendMessage(jid, {
719
- audio: { url: './media/audio.mp3' },
720
- mimetype: 'audio/mp4',
721
- ptt: true // true per messaggio vocale, false per audio normale
722
- });
723
-
724
- // Documento
725
- await conn.sendMessage(jid, {
726
- document: { url: './media/doc.pdf' },
727
- mimetype: 'application/pdf',
728
- fileName: 'documento.pdf'
729
- });
730
- ```
731
-
732
- #### Media Avanzati
733
- ```typescript
734
- // Album (Multiple immagini)
735
- await conn.sendMessage(jid, {
736
- album: imageBuffers.map(buffer => ({ image: buffer })),
737
- caption: 'ts gettin real'
738
- });
739
-
740
- // Sticker
741
- await conn.sendMessage(jid, {
742
- sticker: { url: './stickers/sticker.webp' }
743
- });
744
-
745
- // Messaggio con posizione
746
- await conn.sendMessage(jid, {
747
- location: {
748
- degreesLatitude: 45.4642,
749
- degreesLongitude: 9.1900,
750
- name: "Milano",
751
- address: "Piazza del Duomo, Milano"
752
- }
753
- });
754
- ```
755
-
756
- #### Messaggi Interattivi
757
- Questi messaggi includono elementi interattivi come bottoni, liste e template.
758
-
759
- ##### Messaggi con Bottoni Semplici
760
- Invia bottoni di risposta rapida.
761
-
762
- ```typescript
763
- await conn.sendMessage(jid, {
764
- text: 'Scegli un\'opzione:',
765
- footer: 'Footer',
766
- buttons: [
767
- { buttonId: 'cmd1', buttonText: { displayText: 'testo1' }, type: 1 },
768
- { buttonId: 'cmd2', buttonText: { displayText: 'testo2' }, type: 1 },
769
- ],
770
- headerType: 1,
771
- });
772
- ```
773
-
774
- ##### Messaggi con Bottoni e Immagine
775
- Combina immagine con bottoni.
776
-
777
- ```typescript
778
- await conn.sendMessage(jid, {
779
- image: { url: 'https://i.ibb.co/hJW7WwxV/varebot.jpg' },
780
- caption: 'Messaggio con bottoni e immagine',
781
- footer: 'vare ✧ bot',
782
- buttons: [
783
- { buttonId: 'cmd', buttonText: { displayText: 'testo1' }, type: 1 },
784
- ],
785
- });
786
- ```
787
-
788
- ##### Messaggi Liste
789
- Invia una lista di opzioni (solo in privato).
790
-
791
- ```typescript
792
- await conn.sendMessage(jid, {
793
- text: 'Questa Γ¨ una lista!',
794
- footer: 'purplepurplepurple!',
795
- title: 'Titolo Lista',
796
- buttonText: 'Visualizza Lista',
797
- sections: [
798
- {
799
- title: 'Sezione 1',
800
- rows: [
801
- { title: 'Opzione 1', rowId: 'opt1',description: 'Descrizionex' },
802
- { title: 'Opzione 2', rowId: 'opt2', description: 'Descrizioney' }
803
- ]
804
- },
805
- ],
806
- });
807
- ```
808
-
809
- ##### Carousel e Card Messages
810
- Il carousel Γ¨ un tipo speciale di messaggio che permette di mostrare una serie di card scorrevoli.
811
- ```typescript
812
- await conn.sendMessage(jid, {
813
- text: 'γ€– 🌸 γ€— Benvenuto in VareBot!',
814
- title: '',
815
- footer: '',
816
- cards: [
817
- {
818
- image: { url: 'https://i.ibb.co/hJW7WwxV/varebot.jpg' },
819
- title: 'by sam aka vare',
820
- body: 'γ€– πŸ’« γ€— Esplora funzionalitΓ \nγ€– πŸš€ γ€— Bot aggiornato',
821
- footer: '˗ˏˋ ☾ πšŸπšŠπš›πšŽπš‹πš˜πš ☽ ΛŽΛŠΛ—',
822
- buttons: [
823
- { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: 'Sito VareBot', url: 'https://varebot.netlify.app' }) },
824
- { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: 'πŸ’» GitHub', url: 'https://github.com/realvare' }) },
825
- { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: 'πŸ’¬ WhatsApp', url: 'https://wa.me/393476686131' }) },
826
- { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: 'πŸ“Έ Instagram', url: 'https://instagram.com/samakavare' }) },
827
- { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: 'πŸ“§ Email', url: 'mailto:samakavare1@gmail.com' }) },
828
- ],
829
- },
830
- ],
831
- }, { quoted: m });
832
- ```
833
-
834
- #### Altri Messaggi
835
- ```typescript
836
- // Messaggio con citazione
837
- await conn.sendMessage(jid, {
838
- text: 'bang bang',
839
- quoted: quotedMessage // Il messaggio da quotare/rispondere/citare
840
- });
841
-
842
- // Messaggi Contatto
843
- await conn.sendMessage(jid, {
844
- contacts: {
845
- displayName: 'Sam aka vare',
846
- contacts: [{ vcard: 'BEGIN:VCARD\nVERSION:3.0\nFN:Sam aka vare\nTEL;waid=393476686131:+39 347 6686131\nEND:VCARD' }]
847
- }
848
- });
849
-
850
- // Messaggi Poll (Sondaggio)
851
- await conn.sendMessage(jid, {
852
- poll: {
853
- name: 'Anime preferito?',
854
- values: ['Aot', 'Bleach', 'Death note'],
855
- selectableCount: 1 // quante scelte possibili
856
- }
857
- });
858
-
859
- // Messaggi Ephemeral (Che si Autodistruggono)
860
- await conn.sendMessage(jid, {
861
- text: "Questo messaggio si autodistruggerΓ  {speriamo come israele}"
862
- }, {
863
- ephemeralExpiration: 7 * 24 * 60 * 60
864
- });
865
-
866
- // Messaggi con Risposta a Visualizzazione
867
- await conn.sendMessage(
868
- jid,
869
- {
870
- video: { url: './media/hado90.mp4' },
871
- viewOnce: true,
872
- caption: 'tuff'
873
- }
874
- )
875
-
876
- // Messaggi di Status (Stato)
877
- await conn.sendMessage('status@broadcast', {
878
- text: 'god forgive em'
879
- }, {
880
- statusJidList: contatti
881
- });
882
-
883
- // Invia uno stato con media (visibile solo a contatti selezionati)
884
- await conn.sendMessage('status@broadcast', {
885
- image: { url: './media/menu/menu.jpg' },
886
- caption: 'all i need in this life of sin is-',
887
- }, {
888
- statusJidList: contatti
889
- });
890
-
891
- // Messaggi Newsletter
892
- await conn.sendMessage('120363418582531215@newsletter', {
893
- text: 'ay yo',
894
- });
895
-
896
- // Messaggi di Pagamento
897
- await conn.sendMessage(jid, {
898
- requestPayment: {
899
- currency: 'EUR',
900
- amount1000: 5000,
901
- requestFrom: '393514357738@s.whatsapp.net',
902
- note: 'js gimme my money' // https://paypal.me/samakavare
903
- }
904
- });
905
-
906
- // Messaggi di Chiamata
907
- await conn.sendMessage(jid, {
908
- call: {
909
- callKey: {
910
- fromMe: true,
911
- id: Date.now().toString(),
912
- remoteJid: jid
913
- },
914
- type: 'ACCEPT' // 'MISSED', 'OFFER', 'ACCEPT', 'REJECT'..
915
- }
916
- });
917
-
918
- // Messaggi con Live Location
919
- await conn.sendMessage(jid, {
920
- liveLocation: {
921
- degreesLatitude: 45.4642,
922
- degreesLongitude: 9.1900,
923
- accuracyInMeters: 50,
924
- speedInMps: 5,
925
- degreesClockwiseFromMagneticNorth: 359,
926
- caption: "kmt im mean kiss my teeth",
927
- sequenceNumber: 21,
928
- timeOffset: 2000,
929
- }
930
- });
931
-
932
- // Messaggi di Ordini/Prodotti
933
- await conn.sendMessage(jid, {
934
- order: {
935
- id: 'bysamakavare',
936
- thumbnail: buffer, // immagine buffer
937
- itemCount: 67,
938
- surface: 'CATALOG',
939
- title: 'heh',
940
- text: 'gotta make it happen',
941
- seller: '393514357738@s.whatsapp.net',
942
- amount: 67000,
943
- currency: 'EUR'
944
- }
945
- });
946
-
947
- // Prodotto
948
- await conn.sendMessage(jid, {
949
- product: {
950
- productImage: { url: './media/menu/menu.jpg' },
951
- productId: 'prod123',
952
- title: 'titolo',
953
- description: 'Desc',
954
- currency: 'EUR',
955
- priceAmount1000: 67000,
956
- retailerId: 'bysamakavare',
957
- url: 'https://varebot.netlify.app',
958
- },
959
- businessOwnerJid: m.sender
960
- });
961
-
962
- // Messaggi con Intestazione Personalizzata
963
- await conn.sendMessage(jid, {
964
- text: 'dilemma',
965
- contextInfo: {
966
- externalAdReply: {
967
- title: `titolo`,
968
- body: `desc`,
969
- thumbnailUrl: 'https://i.ibb.co/hJW7WwxV/sam.jpg', // immagine
970
- sourceUrl: '', // sconsiglio di metterla
971
- mediaType: 1,
972
- renderLargerThumbnail: false
973
- }
974
- }
975
- });
976
- > nota: non usate showAdAttribution o tenetela in false, poiche con essa attiva non viene visualizzato il messaggio
977
- ```
978
-
979
- ### Gestione delle Risposte
980
-
981
- Per gestire le risposte ai messaggi interattivi, usa il listener `messages.upsert` e controlla il tipo di risposta:
982
-
983
- ```typescript
984
- conn.ev.on('messages.upsert', async ({ messages }) => {
985
- const msg = messages[0];
986
-
987
- // Risposta a bottoni
988
- if (msg.message?.buttonsResponseMessage) {
989
- const selectedId = msg.message.buttonsResponseMessage.selectedButtonId;
990
- console.log(`Bottone selezionato: ${selectedId}`);
991
- }
992
-
993
- // Risposta a liste
994
- if (msg.message?.listResponseMessage) {
995
- const selectedId = msg.message.listResponseMessage.singleSelectReply.selectedRowId;
996
- console.log(`Opzione selezionata: ${selectedId}`);
997
- }
998
-
999
- // Risposta a sondaggio
1000
- if (msg.message?.pollResponseMessage) {
1001
- const selectedOptions = msg.message.pollResponseMessage.selectedOptions;
1002
- console.log('Opzioni selezionate:', selectedOptions);
1003
- }
1004
- });
1005
- ```
1006
-
1007
- ### 🎭 Funzionalità Gruppi
1008
-
1009
- #### Gestione Base Gruppi
1010
-
1011
- ```typescript
1012
- // Creazione gruppo - il jid sta per l'aggiunta di partecipanti
1013
- const group = await conn.groupCreate('Angels πŸ©ΈπŸ•ŠοΈ', ['user@s.whatsapp.net']);
1014
-
1015
- // Ottenere info gruppo
1016
- const metadata = await conn.groupMetadata(jid);
1017
-
1018
- // Ottenere codice invito
1019
- const code = await conn.groupInviteCode(jid);
1020
-
1021
- // Revocare link invito
1022
- await conn.groupRevokeInvite(jid);
1023
-
1024
- // Lasciare gruppo
1025
- await conn.groupLeave(jid);
1026
- ```
1027
-
1028
- #### Gestione Partecipanti
1029
-
1030
- ```typescript
1031
- // Aggiungere partecipanti
1032
- await conn.groupParticipantsUpdate(
1033
- jid,
1034
- ['user@s.whatsapp.net'],
1035
- 'add'
1036
- );
1037
-
1038
- // Rimuovere partecipanti
1039
- await conn.groupParticipantsUpdate(
1040
- jid,
1041
- ['user@s.whatsapp.net'],
1042
- 'remove'
1043
- );
1044
-
1045
- // Promuovere ad admin
1046
- await conn.groupParticipantsUpdate(
1047
- jid,
1048
- ['user@s.whatsapp.net'],
1049
- 'promote'
1050
- );
1051
-
1052
- // Degradare da admin
1053
- await conn.groupParticipantsUpdate(
1054
- jid,
1055
- ['user@s.whatsapp.net'],
1056
- 'demote'
1057
- );
1058
- ```
1059
-
1060
- #### Impostazioni Gruppo
1061
-
1062
- ```typescript
1063
- // Modificare nome gruppo
1064
- await conn.groupUpdateSubject(jid, 'Nuovo Nome');
1065
-
1066
- // Modificare descrizione
1067
- await conn.groupUpdateDescription(jid, 'Nuova descrizione');
1068
-
1069
- // Modificare foto gruppo
1070
- await conn.updateProfilePicture(jid, { url: './img/group.jpg' });
1071
-
1072
- // Rimuovere foto gruppo
1073
- await conn.removeProfilePicture(jid);
1074
-
1075
- // Impostare gruppo come solo admin
1076
- await conn.groupSettingUpdate(jid, 'announcement');
1077
-
1078
- // Impostare gruppo come aperto a tutti
1079
- await conn.groupSettingUpdate(jid, 'not_announcement');
1080
-
1081
- // Impostare chi puΓ² modificare le info - solo admin
1082
- await conn.groupSettingUpdate(jid, 'locked');
1083
-
1084
- // Impostare chi puΓ² modificare le info - tutti
1085
- await conn.groupSettingUpdate(jid, 'unlocked');
1086
-
1087
- // Impostare chi puΓ² aggiungere membri - solo admin
1088
- await conn.groupMemberAddMode(jid, 'admin_add');
1089
-
1090
- // Impostare chi puΓ² aggiungere membri - tutti
1091
- await conn.groupMemberAddMode(jid, 'all_member_add');
1092
-
1093
- // Attivare/disattivare messaggi temporanei (24 ore)
1094
- await conn.groupToggleEphemeral(jid, 86400); // secondi
1095
-
1096
- // Disattivare messaggi temporanei
1097
- await conn.groupToggleEphemeral(jid, 0);
1098
-
1099
- // Attivare/disattivare modalitΓ  approvazione adesioni
1100
- await conn.groupJoinApprovalMode(jid, 'on'); // richiede approvazione
1101
- await conn.groupJoinApprovalMode(jid, 'off'); // aperta
1102
-
1103
- // Ottenere tutti i gruppi
1104
- const groups = await conn.groupFetchAllParticipating();
1105
-
1106
- // Ottenere inviti pendenti
1107
- const invites = await conn.groupGetInviteInfo(code);
1108
-
1109
- // Accettare invito gruppo
1110
- await conn.groupAcceptInvite(code);
1111
-
1112
- // Ottenere info gruppo da link
1113
- const groupInfo = await conn.groupGetInviteInfo('https://chat.whatsapp.com/ABC123');
1114
-
1115
- // Ascolta modifiche impostazioni
1116
- conn.ev.on('group-settings.update', async ({ id, announce, restrict }) => {
1117
- if (announce !== undefined) {
1118
- await conn.sendMessage(id, { text: `Il gruppo Γ¨ stato impostato come ${announce ? 'solo admin' : 'tutti'}` });
1119
- }
1120
- if (restrict !== undefined) {
1121
- await conn.sendMessage(id, { text: `Le info gruppo possono essere modificate da ${restrict ? 'solo admin' : 'tutti'}` });
1122
- }
1123
- });
1124
- ```
1125
-
1126
- #### Messaggi Gruppo Avanzati
1127
-
1128
- ```typescript
1129
- // Messaggio con menzione multipla
1130
- await conn.sendMessage(jid, {
1131
- text: '@user1 @user2 @user3',
1132
- mentions: [user1, user2, user3],
1133
- contextInfo: {
1134
- mentionedJid: [user1, user2, user3]
1135
- }
1136
- });
1137
-
1138
- // Messaggio con ricerca google
1139
- await conn.sendMessage(jid, {
1140
- text: 'ZWAG',
1141
- contextInfo: {
1142
- forwardingScore: 999,
1143
- isForwarded: true
1144
- }
1145
- });
1146
- ```
1147
-
1148
- ---
1149
-
1150
- ## πŸ”§ Fix LID/JID nel Proprio Main e Handler
1151
-
1152
- *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.*
1153
-
1154
- ### Best Practices per LID/JID
1155
-
1156
- - **decodeJid(jid)**: Funzione principale per normalizzare JID/LID. Gestisce:
1157
- - Formati con `:\d+@` (usa `jidNormalizedUser`).
1158
- - Decodifica user/server in `${user}@${server}`.
1159
- - Converti `@lid` in `@s.whatsapp.net`.
1160
-
1161
- **Esempio di Implementazione (da main.js):**
1162
- ```typescript
1163
- decodeJid: (jid) => {
1164
- if (!jid) return jid;
1165
- let decoded = jid;
1166
- if (/:\d+@/gi.test(jid)) {
1167
- decoded = jidNormalizedUser(jid);
1168
- }
1169
- if (typeof decoded === 'object' && decoded.user && decoded.server) {
1170
- decoded = `${decoded.user}@${decoded.server}`;
1171
- }
1172
- if (decoded.endsWith('@lid')) {
1173
- decoded = decoded.replace('@lid', '@s.whatsapp.net');
1174
- }
1175
- return decoded;
1176
- },
1177
- ```
1178
- Usa `conn.decodeJid(jid)` ovunque per normalizzare IDs (es. sender, participant, quoted).
1179
-
1180
- - **Monkey-Patch per groupParticipantsUpdate**: Corregge aggiornamenti partecipanti gruppo trovando il JID reale dal metadata.
1181
-
1182
- **Esempio (da handler.js):**
1183
- ```typescript
1184
- if (!this.originalGroupParticipantsUpdate) {
1185
- this.originalGroupParticipantsUpdate = this.groupParticipantsUpdate;
1186
- this.groupParticipantsUpdate = async function(chatId, users, action) {
1187
- try {
1188
- let metadata = global.groupCache.get(chatId);
1189
- if (!metadata) {
1190
- metadata = await fetchGroupMetadataWithRetry(this, chatId);
1191
- if (metadata) global.groupCache.set(chatId, metadata);
1192
- }
1193
- if (!metadata) {
1194
- console.error('[ERRORE] Nessun metadato del gruppo disponibile per un aggiornamento sicuro');
1195
- return this.originalGroupParticipantsUpdate.call(this, chatId, users, action);
1196
- }
1197
-
1198
- const correctedUsers = users.map(userJid => {
1199
- const decoded = this.decodeJid(userJid);
1200
- const phone = decoded.split('@')[0].split(':')[0];
1201
- const participant = metadata.participants.find(p => {
1202
- const pId = this.decodeJid(p.id || p.jid || '');
1203
- const pPhone = pId.split('@')[0].split(':')[0];
1204
- return pPhone === phone;
1205
- });
1206
- return participant ? participant.id : userJid; // Fallback all'originale se non trovato
1207
- });
1208
-
1209
- return this.originalGroupParticipantsUpdate.call(this, chatId, correctedUsers, action);
1210
- } catch (e) {
1211
- console.error('[ERRORE] Errore in safeGroupParticipantsUpdate:', e);
1212
- throw e;
1213
- }
1214
- };
1215
- }
1216
- ```
1217
-
1218
- - **Cache per Metadata Gruppo**: Usa NodeCache per memorizzare metadata, normalizzando con `decodeJid`.
1219
-
1220
- **Esempio (da handler.js):**
1221
- ```typescript
1222
- global.groupCache = new NodeCache({ stdTTL: 5 * 60, useClones: false });
1223
-
1224
- // In participantsUpdate o groups.update:
1225
- metadata.participants.forEach(u => {
1226
- const normId = this.decodeJid(u.id);
1227
- const jid = u.jid || normId;
1228
- });
1229
- global.groupCache.set(update.id, metadata);
1230
- ```
1231
-
1232
- - **Normalizzazione in Print/Log**: Rimuovi `:xx` dai numeri telefono per clean display.
1233
-
1234
- **Esempio (da print.js):**
1235
- ```typescript
1236
- function formatPhoneNumber(jid, name) {
1237
- if (!jid) return 'Sconosciuto';
1238
- let userPart = jid.split('@')[0];
1239
- let cleanNumber = userPart.split(':')[0]; // Rimuovi la parte :xx per ottenere il numero reale
1240
- try {
1241
- const number = PhoneNumber('+' + cleanNumber).getNumber('international');
1242
- return number + (name ? ` ~${name}` : '');
1243
- } catch {
1244
- return (cleanNumber || '') + (name ? ` ~${name}` : '');
1245
- }
1246
- }
1247
- ```
1248
-
1249
- - **Problemi Comuni e Fix:**
1250
- - **LID Mancante in Gruppi:** Usa `decodeJid` e cache metadata per trovare JID reali.
1251
- - **Conversione JID:** Sempre applica `decodeJid` prima di `sendMessage` o query.
1252
- - **Multi-Dispositivo:** Imposta `syncFullHistory: true` in config per sync LID.
1253
- - **Errori in Mention/Quoted:** Normalizza con `decodeJid` in handler per quoted.sender e mentionedJid.
1254
-
1255
- ### Esempio Integrato in Main
1256
-
1257
- ```typescript
1258
- // Nel tuo file main
1259
- import makeWASocket, { getSenderLid, toJid } from '@realvare/based';
1260
- // ... (autenticazione e creazione sock)
1261
-
1262
- conn.ev.on('messages.upsert', async ({ messages }) => {
1263
- const msg = messages[0];
1264
- if (!msg.message) return;
1265
-
1266
- const info = getSenderLid(msg);
1267
- const senderJid = toJid(info.lid); // Fix LID -> JID
1268
-
1269
- // Esempio: Rispondi solo se JID valido
1270
- if (senderJid.endsWith('@s.whatsapp.net')) {
1271
- await conn.sendMessage(senderJid, { text: `Ciao da ${senderJid}!` }, { quoted: msg });
1272
- }
1273
- });
1274
- ```
1275
-
1276
- ### Esempio Handler Personalizzato
1277
-
1278
- Crea un handler separato per modularitΓ :
1279
-
1280
- ```typescript
1281
- // handler.js
1282
- export async function handleMessage(sock, msg) {
1283
- const info = getSenderLid(msg);
1284
- const jid = toJid(info.lid);
1285
-
1286
- // Log e risposta
1287
- console.log(`Messaggio da ${jid}`);
1288
- await conn.sendMessage(jid, { text: 'Handler attivato!' });
1289
- }
1290
-
1291
- // Nel main: conn.ev.on('messages.upsert', ({ messages }) => handleMessage(sock, messages[0]));
1292
- ```
1293
-
1294
- **Consiglio:** Testa in gruppi per verificare LID, poichΓ© Baileys upstream ha migliorato il supporto nativo nel 2025, ma i fix personalizzati qui garantiscono retrocompatibilitΓ .
1295
-
1296
- ---
1297
-
1298
- ### πŸš€ Cache Intelligente LID/JID
1299
-
1300
- La libreria ora include un sistema di cache avanzato per ottimizzare le conversioni LID/JID:
1301
-
1302
- ```typescript
1303
- import { getCacheStats, clearCache, setPerformanceConfig } from '@realvare/based';
1304
-
1305
- // Configura cache personalizzata
1306
- setPerformanceConfig({
1307
- cache: {
1308
- lidCache: {
1309
- ttl: 10 * 60 * 1000, // 10 minuti
1310
- maxSize: 15000
1311
- }
1312
- }
1313
- });
1314
-
1315
- // Monitora performance
1316
- const stats = getCacheStats();
1317
- console.log('Cache LID:', stats.lidCache.size, '/', stats.lidCache.maxSize);
1318
-
1319
- // Pulisci cache se necessario
1320
- clearCache();
1321
- ```
1322
-
1323
- ### πŸ›‘οΈ Validazione JID Avanzata
1324
-
1325
- ```typescript
1326
- import { validateJid, Logger } from '@realvare/based';
1327
-
1328
- const jid = '1234567890@s.whatsapp.net';
1329
- const validation = validateJid(jid);
1330
-
1331
- if (validation.isValid) {
1332
- Logger.info('JID valido:', jid);
1333
- } else {
1334
- Logger.error('JID non valido:', validation.error);
1335
- }
1336
- ```
1337
-
1338
- ### πŸ“Š Logging Condizionale
1339
-
1340
- ```typescript
1341
- import { Logger, setPerformanceConfig } from '@realvare/based';
1342
-
1343
- // Configura logging
1344
- setPerformanceConfig({
1345
- debug: {
1346
- enableLidLogging: true,
1347
- enablePerformanceLogging: true,
1348
- logLevel: 'debug' // 'error', 'warn', 'info', 'debug'
1349
- }
1350
- });
1351
-
1352
- // Usa logger condizionale
1353
- Logger.debug('Debug info');
1354
- Logger.performance('Performance metrics');
1355
- Logger.error('Error occurred');
1356
- ```
1357
-
1358
- ### πŸ”§ Configurazione Performance
1359
-
1360
- ```typescript
1361
- import { setPerformanceConfig, getPerformanceConfig } from '@realvare/based';
1362
-
1363
- // Configurazione completa
1364
- setPerformanceConfig({
1365
- performance: {
1366
- enableCache: true,
1367
- enableMetrics: true,
1368
- batchSize: 100,
1369
- maxRetries: 3
1370
- },
1371
- cache: {
1372
- lidCache: { ttl: 5 * 60 * 1000, maxSize: 10000 },
1373
- jidCache: { ttl: 5 * 60 * 1000, maxSize: 10000 }
1374
- },
1375
- debug: {
1376
- enableLidLogging: false,
1377
- logLevel: 'warn'
1378
- }
1379
- });
1380
-
1381
- // Ottieni configurazione corrente
1382
- const config = getPerformanceConfig();
1383
- console.log('Cache abilitata:', config.performance.enableCache);
1384
- ```
1385
-
1386
- ---
1387
-
1388
- ## 🧩 Eventi: LID e JID sempre disponibili (nuovo)
1389
-
1390
- Gli eventi emessi includono campi ausiliari sui messaggi per accedere facilmente sia al JID sia al LID del mittente/partecipante.
1391
-
1392
- ```typescript
1393
- conn.ev.on('messages.upsert', ({ messages, type }) => {
1394
- for (const msg of messages) {
1395
- // Campi aggiuntivi su msg.key
1396
- // - remoteJidNormalized: JID normalizzato (es. @s.whatsapp.net)
1397
- // - remoteLid: LID equivalente del remoteJid
1398
- // - participantLid: LID equivalente del participant (se presente)
1399
- const jid = msg.key.remoteJidNormalized || msg.key.remoteJid;
1400
- const remoteLid = msg.key.remoteLid;
1401
- const participantLid = msg.key.participantLid;
1402
-
1403
- if (jid?.endsWith('@s.whatsapp.net')) {
1404
- conn.sendMessage(jid, { text: `Ciao! LID: ${remoteLid || 'n/d'}` });
1405
- }
1406
- }
1407
- });
1408
- ```
1409
-
1410
- Questi campi eliminano ambiguitΓ  in gruppi e contesti multi-dispositivo dove alcuni eventi riportano LID, altri JID.
1411
-
1412
- ---
1413
-
1414
- ## βš™οΈ Configurazione Avanzata
1415
-
1416
- Personalizza il socket per performance e comportamento.
1417
-
1418
- ### πŸ”§ Opzioni Complete per makeWASocket
1419
-
1420
- ```typescript
1421
- const sock = makeWASocket({
1422
- // πŸ” Autenticazione
1423
- auth: state,
1424
-
1425
- // πŸ–₯️ UI e Debug
1426
- printQRInTerminal: true,
1427
- logger: console,
1428
- browser: ['VareBot', 'Chrome', '4.0.0'],
1429
-
1430
- // ⏱️ Timeout e Connessione
1431
- defaultQueryTimeoutMs: 60000,
1432
- keepAliveIntervalMs: 30000,
1433
- connectTimeoutMs: 60000,
1434
- retryRequestDelayMs: 250,
1435
- maxMsgRetryCount: 5,
1436
-
1437
- // πŸŽ›οΈ Comportamento
1438
- markOnlineOnConnect: true,
1439
- syncFullHistory: false, // Attiva per sync completo (consuma dati)
1440
- fireInitQueries: true,
1441
- generateHighQualityLinkPreview: true,
1442
- });
1443
- ```
1444
- <div align="center">
1445
-
1446
- ### πŸ›‘οΈ Sicurezza e Crittografia
1447
-
1448
- | Caratteristica | Descrizione |
1449
- |---------------------------|------------------------------------------|
1450
- | πŸ” End-to-End Encryption | Protocollo Signal per messaggi sicuri |
1451
- | πŸ”‘ Key Management | Generazione/rotazione automatica chiavi |
1452
- | πŸ” Authentication | Sicurezza tramite QR code o pairing code |
1453
- | πŸ›‘οΈ Data Protection | Archiviazione sicura credenziali locali |
1454
-
1455
- ---
1456
-
1457
- ## 🌐 Supporto e Community
1458
-
1459
- Unisciti alla community per aiuto e contributi.
1460
-
1461
- ### πŸ“ž Contatti e Risorse
1462
-
1463
- | Canale | Link/Info |
1464
- |------------------|------------------------------------------|
1465
- | **Email** | [samakavare1@gmail.com](mailto:samakavare1@gmail.com) |
1466
- | **GitHub Issues**| [Segnala Bug](https://github.com/realvare/based/issues) |
1467
- | **PayPal** | [Dona](https://www.paypal.me/samakavare) |
1468
- | **Canale whatsapp**| [Canale](https://www.whatsapp.com/channel/0029VbB41Sa1Hsq1JhsC1Z1z) |
1469
-
1470
- ---
1471
-
1472
- ## πŸ™ Ringraziamenti
1473
-
1474
- Grazie ai progetti che ispirano Based:
1475
-
1476
- | Progetto | Contributo |
1477
- |---------------------------|------------------------------------------|
1478
- | [Baileys](https://github.com/WhiskeySockets/Baileys) | API WhatsApp Web originale |
1479
- | [Yupra](https://www.npmjs.com/package/@yupra/baileys) | Fix LID/JID |
1480
- | [Signal Protocol](https://signal.org/) | Crittografia end-to-end |
1481
-
1482
- ---
1483
-
1484
- ## ⚠️ Disclaimer & Licenza
1485
-
1486
- ### πŸ“‹ Nota Legale
1487
-
1488
- ⚠️ **Importante**: Non affiliato a WhatsApp Inc. o Meta. Uso educativo/sviluppo solo.
1489
-
1490
- πŸ›‘οΈ **Uso Responsabile**: Evita spam, violazioni ToS WhatsApp. Rischio ban account.
1491
-
1492
- ### πŸ“œ Licenza MIT
1493
-
1494
- MIT License Β© 2025 [realvare](https://github.com/realvare)
1495
-
1496
- Vedi [LICENSE](LICENSE) per dettagli.
1497
-
1498
- ---
1499
-
1500
- <div align="center">
1501
- <table align="center">
1502
- <tr>
1503
- <td align="center">
1504
- <img src="https://i.ibb.co/Cp0SQznC/sam2.png" width="120" height="120" alt="pfp" style="bysamakavare"/>
1505
- <br><br>
1506
- <h2>πŸ‘¨β€πŸ’» Creato da <a href="https://github.com/realvare" style="color: #8a2be2; text-decoration: none;">realvare</a></h2>
1507
- <p><em>sam aka vare</em></p>
1508
- </td>
1509
- </tr>
1510
- </table>
1511
-
1512
- <br>
1513
- <p align="center">
1514
- <a href="https://github.com/realvare/based">
1515
- <img src="https://img.shields.io/badge/⭐_Stella_il_Progetto-8a2be2?style=for-the-badge&logo=github&logoColor=white&labelColor=2d1b69"/>
1516
- </a>&nbsp;&nbsp;
1517
- <a href="https://github.com/realvare/based/fork">
1518
- <img src="https://img.shields.io/badge/πŸ”„_Fork_Repository-8a2be2?style=for-the-badge&logo=github&logoColor=white&labelColor=2d1b69"/>
1519
- </a>&nbsp;&nbsp;
1520
- <a href="https://paypal.me/samakavare">
1521
- <img src="https://img.shields.io/badge/πŸ’°_Dona-8a2be2?style=for-the-badge&logo=paypal&logoColor=white&labelColor=2d1b69"/>
1522
- </a>
1523
- </p>
1524
- <p align="center">
1525
- <a href="https://github.com/realvare">
1526
- <img src="https://img.shields.io/badge/GitHub-100000?style=for-the-badge&logo=github&logoColor=white&color=8a2be2"/>
1527
- </a>&nbsp;
1528
- <a href="https://wa.me/393476686131">
1529
- <img src="https://img.shields.io/badge/WhatsApp-25D366?style=for-the-badge&logo=whatsapp&logoColor=white&color=8a2be2"/>
1530
- </a>&nbsp;
1531
- <a href="https://instagram.com/samakavare">
1532
- <img src="https://img.shields.io/badge/Instagram-E4405F?style=for-the-badge&logo=instagram&logoColor=white&color=8a2be2"/>
1533
- </a>&nbsp;
1534
- <a href="mailto:samakavare1@gmail.com">
1535
- <img src="https://img.shields.io/badge/Email-D14836?style=for-the-badge&logo=gmail&logoColor=white&color=8a2be2"/>
1536
- </a>
1537
- </p>
1538
- <div align="center">
1539
- <p><strong>Se ti è stato utile, lascia una stella e/o considera una donazione! ✧</strong></p>
1540
-
1541
- <br>
1542
- <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"/>
1543
-
1544
- </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
+ ## Indice
29
+
30
+ - [✨ Caratteristiche Principali](#-caratteristiche-principali)
31
+ - [πŸš€ Guida Rapida](#-guida-rapida)
32
+ - [πŸ“Š Gestione Avanzata Cache](#-gestione-avanzata-cache)
33
+ - [πŸ” Risoluzione Problemi](#-risoluzione-problemi)
34
+ - [πŸ“š Documentazione API](#-documentazione-api)
35
+ - [πŸ—οΈ Metodi Fondamentali](#-metodi-fondamentali)
36
+ - [🎯 Eventi Principali](#-eventi-principali)
37
+ - [πŸŽͺ Messaggi e FunzionalitΓ  Interattive](#-messaggi-e-funzionalit-interattive)
38
+ - [Messaggi Base](#messaggi-base)
39
+ - [Media Base](#media-base)
40
+ - [Media Avanzati](#media-avanzati)
41
+ - [Messaggi Interattivi](#messaggi-interattivi)
42
+ - [Altri Messaggi](#altri-messaggi)
43
+ - [Gestione delle Risposte](#gestione-delle-risposte)
44
+ - [🎭 Funzionalità Gruppi](#-funzionalit-gruppi)
45
+ - [Gestione Base Gruppi](#gestione-base-gruppi)
46
+ - [Gestione Partecipanti](#gestione-partecipanti)
47
+ - [Impostazioni Gruppo](#impostazioni-gruppo)
48
+ - [Messaggi Gruppo Avanzati](#messaggi-gruppo-avanzati)
49
+ - [πŸ”§ Fix LID/JID nel Proprio Main e Handler](#-fix-lidjid-nel-proprio-main-e-handler)
50
+ - [Best Practices per LID/JID](#best-practices-per-lidjid)
51
+ - [Esempio Integrato in Main](#esempio-integrato-in-main)
52
+ - [Esempio Handler Personalizzato](#esempio-handler-personalizzato)
53
+ - [πŸš€ Cache Intelligente LID/JID](#-cache-intelligente-lidjid)
54
+ - [πŸ›‘οΈ Validazione JID Avanzata](#-validazione-jid-avanzata)
55
+ - [πŸ“Š Logging Condizionale](#-logging-condizionale)
56
+ - [πŸ”§ Configurazione Performance](#-configurazione-performance)
57
+ - [🧩 Eventi: LID e JID sempre disponibili (nuovo)](#-eventi-lid-e-jid-sempre-disponibili-nuovo)
58
+ - [βš™οΈ Configurazione Avanzata](#-configurazione-avanzata)
59
+ - [πŸ”§ Opzioni Complete per makeWASocket](#-opzioni-complete-per-makewasocket)
60
+ - [πŸ›‘οΈ Sicurezza e Crittografia](#-sicurezza-e-crittografia)
61
+ - [🌐 Supporto e Community](#-supporto-e-community)
62
+ - [πŸ“ž Contatti e Risorse](#-contatti-e-risorse)
63
+ - [πŸ™ Ringraziamenti](#-ringraziamenti)
64
+ - [⚠️ Disclaimer & Licenza](#-disclaimer--licenza)
65
+ - [πŸ“‹ Nota Legale](#-nota-legale)
66
+ - [πŸ“œ Licenza MIT](#-licenza-mit)
67
+
68
+ ----
69
+
70
+ ## ✨ Caratteristiche Principali
71
+
72
+ <p align="center">
73
+ <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">
74
+ </div>
75
+
76
+ <br>
77
+
78
+ Questa libreria, basata su Baileys con miglioramenti specifici, offre un'API intuitiva per interagire con WhatsApp Web. Ecco un riassunto delle funzionalitΓ  chiave:
79
+
80
+ <table align="center">
81
+ <tr>
82
+ <td align="center" width="25%">
83
+ <h3>πŸ”„ Core Features</h3>
84
+ <p>β€’ Mappatura intelligente LID/JID<br>β€’ Supporto multi-dispositivo<br>β€’ Crittografia E2E Signal<br>β€’ TypeScript moderno</p>
85
+ </td>
86
+ <td align="center" width="25%">
87
+ <h3>πŸ’¬ Messaggi</h3>
88
+ <p>β€’ Testo, media, interattivi<br>β€’ Bottoni, liste, album<br>β€’ Poll, reazioni<br>β€’ Template avanzati</p>
89
+ </td>
90
+ <td align="center" width="25%">
91
+ <h3>πŸ› οΈ Developer</h3>
92
+ <p>β€’ Eventi real-time<br>β€’ TypeScript completo<br>β€’ Documentazione estesa<br>β€’ API estendibili</p>
93
+ </td>
94
+ <td align="center" width="25%">
95
+ <h3>⚑ Performance</h3>
96
+ <p>β€’ Riconnessione intelligente<br>β€’ Cache avanzata TTL<br>β€’ Monitoraggio prestazioni</p>
97
+ </td>
98
+ </tr>
99
+ </table>
100
+ <p align="center">
101
+ <img src="https://64.media.tumblr.com/13bc9e3c3b332dfc008cb4b9e8571558/2a577b39b15547dc-cc/s400x600/3db051b3117b695a61ad8e0b686f2774b971d210.gifv" width="800">
102
+
103
+
104
+ ## πŸš€ Guida Rapida
105
+
106
+ - Questa sezione include esempi base per l'autenticazione e la gestione delle connessioni.
107
+
108
+ ### Esempio Base - Avvio Bot
109
+
110
+ ```typescript
111
+ import makeWASocket, { DisconnectReason, useMultiFileAuthState, getPerformanceConfig, setPerformanceConfig } from '@realvare/based';
112
+
113
+ // Configura performance e cache
114
+ setPerformanceConfig({
115
+ performance: {
116
+ enableCache: true,
117
+ enableMetrics: true
118
+ },
119
+ debug: {
120
+ enableLidLogging: true,
121
+ logLevel: 'info'
122
+ }
123
+ });
124
+
125
+ async function startBot() {
126
+ // πŸ” Setup autenticazione multi-file per sessioni persistenti
127
+ const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
128
+
129
+ // 🌐 Creazione del socket con configurazione base
130
+ const sock = makeWASocket({
131
+ auth: state,
132
+ printQRInTerminal: true,
133
+ logger: console,
134
+ browser: ['VareBot', 'Chrome', '4.0.0'],
135
+ });
136
+
137
+ // Sistema di riconnessione migliorato
138
+ let reconnectAttempts = 0;
139
+ const config = getPerformanceConfig();
140
+
141
+ sock.ev.on('connection.update', (update) => {
142
+ const { connection, lastDisconnect } = update;
143
+
144
+ if (connection === 'close') {
145
+ const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
146
+
147
+ if (shouldReconnect) {
148
+ reconnectAttempts++;
149
+ const delay = Math.min(
150
+ config.performance.retryDelay * Math.pow(
151
+ config.performance.retryBackoffMultiplier,
152
+ reconnectAttempts - 1
153
+ ),
154
+ config.performance.maxRetryDelay
155
+ );
156
+
157
+ console.log(`πŸ”„ Tentativo di riconnessione ${reconnectAttempts}/${config.performance.maxRetries} tra ${delay}ms`);
158
+
159
+ if (reconnectAttempts <= config.performance.maxRetries) {
160
+ setTimeout(startBot, delay);
161
+ } else {
162
+ console.log('❌ Numero massimo di tentativi di riconnessione raggiunto');
163
+ }
164
+ }
165
+ } else if (connection === 'open') {
166
+ console.log('🟒 Connesso con successo!');
167
+ reconnectAttempts = 0;
168
+ }
169
+ });
170
+
171
+ sock.ev.on('creds.update', saveCreds);
172
+ }startBot().catch(console.error);
173
+ ```
174
+
175
+ ### Esempio Anti-Ban - Configurazione consigliata per Evitare Ban
176
+
177
+ ```typescript
178
+ import makeWASocket, { DisconnectReason, useMultiFileAuthState, getPerformanceConfig, setPerformanceConfig, getSenderLid, validateJid } from '@realvare/based';
179
+
180
+ // Configurazione anti-ban per ridurre rischi ban da acks impropri
181
+ setPerformanceConfig({
182
+ performance: {
183
+ enableCache: true, // Abilita cache TTL per ridurre chiamate API
184
+ enableMetrics: true, // Monitora performance per evitare sovraccarico
185
+ batchSize: 50, // Elabora messaggi in batch piΓΉ piccoli per simulare velocitΓ  umana
186
+ maxRetries: 5, // Limita tentativi retry per evitare comportamento aggressivo
187
+ retryDelay: 5000, // Ritardo base in ms per riconnessioni
188
+ retryBackoffMultiplier: 1.5,// Backoff esponenziale per spaziare retry
189
+ maxRetryDelay: 60000, // Ritardo massimo per evitare riconnessioni rapide
190
+ maxMsgRetryCount: 3 // Limita tentativi rispedizione messaggi
191
+ }
192
+ });
193
+
194
+ async function startBot() {
195
+ const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
196
+
197
+ const sock = makeWASocket({
198
+ auth: state,
199
+ printQRInTerminal: true,
200
+ logger: console,
201
+ browser: ['YourBotName', 'Chrome', '4.0.0'], // Personalizza fingerprint browser
202
+ markOnlineOnConnect: false, // Cruciale: Previene apparire sempre online, riduce rischio ban
203
+ syncFullHistory: false // Evita sync dati non necessari che potrebbero segnalare attivitΓ 
204
+ });
205
+
206
+ let reconnectAttempts = 0;
207
+ const config = getPerformanceConfig();
208
+
209
+ sock.ev.on('connection.update', (update) => {
210
+ const { connection, lastDisconnect } = update;
211
+
212
+ if (connection === 'close') {
213
+ const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
214
+
215
+ if (shouldReconnect) {
216
+ reconnectAttempts++;
217
+ const delay = Math.min(
218
+ config.performance.retryDelay * Math.pow(
219
+ config.performance.retryBackoffMultiplier,
220
+ reconnectAttempts - 1
221
+ ),
222
+ config.performance.maxRetryDelay
223
+ );
224
+
225
+ console.log(`Reconnecting attempt ${reconnectAttempts}/${config.performance.maxRetries} in ${delay}ms`);
226
+
227
+ if (reconnectAttempts <= config.performance.maxRetries) {
228
+ setTimeout(startBot, delay);
229
+ } else {
230
+ console.log('Max reconnection attempts reached');
231
+ }
232
+ }
233
+ } else if (connection === 'open') {
234
+ console.log('Connected successfully!');
235
+ reconnectAttempts = 0;
236
+ }
237
+ });
238
+
239
+ // Monitora acks tramite aggiornamenti messaggi per garantire gestione corretta
240
+ sock.ev.on('messages.update', (updates) => {
241
+ for (const update of updates) {
242
+ if (update.update.status) {
243
+ console.log(`Message ${update.key.id} status: ${update.update.status}`); // Traccia acks (1=sent, 2=delivered, 3=read)
244
+ // Aggiungi logica personalizzata se necessaria, ma evita override predefiniti per prevenire detection
245
+ }
246
+ }
247
+ });
248
+
249
+ // UtilitΓ  LID/JID avanzate per stabilitΓ  acks
250
+ sock.ev.on('messages.upsert', ({ messages }) => {
251
+ for (const msg of messages) {
252
+ const info = getSenderLid(msg);
253
+ const validation = validateJid(info.jid);
254
+ if (validation.isValid) {
255
+ // Elabora e ack in sicurezza
256
+ console.log(`Valid JID: ${info.jid}, LID: ${info.lid}`);
257
+ } else {
258
+ console.warn(`Invalid JID detected: ${info.jid}`);
259
+ }
260
+ }
261
+ });
262
+
263
+ sock.ev.on('creds.update', saveCreds);
264
+ }
265
+
266
+ startBot().catch(console.error);
267
+ ```
268
+
269
+ ## πŸ“Š Gestione Avanzata Cache
270
+
271
+ La libreria ora include un sistema di cache avanzato con gestione automatica della memoria e TTL configurabile:
272
+
273
+ ```typescript
274
+ import { CacheManager } from 'based/lib/Utils/cache-manager';
275
+
276
+ // Esempio di utilizzo della cache
277
+ const cache = CacheManager;
278
+
279
+ // Salva un valore nella cache
280
+ cache.set('lidCache', 'chiave', 'valore', 300); // TTL di 300 secondi
281
+
282
+ // Recupera un valore
283
+ const valore = cache.get('lidCache', 'chiave');
284
+
285
+ // Ottieni statistiche della cache
286
+ const stats = cache.getStats('lidCache');
287
+ console.log('Statistiche cache:', stats);
288
+ ```
289
+
290
+ ### Configurazione Cache Avanzata
291
+
292
+ La cache puΓ² essere configurata con varie opzioni per ottimizzare le prestazioni:
293
+
294
+ ```typescript
295
+ setPerformanceConfig({
296
+ cache: {
297
+ lidCache: {
298
+ ttl: 5 * 60 * 1000, // Tempo di vita delle entries
299
+ maxSize: 10000, // Numero massimo di entries
300
+ cleanupInterval: 2 * 60 * 1000 // Intervallo pulizia
301
+ }
302
+ },
303
+ performance: {
304
+ memoryThreshold: 0.85 // Soglia per pulizia automatica
305
+ }
306
+ });
307
+ ```
308
+ ## πŸ” Risoluzione Problemi
309
+
310
+ ### Problemi di Connessione
311
+ - La libreria ora implementa un sistema di retry con backoff esponenziale
312
+ - Monitoraggio automatico dello stato della connessione
313
+ - Tentativi di riconnessione configurabili
314
+
315
+ ### Gestione Memoria
316
+ - Monitoraggio automatico dell'uso della memoria
317
+ - Pulizia cache automatica quando necessario
318
+ - TTL configurabile per ogni tipo di cache
319
+
320
+ ### Logging Avanzato
321
+ ```typescript
322
+ setPerformanceConfig({
323
+ debug: {
324
+ enableLidLogging: true,
325
+ enablePerformanceLogging: true,
326
+ logLevel: 'debug'
327
+ }
328
+ });
329
+ ```
330
+
331
+ ### Gestione Messaggi Base con LID/JID
332
+
333
+ ```typescript
334
+ import makeWASocket, { getSenderLid, toJid, getCacheStats, validateJid, Logger } from '@realvare/based';
335
+
336
+ // ... (codice di creazione sock qui)
337
+
338
+ conn.ev.on('messages.upsert', ({ messages }) => {
339
+ for (const msg of messages) {
340
+ // πŸ” Estrai LID del mittente con validazione
341
+ const info = getSenderLid(msg);
342
+
343
+ // βœ… Valida JID prima di usarlo
344
+ const validation = validateJid(info.jid);
345
+ if (!validation.isValid) {
346
+ Logger.error('JID non valido:', validation.error);
347
+ continue;
348
+ }
349
+
350
+ const jid = toJid(info.lid); // Normalizza in JID
351
+
352
+ Logger.info('πŸ’¬ Messaggio da:', jid, 'Valid:', info.isValid);
353
+ console.log('πŸ“ Contenuto:', msg.message?.conversation);
354
+
355
+ // Rispondi automaticamente solo se valido
356
+ if (info.isValid) {
357
+ conn.sendMessage(jid, { text: 'Messaggio ricevuto!' });
358
+ }
359
+ }
360
+
361
+ // πŸ“Š Monitora performance cache
362
+ const stats = getCacheStats();
363
+ Logger.performance('Cache stats:', stats);
364
+ });
365
+ ```
366
+
367
+ ---
368
+
369
+ ## πŸ“š Documentazione API
370
+
371
+ Questa sezione espande i metodi principali, con esempi dettagliati e parametri. Tutti i metodi sono tipizzati in TypeScript per un'esperienza di sviluppo sicura.
372
+
373
+ ### πŸ—οΈ Metodi Fondamentali
374
+
375
+ | Metodo | Descrizione | Import |
376
+ |--------|-------------|--------|
377
+ | `makeWASocket(config)` | **Core**: Crea socket WhatsApp | βœ… Incluso |
378
+ | `useMultiFileAuthState(folder)` | **Auth**: Gestione credenziali persistenti | βœ… Incluso |
379
+ | `getSenderLid(msg)` | **LID**: Estrae LID dal messaggio | βœ… Incluso |
380
+ | `toJid(lid)` | **JID**: Converte LID β†’ JID | βœ… Incluso |
381
+ | `validateJid(jid)` | **Validazione**: Verifica JID | βœ… Incluso |
382
+ | `getCacheStats()` | **Performance**: Statistiche cache | βœ… Incluso |
383
+ | `clearCache()` | **Pulizia**: Svuota cache | βœ… Incluso |
384
+ | `setPerformanceConfig(config)` | **Config**: Personalizza performance | βœ… Incluso |
385
+
386
+ **πŸ”₯ Nota**: Tutti i metodi sopra sono **giΓ  pronti all'uso** e mostrati nella Guida Rapida. Passa direttamente alle sezioni avanzate per funzionalitΓ  specifiche!
387
+
388
+ ---
389
+
390
+ ### 🎯 Eventi Principali
391
+
392
+ | Evento | Descrizione | Callback Signature |
393
+ |---------------------|--------------------------------------|-------------------------------------|
394
+ | `connection.update` | Aggiornamenti stato connessione | `(update: Partial<ConnectionState>) => void` |
395
+ | `creds.update` | Aggiornamento credenziali | `() => void` |
396
+ | `messages.upsert` | Nuovi messaggi o aggiornamenti | `({ messages: WAMessage[], type: MessageUpsertType }) => void` |
397
+ | `messages.update` | Modifiche a messaggi esistenti | `(update: WAMessageUpdate[]) => void` |
398
+ | `group-participants.update` | Cambiamenti partecipanti gruppo | `(update: GroupParticipantEvent) => void` |
399
+
400
+ **Esempio Registrazione Evento:**
401
+ ```typescript
402
+ conn.ev.on('group-participants.update', (update) => {
403
+ console.log('Partecipante aggiornato:', update);
404
+ });
405
+ ```
406
+
407
+ ---
408
+
409
+ ## πŸŽͺ Messaggi e FunzionalitΓ  Interattive
410
+
411
+ ### Messaggi Base
412
+
413
+ #### Testo con Formattazione
414
+ ```typescript
415
+ // Testo con formattazione e menzioni
416
+ await conn.sendMessage(jid, {
417
+ text: `*Bold* _italic_ ~strikethrough~ \`monospace\`\n@menzione`,
418
+ mentions: ['393476686131@s.whatsapp.net']
419
+ });
420
+ ```
421
+
422
+ #### Media Base
423
+ ```typescript
424
+ // Immagine
425
+ await conn.sendMessage(jid, {
426
+ image: { url: './media/varebot.jpg' }, // Supporta anche Buffer
427
+ caption: 'zwag'
428
+ });
429
+
430
+ // Video
431
+ await conn.sendMessage(jid, {
432
+ video: { url: './media/oppastoppa.mp4' },
433
+ caption: 'brrrr',
434
+ gifPlayback: false // true per riprodurre come GIF
435
+ });
436
+
437
+ // Audio
438
+ await conn.sendMessage(jid, {
439
+ audio: { url: './media/audio.mp3' },
440
+ mimetype: 'audio/mp4',
441
+ ptt: true // true per messaggio vocale, false per audio normale
442
+ });
443
+
444
+ // Documento
445
+ await conn.sendMessage(jid, {
446
+ document: { url: './media/doc.pdf' },
447
+ mimetype: 'application/pdf',
448
+ fileName: 'documento.pdf'
449
+ });
450
+ ```
451
+
452
+ #### Media Avanzati
453
+ ```typescript
454
+ // Album (Multiple immagini)
455
+ await conn.sendMessage(jid, {
456
+ album: imageBuffers.map(buffer => ({ image: buffer })),
457
+ caption: 'ts gettin real'
458
+ });
459
+
460
+ // Sticker
461
+ await conn.sendMessage(jid, {
462
+ sticker: { url: './stickers/sticker.webp' }
463
+ });
464
+
465
+ // Messaggio con posizione
466
+ await conn.sendMessage(jid, {
467
+ location: {
468
+ degreesLatitude: 45.4642,
469
+ degreesLongitude: 9.1900,
470
+ name: "Milano",
471
+ address: "Piazza del Duomo, Milano"
472
+ }
473
+ });
474
+ ```
475
+
476
+ #### Messaggi Interattivi
477
+ Questi messaggi includono elementi interattivi come bottoni, liste e template.
478
+
479
+ ##### Messaggi con Bottoni Semplici
480
+ Invia bottoni di risposta rapida.
481
+
482
+ ```typescript
483
+ await conn.sendMessage(jid, {
484
+ text: 'Scegli un\'opzione:',
485
+ footer: 'Footer',
486
+ buttons: [
487
+ { buttonId: 'cmd1', buttonText: { displayText: 'testo1' }, type: 1 },
488
+ { buttonId: 'cmd2', buttonText: { displayText: 'testo2' }, type: 1 },
489
+ ],
490
+ headerType: 1,
491
+ });
492
+ ```
493
+
494
+ ##### Messaggi con Bottoni e Immagine
495
+ Combina immagine con bottoni.
496
+
497
+ ```typescript
498
+ await conn.sendMessage(jid, {
499
+ image: { url: 'https://i.ibb.co/hJW7WwxV/varebot.jpg' },
500
+ caption: 'Messaggio con bottoni e immagine',
501
+ footer: 'vare ✧ bot',
502
+ buttons: [
503
+ { buttonId: 'cmd', buttonText: { displayText: 'testo1' }, type: 1 },
504
+ ],
505
+ });
506
+ ```
507
+
508
+ ##### Messaggi Liste
509
+ Invia una lista di opzioni (solo in privato).
510
+
511
+ ```typescript
512
+ await conn.sendMessage(jid, {
513
+ text: 'Questa Γ¨ una lista!',
514
+ footer: 'purplepurplepurple!',
515
+ title: 'Titolo Lista',
516
+ buttonText: 'Visualizza Lista',
517
+ sections: [
518
+ {
519
+ title: 'Sezione 1',
520
+ rows: [
521
+ { title: 'Opzione 1', rowId: 'opt1',description: 'Descrizionex' },
522
+ { title: 'Opzione 2', rowId: 'opt2', description: 'Descrizioney' }
523
+ ]
524
+ },
525
+ ],
526
+ });
527
+ ```
528
+
529
+ #### Altri Messaggi
530
+ ```typescript
531
+ // Messaggio con citazione
532
+ await conn.sendMessage(jid, {
533
+ text: 'bang bang',
534
+ quoted: quotedMessage // Il messaggio da quotare/rispondere/citare
535
+ });
536
+
537
+ // Messaggi Contatto
538
+ await conn.sendMessage(jid, {
539
+ contacts: {
540
+ displayName: 'Sam aka vare',
541
+ contacts: [{ vcard: 'BEGIN:VCARD\nVERSION:3.0\nFN:Sam aka vare\nTEL;waid=393476686131:+39 347 6686131\nEND:VCARD' }]
542
+ }
543
+ });
544
+
545
+ // Messaggi Poll (Sondaggio)
546
+ await conn.sendMessage(jid, {
547
+ poll: {
548
+ name: 'Anime preferito?',
549
+ values: ['Aot', 'Bleach', 'Death note'],
550
+ selectableCount: 1 // quante scelte possibili
551
+ }
552
+ });
553
+
554
+ // Messaggi Ephemeral (Che si Autodistruggono)
555
+ await conn.sendMessage(jid, {
556
+ text: "Questo messaggio si autodistruggerΓ  {speriamo come israele}"
557
+ }, {
558
+ ephemeralExpiration: 7 * 24 * 60 * 60
559
+ });
560
+
561
+ // Messaggi con Risposta a Visualizzazione
562
+ await conn.sendMessage(
563
+ jid,
564
+ {
565
+ video: { url: './media/hado90.mp4' },
566
+ viewOnce: true,
567
+ caption: 'tuff'
568
+ }
569
+ )
570
+
571
+ // Messaggi di Status (Stato)
572
+ await conn.sendMessage('status@broadcast', {
573
+ text: 'god forgive em'
574
+ }, {
575
+ statusJidList: contatti
576
+ });
577
+
578
+ // Invia uno stato con media (visibile solo a contatti selezionati)
579
+ await conn.sendMessage('status@broadcast', {
580
+ image: { url: './media/menu/menu.jpg' },
581
+ caption: 'all i need in this life of sin is-',
582
+ }, {
583
+ statusJidList: contatti
584
+ });
585
+
586
+ // Messaggi Newsletter
587
+ await conn.sendMessage('120363418582531215@newsletter', {
588
+ text: 'ay yo',
589
+ });
590
+
591
+ // Messaggi di Pagamento
592
+ await conn.sendMessage(jid, {
593
+ requestPayment: {
594
+ currency: 'EUR',
595
+ amount1000: 5000,
596
+ requestFrom: '393514357738@s.whatsapp.net',
597
+ note: 'js gimme my money' // https://paypal.me/samakavare
598
+ }
599
+ });
600
+
601
+ // Messaggi di Chiamata
602
+ await conn.sendMessage(jid, {
603
+ call: {
604
+ callKey: {
605
+ fromMe: true,
606
+ id: Date.now().toString(),
607
+ remoteJid: jid
608
+ },
609
+ type: 'ACCEPT' // 'MISSED', 'OFFER', 'ACCEPT', 'REJECT'..
610
+ }
611
+ });
612
+
613
+ // Messaggi con Live Location
614
+ await conn.sendMessage(jid, {
615
+ liveLocation: {
616
+ degreesLatitude: 45.4642,
617
+ degreesLongitude: 9.1900,
618
+ accuracyInMeters: 50,
619
+ speedInMps: 5,
620
+ degreesClockwiseFromMagneticNorth: 359,
621
+ caption: "kmt im mean kiss my teeth",
622
+ sequenceNumber: 21,
623
+ timeOffset: 2000,
624
+ }
625
+ });
626
+
627
+ // Messaggi di Ordini/Prodotti
628
+ await conn.sendMessage(jid, {
629
+ order: {
630
+ id: 'bysamakavare',
631
+ thumbnail: buffer, // immagine buffer
632
+ itemCount: 67,
633
+ surface: 'CATALOG',
634
+ title: 'heh',
635
+ text: 'gotta make it happen',
636
+ seller: '393514357738@s.whatsapp.net',
637
+ amount: 67000,
638
+ currency: 'EUR'
639
+ }
640
+ });
641
+
642
+ // Prodotto
643
+ await conn.sendMessage(jid, {
644
+ product: {
645
+ productImage: { url: './media/menu/menu.jpg' },
646
+ productId: 'prod123',
647
+ title: 'titolo',
648
+ description: 'Desc',
649
+ currency: 'EUR',
650
+ priceAmount1000: 67000,
651
+ retailerId: 'bysamakavare',
652
+ url: 'https://varebot.netlify.app',
653
+ },
654
+ businessOwnerJid: m.sender
655
+ });
656
+
657
+ // Messaggi con Intestazione Personalizzata
658
+ await conn.sendMessage(jid, {
659
+ text: 'dilemma',
660
+ contextInfo: {
661
+ externalAdReply: {
662
+ title: `titolo`,
663
+ body: `desc`,
664
+ thumbnailUrl: 'https://i.ibb.co/hJW7WwxV/sam.jpg', // immagine
665
+ sourceUrl: '', // sconsiglio di metterla
666
+ mediaType: 1,
667
+ renderLargerThumbnail: false
668
+ }
669
+ }
670
+ });
671
+ > nota: non usate showAdAttribution o tenetela in false, poiche con essa attiva non viene visualizzato il messaggio
672
+ ```
673
+
674
+ ### Gestione delle Risposte
675
+
676
+ Per gestire le risposte ai messaggi interattivi, usa il listener `messages.upsert` e controlla il tipo di risposta:
677
+
678
+ ```typescript
679
+ conn.ev.on('messages.upsert', async ({ messages }) => {
680
+ const msg = messages[0];
681
+
682
+ // Risposta a bottoni
683
+ if (msg.message?.buttonsResponseMessage) {
684
+ const selectedId = msg.message.buttonsResponseMessage.selectedButtonId;
685
+ console.log(`Bottone selezionato: ${selectedId}`);
686
+ }
687
+
688
+ // Risposta a liste
689
+ if (msg.message?.listResponseMessage) {
690
+ const selectedId = msg.message.listResponseMessage.singleSelectReply.selectedRowId;
691
+ console.log(`Opzione selezionata: ${selectedId}`);
692
+ }
693
+
694
+ // Risposta a sondaggio
695
+ if (msg.message?.pollResponseMessage) {
696
+ const selectedOptions = msg.message.pollResponseMessage.selectedOptions;
697
+ console.log('Opzioni selezionate:', selectedOptions);
698
+ }
699
+ });
700
+ ```
701
+
702
+ ### 🎭 Funzionalità Gruppi
703
+
704
+ #### Gestione Base Gruppi
705
+
706
+ ```typescript
707
+ // Creazione gruppo - il jid sta per l'aggiunta di partecipanti
708
+ const group = await conn.groupCreate('Angels πŸ©ΈπŸ•ŠοΈ', ['user@s.whatsapp.net']);
709
+
710
+ // Ottenere info gruppo
711
+ const metadata = await conn.groupMetadata(jid);
712
+
713
+ // Ottenere codice invito
714
+ const code = await conn.groupInviteCode(jid);
715
+
716
+ // Revocare link invito
717
+ await conn.groupRevokeInvite(jid);
718
+
719
+ // Lasciare gruppo
720
+ await conn.groupLeave(jid);
721
+ ```
722
+
723
+ #### Gestione Partecipanti
724
+
725
+ ```typescript
726
+ // Aggiungere partecipanti
727
+ await conn.groupParticipantsUpdate(
728
+ jid,
729
+ ['user@s.whatsapp.net'],
730
+ 'add'
731
+ );
732
+
733
+ // Rimuovere partecipanti
734
+ await conn.groupParticipantsUpdate(
735
+ jid,
736
+ ['user@s.whatsapp.net'],
737
+ 'remove'
738
+ );
739
+
740
+ // Promuovere ad admin
741
+ await conn.groupParticipantsUpdate(
742
+ jid,
743
+ ['user@s.whatsapp.net'],
744
+ 'promote'
745
+ );
746
+
747
+ // Degradare da admin
748
+ await conn.groupParticipantsUpdate(
749
+ jid,
750
+ ['user@s.whatsapp.net'],
751
+ 'demote'
752
+ );
753
+ ```
754
+
755
+ #### Impostazioni Gruppo
756
+
757
+ ```typescript
758
+ // Modificare nome gruppo
759
+ await conn.groupUpdateSubject(jid, 'Nuovo Nome');
760
+
761
+ // Modificare descrizione
762
+ await conn.groupUpdateDescription(jid, 'Nuova descrizione');
763
+
764
+ // Modificare foto gruppo
765
+ await conn.updateProfilePicture(jid, { url: './img/group.jpg' });
766
+
767
+ // Rimuovere foto gruppo
768
+ await conn.removeProfilePicture(jid);
769
+
770
+ // Impostare gruppo come solo admin
771
+ await conn.groupSettingUpdate(jid, 'announcement');
772
+
773
+ // Impostare gruppo come aperto a tutti
774
+ await conn.groupSettingUpdate(jid, 'not_announcement');
775
+
776
+ // Impostare chi puΓ² modificare le info - solo admin
777
+ await conn.groupSettingUpdate(jid, 'locked');
778
+
779
+ // Impostare chi puΓ² modificare le info - tutti
780
+ await conn.groupSettingUpdate(jid, 'unlocked');
781
+
782
+ // Impostare chi puΓ² aggiungere membri - solo admin
783
+ await conn.groupMemberAddMode(jid, 'admin_add');
784
+
785
+ // Impostare chi puΓ² aggiungere membri - tutti
786
+ await conn.groupMemberAddMode(jid, 'all_member_add');
787
+
788
+ // Attivare/disattivare messaggi temporanei (24 ore)
789
+ await conn.groupToggleEphemeral(jid, 86400); // secondi
790
+
791
+ // Disattivare messaggi temporanei
792
+ await conn.groupToggleEphemeral(jid, 0);
793
+
794
+ // Attivare/disattivare modalitΓ  approvazione adesioni
795
+ await conn.groupJoinApprovalMode(jid, 'on'); // richiede approvazione
796
+ await conn.groupJoinApprovalMode(jid, 'off'); // aperta
797
+
798
+ // Ottenere tutti i gruppi
799
+ const groups = await conn.groupFetchAllParticipating();
800
+
801
+ // Ottenere inviti pendenti
802
+ const invites = await conn.groupGetInviteInfo(code);
803
+
804
+ // Accettare invito gruppo
805
+ await conn.groupAcceptInvite(code);
806
+
807
+ // Ottenere info gruppo da link
808
+ const groupInfo = await conn.groupGetInviteInfo('https://chat.whatsapp.com/ABC123');
809
+
810
+ // Ascolta modifiche impostazioni
811
+ conn.ev.on('group-settings.update', async ({ id, announce, restrict }) => {
812
+ if (announce !== undefined) {
813
+ await conn.sendMessage(id, { text: `Il gruppo Γ¨ stato impostato come ${announce ? 'solo admin' : 'tutti'}` });
814
+ }
815
+ if (restrict !== undefined) {
816
+ await conn.sendMessage(id, { text: `Le info gruppo possono essere modificate da ${restrict ? 'solo admin' : 'tutti'}` });
817
+ }
818
+ });
819
+ ```
820
+
821
+ #### Messaggi Gruppo Avanzati
822
+
823
+ ```typescript
824
+ // Messaggio con menzione multipla
825
+ await conn.sendMessage(jid, {
826
+ text: '@user1 @user2 @user3',
827
+ mentions: [user1, user2, user3],
828
+ contextInfo: {
829
+ mentionedJid: [user1, user2, user3]
830
+ }
831
+ });
832
+
833
+ // Messaggio con ricerca google
834
+ await conn.sendMessage(jid, {
835
+ text: 'ZWAG',
836
+ contextInfo: {
837
+ forwardingScore: 999,
838
+ isForwarded: true
839
+ }
840
+ });
841
+ ```
842
+
843
+ ---
844
+
845
+ ## πŸ”§ Fix LID/JID nel Proprio Main e Handler
846
+
847
+ *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.*
848
+
849
+ ### Best Practices per LID/JID
850
+
851
+ - **decodeJid(jid)**: Funzione principale per normalizzare JID/LID. Gestisce:
852
+ - Formati con `:\d+@` (usa `jidNormalizedUser`).
853
+ - Decodifica user/server in `${user}@${server}`.
854
+ - Converti `@lid` in `@s.whatsapp.net`.
855
+
856
+ **Esempio di Implementazione (da main.js):**
857
+ ```typescript
858
+ decodeJid: (jid) => {
859
+ if (!jid) return jid;
860
+ let decoded = jid;
861
+ if (/:\d+@/gi.test(jid)) {
862
+ decoded = jidNormalizedUser(jid);
863
+ }
864
+ if (typeof decoded === 'object' && decoded.user && decoded.server) {
865
+ decoded = `${decoded.user}@${decoded.server}`;
866
+ }
867
+ if (decoded.endsWith('@lid')) {
868
+ decoded = decoded.replace('@lid', '@s.whatsapp.net');
869
+ }
870
+ return decoded;
871
+ },
872
+ ```
873
+ Usa `conn.decodeJid(jid)` ovunque per normalizzare IDs (es. sender, participant, quoted).
874
+
875
+ - **Monkey-Patch per groupParticipantsUpdate**: Corregge aggiornamenti partecipanti gruppo trovando il JID reale dal metadata.
876
+
877
+ **Esempio (da handler.js):**
878
+ ```typescript
879
+ if (!this.originalGroupParticipantsUpdate) {
880
+ this.originalGroupParticipantsUpdate = this.groupParticipantsUpdate;
881
+ this.groupParticipantsUpdate = async function(chatId, users, action) {
882
+ try {
883
+ let metadata = global.groupCache.get(chatId);
884
+ if (!metadata) {
885
+ metadata = await fetchGroupMetadataWithRetry(this, chatId);
886
+ if (metadata) global.groupCache.set(chatId, metadata);
887
+ }
888
+ if (!metadata) {
889
+ console.error('[ERRORE] Nessun metadato del gruppo disponibile per un aggiornamento sicuro');
890
+ return this.originalGroupParticipantsUpdate.call(this, chatId, users, action);
891
+ }
892
+
893
+ const correctedUsers = users.map(userJid => {
894
+ const decoded = this.decodeJid(userJid);
895
+ const phone = decoded.split('@')[0].split(':')[0];
896
+ const participant = metadata.participants.find(p => {
897
+ const pId = this.decodeJid(p.id || p.jid || '');
898
+ const pPhone = pId.split('@')[0].split(':')[0];
899
+ return pPhone === phone;
900
+ });
901
+ return participant ? participant.id : userJid; // Fallback all'originale se non trovato
902
+ });
903
+
904
+ return this.originalGroupParticipantsUpdate.call(this, chatId, correctedUsers, action);
905
+ } catch (e) {
906
+ console.error('[ERRORE] Errore in safeGroupParticipantsUpdate:', e);
907
+ throw e;
908
+ }
909
+ };
910
+ }
911
+ ```
912
+
913
+ - **Cache per Metadata Gruppo**: Usa NodeCache per memorizzare metadata, normalizzando con `decodeJid`.
914
+
915
+ **Esempio (da handler.js):**
916
+ ```typescript
917
+ global.groupCache = new NodeCache({ stdTTL: 5 * 60, useClones: false });
918
+
919
+ // In participantsUpdate o groups.update:
920
+ metadata.participants.forEach(u => {
921
+ const normId = this.decodeJid(u.id);
922
+ const jid = u.jid || normId;
923
+ });
924
+ global.groupCache.set(update.id, metadata);
925
+ ```
926
+
927
+ - **Normalizzazione in Print/Log**: Rimuovi `:xx` dai numeri telefono per clean display.
928
+
929
+ **Esempio (da print.js):**
930
+ ```typescript
931
+ function formatPhoneNumber(jid, name) {
932
+ if (!jid) return 'Sconosciuto';
933
+ let userPart = jid.split('@')[0];
934
+ let cleanNumber = userPart.split(':')[0]; // Rimuovi la parte :xx per ottenere il numero reale
935
+ try {
936
+ const number = PhoneNumber('+' + cleanNumber).getNumber('international');
937
+ return number + (name ? ` ~${name}` : '');
938
+ } catch {
939
+ return (cleanNumber || '') + (name ? ` ~${name}` : '');
940
+ }
941
+ }
942
+ ```
943
+
944
+ - **Problemi Comuni e Fix:**
945
+ - **LID Mancante in Gruppi:** Usa `decodeJid` e cache metadata per trovare JID reali.
946
+ - **Conversione JID:** Sempre applica `decodeJid` prima di `sendMessage` o query.
947
+ - **Multi-Dispositivo:** Imposta `syncFullHistory: true` in config per sync LID.
948
+ - **Errori in Mention/Quoted:** Normalizza con `decodeJid` in handler per quoted.sender e mentionedJid.
949
+
950
+ ### Esempio Integrato in Main
951
+
952
+ ```typescript
953
+ // Nel tuo file main
954
+ import makeWASocket, { getSenderLid, toJid } from '@realvare/based';
955
+ // ... (autenticazione e creazione sock)
956
+
957
+ conn.ev.on('messages.upsert', async ({ messages }) => {
958
+ const msg = messages[0];
959
+ if (!msg.message) return;
960
+
961
+ const info = getSenderLid(msg);
962
+ const senderJid = toJid(info.lid); // Fix LID -> JID
963
+
964
+ // Esempio: Rispondi solo se JID valido
965
+ if (senderJid.endsWith('@s.whatsapp.net')) {
966
+ await conn.sendMessage(senderJid, { text: `Ciao da ${senderJid}!` }, { quoted: msg });
967
+ }
968
+ });
969
+ ```
970
+
971
+ ### Esempio Handler Personalizzato
972
+
973
+ ```typescript
974
+ // handler.js
975
+ export async function handleMessage(sock, msg) {
976
+ const info = getSenderLid(msg);
977
+ const jid = toJid(info.lid);
978
+
979
+ // Log e risposta
980
+ console.log(`Messaggio da ${jid}`);
981
+ await conn.sendMessage(jid, { text: 'Handler attivato!' });
982
+ }
983
+
984
+ // Nel main: conn.ev.on('messages.upsert', ({ messages }) => handleMessage(sock, messages[0]));
985
+ ```
986
+
987
+ **Consiglio:** Testa in gruppi per verificare LID, poichΓ© Baileys upstream ha migliorato il supporto nativo nel 2025, ma i fix personalizzati qui garantiscono retrocompatibilitΓ .
988
+
989
+ ---
990
+
991
+ ### πŸš€ Cache Intelligente LID/JID
992
+
993
+ La libreria ora include un sistema di cache avanzato per ottimizzare le conversioni LID/JID:
994
+
995
+ ```typescript
996
+ import { getCacheStats, clearCache, setPerformanceConfig } from '@realvare/based';
997
+
998
+ // Configura cache personalizzata
999
+ setPerformanceConfig({
1000
+ cache: {
1001
+ lidCache: {
1002
+ ttl: 10 * 60 * 1000, // 10 minuti
1003
+ maxSize: 15000
1004
+ }
1005
+ }
1006
+ });
1007
+
1008
+ // Monitora performance
1009
+ const stats = getCacheStats();
1010
+ console.log('Cache LID:', stats.lidCache.size, '/', stats.lidCache.maxSize);
1011
+
1012
+ // Pulisci cache se necessario
1013
+ clearCache();
1014
+ ```
1015
+
1016
+ ### πŸ›‘οΈ Validazione JID Avanzata
1017
+
1018
+ ```typescript
1019
+ import { validateJid, Logger } from '@realvare/based';
1020
+
1021
+ const jid = '1234567890@s.whatsapp.net';
1022
+ const validation = validateJid(jid);
1023
+
1024
+ if (validation.isValid) {
1025
+ Logger.info('JID valido:', jid);
1026
+ } else {
1027
+ Logger.error('JID non valido:', validation.error);
1028
+ }
1029
+ ```
1030
+
1031
+ ### πŸ“Š Logging Condizionale
1032
+
1033
+ ```typescript
1034
+ import { Logger, setPerformanceConfig } from '@realvare/based';
1035
+
1036
+ // Configura logging
1037
+ setPerformanceConfig({
1038
+ debug: {
1039
+ enableLidLogging: true,
1040
+ enablePerformanceLogging: true,
1041
+ logLevel: 'debug' // 'error', 'warn', 'info', 'debug'
1042
+ }
1043
+ });
1044
+
1045
+ // Usa logger condizionale
1046
+ Logger.debug('Debug info');
1047
+ Logger.performance('Performance metrics');
1048
+ Logger.error('Error occurred');
1049
+ ```
1050
+
1051
+ ### πŸ”§ Configurazione Performance
1052
+
1053
+ ```typescript
1054
+ import { setPerformanceConfig, getPerformanceConfig } from '@realvare/based';
1055
+
1056
+ // Configurazione completa
1057
+ setPerformanceConfig({
1058
+ performance: {
1059
+ enableCache: true,
1060
+ enableMetrics: true,
1061
+ batchSize: 100,
1062
+ maxRetries: 3
1063
+ },
1064
+ cache: {
1065
+ lidCache: { ttl: 5 * 60 * 1000, maxSize: 10000 },
1066
+ jidCache: { ttl: 5 * 60 * 1000, maxSize: 10000 }
1067
+ },
1068
+ debug: {
1069
+ enableLidLogging: false,
1070
+ logLevel: 'warn'
1071
+ }
1072
+ });
1073
+
1074
+ // Ottieni configurazione corrente
1075
+ const config = getPerformanceConfig();
1076
+ console.log('Cache abilitata:', config.performance.enableCache);
1077
+ ```
1078
+
1079
+ ---
1080
+
1081
+ ## 🧩 Eventi: LID e JID sempre disponibili (nuovo)
1082
+
1083
+ Gli eventi emessi includono campi ausiliari sui messaggi per accedere facilmente sia al JID sia al LID del mittente/partecipante.
1084
+
1085
+ ```typescript
1086
+ conn.ev.on('messages.upsert', ({ messages, type }) => {
1087
+ for (const msg of messages) {
1088
+ // Campi aggiuntivi su msg.key
1089
+ // - remoteJidNormalized: JID normalizzato (es. @s.whatsapp.net)
1090
+ // - remoteLid: LID equivalente del remoteJid
1091
+ // - participantLid: LID equivalente del participant (se presente)
1092
+ const jid = msg.key.remoteJidNormalized || msg.key.remoteJid;
1093
+ const remoteLid = msg.key.remoteLid;
1094
+ const participantLid = msg.key.participantLid;
1095
+
1096
+ if (jid?.endsWith('@s.whatsapp.net')) {
1097
+ conn.sendMessage(jid, { text: `Ciao! LID: ${remoteLid || 'n/d'}` });
1098
+ }
1099
+ }
1100
+ });
1101
+ ```
1102
+
1103
+ Questi campi eliminano ambiguitΓ  in gruppi e contesti multi-dispositivo dove alcuni eventi riportano LID, altri JID.
1104
+
1105
+ ---
1106
+
1107
+ ## βš™οΈ Configurazione Avanzata
1108
+
1109
+ Personalizza il socket per performance e comportamento.
1110
+
1111
+ ### πŸ”§ Opzioni Complete per makeWASocket
1112
+
1113
+ ```typescript
1114
+ const sock = makeWASocket({
1115
+ // πŸ” Autenticazione
1116
+ auth: state,
1117
+
1118
+ // πŸ–₯️ UI e Debug
1119
+ printQRInTerminal: true,
1120
+ logger: console,
1121
+ browser: ['VareBot', 'Chrome', '4.0.0'],
1122
+
1123
+ // ⏱️ Timeout e Connessione
1124
+ defaultQueryTimeoutMs: 60000,
1125
+ keepAliveIntervalMs: 30000,
1126
+ connectTimeoutMs: 60000,
1127
+ retryRequestDelayMs: 250,
1128
+ maxMsgRetryCount: 5,
1129
+
1130
+ // πŸŽ›οΈ Comportamento
1131
+ markOnlineOnConnect: true,
1132
+ syncFullHistory: false, // Attiva per sync completo (consuma dati)
1133
+ fireInitQueries: true,
1134
+ generateHighQualityLinkPreview: true,
1135
+ });
1136
+ ```
1137
+ <div align="center">
1138
+
1139
+ ### πŸ›‘οΈ Sicurezza e Crittografia
1140
+
1141
+ | Caratteristica | Descrizione |
1142
+ |---------------------------|------------------------------------------|
1143
+ | πŸ” End-to-End Encryption | Protocollo Signal per messaggi sicuri |
1144
+ | πŸ”‘ Key Management | Generazione/rotazione automatica chiavi |
1145
+ | πŸ” Authentication | Sicurezza tramite QR code o pairing code |
1146
+ | πŸ›‘οΈ Data Protection | Archiviazione sicura credenziali locali |
1147
+
1148
+ ---
1149
+
1150
+ ## 🌐 Supporto e Community
1151
+
1152
+ Unisciti alla community per aiuto e contributi.
1153
+
1154
+ ### πŸ“ž Contatti e Risorse
1155
+
1156
+ | Canale | Link/Info |
1157
+ |------------------|------------------------------------------|
1158
+ | **Email** | [samakavare1@gmail.com](mailto:samakavare1@gmail.com) |
1159
+ | **GitHub Issues**| [Segnala Bug](https://github.com/realvare/based/issues) |
1160
+ | **PayPal** | [Dona](https://www.paypal.me/samakavare) |
1161
+ | **Canale whatsapp**| [Canale](https://www.whatsapp.com/channel/0029VbB41Sa1Hsq1JhsC1Z1z) |
1162
+
1163
+ ---
1164
+
1165
+ ## πŸ™ Ringraziamenti
1166
+
1167
+ Grazie ai progetti che ispirano Based:
1168
+
1169
+ | Progetto | Contributo |
1170
+ |---------------------------|------------------------------------------|
1171
+ | [Baileys](https://github.com/WhiskeySockets/Baileys) | API WhatsApp Web originale |
1172
+ | [Yupra](https://www.npmjs.com/package/@yupra/baileys) | Fix LID/JID |
1173
+ | [Signal Protocol](https://signal.org/) | Crittografia end-to-end |
1174
+
1175
+ ---
1176
+
1177
+ ## ⚠️ Disclaimer & Licenza
1178
+
1179
+ ### πŸ“‹ Nota Legale
1180
+
1181
+ ⚠️ **Importante**: Non affiliato a WhatsApp Inc. o Meta. Uso educativo/sviluppo solo.
1182
+
1183
+ πŸ›‘οΈ **Uso Responsabile**: Evita spam, violazioni ToS WhatsApp. Rischio ban account.
1184
+
1185
+ ### πŸ“œ Licenza MIT
1186
+
1187
+ MIT License Β© 2025 [realvare](https://github.com/realvare)
1188
+
1189
+ Vedi [LICENSE](LICENSE) per dettagli.
1190
+
1191
+ ---
1192
+
1193
+ <div align="center">
1194
+ <table align="center">
1195
+ <tr>
1196
+ <td align="center">
1197
+ <img src="https://i.ibb.co/Cp0SQznC/sam2.png" width="120" height="120" alt="pfp" style="bysamakavare"/>
1198
+ <br><br>
1199
+ <h2>πŸ‘¨β€πŸ’» Creato da <a href="https://github.com/realvare" style="color: #8a2be2; text-decoration: none;">realvare</a></h2>
1200
+ <p><em>sam aka vare</em></p>
1201
+ </td>
1202
+ </tr>
1203
+ </table>
1204
+
1205
+ <br>
1206
+ <p align="center">
1207
+ <a href="https://github.com/realvare/based">
1208
+ <img src="https://img.shields.io/badge/⭐_Stella_il_Progetto-8a2be2?style=for-the-badge&logo=github&logoColor=white&labelColor=2d1b69"/>
1209
+ </a>&nbsp;&nbsp;
1210
+ <a href="https://github.com/realvare/based/fork">
1211
+ <img src="https://img.shields.io/badge/πŸ”„_Fork_Repository-8a2be2?style=for-the-badge&logo=github&logoColor=white&labelColor=2d1b69"/>
1212
+ </a>&nbsp;&nbsp;
1213
+ <a href="https://paypal.me/samakavare">
1214
+ <img src="https://img.shields.io/badge/πŸ’°_Dona-8a2be2?style=for-the-badge&logo=paypal&logoColor=white&labelColor=2d1b69"/>
1215
+ </a>
1216
+ </p>
1217
+ <p align="center">
1218
+ <a href="https://github.com/realvare">
1219
+ <img src="https://img.shields.io/badge/GitHub-100000?style=for-the-badge&logo=github&logoColor=white&color=8a2be2"/>
1220
+ </a>&nbsp;
1221
+ <a href="https://wa.me/393476686131">
1222
+ <img src="https://img.shields.io/badge/WhatsApp-25D366?style=for-the-badge&logo=whatsapp&logoColor=white&color=8a2be2"/>
1223
+ </a>&nbsp;
1224
+ <a href="https://instagram.com/samakavare">
1225
+ <img src="https://img.shields.io/badge/Instagram-E4405F?style=for-the-badge&logo=instagram&logoColor=white&color=8a2be2"/>
1226
+ </a>&nbsp;
1227
+ <a href="mailto:samakavare1@gmail.com">
1228
+ <img src="https://img.shields.io/badge/Email-D14836?style=for-the-badge&logo=gmail&logoColor=white&color=8a2be2"/>
1229
+ </a>
1230
+ </p>
1231
+ <div align="center">
1232
+ <p><strong>Se ti è stato utile, lascia una stella e/o considera una donazione! ✧</strong></p>
1233
+
1234
+ <br>
1235
+ <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"/>
1236
+
1237
+ </div>