Erinaldordso commited on
Commit
ea60820
·
verified ·
1 Parent(s): 3383549

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +25 -13
index.js CHANGED
@@ -32,10 +32,22 @@ function formatarVip(t) {
32
  }
33
 
34
  async function iniciar() {
35
- console.log("🚀 INICIANDO SISTEMA...");
 
 
 
36
 
37
- // Define o caminho do disco persistente (/data) se existir
38
  const authPath = fs.existsSync('/data') ? '/data/auth_naldo' : './auth_naldo';
 
 
 
 
 
 
 
 
 
 
39
  const { state, saveCreds } = await useMultiFileAuthState(authPath);
40
  const { version } = await fetchLatestBaileysVersion();
41
 
@@ -45,8 +57,6 @@ async function iniciar() {
45
  logger: pino({ level: 'silent' }),
46
  browser: Browsers.ubuntu('Chrome'),
47
  syncFullHistory: false,
48
- connectTimeoutMs: 60000,
49
- defaultQueryTimeoutMs: 0,
50
  keepAliveInternalMs: 30000
51
  });
52
 
@@ -56,9 +66,8 @@ async function iniciar() {
56
  const { connection, lastDisconnect } = update;
57
 
58
  if (connection === 'open') {
59
- console.log("✅ WHATSAPP CONECTADO!");
60
 
61
- // INICIA TELEGRAM SÓ DEPOIS QUE O WHATSAPP ESTIVER OK
62
  const client = new TelegramClient(new StringSession(CONFIG.tgSession), CONFIG.tgId, CONFIG.tgHash, {});
63
  await client.connect();
64
  console.log("📡 MONITORANDO TELEGRAM...");
@@ -77,25 +86,28 @@ async function iniciar() {
77
 
78
  if (connection === 'close') {
79
  const reason = lastDisconnect?.error?.output?.statusCode;
80
- console.log(`❌ Conexão fechada. Razão: ${reason}`);
81
  if (reason !== DisconnectReason.loggedOut) {
82
- console.log("🔄 Tentando reconectar em 5 segundos...");
83
- setTimeout(() => iniciar(), 5000);
 
 
 
 
84
  }
85
  }
86
  });
87
 
88
- // Pede o código se não estiver registrado, mas com proteção de erro
89
  if (!sock.authState.creds.registered) {
90
- console.log("⏳ Aguardando estabilidade para gerar código...");
91
  setTimeout(async () => {
92
  try {
93
  const code = await sock.requestPairingCode(CONFIG.waPhone);
94
  console.log(`\n🔥 CÓDIGO WHATSAPP: ${code}\n`);
95
  } catch (err) {
96
- console.log("⚠️ Erro ao gerar código. O sistema vai reiniciar e tentar de novo.");
97
  }
98
- }, 10000); // 10 segundos de espera para garantir conexão
99
  }
100
  }
101
 
 
32
  }
33
 
34
  async function iniciar() {
35
+ console.log("🚀 AGUARDANDO 10 SEGUNDOS PARA VERIFICAR STORAGE...");
36
+
37
+ // Aguarda o tempo que você pediu para o sistema estabilizar
38
+ await new Promise(resolve => setTimeout(resolve, 10000));
39
 
 
40
  const authPath = fs.existsSync('/data') ? '/data/auth_naldo' : './auth_naldo';
41
+
42
+ // Verifica se o arquivo principal de credenciais já existe no disco
43
+ const temLogin = fs.existsSync(`${authPath}/creds.json`);
44
+
45
+ if (temLogin) {
46
+ console.log("📂 LOGIN ENCONTRADO! Tentando conectar sem pedir código...");
47
+ } else {
48
+ console.log("🆕 NENHUM LOGIN ENCONTRADO. Preparando para gerar novo código...");
49
+ }
50
+
51
  const { state, saveCreds } = await useMultiFileAuthState(authPath);
52
  const { version } = await fetchLatestBaileysVersion();
53
 
 
57
  logger: pino({ level: 'silent' }),
58
  browser: Browsers.ubuntu('Chrome'),
59
  syncFullHistory: false,
 
 
60
  keepAliveInternalMs: 30000
61
  });
62
 
 
66
  const { connection, lastDisconnect } = update;
67
 
68
  if (connection === 'open') {
69
+ console.log("✅ WHATSAPP CONECTADO COM SUCESSO!");
70
 
 
71
  const client = new TelegramClient(new StringSession(CONFIG.tgSession), CONFIG.tgId, CONFIG.tgHash, {});
72
  await client.connect();
73
  console.log("📡 MONITORANDO TELEGRAM...");
 
86
 
87
  if (connection === 'close') {
88
  const reason = lastDisconnect?.error?.output?.statusCode;
 
89
  if (reason !== DisconnectReason.loggedOut) {
90
+ console.log(`🔄 Conexão interrompida (Razão: ${reason}). Reconectando...`);
91
+ iniciar();
92
+ } else {
93
+ console.log("❌ Deslogado do WhatsApp. Apagando pasta de login e reiniciando...");
94
+ fs.rmSync(authPath, { recursive: true, force: true });
95
+ iniciar();
96
  }
97
  }
98
  });
99
 
100
+ // SÓ PEDE O CÓDIGO SE NÃO TIVER LOGIN SALVO
101
  if (!sock.authState.creds.registered) {
102
+ console.log("⏳ Gerando código de pareamento em 5 segundos...");
103
  setTimeout(async () => {
104
  try {
105
  const code = await sock.requestPairingCode(CONFIG.waPhone);
106
  console.log(`\n🔥 CÓDIGO WHATSAPP: ${code}\n`);
107
  } catch (err) {
108
+ console.log("⚠️ Erro ao gerar código. Tentando novamente.");
109
  }
110
+ }, 5000);
111
  }
112
  }
113