File size: 9,086 Bytes
7226ab4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 |
/**
* ═══════════════════════════════════════════════════════════════════════
* PRESENCE SIMULATOR - AKIRA BOT V21
* ═══════════════════════════════════════════════════════════════════════
* ✅ Simulações realistas de presença e status de mensagem
* ✅ Digitação, gravação de áudio, ticks, leitura
* ✅ Totalmente compatível com Baileys
* ═══════════════════════════════════════════════════════════════════════
*/
const { delay } = require('@whiskeysockets/baileys');
class PresenceSimulator {
constructor(sock) {
this.sock = sock;
this.logger = console;
}
/**
* Simula digitação realista
* - Inicia presença como "disponível"
* - Muda para "digitando"
* - Aguarda tempo proporcional ao tamanho da resposta
* - Volta para "pausado"
* - Retorna para "disponível"
*/
async simulateTyping(jid, durationMs = 3000) {
try {
// Step 1: Garantir que está online
await this.sock.sendPresenceUpdate('available', jid);
await delay(300);
// Step 2: Começar a digitar
await this.sock.sendPresenceUpdate('composing', jid);
this.logger.log(`⌨️ [DIGITANDO] Simulando digitação por ${(durationMs / 1000).toFixed(1)}s...`);
// Step 3: Aguardar conforme tamanho da mensagem
await delay(durationMs);
// Step 4: Parar de digitar (transição)
await this.sock.sendPresenceUpdate('paused', jid);
await delay(300);
// Step 5: Voltar ao normal
await this.sock.sendPresenceUpdate('available', jid);
this.logger.log('✅ [PRONTO] Digitação simulada concluída');
return true;
} catch (error) {
this.logger.error('❌ Erro ao simular digitação:', error.message);
return false;
}
}
/**
* Simula gravação de áudio realista
* - Muda para "gravando"
* - Aguarda duração
* - Volta para "pausado"
*/
async simulateRecording(jid, durationMs = 2000) {
try {
this.logger.log(`🎤 [GRAVANDO] Preparando áudio por ${(durationMs / 1000).toFixed(1)}s...`);
// Step 1: Começar a "gravar"
await this.sock.sendPresenceUpdate('recording', jid);
// Step 2: Aguardar processamento
await delay(durationMs);
// Step 3: Concluir gravação
await this.sock.sendPresenceUpdate('paused', jid);
this.logger.log('✅ [PRONTO] Áudio preparado para envio');
return true;
} catch (error) {
this.logger.error('❌ Erro ao simular gravação:', error.message);
return false;
}
}
/**
* Simula envio de "ticks" (confirmações de entrega/leitura)
*
* Em grupos:
* - Sem ativação: Um tick (entregue)
* - Com ativação: Dois ticks azuis (lido)
*
* Em PV:
* - Sem ativação: Um tick (entregue)
* - Com ativação: Dois ticks azuis (lido)
*/
async simulateTicks(m, wasActivated = true, isAudio = false) {
try {
const isGroup = String(m.key.remoteJid || '').endsWith('@g.us');
const jid = m.key.remoteJid;
const participant = m.key.participant;
const messageId = m.key.id;
if (isGroup) {
// ═══ GRUPO ═══
if (!wasActivated) {
// Não foi ativada: Apenas um tick (entregue)
try {
await this.sock.sendReadReceipt(jid, participant, [messageId]);
this.logger.log('✓ [ENTREGUE] Grupo - Um tick (mensagem entregue)');
return true;
} catch (err1) {
try {
await this.sock.sendReceipt(jid, participant, [messageId]);
this.logger.log('✓ [ENTREGUE] Grupo - Método alternativo');
return true;
} catch (err2) {
this.logger.warn('⚠️ Não conseguiu enviar tick em grupo');
return false;
}
}
} else {
// Foi ativada: Dois ticks azuis (lido)
try {
await this.sock.readMessages([m.key]);
this.logger.log('✓✓ [LIDO] Grupo - Dois ticks azuis (mensagem lida)');
return true;
} catch (err) {
this.logger.warn('⚠️ Não conseguiu marcar como lido em grupo');
return false;
}
}
} else {
// ═══ PV (PRIVADO) ═══
if (wasActivated || isAudio) {
// Marcar como lido (dois ticks azuis)
try {
await this.sock.readMessages([m.key]);
if (isAudio) {
this.logger.log('▶️ [REPRODUZIDO] PV - Áudio marcado como reproduzido (✓✓)');
} else {
this.logger.log('✓✓ [LIDO] PV - Marcado como lido (dois ticks azuis)');
}
return true;
} catch (err) {
this.logger.warn('⚠️ Não conseguiu marcar como lido em PV');
return false;
}
} else {
// Não foi ativada: Um tick (entregue)
try {
await this.sock.sendReadReceipt(m.key.remoteJid, m.key.participant, [messageId]);
this.logger.log('✓ [ENTREGUE] PV - Um tick (mensagem entregue)');
return true;
} catch (err) {
this.logger.warn('⚠️ Não conseguiu enviar tick em PV');
return false;
}
}
}
} catch (error) {
this.logger.error('❌ Erro ao simular ticks:', error.message);
return false;
}
}
/**
* Simula leitura de mensagem
* Marca mensagem como lida (dois ticks azuis)
*/
async markAsRead(m) {
try {
await this.sock.readMessages([m.key]);
this.logger.log('✓✓ [LIDO] Mensagem marcada como lida');
return true;
} catch (error) {
this.logger.warn('⚠️ Não conseguiu marcar como lido:', error.message);
return false;
}
}
/**
* Simula status completo de mensagem
* Combina: Entrega → Leitura com delays realistas
*/
async simulateMessageStatus(m, wasActivated = true) {
try {
const isGroup = String(m.key.remoteJid || '').endsWith('@g.us');
// Em grupos, sempre enviar entrega primeiro
if (isGroup) {
try {
await this.sock.sendReadReceipt(m.key.remoteJid, m.key.participant, [m.key.id]);
this.logger.log('✓ [ENTREGUE] Grupo');
await delay(300);
} catch (e) {
// Ignorar erro
}
}
// Se foi ativada, marcar como lido
if (wasActivated) {
await delay(500);
await this.markAsRead(m);
}
return true;
} catch (error) {
this.logger.error('❌ Erro ao simular status completo:', error.message);
return false;
}
}
/**
* Simula comportamento completo ao responder
* 1. Marca entrega
* 2. Simula digitação
* 3. Envia mensagem
* 4. Marca leitura
*/
async simulateFullResponse(sock, m, responseText, isAudio = false) {
try {
const jid = m.key.remoteJid;
const isGroup = String(jid || '').endsWith('@g.us');
// Step 1: Marcar como entregue (em grupos)
if (isGroup) {
await this.simulateTicks(m, false, false);
await delay(300);
}
// Step 2: Simular digitação ou gravação
if (isAudio) {
const estimatedDuration = Math.min(
Math.max((responseText.length / 10) * 100, 2000),
5000
);
await this.simulateRecording(jid, estimatedDuration);
} else {
const estimatedDuration = Math.min(
Math.max(responseText.length * 50, 2000),
10000
);
await this.simulateTyping(jid, estimatedDuration);
}
// Step 3: Mensagem será enviada pelo caller
// (Aqui apenas retornamos sucesso)
// Step 4: Marcar como lido
await delay(500);
await this.simulateTicks(m, true, isAudio);
return true;
} catch (error) {
this.logger.error('❌ Erro ao simular resposta completa:', error.message);
return false;
}
}
/**
* Calcula duração realista de digitação baseado no tamanho da resposta
* Fórmula: 30-50ms por caractere, mínimo 1s, máximo 15s
*/
calculateTypingDuration(text, minMs = 1000, maxMs = 15000) {
const estimatedMs = Math.max(text.length * 40, minMs);
return Math.min(estimatedMs, maxMs);
}
/**
* Calcula duração realista de gravação de áudio
* Fórmula: 100ms por 10 caracteres, mínimo 2s, máximo 10s
*/
calculateRecordingDuration(text, minMs = 2000, maxMs = 10000) {
const estimatedMs = Math.max((text.length / 10) * 100, minMs);
return Math.min(estimatedMs, maxMs);
}
}
module.exports = PresenceSimulator;
|