akra35567 commited on
Commit
d0c2824
Β·
verified Β·
1 Parent(s): 5b9fd08

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +48 -93
index.js CHANGED
@@ -5,40 +5,51 @@
5
  */
6
 
7
  // ═══════════════════════════════════════════════════════════════════════
8
- // 1. CRÍTICO: INICIALIZA CORREÇÕES DE DNS ANTES DE TUDO
9
  // ═══════════════════════════════════════════════════════════════════════
10
- // Isso forΓ§a o uso dos IPs diretos definidos no HFCorrections.js
11
- // impedindo o erro ENOTFOUND/ENODATA no container.
12
- const HFCorrections = require('./modules/HFCorrections');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  HFCorrections.configureDNS();
14
 
15
- // ═══════════════════════════════════════════════════════════════════════
16
- // 2. IMPORTS E CONFIGURAÇÃO
17
- // ═══════════════════════════════════════════════════════════════════════
18
  const express = require('express');
19
  const QRCode = require('qrcode');
20
- const ConfigManager = require('./ConfigManager');
21
- const BotCore = require('./BotCore');
22
 
 
 
 
 
 
23
  const config = ConfigManager.getInstance();
24
  let botCore = null;
25
  let app = null;
26
  let server = null;
27
 
28
  // ═══════════════════════════════════════════════════════════════════════
29
- // 3. SERVIDOR EXPRESS (INTERFACE WEB)
30
  // ═══════════════════════════════════════════════════════════════════════
31
 
32
  function initializeServer() {
33
  app = express();
34
  app.use(express.json());
35
 
36
- // Middleware de log simples
37
- app.use((req, res, next) => {
38
- // console.log(`[WEB] ${req.method} ${req.path}`); // Descomente para debug web
39
- next();
40
- });
41
-
42
  // ROTA PRINCIPAL: Status visual
43
  app.get('/', (req, res) => {
44
  if (!botCore) {
@@ -70,30 +81,22 @@ function initializeServer() {
70
  <body>
71
  <div class="card">
72
  <h1>πŸ€– AKIRA BOT V21</h1>
73
-
74
  <div class="status-box ${status.isConnected ? 'online' : 'offline'}">
75
  STATUS: ${status.isConnected ? 'βœ… CONECTADO' : '❌ DESCONECTADO'}
76
  </div>
77
-
78
  <p>
79
  <strong>Bot:</strong> ${config.BOT_NAME}<br>
80
  <strong>VersΓ£o:</strong> ${config.BOT_VERSION}
81
  </p>
82
-
83
  ${!status.isConnected ? `
84
  <div style="margin: 20px 0;">
85
  ${hasQR
86
  ? '<a href="/qr" class="btn">πŸ“± ESCANEAR QR CODE</a>'
87
  : '⏳ Gerando QR Code... aguarde...'}
88
  </div>
89
- <p style="color: #f85149">O QR Code expira rapidamente. Se sumir, aguarde ele recarregar.</p>
90
- ` : `
91
- <p>Bot operando normalmente.</p>
92
- `}
93
-
94
- <div class="footer">
95
- Hugging Face Spaces β€’ Porta ${config.PORT}
96
- </div>
97
  </div>
98
  </body>
99
  </html>
@@ -103,82 +106,47 @@ function initializeServer() {
103
  // ROTA QR: Exibe apenas a imagem do QR
104
  app.get('/qr', async (req, res) => {
105
  if (!botCore) return res.send('Inicializando...');
106
-
107
  const qr = botCore.getQRCode();
108
-
109
- if (botCore.isConnected) {
110
- return res.send('<h2 style="color:green; font-family:monospace; text-align:center">βœ… BOT JÁ CONECTADO!</h2>');
111
- }
112
-
113
- if (!qr) {
114
- return res.send(`
115
- <div style="font-family:monospace; text-align:center">
116
- <h2>πŸ”„ Gerando novo QR Code...</h2>
117
- <p>Aguarde 5 segundos...</p>
118
- <script>setTimeout(() => window.location.reload(), 3000);</script>
119
- </div>
120
- `);
121
- }
122
 
123
  try {
124
  const img = await QRCode.toDataURL(qr, { scale: 8, margin: 4 });
125
- res.send(`
126
- <div style="text-align:center; background: #fff; padding: 20px; height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center;">
127
- <h2 style="font-family: sans-serif; margin-bottom: 20px;">Escaneie com o WhatsApp</h2>
128
- <img src="${img}" style="max-width: 100%; border: 1px solid #ccc;">
129
- <br>
130
- <p style="font-family: sans-serif;">Atualiza automaticamente</p>
131
- <script>setTimeout(() => window.location.reload(), 15000);</script>
132
- </div>
133
- `);
134
- } catch (e) {
135
- res.status(500).send('Erro ao gerar imagem QR');
136
- }
137
- });
138
-
139
- // ROTA HEALTH: Para uptime checks
140
- app.get('/health', (req, res) => {
141
- res.json({
142
- status: botCore?.isConnected ? 'online' : 'offline',
143
- timestamp: new Date().toISOString()
144
- });
145
  });
146
 
147
  // Inicializa servidor
148
  server = app.listen(config.PORT, '0.0.0.0', () => {
149
- console.log('\n' + '═'.repeat(50));
150
- console.log(`🌐 SERVIDOR WEB INICIADO`);
151
- console.log(`πŸ”— URL: http://localhost:${config.PORT}`);
152
- console.log('═'.repeat(50) + '\n');
153
  });
154
  }
155
 
156
  // ═══════════════════════════════════════════════════════════════════════
157
- // 4. FUNÇÃO PRINCIPAL (MAIN LOOP)
158
  // ═══════════════════════════════════════════════════════════════════════
159
 
160
  async function main() {
161
  try {
162
- console.log('\n' + '═'.repeat(50));
163
- console.log('πŸš€ INICIANDO AKIRA BOT V21 (HF SPACES)');
164
- console.log('═'.repeat(50));
165
 
166
  // 1. Instancia o BotCore
167
- console.log('πŸ”§ Carregando nΓΊcleo...');
168
  botCore = new BotCore();
169
 
170
  // 2. Inicializa pastas e componentes
171
  await botCore.initialize();
172
 
173
- // 3. Sobe o servidor Web (para mostrar QR)
174
  initializeServer();
175
 
176
- // 4. Conecta ao WhatsApp (em background)
177
- // Usamos .catch para que erros de conexΓ£o nΓ£o derrubem o servidor web
178
  console.log('πŸ”— Iniciando conexΓ£o com WhatsApp...');
179
  botCore.connect().catch(err => {
180
- console.error('❌ Erro na primeira tentativa de conexão:', err.message);
181
- console.log('πŸ”„ O sistema tentarΓ‘ reconectar automaticamente...');
182
  });
183
 
184
  } catch (error) {
@@ -187,24 +155,11 @@ async function main() {
187
  }
188
  }
189
 
190
- // ═══════════════════════════════════════════════════════════════════════
191
- // 5. ENCERRAMENTO SEGURO
192
- // ═══════════════════════════════════════════════════════════════════════
193
-
194
- process.on('SIGINT', () => {
195
- console.log('\nπŸ›‘ Encerrando bot...');
196
- if (server) server.close();
197
- process.exit(0);
198
- });
199
-
200
- process.on('uncaughtException', (err) => {
201
- console.error('❌ ERRO NΓƒO TRATADO:', err);
202
- // NΓ£o sai do processo para manter o container vivo se possΓ­vel
203
- });
204
 
205
  // Executa
206
- if (require.main === module) {
207
- main();
208
- }
209
 
210
  module.exports = { botCore, app, config };
 
5
  */
6
 
7
  // ═══════════════════════════════════════════════════════════════════════
8
+ // 1. CRÍTICO: CARREGAMENTO DOS MΓ“DULOS COM FALLBACK DE CAMINHO
9
  // ═══════════════════════════════════════════════════════════════════════
10
+
11
+ function smartRequire(moduleName) {
12
+ try {
13
+ // Tenta carregar da raiz
14
+ return require(`./${moduleName}`);
15
+ } catch (e) {
16
+ try {
17
+ // Tenta carregar da subpasta modules (comum no HF)
18
+ return require(`./modules/${moduleName}`);
19
+ } catch (e2) {
20
+ console.error(`❌ ERRO CRÍTICO: Não foi possível encontrar o módulo ${moduleName}`);
21
+ console.error(`Tentativas falhas em: ./${moduleName} e ./modules/${moduleName}`);
22
+ process.exit(1);
23
+ }
24
+ }
25
+ }
26
+
27
+ // Inicializa correΓ§Γ΅es de DNS antes de qualquer outro import
28
+ const HFCorrections = smartRequire('HFCorrections');
29
  HFCorrections.configureDNS();
30
 
31
+ // Imports de bibliotecas externas
 
 
32
  const express = require('express');
33
  const QRCode = require('qrcode');
 
 
34
 
35
+ // Imports dos componentes do Bot usando o carregador inteligente
36
+ const ConfigManager = smartRequire('ConfigManager');
37
+ const BotCore = smartRequire('BotCore');
38
+
39
+ // InicializaΓ§Γ£o das constantes
40
  const config = ConfigManager.getInstance();
41
  let botCore = null;
42
  let app = null;
43
  let server = null;
44
 
45
  // ═══════════════════════════════════════════════════════════════════════
46
+ // 2. SERVIDOR EXPRESS (INTERFACE WEB)
47
  // ═══════════════════════════════════════════════════════════════════════
48
 
49
  function initializeServer() {
50
  app = express();
51
  app.use(express.json());
52
 
 
 
 
 
 
 
53
  // ROTA PRINCIPAL: Status visual
54
  app.get('/', (req, res) => {
55
  if (!botCore) {
 
81
  <body>
82
  <div class="card">
83
  <h1>πŸ€– AKIRA BOT V21</h1>
 
84
  <div class="status-box ${status.isConnected ? 'online' : 'offline'}">
85
  STATUS: ${status.isConnected ? 'βœ… CONECTADO' : '❌ DESCONECTADO'}
86
  </div>
 
87
  <p>
88
  <strong>Bot:</strong> ${config.BOT_NAME}<br>
89
  <strong>VersΓ£o:</strong> ${config.BOT_VERSION}
90
  </p>
 
91
  ${!status.isConnected ? `
92
  <div style="margin: 20px 0;">
93
  ${hasQR
94
  ? '<a href="/qr" class="btn">πŸ“± ESCANEAR QR CODE</a>'
95
  : '⏳ Gerando QR Code... aguarde...'}
96
  </div>
97
+ <p style="color: #f85149">O QR Code expira rapidamente.</p>
98
+ ` : `<p>Bot operando normalmente.</p>`}
99
+ <div class="footer">Hugging Face Spaces β€’ Porta ${config.PORT}</div>
 
 
 
 
 
100
  </div>
101
  </body>
102
  </html>
 
106
  // ROTA QR: Exibe apenas a imagem do QR
107
  app.get('/qr', async (req, res) => {
108
  if (!botCore) return res.send('Inicializando...');
 
109
  const qr = botCore.getQRCode();
110
+ if (botCore.isConnected) return res.send('<h2 style="color:green; text-align:center">βœ… BOT JÁ CONECTADO!</h2>');
111
+ if (!qr) return res.send('<h2>πŸ”„ Gerando novo QR Code... aguarde 5s.</h2><script>setTimeout(()=>location.reload(),5000)</script>');
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
  try {
114
  const img = await QRCode.toDataURL(qr, { scale: 8, margin: 4 });
115
+ res.send(`<div style="text-align:center; background:#fff; padding:20px; height:100vh; display:flex; flex-direction:column; align-items:center; justify-content:center;">
116
+ <h2>Escaneie com o WhatsApp</h2>
117
+ <img src="${img}" style="max-width:100%;">
118
+ <script>setTimeout(()=>location.reload(),15000)</script>
119
+ </div>`);
120
+ } catch (e) { res.status(500).send('Erro ao gerar imagem QR'); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  });
122
 
123
  // Inicializa servidor
124
  server = app.listen(config.PORT, '0.0.0.0', () => {
125
+ console.log(`🌐 SERVIDOR WEB EM EXECUÇÃO NA PORTA ${config.PORT}`);
 
 
 
126
  });
127
  }
128
 
129
  // ═══════════════════════════════════════════════════════════════════════
130
+ // 3. FUNÇÃO PRINCIPAL
131
  // ═══════════════════════════════════════════════════════════════════════
132
 
133
  async function main() {
134
  try {
135
+ console.log('πŸš€ INICIANDO AKIRA BOT V21...');
 
 
136
 
137
  // 1. Instancia o BotCore
 
138
  botCore = new BotCore();
139
 
140
  // 2. Inicializa pastas e componentes
141
  await botCore.initialize();
142
 
143
+ // 3. Sobe o servidor Web
144
  initializeServer();
145
 
146
+ // 4. Conecta ao WhatsApp
 
147
  console.log('πŸ”— Iniciando conexΓ£o com WhatsApp...');
148
  botCore.connect().catch(err => {
149
+ console.error('❌ Erro na conexão:', err.message);
 
150
  });
151
 
152
  } catch (error) {
 
155
  }
156
  }
157
 
158
+ // Handlers de encerramento
159
+ process.on('SIGINT', () => { if (server) server.close(); process.exit(0); });
160
+ process.on('uncaughtException', (err) => { console.error('❌ ERRO NΓƒO TRATADO:', err); });
 
 
 
 
 
 
 
 
 
 
 
161
 
162
  // Executa
163
+ main();
 
 
164
 
165
  module.exports = { botCore, app, config };