fix(whatsapp.gblib): #288 fix list and buttons.

This commit is contained in:
rodrigorodriguez 2023-03-06 20:36:27 -03:00
parent b96a78e810
commit 6f62453f4e
4 changed files with 149 additions and 155 deletions

View file

@ -172,10 +172,10 @@
"vm2-process": "2.1.1",
"walk-promise": "0.2.0",
"washyourmouthoutwithsoap": "1.0.2",
"whatsapp-web.js": "github:pedroslopez/whatsapp-web.js#fix-buttons-list",
"whatsapp-web.js": "github:meetscrm/whatsapp-web.js#8a46b65e2284ae2b031b5a9217e33ec2bab2e579",
"winston": "3.8.2",
"winston-logs-display": "1.0.0",
"ws": "^8.12.1",
"ws": "8.12.1",
"yarn": "1.22.19"
},
"devDependencies": {

View file

@ -46,20 +46,19 @@ import { Messages } from '../strings.js';
import * as Fs from 'fs';
import { CollectionUtil } from 'pragmatismo-io-framework';
import { GBConversationalService } from '../../core.gbapp/services/GBConversationalService.js';
import { GuaribasUser } from '../../security.gbapp/models/index.js';
import phoneUtil from 'google-libphonenumber';
import phone from 'phone';
import DateDiff from 'date-diff';
import { Buttons, List } from 'whatsapp-web.js';
import tesseract from 'node-tesseract-ocr';
import Path from 'path';
import sgMail from '@sendgrid/mail';
import mammoth from 'mammoth';
import qrcode from 'qrcode';
import { json } from 'body-parser';
import { WebAutomationServices } from './WebAutomationServices.js';
import urljoin from 'url-join';
import QrScanner from 'qr-scanner';
import pkg from 'whatsapp-web.js';
const { List, Buttons } = pkg;
/**
* Default check interval for user replay
@ -70,7 +69,6 @@ const DEFAULT_HEAR_POLL_INTERVAL = 500;
* Base services of conversation to be called by BASIC.
*/
export class DialogKeywords {
/**
*
* Data = [10,20,30]
@ -704,15 +702,16 @@ public async setFilterTypes({ pid, types }) {
* @example HEAR name
*
*/
public async hear({ pid, kind, arg }) {
public async hear({ pid, kind, args }) {
let { min, user, params } = await DialogKeywords.getProcessInfo(pid);
// Handles first arg as an array of args.
let args = [];
if (arg && arg.length) {
args = arg;
let args1 = [];
if (args && args.length) {
args1 = args;
}
args = args1;
try {
const isIntentYes = (locale, utterance) => {
@ -736,28 +735,25 @@ public async setFilterTypes({ pid, types }) {
// https://github.com/GeneralBots/BotServer/issues/266
if (args && args.length > 1) {
// https://github.com/pedroslopez/whatsapp-web.js/issues/1811
//
// const list = new List(
// 'Escolha um dos itens',
// 'Itens1',
// [
// {
// title: 'Itens2',
// rows: []
// }
// ],
// 'Please select a product'
// );
// let i = 0;
// await CollectionUtil.asyncForEach(args, async arg => {
// i++;
// list.sections[0].rows.push({ title: arg, id: `button${i}` });
// await this.getTalk(arg);
// });
let i = 0;
// const button = new wpp.Buttons(Messages[locale].choices, choices, ' ', ' ');
// await this.getTalk(button);
if (args.length > 3) {
let section = { title: '', rows: [] };
await CollectionUtil.asyncForEach(args, async arg => {
i++;
section.rows.push({ title: arg, id: `button${i}` });
});
const list = new List('Select:', '', [section], '', '');
await this.talk({ pid: pid, text: list });
} else {
let buttons = [];
await CollectionUtil.asyncForEach(args, async arg => {
i++;
buttons.push({ body: arg, id: `button${i}` });
});
let button = new Buttons('Select:', buttons, '', 'General Bots');
await this.talk({ pid: pid, text: button });
}
GBLog.info(`BASIC: HEAR with [${args.toString()}] (Asking for input).`);
} else {
@ -781,7 +777,6 @@ public async setFilterTypes({ pid, types }) {
const answer = min.cbMap[userId].promise;
if (kind === 'sheet') {
// Retrieves the .xlsx file associated with the HEAR var AS file.xlsx.
let { baseUrl, client } = await GBDeployer.internalGetDriveClient(min);
@ -795,10 +790,10 @@ public async setFilterTypes({ pid, types }) {
// Finds .xlsx specified by arg.
const document = res.value.filter(m => {
return m.name === arg;
return m.name === args;
});
if (document === undefined || document.length === 0) {
GBLog.info(`${arg} not found on .gbdata folder, check the package.`);
GBLog.info(`${args} not found on .gbdata folder, check the package.`);
return null;
}
@ -818,8 +813,7 @@ public async setFilterTypes({ pid, types }) {
for (; index < results.text.length; index++) {
if (results.text[index][0] !== '') {
list.push(results.text[index][0]);
}
else {
} else {
break;
}
}
@ -837,9 +831,8 @@ public async setFilterTypes({ pid, types }) {
if (result === null) {
await this.talk({ pid, text: `Escolha por favor um dos itens sugeridos.` });
return await this.hear({ pid, kind, arg });
return await this.hear({ pid, kind, args });
}
} else if (kind === 'file') {
GBLog.info(`BASIC (${min.botId}): Upload done for ${answer.filename}.`);
const handle = WebAutomationServices.cyrb53(min.botId + answer.filename);
@ -860,7 +853,7 @@ public async setFilterTypes({ pid, types }) {
if (value === null) {
await this.talk({ pid, text: 'Por favor, digite um e-mail válido.' });
return await this.hear({ pid, kind, arg });
return await this.hear({ pid, kind, args });
}
result = value;
@ -873,7 +866,7 @@ public async setFilterTypes({ pid, types }) {
if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite um nome válido.' });
return await this.hear({ pid, kind, arg });
return await this.hear({ pid, kind, args });
}
result = value;
@ -886,7 +879,7 @@ public async setFilterTypes({ pid, types }) {
if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite um número válido.' });
return await this.hear({ pid, kind, arg });
return await this.hear({ pid, kind, args });
}
result = value;
@ -901,7 +894,7 @@ public async setFilterTypes({ pid, types }) {
if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite uma data no formato 12/12/2020.' });
return await this.hear({ pid, kind, arg });
return await this.hear({ pid, kind, args });
}
result = value;
@ -914,7 +907,7 @@ public async setFilterTypes({ pid, types }) {
if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite um horário no formato hh:ss.' });
return await this.hear({ pid, kind, arg });
return await this.hear({ pid, kind, args });
}
result = value;
@ -933,7 +926,7 @@ public async setFilterTypes({ pid, types }) {
if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite um valor monetário.' });
return await this.hear({ pid, kind, arg });
return await this.hear({ pid, kind, args });
}
result = value;
@ -946,11 +939,11 @@ public async setFilterTypes({ pid, types }) {
} catch (error) {
await this.talk({ pid, text: Messages[locale].validation_enter_valid_mobile });
return await this.hear({ pid, kind, arg });
return await this.hear({ pid, kind, args });
}
if (!phoneUtil.isPossibleNumber(phoneNumber)) {
await this.talk({ pid, text: 'Por favor, digite um número de telefone válido.' });
return await this.hear({ pid, kind, arg });
return await this.hear({ pid, kind, args });
}
result = phoneNumber;
@ -959,8 +952,9 @@ public async setFilterTypes({ pid, types }) {
GBLog.info(`BASIC (${min.botId}): Upload done for ${answer.filename}.`);
const handle = WebAutomationServices.cyrb53(min.botId + answer.filename);
GBServer.globals.files[handle] = answer;
QrScanner.scanImage(GBServer.globals.files[handle]).then(result => console.log(result)).catch(error => console.log(error || 'no QR code found.'));
QrScanner.scanImage(GBServer.globals.files[handle])
.then(result => console.log(result))
.catch(error => console.log(error || 'no QR code found.'));
} else if (kind === 'zipcode') {
const extractEntity = (text: string) => {
text = text.replace(/\-/gi, '');
@ -977,7 +971,7 @@ public async setFilterTypes({ pid, types }) {
if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite um CEP válido.' });
return await this.hear({ pid, kind, arg });
return await this.hear({ pid, kind, args });
}
result = value[0];
@ -992,7 +986,7 @@ public async setFilterTypes({ pid, types }) {
if (result === null) {
await this.talk({ pid, text: `Escolha por favor um dos itens sugeridos.` });
return await this.hear({ pid, kind, arg });
return await this.hear({ pid, kind, args });
}
} else if (kind === 'language') {
result = null;
@ -1024,7 +1018,7 @@ public async setFilterTypes({ pid, types }) {
if (result === null) {
await this.talk({ pid, text: `Escolha por favor um dos itens sugeridos.` });
return await this.hear({ pid, kind, arg });
return await this.hear({ pid, kind, args });
}
}
return result;

View file

@ -63,6 +63,7 @@ import TextToSpeechV1 from 'ibm-watson/text-to-speech/v1.js';
import { IamAuthenticator } from 'ibm-watson/auth/index.js';
import * as marked from 'marked';
import Translate from '@google-cloud/translate';
import { List } from 'whatsapp-web.js';
/**
* Provides basic services for handling messages and dispatching to back-end
@ -1087,8 +1088,10 @@ export class GBConversationalService {
*
* Sends a message in a user with an already started conversation (got ConversationReference set)
*/
public async sendOnConversation(min: GBMinInstance, user: GuaribasUser, message: string) {
if (user.conversationReference.startsWith('spaces')) {
public async sendOnConversation(min: GBMinInstance, user: GuaribasUser, message: any) {
if (message['buttons'] || message['sections']) {
await min['whatsAppDirectLine'].sendToDevice(user.userSystemId, message, user.conversationReference );
} else if (user.conversationReference.startsWith('spaces')) {
await min['googleDirectLine'].sendToDevice(user.userSystemId, null, user.conversationReference, message);
} else {
const ref = JSON.parse(user.conversationReference);

View file

@ -45,12 +45,9 @@ import { GBMinService } from '../../core.gbapp/services/GBMinService.js';
import { GBConfigService } from '../../core.gbapp/services/GBConfigService.js';
import qrcode from 'qrcode-terminal';
import express from 'express';
import { DialogKeywords } from '../../basic.gblib/services/DialogKeywords.js';
import { GBAdminService } from '../../admin.gbapp/services/GBAdminService.js';
import { method } from 'lodash';
import pkg from 'whatsapp-web.js';
import { GBSSR } from '../../core.gbapp/services/GBSSR.js';
const { Buttons, Client, MessageMedia } = pkg;
import pkg from 'whatsapp-web.js';
const { List, Buttons, Client, MessageMedia } = pkg;
/**
* Support for Whatsapp.
@ -116,13 +113,17 @@ export class WhatsappDirectLine extends GBService {
}
}
public async sendButton() {
let url = '';
const media = await MessageMedia.fromUrl(url);
public async sendButton(number) {
let url = 'https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE1Mu3b?ver=5c31';
const media = await MessageMedia.fromUrl(url, {unsafeMime: true});
media.mimetype = 'image/png';
media.filename = 'hello.png';
let btnClickableMenu = new Buttons(media as any, [{ id: 'customId', body: 'button1' }, { body: 'button2' }]);
await this.sendToDevice('', btnClickableMenu as any, null);
let btnClickableMenu = new Buttons(media as any, [
{ id: 'customId', body: 'button1' }, { body: 'button2' },
{ body: 'button3' }, { body: 'button4' },
{ body: 'button4' }, { body: 'button6' },
]);
await this.sendToDevice(number, btnClickableMenu as any, null);
}
public async setup(setUrl: boolean) {
const client = await new SwaggerClient({
@ -140,10 +141,6 @@ export class WhatsappDirectLine extends GBService {
switch (this.provider) {
case 'GeneralBots':
const minBoot = GBServer.globals.minBoot;
// TODO: REMOVE THIS.
if (!setUrl) {
this.customClient = minBoot.whatsAppDirectLine.customClient;
} else {
// Initialize the browser using a local profile for each bot.
const gbaiName = `${this.min.botId}.gbai`;
const localName = Path.join('work', gbaiName, 'profile');
@ -183,6 +180,7 @@ export class WhatsappDirectLine extends GBService {
}).bind(this)
);
client.on('authenticated', async () => {
GBLog.verbose(`GBWhatsApp: QR Code authenticated for ${this.botId}.`);
});
client.on('ready', async () => {
@ -199,9 +197,9 @@ export class WhatsappDirectLine extends GBService {
const wait = Math.floor(Math.random() * 5000) + 1000;
await sleep(wait);
if (chat.isGroup) {
await chat.clearMessages();
// await chat.clearMessages();
} else if (!chat.pinned) {
await chat.delete();
// await chat.delete();
}
});
});
@ -209,7 +207,6 @@ export class WhatsappDirectLine extends GBService {
};
createClient.bind(this)();
setUrl = false;
}
break;
case 'chatapi':
options = {
@ -226,7 +223,7 @@ export class WhatsappDirectLine extends GBService {
}
};
break;
case 'chatapi':
case 'official':
url = urlJoin(this.whatsappServiceUrl, 'webhook');
options = {
method: 'POST',