Update modules/BotCore.js
Browse files- modules/BotCore.js +112 -11
modules/BotCore.js
CHANGED
|
@@ -46,6 +46,7 @@ class BotCore {
|
|
| 46 |
this.isConnected = false;
|
| 47 |
this.lastProcessedTime = 0;
|
| 48 |
this.processadas = new Set();
|
|
|
|
| 49 |
|
| 50 |
// Armazenamento
|
| 51 |
this.store = null;
|
|
@@ -154,6 +155,12 @@ class BotCore {
|
|
| 154 |
*/
|
| 155 |
async connect() {
|
| 156 |
try {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
this.logger.info('🔗 Conectando ao WhatsApp...');
|
| 158 |
|
| 159 |
// Verifica se devemos limpar credenciais antigas
|
|
@@ -170,13 +177,19 @@ class BotCore {
|
|
| 170 |
markOnlineOnConnect: true,
|
| 171 |
syncFullHistory: false,
|
| 172 |
printQRInTerminal: false,
|
| 173 |
-
connectTimeoutMs:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
getMessage: async (key) => {
|
| 175 |
if (!key) return undefined;
|
| 176 |
try {
|
| 177 |
if (this.store && typeof this.store.loadMessage === 'function') {
|
| 178 |
const msg = await this.store.loadMessage(key.remoteJid, key.id);
|
| 179 |
-
return msg
|
| 180 |
}
|
| 181 |
} catch (e) {}
|
| 182 |
return undefined;
|
|
@@ -195,6 +208,14 @@ class BotCore {
|
|
| 195 |
this.sock.ev.on('connection.update', this.handleConnectionUpdate.bind(this));
|
| 196 |
this.sock.ev.on('messages.upsert', this.handleMessagesUpsert.bind(this));
|
| 197 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
this.logger.info('✅ Conexão inicializada');
|
| 199 |
|
| 200 |
} catch (error) {
|
|
@@ -212,14 +233,28 @@ class BotCore {
|
|
| 212 |
|
| 213 |
if (qr) {
|
| 214 |
this.currentQR = qr;
|
| 215 |
-
this.logger.info('📱 QR Code gerado');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
}
|
| 217 |
|
| 218 |
if (connection === 'open') {
|
| 219 |
-
this.BOT_JID = this.sock.user
|
| 220 |
this.isConnected = true;
|
| 221 |
this.lastProcessedTime = Date.now();
|
| 222 |
this.currentQR = null;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
|
| 224 |
this.logger.info('\n' + '═'.repeat(70));
|
| 225 |
this.logger.info('✅ AKIRA BOT V21 ONLINE!');
|
|
@@ -229,10 +264,33 @@ class BotCore {
|
|
| 229 |
|
| 230 |
} else if (connection === 'close') {
|
| 231 |
this.isConnected = false;
|
| 232 |
-
const code = lastDisconnect
|
| 233 |
-
|
| 234 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
}
|
|
|
|
| 236 |
} catch (error) {
|
| 237 |
this.logger.error('❌ Erro em handleConnectionUpdate:', error.message);
|
| 238 |
}
|
|
@@ -404,7 +462,7 @@ class BotCore {
|
|
| 404 |
deveResponder = true;
|
| 405 |
} else {
|
| 406 |
// Em grupos, responde se for reply ao bot ou menção
|
| 407 |
-
if (replyInfo
|
| 408 |
deveResponder = true;
|
| 409 |
} else if (this.messageProcessor.isBotMentioned(m)) {
|
| 410 |
deveResponder = true;
|
|
@@ -412,7 +470,7 @@ class BotCore {
|
|
| 412 |
}
|
| 413 |
} else {
|
| 414 |
// Texto
|
| 415 |
-
if (replyInfo
|
| 416 |
deveResponder = true;
|
| 417 |
} else if (!ehGrupo) {
|
| 418 |
// Em PV sempre responde
|
|
@@ -439,7 +497,7 @@ class BotCore {
|
|
| 439 |
mensagem: texto,
|
| 440 |
tipo_conversa: ehGrupo ? 'grupo' : 'pv',
|
| 441 |
tipo_mensagem: foiAudio ? 'audio' : 'texto',
|
| 442 |
-
mensagem_citada: replyInfo
|
| 443 |
reply_metadata: replyInfo ? {
|
| 444 |
reply_to_bot: replyInfo.ehRespostaAoBot,
|
| 445 |
quoted_author_name: replyInfo.quemEscreveuCitacao || 'desconhecido'
|
|
@@ -480,7 +538,7 @@ class BotCore {
|
|
| 480 |
|
| 481 |
await this.simulateTyping(m.key.remoteJid, tempoDigitacao);
|
| 482 |
|
| 483 |
-
const opcoes = ehGrupo || (replyInfo
|
| 484 |
await this.sock.sendMessage(m.key.remoteJid, { text: resposta }, opcoes);
|
| 485 |
}
|
| 486 |
|
|
@@ -550,6 +608,49 @@ class BotCore {
|
|
| 550 |
}
|
| 551 |
}
|
| 552 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 553 |
/**
|
| 554 |
* Obtém QR Code atual
|
| 555 |
*/
|
|
|
|
| 46 |
this.isConnected = false;
|
| 47 |
this.lastProcessedTime = 0;
|
| 48 |
this.processadas = new Set();
|
| 49 |
+
this.reconnectAttempts = 0;
|
| 50 |
|
| 51 |
// Armazenamento
|
| 52 |
this.store = null;
|
|
|
|
| 155 |
*/
|
| 156 |
async connect() {
|
| 157 |
try {
|
| 158 |
+
// Evita múltiplas conexões simultâneas
|
| 159 |
+
if (this.sock && this.sock.ws && this.sock.ws.readyState === 1) {
|
| 160 |
+
this.logger.info('🔄 Já conectado, ignorando tentativa de reconexão');
|
| 161 |
+
return;
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
this.logger.info('🔗 Conectando ao WhatsApp...');
|
| 165 |
|
| 166 |
// Verifica se devemos limpar credenciais antigas
|
|
|
|
| 177 |
markOnlineOnConnect: true,
|
| 178 |
syncFullHistory: false,
|
| 179 |
printQRInTerminal: false,
|
| 180 |
+
connectTimeoutMs: 120000, // Aumentado para 2 minutos
|
| 181 |
+
qrTimeout: 90000, // 90 segundos para QR
|
| 182 |
+
defaultQueryTimeoutMs: 60000,
|
| 183 |
+
// Configurações para ambientes com conectividade limitada
|
| 184 |
+
keepAliveIntervalMs: 30000,
|
| 185 |
+
retryRequestDelayMs: 5000,
|
| 186 |
+
maxRetries: 5,
|
| 187 |
getMessage: async (key) => {
|
| 188 |
if (!key) return undefined;
|
| 189 |
try {
|
| 190 |
if (this.store && typeof this.store.loadMessage === 'function') {
|
| 191 |
const msg = await this.store.loadMessage(key.remoteJid, key.id);
|
| 192 |
+
return msg ? msg.message : undefined;
|
| 193 |
}
|
| 194 |
} catch (e) {}
|
| 195 |
return undefined;
|
|
|
|
| 208 |
this.sock.ev.on('connection.update', this.handleConnectionUpdate.bind(this));
|
| 209 |
this.sock.ev.on('messages.upsert', this.handleMessagesUpsert.bind(this));
|
| 210 |
|
| 211 |
+
// Timeout para forçar geração de QR se não vier automaticamente
|
| 212 |
+
this.qrTimeout = setTimeout(() => {
|
| 213 |
+
if (!this.currentQR && !this.isConnected) {
|
| 214 |
+
this.logger.warn('⏰ QR não gerado automaticamente. Tentando forçar...');
|
| 215 |
+
this._forceQRGeneration();
|
| 216 |
+
}
|
| 217 |
+
}, 10000); // 10 segundos
|
| 218 |
+
|
| 219 |
this.logger.info('✅ Conexão inicializada');
|
| 220 |
|
| 221 |
} catch (error) {
|
|
|
|
| 233 |
|
| 234 |
if (qr) {
|
| 235 |
this.currentQR = qr;
|
| 236 |
+
this.logger.info('📱 QR Code gerado - pronto para scan!');
|
| 237 |
+
this.logger.info('🔗 Acesse http://localhost:7860/qr para ver o QR code');
|
| 238 |
+
|
| 239 |
+
// Limpa timeout de força
|
| 240 |
+
if (this.qrTimeout) {
|
| 241 |
+
clearTimeout(this.qrTimeout);
|
| 242 |
+
this.qrTimeout = null;
|
| 243 |
+
}
|
| 244 |
}
|
| 245 |
|
| 246 |
if (connection === 'open') {
|
| 247 |
+
this.BOT_JID = (this.sock.user && this.sock.user.id) || null;
|
| 248 |
this.isConnected = true;
|
| 249 |
this.lastProcessedTime = Date.now();
|
| 250 |
this.currentQR = null;
|
| 251 |
+
this.reconnectAttempts = 0; // Reseta contador de tentativas
|
| 252 |
+
|
| 253 |
+
// Limpa timeout de força
|
| 254 |
+
if (this.qrTimeout) {
|
| 255 |
+
clearTimeout(this.qrTimeout);
|
| 256 |
+
this.qrTimeout = null;
|
| 257 |
+
}
|
| 258 |
|
| 259 |
this.logger.info('\n' + '═'.repeat(70));
|
| 260 |
this.logger.info('✅ AKIRA BOT V21 ONLINE!');
|
|
|
|
| 264 |
|
| 265 |
} else if (connection === 'close') {
|
| 266 |
this.isConnected = false;
|
| 267 |
+
const code = (lastDisconnect && lastDisconnect.error && lastDisconnect.error.output && lastDisconnect.error.output.statusCode) || undefined;
|
| 268 |
+
const reason = (lastDisconnect && lastDisconnect.error && lastDisconnect.error.message) || 'desconhecido';
|
| 269 |
+
|
| 270 |
+
this.logger.warn(`⚠️ Conexão perdida (código: ${code}, motivo: ${reason})`);
|
| 271 |
+
|
| 272 |
+
// Códigos de erro específicos
|
| 273 |
+
if (code === 408) {
|
| 274 |
+
this.logger.warn('⏰ Timeout de conexão - possível problema de rede');
|
| 275 |
+
} else if (code === 401) {
|
| 276 |
+
this.logger.warn('🔐 Credenciais rejeitadas - será necessário novo login');
|
| 277 |
+
// Limpa credenciais em caso de auth error
|
| 278 |
+
this._cleanAuthOnError();
|
| 279 |
+
} else if (code === 403) {
|
| 280 |
+
this.logger.warn('🚫 Conta banida ou bloqueada');
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
// Reconecta com backoff exponencial
|
| 284 |
+
const delay = Math.min(5000 * Math.pow(2, this.reconnectAttempts || 0), 30000);
|
| 285 |
+
this.reconnectAttempts = (this.reconnectAttempts || 0) + 1;
|
| 286 |
+
|
| 287 |
+
this.logger.info(`🔄 Reconectando em ${delay/1000}s... (tentativa ${this.reconnectAttempts})`);
|
| 288 |
+
setTimeout(() => this.connect().catch(e => this.logger.error('Erro na reconexão:', e)), delay);
|
| 289 |
+
|
| 290 |
+
} else if (connection === 'connecting') {
|
| 291 |
+
this.logger.info('🔄 Conectando ao WhatsApp...');
|
| 292 |
}
|
| 293 |
+
|
| 294 |
} catch (error) {
|
| 295 |
this.logger.error('❌ Erro em handleConnectionUpdate:', error.message);
|
| 296 |
}
|
|
|
|
| 462 |
deveResponder = true;
|
| 463 |
} else {
|
| 464 |
// Em grupos, responde se for reply ao bot ou menção
|
| 465 |
+
if (replyInfo && replyInfo.ehRespostaAoBot) {
|
| 466 |
deveResponder = true;
|
| 467 |
} else if (this.messageProcessor.isBotMentioned(m)) {
|
| 468 |
deveResponder = true;
|
|
|
|
| 470 |
}
|
| 471 |
} else {
|
| 472 |
// Texto
|
| 473 |
+
if (replyInfo && replyInfo.ehRespostaAoBot) {
|
| 474 |
deveResponder = true;
|
| 475 |
} else if (!ehGrupo) {
|
| 476 |
// Em PV sempre responde
|
|
|
|
| 497 |
mensagem: texto,
|
| 498 |
tipo_conversa: ehGrupo ? 'grupo' : 'pv',
|
| 499 |
tipo_mensagem: foiAudio ? 'audio' : 'texto',
|
| 500 |
+
mensagem_citada: (replyInfo && replyInfo.textoMensagemCitada) || '',
|
| 501 |
reply_metadata: replyInfo ? {
|
| 502 |
reply_to_bot: replyInfo.ehRespostaAoBot,
|
| 503 |
quoted_author_name: replyInfo.quemEscreveuCitacao || 'desconhecido'
|
|
|
|
| 538 |
|
| 539 |
await this.simulateTyping(m.key.remoteJid, tempoDigitacao);
|
| 540 |
|
| 541 |
+
const opcoes = ehGrupo || (replyInfo && replyInfo.ehRespostaAoBot) ? { quoted: m } : {};
|
| 542 |
await this.sock.sendMessage(m.key.remoteJid, { text: resposta }, opcoes);
|
| 543 |
}
|
| 544 |
|
|
|
|
| 608 |
}
|
| 609 |
}
|
| 610 |
|
| 611 |
+
/**
|
| 612 |
+
* Limpa credenciais em caso de erro de autenticação
|
| 613 |
+
*/
|
| 614 |
+
_cleanAuthOnError() {
|
| 615 |
+
const fs = require('fs');
|
| 616 |
+
try {
|
| 617 |
+
if (fs.existsSync(this.config.AUTH_FOLDER)) {
|
| 618 |
+
fs.rmSync(this.config.AUTH_FOLDER, { recursive: true, force: true });
|
| 619 |
+
this.logger.info('🧹 Credenciais limpas devido a erro de autenticação');
|
| 620 |
+
}
|
| 621 |
+
this.isConnected = false;
|
| 622 |
+
this.currentQR = null;
|
| 623 |
+
this.BOT_JID = null;
|
| 624 |
+
} catch (error) {
|
| 625 |
+
this.logger.error('❌ Erro ao limpar credenciais:', error.message);
|
| 626 |
+
}
|
| 627 |
+
}
|
| 628 |
+
|
| 629 |
+
/**
|
| 630 |
+
* Força geração de QR code se não vier automaticamente
|
| 631 |
+
*/
|
| 632 |
+
async _forceQRGeneration() {
|
| 633 |
+
try {
|
| 634 |
+
this.logger.info('🔄 Forçando geração de QR code...');
|
| 635 |
+
|
| 636 |
+
if (this.sock) {
|
| 637 |
+
this.sock.ev.removeAllListeners();
|
| 638 |
+
if (this.sock.ws) {
|
| 639 |
+
this.sock.ws.close();
|
| 640 |
+
}
|
| 641 |
+
}
|
| 642 |
+
|
| 643 |
+
// Pequeno delay antes de reconectar
|
| 644 |
+
await delay(2000);
|
| 645 |
+
|
| 646 |
+
// Reconecta
|
| 647 |
+
await this.connect();
|
| 648 |
+
|
| 649 |
+
} catch (error) {
|
| 650 |
+
this.logger.error('❌ Erro ao forçar QR:', error.message);
|
| 651 |
+
}
|
| 652 |
+
}
|
| 653 |
+
|
| 654 |
/**
|
| 655 |
* Obtém QR Code atual
|
| 656 |
*/
|