new(whatsapp.gblib): Native provider works in groups now.

This commit is contained in:
rodrigorodriguez 2022-10-12 00:30:34 -03:00
parent 633a7cb0ea
commit 76308153b3
2 changed files with 98 additions and 59 deletions

View file

@ -362,7 +362,7 @@ export class GBMinService {
this.createCheckHealthAddress(GBServer.globals.server, min, min.instance); this.createCheckHealthAddress(GBServer.globals.server, min, min.instance);
GBDeployer.mountGBKBAssets(`${instance.botId}.gbkb`, GBDeployer.mountGBKBAssets(`${instance.botId}.gbkb`,
instance.botId, `${instance.botId}.gbkb`); instance.botId, `${instance.botId}.gbkb`);
} }
public static isChatAPI(req, res) { public static isChatAPI(req, res) {
@ -655,6 +655,15 @@ export class GBMinService {
); );
await min['googleDirectLine'].setup(true); await min['googleDirectLine'].setup(true);
} }
const group = min.core.getParam<string>(
min.instance,
'WhatsApp Group ID',
null,
);
WhatsappDirectLine.botGroups[min.botId] = group;
// If there is WhatsApp configuration specified, initialize // If there is WhatsApp configuration specified, initialize
// infrastructure objects. // infrastructure objects.
@ -665,8 +674,10 @@ export class GBMinService {
min.instance.whatsappBotKey, min.instance.whatsappBotKey,
min.instance.whatsappServiceKey, min.instance.whatsappServiceKey,
min.instance.whatsappServiceNumber, min.instance.whatsappServiceNumber,
min.instance.whatsappServiceUrl min.instance.whatsappServiceUrl,
group
); );
await min.whatsAppDirectLine.setup(true); await min.whatsAppDirectLine.setup(true);
} else { } else {
const minBoot = GBServer.globals.minBoot as any; const minBoot = GBServer.globals.minBoot as any;
@ -676,7 +687,8 @@ export class GBMinService {
min.instance.whatsappBotKey, min.instance.whatsappBotKey,
minBoot.instance.whatsappServiceKey, minBoot.instance.whatsappServiceKey,
minBoot.instance.whatsappServiceNumber, minBoot.instance.whatsappServiceNumber,
minBoot.instance.whatsappServiceUrl minBoot.instance.whatsappServiceUrl,
group
); );
await min.whatsAppDirectLine.setup(false); await min.whatsAppDirectLine.setup(false);
} }

View file

@ -47,7 +47,7 @@ import { DialogKeywords } from '../../basic.gblib/services/DialogKeywords';
import { GBAdminService } from '../../admin.gbapp/services/GBAdminService'; import { GBAdminService } from '../../admin.gbapp/services/GBAdminService';
import { GBMinService } from '../../core.gbapp/services/GBMinService'; import { GBMinService } from '../../core.gbapp/services/GBMinService';
import { GBConfigService } from '../../core.gbapp/services/GBConfigService'; import { GBConfigService } from '../../core.gbapp/services/GBConfigService';
import { createBrowser } from '../../core.gbapp/services/GBSSR';
const puppeteer = require('puppeteer'); const puppeteer = require('puppeteer');
const { MessageMedia, Client, LocalAuth } = require('whatsapp-web.js'); const { MessageMedia, Client, LocalAuth } = require('whatsapp-web.js');
@ -66,6 +66,7 @@ export class WhatsappDirectLine extends GBService {
public static usernames = {}; public static usernames = {};
public static state = {}; // 2: Waiting, 3: MessageArrived. public static state = {}; // 2: Waiting, 3: MessageArrived.
public static lastMessage = {}; // 2: Waiting, 3: MessageArrived. public static lastMessage = {}; // 2: Waiting, 3: MessageArrived.
public static botGroups = {};
public pollInterval = 3000; public pollInterval = 3000;
public directLineClientName = 'DirectLineClient'; public directLineClientName = 'DirectLineClient';
@ -82,6 +83,7 @@ export class WhatsappDirectLine extends GBService {
INSTANCE_URL = 'https://api.maytapi.com/api'; INSTANCE_URL = 'https://api.maytapi.com/api';
private customClient; private customClient;
private browserWSEndpoint; private browserWSEndpoint;
private groupId;
constructor( constructor(
min: GBMinInstance, min: GBMinInstance,
@ -89,7 +91,8 @@ export class WhatsappDirectLine extends GBService {
directLineSecret, directLineSecret,
whatsappServiceKey, whatsappServiceKey,
whatsappServiceNumber, whatsappServiceNumber,
whatsappServiceUrl whatsappServiceUrl,
groupId
) { ) {
super(); super();
@ -101,6 +104,7 @@ export class WhatsappDirectLine extends GBService {
this.whatsappServiceUrl = whatsappServiceUrl; this.whatsappServiceUrl = whatsappServiceUrl;
this.provider = whatsappServiceKey === "internal" ? this.provider = whatsappServiceKey === "internal" ?
'GeneralBots' : whatsappServiceNumber.indexOf(';') > -1 ? 'maytapi' : 'chatapi'; 'GeneralBots' : whatsappServiceNumber.indexOf(';') > -1 ? 'maytapi' : 'chatapi';
this.groupId = groupId;
} }
public static async asyncForEach(array, callback) { public static async asyncForEach(array, callback) {
@ -228,8 +232,12 @@ export class WhatsappDirectLine extends GBService {
}; };
const wait = Math.floor(Math.random() * 5000) + 1000; const wait = Math.floor(Math.random() * 5000) + 1000;
await sleep(wait); await sleep(wait);
await chat.delete(); if (chat.isGroup) {
await chat.clearMessages();
}
else if (!chat.pinned) {
await chat.delete();
}
}); });
}); });
@ -393,64 +401,72 @@ export class WhatsappDirectLine extends GBService {
text = text.replace(/\@\d+ /gi, ''); text = text.replace(/\@\d+ /gi, '');
GBLog.info(`GBWhatsapp: RCV ${from}(${fromName}): ${text})`); GBLog.info(`GBWhatsapp: RCV ${from}(${fromName}): ${text})`);
let botGroupID = WhatsappDirectLine.botGroups[this.min.botId];
let botShortcuts = this.min.core.getParam<string>(this.min.instance, 'WhatsApp Group Shortcuts', null);
if (!botShortcuts) {
botShortcuts = new Array()
}
else {
botShortcuts = botShortcuts.split(' ');
}
if (provider === "chatapi") { if (provider === "chatapi") {
if (message.chatName.charAt(0) !== '+') { if (message.chatName.charAt(0) !== '+') {
group = message.chatName; group = message.chatName;
}
}
else if (provider === "GeneralBots") {
if (message.from.endsWith('@g.us')) {
group = message.from;
}
}
let botGroupName = this.min.core.getParam<string>(this.min.instance, 'WhatsApp Group Name', null); if (group) {
let botShortcuts = this.min.core.getParam<string>(this.min.instance, 'WhatsApp Group Shortcuts', null); const parts = text.split(' ');
if (!botShortcuts) {
botShortcuts = new Array()
}
else {
botShortcuts = botShortcuts.split(' ');
}
const parts = text.split(' '); // Bot name must be specified on config.
// Bot name must be specified on config. if (botGroupID === group) {
if (botGroupName === group) { // Shortcut has been mentioned?
// Shortcut has been mentioned? let found = false;
parts.forEach(e1 => {
botShortcuts.forEach(e2 => {
if (e1 === e2 && !found) {
found = true;
text = text.replace(e2, '');
}
});
let found = false;
parts.forEach(e1 => { // Verify if it is a group cache answer.
botShortcuts.forEach(e2 => {
if (e1 === e2 && !found) { const questions = this.min['groupCache'];
found = true; if (questions && questions.length > 0) {
text = text.replace(e2, ''); questions.forEach(q => {
if (q.content === e1 && !found) {
const answer = this.min.kbService['getAnswerById'](this.min.instance.instanceId,
q.answerId);
answerText = answer.content;
} }
}); });
}
// Verify if it is a group cache answer. // Ignore group messages without the mention to Bot.
const questions = this.min['groupCache']; let smsServiceNumber = this.min.core.getParam<string>(this.min.instance, 'whatsappServiceNumber', null);
if (questions && questions.length > 0) { if (smsServiceNumber && !answerText) {
questions.forEach(q => { smsServiceNumber = smsServiceNumber.replace('+', '');
if (q.content === e1 && !found) { if (!message.body.startsWith('@' + smsServiceNumber)) {
const answer = this.min.kbService['getAnswerById'](this.min.instance.instanceId, return;
q.answerId);
answerText = answer.content;
}
});
} }
}
});
// Ignore group messages without the mention to Bot.
let smsServiceNumber = this.min.core.getParam<string>(this.min.instance, 'whatsappServiceNumber', null);
if (smsServiceNumber && !answerText) {
smsServiceNumber = smsServiceNumber.replace('+', '');
if (!message.body.startsWith('@' + smsServiceNumber)) {
return;
}
}
});
}
} }
} }
const botId = this.min.instance.botId; const botId = this.min.instance.botId;
@ -843,7 +859,15 @@ export class WhatsappDirectLine extends GBService {
switch (this.provider) { switch (this.provider) {
case 'GeneralBots': case 'GeneralBots':
this.customClient.sendMessage(to + '@c.us', msg); if (to.length == 18)
{
to = to + '@g.us';
}
else
{
to = to + '@c.us';
}
this.customClient.sendMessage(to, msg);
break; break;
@ -1010,20 +1034,23 @@ export class WhatsappDirectLine extends GBService {
// Ensures that the bot group is the active bot for the user (like switching). // Ensures that the bot group is the active bot for the user (like switching).
const message = req.group; const message = req;
if (message.chatName.charAt(0) !== '+') { if (message.from.endsWith('@g.us')) {
group = message.chatName; group = message.from;
} }
} }
if (group) { if (group) {
const botGroup = await this.min.core.loadInstanceByBotId(group); function getKeyByValue(object, value) {
if (botGroup && user.instanceId !== botGroup.instanceId) { return Object.keys(object).find(key => object[key] === value);
await sec.updateUserInstance(id, botGroup.instanceId);
} }
if (botGroup) { const botId = getKeyByValue(WhatsappDirectLine.botGroups, group) ;
if (botId && user.instanceId !== this.min.instance.instanceId) {
await sec.updateUserInstance(id, this.min.instance.instanceId);
}
if (botId) {
activeMin = GBServer.globals.minInstances.filter activeMin = GBServer.globals.minInstances.filter
(p => p.instance.instanceId === botGroup.instanceId)[0]; (p => p.instance.botId === botId)[0];
await (activeMin as any).whatsAppDirectLine.received(req, res); await (activeMin as any).whatsAppDirectLine.received(req, res);
return; // EXIT HERE. return; // EXIT HERE.
} }