From f010a2a6e407e267990e6e0e5b7bca69130fbc4b Mon Sep 17 00:00:00 2001 From: cheveguerra Date: Sat, 25 Feb 2023 06:50:48 -0600 Subject: [PATCH] Fixes --- .env | 2 +- controllers/handle.js | 11 +- controllers/save.js | 6 +- controllers/send_baileys.js | 27 ++ implementaciones/appFuncs.js | 641 +++++++++++++++++---------------- implementaciones/extraFuncs.js | 25 +- 6 files changed, 368 insertions(+), 344 deletions(-) diff --git a/.env b/.env index 90bc32a..81114ea 100644 --- a/.env +++ b/.env @@ -13,4 +13,4 @@ KEEP_DIALOG_FLOW=false MULTI_DEVICE=true DIALOGFLOW_MEDIA_FOR_SLOT_FILLING=false GDRIVE_FOLDER_ID= -PROVIDER=wwebjs \ No newline at end of file +PROVIDER=baileys \ No newline at end of file diff --git a/controllers/handle.js b/controllers/handle.js index 4dfdfd0..7436e6b 100644 --- a/controllers/handle.js +++ b/controllers/handle.js @@ -80,21 +80,14 @@ const createClient = () => { }); } -const isValidNumber_wwebjs = (rawNumber) => { +const isValidNumber = (rawNumber) => { const regexGroup = /\@g.us\b/gm; const exist = rawNumber.match(regexGroup); console.log("IsValidWawebJS", rawNumber, exist, !exist) return !exist } -const isValidNumber_baileys = (rawNumber) => { - const regexGroup = /\@g.us\b/gm; - const exist = rawNumber.match(regexGroup); - // console.log("IsValidBaileys", rawNumber, exist, !exist) - return !exist -} - -const isValidNumber = eval(`isValidNumber_${provider}`) +// const isValidNumber = eval(`isValidNumber_${provider}`) const cleanNumber = eval(`cleanNumber_${provider}`) module.exports = {cleanNumber, saveExternalFile, generateImage, checkIsUrl, checkEnvFile, createClient, isValidNumber } diff --git a/controllers/save.js b/controllers/save.js index 4ada401..85261c1 100644 --- a/controllers/save.js +++ b/controllers/save.js @@ -1,7 +1,7 @@ -const mimeDb = require('mime-db'); -// const { uploadSingleFile } = require('../adapter/gdrive') // Para Goole Drive y DialogFlow +const mimeDb = require('mime-db') +const GDRIVE_FOLDER_ID = process.env.GDRIVE_FOLDER_ID || 'false' +if(GDRIVE_FOLDER_ID == true) { const { uploadSingleFile } = require('../adapter/gdrive') } const fs = require('fs'); - var fileName; /** diff --git a/controllers/send_baileys.js b/controllers/send_baileys.js index 91171f2..df13e0d 100644 --- a/controllers/send_baileys.js +++ b/controllers/send_baileys.js @@ -114,6 +114,33 @@ const sendMessageButton2 = async (client, number = null, text = null, actionButt * @example await sendMessage("+XXXXXXXXXXX", "Your Text", "Your Footer", [{"buttonId": "id", "buttonText": {"displayText": "Button"}, "type": 1}]) */ const sendMessageButton = async (client, number, text = null, actionButtons) => { + number = cleanNumber(number) + const { title = null, message = null, footer = null, buttons = [] } = actionButtons; + const templateButtons = buttons.map((btn, i) => ({ + buttonId: `id-btn-${i}`, + buttonText: { displayText: btn.body }, + type: 1, + })) + let mensaje2 = "" + if (title != null) { mensaje2 = "*" + title + "*\n\n" + message } + else { mensaje2 = message } + text = remplazos(mensaje2, client) + const buttonMessage = { text, footer, buttons: templateButtons, headerType: 1 } + console.log("sendMessageButton:", buttonMessage) + console.log(templateButtons) + return client.sendMessage(number, buttonMessage) + await readChat(number, message) +} + +/** + * + * @param {string} number + * @param {string} text + * @param {string} footer + * @param {Array} buttons + * @example await sendMessage("+XXXXXXXXXXX", "Your Text", "Your Footer", [{"buttonId": "id", "buttonText": {"displayText": "Button"}, "type": 1}]) + */ +const sendMessageButtonTemplate = async (client, number, text = null, actionButtons) => { number = cleanNumber(number) const { title = null, message = null, footer = null, buttons = [] } = actionButtons; const templateButtons = buttons.map((btn, i) => ({ diff --git a/implementaciones/appFuncs.js b/implementaciones/appFuncs.js index 5ba9e39..82256c0 100644 --- a/implementaciones/appFuncs.js +++ b/implementaciones/appFuncs.js @@ -4,328 +4,329 @@ const { sendMedia, sendMessage, sendMessageButton, sendMessageList, readChat } = const { vamosA, traeUltimaVisita } = require('../adapter/index') /** - * LAS FUNCIONES SE DECLARAN COMO UN OBJETO DENTRO DE MODULE.EXPORTS, DE LA SIGUIENTE MANERA: - * - * nombreFuncion1 : function nombreFuncion1(ctx) { // Aqui va el código de la funcion }, - * nombreFuncion2 : function nombreFuncion2(ctx) { // Aqui va el código de la funcion } - * - * SE PUEDE USAR LA FUNCION traeVariablesFromClient(ctx) PARA OBTENER LAS VARIABLES from, body, name, hasMedia y step: - * - * const { from, body, name, hasMedia, step } = traeVariablesFromClient(ctx) - * - * O SE PUEDEN OBTENER DIRECTAMENTE DEL OBJETO ctx QUE RECIBE LA FUNCION: - * - * const from = ctx.theMsg.from - */ +* LAS FUNCIONES SE DECLARAN COMO UN OBJETO DENTRO DE MODULE.EXPORTS, DE LA SIGUIENTE MANERA: +* +* nombreFuncion1 : function nombreFuncion1(ctx) { // Aqui va el código de la funcion }, +* nombreFuncion2 : function nombreFuncion2(ctx) { // Aqui va el código de la funcion } +* +* SE PUEDE USAR LA FUNCION traeVariablesFromClient(ctx) PARA OBTENER LAS VARIABLES from, body, name, hasMedia y step: +* +* const { from, body, name, hasMedia, step } = traeVariablesFromClient(ctx) +* +* O SE PUEDEN OBTENER DIRECTAMENTE DEL OBJETO ctx QUE RECIBE LA FUNCION: +* +* const from = ctx.theMsg.from +*/ module.exports = { - /** - * Llama el API para traer categorias de Guna. - * @param {*} ctx El objeto del mensaje. - */ - getGunaCats : async function getGunaCats(ctx) { - const { from, body, name, hasMedia, step } = traeVariablesFromClient(ctx) - let lasOpciones = [] - let lasOpciones2 = [] - let theUrl = `http://localhost:8888/dbrquery?j={"query":"selectTipoFerreroMty","exec":"ExecuteQuery","params":{"par1":"xxx"}}` - const RES = await axios.get(theUrl).then(function (response) { - for(reg=0;reg -1){ // Producto con formato correcto. - vars[from]['ultimoProd'] = elProd - elProd = elProd.substring(0, elProd.indexOf(' $')).trim().toLowerCase() - var precio = ctx.theMsg.body.substring(ctx.theMsg.body.indexOf(' $')+2) - // console.log("precio",precio) - precio = precio.substring(0, precio.indexOf(',')) - // console.log("precio",precio) - vars[from]['prods'][elProd] = {"cant":0, "precio":precio} - // console.log("EL_PROD=", elProd) - // console.log(vars[from]['prods']) - elMensaje = ctx.theMsg.replyMessage - let re = ctx.theMsg.body.trim().toLowerCase() - elMensaje = elMensaje.replace(re, elProd.toLowerCase()) - } - else{ // Producto SIN precio. - elMensaje = "El producto que seleccionaste es *incorrecto*, por favor intenta de nuevo." - sendMessage(ctx, from, elMensaje, null, step); - await delay(500) - vars[from]['recompra'] = true - getGunaProds(ctx) - vamosA(from, "gunaProds") - return - } - sendMessage(ctx, from, elMensaje, null, step); - return - }, - /** - * Tomamos la cantidad del producto seleccionado. - * @param {*} ctx El objeto del mensaje. - */ - prodCantidad : async function prodCantidad(ctx) { - const { from, body, name, hasMedia, step } = traeVariablesFromClient(ctx); - // console.log("Entramos a prodCantidad") - let laCant = ctx.theMsg.body.trim() - const reg = new RegExp(/^\d+$/) - let elProd = vars[from]['ultimoProd'].toLowerCase() - elProd = elProd.substring(0, elProd.indexOf(' $')).trim() - console.log("SOLO NUMS |" + laCant + "|", reg.test(laCant)) - if(reg.test(laCant)){ - // console.log(vars) - // console.log("Recibimos cant = " + laCant) - // console.log("EL_PROD=", vars[from]['prods'][elProd]) - // console.log("precio=", vars[from]['prods'][elProd].precio) - vars[from]['prods'][elProd] = {"cant":laCant, "precio":vars[from]['prods'][elProd]['precio']} - var elMensaje = "" - const prods = Object.keys(vars[from]['prods']); - var total = 0 - prods.forEach((prod, index) => { - if( vars[from]['prods'][prod] !== undefined && prod[0] !== undefined ){ - elMensaje = elMensaje + `${vars[from]['prods'][prod].cant} - ${prod[0].toUpperCase() + prod.substring(1)}\n` - console.log("cant y precio=", vars[from]['prods'][prod].cant, vars[from]['prods'][prod].precio) - if(reg.test(vars[from]['prods'][prod].cant) && vars[from]['prods'][prod].precio != ""){ - total = total + (vars[from]['prods'][prod].cant * vars[from]['prods'][prod].precio) - } - } - console.log(prod, vars[from]['prods'][prod]); - }); - let pesos = Intl.NumberFormat('en-US') - elMensaje = elMensaje + "\n*Total*: $" + pesos.format(total) - elMensaje = elMensaje + "\n¿Quieres agregar mas productos a tu orden?" - var bts = { - "title":"Tu orden", - "message":elMensaje, - "buttons":[ - {"body":"➕ Agregar productos"}, - {"body":"⬅️ Cambiar categoría"}, - {"body":"✖️ Terminar"} - ] - } - sendMessageButton(ctx, from, null, bts) - } - else{ - console.log("NO SOLO NUMS") - vamosA(from, "gunaProdsAgrega") - sendMessage(ctx, from, "Por favor escribe 👉🏽 *solo* 👈🏽 el número.", null, step); - } - return "1" - }, - /** - * Mandamos nuevamente la lista de productos. - * @param {*} ctx El objeto del mensaje. - */ - comprarMas : async function comprarMas(ctx) { - const { from, body, name, hasMedia, step } = traeVariablesFromClient(ctx); - console.log("Entramos a comprarMas") - vars[from]['recompra'] = true - vamosA(from, "gunaProds") - await getGunaProds(ctx) - vars[from]['recompra'] = undefined - return "1" - }, - /** - * Mandamos nuevamente la lista de categorías. - * @param {*} ctx El objeto del mensaje. - */ - terminaCompra : async function terminaCompra(ctx) { - const { from, body, name, hasMedia, step } = traeVariablesFromClient(ctx); - console.log("Entramos a terminaCompra") - vars[from] = [] - sendMessage(ctx, from, "!Gracias por tu compra, regresa pronto!", null, step); - return - }, - /** - * Llama el API para desbloquear un usuario. - * @param {*} ctx El objeto del mensaje. - */ - desbloqueaUsuario : async function desbloqueaUsuario(ctx) { - const { from, body, name, hasMedia, step } = traeVariablesFromClient(ctx); - let par1 = ctx.theMsg.body - let theUrl = `http://localhost:8888/dbrquery?j={"query":"update_usuario_guna_nobajas","exec":"ExecuteCommand","params":{"par1":"${par1}", "par2":"XXPARAM2XX", "par3":"XXPARAM3XX"}}` - const RES = await axios.get(theUrl).then(function (response) { - const { AffectedRows } = response.data['respuesta'][0] - console.log('AFFECTED_ROWS = ', AffectedRows) - if(response.data['respuesta'][0]['AffectedRows']=="1"){ - sendMessage(ctx, from, "Listo, usuario *"+response.data['params']['par1']+"* desbloqueado, por favor *cerrar navegadores* y reingresar.", null, step); - } - else{ - sendMessage(ctx, from, "El usuario *"+response.data['params']['par1']+"* no *existe* o esta dado de *baja*, por favor revisarlo y volver a intentar.", null, step); - } - return response - }).catch(function (error) { - console.log(error); - return error - }); - }, - /** - * Llama el API para desbloquear el usuario. - * - * @param {*} theURL El URL para llamar al API - * @param {*} step - */ - desbloqueaUsuario2 : async function desbloqueaUsuario2(theUrl, step) { - // const { from, body, name, hasMedia, step } = traeVariablesFromClient(ctx); - // const RES = await axios.get(theUrl).then(function (response) { - // const { AffectedRows } = response.data['respuesta'][0] - // console.log('AFFECTED_ROWS = ', AffectedRows) - // if(response.data['respuesta'][0]['AffectedRows']=="1"){ - // sendMessage(ctx, from, "Listo, usuario *"+response.data['params']['par1']+"* desbloqueado, por favor *cerrar navegadores* y reingresar.", null, step); - // } - // else{ - // sendMessage(ctx, from, "El usuario *"+response.data['params']['par1']+"* no *existe* o esta dado de *baja*, por favor revisarlo y volver a intentar.", null, step); - // } - // return response - // }).catch(function (error) { - // console.log(error); - // return error - // }); + /** + * Llama el API para traer categorias de Guna. + * @param {*} ctx El objeto del mensaje. + */ + getGunaCats : async function getGunaCats(ctx) { + const { from, body, name, hasMedia, step } = traeVariablesFromClient(ctx) + let lasOpciones = [] + let lasOpciones2 = [] + let theUrl = `http://localhost:8888/dbrquery?j={"query":"selectTipoFerreroMty","exec":"ExecuteQuery","params":{"par1":"xxx"}}` + const RES = await axios.get(theUrl).then(function (response) { + for(reg=0;reg -1){ // Producto con formato correcto. + vars[from]['ultimoProd'] = elProd + elProd = elProd.substring(0, elProd.indexOf(' $')).trim().toLowerCase() + var precio = ctx.theMsg.body.substring(ctx.theMsg.body.indexOf(' $')+2) + // console.log("precio",precio) + precio = precio.substring(0, precio.indexOf(',')) + // console.log("precio",precio) + vars[from]['prods'][elProd] = {"cant":0, "precio":precio} + // console.log("EL_PROD=", elProd) + // console.log(vars[from]['prods']) + elMensaje = ctx.theMsg.replyMessage + let re = ctx.theMsg.body.trim().toLowerCase() + elMensaje = elMensaje.replace(re, elProd.toLowerCase()) + } + else{ // Producto SIN precio. + elMensaje = "El producto que seleccionaste es *incorrecto*, por favor intenta de nuevo." + sendMessage(ctx, from, elMensaje, null, step); + await delay(500) + vars[from]['recompra'] = true + getGunaProds(ctx) + vamosA(from, "gunaProds") + return + } + sendMessage(ctx, from, elMensaje, null, step); + return + }, + /** + * Tomamos la cantidad del producto seleccionado. + * @param {*} ctx El objeto del mensaje. + */ + prodCantidad : async function prodCantidad(ctx) { + const { from, body, name, hasMedia, step } = traeVariablesFromClient(ctx); + // console.log("Entramos a prodCantidad") + let laCant = ctx.theMsg.body.trim() + const reg = new RegExp(/^\d+$/) + let elProd = vars[from]['ultimoProd'].toLowerCase() + elProd = elProd.substring(0, elProd.indexOf(' $')).trim() + console.log("SOLO NUMS |" + laCant + "|", reg.test(laCant)) + if(reg.test(laCant)){ + // console.log(vars) + // console.log("Recibimos cant = " + laCant) + // console.log("EL_PROD=", vars[from]['prods'][elProd]) + // console.log("precio=", vars[from]['prods'][elProd].precio) + vars[from]['prods'][elProd] = {"cant":laCant, "precio":vars[from]['prods'][elProd]['precio']} + var elMensaje = "" + const prods = Object.keys(vars[from]['prods']); + var total = 0 + prods.forEach((prod, index) => { + if( vars[from]['prods'][prod] !== undefined && prod[0] !== undefined ){ + elMensaje = elMensaje + `${vars[from]['prods'][prod].cant} - ${prod[0].toUpperCase() + prod.substring(1)}\n` + console.log("cant y precio=", vars[from]['prods'][prod].cant, vars[from]['prods'][prod].precio) + if(reg.test(vars[from]['prods'][prod].cant) && vars[from]['prods'][prod].precio != ""){ + total = total + (vars[from]['prods'][prod].cant * vars[from]['prods'][prod].precio) + } + } + console.log(prod, vars[from]['prods'][prod]); + }); + let pesos = Intl.NumberFormat('en-US') + elMensaje = elMensaje + "\n*Total*: $" + pesos.format(total) + elMensaje = elMensaje + "\n¿Quieres agregar mas productos a tu orden?" + var bts = { + "title":"Tu orden", + "message":elMensaje, + "buttons":[ + {"body":"➕ Agregar productos"}, + {"body":"⬅️ Cambiar categoría"}, + {"body":"✖️ Terminar"} + ] + } + sendMessageButton(ctx, from, null, bts) + } + else{ + console.log("NO SOLO NUMS") + vamosA(from, "gunaProdsAgrega") + sendMessage(ctx, from, "Por favor escribe 👉🏽 *solo* 👈🏽 el número.", null, step); + } + return "1" + }, + /** + * Mandamos nuevamente la lista de productos. + * @param {*} ctx El objeto del mensaje. + */ + comprarMas : async function comprarMas(ctx) { + const { from, body, name, hasMedia, step } = traeVariablesFromClient(ctx); + console.log("Entramos a comprarMas") + vars[from]['recompra'] = true + vamosA(from, "gunaProds") + await getGunaProds(ctx) + vars[from]['recompra'] = undefined + return "1" + }, + /** + * Mandamos nuevamente la lista de categorías. + * @param {*} ctx El objeto del mensaje. + */ + terminaCompra : async function terminaCompra(ctx) { + const { from, body, name, hasMedia, step } = traeVariablesFromClient(ctx); + console.log("Entramos a terminaCompra") + vars[from] = [] + sendMessage(ctx, from, "!Gracias por tu compra, regresa pronto!", null, step); + return + }, + /** + * Llama el API para desbloquear un usuario. + * @param {*} ctx El objeto del mensaje. + */ + desbloqueaUsuario : async function desbloqueaUsuario(ctx) { + const { from, body, name, hasMedia, step } = traeVariablesFromClient(ctx); + let par1 = ctx.theMsg.body + let theUrl = `http://localhost:8888/dbrquery?j={"query":"update_usuario_guna_nobajas","exec":"ExecuteCommand","params":{"par1":"${par1}", "par2":"XXPARAM2XX", "par3":"XXPARAM3XX"}}` + const RES = await axios.get(theUrl).then(function (response) { + const { AffectedRows } = response.data['respuesta'][0] + console.log('AFFECTED_ROWS = ', AffectedRows) + if(response.data['respuesta'][0]['AffectedRows']=="1"){ + sendMessage(ctx, from, "Listo, usuario *"+response.data['params']['par1']+"* desbloqueado, por favor *cerrar navegadores* y reingresar.", null, step); + } + else{ + sendMessage(ctx, from, "El usuario *"+response.data['params']['par1']+"* no *existe* o esta dado de *baja*, por favor revisarlo y volver a intentar.", null, step); + } + return response + }).catch(function (error) { + console.log(error); + return error + }); + }, + /** + * Llama el API para desbloquear el usuario. + * + * @param {*} theURL El URL para llamar al API + * @param {*} step + */ + desbloqueaUsuario2 : async function desbloqueaUsuario2(theUrl, step) { + // const { from, body, name, hasMedia, step } = traeVariablesFromClient(ctx); + // const RES = await axios.get(theUrl).then(function (response) { + // const { AffectedRows } = response.data['respuesta'][0] + // console.log('AFFECTED_ROWS = ', AffectedRows) + // if(response.data['respuesta'][0]['AffectedRows']=="1"){ + // sendMessage(ctx, from, "Listo, usuario *"+response.data['params']['par1']+"* desbloqueado, por favor *cerrar navegadores* y reingresar.", null, step); + // } + // else{ + // sendMessage(ctx, from, "El usuario *"+response.data['params']['par1']+"* no *existe* o esta dado de *baja*, por favor revisarlo y volver a intentar.", null, step); + // } + // return response + // }).catch(function (error) { + // console.log(error); + // return error + // }); + } + } // module.exports = new funcsClass() \ No newline at end of file diff --git a/implementaciones/extraFuncs.js b/implementaciones/extraFuncs.js index 603fed4..93d4e75 100644 --- a/implementaciones/extraFuncs.js +++ b/implementaciones/extraFuncs.js @@ -210,7 +210,7 @@ function traeVariablesFromMsg(msg){ function traeVariablesFromMsgBaileys(msg){ const { remoteJid } = msg.messages[0].key const { pushName } = msg.messages[0] - let theBody = msg.messages[0].message?.conversation || msg.messages[0].message?.buttonsResponseMessage?.selectedDisplayText || msg.messages[0].message?.listResponseMessage?.title + let theBody = msg.messages[0].message?.conversation || msg.messages[0].message?.templateButtonReplyMessage?.selectedDisplayText || msg.messages[0].message?.buttonsResponseMessage?.selectedDisplayText || msg.messages[0].message?.listResponseMessage?.title let from = remoteJid let body = theBody let name = pushName @@ -227,15 +227,15 @@ function traeVariablesFromMsgWWebJS(msg){ } /** - * Regresa las variables from, body, name, hasMedia y steps del objeto del cliente. + * Regresa las variables from, body, name, hasMedia, step y number del objeto del cliente. * @param {*} client - * @returns from, body, name, hasMedia y step + * @returns from, body, name, hasMedia, step y number */ function traeVariablesFromClient(client){ // console.log(client) - const { body, from, name, hasMedia, step } = client.theMsg - const { pushName } = client.theMsg - return {"from":from, "body":body, "name":name, "hasMedia":hasMedia, "step":step} + const { body, from, name, hasMedia, step, number } = client.theMsg + // const { pushName } = client.theMsg + return {"from":from, "body":body, "name":name, "hasMedia":hasMedia, "step":step, "number":number} } /** @@ -264,7 +264,7 @@ function agregaVars(client, msg, vars){ client.theMsg['from'] = from client.theMsg['hasMedia'] = hasMedia client.theMsg['name'] = name - client.theMsg['numero'] = soloNumero(from) + client.theMsg['number'] = soloNumero(from) return client } @@ -500,10 +500,13 @@ for (var i=0; i < defaultDiacriticsRemovalMap .length; i++){ } // "what?" version ... http://jsperf.com/diacritics/12 -function removeDiacritics (str) { - return str.replace(/[^\u0000-\u007E]/g, function(a){ - return diacriticsMap[a] || a; - }); +function removeDiacritics(str) { + if (str !== undefined) { + return str.replace(/[^\u0000-\u007E]/g, function (a) { + return diacriticsMap[a] || a; + }); + } + else { return "" } } // var paragraph = "L'avantage d'utiliser le lorem ipsum est bien évidemment de pouvoir créer des maquettes ou de remplir un site internet de contenus qui présentent un rendu s'approchant un maximum du rendu final. \n Par défaut lorem ipsum ne contient pas d'accent ni de caractères spéciaux contrairement à la langue française qui en contient beaucoup. C'est sur ce critère que nous proposons une solution avec cet outil qui générant du faux-texte lorem ipsum mais avec en plus, des caractères spéciaux tel que les accents ou certains symboles utiles pour la langue française. \n L'utilisation du lorem standard est facile d’utilisation mais lorsque le futur client utilisera votre logiciel il se peut que certains caractères spéciaux ou qu'un accent ne soient pas codés correctement. \n Cette page a pour but donc de pouvoir perdre le moins de temps possible et donc de tester directement si tous les encodages de base de donnée ou des sites sont les bons de plus il permet de récuperer un code css avec le texte formaté !"; // alert(removeDiacritics(paragraph));