Compare commits

..

62 Commits
1.5.1 ... 1.5.4

Author SHA1 Message Date
Davidson Gomes
8fe75cd210 Merge branch 'release/1.5.4' 2023-10-09 20:43:40 -03:00
Davidson Gomes
303effebbc version: 1.5.4 2023-10-09 20:43:30 -03:00
Davidson Gomes
f32a34190d fix: adjusts logger 2023-10-09 20:17:01 -03:00
Davidson Gomes
8588ef1d8a fix: adjusts logger 2023-10-09 20:15:53 -03:00
Davidson Gomes
51ec4821f3 fix: adjusts logger 2023-10-09 20:14:50 -03:00
Davidson Gomes
957033a7bb ajustes 2023-10-09 19:57:26 -03:00
Davidson Gomes
62c74deac3 fix: Solved problem with duplicate messages in chatwoot 2023-10-09 18:00:14 -03:00
Davidson Gomes
29fd448998 Merge tag '1.5.3' into develop
* Swagger documentation
* Added base 64 sending option via webhook

* Remove rabbitmq queues when delete instances
* Improvement in restart instance to completely redo the connection
* Update node version: v20
* Correction of messages sent by the api and typebot not appearing in chatwoot
* Adjustment to start typebot, added startSession parameter
* Chatwoot now receives messages sent via api and typebot
* Fixed problem with starting with an input in typebot
* Added check to ensure variables are not empty before executing foreach in start typebot
2023-10-06 18:55:52 -03:00
Davidson Gomes
e55cb08a6a Merge branch 'release/1.5.3' 2023-10-06 18:55:44 -03:00
Davidson Gomes
047359e8dc version: 1.5.3 2023-10-06 18:55:36 -03:00
Davidson Gomes
eb814e181a adjusts in swagger 2023-10-06 18:45:26 -03:00
Davidson Gomes
857031ff5a adjusts in swagger 2023-10-06 18:05:37 -03:00
Davidson Gomes
d5eeb68714 feat: webhook base64 option 2023-10-05 17:05:41 -03:00
Davidson Gomes
966b287026 feat: webhook base64 option 2023-10-05 16:01:47 -03:00
Davidson Gomes
a348729109 Merge branch 'develop' of github.com:EvolutionAPI/evolution-api into develop 2023-10-05 15:59:59 -03:00
Davidson Gomes
1f29b7733e Merge pull request #163 from w3nder/develop
Fix: Variables null
2023-10-05 15:59:39 -03:00
Davidson Gomes
e26ae30f6f feat: webhook base64 option 2023-10-05 15:57:53 -03:00
Davidson Gomes
547943a05c Merge branch 'develop' of github.com:EvolutionAPI/evolution-api into develop 2023-10-05 15:54:53 -03:00
Davidson Gomes
46aa229531 fix: adjusts in swagger 2023-10-05 15:54:46 -03:00
Davidson Gomes
28bd796289 Merge pull request #161 from moraisamilton/develop
Recuperar base64 de media enviada por webhook
2023-10-05 15:54:20 -03:00
Wender Teixeira
6a3f82ed7e Fix: Variables null 2023-10-05 11:43:18 -03:00
Amilton Morais
523f3301c0 Update wa.types.ts
Foi criado novas propriedades para recuperar Base64 da media enviada por webhook.
2023-10-03 17:20:14 -03:00
Amilton Morais
f085343a99 Update whatsapp.service.ts
Foi criado novo código para recuperar Base64 da media enviada por webhook.
2023-10-03 17:18:58 -03:00
Amilton Morais
f76a924700 Update webhook.service.ts
Foi criado novo variavel "webhook_base64:false' para retorno erro.
2023-10-03 17:13:58 -03:00
Amilton Morais
f8e3b76a4a Update webhook.model.ts
Foi criado novas propriedades para recuperar Base64 da media enviada por webhook.
2023-10-03 16:59:06 -03:00
Amilton Morais
b8f1e8a7ef Update instance.dto.ts
Foi criado novas propriedades "webhook_base64?: boolean;" para recuperar Base64 da media enviada por webhook.
2023-10-03 16:56:44 -03:00
Amilton Morais
d007fc49d8 Update instance.controller.ts
Foi criado novas propriedades para recuperar Base64 da media enviada por webhook.
2023-10-03 16:45:05 -03:00
Amilton Morais
f6d8ebd8d3 Update dev-env.yml
Inserido nova variável WEBHOOK_BASE64 para recuperar Base64 da media enviar por webhook.
2023-10-03 16:39:04 -03:00
Davidson Gomes
6ff9c4578a Fixed problem with starting with an input in typebot 2023-10-02 18:23:03 -03:00
Davidson Gomes
33acfe1464 chatwoot now receives messages sent via api and typebot 2023-10-02 17:59:54 -03:00
Davidson Gomes
f5eeb16bb1 Adjustment to start typebot, added startSession parameter 2023-10-02 17:05:22 -03:00
Davidson Gomes
c35c5faaa4 correction of messages sent by the api and typebot not appearing in chatwoot 2023-10-02 16:17:28 -03:00
Davidson Gomes
8425ebc13f Merge pull request #156 from EvolutionAPI/revert-154-evolution-api-1.5.2-develop-francis
Revert "Start Typebot com opção de ativar chatbot ou não"
2023-10-02 16:10:45 -03:00
Davidson Gomes
6fc37a4298 Revert "Start Typebot com opção de ativar chatbot ou não" 2023-10-02 19:10:34 +00:00
Davidson Gomes
99f3e77c12 Merge pull request #154 from francisbreit/evolution-api-1.5.2-develop-francis
Start Typebot com opção de ativar chatbot ou não
2023-10-02 16:10:29 -03:00
Davidson Gomes
a9c087c45f correction of messages sent by the api and typebot not appearing in chatwoot 2023-10-02 16:10:04 -03:00
Francis Breit
3f4333087f Start Typebot com opção de ativar chatbot ou não
Foi criada a variável enabled_typebot (não obrigatória)
enabled_typebot igual a true ou vazio: o comportamento do "startTypebot" atua como a nova funcionalidadede sessões persistentes (v1.5.2) onde o flow do Typebot disparado atua como chatbot.
enabled_typebot igual a false: o comportamento do "startTypebot" atua como era na Evolution v.1.5.1 onde o flow do Typebot disparado atua como mensagem simples, nao ativa o chatbot e funciona apenas como mensagens simples.
Obs1: Se setada como true ou se for omitida essa variável no comando start Typebot, enabled_typebot será assumida como true, ou seja, start typebot aciona o flow com o chatbot ativado, imediatamente após o envio, aguardando interação do contato.. Se, antes do acionamento do start typebot, tiver um outro chatbot ativo, o mesmo será substituído pelo novo, ora enviado.
Obs2: Se setada como false, dispara apenas como notificação e não ativa o bot. se tiver outro bot ativo na instancia o mesmo continuará ativo, após disparada a mensagem
2023-10-02 11:56:24 -03:00
Davidson Gomes
e1ac29683d wip: swagger 2023-10-02 09:24:53 -03:00
Davidson Gomes
5c74cbfe19 improvement in restart instance to completely redo the connection 2023-09-30 16:36:32 -03:00
Davidson Gomes
3fdb3fa673 fix: Remove rabbitmq queues when delete instances 2023-09-30 07:20:57 -03:00
Davidson Gomes
ba584974cb Merge tag '1.5.2' into develop
v
2023-09-28 17:58:59 -03:00
Davidson Gomes
bddd6408ac Merge branch 'release/1.5.2' 2023-09-28 17:58:55 -03:00
Davidson Gomes
413ad66a07 version: 1.5.2 2023-09-28 17:58:37 -03:00
Davidson Gomes
0ef5d884cc version: 1.5.2 2023-09-28 17:56:47 -03:00
Davidson Gomes
f6b6d23e93 Merge pull request #133 from francisbreit/fetch-instances
Correção de nao recebimento de midias armazenadas mo minio/s3 Update whatsapp.service.ts
2023-09-28 17:47:17 -03:00
Davidson Gomes
50be69f3d3 Merge pull request #132 from IsraelXabregas/chatwoot-model-fix-schema-db
Fix chatwootSchema in chatwoot model to store reopen_conversation and conversation_pending options
2023-09-28 17:45:13 -03:00
Davidson Gomes
5a75e4d5e6 Merge pull request #131 from matheuskshn/develop
Melhoria no método "startTypebot" para criar sessão persistente quando acionado
2023-09-28 17:44:00 -03:00
Davidson Gomes
ec463df9d6 Merge pull request #126 from francisbreit/main
Novo manager para Evo 1.5.1 - atualização Set Typebot
2023-09-28 17:42:06 -03:00
Francis Breit
b648334323 Corrigir nao recebimento de midias minio/s3 - finalizado- Update whatsapp.service.tsUpdate whatsapp.service.ts
Correção nao recebimento de midias com urls do minio/s3 .
Urls sem o nome da extensão da midia impediam o envio das mensagens por erro na detecção do mimetype.
Imagem e Video
2023-09-26 14:15:50 -03:00
Francis Breit
916972aeb1 Update whatsapp.service.ts 2023-09-26 13:52:11 -03:00
Francis Breit
3893e01af9 Corrigir nao recebimento de midias minio/s3 Update whatsapp.service.ts
Correção nao recebimento de midias com urls do minio/s3 .
Urls sem o nome da extensão da midia impediam o envio das mensagens por erro na detecção do mimetype.
2023-09-26 13:27:58 -03:00
Israel Xabregas Ramos
7835f32c8b Fix chatwootSchema in chatwoot model to store reopen_conversation and conversation_pending options 2023-09-25 20:45:14 -03:00
Matheus Gomes
37302244ee Update typebot.service.ts 2023-09-25 16:37:43 -03:00
Matheus Gomes
f1be7ddb83 Update typebot.service.ts 2023-09-25 16:22:41 -03:00
Matheus Gomes
7447a65a83 Update typebot.service.ts 2023-09-25 16:05:18 -03:00
Matheus Gomes
129009d602 Update typebot.service.ts 2023-09-25 15:55:12 -03:00
Matheus Gomes
c656bd6f4b Enhancement of Session Initialization in "StartTypebot" Function
Enhanced "StartTypebot" to initialize sessionIDs during the initial interaction, improving user experience on WhatsApp and preventing unexpected bot restarts.
2023-09-25 02:38:37 -03:00
Francis Breit
36528d7484 Inclusão de Listening From Me no est Typebot Update manager.json
Correção e inclusão de Listening From Me
2023-09-22 13:28:29 -03:00
Francis Breit
f9c85b6a67 Novo manager para Evo 1.5.1 - atualização Set Typebot
Incluída a opção da variável listening_from_me do Set Typebot
2023-09-21 10:04:00 -03:00
Davidson Gomes
4dfe6bdbe8 Merge pull request #122 from francisbreit/fetch-instances
Update monitor.service.ts - Evolution ap i 1.5.1 - Problemas ao ler / consultar instancias (FETCH_INSTANCES)
2023-09-20 15:09:28 -03:00
Francis Breit
ee343f2fa1 Update monitor.service.ts
Evolution ap i 1.5.1 - Problemas ao ler / consultar instancias (FETCH_INSTANCES)

Ao consultar instancias as mesmas nao apareciam, seja via manager, seja via postman
2023-09-20 11:13:43 -03:00
Davidson Gomes
1a1f5f85b2 Merge tag '1.5.1' into develop
* Added listening_from_me option in Set Typebot
* Added variables options in Start Typebot
* Added webhooks for typebot events
* Added ChamaAI integration
* Added webhook to send errors
* Added support for messaging with ads on chatwoot

* Fix looping connection messages in chatwoot
* Improved performance of fetch instances
2023-09-17 13:55:02 -03:00
27 changed files with 3237 additions and 104 deletions

View File

@@ -1,3 +1,38 @@
# 1.5.4 (2023-10-09 20:43)
### Fixed
* Baileys logger typing issue resolved
* Solved problem with duplicate messages in chatwoot
# 1.5.3 (2023-10-06 18:55)
### Feature
* Swagger documentation
* Added base 64 sending option via webhook
### Fixed
* Remove rabbitmq queues when delete instances
* Improvement in restart instance to completely redo the connection
* Update node version: v20
* Correction of messages sent by the api and typebot not appearing in chatwoot
* Adjustment to start typebot, added startSession parameter
* Chatwoot now receives messages sent via api and typebot
* Fixed problem with starting with an input in typebot
* Added check to ensure variables are not empty before executing foreach in start typebot
# 1.5.2 (2023-09-28 17:56)
### Fixed
* Fix chatwootSchema in chatwoot model to store reopen_conversation and conversation_pending options
* Problem resolved when sending files from minio to typebot
* Improvement in the "startTypebot" method to create persistent session when triggered
* New manager for Evo 1.5.2 - Set Typebot update
* Resolved problems when reading/querying instances
# 1.5.1 (2023-09-17 13:50)
### Feature

View File

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

File diff suppressed because one or more lines are too long

View File

@@ -1,6 +1,6 @@
{
"name": "evolution-api",
"version": "1.5.1",
"version": "1.5.4",
"description": "Rest api for communication with WhatsApp",
"main": "./dist/src/main.js",
"scripts": {
@@ -46,7 +46,7 @@
"@figuro/chatwoot-sdk": "^1.1.16",
"@hapi/boom": "^10.0.1",
"@sentry/node": "^7.59.2",
"@whiskeysockets/baileys": "^6.4.0",
"@whiskeysockets/baileys": "^6.5.0",
"amqplib": "^0.10.3",
"axios": "^1.3.5",
"class-validator": "^0.13.2",
@@ -78,8 +78,9 @@
"sharp": "^0.30.7",
"socket.io": "^4.7.1",
"socks-proxy-agent": "^8.0.1",
"swagger-ui-express": "^5.0.0",
"uuid": "^9.0.0",
"whatsapp-web.js": "^1.22.1"
"yamljs": "^0.3.0"
},
"devDependencies": {
"@types/compression": "^1.7.2",

View File

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

17
src/docs/swagger.conf.ts Normal file
View File

@@ -0,0 +1,17 @@
import { Router } from 'express';
import { join } from 'path';
import swaggerUi from 'swagger-ui-express';
import YAML from 'yamljs';
const document = YAML.load(join(process.cwd(), 'src', 'docs', 'swagger.yaml'));
const router = Router();
export const swaggerRouter = router.use('/docs', swaggerUi.serve).get(
'/docs',
swaggerUi.setup(document, {
customCssUrl: '/css/dark-theme-swagger.css',
customSiteTitle: 'Evolution API',
customfavIcon: '/images/logo.svg',
}),
);

2597
src/docs/swagger.yaml Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -71,3 +71,30 @@ export const initQueues = (instanceName: string, events: string[]) => {
amqp.bindQueue(queueName, exchangeName, event);
});
};
export const removeQueues = (instanceName: string, events: string[]) => {
if (!events || !events.length) return;
const channel = getAMQP();
const queues = events.map((event) => {
return `${event.replace(/_/g, '.').toLowerCase()}`;
});
const exchangeName = instanceName ?? 'evolution_exchange';
queues.forEach((event) => {
const amqp = getAMQP();
amqp.assertExchange(exchangeName, 'topic', {
durable: true,
autoDelete: false,
});
const queueName = `${instanceName}.${event}`;
amqp.deleteQueue(queueName);
});
channel.deleteExchange(exchangeName);
};

View File

@@ -10,6 +10,7 @@ import { Auth, configService, Cors, HttpServer, Rabbitmq, Webhook } from './conf
import { onUnexpectedError } from './config/error.config';
import { Logger } from './config/logger.config';
import { ROOT_DIR } from './config/path.config';
import { swaggerRouter } from './docs/swagger.conf';
import { initAMQP } from './libs/amqp.server';
import { initIO } from './libs/socket.server';
import { ServerUP } from './utils/server-up';
@@ -51,6 +52,7 @@ function bootstrap() {
app.use('/store', express.static(join(ROOT_DIR, 'store')));
app.use('/', router);
app.use(swaggerRouter);
app.use(
(err: Error, req: Request, res: Response, next: NextFunction) => {

View File

@@ -41,6 +41,7 @@ export class InstanceController {
instanceName,
webhook,
webhook_by_events,
webhook_base64,
events,
qrcode,
number,
@@ -139,6 +140,7 @@ export class InstanceController {
url: webhook,
events: newEvents,
webhook_by_events,
webhook_base64,
});
webhookEvents = (await this.webhookService.find(instance)).events;
@@ -297,6 +299,7 @@ export class InstanceController {
webhook: {
webhook,
webhook_by_events,
webhook_base64,
events: webhookEvents,
},
websocket: {
@@ -390,6 +393,7 @@ export class InstanceController {
webhook: {
webhook,
webhook_by_events,
webhook_base64,
events: webhookEvents,
},
websocket: {
@@ -475,10 +479,19 @@ export class InstanceController {
try {
this.logger.verbose('requested restartInstance from ' + instanceName + ' instance');
this.logger.verbose('logging out instance: ' + instanceName);
this.waMonitor.waInstances[instanceName]?.client?.ws?.close();
const instance = this.waMonitor.waInstances[instanceName];
const state = instance?.connectionStatus?.state;
return { status: 'SUCCESS', error: false, response: { message: 'Instance restarted' } };
switch (state) {
case 'open':
this.logger.verbose('logging out instance: ' + instanceName);
await instance.reloadConnection();
await delay(2000);
return await this.connectionState({ instanceName });
default:
return await this.connectionState({ instanceName });
}
} catch (error) {
this.logger.error(error);
}
@@ -534,6 +547,8 @@ export class InstanceController {
throw new BadRequestException('The "' + instanceName + '" instance needs to be disconnected');
}
try {
this.waMonitor.waInstances[instanceName]?.removeRabbitmqQueues();
if (instance.state === 'connecting') {
this.logger.verbose('logging out instance: ' + instanceName);

View File

@@ -1,15 +1,21 @@
import { Request, Response } from 'express';
import { ConfigService } from '../../config/env.config';
import { Auth, ConfigService, HttpServer } from '../../config/env.config';
import { HttpStatus } from '../routers/index.router';
import { WAMonitoringService } from '../services/monitor.service';
export class ViewsController {
constructor(private readonly waMonit: WAMonitoringService, private readonly configService: ConfigService) {}
constructor(private readonly waMonitor: WAMonitoringService, private readonly configService: ConfigService) {}
public async manager(request: Request, response: Response) {
try {
return response.status(HttpStatus.OK).render('manager');
const token = this.configService.get<Auth>('AUTHENTICATION').API_KEY.KEY;
const port = this.configService.get<HttpServer>('SERVER').PORT;
const instances = await this.waMonitor.instanceInfo();
console.log('INSTANCES: ', instances);
return response.status(HttpStatus.OK).render('manager', { token, port, instances });
} catch (error) {
console.log('ERROR: ', error);
}

View File

@@ -5,6 +5,7 @@ export class InstanceDto {
token?: string;
webhook?: string;
webhook_by_events?: boolean;
webhook_base64?: boolean;
events?: string[];
reject_call?: boolean;
msg_call?: string;

View File

@@ -4,6 +4,13 @@ export class Session {
status?: string;
createdAt?: number;
updateAt?: number;
prefilledVariables?: PrefilledVariables;
}
export class PrefilledVariables {
remoteJid?: string;
pushName?: string;
additionalData?: { [key: string]: any };
}
export class TypebotDto {

View File

@@ -3,4 +3,5 @@ export class WebhookDto {
url?: string;
events?: string[];
webhook_by_events?: boolean;
webhook_base64?: boolean;
}

View File

@@ -65,6 +65,7 @@ export async function instanceLoggedGuard(req: Request, _: Response, next: NextF
}
if (waMonitor.waInstances[instance.instanceName]) {
waMonitor.waInstances[instance.instanceName]?.removeRabbitmqQueues();
delete waMonitor.waInstances[instance.instanceName];
}
}

View File

@@ -24,6 +24,8 @@ const chatwootSchema = new Schema<ChatwootRaw>({
name_inbox: { type: String, required: true },
sign_msg: { type: Boolean, required: true },
number: { type: String, required: true },
reopen_conversation: { type: Boolean, required: true },
conversation_pending: { type: Boolean, required: true },
});
export const ChatwootModel = dbserver?.model(ChatwootRaw.name, chatwootSchema, 'chatwoot');

View File

@@ -8,6 +8,11 @@ class Session {
status?: string;
createdAt?: number;
updateAt?: number;
prefilledVariables?: {
remoteJid?: string;
pushName?: string;
additionalData?: { [key: string]: any };
};
}
export class TypebotRaw {
@@ -40,6 +45,11 @@ const typebotSchema = new Schema<TypebotRaw>({
status: { type: String, required: true },
createdAt: { type: Number, required: true },
updateAt: { type: Number, required: true },
prefilledVariables: {
remoteJid: { type: String, required: false },
pushName: { type: String, required: false },
additionalData: { type: Schema.Types.Mixed, required: false },
},
},
],
});

View File

@@ -8,6 +8,7 @@ export class WebhookRaw {
enabled?: boolean;
events?: string[];
webhook_by_events?: boolean;
webhook_base64?: boolean;
}
const webhookSchema = new Schema<WebhookRaw>({
@@ -16,6 +17,7 @@ const webhookSchema = new Schema<WebhookRaw>({
enabled: { type: Boolean, required: true },
events: { type: [String], required: true },
webhook_by_events: { type: Boolean, required: true },
webhook_base64: { type: Boolean, required: true },
});
export const WebhookModel = dbserver?.model(WebhookRaw.name, webhookSchema, 'webhook');

View File

@@ -40,6 +40,7 @@ router
status: HttpStatus.OK,
message: 'Welcome to the Evolution API, it is working!',
version: packageJson.version,
documentation: `${req.protocol}://${req.get('host')}/docs`,
});
})
.use('/instance', new InstanceRouter(configService, ...guards).router)

View File

@@ -914,7 +914,7 @@ export class ChatwootService {
},
};
await waInstance?.audioWhatsapp(data);
await waInstance?.audioWhatsapp(data, true);
this.logger.verbose('audio sent');
return;
@@ -939,7 +939,7 @@ export class ChatwootService {
data.mediaMessage.caption = caption;
}
await waInstance?.mediaMessage(data);
await waInstance?.mediaMessage(data, true);
this.logger.verbose('media sent');
return;
@@ -1074,7 +1074,7 @@ export class ChatwootService {
},
};
await waInstance?.textMessage(data);
await waInstance?.textMessage(data, true);
}
}
}
@@ -1132,7 +1132,7 @@ export class ChatwootService {
thumbnailUrl: string;
sourceUrl: string;
}
const adsMessage: AdsMessage | undefined = msg.extendedTextMessage?.contextInfo.externalAdReply;
const adsMessage: AdsMessage | undefined = msg.extendedTextMessage?.contextInfo?.externalAdReply;
this.logger.verbose('Get ads message if it exist');
adsMessage && this.logger.verbose('Ads message: ' + adsMessage);
@@ -1279,7 +1279,7 @@ export class ChatwootService {
return null;
}
if (event === 'messages.upsert') {
if (event === 'messages.upsert' || event === 'send.message') {
this.logger.verbose('event messages.upsert');
if (body.key.remoteJid === 'status@broadcast') {

View File

@@ -7,6 +7,7 @@ import { join } from 'path';
import { Auth, ConfigService, Database, DelInstance, HttpServer, Redis } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config';
import { NotFoundException } from '../../exceptions';
import { dbserver } from '../../libs/db.connect';
import { RedisCache } from '../../libs/redis.client';
import {
@@ -63,8 +64,10 @@ export class WAMonitoringService {
await this.waInstances[instance]?.client?.logout('Log out instance: ' + instance);
this.waInstances[instance]?.client?.ws?.close();
this.waInstances[instance]?.client?.end(undefined);
this.waInstances[instance]?.removeRabbitmqQueues();
delete this.waInstances[instance];
} else {
this.waInstances[instance]?.removeRabbitmqQueues();
delete this.waInstances[instance];
this.eventEmitter.emit('remove.instance', instance, 'inner');
}
@@ -75,57 +78,77 @@ export class WAMonitoringService {
public async instanceInfo(instanceName?: string) {
this.logger.verbose('get instance info');
if (instanceName && !this.waInstances[instanceName]) {
throw new NotFoundException(`Instance "${instanceName}" not found`);
}
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
const instances: any[] = [];
const instances: any[] = await Promise.all(
Object.entries(this.waInstances).map(async ([key, value]) => {
const status = value?.connectionStatus?.state || 'unknown';
for await (const [key, value] of Object.entries(this.waInstances)) {
if (value) {
this.logger.verbose('get instance info: ' + key);
let chatwoot: any;
if (status === 'unknown') {
return null;
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
const findChatwoot = await this.waInstances[key].findChatwoot();
if (findChatwoot && findChatwoot.enabled) {
chatwoot = {
...findChatwoot,
webhook_url: `${urlServer}/chatwoot/webhook/${encodeURIComponent(key)}`,
};
}
if (status === 'open') {
if (value.connectionStatus.state === 'open') {
this.logger.verbose('instance: ' + key + ' - connectionStatus: open');
}
const instanceData: any = {
instance: {
instanceName: key,
owner: value.wuid,
profileName: (await value.getProfileName()) || 'not loaded',
profilePictureUrl: value.profilePictureUrl,
profileStatus: (await value.getProfileStatus()) || '',
status: status,
},
};
const instanceData = {
instance: {
instanceName: key,
owner: value.wuid,
profileName: (await value.getProfileName()) || 'not loaded',
profilePictureUrl: value.profilePictureUrl,
profileStatus: (await value.getProfileStatus()) || '',
status: value.connectionStatus.state,
},
};
if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) {
instanceData.instance.serverUrl = urlServer;
instanceData.instance.apikey = (await this.repository.auth.find(key))?.apikey;
if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) {
instanceData.instance['serverUrl'] = this.configService.get<HttpServer>('SERVER').URL;
const findChatwoot = await this.waInstances[key].findChatwoot();
if (findChatwoot && findChatwoot.enabled) {
instanceData.instance.chatwoot = {
...findChatwoot,
webhook_url: `${urlServer}/chatwoot/webhook/${encodeURIComponent(key)}`,
};
instanceData.instance['apikey'] = (await this.repository.auth.find(key)).apikey;
instanceData.instance['chatwoot'] = chatwoot;
}
}
return instanceData;
}),
).then((results) => results.filter((instance) => instance !== null));
instances.push(instanceData);
} else {
this.logger.verbose('instance: ' + key + ' - connectionStatus: ' + value.connectionStatus.state);
const instanceData = {
instance: {
instanceName: key,
status: value.connectionStatus.state,
},
};
if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) {
instanceData.instance['serverUrl'] = this.configService.get<HttpServer>('SERVER').URL;
instanceData.instance['apikey'] = (await this.repository.auth.find(key)).apikey;
instanceData.instance['chatwoot'] = chatwoot;
}
instances.push(instanceData);
}
}
}
this.logger.verbose('return instance info: ' + instances.length);
if (instanceName) {
const instance = instances.find((i) => i.instance.instanceName === instanceName);
return instance || [];
}
return instances;
return instances.find((i) => i.instance.instanceName === instanceName) ?? instances;
}
private delInstanceFiles() {

View File

@@ -99,43 +99,82 @@ export class TypebotService {
const remoteJid = data.remoteJid;
const url = data.url;
const typebot = data.typebot;
const startSession = data.startSession;
const variables = data.variables;
const findTypebot = await this.find(instance);
const sessions = (findTypebot.sessions as Session[]) ?? [];
const expire = findTypebot.expire;
const keyword_finish = findTypebot.keyword_finish;
const delay_message = findTypebot.delay_message;
const unknown_message = findTypebot.unknown_message;
const listening_from_me = findTypebot.listening_from_me;
const prefilledVariables = {
remoteJid: remoteJid,
instanceName: instance.instanceName,
};
variables.forEach((variable) => {
prefilledVariables[variable.name] = variable.value;
});
if (variables?.length) {
variables.forEach((variable: { name: string | number; value: string }) => {
prefilledVariables[variable.name] = variable.value;
});
}
const id = Math.floor(Math.random() * 10000000000).toString();
const reqData = {
sessionId: id,
startParams: {
typebot: data.typebot,
if (startSession) {
const response = await this.createNewSession(instance, {
url: url,
typebot: typebot,
remoteJid: remoteJid,
expire: expire,
keyword_finish: keyword_finish,
delay_message: delay_message,
unknown_message: unknown_message,
listening_from_me: listening_from_me,
sessions: sessions,
prefilledVariables: prefilledVariables,
},
};
});
const request = await axios.post(data.url + '/api/v1/sendMessage', reqData);
if (response.sessionId) {
await this.sendWAMessage(instance, remoteJid, response.messages, response.input, response.clientSideActions);
await this.sendWAMessage(
instance,
remoteJid,
request.data.messages,
request.data.input,
request.data.clientSideActions,
);
this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_START, {
remoteJid: remoteJid,
url: url,
typebot: typebot,
prefilledVariables: prefilledVariables,
sessionId: `${response.sessionId}`,
});
} else {
throw new Error('Session ID not found in response');
}
} else {
const id = Math.floor(Math.random() * 10000000000).toString();
this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_START, {
remoteJid: remoteJid,
url: url,
typebot: typebot,
variables: variables,
sessionId: id,
});
const reqData = {
startParams: {
typebot: data.typebot,
prefilledVariables: prefilledVariables,
},
};
const request = await axios.post(data.url + '/api/v1/sendMessage', reqData);
await this.sendWAMessage(
instance,
remoteJid,
request.data.messages,
request.data.input,
request.data.clientSideActions,
);
this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_START, {
remoteJid: remoteJid,
url: url,
typebot: typebot,
variables: variables,
sessionId: id,
});
}
return {
typebot: {
@@ -144,7 +183,7 @@ export class TypebotService {
url: url,
remoteJid: remoteJid,
typebot: typebot,
variables: variables,
prefilledVariables: prefilledVariables,
},
},
};
@@ -189,12 +228,12 @@ export class TypebotService {
public async createNewSession(instance: InstanceDto, data: any) {
const id = Math.floor(Math.random() * 10000000000).toString();
const reqData = {
sessionId: id,
startParams: {
typebot: data.typebot,
prefilledVariables: {
...data.prefilledVariables,
remoteJid: data.remoteJid,
pushName: data.pushName,
pushName: data.pushName || '',
instanceName: instance.instanceName,
},
},
@@ -209,6 +248,12 @@ export class TypebotService {
status: 'opened',
createdAt: Date.now(),
updateAt: Date.now(),
prefilledVariables: {
...data.prefilledVariables,
remoteJid: data.remoteJid,
pushName: data.pushName || '',
instanceName: instance.instanceName,
},
});
const typebotData = {
@@ -416,6 +461,62 @@ export class TypebotService {
await this.sendWAMessage(instance, remoteJid, data.messages, data.input, data.clientSideActions);
if (data.messages.length === 0) {
const content = this.getConversationMessage(msg.message);
if (!content) {
if (unknown_message) {
this.waMonitor.waInstances[instance.instanceName].textMessage({
number: remoteJid.split('@')[0],
options: {
delay: delay_message || 1000,
presence: 'composing',
},
textMessage: {
text: unknown_message,
},
});
}
return;
}
if (keyword_finish && content.toLowerCase() === keyword_finish.toLowerCase()) {
sessions.splice(sessions.indexOf(session), 1);
const typebotData = {
enabled: true,
url: url,
typebot: typebot,
expire: expire,
keyword_finish: keyword_finish,
delay_message: delay_message,
unknown_message: unknown_message,
listening_from_me: listening_from_me,
sessions,
};
this.create(instance, typebotData);
return;
}
const reqData = {
message: content,
sessionId: data.sessionId,
};
const request = await axios.post(url + '/api/v1/sendMessage', reqData);
console.log('request', request);
await this.sendWAMessage(
instance,
remoteJid,
request.data.messages,
request.data.input,
request.data.clientSideActions,
);
}
return;
}
}
@@ -440,6 +541,61 @@ export class TypebotService {
await this.sendWAMessage(instance, remoteJid, data.messages, data.input, data.clientSideActions);
if (data.messages.length === 0) {
const content = this.getConversationMessage(msg.message);
if (!content) {
if (unknown_message) {
this.waMonitor.waInstances[instance.instanceName].textMessage({
number: remoteJid.split('@')[0],
options: {
delay: delay_message || 1000,
presence: 'composing',
},
textMessage: {
text: unknown_message,
},
});
}
return;
}
if (keyword_finish && content.toLowerCase() === keyword_finish.toLowerCase()) {
sessions.splice(sessions.indexOf(session), 1);
const typebotData = {
enabled: true,
url: url,
typebot: typebot,
expire: expire,
keyword_finish: keyword_finish,
delay_message: delay_message,
unknown_message: unknown_message,
listening_from_me: listening_from_me,
sessions,
};
this.create(instance, typebotData);
return;
}
const reqData = {
message: content,
sessionId: data.sessionId,
};
const request = await axios.post(url + '/api/v1/sendMessage', reqData);
console.log('request', request);
await this.sendWAMessage(
instance,
remoteJid,
request.data.messages,
request.data.input,
request.data.clientSideActions,
);
}
return;
}
@@ -481,7 +637,7 @@ export class TypebotService {
return;
}
if (content.toLowerCase() === keyword_finish.toLowerCase()) {
if (keyword_finish && content.toLowerCase() === keyword_finish.toLowerCase()) {
sessions.splice(sessions.indexOf(session), 1);
const typebotData = {

View File

@@ -26,7 +26,7 @@ export class WebhookService {
return result;
} catch (error) {
return { enabled: false, url: '', events: [], webhook_by_events: false };
return { enabled: false, url: '', events: [], webhook_by_events: false, webhook_base64: false };
}
}
}

View File

@@ -66,7 +66,7 @@ import {
import { Logger } from '../../config/logger.config';
import { INSTANCE_DIR, ROOT_DIR } from '../../config/path.config';
import { BadRequestException, InternalServerErrorException, NotFoundException } from '../../exceptions';
import { getAMQP } from '../../libs/amqp.server';
import { getAMQP, removeQueues } from '../../libs/amqp.server';
import { dbserver } from '../../libs/db.connect';
import { RedisCache } from '../../libs/redis.client';
import { getIO } from '../../libs/socket.server';
@@ -276,6 +276,9 @@ export class WAStartupService {
this.localWebhook.webhook_by_events = data?.webhook_by_events;
this.logger.verbose(`Webhook by events: ${this.localWebhook.webhook_by_events}`);
this.localWebhook.webhook_base64 = data?.webhook_base64;
this.logger.verbose(`Webhook by webhook_base64: ${this.localWebhook.webhook_base64}`);
this.logger.verbose('Webhook loaded');
}
@@ -495,6 +498,14 @@ export class WAStartupService {
return data;
}
public async removeRabbitmqQueues() {
this.logger.verbose('Removing rabbitmq');
if (this.localRabbitmq.enabled) {
removeQueues(this.instanceName, this.localRabbitmq.events);
}
}
private async loadTypebot() {
this.logger.verbose('Loading typebot');
const data = await this.repository.typebot.find(this.instanceName);
@@ -1182,7 +1193,7 @@ export class WAStartupService {
...options,
auth: {
creds: this.instance.authState.state.creds,
keys: makeCacheableSignalKeyStore(this.instance.authState.state.keys, P({ level: 'error' })),
keys: makeCacheableSignalKeyStore(this.instance.authState.state.keys, P({ level: 'error' }) as any),
},
logger: P({ level: this.logBaileys }),
printQRInTerminal: false,
@@ -1240,6 +1251,74 @@ export class WAStartupService {
}
}
public async reloadConnection(): Promise<WASocket> {
try {
this.instance.authState = await this.defineAuthState();
const { version } = await fetchLatestBaileysVersion();
const session = this.configService.get<ConfigSessionPhone>('CONFIG_SESSION_PHONE');
const browser: WABrowserDescription = [session.CLIENT, session.NAME, release()];
let options;
if (this.localProxy.enabled) {
this.logger.verbose('Proxy enabled');
options = {
agent: new ProxyAgent(this.localProxy.proxy as any),
fetchAgent: new ProxyAgent(this.localProxy.proxy as any),
};
}
const socketConfig: UserFacingSocketConfig = {
...options,
auth: {
creds: this.instance.authState.state.creds,
keys: makeCacheableSignalKeyStore(this.instance.authState.state.keys, P({ level: 'error' }) as any),
},
logger: P({ level: this.logBaileys }),
printQRInTerminal: false,
browser,
version,
markOnlineOnConnect: this.localSettings.always_online,
connectTimeoutMs: 60_000,
qrTimeout: 40_000,
defaultQueryTimeoutMs: undefined,
emitOwnEvents: false,
msgRetryCounterCache: this.msgRetryCounterCache,
getMessage: async (key) => (await this.getMessage(key)) as Promise<proto.IMessage>,
generateHighQualityLinkPreview: true,
syncFullHistory: true,
userDevicesCache: this.userDevicesCache,
transactionOpts: { maxCommitRetries: 1, delayBetweenTriesMs: 10 },
patchMessageBeforeSending: (message) => {
const requiresPatch = !!(message.buttonsMessage || message.listMessage || message.templateMessage);
if (requiresPatch) {
message = {
viewOnceMessageV2: {
message: {
messageContextInfo: {
deviceListMetadataVersion: 2,
deviceListMetadata: {},
},
...message,
},
},
};
}
return message;
},
};
this.client = makeWASocket(socketConfig);
return this.client;
} catch (error) {
this.logger.error(error);
throw new InternalServerErrorException(error?.toString());
}
}
private readonly chatHandle = {
'chats.upsert': async (chats: Chat[], database: Database) => {
this.logger.verbose('Event received: chats.upsert');
@@ -1452,15 +1531,45 @@ export class WAStartupService {
return;
}
const messageRaw: MessageRaw = {
key: received.key,
pushName: received.pushName,
message: { ...received.message },
messageType: getContentType(received.message),
messageTimestamp: received.messageTimestamp as number,
owner: this.instance.name,
source: getDevice(received.key.id),
};
let messageRaw: MessageRaw;
if (
(this.localWebhook.webhook_base64 === true && received?.message.documentMessage) ||
received?.message.imageMessage
) {
const buffer = await downloadMediaMessage(
{ key: received.key, message: received?.message },
'buffer',
{},
{
logger: P({ level: 'error' }) as any,
reuploadRequest: this.client.updateMediaMessage,
},
);
console.log(buffer);
messageRaw = {
key: received.key,
pushName: received.pushName,
message: {
...received.message,
base64: buffer ? buffer.toString('base64') : undefined,
},
messageType: getContentType(received.message),
messageTimestamp: received.messageTimestamp as number,
owner: this.instance.name,
source: getDevice(received.key.id),
};
} else {
messageRaw = {
key: received.key,
pushName: received.pushName,
message: { ...received.message },
messageType: getContentType(received.message),
messageTimestamp: received.messageTimestamp as number,
owner: this.instance.name,
source: getDevice(received.key.id),
};
}
if (this.localSettings.read_messages && received.key.id !== 'status@broadcast') {
await this.client.readMessages([received.key]);
@@ -1952,7 +2061,12 @@ export class WAStartupService {
}
}
private async sendMessageWithTyping<T = proto.IMessage>(number: string, message: T, options?: Options) {
private async sendMessageWithTyping<T = proto.IMessage>(
number: string,
message: T,
options?: Options,
isChatwoot = false,
) {
this.logger.verbose('Sending message with typing');
this.logger.verbose(`Check if number "${number}" is WhatsApp`);
@@ -2110,7 +2224,7 @@ export class WAStartupService {
this.logger.verbose('Sending data to webhook in event SEND_MESSAGE');
await this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw);
if (this.localChatwoot.enabled) {
if (this.localChatwoot.enabled && !isChatwoot) {
this.chatwootService.eventWhatsapp(Events.SEND_MESSAGE, { instanceName: this.instance.name }, messageRaw);
}
@@ -2135,7 +2249,7 @@ export class WAStartupService {
}
// Send Message Controller
public async textMessage(data: SendTextDto) {
public async textMessage(data: SendTextDto, isChatwoot = false) {
this.logger.verbose('Sending text message');
return await this.sendMessageWithTyping(
data.number,
@@ -2143,6 +2257,7 @@ export class WAStartupService {
conversation: data.textMessage.text,
},
data?.options,
isChatwoot,
);
}
@@ -2419,11 +2534,11 @@ export class WAStartupService {
return result;
}
public async mediaMessage(data: SendMediaDto) {
public async mediaMessage(data: SendMediaDto, isChatwoot = false) {
this.logger.verbose('Sending media message');
const generate = await this.prepareMediaMessage(data.mediaMessage);
return await this.sendMessageWithTyping(data.number, { ...generate.message }, data?.options);
return await this.sendMessageWithTyping(data.number, { ...generate.message }, data?.options, isChatwoot);
}
public async processAudio(audio: string, number: string) {
@@ -2480,7 +2595,7 @@ export class WAStartupService {
});
}
public async audioWhatsapp(data: SendAudioDto) {
public async audioWhatsapp(data: SendAudioDto, isChatwoot = false) {
this.logger.verbose('Sending audio whatsapp');
if (!data.options?.encoding && data.options?.encoding !== false) {
@@ -2499,6 +2614,7 @@ export class WAStartupService {
mimetype: 'audio/mp4',
},
{ presence: 'recording', delay: data?.options?.delay },
isChatwoot,
);
fs.unlinkSync(convert);
@@ -2520,6 +2636,7 @@ export class WAStartupService {
mimetype: 'audio/ogg; codecs=opus',
},
{ presence: 'recording', delay: data?.options?.delay },
isChatwoot,
);
}
@@ -2700,6 +2817,7 @@ export class WAStartupService {
public async markMessageAsRead(data: ReadMessageDto) {
this.logger.verbose('Marking message as read');
try {
const keys: proto.IMessageKey[] = [];
data.read_messages.forEach((read) => {
@@ -2829,7 +2947,7 @@ export class WAStartupService {
'buffer',
{},
{
logger: P({ level: 'error' }),
logger: P({ level: 'error' }) as any,
reuploadRequest: this.client.updateMediaMessage,
},
);

View File

@@ -50,6 +50,7 @@ export declare namespace wa {
url?: string;
events?: string[];
webhook_by_events?: boolean;
webhook_base64?: boolean;
};
export type LocalChatwoot = {

110
views/manager-wip.hbs Normal file
View File

@@ -0,0 +1,110 @@
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="https://evolution-api.com/files/evolution-api-favicon.png" type="image/x-icon">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"
integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<title>Instance Manager</title>
</head>
<body>
<div class="container mt-4">
<!-- Botão para abrir o modal de adicionar nova instância -->
<button class="btn btn-primary mb-3" data-toggle="modal" data-target="#actionModal" data-action="add">Nova
Instância</button>
<!-- Tabela de instâncias -->
<table class="table table-bordered">
<thead>
<tr>
<th>Nome da Instância</th>
<th>Status</th>
<th>API Key</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
<!-- Iterando sobre as instâncias e preenchendo a tabela -->
{{#each instances}}
<tr>
<td>{{this.instance.instanceName}}</td>
<td>{{this.instance.status}}</td>
<td>{{this.instance.apikey}}</td>
<td>
<!-- Dropdown de ações para cada instância -->
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="actionDropdown"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Ações
</button>
<div class="dropdown-menu" aria-labelledby="actionDropdown">
<a class="dropdown-item" href="#" data-toggle="modal" data-target="#actionModal"
data-action="connect">Connect</a>
<a class="dropdown-item" href="#" data-toggle="modal" data-target="#actionModal"
data-action="restart">Restart</a>
<!-- Adicione mais itens de ação aqui -->
<!-- ... -->
</div>
</div>
</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
<!-- Modal de ações -->
<div class="modal fade" id="actionModal" tabindex="-1" role="dialog" aria-labelledby="actionModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="actionModalLabel">Ação</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
<button type="button" class="btn btn-primary">Salvar</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.min.js"
integrity="sha384-+sLIOodYLS7CIrQpBjl+C7nPvqq+FbNUBDunl/OZv93DB7Ln/533i8e/mZXLi/P+"
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$('#actionModal').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
var action = button.data('action');
console.log(action);
if (action === 'connect') {
} else if (action === 'restart') {
}
});
})
</script>
</body>
</html>

View File

@@ -11,7 +11,7 @@
<body>
<iframe src="https://app.smith.dgcode.com.br/app/evolutionapi-public/home-64ca60783615e270291978b4?embed=true" frameborder="0" style="width: 100%; height: 100vh;"></iframe>
<iframe src="https://manager.evolution-api.com" frameborder="0" style="width: 100%; height: 100vh;"></iframe>
</body>