akra35567 commited on
Commit
c6c710c
·
verified ·
1 Parent(s): c143758

Update modules/BotCore.js

Browse files
Files changed (1) hide show
  1. modules/BotCore.js +59 -22
modules/BotCore.js CHANGED
@@ -7,6 +7,10 @@
7
  * ═══════════════════════════════════════════════════════════════════════
8
  */
9
 
 
 
 
 
10
  const {
11
  default: makeWASocket,
12
  useMultiFileAuthState,
@@ -247,15 +251,8 @@ class BotCore {
247
 
248
  this.logger.info(`📄 Credenciais encontradas (${ageHours.toFixed(1)}h atrás)`);
249
 
250
- // Se as credenciais têm mais de 24 horas, força novo login
251
- if (ageHours > 24) {
252
- this.logger.warn(`🧹 Credenciais antigas detectadas (${ageHours.toFixed(1)}h). Forçando novo login...`);
253
- fs.rmSync(authPath, { recursive: true, force: true });
254
- this.isConnected = false;
255
- this.currentQR = null;
256
- this.BOT_JID = null;
257
- return;
258
- }
259
 
260
  // Verifica se o arquivo de credenciais é válido
261
  const credsContent = fs.readFileSync(credsPath, 'utf8');
@@ -316,6 +313,18 @@ class BotCore {
316
  this.logger.info('🔗 Conectando ao WhatsApp...');
317
  this.logger.info(`📁 Usando pasta de auth: ${this.config.AUTH_FOLDER}`);
318
 
 
 
 
 
 
 
 
 
 
 
 
 
319
  // Verifica conectividade de rede antes de tentar conectar
320
  const networkOk = await this._checkNetworkConnectivity();
321
  if (!networkOk) {
@@ -330,24 +339,34 @@ class BotCore {
330
 
331
  this.logger.info(`📦 Versão Baileys: ${version}`);
332
 
333
- // Configurações do socket
334
  const socketConfig = {
335
  version,
336
  auth: state,
337
  logger: pino({ level: 'silent' }), // Silencia logs do Baileys
338
- browser: Browsers.macOS(this.config.BOT_NAME),
339
  markOnlineOnConnect: true,
340
  syncFullHistory: false,
341
  printQRInTerminal: false, // Não mostra QR no terminal (usamos web)
342
- connectTimeoutMs: 120000, // 2 minutos
343
- qrTimeout: 90000, // 90 segundos para QR
344
  defaultQueryTimeoutMs: 60000,
345
- // Configurações para ambientes com conectividade limitada
346
- keepAliveIntervalMs: 30000,
347
- retryRequestDelayMs: 5000,
348
- maxRetries: 5,
349
  // Configurações específicas para ambientes restritos
350
  agent: this._createCustomAgent(),
 
 
 
 
 
 
 
 
 
 
351
  getMessage: async (key) => {
352
  if (!key) return undefined;
353
  try {
@@ -362,7 +381,7 @@ class BotCore {
362
  }
363
  };
364
 
365
- this.logger.debug('⚙️ Configuração do socket:', socketConfig);
366
 
367
  this.sock = makeWASocket(socketConfig);
368
 
@@ -387,17 +406,35 @@ class BotCore {
387
  this.logger.warn('⏰ QR não gerado automaticamente. Tentando forçar...');
388
  this._forceQRGeneration();
389
  }
390
- }, 15000); // 15 segundos
391
 
392
  this.logger.info('✅ Conexão inicializada - Aguardando QR code ou conexão...');
393
 
394
  } catch (error) {
395
  this.logger.error('❌ Erro na conexão:', error.message);
396
  this.logger.error(error.stack);
 
 
 
397
  throw error;
398
  }
399
  }
400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
  /**
402
  * Handle connection update
403
  */
@@ -422,7 +459,7 @@ class BotCore {
422
  console.log('📱 QR CODE DISPONÍVEL NA WEB!');
423
  console.log('═'.repeat(70));
424
  console.log(`🔗 URL: http://localhost:${this.config.PORT}/qr`);
425
- console.log('⏳ Válido por 90 segundos');
426
  console.log('📱 Abra essa URL no seu navegador');
427
  console.log('═'.repeat(70) + '\n');
428
 
@@ -504,8 +541,8 @@ class BotCore {
504
  this.eventListeners.onDisconnected(code, reason);
505
  }
506
 
507
- // Reconecta com backoff exponencial
508
- const reconnectDelay = Math.min(5000 * Math.pow(2, this.reconnectAttempts || 0), 60000); // Máximo 60 segundos
509
  this.reconnectAttempts = (this.reconnectAttempts || 0) + 1;
510
 
511
  this.logger.info(`🔄 Reconectando em ${reconnectDelay/1000}s... (tentativa ${this.reconnectAttempts})`);
 
7
  * ═══════════════════════════════════════════════════════════════════════
8
  */
9
 
10
+ // SOLUÇÃO CRÍTICA: Força IPv4 para resolver erro ENOTFOUND no Hugging Face
11
+ const dns = require('dns');
12
+ dns.setDefaultResultOrder('ipv4first');
13
+
14
  const {
15
  default: makeWASocket,
16
  useMultiFileAuthState,
 
251
 
252
  this.logger.info(`📄 Credenciais encontradas (${ageHours.toFixed(1)}h atrás)`);
253
 
254
+ // REMOVIDO: Limpeza automática após 24h - Mantém conexão estável no HF
255
+ // Credenciais são mantidas indefinidamente para evitar QR code diário
 
 
 
 
 
 
 
256
 
257
  // Verifica se o arquivo de credenciais é válido
258
  const credsContent = fs.readFileSync(credsPath, 'utf8');
 
313
  this.logger.info('🔗 Conectando ao WhatsApp...');
314
  this.logger.info(`📁 Usando pasta de auth: ${this.config.AUTH_FOLDER}`);
315
 
316
+ // Verificação de DNS para debugging
317
+ this.logger.info('🔍 Verificando resolução DNS...');
318
+ try {
319
+ const dns = require('dns');
320
+ await dns.promises.resolve('web.whatsapp.com');
321
+ this.logger.info('✅ DNS: web.whatsapp.com resolvido com sucesso');
322
+ } catch (dnsError) {
323
+ this.logger.warn(`⚠️ Erro DNS: ${dnsError.message}`);
324
+ // Força uso de IPv4 explicitamente
325
+ dns.setDefaultResultOrder('ipv4first');
326
+ }
327
+
328
  // Verifica conectividade de rede antes de tentar conectar
329
  const networkOk = await this._checkNetworkConnectivity();
330
  if (!networkOk) {
 
339
 
340
  this.logger.info(`📦 Versão Baileys: ${version}`);
341
 
342
+ // Configurações otimizadas para Hugging Face Spaces
343
  const socketConfig = {
344
  version,
345
  auth: state,
346
  logger: pino({ level: 'silent' }), // Silencia logs do Baileys
347
+ browser: Browsers.ubuntu('Chrome'), // Alterado para Ubuntu/Chrome (mais estável em container)
348
  markOnlineOnConnect: true,
349
  syncFullHistory: false,
350
  printQRInTerminal: false, // Não mostra QR no terminal (usamos web)
351
+ connectTimeoutMs: 180000, // Aumentado para 3 minutos para ambientes lentos
352
+ qrTimeout: 120000, // 120 segundos para QR
353
  defaultQueryTimeoutMs: 60000,
354
+ // Configurações otimizadas para ambientes com conectividade limitada
355
+ keepAliveIntervalMs: 45000, // Aumentado para manter conexão
356
+ retryRequestDelayMs: 8000, // Aumentado delay entre retentativas
357
+ maxRetries: 3, // Reduzido número de retentativas
358
  // Configurações específicas para ambientes restritos
359
  agent: this._createCustomAgent(),
360
+ // Força uso de IPv4
361
+ fetchAgent: this._createCustomAgent(),
362
+ // Configurações de WebSocket otimizadas
363
+ wsOptions: {
364
+ headers: {
365
+ 'Origin': 'https://web.whatsapp.com',
366
+ 'Host': 'web.whatsapp.com',
367
+ 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
368
+ }
369
+ },
370
  getMessage: async (key) => {
371
  if (!key) return undefined;
372
  try {
 
381
  }
382
  };
383
 
384
+ this.logger.debug('⚙️ Configuração do socket:', JSON.stringify(socketConfig, null, 2));
385
 
386
  this.sock = makeWASocket(socketConfig);
387
 
 
406
  this.logger.warn('⏰ QR não gerado automaticamente. Tentando forçar...');
407
  this._forceQRGeneration();
408
  }
409
+ }, 25000); // Aumentado para 25 segundos
410
 
411
  this.logger.info('✅ Conexão inicializada - Aguardando QR code ou conexão...');
412
 
413
  } catch (error) {
414
  this.logger.error('❌ Erro na conexão:', error.message);
415
  this.logger.error(error.stack);
416
+
417
+ // Reconecta automaticamente após erro
418
+ this._scheduleReconnect();
419
  throw error;
420
  }
421
  }
422
 
423
+ /**
424
+ * Agenda reconexão automática
425
+ */
426
+ _scheduleReconnect() {
427
+ const reconnectDelay = Math.min(10000 * Math.pow(1.5, this.reconnectAttempts), 120000);
428
+ this.reconnectAttempts = (this.reconnectAttempts || 0) + 1;
429
+
430
+ this.logger.info(`🔄 Reconectando em ${reconnectDelay/1000}s... (tentativa ${this.reconnectAttempts})`);
431
+
432
+ setTimeout(() => {
433
+ this.logger.info('🔄 Iniciando reconexão...');
434
+ this.connect().catch(e => this.logger.error('Erro na reconexão:', e.message));
435
+ }, reconnectDelay);
436
+ }
437
+
438
  /**
439
  * Handle connection update
440
  */
 
459
  console.log('📱 QR CODE DISPONÍVEL NA WEB!');
460
  console.log('═'.repeat(70));
461
  console.log(`🔗 URL: http://localhost:${this.config.PORT}/qr`);
462
+ console.log('⏳ Válido por 120 segundos');
463
  console.log('📱 Abra essa URL no seu navegador');
464
  console.log('═'.repeat(70) + '\n');
465
 
 
541
  this.eventListeners.onDisconnected(code, reason);
542
  }
543
 
544
+ // Reconecta com backoff exponencial otimizado
545
+ const reconnectDelay = Math.min(8000 * Math.pow(1.8, this.reconnectAttempts || 0), 90000); // Máximo 90 segundos
546
  this.reconnectAttempts = (this.reconnectAttempts || 0) + 1;
547
 
548
  this.logger.info(`🔄 Reconectando em ${reconnectDelay/1000}s... (tentativa ${this.reconnectAttempts})`);