refactor: simplify TypebotController and TypebotService methods

This commit refactors the TypebotController and TypebotService to streamline the processTypebot method, aligning it with the base class pattern. It reduces complexity by consolidating parameters and improving readability. Additionally, it updates the TypebotDto and TypebotSettingDto to remove unused properties, enhancing code clarity and maintainability.
This commit is contained in:
Guilherme Gomes 2025-05-27 13:07:15 -03:00
parent dd0dfd447c
commit 22e99f7934
4 changed files with 32 additions and 97 deletions

View File

@ -90,34 +90,20 @@ export class TypebotController extends BaseChatbotController<TypebotModel, Typeb
pushName?: string,
msg?: any,
) {
await this.typebotService.processTypebot(
instance,
remoteJid,
msg,
session,
bot,
bot.url,
settings.expire,
bot.typebot,
settings.keywordFinish,
settings.delayMessage,
settings.unknownMessage,
settings.listeningFromMe,
settings.stopBotFromMe,
settings.keepOpen,
content,
);
// Use the simplified service method that follows the base class pattern
await this.typebotService.processTypebot(instance, remoteJid, bot, session, settings, content, pushName, msg);
}
// TypeBot specific method for starting a bot from API
public async startBot(instance: InstanceDto, data: any) {
if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled');
if (!this.integrationEnabled)
throw new BadRequestException('Typebot is disabled');
if (data.remoteJid === 'status@broadcast') return;
const instanceData = await this.prismaRepository.instance.findFirst({
where: {
name: instance.instanceName,
id: instance.instanceId,
},
});
@ -226,22 +212,25 @@ export class TypebotController extends BaseChatbotController<TypebotModel, Typeb
},
});
await this.typebotService.processTypebot(
instanceData,
remoteJid,
null,
null,
findBot,
url,
// Use the simplified service method instead of the complex one
const settings = {
expire,
typebot,
keywordFinish,
delayMessage,
unknownMessage,
listeningFromMe,
stopBotFromMe,
keepOpen,
};
await this.typebotService.processTypebot(
instanceData,
remoteJid,
findBot,
null, // session
settings,
'init',
null, // pushName
prefilledVariables,
);
} else {
@ -287,7 +276,7 @@ export class TypebotController extends BaseChatbotController<TypebotModel, Typeb
request.data.clientSideActions,
);
this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_START, {
this.waMonitor.waInstances[instance.instanceId].sendDataWebhook(Events.TYPEBOT_START, {
remoteJid: remoteJid,
url: url,
typebot: typebot,

View File

@ -1,5 +1,3 @@
import { TriggerOperator, TriggerType } from '@prisma/client';
import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto';
export class PrefilledVariables {
@ -12,30 +10,8 @@ export class PrefilledVariables {
export class TypebotDto extends BaseChatbotDto {
url: string;
typebot: string;
description: string;
expire?: number;
keywordFinish?: string | null;
delayMessage?: number;
unknownMessage?: string;
listeningFromMe?: boolean;
stopBotFromMe?: boolean;
keepOpen?: boolean;
debounceTime?: number;
triggerType: TriggerType;
triggerOperator?: TriggerOperator;
triggerValue?: string;
ignoreJids?: any;
}
export class TypebotSettingDto extends BaseChatbotSettingDto {
expire?: number;
keywordFinish?: string | null;
delayMessage?: number;
unknownMessage?: string;
listeningFromMe?: boolean;
stopBotFromMe?: boolean;
keepOpen?: boolean;
debounceTime?: number;
typebotIdFallback?: string;
ignoreJids?: any;
}

View File

@ -1,9 +1,7 @@
import { RouterBroker } from '@api/abstract/abstract.router';
import { IgnoreJidDto } from '@api/dto/chatbot.dto';
import { InstanceDto } from '@api/dto/instance.dto';
import { TypebotDto, TypebotSettingDto } from '@api/integrations/chatbot/typebot/dto/typebot.dto';
import { HttpStatus } from '@api/routes/index.router';
import { typebotController } from '@api/server.module';
import {
instanceSchema,
typebotIgnoreJidSchema,
@ -12,8 +10,11 @@ import {
typebotStartSchema,
typebotStatusSchema,
} from '@validate/validate.schema';
import { typebotController } from '@api/server.module';
import { RequestHandler, Router } from 'express';
import { RouterBroker } from '@api/abstract/abstract.router';
export class TypebotRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) {
super();

View File

@ -1,8 +1,7 @@
import { PrismaRepository } from '@api/repository/repository.service';
import { WAMonitoringService } from '@api/services/monitor.service';
import { Auth, ConfigService, HttpServer, Typebot } from '@config/env.config';
import { Instance, IntegrationSession, Message, Typebot as TypebotModel } from '@prisma/client';
import { sendTelemetry } from '@utils/sendTelemetry';
import { IntegrationSession, Typebot as TypebotModel } from '@prisma/client';
import axios from 'axios';
import { BaseChatbotService } from '../../base-chatbot.service';
@ -83,15 +82,12 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
if (this.isAudioMessage(content) && msg) {
try {
this.logger.debug(`[EvolutionBot] Downloading audio for Whisper transcription`);
const transcription = await this.openaiService.speechToText(msg);
const transcription = await this.openaiService.speechToText(msg, instance);
if (transcription) {
reqData.message = transcription;
} else {
reqData.message = '[Audio message could not be transcribed]';
reqData.message = `[audio] ${transcription}`;
}
} catch (err) {
this.logger.error(`[EvolutionBot] Failed to transcribe audio: ${err}`);
reqData.message = '[Audio message could not be transcribed]';
}
}
@ -107,9 +103,6 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
response?.data?.input,
response?.data?.clientSideActions,
);
// Send telemetry data
sendTelemetry('/message/sendText');
} catch (error) {
this.logger.error(`Error in sendMessageToBot for Typebot: ${error.message || JSON.stringify(error)}`);
}
@ -526,44 +519,20 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
return { text, buttons: [] };
}
}
/**
* Main process method for handling Typebot messages
* This is called directly from the controller
* Simplified method that matches the base class pattern
* This should be the preferred way for the controller to call
*/
public async processTypebot(
instance: Instance,
instance: any,
remoteJid: string,
msg: Message,
session: IntegrationSession,
bot: TypebotModel,
url: string,
expire: number,
typebot: string,
keywordFinish: string,
delayMessage: number,
unknownMessage: string,
listeningFromMe: boolean,
stopBotFromMe: boolean,
keepOpen: boolean,
session: IntegrationSession,
settings: any,
content: string,
prefilledVariables?: any,
) {
try {
const settings = {
expire,
keywordFinish,
delayMessage,
unknownMessage,
listeningFromMe,
stopBotFromMe,
keepOpen,
};
// Use the base class process method to handle the message
await this.process(instance, remoteJid, bot, session, settings, content, msg.pushName, prefilledVariables || msg);
} catch (error) {
this.logger.error(`Error in processTypebot: ${error}`);
}
pushName?: string,
msg?: any,
): Promise<void> {
return this.process(instance, remoteJid, bot, session, settings, content, pushName, msg);
}
}