This commit is contained in:
Saulo Mendes Martins 2025-08-21 22:19:16 -03:00 committed by GitHub
commit e60048ede1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 111 additions and 30 deletions

View File

@ -19,10 +19,15 @@ export class BaileysMessageProcessor {
}>(); }>();
mount({ onMessageReceive }: MountProps) { mount({ onMessageReceive }: MountProps) {
this.processorLogs.log(`🧪 [TESTE] mount chamado - BaileysMessageProcessor inicializado`);
this.subscription = this.messageSubject this.subscription = this.messageSubject
.pipe( .pipe(
tap(({ messages }) => { tap(({ messages }) => {
this.processorLogs.log(`Processing batch of ${messages.length} messages`); this.processorLogs.log(`🚀 [BaileysMessageProcessor] Processing batch of ${messages.length} messages`);
this.processorLogs.log(`🧪 [TESTE] LOG DE TESTE FUNCIONANDO - ${new Date().toISOString()}`);
messages.forEach((msg, index) => {
this.processorLogs.log(`📱 [BaileysMessageProcessor] Message ${index + 1}: ${msg.key?.remoteJid} - ${msg.message?.conversation || msg.message?.extendedTextMessage?.text || 'NO_TEXT'}`);
});
}), }),
concatMap(({ messages, type, requestId, settings }) => concatMap(({ messages, type, requestId, settings }) =>
from(onMessageReceive({ messages, type, requestId }, settings)).pipe( from(onMessageReceive({ messages, type, requestId }, settings)).pipe(
@ -49,6 +54,7 @@ export class BaileysMessageProcessor {
processMessage(payload: MessageUpsertPayload, settings: any) { processMessage(payload: MessageUpsertPayload, settings: any) {
const { messages, type, requestId } = payload; const { messages, type, requestId } = payload;
this.processorLogs.log(`🧪 [TESTE] processMessage chamado - messages: ${messages.length}, type: ${type}`);
this.messageSubject.next({ messages, type, requestId, settings }); this.messageSubject.next({ messages, type, requestId, settings });
} }

View File

@ -1047,7 +1047,10 @@ export class BaileysStartupService extends ChannelStartupService {
settings: any, settings: any,
) => { ) => {
try { try {
this.logger.log(`🚀 [Baileys] MESSAGES.UPSERT STARTED - type: ${type}, messages: ${messages.length}`);
for (const received of messages) { for (const received of messages) {
this.logger.log(`📱 [Baileys] Processing message: ${received.key.id} from ${received.key.remoteJid} - text: "${received.message?.conversation || received.message?.extendedTextMessage?.text || 'NO_TEXT'}"`);
if (received.key.remoteJid?.includes('@lid') && received.key.senderPn) { if (received.key.remoteJid?.includes('@lid') && received.key.senderPn) {
(received.key as { previousRemoteJid?: string | null }).previousRemoteJid = received.key.remoteJid; (received.key as { previousRemoteJid?: string | null }).previousRemoteJid = received.key.remoteJid;
received.key.remoteJid = received.key.senderPn; received.key.remoteJid = received.key.senderPn;
@ -1336,12 +1339,19 @@ export class BaileysStartupService extends ChannelStartupService {
this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw);
await chatbotController.emit({ this.logger.log(`🤖 [Baileys] Calling chatbotController.emit for remoteJid: ${messageRaw.key.remoteJid}`);
instance: { instanceName: this.instance.name, instanceId: this.instanceId },
remoteJid: messageRaw.key.remoteJid, try {
msg: messageRaw, await chatbotController.emit({
pushName: messageRaw.pushName, instance: { instanceName: this.instance.name, instanceId: this.instanceId },
}); remoteJid: messageRaw.key.remoteJid,
msg: messageRaw,
pushName: messageRaw.pushName,
});
this.logger.log(`✅ [Baileys] chatbotController.emit completed successfully`);
} catch (error) {
this.logger.error(`❌ [Baileys] Error in chatbotController.emit: ${error.message}`);
}
const contact = await this.prismaRepository.contact.findFirst({ const contact = await this.prismaRepository.contact.findFirst({
where: { remoteJid: received.key.remoteJid, instanceId: this.instanceId }, where: { remoteJid: received.key.remoteJid, instanceId: this.instanceId },

View File

@ -775,29 +775,46 @@ export abstract class BaseChatbotController<BotType = any, BotData extends BaseC
// Base implementation for emit // Base implementation for emit
public async emit({ instance, remoteJid, msg }: EmitData) { public async emit({ instance, remoteJid, msg }: EmitData) {
if (!this.integrationEnabled) return; this.logger.log(`🚀 [${this.integrationName}] EMIT STARTED - remoteJid: ${remoteJid}, instance: ${instance.instanceName}`);
if (!this.integrationEnabled) {
this.logger.warn(`❌ [${this.integrationName}] Integration is DISABLED`);
return;
}
try { try {
this.logger.log(`🔍 [${this.integrationName}] Looking for settings...`);
const settings = await this.settingsRepository.findFirst({ const settings = await this.settingsRepository.findFirst({
where: { where: {
instanceId: instance.instanceId, instanceId: instance.instanceId,
}, },
}); });
this.logger.log(`⚙️ [${this.integrationName}] Settings found: ${settings ? 'YES' : 'NO'}`);
if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) return; if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) {
this.logger.warn(`🚫 [${this.integrationName}] Message ignored due to ignoreJids`);
return;
}
this.logger.log(`🔍 [${this.integrationName}] Looking for session...`);
const session = await this.getSession(remoteJid, instance); const session = await this.getSession(remoteJid, instance);
this.logger.log(`📱 [${this.integrationName}] Session found: ${session ? 'YES' : 'NO'}`);
const content = getConversationMessage(msg); const content = getConversationMessage(msg);
this.logger.log(`💬 [${this.integrationName}] Content: ${content}`);
// Get integration type // Get integration type
// const integrationType = this.getIntegrationType(); // const integrationType = this.getIntegrationType();
// Find a bot for this message // Find a bot for this message
this.logger.log(`🤖 [${this.integrationName}] Looking for bot trigger...`);
let findBot: any = await this.findBotTrigger(this.botRepository, content, instance, session); let findBot: any = await this.findBotTrigger(this.botRepository, content, instance, session);
this.logger.log(`🤖 [${this.integrationName}] Bot found: ${findBot ? 'YES' : 'NO'} - ID: ${findBot?.id || 'NONE'}`);
// If no bot is found, try to use fallback // If no bot is found, try to use fallback
if (!findBot) { if (!findBot) {
this.logger.warn(`⚠️ [${this.integrationName}] No bot found, trying fallback...`);
const fallback = await this.settingsRepository.findFirst({ const fallback = await this.settingsRepository.findFirst({
where: { where: {
instanceId: instance.instanceId, instanceId: instance.instanceId,
@ -806,6 +823,7 @@ export abstract class BaseChatbotController<BotType = any, BotData extends BaseC
// Get the fallback ID for this integration type // Get the fallback ID for this integration type
const fallbackId = this.getFallbackBotId(fallback); const fallbackId = this.getFallbackBotId(fallback);
this.logger.log(`🔄 [${this.integrationName}] Fallback ID: ${fallbackId || 'NONE'}`);
if (fallbackId) { if (fallbackId) {
const findFallback = await this.botRepository.findFirst({ const findFallback = await this.botRepository.findFirst({
@ -815,13 +833,16 @@ export abstract class BaseChatbotController<BotType = any, BotData extends BaseC
}); });
findBot = findFallback; findBot = findFallback;
this.logger.log(`🔄 [${this.integrationName}] Fallback bot found: ${findFallback ? 'YES' : 'NO'}`);
} else { } else {
this.logger.warn(`❌ [${this.integrationName}] No fallback bot available`);
return; return;
} }
} }
// If we still don't have a bot, return // If we still don't have a bot, return
if (!findBot) { if (!findBot) {
this.logger.warn(`❌ [${this.integrationName}] Still no bot found, returning`);
return; return;
} }
@ -904,29 +925,42 @@ export abstract class BaseChatbotController<BotType = any, BotData extends BaseC
// Process with debounce if needed // Process with debounce if needed
if (debounceTime && debounceTime > 0) { if (debounceTime && debounceTime > 0) {
this.logger.log(`⏱️ [${this.integrationName}] Processing with debounce (${debounceTime}s)...`);
this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => {
this.logger.log(`🚀 [${this.integrationName}] Debounce complete! Calling processBot...`);
try {
await this.processBot(
this.waMonitor.waInstances[instance.instanceName],
remoteJid,
findBot,
session,
mergedSettings,
debouncedContent,
msg?.pushName,
msg,
);
this.logger.log(`✅ [${this.integrationName}] processBot completed successfully`);
} catch (error) {
this.logger.error(`❌ [${this.integrationName}] Error in processBot: ${error.message}`);
}
});
} else {
this.logger.log(`🚀 [${this.integrationName}] Processing without debounce...`);
try {
await this.processBot( await this.processBot(
this.waMonitor.waInstances[instance.instanceName], this.waMonitor.waInstances[instance.instanceName],
remoteJid, remoteJid,
findBot, findBot,
session, session,
mergedSettings, mergedSettings,
debouncedContent, content,
msg?.pushName, msg?.pushName,
msg, msg,
); );
}); this.logger.log(`✅ [${this.integrationName}] processBot completed successfully`);
} else { } catch (error) {
await this.processBot( this.logger.error(`❌ [${this.integrationName}] Error in processBot: ${error.message}`);
this.waMonitor.waInstances[instance.instanceName], }
remoteJid,
findBot,
session,
mergedSettings,
content,
msg?.pushName,
msg,
);
} }
} catch (error) { } catch (error) {
this.logger.error(error); this.logger.error(error);

View File

@ -84,6 +84,8 @@ export class ChatbotController {
pushName?: string; pushName?: string;
isIntegration?: boolean; isIntegration?: boolean;
}): Promise<void> { }): Promise<void> {
this.logger.log(`🚀 [ChatbotController] EMIT STARTED - remoteJid: ${remoteJid}, instance: ${instance.instanceName}`);
const emitData = { const emitData = {
instance, instance,
remoteJid, remoteJid,
@ -91,19 +93,40 @@ export class ChatbotController {
pushName, pushName,
isIntegration, isIntegration,
}; };
await evolutionBotController.emit(emitData);
try {
this.logger.log(`🤖 [ChatbotController] Calling evolutionBotController.emit...`);
await evolutionBotController.emit(emitData);
this.logger.log(`✅ [ChatbotController] evolutionBotController.emit completed`);
await typebotController.emit(emitData); this.logger.log(`🤖 [ChatbotController] Calling typebotController.emit...`);
await typebotController.emit(emitData);
this.logger.log(`✅ [ChatbotController] typebotController.emit completed`);
await openaiController.emit(emitData); this.logger.log(`🤖 [ChatbotController] Calling openaiController.emit...`);
await openaiController.emit(emitData);
this.logger.log(`✅ [ChatbotController] openaiController.emit completed`);
await difyController.emit(emitData); this.logger.log(`🤖 [ChatbotController] Calling difyController.emit...`);
await difyController.emit(emitData);
this.logger.log(`✅ [ChatbotController] difyController.emit completed`);
await n8nController.emit(emitData); this.logger.log(`🤖 [ChatbotController] Calling n8nController.emit...`);
await n8nController.emit(emitData);
this.logger.log(`✅ [ChatbotController] n8nController.emit completed`);
await evoaiController.emit(emitData); this.logger.log(`🤖 [ChatbotController] Calling evoaiController.emit...`);
await evoaiController.emit(emitData);
this.logger.log(`✅ [ChatbotController] evoaiController.emit completed`);
await flowiseController.emit(emitData); this.logger.log(`🤖 [ChatbotController] Calling flowiseController.emit...`);
await flowiseController.emit(emitData);
this.logger.log(`✅ [ChatbotController] flowiseController.emit completed`);
this.logger.log(`🎉 [ChatbotController] All controllers completed successfully`);
} catch (error) {
this.logger.error(`❌ [ChatbotController] Error in emit: ${error.message}`);
}
} }
public processDebounce( public processDebounce(

View File

@ -52,7 +52,10 @@ export class OpenaiService extends BaseChatbotService<OpenaiBot, OpenaiSetting>
msg?: any, msg?: any,
): Promise<void> { ): Promise<void> {
try { try {
this.logger.log(`Starting process for remoteJid: ${remoteJid}, bot type: ${openaiBot.botType}`); this.logger.log(`🚀 [OpenaiService] PROCESS STARTED - remoteJid: ${remoteJid}, bot type: ${openaiBot.botType}`);
this.logger.log(`🤖 [OpenaiService] Bot ID: ${openaiBot.id}, enabled: ${openaiBot.enabled}`);
this.logger.log(`💬 [OpenaiService] Content: "${content}"`);
this.logger.log(`📱 [OpenaiService] Session: ${session ? 'EXISTS' : 'NEW'}`);
// Handle audio message transcription // Handle audio message transcription
if (content.startsWith('audioMessage|') && msg) { if (content.startsWith('audioMessage|') && msg) {

View File

@ -1,6 +1,8 @@
import { advancedOperatorsSearch } from './advancedOperatorsSearch'; import { advancedOperatorsSearch } from './advancedOperatorsSearch';
export const findBotByTrigger = async (botRepository: any, content: string, instanceId: string) => { export const findBotByTrigger = async (botRepository: any, content: string, instanceId: string) => {
console.log(`🔍 [findBotByTrigger] Searching for bot - content: "${content}", instanceId: ${instanceId}`);
// Check for triggerType 'all' or 'none' (both should match any message) // Check for triggerType 'all' or 'none' (both should match any message)
const findTriggerAllOrNone = await botRepository.findFirst({ const findTriggerAllOrNone = await botRepository.findFirst({
where: { where: {
@ -12,7 +14,10 @@ export const findBotByTrigger = async (botRepository: any, content: string, inst
}, },
}); });
console.log(`🤖 [findBotByTrigger] All/None trigger found: ${findTriggerAllOrNone ? 'YES' : 'NO'} - ID: ${findTriggerAllOrNone?.id || 'NONE'}`);
if (findTriggerAllOrNone) { if (findTriggerAllOrNone) {
console.log(`✅ [findBotByTrigger] Returning bot with triggerType: ${findTriggerAllOrNone.triggerType}`);
return findTriggerAllOrNone; return findTriggerAllOrNone;
} }