@realvare/based 2.5.5 → 2.5.6

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
@@ -83,7 +83,7 @@ setPerformanceConfig({
83
83
  async function startBot() {
84
84
  // 🔐 Setup autenticazione multi-file per sessioni persistenti
85
85
  const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
86
-
86
+
87
87
  // 🌐 Creazione del socket con configurazione base
88
88
  const sock = makeWASocket({
89
89
  auth: state,
@@ -98,22 +98,22 @@ async function startBot() {
98
98
 
99
99
  sock.ev.on('connection.update', (update) => {
100
100
  const { connection, lastDisconnect } = update;
101
-
101
+
102
102
  if (connection === 'close') {
103
103
  const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
104
-
104
+
105
105
  if (shouldReconnect) {
106
106
  reconnectAttempts++;
107
107
  const delay = Math.min(
108
108
  config.performance.retryDelay * Math.pow(
109
- config.performance.retryBackoffMultiplier,
109
+ config.performance.retryBackoffMultiplier,
110
110
  reconnectAttempts - 1
111
111
  ),
112
112
  config.performance.maxRetryDelay
113
113
  );
114
-
114
+
115
115
  console.log(`🔄 Tentativo di riconnessione ${reconnectAttempts}/${config.performance.maxRetries} tra ${delay}ms`);
116
-
116
+
117
117
  if (reconnectAttempts <= config.performance.maxRetries) {
118
118
  setTimeout(startBot, delay);
119
119
  } else {
@@ -130,6 +130,100 @@ async function startBot() {
130
130
  }startBot().catch(console.error);
131
131
  ```
132
132
 
133
+ ### Esempio Anti-Ban - Configurazione consigliata per Evitare Ban
134
+
135
+ ```typescript
136
+ import makeWASocket, { DisconnectReason, useMultiFileAuthState, getPerformanceConfig, setPerformanceConfig, getSenderLid, validateJid } from '@realvare/based';
137
+
138
+ // Configurazione anti-ban per ridurre rischi ban da acks impropri
139
+ setPerformanceConfig({
140
+ performance: {
141
+ enableCache: true, // Abilita cache TTL per ridurre chiamate API
142
+ enableMetrics: true, // Monitora performance per evitare sovraccarico
143
+ batchSize: 50, // Elabora messaggi in batch più piccoli per simulare velocità umana
144
+ maxRetries: 5, // Limita tentativi retry per evitare comportamento aggressivo
145
+ retryDelay: 5000, // Ritardo base in ms per riconnessioni
146
+ retryBackoffMultiplier: 1.5,// Backoff esponenziale per spaziare retry
147
+ maxRetryDelay: 60000, // Ritardo massimo per evitare riconnessioni rapide
148
+ maxMsgRetryCount: 3 // Limita tentativi rispedizione messaggi
149
+ }
150
+ });
151
+
152
+ async function startBot() {
153
+ const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
154
+
155
+ const sock = makeWASocket({
156
+ auth: state,
157
+ printQRInTerminal: true,
158
+ logger: console,
159
+ browser: ['YourBotName', 'Chrome', '4.0.0'], // Personalizza fingerprint browser
160
+ markOnlineOnConnect: false, // Cruciale: Previene apparire sempre online, riduce rischio ban
161
+ syncFullHistory: false // Evita sync dati non necessari che potrebbero segnalare attività
162
+ });
163
+
164
+ let reconnectAttempts = 0;
165
+ const config = getPerformanceConfig();
166
+
167
+ sock.ev.on('connection.update', (update) => {
168
+ const { connection, lastDisconnect } = update;
169
+
170
+ if (connection === 'close') {
171
+ const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
172
+
173
+ if (shouldReconnect) {
174
+ reconnectAttempts++;
175
+ const delay = Math.min(
176
+ config.performance.retryDelay * Math.pow(
177
+ config.performance.retryBackoffMultiplier,
178
+ reconnectAttempts - 1
179
+ ),
180
+ config.performance.maxRetryDelay
181
+ );
182
+
183
+ console.log(`Reconnecting attempt ${reconnectAttempts}/${config.performance.maxRetries} in ${delay}ms`);
184
+
185
+ if (reconnectAttempts <= config.performance.maxRetries) {
186
+ setTimeout(startBot, delay);
187
+ } else {
188
+ console.log('Max reconnection attempts reached');
189
+ }
190
+ }
191
+ } else if (connection === 'open') {
192
+ console.log('Connected successfully!');
193
+ reconnectAttempts = 0;
194
+ }
195
+ });
196
+
197
+ // Monitora acks tramite aggiornamenti messaggi per garantire gestione corretta
198
+ sock.ev.on('messages.update', (updates) => {
199
+ for (const update of updates) {
200
+ if (update.update.status) {
201
+ console.log(`Message ${update.key.id} status: ${update.update.status}`); // Traccia acks (1=sent, 2=delivered, 3=read)
202
+ // Aggiungi logica personalizzata se necessaria, ma evita override predefiniti per prevenire detection
203
+ }
204
+ }
205
+ });
206
+
207
+ // Utilità LID/JID avanzate per stabilità acks
208
+ sock.ev.on('messages.upsert', ({ messages }) => {
209
+ for (const msg of messages) {
210
+ const info = getSenderLid(msg);
211
+ const validation = validateJid(info.jid);
212
+ if (validation.isValid) {
213
+ // Elabora e ack in sicurezza
214
+ console.log(`Valid JID: ${info.jid}, LID: ${info.lid}`);
215
+ } else {
216
+ console.warn(`Invalid JID detected: ${info.jid}`);
217
+ }
218
+ }
219
+ });
220
+
221
+ sock.ev.on('creds.update', saveCreds);
222
+ }
223
+
224
+ startBot().catch(console.error);
225
+ ```
226
+
133
227
  ## 📊 Gestione Avanzata Cache
134
228
 
135
229
  La libreria ora include un sistema di cache avanzato con gestione automatica della memoria e TTL configurabile:
@@ -602,17 +696,17 @@ await conn.sendMessage(jid, {
602
696
  businessOwnerJid: m.sender
603
697
  });
604
698
 
605
- // Messaggi con Intestazione Personalizzata
699
+ // Messaggi con Intestazione Personalizzata
606
700
  await conn.sendMessage(jid, {
607
701
  text: 'dilemma',
608
702
  contextInfo: {
609
703
  externalAdReply: {
610
704
  title: `titolo`,
611
705
  body: `desc`,
612
- thumbnailUrl: 'https://i.ibb.co/kVdFLyGL/sam.jpg', // immagine
706
+ thumbnailUrl: 'https://i.ibb.co/hJW7WwxV/sam.jpg', // immagine
613
707
  sourceUrl: '', // sconsiglio di metterla
614
708
  mediaType: 1,
615
- renderLargerThumbnail: false // o true se la volete grande
709
+ renderLargerThumbnail: false
616
710
  }
617
711
  }
618
712
  });
@@ -46,7 +46,7 @@ exports.DEFAULT_CONNECTION_CONFIG = {
46
46
  maxMsgRetryCount: 5,
47
47
  fireInitQueries: true,
48
48
  auth: undefined,
49
- markOnlineOnConnect: true,
49
+ markOnlineOnConnect: false,
50
50
  syncFullHistory: false,
51
51
  patchMessageBeforeSending: msg => msg,
52
52
  shouldSyncHistoryMessage: () => true,
@@ -307,8 +307,10 @@ const makeSocket = (config) => {
307
307
  logger.trace({ trace: error === null || error === void 0 ? void 0 : error.stack }, 'connection already closed');
308
308
  return;
309
309
  }
310
- closed = true;
311
- logger.info({ trace: error === null || error === void 0 ? void 0 : error.stack }, error ? 'connection errored' : 'connection closed');
310
+ const statusCode = error?.output?.statusCode;
311
+ const shouldReconnect = statusCode !== Types_1.DisconnectReason.loggedOut;
312
+ logger.info({ trace: error === null || error === void 0 ? void 0 : error.stack, shouldReconnect }, error ? 'connection errored' : 'connection closed');
313
+ closed = !shouldReconnect;
312
314
  clearInterval(keepAliveReq);
313
315
  clearTimeout(qrTimer);
314
316
  ws.removeAllListeners('close');
@@ -328,7 +330,12 @@ const makeSocket = (config) => {
328
330
  date: new Date()
329
331
  }
330
332
  });
331
- ev.removeAllListeners('connection.update');
333
+ if (shouldReconnect) {
334
+ handleReconnect();
335
+ }
336
+ else {
337
+ ev.removeAllListeners('connection.update');
338
+ }
332
339
  };
333
340
  const waitForSocketOpen = async () => {
334
341
  if (ws.isOpen) {