File size: 8,129 Bytes
6727a3d 42306bf 6727a3d 42306bf 6727a3d 42306bf 6727a3d 42306bf 6727a3d 42306bf 6727a3d 42306bf 6727a3d 42306bf 6727a3d 42306bf 6727a3d | 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 | import ConfigManager from './ConfigManager.js';
import { CustomerIdentifier } from './CustomerIdentifier.js';
import { getContentType, normalizeMessageContent } from '@whiskeysockets/baileys';
import type { Logger } from 'pino';
export type ExtractedMessage = {
type: string | undefined;
text: string;
isGroup: boolean;
remoteJid: string;
senderNum: string;
senderCrmFormat: string;
senderName: string;
isReplyToBot: boolean;
messageId: string | undefined;
fromMe: boolean;
mentionedJid: string[];
};
/**
* Fluxo PV simples (estilo negra_plena, sem menus) — espelha o index:
* - PV: responde a tudo (menos fromMe/stubs/vazio/só-emoji/convite/sistema).
* - Botão/lista clicado responde sempre (buttonId).
* - Grupo: só se for reply à Akira, menção ou "akira" no texto.
*/
export class MessageProcessor {
private config: ConfigManager;
private logger: Logger;
private customerId: CustomerIdentifier;
private botId: string = '';
constructor(logger: Logger) {
this.config = ConfigManager.getInstance();
this.logger = logger;
this.customerId = new CustomerIdentifier();
}
public setBotId(id: string) {
this.botId = this.customerId.getClientId(id);
}
/** Desembrulha ephemeral/viewOnce/device-sent (Baileys não desembrulha em messages.upsert). */
private _unwrap(content: any): any {
if (!content) return content;
try {
const normalized: any = normalizeMessageContent(content);
if (normalized) content = normalized;
} catch { /* segue com o conteúdo original */ }
return content?.deviceSentMessage?.message
|| content?.deviceSentMessage?.sentMessage
|| content;
}
public extractInfo(m: any): ExtractedMessage | null {
const message = this._unwrap(m.message);
if (!message) return null;
const type = getContentType(message);
let text = '';
if (type === 'conversation') text = message.conversation || '';
else if (type === 'extendedTextMessage') text = message.extendedTextMessage?.text || '';
else if (type === 'imageMessage') text = message.imageMessage?.caption || '[IMAGEM SEM LEGENDA]';
else if (type === 'videoMessage') text = message.videoMessage?.caption || '[VÍDEO]';
else if (type === 'audioMessage') text = '[ÁUDIO]';
else if (type === 'stickerMessage') text = '[FIGURINHA]';
else if (type === 'documentMessage') text = message.documentMessage?.caption || '[DOCUMENTO]';
else if (type === 'contactMessage') text = '[CONTATO]';
else if (type === 'locationMessage') text = '[LOCALIZAÇÃO]';
else if (type === 'reactionMessage') text = `[reação: ${message.reactionMessage?.text ?? ''}]`;
else if (type === 'pollCreationMessageV3' || type === 'pollCreationMessage') text = `[enquete: ${message[type]?.name ?? ''}]`;
else if (type === 'buttonsResponseMessage') {
text = message.buttonsResponseMessage?.selectedDisplayText || message.buttonsResponseMessage?.selectedButtonId || '';
} else if (type === 'templateButtonReplyMessage') {
text = message.templateButtonReplyMessage?.selectedDisplayText || message.templateButtonReplyMessage?.selectedId || '';
} else if (type === 'listResponseMessage') {
text = message.listResponseMessage?.title || message.listResponseMessage?.singleSelectReply?.selectedRowId || '';
} else if (type === 'interactiveResponseMessage') {
const native = message.interactiveResponseMessage?.nativeFlowResponseMessage;
if (native?.paramsJson) {
try {
const parsed = JSON.parse(native.paramsJson);
text = parsed.display_text || parsed.title || parsed.id || parsed.selectedId || '';
} catch {
text = native.name || '';
}
} else {
text = message.interactiveResponseMessage?.body?.text || '';
}
}
const remoteJid = m.key.remoteJid || '';
const isGroup = remoteJid.endsWith('@g.us');
let senderRaw = isGroup ? m.key.participant : remoteJid;
if (m.key.fromMe) senderRaw = this.botId;
const senderPn = m.key.senderPn || m.key.remoteJidAlt || senderRaw;
const senderNum = this.customerId.getClientId(senderPn);
const senderCrmFormat = this.customerId.formatForCRM(senderPn);
const contextInfo = message?.extendedTextMessage?.contextInfo;
const repliedJid = contextInfo?.participant || '';
const isReplyToBot = !!repliedJid && this.customerId.getClientId(repliedJid) === this.botId;
return {
type,
text: text || '',
isGroup,
remoteJid,
senderNum,
senderCrmFormat,
senderName: m.pushName || 'Cliente',
isReplyToBot,
messageId: m.key.id,
fromMe: m.key.fromMe || false,
mentionedJid: contextInfo?.mentionedJid || [],
};
}
/** buttonId (estilo negra/index): identifica clique em botão/lista/interativo. */
public extractButtonId(message: any): string | null {
try {
const msg = this._unwrap(message?.message);
if (!msg) return null;
const tipo = getContentType(msg);
if (tipo === 'buttonsResponseMessage') return msg.buttonsResponseMessage?.selectedButtonId || null;
if (tipo === 'templateButtonReplyMessage') return msg.templateButtonReplyMessage?.selectedId || null;
if (tipo === 'listResponseMessage') return msg.listResponseMessage?.singleSelectReply?.selectedRowId || null;
if (tipo === 'interactiveResponseMessage') {
const native = msg.interactiveResponseMessage?.nativeFlowResponseMessage;
if (native?.paramsJson) {
try {
const parsed = JSON.parse(native.paramsJson);
return parsed.id || parsed.selectedId || parsed.row_id || null;
} catch { return null; }
}
}
return null;
} catch {
return null;
}
}
public shouldRespondToAI(info: ExtractedMessage, rawMessage: any): boolean {
if (info.fromMe) return false;
if (rawMessage.messageStubType) {
this.logger.debug('STUB ignorado');
return false;
}
// Clique em botão/lista/interativo responde sempre (espelho do index)
try {
if (this.extractButtonId(rawMessage)) return true;
} catch { /* segue com o resto da decisão */ }
const msgContent = rawMessage.message;
if (msgContent?.groupInviteMessage || msgContent?.groupJidMessage) return false;
if (msgContent?.protocolMessage || msgContent?.paymentInviteMessage) return false;
const textoLimpo = (info.text || '').trim();
if (textoLimpo.length === 0) {
// Mídia sem legenda já vem com placeholder ([ÁUDIO] etc) — isto é só fallback
const temMidia = msgContent?.audioMessage || msgContent?.imageMessage
|| msgContent?.videoMessage || msgContent?.stickerMessage
|| msgContent?.documentMessage;
if (temMidia) return true;
return false;
}
if (!info.isGroup) {
const emojiOnlyRegex = /^[\p{Emoji}\p{Emoji_Modifier}\p{Emoji_Component}\p{Emoji_Modifier_Base}\p{Emoji_Presentation}\s]{1,10}$/u;
if (emojiOnlyRegex.test(textoLimpo) && textoLimpo.length <= 10) return false;
return true;
}
if (info.isReplyToBot) return true;
const isBotMentioned = info.mentionedJid.some(
(jid) => this.customerId.getClientId(jid) === this.botId
);
if (isBotMentioned) return true;
if (textoLimpo.toLowerCase().includes('akira')) return true;
return false;
}
}
|