fix: variables in typebot

This commit is contained in:
Davidson Gomes 2023-12-14 08:35:45 -03:00
parent 87027ea2d0
commit a44646161b
9 changed files with 143 additions and 88 deletions

View File

@ -3,6 +3,8 @@
### Fixed ### Fixed
* Fixed Lid Messages * Fixed Lid Messages
* Fixed sending variables to typebot
* Fixed sending variables from typebot
# 1.6.0 (2023-12-12 17:24) # 1.6.0 (2023-12-12 17:24)

View File

@ -1,6 +1,6 @@
FROM node:20.7.0-alpine FROM node:20.7.0-alpine
LABEL version="1.6.0" description="Api to control whatsapp features through http requests." LABEL version="1.6.1" description="Api to control whatsapp features through http requests."
LABEL maintainer="Davidson Gomes" git="https://github.com/DavidsonGomes" LABEL maintainer="Davidson Gomes" git="https://github.com/DavidsonGomes"
LABEL contact="contato@agenciadgcode.com" LABEL contact="contato@agenciadgcode.com"

View File

@ -1,6 +1,6 @@
{ {
"name": "evolution-api", "name": "evolution-api",
"version": "1.6.0", "version": "1.6.1",
"description": "Rest api for communication with WhatsApp", "description": "Rest api for communication with WhatsApp",
"main": "./dist/src/main.js", "main": "./dist/src/main.js",
"scripts": { "scripts": {
@ -56,7 +56,7 @@
"cross-env": "^7.0.3", "cross-env": "^7.0.3",
"dayjs": "^1.11.7", "dayjs": "^1.11.7",
"eventemitter2": "^6.4.9", "eventemitter2": "^6.4.9",
"evolution-manager": "^0.4.5", "evolution-manager": "^0.4.6",
"exiftool-vendored": "^22.0.0", "exiftool-vendored": "^22.0.0",
"express": "^4.18.2", "express": "^4.18.2",
"express-async-errors": "^3.1.1", "express-async-errors": "^3.1.1",

View File

@ -169,8 +169,8 @@ export class ConfigService {
this.env = !(process.env?.DOCKER_ENV === 'true') ? this.envYaml() : this.envProcess(); this.env = !(process.env?.DOCKER_ENV === 'true') ? this.envYaml() : this.envProcess();
this.env.PRODUCTION = process.env?.NODE_ENV === 'PROD'; this.env.PRODUCTION = process.env?.NODE_ENV === 'PROD';
if (process.env?.DOCKER_ENV === 'true') { if (process.env?.DOCKER_ENV === 'true') {
this.env.SERVER.TYPE = 'http'; this.env.SERVER.TYPE = process.env.SERVER_TYPE as 'http' | 'http';
this.env.SERVER.PORT = 8080; this.env.SERVER.PORT = Number.parseInt(process.env.SERVER_PORT) || 8080;
} }
} }

View File

@ -25,7 +25,7 @@ info:
</font> </font>
[![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/26869335-5546d063-156b-4529-915f-909dd628c090?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D26869335-5546d063-156b-4529-915f-909dd628c090%26entityType%3Dcollection%26workspaceId%3D339a4ee7-378b-45c9-b5b8-fd2c0a9c2442) [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/26869335-5546d063-156b-4529-915f-909dd628c090?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D26869335-5546d063-156b-4529-915f-909dd628c090%26entityType%3Dcollection%26workspaceId%3D339a4ee7-378b-45c9-b5b8-fd2c0a9c2442)
version: 1.5.5 version: 1.6.1
contact: contact:
name: DavidsonGomes name: DavidsonGomes
email: contato@agenciadgcode.com email: contato@agenciadgcode.com

View File

@ -41,7 +41,8 @@ router
status: HttpStatus.OK, status: HttpStatus.OK,
message: 'Welcome to the Evolution API, it is working!', message: 'Welcome to the Evolution API, it is working!',
version: packageJson.version, version: packageJson.version,
documentation: `${req.protocol}://${req.get('host')}/docs`, swagger: `${req.protocol}://${req.get('host')}/docs`,
documentation: `https://doc.evolution-api.com`,
manager: `${req.protocol}://${req.get('host')}/manager`, manager: `${req.protocol}://${req.get('host')}/manager`,
}); });
}) })

View File

@ -1,4 +1,5 @@
import axios from 'axios'; import axios from 'axios';
import EventEmitter2 from 'eventemitter2';
import { ConfigService, Typebot } from '../../config/env.config'; import { ConfigService, Typebot } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
@ -9,7 +10,15 @@ import { Events } from '../types/wa.types';
import { WAMonitoringService } from './monitor.service'; import { WAMonitoringService } from './monitor.service';
export class TypebotService { export class TypebotService {
constructor(private readonly waMonitor: WAMonitoringService, private readonly configService: ConfigService) {} constructor(
private readonly waMonitor: WAMonitoringService,
private readonly configService: ConfigService,
private readonly eventEmitter: EventEmitter2,
) {
this.eventEmitter.on('typebot:end', async (data) => {
await this.clearSessions(data.instance, data.remoteJid);
});
}
private readonly logger = new Logger(TypebotService.name); private readonly logger = new Logger(TypebotService.name);
@ -110,6 +119,37 @@ export class TypebotService {
return { typebot: { ...instance, typebot: typebotData } }; return { typebot: { ...instance, typebot: typebotData } };
} }
public async clearSessions(instance: InstanceDto, remoteJid: string) {
const findTypebot = await this.find(instance);
const sessions = (findTypebot.sessions as Session[]) ?? [];
const sessionWithRemoteJid = sessions.filter((session) => session.remoteJid === remoteJid);
if (sessionWithRemoteJid.length > 0) {
sessionWithRemoteJid.forEach((session) => {
sessions.splice(sessions.indexOf(session), 1);
});
const typebotData = {
enabled: findTypebot.enabled,
url: findTypebot.url,
typebot: findTypebot.typebot,
expire: findTypebot.expire,
keyword_finish: findTypebot.keyword_finish,
delay_message: findTypebot.delay_message,
unknown_message: findTypebot.unknown_message,
listening_from_me: findTypebot.listening_from_me,
sessions,
};
this.create(instance, typebotData);
return sessions;
}
return sessions;
}
public async startTypebot(instance: InstanceDto, data: any) { public async startTypebot(instance: InstanceDto, data: any) {
if (data.remoteJid === 'status@broadcast') return; if (data.remoteJid === 'status@broadcast') return;
@ -169,20 +209,25 @@ export class TypebotService {
} else { } else {
const id = Math.floor(Math.random() * 10000000000).toString(); const id = Math.floor(Math.random() * 10000000000).toString();
const reqData = {
startParams: {
publicId: data.typebot,
prefilledVariables: prefilledVariables,
},
};
try { try {
const version = this.configService.get<Typebot>('TYPEBOT').API_VERSION; const version = this.configService.get<Typebot>('TYPEBOT').API_VERSION;
let url: string; let url: string;
let reqData: {};
if (version === 'latest') { if (version === 'latest') {
url = `${data.url}/api/v1/typebots/${data.typebot}/startChat`; url = `${data.url}/api/v1/typebots/${data.typebot}/startChat`;
reqData = {
prefilledVariables: prefilledVariables,
};
} else { } else {
url = `${data.url}/api/v1/sendMessage`; url = `${data.url}/api/v1/sendMessage`;
reqData = {
startParams: {
publicId: data.typebot,
prefilledVariables: prefilledVariables,
},
};
} }
const request = await axios.post(url, reqData); const request = await axios.post(url, reqData);
@ -260,25 +305,35 @@ export class TypebotService {
if (data.remoteJid === 'status@broadcast') return; if (data.remoteJid === 'status@broadcast') return;
const id = Math.floor(Math.random() * 10000000000).toString(); const id = Math.floor(Math.random() * 10000000000).toString();
const reqData = {
startParams: {
publicId: data.typebot,
prefilledVariables: {
...data.prefilledVariables,
remoteJid: data.remoteJid,
pushName: data.pushName || data.prefilledVariables?.pushName || '',
instanceName: instance.instanceName,
},
},
};
try { try {
const version = this.configService.get<Typebot>('TYPEBOT').API_VERSION; const version = this.configService.get<Typebot>('TYPEBOT').API_VERSION;
let url: string; let url: string;
let reqData: {};
if (version === 'latest') { if (version === 'latest') {
url = `${data.url}/api/v1/typebots/${data.typebot}/startChat`; url = `${data.url}/api/v1/typebots/${data.typebot}/startChat`;
reqData = {
prefilledVariables: {
...data.prefilledVariables,
remoteJid: data.remoteJid,
pushName: data.pushName || data.prefilledVariables?.pushName || '',
instanceName: instance.instanceName,
},
};
} else { } else {
url = `${data.url}/api/v1/sendMessage`; url = `${data.url}/api/v1/sendMessage`;
reqData = {
startParams: {
publicId: data.typebot,
prefilledVariables: {
...data.prefilledVariables,
remoteJid: data.remoteJid,
pushName: data.pushName || data.prefilledVariables?.pushName || '',
instanceName: instance.instanceName,
},
},
};
} }
const request = await axios.post(url, reqData); const request = await axios.post(url, reqData);
@ -318,37 +373,6 @@ export class TypebotService {
} }
} }
public async clearSessions(instance: InstanceDto, remoteJid: string) {
const findTypebot = await this.find(instance);
const sessions = (findTypebot.sessions as Session[]) ?? [];
const sessionWithRemoteJid = sessions.filter((session) => session.remoteJid === remoteJid);
if (sessionWithRemoteJid.length > 0) {
sessionWithRemoteJid.forEach((session) => {
sessions.splice(sessions.indexOf(session), 1);
});
const typebotData = {
enabled: findTypebot.enabled,
url: findTypebot.url,
typebot: findTypebot.typebot,
expire: findTypebot.expire,
keyword_finish: findTypebot.keyword_finish,
delay_message: findTypebot.delay_message,
unknown_message: findTypebot.unknown_message,
listening_from_me: findTypebot.listening_from_me,
sessions,
};
this.create(instance, typebotData);
return sessions;
}
return sessions;
}
public async sendWAMessage( public async sendWAMessage(
instance: InstanceDto, instance: InstanceDto,
remoteJid: string, remoteJid: string,
@ -356,11 +380,15 @@ export class TypebotService {
input: any[], input: any[],
clientSideActions: any[], clientSideActions: any[],
) { ) {
processMessages(this.waMonitor.waInstances[instance.instanceName], messages, input, clientSideActions).catch( processMessages(
(err) => { this.waMonitor.waInstances[instance.instanceName],
console.error('Erro ao processar mensagens:', err); messages,
}, input,
); clientSideActions,
this.eventEmitter,
).catch((err) => {
console.error('Erro ao processar mensagens:', err);
});
function findItemAndGetSecondsToWait(array, targetId) { function findItemAndGetSecondsToWait(array, targetId) {
if (!array) return null; if (!array) return null;
@ -373,7 +401,7 @@ export class TypebotService {
return null; return null;
} }
async function processMessages(instance, messages, input, clientSideActions) { async function processMessages(instance, messages, input, clientSideActions, eventEmitter) {
for (const message of messages) { for (const message of messages) {
const wait = findItemAndGetSecondsToWait(clientSideActions, message.id); const wait = findItemAndGetSecondsToWait(clientSideActions, message.id);
@ -383,31 +411,50 @@ export class TypebotService {
let linkPreview = false; let linkPreview = false;
for (const richText of message.content.richText) { for (const richText of message.content.richText) {
for (const element of richText.children) { if (richText.type === 'variable') {
let text = ''; for (const child of richText.children) {
if (element.text) { for (const grandChild of child.children) {
text = element.text; formattedText += grandChild.text;
}
} }
} else {
for (const element of richText.children) {
let text = '';
if (element.bold) { if (element.type === 'inline-variable') {
text = `*${text}*`; for (const child of element.children) {
for (const grandChild of child.children) {
text += grandChild.text;
}
}
} else if (element.text) {
text = element.text;
}
// if (element.text) {
// text = element.text;
// }
if (element.bold) {
text = `*${text}*`;
}
if (element.italic) {
text = `_${text}_`;
}
if (element.underline) {
text = `*${text}*`;
}
if (element.url) {
const linkText = element.children[0].text;
text = `[${linkText}](${element.url})`;
linkPreview = true;
}
formattedText += text;
} }
if (element.italic) {
text = `_${text}_`;
}
if (element.underline) {
text = `*${text}*`;
}
if (element.url) {
const linkText = element.children[0].text;
text = `[${linkText}](${element.url})`;
linkPreview = true;
}
formattedText += text;
} }
formattedText += '\n'; formattedText += '\n';
} }
@ -494,6 +541,11 @@ export class TypebotService {
}, },
}); });
} }
} else {
eventEmitter.emit('typebot:end', {
instance: instance,
remoteJid: remoteJid,
});
} }
} }
} }

View File

@ -168,7 +168,7 @@ export class WAStartupService {
private chatwootService = new ChatwootService(waMonitor, this.configService, this.repository); private chatwootService = new ChatwootService(waMonitor, this.configService, this.repository);
private typebotService = new TypebotService(waMonitor, this.configService); private typebotService = new TypebotService(waMonitor, this.configService, this.eventEmitter);
private chamaaiService = new ChamaaiService(waMonitor, this.configService); private chamaaiService = new ChamaaiService(waMonitor, this.configService);

View File

@ -101,7 +101,7 @@ export const waMonitor = new WAMonitoringService(eventEmitter, configService, re
const authService = new AuthService(configService, waMonitor, repository); const authService = new AuthService(configService, waMonitor, repository);
const typebotService = new TypebotService(waMonitor, configService); const typebotService = new TypebotService(waMonitor, configService, eventEmitter);
export const typebotController = new TypebotController(typebotService); export const typebotController = new TypebotController(typebotService);