Spaces:
Build error
Build error
Update index.js
Browse files
index.js
CHANGED
|
@@ -1,208 +1,207 @@
|
|
| 1 |
-
//
|
|
|
|
|
|
|
|
|
|
| 2 |
const {
|
| 3 |
default: makeWASocket,
|
| 4 |
useMultiFileAuthState,
|
| 5 |
fetchLatestBaileysVersion,
|
| 6 |
Browsers,
|
| 7 |
-
delay
|
| 8 |
-
DisconnectReason
|
| 9 |
} = require('@whiskeysockets/baileys');
|
| 10 |
-
|
| 11 |
const pino = require('pino');
|
| 12 |
const axios = require('axios');
|
| 13 |
const express = require('express');
|
| 14 |
-
const qrcode = require('qrcode');
|
| 15 |
|
|
|
|
|
|
|
| 16 |
const PORT = process.env.PORT || 3000;
|
| 17 |
-
const AKIRA_API_URL = process.env.AKIRA_API_URL || 'https://akra35567-akira.hf.space/api/akira';
|
| 18 |
-
const BOT_REAL_JID = process.env.BOT_REAL_JID || '37839265886398@lid';
|
| 19 |
|
| 20 |
let sock;
|
| 21 |
-
let
|
| 22 |
let lastProcessedTime = 0;
|
| 23 |
-
let healthInterval;
|
| 24 |
-
let currentQR = null;
|
| 25 |
-
|
| 26 |
-
// --- Express Server para página QR ---
|
| 27 |
-
const app = express();
|
| 28 |
-
const server = app.listen(PORT, '0.0.0.0', () => {
|
| 29 |
-
console.log(`Servidor ativo na porta ${server.address().port}`);
|
| 30 |
-
});
|
| 31 |
-
|
| 32 |
-
app.get('/', (req, res) => {
|
| 33 |
-
res.send(`AKIRA BOT ONLINE | ${new Date().toLocaleString()} | <a href="/qr">Ver QR Code</a>`);
|
| 34 |
-
});
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
</body>
|
| 50 |
-
</html>
|
| 51 |
-
`);
|
| 52 |
-
});
|
| 53 |
-
} else {
|
| 54 |
-
res.send('<h1>Bot já conectado!</h1><p>Atualize para ver QR.</p>');
|
| 55 |
-
}
|
| 56 |
-
});
|
| 57 |
|
| 58 |
-
|
| 59 |
-
function normalizeJid(jid) {
|
| 60 |
if (!jid) return null;
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
}
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
healthInterval = setInterval(() => {
|
| 68 |
-
console.log(`[HEALTH] ${new Date().toLocaleString()} - Bot ativo`);
|
| 69 |
-
if (sock?.sendPresenceUpdate) {
|
| 70 |
-
sock.sendPresenceUpdate('available').catch(() => {});
|
| 71 |
-
}
|
| 72 |
-
}, 20000); // ping a cada 20s
|
| 73 |
}
|
| 74 |
|
| 75 |
-
//
|
|
|
|
|
|
|
| 76 |
async function connect() {
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
});
|
| 181 |
-
|
| 182 |
-
} catch (err) {
|
| 183 |
-
isConnecting = false;
|
| 184 |
-
console.error('Erro crítico:', err.message);
|
| 185 |
-
setTimeout(connect, 20000);
|
| 186 |
-
}
|
| 187 |
}
|
| 188 |
|
| 189 |
-
//
|
| 190 |
-
|
|
|
|
|
|
|
| 191 |
const context = msg.message?.extendedTextMessage?.contextInfo;
|
| 192 |
-
const
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
}
|
| 198 |
|
|
|
|
| 199 |
if (isGroup) {
|
| 200 |
const mentions = context?.mentionedJid || [];
|
| 201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
}
|
| 203 |
|
|
|
|
|
|
|
| 204 |
return false;
|
| 205 |
}
|
| 206 |
|
| 207 |
-
//
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
connect();
|
|
|
|
| 1 |
+
// ===============================================================
|
| 2 |
+
// AKIRA BOT — JID/LID unify + Session fix + Reply PV/Group logic
|
| 3 |
+
// ===============================================================
|
| 4 |
+
|
| 5 |
const {
|
| 6 |
default: makeWASocket,
|
| 7 |
useMultiFileAuthState,
|
| 8 |
fetchLatestBaileysVersion,
|
| 9 |
Browsers,
|
| 10 |
+
delay
|
|
|
|
| 11 |
} = require('@whiskeysockets/baileys');
|
|
|
|
| 12 |
const pino = require('pino');
|
| 13 |
const axios = require('axios');
|
| 14 |
const express = require('express');
|
| 15 |
+
const qrcode = require('qrcode-terminal');
|
| 16 |
|
| 17 |
+
const logger = pino({ level: 'info' });
|
| 18 |
+
const AKIRA_API_URL = 'https://akra35567-akira.hf.space/api/akira';
|
| 19 |
const PORT = process.env.PORT || 3000;
|
|
|
|
|
|
|
| 20 |
|
| 21 |
let sock;
|
| 22 |
+
let BOT_JID = null;
|
| 23 |
let lastProcessedTime = 0;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
// ===============================================================
|
| 26 |
+
// 🔧 UTILITÁRIOS
|
| 27 |
+
// ===============================================================
|
| 28 |
+
|
| 29 |
+
function extractNumber(input = '') {
|
| 30 |
+
if (!input) return 'desconhecido';
|
| 31 |
+
const clean = input.toString();
|
| 32 |
+
const match = clean.match(/2449\d{8}/);
|
| 33 |
+
if (match) return match[0];
|
| 34 |
+
const local = clean.match(/9\d{8}/);
|
| 35 |
+
if (local) return `244${local[0]}`;
|
| 36 |
+
return clean.replace(/\D/g, '').slice(-12);
|
| 37 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
function normalizeJid(jid = '') {
|
|
|
|
| 40 |
if (!jid) return null;
|
| 41 |
+
jid = jid.toString().trim();
|
| 42 |
+
|
| 43 |
+
// remove lixo e sufixos
|
| 44 |
+
jid = jid.replace(/[:@].*/g, '');
|
| 45 |
+
if (jid.startsWith('37') || jid.startsWith('202') || jid.length < 9)
|
| 46 |
+
return BOT_JID || '244952786417@s.whatsapp.net';
|
| 47 |
+
if (!jid.startsWith('244') && /^9\d{8}$/.test(jid))
|
| 48 |
+
jid = '244' + jid;
|
| 49 |
+
return `${jid}@s.whatsapp.net`;
|
| 50 |
}
|
| 51 |
|
| 52 |
+
function isBotJid(jid) {
|
| 53 |
+
const norm = normalizeJid(jid);
|
| 54 |
+
return norm === normalizeJid(BOT_JID);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
}
|
| 56 |
|
| 57 |
+
// ===============================================================
|
| 58 |
+
// ⚙️ CONEXÃO
|
| 59 |
+
// ===============================================================
|
| 60 |
async function connect() {
|
| 61 |
+
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
|
| 62 |
+
const { version } = await fetchLatestBaileysVersion();
|
| 63 |
+
|
| 64 |
+
sock = makeWASocket({
|
| 65 |
+
version,
|
| 66 |
+
auth: state,
|
| 67 |
+
logger,
|
| 68 |
+
browser: Browsers.macOS('Desktop'),
|
| 69 |
+
markOnlineOnConnect: true,
|
| 70 |
+
syncFullHistory: false,
|
| 71 |
+
connectTimeoutMs: 60000
|
| 72 |
+
});
|
| 73 |
+
|
| 74 |
+
sock.ev.on('creds.update', saveCreds);
|
| 75 |
+
|
| 76 |
+
sock.ev.on('connection.update', async (update) => {
|
| 77 |
+
const { connection, qr } = update;
|
| 78 |
+
|
| 79 |
+
if (qr) {
|
| 80 |
+
qrcode.generate(qr, { small: true });
|
| 81 |
+
console.log('\n📱 ESCANEIE O QR PARA CONECTAR\n');
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
if (connection === 'open') {
|
| 85 |
+
BOT_JID = normalizeJid(sock.user.id);
|
| 86 |
+
console.log('✅ AKIRA BOT ONLINE!');
|
| 87 |
+
console.log('botJid detectado:', BOT_JID);
|
| 88 |
+
lastProcessedTime = Date.now();
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
if (connection === 'close') {
|
| 92 |
+
console.log('⚠️ Conexão perdida. Tentando reconectar...');
|
| 93 |
+
setTimeout(connect, 5000);
|
| 94 |
+
}
|
| 95 |
+
});
|
| 96 |
+
|
| 97 |
+
// ===============================================================
|
| 98 |
+
// 💬 MENSAGENS
|
| 99 |
+
// ===============================================================
|
| 100 |
+
sock.ev.on('messages.upsert', async (m) => {
|
| 101 |
+
const msg = m.messages[0];
|
| 102 |
+
if (!msg.message || msg.key.fromMe) return;
|
| 103 |
+
|
| 104 |
+
const from = msg.key.remoteJid;
|
| 105 |
+
const isGroup = from.endsWith('@g.us');
|
| 106 |
+
if (msg.messageTimestamp && msg.messageTimestamp * 1000 < lastProcessedTime - 10000) return;
|
| 107 |
+
|
| 108 |
+
// Extração inteligente do número real
|
| 109 |
+
let sender = msg.key.participant || msg.participant || msg.key.remoteJid;
|
| 110 |
+
const pn = msg.message?.participantPn || msg.message?.senderPn;
|
| 111 |
+
const lid = msg.key.senderLid || msg.participantLid || msg.message?.senderLid;
|
| 112 |
+
const possible = pn || lid || sender;
|
| 113 |
+
const senderNumber = extractNumber(possible);
|
| 114 |
+
const nome = msg.pushName || senderNumber;
|
| 115 |
+
|
| 116 |
+
const text =
|
| 117 |
+
msg.message.conversation ||
|
| 118 |
+
msg.message.extendedTextMessage?.text ||
|
| 119 |
+
msg.message?.imageMessage?.caption ||
|
| 120 |
+
msg.message?.videoMessage?.caption ||
|
| 121 |
+
'';
|
| 122 |
+
|
| 123 |
+
if (!text.trim()) return;
|
| 124 |
+
console.log(`\n[MENSAGEM] ${isGroup ? 'GRUPO' : 'PV'} | ${nome} (${senderNumber}): ${text}`);
|
| 125 |
+
|
| 126 |
+
const ativar = await shouldActivate(msg, isGroup, text);
|
| 127 |
+
if (!ativar) {
|
| 128 |
+
console.log('[IGNORADO] Não ativado para responder (não reply ou não menção).');
|
| 129 |
+
return;
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
await sock.sendPresenceUpdate('composing', from);
|
| 133 |
+
|
| 134 |
+
try {
|
| 135 |
+
const res = await axios.post(AKIRA_API_URL, {
|
| 136 |
+
usuario: nome,
|
| 137 |
+
mensagem: text,
|
| 138 |
+
numero: senderNumber
|
| 139 |
+
});
|
| 140 |
+
|
| 141 |
+
const resposta = res.data.resposta || '...';
|
| 142 |
+
console.log(`[RESPOSTA] ${resposta}`);
|
| 143 |
+
|
| 144 |
+
await delay(Math.min(resposta.length * 50, 4000));
|
| 145 |
+
await sock.sendPresenceUpdate('paused', from);
|
| 146 |
+
await sock.sendMessage(from, { text: resposta }, { quoted: msg });
|
| 147 |
+
} catch (err) {
|
| 148 |
+
console.error('⚠️ Erro na API:', err.message);
|
| 149 |
+
await sock.sendMessage(from, { text: 'Erro interno. 😴' }, { quoted: msg });
|
| 150 |
+
}
|
| 151 |
+
});
|
| 152 |
+
|
| 153 |
+
// ===============================================================
|
| 154 |
+
// 🧰 REGENERAÇÃO DE SESSÃO
|
| 155 |
+
// ===============================================================
|
| 156 |
+
sock.ev.on('message-decrypt-failed', async (msgKey) => {
|
| 157 |
+
console.log('⚠️ Tentando regenerar sessão perdida...');
|
| 158 |
+
try {
|
| 159 |
+
await sock.sendRetryRequest(msgKey.key);
|
| 160 |
+
} catch (e) {
|
| 161 |
+
console.log('❌ Falha ao regenerar sessão:', e.message);
|
| 162 |
+
}
|
| 163 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
}
|
| 165 |
|
| 166 |
+
// ===============================================================
|
| 167 |
+
// 🎯 ATIVAÇÃO (reply / menção / PV)
|
| 168 |
+
// ===============================================================
|
| 169 |
+
async function shouldActivate(msg, isGroup, text) {
|
| 170 |
const context = msg.message?.extendedTextMessage?.contextInfo;
|
| 171 |
+
const lowered = text.toLowerCase();
|
| 172 |
+
|
| 173 |
+
// Reply ao bot
|
| 174 |
+
if (context?.participant) {
|
| 175 |
+
const quoted = normalizeJid(context.participant);
|
| 176 |
+
if (isBotJid(quoted)) {
|
| 177 |
+
console.log(`[ATIVAÇÃO] Reply ao bot detectado (${BOT_JID})`);
|
| 178 |
+
return true;
|
| 179 |
+
}
|
| 180 |
}
|
| 181 |
|
| 182 |
+
// Menção direta no grupo
|
| 183 |
if (isGroup) {
|
| 184 |
const mentions = context?.mentionedJid || [];
|
| 185 |
+
const mentionMatch = mentions.some(
|
| 186 |
+
j => isBotJid(j) || j.includes(BOT_JID.split('@')[0])
|
| 187 |
+
);
|
| 188 |
+
if (lowered.includes('akira') || mentionMatch) {
|
| 189 |
+
console.log('[ATIVAÇÃO] Menção direta a Akira detectada.');
|
| 190 |
+
return true;
|
| 191 |
+
}
|
| 192 |
}
|
| 193 |
|
| 194 |
+
// PV → sempre responde
|
| 195 |
+
if (!isGroup) return true;
|
| 196 |
return false;
|
| 197 |
}
|
| 198 |
|
| 199 |
+
// ===============================================================
|
| 200 |
+
// 🌐 HEALTH CHECK
|
| 201 |
+
// ===============================================================
|
| 202 |
+
const app = express();
|
| 203 |
+
const server = app.listen(PORT, '0.0.0.0', () => {
|
| 204 |
+
console.log(`Health check na porta ${server.address().port}`);
|
| 205 |
+
});
|
| 206 |
+
app.get('/', (req, res) => res.send('AKIRA BOT ONLINE ✅'));
|
| 207 |
connect();
|