mirror of
https://github.com/EvolutionAPI/evolution-api.git
synced 2025-07-25 18:08:40 -06:00
website-historico
This commit is contained in:
parent
1665654676
commit
1ebcde65d0
0
.env:Zone.Identifier
Normal file
0
.env:Zone.Identifier
Normal file
10
Dockerfile
10
Dockerfile
@ -1,7 +1,6 @@
|
||||
FROM node:20-alpine AS builder
|
||||
FROM node:20-slim AS builder
|
||||
|
||||
RUN apk update && \
|
||||
apk add git ffmpeg wget curl bash
|
||||
RUN apt-get update && apt-get install -y python3 make g++ libvips-dev git pkg-config dos2unix
|
||||
|
||||
LABEL version="2.2.0" description="Api to control whatsapp features through http requests."
|
||||
LABEL maintainer="Davidson Gomes" git="https://github.com/DavidsonGomes"
|
||||
@ -29,10 +28,9 @@ RUN ./Docker/scripts/generate_database.sh
|
||||
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine AS final
|
||||
FROM node:20-slim AS final
|
||||
|
||||
RUN apk update && \
|
||||
apk add tzdata ffmpeg bash
|
||||
RUN apt-get update && apt-get install -y python3 make g++ libvips-dev git pkg-config dos2unix
|
||||
|
||||
ENV TZ=America/Sao_Paulo
|
||||
|
||||
|
16
Dockerfile.dev
Normal file
16
Dockerfile.dev
Normal file
@ -0,0 +1,16 @@
|
||||
FROM node:20-slim
|
||||
|
||||
WORKDIR /evolution
|
||||
|
||||
RUN apt-get update && apt-get install -y python3 make g++ libvips-dev git pkg-config
|
||||
RUN npm install --platform=linux --arch=x64 sharp
|
||||
COPY package*.json /evolution/
|
||||
RUN npm install
|
||||
|
||||
COPY . /evolution
|
||||
|
||||
# Generate your Prisma Client
|
||||
# RUN npm run db:deploy
|
||||
# RUN npx prisma generate --schema=/evolution/prisma/postgresql-schema.prisma
|
||||
|
||||
CMD ["npm", "run", "dev:server"]
|
@ -1,25 +1,57 @@
|
||||
services:
|
||||
api:
|
||||
container_name: evolution_api
|
||||
image: evolution/api:local
|
||||
build: .
|
||||
restart: always
|
||||
ports:
|
||||
- 8080:8080
|
||||
evolution-api-dev:
|
||||
container_name: evolution-api-dev
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.dev
|
||||
depends_on:
|
||||
- evolution-redis
|
||||
- evolution-postgres
|
||||
volumes:
|
||||
- evolution_instances:/evolution/instances
|
||||
- type: bind
|
||||
source: .
|
||||
target: /evolution
|
||||
- type: volume
|
||||
target: /evolution/node_modules
|
||||
ports:
|
||||
- '8080:8080'
|
||||
environment:
|
||||
- NODE_ENV=development
|
||||
networks:
|
||||
- evolution-net
|
||||
- chatwoot-evolution-network
|
||||
env_file:
|
||||
- .env
|
||||
expose:
|
||||
- 8080
|
||||
- ./.env
|
||||
|
||||
evolution-redis:
|
||||
image: redis:latest
|
||||
container_name: evolution-redis
|
||||
command: >
|
||||
redis-server --port 6380 --appendonly yes
|
||||
volumes:
|
||||
- evolution-redis:/data
|
||||
networks:
|
||||
- chatwoot-evolution-network
|
||||
|
||||
evolution-postgres:
|
||||
container_name: evolution-postgres
|
||||
image: postgres:15
|
||||
command: [ "postgres", "-c", "max_connections=1000" ]
|
||||
restart: always
|
||||
volumes:
|
||||
- evolution-postgres:/var/lib/postgresql/data
|
||||
environment:
|
||||
- POSTGRES_USER=${POSTGRES_USER}
|
||||
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
|
||||
- POSTGRES_DB=${POSTGRES_DB}
|
||||
networks:
|
||||
- chatwoot-evolution-network
|
||||
|
||||
volumes:
|
||||
evolution_instances:
|
||||
evolution-instances:
|
||||
evolution-redis:
|
||||
evolution-postgres:
|
||||
|
||||
|
||||
networks:
|
||||
evolution-net:
|
||||
name: evolution-net
|
||||
driver: bridge
|
||||
chatwoot-evolution-network:
|
||||
external: true
|
||||
|
@ -1,57 +1,61 @@
|
||||
services:
|
||||
api:
|
||||
container_name: evolution_api
|
||||
image: atendai/evolution-api:homolog
|
||||
evolution-api:
|
||||
container_name: evolution-api
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
restart: always
|
||||
depends_on:
|
||||
- redis
|
||||
- postgres
|
||||
- evolution-redis
|
||||
- evolution-postgres
|
||||
ports:
|
||||
- 8080:8080
|
||||
volumes:
|
||||
- evolution_instances:/evolution/instances
|
||||
- evolution-instances:/evolution/instances
|
||||
networks:
|
||||
- evolution-net
|
||||
- chatwoot-evolution-network
|
||||
env_file:
|
||||
- .env
|
||||
expose:
|
||||
- 8080
|
||||
|
||||
redis:
|
||||
evolution-redis:
|
||||
image: redis:latest
|
||||
container_name: evolution-redis
|
||||
restart: always
|
||||
networks:
|
||||
- evolution-net
|
||||
container_name: redis
|
||||
- chatwoot-evolution-network
|
||||
command: >
|
||||
redis-server --port 6379 --appendonly yes
|
||||
volumes:
|
||||
- evolution_redis:/data
|
||||
- evolution-redis:/data
|
||||
ports:
|
||||
- 6379:6379
|
||||
|
||||
postgres:
|
||||
container_name: postgres
|
||||
evolution-postgres:
|
||||
container_name: evolution-postgres
|
||||
image: postgres:15
|
||||
networks:
|
||||
- evolution-net
|
||||
command: ["postgres", "-c", "max_connections=1000"]
|
||||
- chatwoot-evolution-network
|
||||
command: [ "postgres", "-c", "max_connections=1000" ]
|
||||
restart: always
|
||||
ports:
|
||||
- 5432:5432
|
||||
environment:
|
||||
- POSTGRES_PASSWORD=PASSWORD
|
||||
- POSTGRES_USER=${POSTGRES_USER}
|
||||
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
|
||||
- POSTGRES_DB=${POSTGRES_DB}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- evolution-postgres:/var/lib/postgresql/data
|
||||
expose:
|
||||
- 5432
|
||||
|
||||
volumes:
|
||||
evolution_instances:
|
||||
evolution_redis:
|
||||
postgres_data:
|
||||
evolution-instances:
|
||||
evolution-redis:
|
||||
evolution-postgres:
|
||||
|
||||
|
||||
networks:
|
||||
evolution-net:
|
||||
name: evolution-net
|
||||
driver: bridge
|
||||
chatwoot-evolution-network:
|
||||
external: true
|
||||
|
@ -17,81 +17,200 @@ import {
|
||||
import { WAMonitoringService } from '@api/services/monitor.service';
|
||||
import { BadRequestException } from '@exceptions';
|
||||
import { isBase64, isURL } from 'class-validator';
|
||||
import { Logger } from '@config/logger.config';
|
||||
|
||||
export class SendMessageController {
|
||||
constructor(private readonly waMonitor: WAMonitoringService) {}
|
||||
|
||||
private readonly logger = new Logger('SendMessageController');
|
||||
|
||||
public async sendTemplate({ instanceName }: InstanceDto, data: SendTemplateDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].templateMessage(data);
|
||||
this.logger.log(`[sendTemplate] [${instanceName}] - Iniciando envio de template...`);
|
||||
this.logger.debug(`[sendTemplate] [${instanceName}] - Dados de envio: ${JSON.stringify(data)}`);
|
||||
|
||||
const result = await this.waMonitor.waInstances[instanceName].templateMessage(data);
|
||||
|
||||
this.logger.log(`[sendTemplate] [${instanceName}] - Envio concluído com sucesso.`);
|
||||
this.logger.debug(`[sendTemplate] [${instanceName}] - Resultado: ${JSON.stringify(result)}`);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async sendText({ instanceName }: InstanceDto, data: SendTextDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].textMessage(data);
|
||||
this.logger.log(`[sendText] [${instanceName}] - Iniciando envio de texto...`);
|
||||
this.logger.debug(`[sendText] [${instanceName}] - Dados de envio: ${JSON.stringify(data)}`);
|
||||
|
||||
const result = await this.waMonitor.waInstances[instanceName].textMessage(data);
|
||||
|
||||
this.logger.log(`[sendText] [${instanceName}] - Envio concluído com sucesso.`);
|
||||
this.logger.debug(`[sendText] [${instanceName}] - Resultado: ${JSON.stringify(result)}`);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async sendMedia({ instanceName }: InstanceDto, data: SendMediaDto, file?: any) {
|
||||
this.logger.log(`[sendMedia] [${instanceName}] - Iniciando envio de mídia...`);
|
||||
this.logger.debug(`[sendMedia] [${instanceName}] - Dados de envio: ${JSON.stringify(data)}`);
|
||||
|
||||
if (isBase64(data?.media) && !data?.fileName && data?.mediatype === 'document') {
|
||||
this.logger.error(
|
||||
`[sendMedia] [${instanceName}] - Falha: Para base64, é necessário informar o nome do arquivo.`
|
||||
);
|
||||
throw new BadRequestException('For base64 the file name must be informed.');
|
||||
}
|
||||
|
||||
if (file || isURL(data?.media) || isBase64(data?.media)) {
|
||||
return await this.waMonitor.waInstances[instanceName].mediaMessage(data, file);
|
||||
const result = await this.waMonitor.waInstances[instanceName].mediaMessage(data, file);
|
||||
this.logger.log(`[sendMedia] [${instanceName}] - Envio de mídia concluído com sucesso.`);
|
||||
this.logger.debug(`[sendMedia] [${instanceName}] - Resultado: ${JSON.stringify(result)}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
this.logger.error(
|
||||
`[sendMedia] [${instanceName}] - Falha: Mídia deve ser uma URL ou base64.`
|
||||
);
|
||||
throw new BadRequestException('Owned media must be a url or base64');
|
||||
}
|
||||
|
||||
public async sendPtv({ instanceName }: InstanceDto, data: SendPtvDto, file?: any) {
|
||||
this.logger.log(`[sendPtv] [${instanceName}] - Iniciando envio de vídeo (PTV)...`);
|
||||
this.logger.debug(`[sendPtv] [${instanceName}] - Dados de envio: ${JSON.stringify(data)}`);
|
||||
|
||||
if (file || isURL(data?.video) || isBase64(data?.video)) {
|
||||
return await this.waMonitor.waInstances[instanceName].ptvMessage(data, file);
|
||||
const result = await this.waMonitor.waInstances[instanceName].ptvMessage(data, file);
|
||||
this.logger.log(`[sendPtv] [${instanceName}] - Envio de vídeo (PTV) concluído com sucesso.`);
|
||||
this.logger.debug(`[sendPtv] [${instanceName}] - Resultado: ${JSON.stringify(result)}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
this.logger.error(
|
||||
`[sendPtv] [${instanceName}] - Falha: Vídeo deve ser uma URL ou base64.`
|
||||
);
|
||||
throw new BadRequestException('Owned media must be a url or base64');
|
||||
}
|
||||
|
||||
public async sendSticker({ instanceName }: InstanceDto, data: SendStickerDto, file?: any) {
|
||||
this.logger.log(`[sendSticker] [${instanceName}] - Iniciando envio de sticker...`);
|
||||
this.logger.debug(`[sendSticker] [${instanceName}] - Dados de envio: ${JSON.stringify(data)}`);
|
||||
|
||||
if (file || isURL(data.sticker) || isBase64(data.sticker)) {
|
||||
return await this.waMonitor.waInstances[instanceName].mediaSticker(data, file);
|
||||
const result = await this.waMonitor.waInstances[instanceName].mediaSticker(data, file);
|
||||
this.logger.log(`[sendSticker] [${instanceName}] - Envio de sticker concluído com sucesso.`);
|
||||
this.logger.debug(`[sendSticker] [${instanceName}] - Resultado: ${JSON.stringify(result)}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
this.logger.error(
|
||||
`[sendSticker] [${instanceName}] - Falha: Sticker deve ser uma URL ou base64.`
|
||||
);
|
||||
throw new BadRequestException('Owned media must be a url or base64');
|
||||
}
|
||||
|
||||
public async sendWhatsAppAudio({ instanceName }: InstanceDto, data: SendAudioDto, file?: any) {
|
||||
this.logger.log(`[sendWhatsAppAudio] [${instanceName}] - Iniciando envio de áudio...`);
|
||||
this.logger.debug(`[sendWhatsAppAudio] [${instanceName}] - Dados de envio: ${JSON.stringify(data)}`);
|
||||
|
||||
if (file?.buffer || isURL(data.audio) || isBase64(data.audio)) {
|
||||
// Si file existe y tiene buffer, o si es una URL o Base64, continúa
|
||||
return await this.waMonitor.waInstances[instanceName].audioWhatsapp(data, file);
|
||||
const result = await this.waMonitor.waInstances[instanceName].audioWhatsapp(data, file);
|
||||
this.logger.log(`[sendWhatsAppAudio] [${instanceName}] - Envio de áudio concluído com sucesso.`);
|
||||
this.logger.debug(`[sendWhatsAppAudio] [${instanceName}] - Resultado: ${JSON.stringify(result)}`);
|
||||
return result;
|
||||
} else {
|
||||
console.error('El archivo no tiene buffer o el audio no es una URL o Base64 válida');
|
||||
throw new BadRequestException('Owned media must be a url, base64, or valid file with buffer');
|
||||
this.logger.error(
|
||||
`[sendWhatsAppAudio] [${instanceName}] - Falha: O arquivo não possui buffer, ou o áudio não é uma URL/base64 válida.`
|
||||
);
|
||||
throw new BadRequestException(
|
||||
'Owned media must be a url, base64, or valid file with buffer'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public async sendButtons({ instanceName }: InstanceDto, data: SendButtonsDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].buttonMessage(data);
|
||||
this.logger.log(`[sendButtons] [${instanceName}] - Iniciando envio de botões...`);
|
||||
this.logger.debug(`[sendButtons] [${instanceName}] - Dados de envio: ${JSON.stringify(data)}`);
|
||||
|
||||
const result = await this.waMonitor.waInstances[instanceName].buttonMessage(data);
|
||||
|
||||
this.logger.log(`[sendButtons] [${instanceName}] - Envio de botões concluído com sucesso.`);
|
||||
this.logger.debug(`[sendButtons] [${instanceName}] - Resultado: ${JSON.stringify(result)}`);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async sendLocation({ instanceName }: InstanceDto, data: SendLocationDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].locationMessage(data);
|
||||
this.logger.log(`[sendLocation] [${instanceName}] - Iniciando envio de localização...`);
|
||||
this.logger.debug(`[sendLocation] [${instanceName}] - Dados de envio: ${JSON.stringify(data)}`);
|
||||
|
||||
const result = await this.waMonitor.waInstances[instanceName].locationMessage(data);
|
||||
|
||||
this.logger.log(`[sendLocation] [${instanceName}] - Envio de localização concluído com sucesso.`);
|
||||
this.logger.debug(`[sendLocation] [${instanceName}] - Resultado: ${JSON.stringify(result)}`);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async sendList({ instanceName }: InstanceDto, data: SendListDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].listMessage(data);
|
||||
this.logger.log(`[sendList] [${instanceName}] - Iniciando envio de lista...`);
|
||||
this.logger.debug(`[sendList] [${instanceName}] - Dados de envio: ${JSON.stringify(data)}`);
|
||||
|
||||
const result = await this.waMonitor.waInstances[instanceName].listMessage(data);
|
||||
|
||||
this.logger.log(`[sendList] [${instanceName}] - Envio de lista concluído com sucesso.`);
|
||||
this.logger.debug(`[sendList] [${instanceName}] - Resultado: ${JSON.stringify(result)}`);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async sendContact({ instanceName }: InstanceDto, data: SendContactDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].contactMessage(data);
|
||||
this.logger.log(`[sendContact] [${instanceName}] - Iniciando envio de contato...`);
|
||||
this.logger.debug(`[sendContact] [${instanceName}] - Dados de envio: ${JSON.stringify(data)}`);
|
||||
|
||||
const result = await this.waMonitor.waInstances[instanceName].contactMessage(data);
|
||||
|
||||
this.logger.log(`[sendContact] [${instanceName}] - Envio de contato concluído com sucesso.`);
|
||||
this.logger.debug(`[sendContact] [${instanceName}] - Resultado: ${JSON.stringify(result)}`);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async sendReaction({ instanceName }: InstanceDto, data: SendReactionDto) {
|
||||
this.logger.log(`[sendReaction] [${instanceName}] - Iniciando envio de reação...`);
|
||||
this.logger.debug(`[sendReaction] [${instanceName}] - Dados de envio: ${JSON.stringify(data)}`);
|
||||
|
||||
if (!data.reaction.match(/[^()\w\sà-ú"-+]+/)) {
|
||||
this.logger.error(`[sendReaction] [${instanceName}] - Falha: "reaction" deve ser um emoji.`);
|
||||
throw new BadRequestException('"reaction" must be an emoji');
|
||||
}
|
||||
return await this.waMonitor.waInstances[instanceName].reactionMessage(data);
|
||||
|
||||
const result = await this.waMonitor.waInstances[instanceName].reactionMessage(data);
|
||||
|
||||
this.logger.log(`[sendReaction] [${instanceName}] - Envio de reação concluído com sucesso.`);
|
||||
this.logger.debug(`[sendReaction] [${instanceName}] - Resultado: ${JSON.stringify(result)}`);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async sendPoll({ instanceName }: InstanceDto, data: SendPollDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].pollMessage(data);
|
||||
this.logger.log(`[sendPoll] [${instanceName}] - Iniciando envio de enquete (poll)...`);
|
||||
this.logger.debug(`[sendPoll] [${instanceName}] - Dados de envio: ${JSON.stringify(data)}`);
|
||||
|
||||
const result = await this.waMonitor.waInstances[instanceName].pollMessage(data);
|
||||
|
||||
this.logger.log(`[sendPoll] [${instanceName}] - Envio de enquete concluído com sucesso.`);
|
||||
this.logger.debug(`[sendPoll] [${instanceName}] - Resultado: ${JSON.stringify(result)}`);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async sendStatus({ instanceName }: InstanceDto, data: SendStatusDto, file?: any) {
|
||||
return await this.waMonitor.waInstances[instanceName].statusMessage(data, file);
|
||||
this.logger.log(`[sendStatus] [${instanceName}] - Iniciando envio de Status...`);
|
||||
this.logger.debug(`[sendStatus] [${instanceName}] - Dados de envio: ${JSON.stringify(data)}`);
|
||||
|
||||
const result = await this.waMonitor.waInstances[instanceName].statusMessage(data, file);
|
||||
|
||||
this.logger.log(`[sendStatus] [${instanceName}] - Envio de Status concluído com sucesso.`);
|
||||
this.logger.debug(`[sendStatus] [${instanceName}] - Resultado: ${JSON.stringify(result)}`);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
@ -47,8 +47,15 @@ export class Metadata {
|
||||
}
|
||||
|
||||
export class SendTextDto extends Metadata {
|
||||
text: string;
|
||||
text: string;
|
||||
// number: string; // WhatsApp ou 'webwidget:...'
|
||||
// delay?: number;
|
||||
// quoted?: any;
|
||||
// linkPreview?: boolean;
|
||||
// mentionsEveryOne?: boolean;
|
||||
// mentioned?: string[];
|
||||
}
|
||||
|
||||
export class SendPresence extends Metadata {
|
||||
text: string;
|
||||
}
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -1,39 +1,68 @@
|
||||
import { Logger } from '@config/logger.config';
|
||||
import { PrismaRepository } from '@api/repository/repository.service';
|
||||
import { WAMonitoringService } from '@api/services/monitor.service';
|
||||
import { Logger } from '@config/logger.config';
|
||||
|
||||
import { ChannelController, ChannelControllerInterface } from '../channel.controller';
|
||||
|
||||
export class EvolutionController extends ChannelController implements ChannelControllerInterface {
|
||||
private readonly logger = new Logger('EvolutionController');
|
||||
|
||||
constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) {
|
||||
super(prismaRepository, waMonitor);
|
||||
}
|
||||
|
||||
// Flag para indicar se a integração está habilitada
|
||||
integrationEnabled: boolean;
|
||||
|
||||
public async receiveWebhook(data: any) {
|
||||
const numberId = data.numberId;
|
||||
constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) {
|
||||
super(prismaRepository, waMonitor);
|
||||
this.logger.debug('EvolutionController -> constructor called');
|
||||
|
||||
// Exemplo de log ao definir flags ou propriedades adicionais
|
||||
this.integrationEnabled = true;
|
||||
this.logger.debug(`EvolutionController -> integrationEnabled set to: ${this.integrationEnabled}`);
|
||||
}
|
||||
|
||||
public async receiveWebhook(data: any) {
|
||||
this.logger.debug('EvolutionController -> receiveWebhook called');
|
||||
this.logger.debug(`EvolutionController -> receiveWebhook -> data: ${JSON.stringify(data)}`);
|
||||
|
||||
// Extraindo número de identificação
|
||||
const numberId = data.numberId;
|
||||
this.logger.debug(`EvolutionController -> receiveWebhook -> numberId: ${numberId}`);
|
||||
|
||||
// Validando se o numberId foi informado
|
||||
if (!numberId) {
|
||||
this.logger.error('WebhookService -> receiveWebhookEvolution -> numberId not found');
|
||||
return;
|
||||
}
|
||||
|
||||
const instance = await this.prismaRepository.instance.findFirst({
|
||||
where: { number: numberId },
|
||||
});
|
||||
try {
|
||||
// Log antes de buscar a instância
|
||||
this.logger.debug(`EvolutionController -> Looking for instance with numberId: ${numberId}`);
|
||||
const instance = await this.prismaRepository.instance.findFirst({
|
||||
where: { number: numberId },
|
||||
});
|
||||
|
||||
if (!instance) {
|
||||
this.logger.error('WebhookService -> receiveWebhook -> instance not found');
|
||||
return;
|
||||
// Log do resultado da busca
|
||||
this.logger.debug(`EvolutionController -> Prisma instance result: ${JSON.stringify(instance)}`);
|
||||
|
||||
// Validando se a instância foi encontrada
|
||||
if (!instance) {
|
||||
this.logger.error('WebhookService -> receiveWebhook -> instance not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Log antes de tentar conectar
|
||||
this.logger.debug(`EvolutionController -> Connecting to WhatsApp instance: ${instance.name}`);
|
||||
await this.waMonitor.waInstances[instance.name].connectToWhatsapp(data);
|
||||
this.logger.debug('EvolutionController -> Successfully connected to WhatsApp instance');
|
||||
|
||||
// Retorno de sucesso
|
||||
this.logger.debug('EvolutionController -> receiveWebhook -> returning success');
|
||||
return {
|
||||
status: 'success',
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error(`EvolutionController -> receiveWebhook -> Error: ${error.message}`);
|
||||
this.logger.debug(`EvolutionController -> receiveWebhook -> Stack trace: ${error.stack}`);
|
||||
throw error;
|
||||
}
|
||||
|
||||
await this.waMonitor.waInstances[instance.name].connectToWhatsapp(data);
|
||||
|
||||
return {
|
||||
status: 'success',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -1,18 +1,64 @@
|
||||
import { Logger } from '@config/logger.config';
|
||||
import { RouterBroker } from '@api/abstract/abstract.router';
|
||||
import { evolutionController } from '@api/server.module';
|
||||
import { ConfigService } from '@config/env.config';
|
||||
import { Router } from 'express';
|
||||
import { Router, Request, Response } from 'express';
|
||||
|
||||
export class EvolutionRouter extends RouterBroker {
|
||||
private readonly logger = new Logger('EvolutionRouter');
|
||||
|
||||
public readonly router: Router = Router();
|
||||
|
||||
constructor(readonly configService: ConfigService) {
|
||||
super();
|
||||
this.router.post(this.routerPath('webhook/evolution', false), async (req, res) => {
|
||||
const { body } = req;
|
||||
const response = await evolutionController.receiveWebhook(body);
|
||||
|
||||
return res.status(200).json(response);
|
||||
});
|
||||
// Log the initialization of the EvolutionRouter
|
||||
this.logger.debug('[EvolutionRouter] Initializing router...');
|
||||
|
||||
this.router.post(
|
||||
this.routerPath('webhook/evolution', false),
|
||||
async (req: Request, res: Response) => {
|
||||
try {
|
||||
this.logger.info('[EvolutionRouter] POST /webhook/evolution route called');
|
||||
|
||||
// Log the request body for debugging (cuidado com dados sensíveis)
|
||||
const { body } = req;
|
||||
this.logger.debug(
|
||||
`[EvolutionRouter] Received request body: ${JSON.stringify(this.sanitizeBody(body))}`
|
||||
);
|
||||
|
||||
this.logger.debug('[EvolutionRouter] Calling evolutionController.receiveWebhook...');
|
||||
const response = await evolutionController.receiveWebhook(body);
|
||||
|
||||
// Log the response from the controller
|
||||
this.logger.debug(
|
||||
`[EvolutionRouter] Response from evolutionController: ${JSON.stringify(response)}`
|
||||
);
|
||||
|
||||
this.logger.debug('[EvolutionRouter] Returning 200 with response');
|
||||
return res.status(200).json(response);
|
||||
} catch (error: any) {
|
||||
// Log the error for debugging
|
||||
this.logger.error(`[EvolutionRouter] Error in POST /webhook/evolution: ${error.message}`);
|
||||
return res.status(500).json({
|
||||
message: 'Internal server error',
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
this.logger.debug('[EvolutionRouter] Router setup complete');
|
||||
}
|
||||
|
||||
public readonly router: Router = Router();
|
||||
}
|
||||
/**
|
||||
* Filters sensitive information from the request body for safe logging.
|
||||
*/
|
||||
private sanitizeBody(body: any): any {
|
||||
// Implement filtering logic to exclude sensitive data
|
||||
const sanitizedBody = { ...body };
|
||||
if (sanitizedBody.password) sanitizedBody.password = '[FILTERED]';
|
||||
if (sanitizedBody.token) sanitizedBody.token = '[FILTERED]';
|
||||
return sanitizedBody;
|
||||
}
|
||||
}
|
@ -270,7 +270,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
public async getProfileStatus() {
|
||||
const status = await this.client.fetchStatus(this.instance.wuid);
|
||||
|
||||
return status?.status;
|
||||
return status?.[0]?.status;
|
||||
}
|
||||
|
||||
public get profilePictureUrl() {
|
||||
@ -990,7 +990,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
);
|
||||
|
||||
if (chatwootImport.getRepositoryMessagesCache(instance) === null) {
|
||||
chatwootImport.setRepositoryMessagesCache(instance, messagesRepository);
|
||||
chatwootImport.setRepositoryMessagesCache(instance, messagesRepository as Set<string>);
|
||||
}
|
||||
|
||||
for (const m of messages) {
|
||||
@ -1785,7 +1785,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
try {
|
||||
return {
|
||||
wuid: jid,
|
||||
status: (await this.client.fetchStatus(jid))?.status,
|
||||
status: (await this.client.fetchStatus(jid))[0]?.status,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
|
@ -1,3 +1,4 @@
|
||||
import { Logger } from '@config/logger.config';
|
||||
import { InstanceDto } from '@api/dto/instance.dto';
|
||||
import { ChatwootDto } from '@api/integrations/chatbot/chatwoot/dto/chatwoot.dto';
|
||||
import { ChatwootService } from '@api/integrations/chatbot/chatwoot/services/chatwoot.service';
|
||||
@ -10,6 +11,8 @@ import { BadRequestException } from '@exceptions';
|
||||
import { isURL } from 'class-validator';
|
||||
|
||||
export class ChatwootController {
|
||||
private readonly logger = new Logger(ChatwootController.name);
|
||||
|
||||
constructor(
|
||||
private readonly chatwootService: ChatwootService,
|
||||
private readonly configService: ConfigService,
|
||||
@ -17,51 +20,85 @@ export class ChatwootController {
|
||||
) {}
|
||||
|
||||
public async createChatwoot(instance: InstanceDto, data: ChatwootDto) {
|
||||
if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled');
|
||||
this.logger.debug(`[createChatwoot] Iniciando criação de Chatwoot para a instância: ${JSON.stringify(instance)}`);
|
||||
this.logger.debug(`[createChatwoot] Dados recebidos: ${JSON.stringify(data)}`);
|
||||
|
||||
const chatwootConfig = this.configService.get<Chatwoot>('CHATWOOT');
|
||||
if (!chatwootConfig.ENABLED) {
|
||||
this.logger.warn('[createChatwoot] Chatwoot está desabilitado. Lançando exceção...');
|
||||
throw new BadRequestException('Chatwoot is disabled');
|
||||
}
|
||||
|
||||
if (data?.enabled) {
|
||||
this.logger.debug('[createChatwoot] Validação de dados habilitados...');
|
||||
|
||||
if (!isURL(data.url, { require_tld: false })) {
|
||||
this.logger.error(`[createChatwoot] URL inválida: ${data.url}`);
|
||||
throw new BadRequestException('url is not valid');
|
||||
}
|
||||
|
||||
if (!data.accountId) {
|
||||
this.logger.error('[createChatwoot] accountId não informado');
|
||||
throw new BadRequestException('accountId is required');
|
||||
}
|
||||
|
||||
if (!data.token) {
|
||||
this.logger.error('[createChatwoot] token não informado');
|
||||
throw new BadRequestException('token is required');
|
||||
}
|
||||
|
||||
if (data.signMsg !== true && data.signMsg !== false) {
|
||||
this.logger.error('[createChatwoot] signMsg inválido ou não informado');
|
||||
throw new BadRequestException('signMsg is required');
|
||||
}
|
||||
if (data.signMsg === false) data.signDelimiter = null;
|
||||
|
||||
if (data.signMsg === false) {
|
||||
this.logger.debug('[createChatwoot] signMsg definido como false, removendo signDelimiter');
|
||||
data.signDelimiter = null;
|
||||
}
|
||||
} else {
|
||||
this.logger.debug('[createChatwoot] Dados informam que Chatwoot não está habilitado (enabled=false ou undefined).');
|
||||
}
|
||||
|
||||
if (!data.nameInbox || data.nameInbox === '') {
|
||||
this.logger.debug(`[createChatwoot] nameInbox não informado. Usando nome da instância: "${instance.instanceName}"`);
|
||||
data.nameInbox = instance.instanceName;
|
||||
}
|
||||
|
||||
this.logger.debug('[createChatwoot] Chamando ChatwootService.create...');
|
||||
const result = await this.chatwootService.create(instance, data);
|
||||
this.logger.debug(`[createChatwoot] Retorno de ChatwootService.create: ${JSON.stringify(result)}`);
|
||||
|
||||
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
|
||||
this.logger.debug(`[createChatwoot] urlServer obtido: ${urlServer}`);
|
||||
|
||||
const response = {
|
||||
...result,
|
||||
webhook_url: `${urlServer}/chatwoot/webhook/${encodeURIComponent(instance.instanceName)}`,
|
||||
};
|
||||
|
||||
this.logger.debug(`[createChatwoot] Retornando resposta final: ${JSON.stringify(response)}`);
|
||||
return response;
|
||||
}
|
||||
|
||||
public async findChatwoot(instance: InstanceDto): Promise<ChatwootDto & { webhook_url: string }> {
|
||||
if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled');
|
||||
this.logger.debug(`[findChatwoot] Buscando configurações Chatwoot para a instância: ${JSON.stringify(instance)}`);
|
||||
|
||||
const chatwootConfig = this.configService.get<Chatwoot>('CHATWOOT');
|
||||
if (!chatwootConfig.ENABLED) {
|
||||
this.logger.warn('[findChatwoot] Chatwoot está desabilitado. Lançando exceção...');
|
||||
throw new BadRequestException('Chatwoot is disabled');
|
||||
}
|
||||
|
||||
this.logger.debug('[findChatwoot] Chamando ChatwootService.find...');
|
||||
const result = await this.chatwootService.find(instance);
|
||||
this.logger.debug(`[findChatwoot] Resposta de ChatwootService.find: ${JSON.stringify(result)}`);
|
||||
|
||||
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
|
||||
this.logger.debug(`[findChatwoot] urlServer obtido: ${urlServer}`);
|
||||
|
||||
if (Object.keys(result || {}).length === 0) {
|
||||
this.logger.debug('[findChatwoot] Nenhuma configuração encontrada. Retornando default desabilitado.');
|
||||
return {
|
||||
enabled: false,
|
||||
url: '',
|
||||
@ -78,15 +115,28 @@ export class ChatwootController {
|
||||
webhook_url: `${urlServer}/chatwoot/webhook/${encodeURIComponent(instance.instanceName)}`,
|
||||
};
|
||||
|
||||
this.logger.debug(`[findChatwoot] Resposta final: ${JSON.stringify(response)}`);
|
||||
return response;
|
||||
}
|
||||
|
||||
public async receiveWebhook(instance: InstanceDto, data: any) {
|
||||
if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled');
|
||||
this.logger.debug(`[receiveWebhook] Recebendo webhook para instância: ${JSON.stringify(instance)}`);
|
||||
this.logger.debug(`[receiveWebhook] Dados recebidos no webhook: ${JSON.stringify(data)}`);
|
||||
|
||||
const chatwootConfig = this.configService.get<Chatwoot>('CHATWOOT');
|
||||
if (!chatwootConfig.ENABLED) {
|
||||
this.logger.warn('[receiveWebhook] Chatwoot está desabilitado. Lançando exceção...');
|
||||
throw new BadRequestException('Chatwoot is disabled');
|
||||
}
|
||||
|
||||
this.logger.debug('[receiveWebhook] Iniciando configuração de CacheService para Chatwoot...');
|
||||
const chatwootCache = new CacheService(new CacheEngine(this.configService, ChatwootService.name).getEngine());
|
||||
const chatwootService = new ChatwootService(waMonitor, this.configService, this.prismaRepository, chatwootCache);
|
||||
|
||||
return chatwootService.receiveWebhook(instance, data);
|
||||
this.logger.debug('[receiveWebhook] Chamando chatwootService.receiveWebhook...');
|
||||
const result = await chatwootService.receiveWebhook(instance, data);
|
||||
this.logger.debug(`[receiveWebhook] Resposta de receiveWebhook: ${JSON.stringify(result)}`);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -726,7 +726,7 @@ export class EvolutionBotController extends ChatbotController implements Chatbot
|
||||
|
||||
const session = await this.getSession(remoteJid, instance);
|
||||
|
||||
const content = getConversationMessage(msg);
|
||||
const content = getConversationMessage(msg);
|
||||
|
||||
let findBot = (await this.findBotTrigger(
|
||||
this.botRepository,
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -5,7 +5,7 @@ import { WAMonitoringService } from '@api/services/monitor.service';
|
||||
import { Integration } from '@api/types/wa.types';
|
||||
import { ConfigService, Language } from '@config/env.config';
|
||||
import { Logger } from '@config/logger.config';
|
||||
import { IntegrationSession, OpenaiBot, OpenaiCreds, OpenaiSetting } from '@prisma/client';
|
||||
import { IntegrationSession, OpenaiBot, OpenaiCreds, OpenaiSetting, Message } from '@prisma/client';
|
||||
import { sendTelemetry } from '@utils/sendTelemetry';
|
||||
import axios from 'axios';
|
||||
import { downloadMediaMessage } from 'baileys';
|
||||
@ -25,7 +25,12 @@ export class OpenaiService {
|
||||
private readonly logger = new Logger('OpenaiService');
|
||||
|
||||
private async sendMessageToBot(instance: any, openaiBot: OpenaiBot, remoteJid: string, content: string) {
|
||||
this.logger.debug('[sendMessageToBot] Enviando mensagem para o bot.');
|
||||
this.logger.debug(`[sendMessageToBot] RemoteJid: ${remoteJid}, Content: ${content}`);
|
||||
|
||||
// System messages
|
||||
const systemMessages: any = openaiBot.systemMessages;
|
||||
this.logger.debug(`[sendMessageToBot] SystemMessages recuperadas: ${systemMessages}`);
|
||||
|
||||
const messagesSystem: any[] = systemMessages.map((message) => {
|
||||
return {
|
||||
@ -34,8 +39,10 @@ export class OpenaiService {
|
||||
};
|
||||
});
|
||||
|
||||
// Assistant messages
|
||||
const assistantMessages: any = openaiBot.assistantMessages;
|
||||
|
||||
this.logger.debug(`[sendMessageToBot] AssistantMessages recuperadas: ${assistantMessages}`);
|
||||
|
||||
const messagesAssistant: any[] = assistantMessages.map((message) => {
|
||||
return {
|
||||
role: 'assistant',
|
||||
@ -43,7 +50,9 @@ export class OpenaiService {
|
||||
};
|
||||
});
|
||||
|
||||
// User messages
|
||||
const userMessages: any = openaiBot.userMessages;
|
||||
this.logger.debug(`[sendMessageToBot] UserMessages recuperadas: ${userMessages}`);
|
||||
|
||||
const messagesUser: any[] = userMessages.map((message) => {
|
||||
return {
|
||||
@ -52,15 +61,18 @@ export class OpenaiService {
|
||||
};
|
||||
});
|
||||
|
||||
// Imagem messages
|
||||
const messageData: any = {
|
||||
role: 'user',
|
||||
content: [{ type: 'text', text: content }],
|
||||
content: content,
|
||||
};
|
||||
|
||||
if (this.isImageMessage(content)) {
|
||||
this.logger.debug('[sendMessageToBot] Identificada mensagem de imagem no texto.');
|
||||
const contentSplit = content.split('|');
|
||||
|
||||
const url = contentSplit[1].split('?')[0];
|
||||
this.logger.debug(`[sendMessageToBot] URL da imagem extraída: ${url}`);
|
||||
|
||||
messageData.content = [
|
||||
{ type: 'text', text: contentSplit[2] || content },
|
||||
@ -73,23 +85,126 @@ export class OpenaiService {
|
||||
];
|
||||
}
|
||||
|
||||
const messages: any[] = [...messagesSystem, ...messagesAssistant, ...messagesUser, messageData];
|
||||
// History Mensagens
|
||||
// Define aqui o limite máximo de caracteres do histórico
|
||||
const MAX_HISTORY_CHARS = 30000;
|
||||
|
||||
/**
|
||||
* Extrai o texto principal de um objeto de mensagem.
|
||||
* @param msg Mensagem recebida do banco (tipo `Message`).
|
||||
* @returns Texto extraído da mensagem ou um JSON.stringify como fallback.
|
||||
*/
|
||||
function extrairTextoDaMensagem(msg: Message): string {
|
||||
// Se não houver conteúdo
|
||||
if (!msg?.message) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Caso seja mensagem de texto simples
|
||||
if (typeof msg.message === 'object' && 'conversation' in msg.message) {
|
||||
return String(msg.message.conversation);
|
||||
}
|
||||
|
||||
// Caso seja extendedTextMessage
|
||||
if (typeof msg.message === 'object' && (msg.message as any)?.extendedTextMessage?.text) {
|
||||
if (typeof msg.message === 'object' && 'extendedTextMessage' in msg.message) {
|
||||
return (msg.message as any).extendedTextMessage.text;
|
||||
}
|
||||
}
|
||||
|
||||
// Caso seja imagem com caption
|
||||
if (typeof msg.message === 'object' && 'imageMessage' in msg.message && (msg.message as any).imageMessage?.caption) {
|
||||
return (msg.message as any).imageMessage.caption;
|
||||
}
|
||||
|
||||
// Fallback: retorna o objeto como JSON
|
||||
return JSON.stringify(msg.message);
|
||||
}
|
||||
|
||||
let historyArray: any[] = [];
|
||||
|
||||
if (remoteJid && remoteJid.startsWith('webwidget:')) {
|
||||
// Extrai o ID da conversa a partir do remoteJid (ex: 'webwidget:12345')
|
||||
const conversationId = remoteJid.split(':')[1] || '0';
|
||||
this.logger.debug(`[sendMessageToBot] RemoteJid é webwidget. Buscando histórico da conversa: ${conversationId}`);
|
||||
|
||||
// Busca todas as mensagens, sem limite de quantidade
|
||||
let conversationHistory = await this.prismaRepository.message.findMany({
|
||||
where: {
|
||||
chatwootConversationId: parseInt(conversationId),
|
||||
},
|
||||
orderBy: {
|
||||
messageTimestamp: 'desc',
|
||||
},
|
||||
});
|
||||
this.logger.debug(`[sendMessageToBot] Histórico da conversa recuperado: ${conversationHistory.length} mensagens`);
|
||||
|
||||
if (conversationHistory.length > 0) {
|
||||
// Inverte para ficar das mais antigas às mais recentes
|
||||
conversationHistory = conversationHistory.reverse();
|
||||
|
||||
// Mapeia cada mensagem para uma linha (role + texto)
|
||||
let lines = conversationHistory.map((msg) => {
|
||||
const textoExtraido = extrairTextoDaMensagem(msg);
|
||||
// Se a mensagem for "fromMe", consideramos como 'assistant'; senão, 'user'
|
||||
const roleOpenAI = (msg.key as any)?.fromMe ? 'assistant' : 'user';
|
||||
return `${roleOpenAI}: ${textoExtraido}`;
|
||||
});
|
||||
|
||||
// Monta o histórico inicial com todas as linhas
|
||||
let conversationString = lines.join('\n');
|
||||
|
||||
// Se exceder o limite de caracteres, remover mensagens mais antigas
|
||||
while (conversationString.length > MAX_HISTORY_CHARS && lines.length > 0) {
|
||||
// Remove a primeira linha (mais antiga) do array
|
||||
lines.shift();
|
||||
conversationString = lines.join('\n');
|
||||
}
|
||||
|
||||
historyArray = [
|
||||
{
|
||||
role: 'system',
|
||||
content: `This is the conversation history so far:\n\n${conversationString}`,
|
||||
}
|
||||
];
|
||||
} else {
|
||||
// Caso não haja histórico
|
||||
historyArray = [
|
||||
{
|
||||
role: 'system',
|
||||
content: 'Não há histórico de conversa ainda.',
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
this.logger.debug(`[sendMessageToBot] HistoryMessages: ${JSON.stringify(historyArray)}`);
|
||||
}
|
||||
|
||||
// debug historyMessages
|
||||
this.logger.debug(`[sendMessageToBot] HistoryMessages: ${JSON.stringify(historyArray)}`);
|
||||
const messages: any[] = [...messagesSystem, ...messagesAssistant, ...messagesUser, ...historyArray, messageData];
|
||||
this.logger.debug(`[sendMessageToBot] Mensagens que serão enviadas para a API da OpenAI: ${JSON.stringify(messages)}`);
|
||||
|
||||
if (instance.integration === Integration.WHATSAPP_BAILEYS) {
|
||||
this.logger.debug('[sendMessageToBot] Atualizando presença para WHATSAPP_BAILEYS (composing).');
|
||||
await instance.client.presenceSubscribe(remoteJid);
|
||||
await instance.client.sendPresenceUpdate('composing', remoteJid);
|
||||
}
|
||||
|
||||
this.logger.debug('[sendMessageToBot] Chamando a API da OpenAI (chat.completions.create).');
|
||||
const completions = await this.client.chat.completions.create({
|
||||
model: openaiBot.model,
|
||||
messages: messages,
|
||||
max_tokens: openaiBot.maxTokens,
|
||||
});
|
||||
|
||||
if (instance.integration === Integration.WHATSAPP_BAILEYS)
|
||||
if (instance.integration === Integration.WHATSAPP_BAILEYS) {
|
||||
this.logger.debug('[sendMessageToBot] Atualizando presença para WHATSAPP_BAILEYS (paused).');
|
||||
await instance.client.sendPresenceUpdate('paused', remoteJid);
|
||||
}
|
||||
|
||||
const message = completions.choices[0].message.content;
|
||||
this.logger.debug(`[sendMessageToBot] Resposta obtida da OpenAI: ${message}`);
|
||||
|
||||
return message;
|
||||
}
|
||||
@ -103,15 +218,20 @@ export class OpenaiService {
|
||||
content: string,
|
||||
threadId: string,
|
||||
) {
|
||||
this.logger.debug('[sendMessageToAssistant] Enviando mensagem para o assistente.');
|
||||
this.logger.debug(`[sendMessageToAssistant] RemoteJid: ${remoteJid}, ThreadId: ${threadId}, Content: ${content}`);
|
||||
|
||||
const messageData: any = {
|
||||
role: fromMe ? 'assistant' : 'user',
|
||||
content: [{ type: 'text', text: content }],
|
||||
};
|
||||
|
||||
if (this.isImageMessage(content)) {
|
||||
this.logger.debug('[sendMessageToAssistant] Identificada mensagem de imagem no texto.');
|
||||
const contentSplit = content.split('|');
|
||||
|
||||
const url = contentSplit[1].split('?')[0];
|
||||
this.logger.debug(`[sendMessageToAssistant] URL da imagem extraída: ${url}`);
|
||||
|
||||
messageData.content = [
|
||||
{ type: 'text', text: contentSplit[2] || content },
|
||||
@ -124,28 +244,36 @@ export class OpenaiService {
|
||||
];
|
||||
}
|
||||
|
||||
this.logger.debug('[sendMessageToAssistant] Criando mensagem no thread do Assistant.');
|
||||
await this.client.beta.threads.messages.create(threadId, messageData);
|
||||
|
||||
if (fromMe) {
|
||||
this.logger.debug('[sendMessageToAssistant] Mensagem enviada foi do próprio bot (fromMe). Enviando Telemetry.');
|
||||
sendTelemetry('/message/sendText');
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.debug('[sendMessageToAssistant] Iniciando corrida (run) do Assistant com ID do assistant configurado.');
|
||||
const runAssistant = await this.client.beta.threads.runs.create(threadId, {
|
||||
assistant_id: openaiBot.assistantId,
|
||||
});
|
||||
|
||||
if (instance.integration === Integration.WHATSAPP_BAILEYS) {
|
||||
this.logger.debug('[sendMessageToAssistant] Atualizando presença para WHATSAPP_BAILEYS (composing).');
|
||||
await instance.client.presenceSubscribe(remoteJid);
|
||||
await instance.client.sendPresenceUpdate('composing', remoteJid);
|
||||
}
|
||||
|
||||
this.logger.debug('[sendMessageToAssistant] Aguardando resposta do Assistant (getAIResponse).');
|
||||
const response = await this.getAIResponse(threadId, runAssistant.id, openaiBot.functionUrl, remoteJid, pushName);
|
||||
|
||||
if (instance.integration === Integration.WHATSAPP_BAILEYS)
|
||||
if (instance.integration === Integration.WHATSAPP_BAILEYS) {
|
||||
this.logger.debug('[sendMessageToAssistant] Atualizando presença para WHATSAPP_BAILEYS (paused).');
|
||||
await instance.client.sendPresenceUpdate('paused', remoteJid);
|
||||
}
|
||||
|
||||
const message = response?.data[0].content[0].text.value;
|
||||
this.logger.debug(`[sendMessageToAssistant] Resposta obtida do Assistant: ${message}`);
|
||||
|
||||
return message;
|
||||
}
|
||||
@ -157,8 +285,10 @@ export class OpenaiService {
|
||||
settings: OpenaiSetting,
|
||||
message: string,
|
||||
) {
|
||||
const linkRegex = /(!?)\[(.*?)\]\((.*?)\)/g;
|
||||
this.logger.debug('[sendMessageWhatsapp] Enviando mensagem para o WhatsApp.');
|
||||
this.logger.debug(`[sendMessageWhatsapp] RemoteJid: ${remoteJid}, Mensagem: ${message}`);
|
||||
|
||||
const linkRegex = /(!?)\[(.*?)\]\((.*?)\)/g;
|
||||
let textBuffer = '';
|
||||
let lastIndex = 0;
|
||||
|
||||
@ -178,8 +308,11 @@ export class OpenaiService {
|
||||
return null;
|
||||
};
|
||||
|
||||
// Processa links (ou mídia) dentro do texto
|
||||
this.logger.debug('[sendMessageWhatsapp] Verificando se a mensagem contém mídia (links) no formato [altText](url).');
|
||||
while ((match = linkRegex.exec(message)) !== null) {
|
||||
const [fullMatch, exclMark, altText, url] = match;
|
||||
this.logger.debug(`[sendMessageWhatsapp] Match encontrado: ${fullMatch}, url: ${url}, altText: ${altText}`);
|
||||
const mediaType = getMediaType(url);
|
||||
|
||||
const beforeText = message.slice(lastIndex, match.index);
|
||||
@ -193,22 +326,24 @@ export class OpenaiService {
|
||||
const minDelay = 1000;
|
||||
const maxDelay = 20000;
|
||||
|
||||
// Envia primeiro o texto que estiver no buffer
|
||||
if (textBuffer.trim()) {
|
||||
if (splitMessages) {
|
||||
const multipleMessages = textBuffer.trim().split('\n\n');
|
||||
|
||||
for (let index = 0; index < multipleMessages.length; index++) {
|
||||
const message = multipleMessages[index];
|
||||
|
||||
const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay);
|
||||
|
||||
if (instance.integration === Integration.WHATSAPP_BAILEYS) {
|
||||
this.logger.debug('[sendMessageWhatsapp] Atualizando presença (composing) antes de enviar texto em partes.');
|
||||
await instance.client.presenceSubscribe(remoteJid);
|
||||
await instance.client.sendPresenceUpdate('composing', remoteJid);
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
setTimeout(async () => {
|
||||
this.logger.debug(`[sendMessageWhatsapp] Enviando texto (splitMessage)`);
|
||||
await instance.textMessage(
|
||||
{
|
||||
number: remoteJid.split('@')[0],
|
||||
@ -222,10 +357,12 @@ export class OpenaiService {
|
||||
});
|
||||
|
||||
if (instance.integration === Integration.WHATSAPP_BAILEYS) {
|
||||
this.logger.debug('[sendMessageWhatsapp] Atualizando presença (paused) após enviar parte do texto.');
|
||||
await instance.client.sendPresenceUpdate('paused', remoteJid);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.logger.debug(`[sendMessageWhatsapp] Enviando texto inteiro do buffer: ${textBuffer.trim()}`);
|
||||
await instance.textMessage(
|
||||
{
|
||||
number: remoteJid.split('@')[0],
|
||||
@ -238,7 +375,9 @@ export class OpenaiService {
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.debug(`[sendMessageWhatsapp] Identificado arquivo de mídia do tipo: ${mediaType}`);
|
||||
if (mediaType === 'audio') {
|
||||
this.logger.debug('[sendMessageWhatsapp] Enviando arquivo de áudio para o WhatsApp.');
|
||||
await instance.audioWhatsapp({
|
||||
number: remoteJid.split('@')[0],
|
||||
delay: settings?.delayMessage || 1000,
|
||||
@ -246,6 +385,7 @@ export class OpenaiService {
|
||||
caption: altText,
|
||||
});
|
||||
} else {
|
||||
this.logger.debug('[sendMessageWhatsapp] Enviando arquivo de mídia (imagem, vídeo ou documento) para o WhatsApp.');
|
||||
await instance.mediaMessage(
|
||||
{
|
||||
number: remoteJid.split('@')[0],
|
||||
@ -259,12 +399,14 @@ export class OpenaiService {
|
||||
);
|
||||
}
|
||||
} else {
|
||||
this.logger.debug('[sendMessageWhatsapp] Não é um tipo de mídia suportado. Adicionando link no buffer de texto.');
|
||||
textBuffer += `[${altText}](${url})`;
|
||||
}
|
||||
|
||||
lastIndex = linkRegex.lastIndex;
|
||||
}
|
||||
|
||||
// Processa o texto restante, caso exista
|
||||
if (lastIndex < message.length) {
|
||||
const remainingText = message.slice(lastIndex);
|
||||
if (remainingText.trim()) {
|
||||
@ -277,22 +419,24 @@ export class OpenaiService {
|
||||
const minDelay = 1000;
|
||||
const maxDelay = 20000;
|
||||
|
||||
// Envia o que restou no textBuffer
|
||||
if (textBuffer.trim()) {
|
||||
if (splitMessages) {
|
||||
const multipleMessages = textBuffer.trim().split('\n\n');
|
||||
|
||||
for (let index = 0; index < multipleMessages.length; index++) {
|
||||
const message = multipleMessages[index];
|
||||
|
||||
const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay);
|
||||
|
||||
if (instance.integration === Integration.WHATSAPP_BAILEYS) {
|
||||
this.logger.debug('[sendMessageWhatsapp] Atualizando presença (composing) antes de enviar resto do texto em partes.');
|
||||
await instance.client.presenceSubscribe(remoteJid);
|
||||
await instance.client.sendPresenceUpdate('composing', remoteJid);
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
setTimeout(async () => {
|
||||
this.logger.debug(`[sendMessageWhatsapp] Enviando texto (splitMessage)`);
|
||||
await instance.textMessage(
|
||||
{
|
||||
number: remoteJid.split('@')[0],
|
||||
@ -306,10 +450,12 @@ export class OpenaiService {
|
||||
});
|
||||
|
||||
if (instance.integration === Integration.WHATSAPP_BAILEYS) {
|
||||
this.logger.debug('[sendMessageWhatsapp] Atualizando presença (paused) após enviar parte final do texto.');
|
||||
await instance.client.sendPresenceUpdate('paused', remoteJid);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.logger.debug(`[sendMessageWhatsapp] Enviando todo o texto restante no buffer: ${textBuffer.trim()}`);
|
||||
await instance.textMessage(
|
||||
{
|
||||
number: remoteJid.split('@')[0],
|
||||
@ -322,8 +468,10 @@ export class OpenaiService {
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.debug('[sendMessageWhatsapp] Enviando telemetria após envio de texto.');
|
||||
sendTelemetry('/message/sendText');
|
||||
|
||||
this.logger.debug(`[sendMessageWhatsapp] Atualizando sessão (id: ${session.id}) para 'opened' e 'awaitUser: true'.`);
|
||||
await this.prismaRepository.integrationSession.update({
|
||||
where: {
|
||||
id: session.id,
|
||||
@ -336,7 +484,13 @@ export class OpenaiService {
|
||||
}
|
||||
|
||||
public async createAssistantNewSession(instance: InstanceDto, data: any) {
|
||||
if (data.remoteJid === 'status@broadcast') return;
|
||||
this.logger.debug('[createAssistantNewSession] Iniciando criação de nova sessão do Assistant.');
|
||||
this.logger.debug(`[createAssistantNewSession] Dados recebidos: ${JSON.stringify(data)}`);
|
||||
|
||||
if (data.remoteJid === 'status@broadcast') {
|
||||
this.logger.debug('[createAssistantNewSession] remoteJid é status@broadcast, abortando criação de sessão.');
|
||||
return;
|
||||
}
|
||||
|
||||
const creds = await this.prismaRepository.openaiCreds.findFirst({
|
||||
where: {
|
||||
@ -344,17 +498,24 @@ export class OpenaiService {
|
||||
},
|
||||
});
|
||||
|
||||
if (!creds) throw new Error('Openai Creds not found');
|
||||
if (!creds) {
|
||||
this.logger.error('[createAssistantNewSession] Openai Creds não encontrados, lançando erro.');
|
||||
throw new Error('Openai Creds not found');
|
||||
}
|
||||
|
||||
try {
|
||||
this.logger.debug('[createAssistantNewSession] Instanciando cliente OpenAI para Assistant.');
|
||||
this.client = new OpenAI({
|
||||
apiKey: creds.apiKey,
|
||||
});
|
||||
|
||||
const threadId = (await this.client.beta.threads.create({})).id;
|
||||
this.logger.debug('[createAssistantNewSession] Criando thread (beta.threads.create).');
|
||||
const thread = await this.client.beta.threads.create({});
|
||||
const threadId = thread.id;
|
||||
|
||||
let session = null;
|
||||
if (threadId) {
|
||||
this.logger.debug('[createAssistantNewSession] Thread criada com sucesso. Salvando sessão no banco de dados.');
|
||||
session = await this.prismaRepository.integrationSession.create({
|
||||
data: {
|
||||
remoteJid: data.remoteJid,
|
||||
@ -370,7 +531,7 @@ export class OpenaiService {
|
||||
}
|
||||
return { session };
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
this.logger.error(`[createAssistantNewSession] Erro ao criar nova sessão do Assistant: ${error}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@ -385,6 +546,9 @@ export class OpenaiService {
|
||||
session: IntegrationSession,
|
||||
content: string,
|
||||
) {
|
||||
this.logger.debug('[initAssistantNewSession] Iniciando sessão do Assistant.');
|
||||
this.logger.debug(`[initAssistantNewSession] RemoteJid: ${remoteJid}, PushName: ${pushName}, Content: ${content}`);
|
||||
|
||||
const data = await this.createAssistantNewSession(instance, {
|
||||
remoteJid,
|
||||
pushName,
|
||||
@ -394,8 +558,10 @@ export class OpenaiService {
|
||||
|
||||
if (data.session) {
|
||||
session = data.session;
|
||||
this.logger.debug(`[initAssistantNewSession] Sessão criada com sucesso. ID: ${session.id}`);
|
||||
}
|
||||
|
||||
this.logger.debug('[initAssistantNewSession] Enviando mensagem para Assistant para iniciar conversa.');
|
||||
const message = await this.sendMessageToAssistant(
|
||||
instance,
|
||||
openaiBot,
|
||||
@ -406,7 +572,11 @@ export class OpenaiService {
|
||||
session.sessionId,
|
||||
);
|
||||
|
||||
await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message);
|
||||
this.logger.debug(`[initAssistantNewSession] Retorno do Assistant: ${message}`);
|
||||
if (message) {
|
||||
this.logger.debug('[initAssistantNewSession] Enviando mensagem do Assistant para WhatsApp.');
|
||||
await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
@ -427,10 +597,12 @@ export class OpenaiService {
|
||||
remoteJid: string,
|
||||
pushName: string,
|
||||
) {
|
||||
this.logger.debug(`[getAIResponse] Consultando run do Assistant. ThreadId: ${threadId}, RunId: ${runId}`);
|
||||
const getRun = await this.client.beta.threads.runs.retrieve(threadId, runId);
|
||||
let toolCalls;
|
||||
switch (getRun.status) {
|
||||
case 'requires_action':
|
||||
this.logger.debug('[getAIResponse] Run requer ação. Verificando chamadas de ferramenta (tool_calls).');
|
||||
toolCalls = getRun?.required_action?.submit_tool_outputs?.tool_calls;
|
||||
|
||||
if (toolCalls) {
|
||||
@ -442,6 +614,7 @@ export class OpenaiService {
|
||||
: toolCall?.function?.arguments;
|
||||
|
||||
let output = null;
|
||||
this.logger.debug(`[getAIResponse] Chamando função externa: ${functionName} com argumentos:`, functionArgument);
|
||||
|
||||
try {
|
||||
const { data } = await axios.post(functionUrl, {
|
||||
@ -449,13 +622,16 @@ export class OpenaiService {
|
||||
arguments: { ...functionArgument, remoteJid, pushName },
|
||||
});
|
||||
|
||||
// Serializa saída para string
|
||||
output = JSON.stringify(data)
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/"/g, '\\"')
|
||||
.replace(/\n/g, '\\n')
|
||||
.replace(/\r/g, '\\r')
|
||||
.replace(/\t/g, '\\t');
|
||||
this.logger.debug(`[getAIResponse] Resposta da função externa (${functionName}):`, data);
|
||||
} catch (error) {
|
||||
this.logger.error(`[getAIResponse] Erro ao chamar função externa (${functionName}):`, error);
|
||||
output = JSON.stringify(error)
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/"/g, '\\"')
|
||||
@ -464,6 +640,7 @@ export class OpenaiService {
|
||||
.replace(/\t/g, '\\t');
|
||||
}
|
||||
|
||||
this.logger.debug('[getAIResponse] Submetendo output para a run do Assistant (submitToolOutputs).');
|
||||
await this.client.beta.threads.runs.submitToolOutputs(threadId, runId, {
|
||||
tool_outputs: [
|
||||
{
|
||||
@ -475,14 +652,18 @@ export class OpenaiService {
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.debug('[getAIResponse] Repetindo chamada getAIResponse até status diferente de requires_action.');
|
||||
return this.getAIResponse(threadId, runId, functionUrl, remoteJid, pushName);
|
||||
case 'queued':
|
||||
this.logger.debug('[getAIResponse] Run está em fila (queued). Aguardando 1 segundo antes de tentar novamente.');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
return this.getAIResponse(threadId, runId, functionUrl, remoteJid, pushName);
|
||||
case 'in_progress':
|
||||
this.logger.debug('[getAIResponse] Run está em progresso (in_progress). Aguardando 1 segundo antes de tentar novamente.');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
return this.getAIResponse(threadId, runId, functionUrl, remoteJid, pushName);
|
||||
case 'completed':
|
||||
this.logger.debug('[getAIResponse] Run concluída (completed). Recuperando última mensagem.');
|
||||
return await this.client.beta.threads.messages.list(threadId, {
|
||||
run_id: runId,
|
||||
limit: 1,
|
||||
@ -504,21 +685,27 @@ export class OpenaiService {
|
||||
settings: OpenaiSetting,
|
||||
content: string,
|
||||
) {
|
||||
this.logger.debug('[processOpenaiAssistant] Processando mensagem para o Assistant.');
|
||||
this.logger.debug(
|
||||
`[processOpenaiAssistant] RemoteJid: ${remoteJid}, pushName: ${pushName}, fromMe: ${fromMe}, content: ${content}`,
|
||||
);
|
||||
|
||||
if (session && session.status === 'closed') {
|
||||
this.logger.debug('[processOpenaiAssistant] A sessão está fechada, não será processada.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (session && settings.expire && settings.expire > 0) {
|
||||
this.logger.debug('[processOpenaiAssistant] Verificando tempo de expiração da sessão...');
|
||||
const now = Date.now();
|
||||
|
||||
const sessionUpdatedAt = new Date(session.updatedAt).getTime();
|
||||
|
||||
const diff = now - sessionUpdatedAt;
|
||||
|
||||
const diffInMinutes = Math.floor(diff / 1000 / 60);
|
||||
|
||||
if (diffInMinutes > settings.expire) {
|
||||
this.logger.debug(`[processOpenaiAssistant] Sessão expirada há ${diffInMinutes} minutos.`);
|
||||
if (settings.keepOpen) {
|
||||
this.logger.debug('[processOpenaiAssistant] Atualizando status da sessão para CLOSED.');
|
||||
await this.prismaRepository.integrationSession.update({
|
||||
where: {
|
||||
id: session.id,
|
||||
@ -528,6 +715,7 @@ export class OpenaiService {
|
||||
},
|
||||
});
|
||||
} else {
|
||||
this.logger.debug('[processOpenaiAssistant] Deletando sessão do banco de dados.');
|
||||
await this.prismaRepository.integrationSession.deleteMany({
|
||||
where: {
|
||||
botId: openaiBot.id,
|
||||
@ -536,6 +724,7 @@ export class OpenaiService {
|
||||
});
|
||||
}
|
||||
|
||||
this.logger.debug('[processOpenaiAssistant] Recriando nova sessão de Assistant...');
|
||||
await this.initAssistantNewSession(
|
||||
instance,
|
||||
remoteJid,
|
||||
@ -551,11 +740,13 @@ export class OpenaiService {
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
this.logger.debug('[processOpenaiAssistant] Nenhuma sessão ativa encontrada, criando nova sessão de Assistant...');
|
||||
await this.initAssistantNewSession(instance, remoteJid, pushName, fromMe, openaiBot, settings, session, content);
|
||||
return;
|
||||
}
|
||||
|
||||
if (session.status !== 'paused')
|
||||
if (session.status !== 'paused') {
|
||||
this.logger.debug('[processOpenaiAssistant] Marcando sessão como aberta e awaitUser = false.');
|
||||
await this.prismaRepository.integrationSession.update({
|
||||
where: {
|
||||
id: session.id,
|
||||
@ -565,9 +756,12 @@ export class OpenaiService {
|
||||
awaitUser: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (!content) {
|
||||
this.logger.debug('[processOpenaiAssistant] Não há conteúdo na mensagem. Verificando se existe unknownMessage para retorno.');
|
||||
if (settings.unknownMessage) {
|
||||
this.logger.debug(`[processOpenaiAssistant] Enviando unknownMessage para o remoteJid: ${remoteJid}`);
|
||||
this.waMonitor.waInstances[instance.instanceName].textMessage(
|
||||
{
|
||||
number: remoteJid.split('@')[0],
|
||||
@ -576,13 +770,13 @@ export class OpenaiService {
|
||||
},
|
||||
false,
|
||||
);
|
||||
|
||||
sendTelemetry('/message/sendText');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) {
|
||||
this.logger.debug('[processOpenaiAssistant] Keyword finish detectada. Encerrando sessão.');
|
||||
if (settings.keepOpen) {
|
||||
await this.prismaRepository.integrationSession.update({
|
||||
where: {
|
||||
@ -603,20 +797,25 @@ export class OpenaiService {
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.debug('[processOpenaiAssistant] Buscando OpenaiCreds no banco...');
|
||||
const creds = await this.prismaRepository.openaiCreds.findFirst({
|
||||
where: {
|
||||
id: openaiBot.openaiCredsId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!creds) throw new Error('Openai Creds not found');
|
||||
if (!creds) {
|
||||
this.logger.error('[processOpenaiAssistant] Openai Creds não encontrados, lançando erro.');
|
||||
throw new Error('Openai Creds not found');
|
||||
}
|
||||
|
||||
this.logger.debug('[processOpenaiAssistant] Instanciando cliente OpenAI para processar a mensagem no Assistant.');
|
||||
this.client = new OpenAI({
|
||||
apiKey: creds.apiKey,
|
||||
});
|
||||
|
||||
const threadId = session.sessionId;
|
||||
|
||||
this.logger.debug(`[processOpenaiAssistant] Enviando mensagem ao Assistant (threadId: ${threadId}).`);
|
||||
const message = await this.sendMessageToAssistant(
|
||||
instance,
|
||||
openaiBot,
|
||||
@ -627,15 +826,25 @@ export class OpenaiService {
|
||||
threadId,
|
||||
);
|
||||
|
||||
await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message);
|
||||
if (message) {
|
||||
this.logger.debug(`[processOpenaiAssistant] Resposta do Assistant recebida. Enviando para WhatsApp: ${message}`);
|
||||
await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
public async createChatCompletionNewSession(instance: InstanceDto, data: any) {
|
||||
if (data.remoteJid === 'status@broadcast') return;
|
||||
this.logger.debug('[createChatCompletionNewSession] Iniciando criação de nova sessão de chatCompletion.');
|
||||
this.logger.debug(`[createChatCompletionNewSession] Dados recebidos: ${JSON.stringify(data)}`);
|
||||
|
||||
if (data.remoteJid === 'status@broadcast') {
|
||||
this.logger.debug('[createChatCompletionNewSession] remoteJid é status@broadcast, abortando criação de sessão.');
|
||||
return;
|
||||
}
|
||||
|
||||
const id = Math.floor(Math.random() * 10000000000).toString();
|
||||
this.logger.debug(`[createChatCompletionNewSession] Gerando ID pseudo-aleatório da sessão: ${id}`);
|
||||
|
||||
const creds = await this.prismaRepository.openaiCreds.findFirst({
|
||||
where: {
|
||||
@ -643,9 +852,13 @@ export class OpenaiService {
|
||||
},
|
||||
});
|
||||
|
||||
if (!creds) throw new Error('Openai Creds not found');
|
||||
if (!creds) {
|
||||
this.logger.error('[createChatCompletionNewSession] Openai Creds não encontrados, lançando erro.');
|
||||
throw new Error('Openai Creds not found');
|
||||
}
|
||||
|
||||
try {
|
||||
this.logger.debug('[createChatCompletionNewSession] Criando sessão no banco de dados.');
|
||||
const session = await this.prismaRepository.integrationSession.create({
|
||||
data: {
|
||||
remoteJid: data.remoteJid,
|
||||
@ -661,7 +874,7 @@ export class OpenaiService {
|
||||
|
||||
return { session, creds };
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
this.logger.error(`[createChatCompletionNewSession] Erro ao criar nova sessão de chatCompletion: ${error}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@ -675,6 +888,9 @@ export class OpenaiService {
|
||||
session: IntegrationSession,
|
||||
content: string,
|
||||
) {
|
||||
this.logger.debug('[initChatCompletionNewSession] Iniciando sessão de chatCompletion.');
|
||||
this.logger.debug(`[initChatCompletionNewSession] RemoteJid: ${remoteJid}, PushName: ${pushName}, Content: ${content}`);
|
||||
|
||||
const data = await this.createChatCompletionNewSession(instance, {
|
||||
remoteJid,
|
||||
pushName,
|
||||
@ -683,16 +899,21 @@ export class OpenaiService {
|
||||
});
|
||||
|
||||
session = data.session;
|
||||
|
||||
const creds = data.creds;
|
||||
this.logger.debug(`[initChatCompletionNewSession] Sessão criada com sucesso (ID: ${session.id}). Instanciando cliente OpenAI.`);
|
||||
|
||||
this.client = new OpenAI({
|
||||
apiKey: creds.apiKey,
|
||||
});
|
||||
|
||||
this.logger.debug('[initChatCompletionNewSession] Enviando mensagem para o Bot usando chatCompletion.');
|
||||
const message = await this.sendMessageToBot(instance, openaiBot, remoteJid, content);
|
||||
|
||||
await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message);
|
||||
this.logger.debug(`[initChatCompletionNewSession] Resposta do Bot: ${message}`);
|
||||
if (message) {
|
||||
this.logger.debug('[initChatCompletionNewSession] Enviando resposta para o WhatsApp.');
|
||||
await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
@ -706,21 +927,27 @@ export class OpenaiService {
|
||||
settings: OpenaiSetting,
|
||||
content: string,
|
||||
) {
|
||||
this.logger.debug('Processando ChatCompletion (processOpenaiChatCompletion).');
|
||||
this.logger.debug(
|
||||
`RemoteJid: ${remoteJid}, PushName: ${pushName}, Content: ${content}, SessionId: ${session?.id}`,
|
||||
);
|
||||
|
||||
if (session && session.status !== 'opened') {
|
||||
this.logger.debug('[processOpenaiChatCompletion] Sessão existente não está aberta. Não será processado.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (session && settings.expire && settings.expire > 0) {
|
||||
this.logger.debug('[processOpenaiChatCompletion] Verificando tempo de expiração da sessão...');
|
||||
const now = Date.now();
|
||||
|
||||
const sessionUpdatedAt = new Date(session.updatedAt).getTime();
|
||||
|
||||
const diff = now - sessionUpdatedAt;
|
||||
|
||||
const diffInMinutes = Math.floor(diff / 1000 / 60);
|
||||
|
||||
if (diffInMinutes > settings.expire) {
|
||||
this.logger.debug(`[processOpenaiChatCompletion] Sessão expirada há ${diffInMinutes} minutos.`);
|
||||
if (settings.keepOpen) {
|
||||
this.logger.debug('[processOpenaiChatCompletion] Atualizando status da sessão para CLOSED.');
|
||||
await this.prismaRepository.integrationSession.update({
|
||||
where: {
|
||||
id: session.id,
|
||||
@ -730,6 +957,7 @@ export class OpenaiService {
|
||||
},
|
||||
});
|
||||
} else {
|
||||
this.logger.debug('[processOpenaiChatCompletion] Deletando sessão do banco de dados.');
|
||||
await this.prismaRepository.integrationSession.deleteMany({
|
||||
where: {
|
||||
botId: openaiBot.id,
|
||||
@ -738,16 +966,19 @@ export class OpenaiService {
|
||||
});
|
||||
}
|
||||
|
||||
this.logger.debug('[processOpenaiChatCompletion] Recriando nova sessão de chatCompletion...');
|
||||
await this.initChatCompletionNewSession(instance, remoteJid, pushName, openaiBot, settings, session, content);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
this.logger.debug('[processOpenaiChatCompletion] Nenhuma sessão encontrada. Criando nova sessão de chatCompletion...');
|
||||
await this.initChatCompletionNewSession(instance, remoteJid, pushName, openaiBot, settings, session, content);
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.debug('[processOpenaiChatCompletion] Marcando sessão como aberta e awaitUser = false.');
|
||||
await this.prismaRepository.integrationSession.update({
|
||||
where: {
|
||||
id: session.id,
|
||||
@ -759,7 +990,9 @@ export class OpenaiService {
|
||||
});
|
||||
|
||||
if (!content) {
|
||||
this.logger.debug('[processOpenaiChatCompletion] Não há conteúdo na mensagem. Verificando se existe unknownMessage para retorno.');
|
||||
if (settings.unknownMessage) {
|
||||
this.logger.debug(`[processOpenaiChatCompletion] Enviando unknownMessage para o remoteJid: ${remoteJid}`);
|
||||
this.waMonitor.waInstances[instance.instanceName].textMessage(
|
||||
{
|
||||
number: remoteJid.split('@')[0],
|
||||
@ -768,13 +1001,13 @@ export class OpenaiService {
|
||||
},
|
||||
false,
|
||||
);
|
||||
|
||||
sendTelemetry('/message/sendText');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) {
|
||||
this.logger.debug('[processOpenaiChatCompletion] Keyword finish detectada. Encerrando sessão.');
|
||||
if (settings.keepOpen) {
|
||||
await this.prismaRepository.integrationSession.update({
|
||||
where: {
|
||||
@ -795,33 +1028,47 @@ export class OpenaiService {
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.debug('[processOpenaiChatCompletion] Buscando OpenaiCreds no banco...');
|
||||
const creds = await this.prismaRepository.openaiCreds.findFirst({
|
||||
where: {
|
||||
id: openaiBot.openaiCredsId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!creds) throw new Error('Openai Creds not found');
|
||||
if (!creds) {
|
||||
this.logger.error('[processOpenaiChatCompletion] Openai Creds não encontrados, lançando erro.');
|
||||
throw new Error('Openai Creds not found');
|
||||
}
|
||||
|
||||
this.logger.debug('[processOpenaiChatCompletion] Instanciando cliente OpenAI para processar a mensagem (ChatCompletion).');
|
||||
this.client = new OpenAI({
|
||||
apiKey: creds.apiKey,
|
||||
});
|
||||
|
||||
this.logger.debug('[processOpenaiChatCompletion] Enviando mensagem para o Bot usando chatCompletion.');
|
||||
const message = await this.sendMessageToBot(instance, openaiBot, remoteJid, content);
|
||||
|
||||
await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message);
|
||||
this.logger.debug(`[processOpenaiChatCompletion] Resposta do Bot: ${message}`);
|
||||
if (message) {
|
||||
this.logger.debug('[processOpenaiChatCompletion] Enviando resposta para o WhatsApp.');
|
||||
await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
public async speechToText(creds: OpenaiCreds, msg: any, updateMediaMessage: any) {
|
||||
this.logger.debug('[speechToText] Iniciando conversão de fala em texto.');
|
||||
|
||||
let audio;
|
||||
|
||||
if (msg?.message?.mediaUrl) {
|
||||
this.logger.debug('[speechToText] Baixando áudio via URL (mediaUrl).');
|
||||
audio = await axios.get(msg.message.mediaUrl, { responseType: 'arraybuffer' }).then((response) => {
|
||||
return Buffer.from(response.data, 'binary');
|
||||
});
|
||||
} else {
|
||||
this.logger.debug('[speechToText] Baixando áudio via downloadMediaMessage (baileys).');
|
||||
audio = await downloadMediaMessage(
|
||||
{ key: msg.key, message: msg?.message },
|
||||
'buffer',
|
||||
@ -836,13 +1083,14 @@ export class OpenaiService {
|
||||
const lang = this.configService.get<Language>('LANGUAGE').includes('pt')
|
||||
? 'pt'
|
||||
: this.configService.get<Language>('LANGUAGE');
|
||||
this.logger.debug(`[speechToText] Definindo idioma da transcrição como: ${lang}`);
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
formData.append('file', audio, 'audio.ogg');
|
||||
formData.append('model', 'whisper-1');
|
||||
formData.append('language', lang);
|
||||
|
||||
this.logger.debug('[speechToText] Enviando requisição POST para a API de transcrição do OpenAI.');
|
||||
const response = await axios.post('https://api.openai.com/v1/audio/transcriptions', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
@ -850,6 +1098,7 @@ export class OpenaiService {
|
||||
},
|
||||
});
|
||||
|
||||
this.logger.debug(`[speechToText] Status da requisição: ${response.status}`);
|
||||
return response?.data?.text;
|
||||
}
|
||||
}
|
||||
|
@ -51,6 +51,7 @@ export class ChannelStartupService {
|
||||
public difyService = new DifyService(waMonitor, this.configService, this.prismaRepository);
|
||||
|
||||
public setInstance(instance: InstanceDto) {
|
||||
this.logger.debug(`[setInstance] Definindo dados da instância: ${JSON.stringify(instance)}`);
|
||||
this.logger.setInstance(instance.instanceName);
|
||||
|
||||
this.instance.name = instance.instanceName;
|
||||
@ -61,6 +62,7 @@ export class ChannelStartupService {
|
||||
this.instance.businessId = instance.businessId;
|
||||
|
||||
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot?.enabled) {
|
||||
this.logger.debug('[setInstance] Enviando evento de STATUS_INSTANCE para Chatwoot');
|
||||
this.chatwootService.eventWhatsapp(
|
||||
Events.STATUS_INSTANCE,
|
||||
{ instanceName: this.instance.name },
|
||||
@ -73,6 +75,7 @@ export class ChannelStartupService {
|
||||
}
|
||||
|
||||
public set instanceName(name: string) {
|
||||
this.logger.debug(`[setter instanceName] Atribuindo: ${name}`);
|
||||
this.logger.setInstance(name);
|
||||
|
||||
if (!name) {
|
||||
@ -87,6 +90,7 @@ export class ChannelStartupService {
|
||||
}
|
||||
|
||||
public set instanceId(id: string) {
|
||||
this.logger.debug(`[setter instanceId] Atribuindo: ${id}`);
|
||||
if (!id) {
|
||||
this.instance.id = v4();
|
||||
return;
|
||||
@ -99,6 +103,7 @@ export class ChannelStartupService {
|
||||
}
|
||||
|
||||
public set integration(integration: string) {
|
||||
this.logger.debug(`[setter integration] Atribuindo: ${integration}`);
|
||||
this.instance.integration = integration;
|
||||
}
|
||||
|
||||
@ -107,6 +112,7 @@ export class ChannelStartupService {
|
||||
}
|
||||
|
||||
public set number(number: string) {
|
||||
this.logger.debug(`[setter number] Atribuindo número: ${number}`);
|
||||
this.instance.number = number;
|
||||
}
|
||||
|
||||
@ -115,6 +121,7 @@ export class ChannelStartupService {
|
||||
}
|
||||
|
||||
public set token(token: string) {
|
||||
this.logger.debug(`[setter token] Atribuindo token.`);
|
||||
this.instance.token = token;
|
||||
}
|
||||
|
||||
@ -127,6 +134,7 @@ export class ChannelStartupService {
|
||||
}
|
||||
|
||||
public async loadWebhook() {
|
||||
this.logger.debug(`[loadWebhook] Carregando webhook para instanceId: ${this.instanceId}`);
|
||||
const data = await this.prismaRepository.webhook.findUnique({
|
||||
where: {
|
||||
instanceId: this.instanceId,
|
||||
@ -135,9 +143,12 @@ export class ChannelStartupService {
|
||||
|
||||
this.localWebhook.enabled = data?.enabled;
|
||||
this.localWebhook.webhookBase64 = data?.webhookBase64;
|
||||
|
||||
this.logger.debug('[loadWebhook] Webhook carregado com sucesso.');
|
||||
}
|
||||
|
||||
public async loadSettings() {
|
||||
this.logger.debug(`[loadSettings] Carregando configurações para instanceId: ${this.instanceId}`);
|
||||
const data = await this.prismaRepository.setting.findUnique({
|
||||
where: {
|
||||
instanceId: this.instanceId,
|
||||
@ -151,9 +162,12 @@ export class ChannelStartupService {
|
||||
this.localSettings.readMessages = data?.readMessages;
|
||||
this.localSettings.readStatus = data?.readStatus;
|
||||
this.localSettings.syncFullHistory = data?.syncFullHistory;
|
||||
|
||||
this.logger.debug('[loadSettings] Configurações carregadas com sucesso.');
|
||||
}
|
||||
|
||||
public async setSettings(data: SettingsDto) {
|
||||
this.logger.debug(`[setSettings] Atualizando configurações: ${JSON.stringify(data)}`);
|
||||
await this.prismaRepository.setting.upsert({
|
||||
where: {
|
||||
instanceId: this.instanceId,
|
||||
@ -186,9 +200,12 @@ export class ChannelStartupService {
|
||||
this.localSettings.readMessages = data?.readMessages;
|
||||
this.localSettings.readStatus = data?.readStatus;
|
||||
this.localSettings.syncFullHistory = data?.syncFullHistory;
|
||||
|
||||
this.logger.debug('[setSettings] Configurações atualizadas com sucesso.');
|
||||
}
|
||||
|
||||
public async findSettings() {
|
||||
this.logger.debug(`[findSettings] Buscando configurações para instanceId: ${this.instanceId}`);
|
||||
const data = await this.prismaRepository.setting.findUnique({
|
||||
where: {
|
||||
instanceId: this.instanceId,
|
||||
@ -196,9 +213,11 @@ export class ChannelStartupService {
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
this.logger.debug('[findSettings] Nenhuma configuração encontrada.');
|
||||
return null;
|
||||
}
|
||||
|
||||
this.logger.debug('[findSettings] Configurações encontradas.');
|
||||
return {
|
||||
rejectCall: data.rejectCall,
|
||||
msgCall: data.msgCall,
|
||||
@ -211,7 +230,9 @@ export class ChannelStartupService {
|
||||
}
|
||||
|
||||
public async loadChatwoot() {
|
||||
this.logger.debug('[loadChatwoot] Carregando dados do Chatwoot...');
|
||||
if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) {
|
||||
this.logger.debug('[loadChatwoot] Chatwoot não está habilitado nas configurações.');
|
||||
return;
|
||||
}
|
||||
|
||||
@ -235,10 +256,14 @@ export class ChannelStartupService {
|
||||
this.localChatwoot.importContacts = data?.importContacts;
|
||||
this.localChatwoot.importMessages = data?.importMessages;
|
||||
this.localChatwoot.daysLimitImportMessages = data?.daysLimitImportMessages;
|
||||
|
||||
this.logger.debug('[loadChatwoot] Dados do Chatwoot carregados com sucesso.');
|
||||
}
|
||||
|
||||
public async setChatwoot(data: ChatwootDto) {
|
||||
this.logger.debug(`[setChatwoot] Atualizando dados do Chatwoot: ${JSON.stringify(data)}`);
|
||||
if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) {
|
||||
this.logger.debug('[setChatwoot] Chatwoot não está habilitado nas configurações.');
|
||||
return;
|
||||
}
|
||||
|
||||
@ -275,8 +300,8 @@ export class ChannelStartupService {
|
||||
});
|
||||
|
||||
Object.assign(this.localChatwoot, { ...data, signDelimiter: data.signMsg ? data.signDelimiter : null });
|
||||
|
||||
this.clearCacheChatwoot();
|
||||
this.logger.debug('[setChatwoot] Dados do Chatwoot atualizados com sucesso.');
|
||||
return;
|
||||
}
|
||||
|
||||
@ -303,12 +328,14 @@ export class ChannelStartupService {
|
||||
});
|
||||
|
||||
Object.assign(this.localChatwoot, { ...data, signDelimiter: data.signMsg ? data.signDelimiter : null });
|
||||
|
||||
this.clearCacheChatwoot();
|
||||
this.logger.debug('[setChatwoot] Dados do Chatwoot criados com sucesso.');
|
||||
}
|
||||
|
||||
public async findChatwoot(): Promise<ChatwootDto | null> {
|
||||
this.logger.debug(`[findChatwoot] Buscando dados do Chatwoot para instanceId: ${this.instanceId}`);
|
||||
if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) {
|
||||
this.logger.debug('[findChatwoot] Chatwoot não está habilitado nas configurações.');
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -319,11 +346,12 @@ export class ChannelStartupService {
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
this.logger.debug('[findChatwoot] Nenhum dado de Chatwoot encontrado.');
|
||||
return null;
|
||||
}
|
||||
|
||||
const ignoreJidsArray = Array.isArray(data.ignoreJids) ? data.ignoreJids.map((event) => String(event)) : [];
|
||||
|
||||
this.logger.debug('[findChatwoot] Dados de Chatwoot encontrados com sucesso.');
|
||||
return {
|
||||
enabled: data?.enabled,
|
||||
accountId: data.accountId,
|
||||
@ -345,12 +373,15 @@ export class ChannelStartupService {
|
||||
}
|
||||
|
||||
public clearCacheChatwoot() {
|
||||
this.logger.debug('[clearCacheChatwoot] Limpando cache do Chatwoot...');
|
||||
if (this.localChatwoot?.enabled) {
|
||||
this.chatwootService.getCache()?.deleteAll(this.instanceName);
|
||||
this.logger.debug('[clearCacheChatwoot] Cache do Chatwoot limpo com sucesso.');
|
||||
}
|
||||
}
|
||||
|
||||
public async loadProxy() {
|
||||
this.logger.debug(`[loadProxy] Carregando dados de proxy para instanceId: ${this.instanceId}`);
|
||||
this.localProxy.enabled = false;
|
||||
|
||||
if (process.env.PROXY_HOST) {
|
||||
@ -376,9 +407,12 @@ export class ChannelStartupService {
|
||||
this.localProxy.username = data?.username;
|
||||
this.localProxy.password = data?.password;
|
||||
}
|
||||
|
||||
this.logger.debug('[loadProxy] Dados de proxy carregados com sucesso.');
|
||||
}
|
||||
|
||||
public async setProxy(data: ProxyDto) {
|
||||
this.logger.debug(`[setProxy] Definindo dados de proxy: ${JSON.stringify(data)}`);
|
||||
await this.prismaRepository.proxy.upsert({
|
||||
where: {
|
||||
instanceId: this.instanceId,
|
||||
@ -403,9 +437,11 @@ export class ChannelStartupService {
|
||||
});
|
||||
|
||||
Object.assign(this.localProxy, data);
|
||||
this.logger.debug('[setProxy] Dados de proxy atualizados com sucesso.');
|
||||
}
|
||||
|
||||
public async findProxy() {
|
||||
this.logger.debug(`[findProxy] Buscando dados de proxy para instanceId: ${this.instanceId}`);
|
||||
const data = await this.prismaRepository.proxy.findUnique({
|
||||
where: {
|
||||
instanceId: this.instanceId,
|
||||
@ -413,20 +449,22 @@ export class ChannelStartupService {
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
this.logger.debug('[findProxy] Proxy não encontrado.');
|
||||
throw new NotFoundException('Proxy not found');
|
||||
}
|
||||
|
||||
this.logger.debug('[findProxy] Dados de proxy encontrados com sucesso.');
|
||||
return data;
|
||||
}
|
||||
|
||||
public async sendDataWebhook<T = any>(event: Events, data: T, local = true) {
|
||||
this.logger.debug(`[sendDataWebhook] Enviando dados de webhook. Evento: ${event}, local: ${local}`);
|
||||
const serverUrl = this.configService.get<HttpServer>('SERVER').URL;
|
||||
const tzoffset = new Date().getTimezoneOffset() * 60000; //offset in milliseconds
|
||||
const localISOTime = new Date(Date.now() - tzoffset).toISOString();
|
||||
const now = localISOTime;
|
||||
|
||||
const expose = this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES;
|
||||
|
||||
const instanceApikey = this.token || 'Apikey not found';
|
||||
|
||||
await eventManager.emit({
|
||||
@ -440,10 +478,12 @@ export class ChannelStartupService {
|
||||
apiKey: expose && instanceApikey ? instanceApikey : null,
|
||||
local,
|
||||
});
|
||||
this.logger.debug('[sendDataWebhook] Evento de webhook enviado com sucesso.');
|
||||
}
|
||||
|
||||
// Check if the number is MX or AR
|
||||
public formatMXOrARNumber(jid: string): string {
|
||||
this.logger.debug(`[formatMXOrARNumber] Formatando número MX ou AR: ${jid}`);
|
||||
const countryCode = jid.substring(0, 2);
|
||||
|
||||
if (Number(countryCode) === 52 || Number(countryCode) === 54) {
|
||||
@ -451,7 +491,6 @@ export class ChannelStartupService {
|
||||
const number = countryCode + jid.substring(3);
|
||||
return number;
|
||||
}
|
||||
|
||||
return jid;
|
||||
}
|
||||
return jid;
|
||||
@ -459,6 +498,7 @@ export class ChannelStartupService {
|
||||
|
||||
// Check if the number is br
|
||||
public formatBRNumber(jid: string) {
|
||||
this.logger.debug(`[formatBRNumber] Formatando número brasileiro: ${jid}`);
|
||||
const regexp = new RegExp(/^(\d{2})(\d{2})\d{1}(\d{8})$/);
|
||||
if (regexp.test(jid)) {
|
||||
const match = regexp.exec(jid);
|
||||
@ -477,11 +517,14 @@ export class ChannelStartupService {
|
||||
}
|
||||
|
||||
public createJid(number: string): string {
|
||||
this.logger.debug(`[createJid] Criando JID para o número: ${number}`);
|
||||
if (number.includes('@g.us') || number.includes('@s.whatsapp.net') || number.includes('@lid')) {
|
||||
this.logger.debug('[createJid] Retornando número pois já possui sufixo de grupo ou WhatsApp.');
|
||||
return number;
|
||||
}
|
||||
|
||||
if (number.includes('@broadcast')) {
|
||||
this.logger.debug('[createJid] Retornando número pois já é um broadcast.');
|
||||
return number;
|
||||
}
|
||||
|
||||
@ -495,6 +538,7 @@ export class ChannelStartupService {
|
||||
|
||||
if (number.includes('-') && number.length >= 24) {
|
||||
number = number.replace(/[^\d-]/g, '');
|
||||
this.logger.debug('[createJid] Número identificado como grupo, adicionando @g.us.');
|
||||
return `${number}@g.us`;
|
||||
}
|
||||
|
||||
@ -502,17 +546,19 @@ export class ChannelStartupService {
|
||||
|
||||
if (number.length >= 18) {
|
||||
number = number.replace(/[^\d-]/g, '');
|
||||
this.logger.debug('[createJid] Número extenso, provavelmente grupo, adicionando @g.us.');
|
||||
return `${number}@g.us`;
|
||||
}
|
||||
|
||||
number = this.formatMXOrARNumber(number);
|
||||
|
||||
number = this.formatBRNumber(number);
|
||||
|
||||
this.logger.debug('[createJid] Adicionando sufixo @s.whatsapp.net para número individual.');
|
||||
return `${number}@s.whatsapp.net`;
|
||||
}
|
||||
|
||||
public async fetchContacts(query: Query<Contact>) {
|
||||
this.logger.debug(`[fetchContacts] Buscando contatos. Query: ${JSON.stringify(query)}`);
|
||||
const remoteJid = query?.where?.remoteJid
|
||||
? query?.where?.remoteJid.includes('@')
|
||||
? query.where?.remoteJid
|
||||
@ -527,12 +573,15 @@ export class ChannelStartupService {
|
||||
where['remoteJid'] = remoteJid;
|
||||
}
|
||||
|
||||
return await this.prismaRepository.contact.findMany({
|
||||
const contacts = await this.prismaRepository.contact.findMany({
|
||||
where,
|
||||
});
|
||||
this.logger.debug(`[fetchContacts] Retornando ${contacts.length} contato(s).`);
|
||||
return contacts;
|
||||
}
|
||||
|
||||
public async fetchMessages(query: Query<Message>) {
|
||||
this.logger.debug(`[fetchMessages] Buscando mensagens. Query: ${JSON.stringify(query)}`);
|
||||
const keyFilters = query?.where?.key as {
|
||||
id?: string;
|
||||
fromMe?: boolean;
|
||||
@ -599,6 +648,7 @@ export class ChannelStartupService {
|
||||
},
|
||||
});
|
||||
|
||||
this.logger.debug(`[fetchMessages] Total de mensagens encontradas: ${count}.`);
|
||||
return {
|
||||
messages: {
|
||||
total: count,
|
||||
@ -610,7 +660,8 @@ export class ChannelStartupService {
|
||||
}
|
||||
|
||||
public async fetchStatusMessage(query: any) {
|
||||
return await this.prismaRepository.messageUpdate.findMany({
|
||||
this.logger.debug(`[fetchStatusMessage] Buscando status de mensagens. Query: ${JSON.stringify(query)}`);
|
||||
const results = await this.prismaRepository.messageUpdate.findMany({
|
||||
where: {
|
||||
instanceId: this.instanceId,
|
||||
remoteJid: query.where?.remoteJid,
|
||||
@ -619,9 +670,12 @@ export class ChannelStartupService {
|
||||
skip: query.offset * (query?.page === 1 ? 0 : (query?.page as number) - 1),
|
||||
take: query.offset,
|
||||
});
|
||||
this.logger.debug(`[fetchStatusMessage] Retornando ${results.length} atualização(ões) de status.`);
|
||||
return results;
|
||||
}
|
||||
|
||||
public async fetchChats(query: any) {
|
||||
this.logger.debug(`[fetchChats] Buscando chats. Query: ${JSON.stringify(query)}`);
|
||||
const remoteJid = query?.where?.remoteJid
|
||||
? query?.where?.remoteJid.includes('@')
|
||||
? query.where?.remoteJid
|
||||
@ -632,77 +686,78 @@ export class ChannelStartupService {
|
||||
|
||||
if (!remoteJid) {
|
||||
results = await this.prismaRepository.$queryRaw`
|
||||
SELECT
|
||||
"Chat"."id",
|
||||
"Chat"."remoteJid",
|
||||
"Chat"."name",
|
||||
"Chat"."labels",
|
||||
"Chat"."createdAt",
|
||||
"Chat"."updatedAt",
|
||||
"Contact"."pushName",
|
||||
"Contact"."profilePicUrl",
|
||||
"Chat"."unreadMessages",
|
||||
(ARRAY_AGG("Message"."id" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_id,
|
||||
(ARRAY_AGG("Message"."key" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_key,
|
||||
(ARRAY_AGG("Message"."pushName" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_push_name,
|
||||
(ARRAY_AGG("Message"."participant" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_participant,
|
||||
(ARRAY_AGG("Message"."messageType" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message_type,
|
||||
(ARRAY_AGG("Message"."message" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message,
|
||||
(ARRAY_AGG("Message"."contextInfo" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_context_info,
|
||||
(ARRAY_AGG("Message"."source" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_source,
|
||||
(ARRAY_AGG("Message"."messageTimestamp" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message_timestamp,
|
||||
(ARRAY_AGG("Message"."instanceId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_instance_id,
|
||||
(ARRAY_AGG("Message"."sessionId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_session_id,
|
||||
(ARRAY_AGG("Message"."status" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_status
|
||||
FROM "Chat"
|
||||
LEFT JOIN "Message" ON "Message"."messageType" != 'reactionMessage' and "Message"."key"->>'remoteJid' = "Chat"."remoteJid"
|
||||
LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid"
|
||||
WHERE
|
||||
"Chat"."instanceId" = ${this.instanceId}
|
||||
GROUP BY
|
||||
"Chat"."id",
|
||||
"Chat"."remoteJid",
|
||||
"Contact"."id"
|
||||
ORDER BY last_message_message_timestamp DESC NULLS LAST, "Chat"."updatedAt" DESC;
|
||||
`;
|
||||
SELECT
|
||||
"Chat"."id",
|
||||
"Chat"."remoteJid",
|
||||
"Chat"."name",
|
||||
"Chat"."labels",
|
||||
"Chat"."createdAt",
|
||||
"Chat"."updatedAt",
|
||||
"Contact"."pushName",
|
||||
"Contact"."profilePicUrl",
|
||||
"Chat"."unreadMessages",
|
||||
(ARRAY_AGG("Message"."id" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_id,
|
||||
(ARRAY_AGG("Message"."key" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_key,
|
||||
(ARRAY_AGG("Message"."pushName" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_push_name,
|
||||
(ARRAY_AGG("Message"."participant" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_participant,
|
||||
(ARRAY_AGG("Message"."messageType" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message_type,
|
||||
(ARRAY_AGG("Message"."message" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message,
|
||||
(ARRAY_AGG("Message"."contextInfo" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_context_info,
|
||||
(ARRAY_AGG("Message"."source" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_source,
|
||||
(ARRAY_AGG("Message"."messageTimestamp" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message_timestamp,
|
||||
(ARRAY_AGG("Message"."instanceId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_instance_id,
|
||||
(ARRAY_AGG("Message"."sessionId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_session_id,
|
||||
(ARRAY_AGG("Message"."status" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_status
|
||||
FROM "Chat"
|
||||
LEFT JOIN "Message" ON "Message"."messageType" != 'reactionMessage' and "Message"."key"->>'remoteJid' = "Chat"."remoteJid"
|
||||
LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid"
|
||||
WHERE
|
||||
"Chat"."instanceId" = ${this.instanceId}
|
||||
GROUP BY
|
||||
"Chat"."id",
|
||||
"Chat"."remoteJid",
|
||||
"Contact"."id"
|
||||
ORDER BY last_message_message_timestamp DESC NULLS LAST, "Chat"."updatedAt" DESC;
|
||||
`;
|
||||
} else {
|
||||
results = await this.prismaRepository.$queryRaw`
|
||||
SELECT
|
||||
"Chat"."id",
|
||||
"Chat"."remoteJid",
|
||||
"Chat"."name",
|
||||
"Chat"."labels",
|
||||
"Chat"."createdAt",
|
||||
"Chat"."updatedAt",
|
||||
"Contact"."pushName",
|
||||
"Contact"."profilePicUrl",
|
||||
"Chat"."unreadMessages",
|
||||
(ARRAY_AGG("Message"."id" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_id,
|
||||
(ARRAY_AGG("Message"."key" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_key,
|
||||
(ARRAY_AGG("Message"."pushName" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_push_name,
|
||||
(ARRAY_AGG("Message"."participant" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_participant,
|
||||
(ARRAY_AGG("Message"."messageType" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message_type,
|
||||
(ARRAY_AGG("Message"."message" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message,
|
||||
(ARRAY_AGG("Message"."contextInfo" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_context_info,
|
||||
(ARRAY_AGG("Message"."source" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_source,
|
||||
(ARRAY_AGG("Message"."messageTimestamp" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message_timestamp,
|
||||
(ARRAY_AGG("Message"."instanceId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_instance_id,
|
||||
(ARRAY_AGG("Message"."sessionId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_session_id,
|
||||
(ARRAY_AGG("Message"."status" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_status
|
||||
FROM "Chat"
|
||||
LEFT JOIN "Message" ON "Message"."messageType" != 'reactionMessage' and "Message"."key"->>'remoteJid' = "Chat"."remoteJid"
|
||||
LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid"
|
||||
WHERE
|
||||
"Chat"."instanceId" = ${this.instanceId} AND "Chat"."remoteJid" = ${remoteJid} and "Message"."messageType" != 'reactionMessage'
|
||||
GROUP BY
|
||||
"Chat"."id",
|
||||
"Chat"."remoteJid",
|
||||
"Contact"."id"
|
||||
ORDER BY last_message_message_timestamp DESC NULLS LAST, "Chat"."updatedAt" DESC;
|
||||
`;
|
||||
SELECT
|
||||
"Chat"."id",
|
||||
"Chat"."remoteJid",
|
||||
"Chat"."name",
|
||||
"Chat"."labels",
|
||||
"Chat"."createdAt",
|
||||
"Chat"."updatedAt",
|
||||
"Contact"."pushName",
|
||||
"Contact"."profilePicUrl",
|
||||
"Chat"."unreadMessages",
|
||||
(ARRAY_AGG("Message"."id" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_id,
|
||||
(ARRAY_AGG("Message"."key" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_key,
|
||||
(ARRAY_AGG("Message"."pushName" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_push_name,
|
||||
(ARRAY_AGG("Message"."participant" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_participant,
|
||||
(ARRAY_AGG("Message"."messageType" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message_type,
|
||||
(ARRAY_AGG("Message"."message" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message,
|
||||
(ARRAY_AGG("Message"."contextInfo" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_context_info,
|
||||
(ARRAY_AGG("Message"."source" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_source,
|
||||
(ARRAY_AGG("Message"."messageTimestamp" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message_timestamp,
|
||||
(ARRAY_AGG("Message"."instanceId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_instance_id,
|
||||
(ARRAY_AGG("Message"."sessionId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_session_id,
|
||||
(ARRAY_AGG("Message"."status" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_status
|
||||
FROM "Chat"
|
||||
LEFT JOIN "Message" ON "Message"."messageType" != 'reactionMessage' and "Message"."key"->>'remoteJid' = "Chat"."remoteJid"
|
||||
LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid"
|
||||
WHERE
|
||||
"Chat"."instanceId" = ${this.instanceId} AND "Chat"."remoteJid" = ${remoteJid} and "Message"."messageType" != 'reactionMessage'
|
||||
GROUP BY
|
||||
"Chat"."id",
|
||||
"Chat"."remoteJid",
|
||||
"Contact"."id"
|
||||
ORDER BY last_message_message_timestamp DESC NULLS LAST, "Chat"."updatedAt" DESC;
|
||||
`;
|
||||
}
|
||||
|
||||
if (results && isArray(results) && results.length > 0) {
|
||||
this.logger.debug(`[fetchChats] Retornando ${results.length} chat(s).`);
|
||||
return results.map((chat) => {
|
||||
return {
|
||||
id: chat.id,
|
||||
@ -734,6 +789,7 @@ export class ChannelStartupService {
|
||||
});
|
||||
}
|
||||
|
||||
this.logger.debug('[fetchChats] Nenhum chat encontrado.');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
@ -136,7 +136,7 @@ export class Logger {
|
||||
this.console(value, Type.WARN);
|
||||
}
|
||||
|
||||
public error(value: any) {
|
||||
public error(value: any, p0?: { message: any; stack: any; }) {
|
||||
this.console(value, Type.ERROR);
|
||||
}
|
||||
|
||||
@ -144,7 +144,7 @@ export class Logger {
|
||||
this.console(value, Type.VERBOSE);
|
||||
}
|
||||
|
||||
public debug(value: any) {
|
||||
public debug(value: any, p0?: { config: any; }) {
|
||||
this.console(value, Type.DEBUG);
|
||||
}
|
||||
|
||||
|
11
src/main.ts
11
src/main.ts
@ -20,18 +20,25 @@ function initWA() {
|
||||
|
||||
async function bootstrap() {
|
||||
const logger = new Logger('SERVER');
|
||||
const app = express();
|
||||
const dsn = process.env.SENTRY_DSN;
|
||||
|
||||
// 1) Inicializa o Sentry aqui
|
||||
if (dsn) {
|
||||
logger.info('Sentry - ON');
|
||||
Sentry.init({
|
||||
dsn: dsn,
|
||||
dsn,
|
||||
environment: process.env.NODE_ENV || 'development',
|
||||
tracesSampleRate: 1.0,
|
||||
profilesSampleRate: 1.0,
|
||||
});
|
||||
}
|
||||
|
||||
// 2) Depois disso, crie o app
|
||||
const app = express();
|
||||
|
||||
// Se quiser instrumentar o Express, chame aqui
|
||||
// (garantindo que app já foi declarado)
|
||||
if (dsn) {
|
||||
Sentry.setupExpressErrorHandler(app);
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user