Skip to content

Commit 97ca23a

Browse files
committed
refactor: enhance Evoai integration with improved validation and message handling
This commit refines the Evoai integration by updating the service and controller logic for better functionality and maintainability. Key changes include: - Added the `openaiService` as a parameter in the EvoaiService constructor for improved dependency management. - Enhanced the createBot method in EvoaiController to include EvoAI-specific validation and duplicate checks. - Updated EvoaiDto and EvoaiSettingDto to remove unnecessary comments and add a fallback property. - Refined the message processing logic in EvoaiService to handle audio messages more effectively and improve logging clarity. - Adjusted the schema for Evoai settings to rename `evoaiIdFallback` to `botIdFallback` for better clarity. These updates contribute to a more robust and maintainable Evoai integration.
1 parent 95bd85b commit 97ca23a

File tree

5 files changed

+44
-112
lines changed

5 files changed

+44
-112
lines changed

src/api/integrations/chatbot/evoai/controllers/evoai.controller.ts

Lines changed: 3 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ export class EvoaiController extends BaseChatbotController<EvoaiModel, EvoaiDto>
7777
}
7878
}
7979

80-
// Bots
80+
// Override createBot to add EvoAI-specific validation
8181
public async createBot(instance: InstanceDto, data: EvoaiDto) {
8282
if (!this.integrationEnabled) throw new BadRequestException('Evoai is disabled');
8383

@@ -89,6 +89,7 @@ export class EvoaiController extends BaseChatbotController<EvoaiModel, EvoaiDto>
8989
})
9090
.then((instance) => instance.id);
9191

92+
// EvoAI-specific duplicate check
9293
const checkDuplicate = await this.botRepository.findFirst({
9394
where: {
9495
instanceId: instanceId,
@@ -101,61 +102,10 @@ export class EvoaiController extends BaseChatbotController<EvoaiModel, EvoaiDto>
101102
throw new Error('Evoai already exists');
102103
}
103104

105+
// Let the base class handle the rest
104106
return super.createBot(instance, data);
105107
}
106108

107-
public async findBot(instance: InstanceDto) {
108-
if (!this.integrationEnabled) throw new BadRequestException('Evoai is disabled');
109-
110-
const instanceId = await this.prismaRepository.instance
111-
.findFirst({
112-
where: {
113-
name: instance.instanceName,
114-
},
115-
})
116-
.then((instance) => instance.id);
117-
118-
const bots = await this.botRepository.findMany({
119-
where: {
120-
instanceId: instanceId,
121-
},
122-
});
123-
124-
if (!bots.length) {
125-
return null;
126-
}
127-
128-
return bots;
129-
}
130-
131-
public async fetchBot(instance: InstanceDto, botId: string) {
132-
if (!this.integrationEnabled) throw new BadRequestException('Evoai is disabled');
133-
134-
const instanceId = await this.prismaRepository.instance
135-
.findFirst({
136-
where: {
137-
name: instance.instanceName,
138-
},
139-
})
140-
.then((instance) => instance.id);
141-
142-
const bot = await this.botRepository.findFirst({
143-
where: {
144-
id: botId,
145-
},
146-
});
147-
148-
if (!bot) {
149-
throw new Error('Evoai not found');
150-
}
151-
152-
if (bot.instanceId !== instanceId) {
153-
throw new Error('Evoai not found');
154-
}
155-
156-
return bot;
157-
}
158-
159109
// Process Evoai-specific bot logic
160110
protected async processBot(
161111
instance: any,
Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto';
22

33
export class EvoaiDto extends BaseChatbotDto {
4-
// Evoai specific fields
54
agentUrl?: string;
65
apiKey?: string;
76
}
87

98
export class EvoaiSettingDto extends BaseChatbotSettingDto {
10-
// Evoai specific fields
9+
evoaiIdFallback?: string;
1110
}

src/api/integrations/chatbot/evoai/services/evoai.service.ts

Lines changed: 38 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,26 @@
1-
import { InstanceDto } from '@api/dto/instance.dto';
21
import { PrismaRepository } from '@api/repository/repository.service';
32
import { WAMonitoringService } from '@api/services/monitor.service';
43
import { Integration } from '@api/types/wa.types';
5-
import { ConfigService } from '@config/env.config';
4+
import { ConfigService, HttpServer } from '@config/env.config';
65
import { Evoai, EvoaiSetting, IntegrationSession } from '@prisma/client';
76
import axios from 'axios';
87
import { downloadMediaMessage } from 'baileys';
98
import { v4 as uuidv4 } from 'uuid';
109

1110
import { BaseChatbotService } from '../../base-chatbot.service';
1211
import { OpenaiService } from '../../openai/services/openai.service';
12+
1313
export class EvoaiService extends BaseChatbotService<Evoai, EvoaiSetting> {
1414
private openaiService: OpenaiService;
1515

16-
constructor(waMonitor: WAMonitoringService, prismaRepository: PrismaRepository, configService: ConfigService) {
16+
constructor(
17+
waMonitor: WAMonitoringService,
18+
prismaRepository: PrismaRepository,
19+
configService: ConfigService,
20+
openaiService: OpenaiService,
21+
) {
1722
super(waMonitor, prismaRepository, 'EvoaiService', configService);
18-
this.openaiService = new OpenaiService(waMonitor, prismaRepository, configService);
23+
this.openaiService = openaiService;
1924
}
2025

2126
/**
@@ -25,74 +30,53 @@ export class EvoaiService extends BaseChatbotService<Evoai, EvoaiSetting> {
2530
return 'evoai';
2631
}
2732

28-
public async createNewSession(instance: InstanceDto, data: any) {
29-
return super.createNewSession(instance, data, 'evoai');
30-
}
31-
3233
/**
33-
* Override the process method to directly handle audio messages
34+
* Implement the abstract method to send message to EvoAI API
35+
* Handles audio transcription, image processing, and complex JSON-RPC payload
3436
*/
35-
public async process(
37+
protected async sendMessageToBot(
3638
instance: any,
37-
remoteJid: string,
38-
bot: Evoai,
3939
session: IntegrationSession,
4040
settings: EvoaiSetting,
41+
evoai: Evoai,
42+
remoteJid: string,
43+
pushName: string,
4144
content: string,
42-
pushName?: string,
4345
msg?: any,
4446
): Promise<void> {
4547
try {
46-
this.logger.debug(`[EvoAI] Processing message with custom process method`);
48+
this.logger.debug(`[EvoAI] Sending message to bot with content: ${content}`);
4749

48-
let contentProcessed = content;
50+
let processedContent = content;
4951

50-
// Check if this is an audio message that we should try to transcribe
52+
// Handle audio messages - transcribe using OpenAI Whisper
5153
if (this.isAudioMessage(content) && msg) {
5254
try {
5355
this.logger.debug(`[EvoAI] Downloading audio for Whisper transcription`);
54-
const transcription = await this.openaiService.speechToText(msg);
56+
const transcription = await this.openaiService.speechToText(msg, instance);
5557
if (transcription) {
56-
contentProcessed = transcription;
57-
} else {
58-
contentProcessed = '[Audio message could not be transcribed]';
58+
processedContent = transcription;
5959
}
6060
} catch (err) {
6161
this.logger.error(`[EvoAI] Failed to transcribe audio: ${err}`);
62-
contentProcessed = '[Audio message could not be transcribed]';
6362
}
6463
}
6564

66-
// For non-audio messages or if transcription failed, proceed normally
67-
return super.process(instance, remoteJid, bot, session, settings, contentProcessed, pushName, msg);
68-
} catch (error) {
69-
this.logger.error(`[EvoAI] Error in process: ${error}`);
70-
return;
71-
}
72-
}
65+
const endpoint: string = evoai.agentUrl;
7366

74-
protected async sendMessageToBot(
75-
instance: any,
76-
session: IntegrationSession,
77-
settings: EvoaiSetting,
78-
evoai: Evoai,
79-
remoteJid: string,
80-
pushName: string,
81-
content: string,
82-
msg?: any,
83-
) {
84-
try {
85-
this.logger.debug(`[EvoAI] Sending message to bot with content: ${content}`);
67+
if (!endpoint) {
68+
this.logger.error('No EvoAI endpoint defined');
69+
return;
70+
}
8671

87-
const endpoint: string = evoai.agentUrl;
8872
const callId = `req-${uuidv4().substring(0, 8)}`;
89-
const messageId = uuidv4();
73+
const messageId = msg?.key?.id || uuidv4();
9074

9175
// Prepare message parts
9276
const parts = [
9377
{
9478
type: 'text',
95-
text: content,
79+
text: processedContent,
9680
},
9781
];
9882

@@ -130,6 +114,17 @@ export class EvoaiService extends BaseChatbotService<Evoai, EvoaiSetting> {
130114
role: 'user',
131115
parts,
132116
messageId: messageId,
117+
metadata: {
118+
messageKey: msg?.key,
119+
},
120+
},
121+
metadata: {
122+
remoteJid: remoteJid,
123+
pushName: pushName,
124+
fromMe: msg?.key?.fromMe,
125+
instanceName: instance.instanceName,
126+
serverUrl: this.configService.get<HttpServer>('SERVER').URL,
127+
apiKey: instance.token,
133128
},
134129
},
135130
};
@@ -177,22 +172,10 @@ export class EvoaiService extends BaseChatbotService<Evoai, EvoaiSetting> {
177172
}
178173

179174
this.logger.debug(`[EvoAI] Extracted message to send: ${message}`);
180-
const conversationId = session.sessionId;
181175

182176
if (message) {
183177
await this.sendMessageWhatsApp(instance, remoteJid, message, settings);
184178
}
185-
186-
await this.prismaRepository.integrationSession.update({
187-
where: {
188-
id: session.id,
189-
},
190-
data: {
191-
status: 'opened',
192-
awaitUser: true,
193-
sessionId: conversationId,
194-
},
195-
});
196179
} catch (error) {
197180
this.logger.error(
198181
`[EvoAI] Error sending message: ${error?.response?.data ? JSON.stringify(error.response.data) : error}`,

src/api/integrations/chatbot/evoai/validate/evoai.schema.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ export const evoaiSettingSchema: JSONSchema7 = {
7171
keepOpen: { type: 'boolean' },
7272
debounceTime: { type: 'integer' },
7373
ignoreJids: { type: 'array', items: { type: 'string' } },
74-
evoaiIdFallback: { type: 'string' },
74+
botIdFallback: { type: 'string' },
7575
splitMessages: { type: 'boolean' },
7676
timePerChar: { type: 'integer' },
7777
},

src/api/server.module.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ export const flowiseController = new FlowiseController(flowiseService, prismaRep
135135
const n8nService = new N8nService(waMonitor, prismaRepository, configService, openaiService);
136136
export const n8nController = new N8nController(n8nService, prismaRepository, waMonitor);
137137

138-
const evoaiService = new EvoaiService(waMonitor, prismaRepository, configService);
138+
const evoaiService = new EvoaiService(waMonitor, prismaRepository, configService, openaiService);
139139
export const evoaiController = new EvoaiController(evoaiService, prismaRepository, waMonitor);
140140

141141
logger.info('Module - ON');

0 commit comments

Comments
 (0)