Akiragpu / botcore /modules /MessageProcessor.ts
Isaac Quarenta
feat(botcore): PV simples espelha o index (buttonId, midia, filtros) + sync api/config
42306bf
Raw History Blame Contribute Delete
8.13 kB
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;
}
}