mirror of
https://github.com/cheveguerra/botGuna.git
synced 2026-04-17 19:37:07 +00:00
Initial
This commit is contained in:
2
.env
2
.env
@@ -1,6 +1,6 @@
|
||||
######DATABASE: none, mysql, dialogflow
|
||||
|
||||
DEFAULT_MESSAGE=true
|
||||
DEFAULT_MESSAGE=false
|
||||
SAVE_MEDIA=true
|
||||
PORT=3005
|
||||
DATABASE=none
|
||||
|
||||
107
adapter/index.js
107
adapter/index.js
@@ -6,12 +6,12 @@ const stepsReponse = require('../flow/response.json')
|
||||
const { isUndefined } = require('util');
|
||||
var msjsRecibidos = [];
|
||||
var ultimoStep; //MOD by CHV -
|
||||
var pasoAnterior = []; //MOD by CHV - Para guardar el paso anterior de cada número.
|
||||
// var pasoAnterior = []; //MOD by CHV - Para guardar el paso anterior de cada número. (MOD - global en app.js)
|
||||
var pasoRequerido; //MOD by CHV -
|
||||
var vamosA = ""; //MOD by CHV -
|
||||
var _vamosA = ""; //MOD by CHV -
|
||||
var VA = ""; //MOD by CHV -
|
||||
var elNum; //MOD by CHV -
|
||||
var cumplePasoPrevio; //MOD by CHV -
|
||||
var cumplePasoPrevio = []; //MOD by CHV -
|
||||
const resps = require('../flow/response.json'); //MOD by CHV - Agregamos para traer las respuestas.
|
||||
const { appendFile } = require('fs')
|
||||
/**
|
||||
@@ -51,6 +51,7 @@ const get = (message, num) => new Promise((resolve, reject) => { //MOD by CHV -
|
||||
if (process.env.DATABASE === 'none') {
|
||||
|
||||
var { key } = stepsInitial.find(k => k.keywords.includes(message)) || { key: null }
|
||||
console.log("KEY="+key)
|
||||
|
||||
/* ############################################### * REGEXP * ####################################################
|
||||
Si queremos usar RegExp, en los "keywords" de inital.json, en lugar de un arreglo usamos un string (quitamos los [])
|
||||
@@ -70,38 +71,50 @@ const get = (message, num) => new Promise((resolve, reject) => { //MOD by CHV -
|
||||
var {keywords} = stepsInitial.find(k => k.key.includes(key)) || { keywords: null }
|
||||
if(!Array.isArray(keywords)){key=null;}//Si "keywords" no es arreglo entonces ponemos "key" en null y usamos REGEXP para buscar reglas.
|
||||
if(key == null && message.length > 0){
|
||||
console.log("======= KEY ES NULO USAMOS REGEXP =======");
|
||||
var logRegEx = true
|
||||
console.log("======= KEY ES NULO, USAMOS REGEXP =======");
|
||||
for (i=0; i<stepsInitial.length;i++){
|
||||
// console.log(i, stepsInitial[i].keywords, message.match(stepsInitial[i].keywords.toString().replaceAll("*",".*")));
|
||||
if(!Array.isArray(stepsInitial[i].keywords)){// Si "Keywords" NO es arreglo entonces ...
|
||||
x = null;
|
||||
console.log("KEY=|" + stepsInitial[i].key.toString() + "|" )
|
||||
var coincideKeyword = null;
|
||||
// console.log("KEY=|" + stepsInitial[i].key.toString() + "|" )
|
||||
// if(resps[stepsInitial[i].key.toString()].pasoRequerido != undefined){pr = resps[stepsInitial[i].key].pasoRequerido};
|
||||
// console.log(resps[stepsInitial[i].key.toString()].pasoRequerido== ultimoStep)
|
||||
console.log("Esta Key=" + stepsInitial[i].key.toString() + " - pasoReq=" + resps[stepsInitial[i].key.toString()].pasoRequerido + " - PasoAnt=" + ultimoStep+"|"+pasoAnterior[elNum])
|
||||
if(logRegEx) console.log("*** PASO=" + stepsInitial[i].key.toString() + " - REQUERIDO=" + resps[stepsInitial[i].key.toString()].pasoRequerido + " - ANTERIOR=" + pasoAnterior[elNum])
|
||||
//Si NO hay paso requerido, o el paso requerido es IGUAL al paso anterior, entonces ...
|
||||
if(resps[stepsInitial[i].key.toString()].pasoRequerido == undefined || resps[stepsInitial[i].key.toString()].pasoRequerido == pasoAnterior[elNum]){
|
||||
var tempKeyword = "";
|
||||
if(logRegEx) console.log(" - El paso requerido COINCIDE con el anterior, o NO hay paso requerido.")
|
||||
if (stepsInitial[i].keywords == "%solo_correos%"){
|
||||
console.log("solo_correos")
|
||||
if(logRegEx) console.log("solo_correos")
|
||||
tempKeyword = "[a-zA-Z0-9]+[_a-zA-Z0-9\.-]*[a-zA-Z0-9]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+[\.][a-zA-Z]{2,12})"}
|
||||
else{tempKeyword = stepsInitial[i].keywords.toString().replaceAll("*",".*")}
|
||||
x = message.match(tempKeyword);
|
||||
else {
|
||||
tempKeyword = stepsInitial[i].keywords.toString().replaceAll("*",".*")
|
||||
}
|
||||
coincideKeyword = message.match(tempKeyword); // Verdadero cuando el mensaje COINCIDE con la palabre clave.
|
||||
// console.log("Keywords="+stepsInitial[i].keywords + " - key=" + stepsInitial[i].key + " - pasoReq=" + resps[stepsInitial[i].key].pasoRequerido + " - PasoAnt=" + ultimoStep)
|
||||
// console.log("x:"+x+" - ultimoStep="+ultimoStep+" - pasoReq="+resps[stepsInitial[i].key].pasoRequerido);
|
||||
// console.log("coincideKeyword:"+coincideKeyword+" - ultimoStep="+ultimoStep+" - pasoReq="+resps[stepsInitial[i].key].pasoRequerido);
|
||||
// console.log(resps[stepsInitial[i].key].replyMessage.toString())
|
||||
if (x != null){
|
||||
if (coincideKeyword != null){ //Si el mensaje COINCIDE con la palabra clave.
|
||||
if(logRegEx) console.log(" - - El mensaje COINCIDE con el keyword")
|
||||
key = stepsInitial[i].key;
|
||||
if(resps[stepsInitial[i].key].pasoRequerido != null && resps[stepsInitial[i].key].pasoRequerido != pasoAnterior[elNum]){key=null;}
|
||||
// console.log("KEY="+key+" - X="+x);
|
||||
//Si HAY paso requerido, y el paso requerido es DIFERENTE del paso anterior, entonces ...
|
||||
if(resps[stepsInitial[i].key].pasoRequerido != null && resps[stepsInitial[i].key].pasoRequerido != pasoAnterior[elNum]){
|
||||
key=null
|
||||
if(logRegEx) console.log(" - - - Hay paso requerido y NO coincide con en paso anterior")
|
||||
}
|
||||
// console.log("KEY="+key+" - coincideKeyword="+coincideKeyword);
|
||||
if(resps[stepsInitial[i].key].replyMessage.toString().search("/URL") > -1){
|
||||
console.log("**************** HAY URL ****************")
|
||||
if(logRegEx) console.log("**************** HAY URL ****************")
|
||||
}
|
||||
break;
|
||||
}
|
||||
else{x = null;}
|
||||
} else
|
||||
{ console.log("NO CUMPLE PASO REQ");
|
||||
console.log("pasoReq=" + resps[stepsInitial[i].key.toString()].pasoRequerido + " - PasoAnt=" + ultimoStep)
|
||||
else {
|
||||
coincideKeyword = null
|
||||
}
|
||||
}
|
||||
else {
|
||||
if(logRegEx) console.log("--- NO CUMPLE PASO REQ");
|
||||
// console.log("pasoReq=" + resps[stepsInitial[i].key.toString()].pasoRequerido + " - PasoAnt=" + ultimoStep)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -114,19 +127,19 @@ const get = (message, num) => new Promise((resolve, reject) => { //MOD by CHV -
|
||||
// if(key != null){remplazos(resps[key].replyMessage.join(''));}
|
||||
if(resps[key]!=undefined){VA = resps[key].goto}else{VA=null}
|
||||
cumplePasoRequerido(key);
|
||||
vamosA = VA;
|
||||
// console.log(elNum)
|
||||
_vamosA = VA;
|
||||
console.log("cumplePasoPrevio[elNum]=", cumplePasoPrevio[elNum])
|
||||
|
||||
if(vamosA != "" && vamosA != undefined && cumplePasoPrevio == true){
|
||||
// console.log("ASIGNAMOS VAMOSA = " + vamosA);
|
||||
pasoAnterior[elNum] = vamosA;
|
||||
if(_vamosA != "" && _vamosA != undefined && cumplePasoPrevio[elNum] == true){
|
||||
console.log("ASIGNAMOS _VAMOSA = " + _vamosA);
|
||||
pasoAnterior[elNum] = _vamosA;
|
||||
}
|
||||
// console.log("ULTIMOSTEP="+ultimoStep)
|
||||
vamosA = "";
|
||||
_vamosA = "";
|
||||
// console.log("MESSAGE: "+message);
|
||||
// console.log("KEY: "+key);
|
||||
// console.log("RESPONSE: "+response);
|
||||
if(cumplePasoPrevio) {resolve(response);}
|
||||
if(cumplePasoPrevio[elNum]) {resolve(response);}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -137,7 +150,6 @@ const get = (message, num) => new Promise((resolve, reject) => { //MOD by CHV -
|
||||
resolve(dt)
|
||||
});
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
const reply = (step) => new Promise((resolve, reject) => {
|
||||
@@ -203,7 +215,18 @@ const saveMessage = ( message, trigger, number, regla ) => new Promise( async (r
|
||||
}
|
||||
})
|
||||
|
||||
module.exports = { get, reply, getIA, saveMessage, remplazos, stepsInitial } //MOD by CHV - Agregamos "remplazos" y "stepsInitial" para usarlos en "apps.js"
|
||||
module.exports = { get, reply, getIA, saveMessage, remplazos, stepsInitial, vamosA } //MOD by CHV - Agregamos "remplazos" y "stepsInitial" para usarlos en "apps.js"
|
||||
|
||||
/**
|
||||
* Asigna el valor especificado a la variable pasoAnterior.
|
||||
* Esta hace que el flujo se redirija al paso siguente al especificado.
|
||||
* @param {elNum} El numero del remitente.
|
||||
* @param {elPaso} El paso al que se va redirigir el flujo.
|
||||
*/
|
||||
function vamosA (elNum, elPaso){
|
||||
pasoAnterior[elNum] = elPaso;
|
||||
console.log("Asignamos pasoAnterior con " + elPaso, elNum)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reemplaza texto en la respuesta con variables predefinidas.
|
||||
@@ -276,7 +299,7 @@ function remplazos(elTexto, extraInfo){
|
||||
}
|
||||
if(laLista[i].search('%msjant_')>-1){//Remplaza con el mensaje anterior especificado.
|
||||
var histlMsjs = {};
|
||||
console.log("entramos a msjant")
|
||||
// console.log("entramos a msjant")
|
||||
// var hayHistorial = (chkFile(`${__dirname}/chats/`+from+".json"));
|
||||
if(chkFile(`${__dirname}/../chats/`+elNum+".json")){
|
||||
let rawdata = fs.readFileSync(`./chats/${elNum}.json`);
|
||||
@@ -286,18 +309,18 @@ function remplazos(elTexto, extraInfo){
|
||||
var inicio = laLista[i].search('%msjant_');
|
||||
var final = laLista[i].indexOf("%", inicio+1);
|
||||
var subStr = laLista[i].substring(inicio, final+1);
|
||||
console.log("Substr = |" + subStr + "|");
|
||||
// console.log("Substr = |" + subStr + "|");
|
||||
var partes = subStr.toString().split('_');
|
||||
if(partes.length > 1){
|
||||
console.log("Partes[1] = |" + partes[1] + "|");
|
||||
// console.log("Partes[1] = |" + partes[1] + "|");
|
||||
let posicion0 = partes[1].substring(0, partes[1].length-1)
|
||||
console.log("Posicion0 = |" + posicion0 + "|");
|
||||
// console.log("Posicion0 = |" + posicion0 + "|");
|
||||
posicion = ((posicion0*1) + 1);
|
||||
console.log("Posicion = " + posicion);
|
||||
console.log( elHistorial.length );
|
||||
console.log((elHistorial.length*1)-posicion);
|
||||
console.log("Mensaje="+elHistorial[elHistorial.length - posicion]["message"])
|
||||
elTexto = elTexto.toString().replace(subStr, elHistorial[elHistorial.length - posicion]["message"]);
|
||||
// console.log("Posicion = " + posicion);
|
||||
// console.log( elHistorial.length );
|
||||
// console.log((elHistorial.length*1)-posicion);
|
||||
// console.log("Mensaje="+elHistorial[elHistorial.length - posicion]["message"])
|
||||
elTexto = elTexto.toString().replace(subStr, elHistorial[elHistorial.length - posicion]["message"].trim());
|
||||
}
|
||||
// histlMsjs = elHistorial["messages"];
|
||||
// totalMsjs = histlMsjs.length-1;
|
||||
@@ -341,7 +364,7 @@ function remplazos(elTexto, extraInfo){
|
||||
}
|
||||
}
|
||||
// console.log("EL TEXTO="+elTexto);
|
||||
return elTexto
|
||||
return elTexto.trim()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -352,15 +375,15 @@ function remplazos(elTexto, extraInfo){
|
||||
if(resps[step]!=undefined){pasoRequerido=resps[step].pasoRequerido}else{pasoRequerido=null}
|
||||
if((pasoRequerido != null && pasoRequerido == ultimoStep)){
|
||||
// console.log("REQUIERE PASO PREVIO Y CUMPLE");
|
||||
cumplePasoPrevio = true;
|
||||
cumplePasoPrevio[elNum] = true;
|
||||
}
|
||||
else if((pasoRequerido != null && pasoRequerido != pasoAnterior[elNum])){
|
||||
// console.log("REQUIERE PASO PREVIO Y NO LO CUMPLE");
|
||||
cumplePasoPrevio = false;
|
||||
cumplePasoPrevio[elNum] = false;
|
||||
}
|
||||
else{
|
||||
// console.log("NO REQUIERE PASO PREVIO")
|
||||
cumplePasoPrevio = true;
|
||||
cumplePasoPrevio[elNum] = true;
|
||||
}
|
||||
pasoAnterior[elNum] = step
|
||||
ultimoPaso = pasoRequerido;
|
||||
|
||||
394
adapter/test.js
Normal file
394
adapter/test.js
Normal file
@@ -0,0 +1,394 @@
|
||||
+++++++++++++++++++++++++++++++++++++ INICIO +++++++++++++++++++++++++++++++++++++++
|
||||
HORA:4:55:56 PM FROM:5215519561677@c.us, BODY:/Guna, HASMEDIA:false
|
||||
NUEVA RESPUESTA= Mensaje de getGunaCats
|
||||
############# Encontramos Funcion, ejecutamos funcion getGunaCats
|
||||
1 { id: 'CHOCOLATE', title: 'CHOCOLATE' }
|
||||
2 { id: 'DULCES', title: 'DULCES' }
|
||||
lasOpciones=[object Object]
|
||||
List {
|
||||
description: 'Buenas tardes, selecciona una categoría 👇🏽',
|
||||
buttonText: 'Ver las categorías',
|
||||
title: 'Categorías',
|
||||
footer: 'Selecciona',
|
||||
sections: [ { title: 'Categorías', rows: [Array] } ]
|
||||
}
|
||||
<ref *1> Client {
|
||||
_events: [Object: null prototype] {
|
||||
qr: [Function (anonymous)],
|
||||
ready: [Function (anonymous)],
|
||||
auth_failure: [Function (anonymous)],
|
||||
authenticated: [Function (anonymous)],
|
||||
message: [AsyncFunction (anonymous)],
|
||||
message_create: [AsyncFunction (anonymous)]
|
||||
},
|
||||
_eventsCount: 6,
|
||||
_maxListeners: undefined,
|
||||
options: {
|
||||
authStrategy: LocalAuth {
|
||||
dataPath: 'C:\\Users\\cheve\\Documents\\GitHub\\botDemoGuna\\.wwebjs_auth',
|
||||
clientId: undefined,
|
||||
client: [Circular *1],
|
||||
userDataDir: 'C:\\Users\\cheve\\Documents\\GitHub\\botDemoGuna\\.wwebjs_auth\\session'
|
||||
},
|
||||
puppeteer: {
|
||||
headless: true,
|
||||
args: [Array],
|
||||
defaultViewport: null,
|
||||
userDataDir: 'C:\\Users\\cheve\\Documents\\GitHub\\botDemoGuna\\.wwebjs_auth\\session'
|
||||
},
|
||||
authTimeoutMs: 0,
|
||||
qrMaxRetries: 0,
|
||||
takeoverOnConflict: false,
|
||||
takeoverTimeoutMs: 0,
|
||||
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36',
|
||||
ffmpegPath: 'ffmpeg',
|
||||
bypassCSP: false
|
||||
},
|
||||
authStrategy: LocalAuth {
|
||||
dataPath: 'C:\\Users\\cheve\\Documents\\GitHub\\botDemoGuna\\.wwebjs_auth',
|
||||
clientId: undefined,
|
||||
client: [Circular *1],
|
||||
userDataDir: 'C:\\Users\\cheve\\Documents\\GitHub\\botDemoGuna\\.wwebjs_auth\\session'
|
||||
},
|
||||
pupBrowser: <ref *2> Browser {
|
||||
eventsMap: Map(2) { 'targetcreated' => [], 'targetchanged' => [] },
|
||||
emitter: {
|
||||
all: [Map],
|
||||
on: [Function: on],
|
||||
off: [Function: off],
|
||||
emit: [Function: emit]
|
||||
},
|
||||
_ignoredTargets: Set(0) {},
|
||||
_ignoreHTTPSErrors: false,
|
||||
_defaultViewport: null,
|
||||
_process: ChildProcess {
|
||||
_events: [Object: null prototype],
|
||||
_eventsCount: 1,
|
||||
_maxListeners: undefined,
|
||||
_closesNeeded: 2,
|
||||
_closesGot: 0,
|
||||
connected: false,
|
||||
signalCode: null,
|
||||
exitCode: null,
|
||||
killed: false,
|
||||
spawnfile: 'C:\\Users\\cheve\\Documents\\GitHub\\botDemoGuna\\node_modules\\puppeteer\\.local-chromium\\win64-982053\\chrome-win\\chrome.exe',
|
||||
_handle: [Process],
|
||||
spawnargs: [Array],
|
||||
pid: 7188,
|
||||
stdin: [Socket],
|
||||
stdout: null,
|
||||
stderr: [Socket],
|
||||
stdio: [Array],
|
||||
[Symbol(kCapture)]: false
|
||||
},
|
||||
_screenshotTaskQueue: TaskQueue { _chain: [Promise] },
|
||||
_connection: Connection {
|
||||
eventsMap: [Map],
|
||||
emitter: [Object],
|
||||
_lastId: 372,
|
||||
_sessions: [Map],
|
||||
_closed: false,
|
||||
_callbacks: Map(0) {},
|
||||
_url: 'ws://127.0.0.1:49386/devtools/browser/8ba98a74-7751-45aa-8256-8f82b8312e65',
|
||||
_delay: 0,
|
||||
_transport: [NodeWebSocketTransport]
|
||||
},
|
||||
_closeCallback: [Function: bound close],
|
||||
_targetFilterCallback: [Function (anonymous)],
|
||||
_defaultContext: BrowserContext {
|
||||
eventsMap: Map(0) {},
|
||||
emitter: [Object],
|
||||
_connection: [Connection],
|
||||
_browser: [Circular *2],
|
||||
_id: undefined
|
||||
},
|
||||
_contexts: Map(0) {},
|
||||
_targets: Map(5) {
|
||||
'4904d96d-4dec-4069-95d8-fe7d70f62b06' => [Target],
|
||||
'71cc8c5e-8516-49de-9387-b2940074aea5' => [Target],
|
||||
'C7071524BC87DF4C8E9569AD3FBB7348' => [Target],
|
||||
'1D7791C3C62A14FB306A0ABD1CD86677' => [Target],
|
||||
'969B67293789E4A52B827E4619DF58D7' => [Target]
|
||||
}
|
||||
},
|
||||
pupPage: <ref *3> Page {
|
||||
eventsMap: Map(1) { 'framenavigated' => [Array] },
|
||||
emitter: {
|
||||
all: [Map],
|
||||
on: [Function: on],
|
||||
off: [Function: off],
|
||||
emit: [Function: emit]
|
||||
},
|
||||
_closed: false,
|
||||
_timeoutSettings: TimeoutSettings {
|
||||
_defaultTimeout: null,
|
||||
_defaultNavigationTimeout: null
|
||||
},
|
||||
_pageBindings: Map(12) {
|
||||
'loadingScreen' => [AsyncFunction (anonymous)],
|
||||
'qrChanged' => [AsyncFunction (anonymous)],
|
||||
'onAddMessageEvent' => [Function (anonymous)],
|
||||
'onChangeMessageTypeEvent' => [Function (anonymous)],
|
||||
'onChangeMessageEvent' => [Function (anonymous)],
|
||||
'onRemoveMessageEvent' => [Function (anonymous)],
|
||||
'onMessageAckEvent' => [Function (anonymous)],
|
||||
'onMessageMediaUploadedEvent' => [Function (anonymous)],
|
||||
'onAppStateChangedEvent' => [AsyncFunction (anonymous)],
|
||||
'onBatteryStateChangedEvent' => [Function (anonymous)],
|
||||
'onIncomingCall' => [Function (anonymous)],
|
||||
'onReaction' => [Function (anonymous)]
|
||||
},
|
||||
_javascriptEnabled: true,
|
||||
_workers: Map(1) { '96E97F3B444D00EB81EFEFDBC3128749' => [WebWorker] },
|
||||
_fileChooserInterceptors: Set(0) {},
|
||||
_userDragInterceptionEnabled: false,
|
||||
_handlerMap: WeakMap { <items unknown> },
|
||||
_client: CDPSession {
|
||||
eventsMap: [Map],
|
||||
emitter: [Object],
|
||||
_callbacks: Map(0) {},
|
||||
_connection: [Connection],
|
||||
_targetType: 'page',
|
||||
_sessionId: '44F15C73737F3B036CBCBE340984F10E'
|
||||
},
|
||||
_target: Target {
|
||||
_targetInfo: [Object],
|
||||
_browserContext: [BrowserContext],
|
||||
_targetId: 'C7071524BC87DF4C8E9569AD3FBB7348',
|
||||
_sessionFactory: [Function (anonymous)],
|
||||
_ignoreHTTPSErrors: false,
|
||||
_defaultViewport: null,
|
||||
_screenshotTaskQueue: [TaskQueue],
|
||||
_pagePromise: [Promise],
|
||||
_workerPromise: null,
|
||||
_initializedCallback: [Function (anonymous)],
|
||||
_initializedPromise: [Promise],
|
||||
_closedCallback: [Function (anonymous)],
|
||||
_isClosedPromise: [Promise],
|
||||
_isInitialized: true
|
||||
},
|
||||
_keyboard: Keyboard {
|
||||
_modifiers: 0,
|
||||
_pressedKeys: Set(0) {},
|
||||
_client: [CDPSession]
|
||||
},
|
||||
_mouse: Mouse {
|
||||
_x: 0,
|
||||
_y: 0,
|
||||
_button: 'none',
|
||||
_client: [CDPSession],
|
||||
_keyboard: [Keyboard]
|
||||
},
|
||||
_touchscreen: Touchscreen { _client: [CDPSession], _keyboard: [Keyboard] },
|
||||
_accessibility: Accessibility { _client: [CDPSession] },
|
||||
_frameManager: FrameManager {
|
||||
eventsMap: [Map],
|
||||
emitter: [Object],
|
||||
_frames: [Map],
|
||||
_contextIdToContext: [Map],
|
||||
_isolatedWorlds: [Set],
|
||||
_client: [CDPSession],
|
||||
_page: [Circular *3],
|
||||
_networkManager: [NetworkManager],
|
||||
_timeoutSettings: [TimeoutSettings],
|
||||
_mainFrame: [Frame]
|
||||
},
|
||||
_emulationManager: EmulationManager {
|
||||
_emulatingMobile: false,
|
||||
_hasTouch: false,
|
||||
_client: [CDPSession]
|
||||
},
|
||||
_tracing: Tracing { _recording: false, _path: '', _client: [CDPSession] },
|
||||
_coverage: Coverage { _jsCoverage: [JSCoverage], _cssCoverage: [CSSCoverage] },
|
||||
_screenshotTaskQueue: TaskQueue { _chain: [Promise] },
|
||||
_viewport: null
|
||||
},
|
||||
info: ClientInfo {
|
||||
pushname: 'Omega',
|
||||
wid: {
|
||||
server: 'c.us',
|
||||
user: '5215527026728',
|
||||
_serialized: '5215527026728@c.us'
|
||||
},
|
||||
me: {
|
||||
server: 'c.us',
|
||||
user: '5215527026728',
|
||||
_serialized: '5215527026728@c.us'
|
||||
},
|
||||
phone: undefined,
|
||||
platform: 'android'
|
||||
},
|
||||
interface: InterfaceController {
|
||||
pupPage: <ref *3> Page {
|
||||
eventsMap: [Map],
|
||||
emitter: [Object],
|
||||
_closed: false,
|
||||
_timeoutSettings: [TimeoutSettings],
|
||||
_pageBindings: [Map],
|
||||
_javascriptEnabled: true,
|
||||
_workers: [Map],
|
||||
_fileChooserInterceptors: Set(0) {},
|
||||
_userDragInterceptionEnabled: false,
|
||||
_handlerMap: [WeakMap],
|
||||
_client: [CDPSession],
|
||||
_target: [Target],
|
||||
_keyboard: [Keyboard],
|
||||
_mouse: [Mouse],
|
||||
_touchscreen: [Touchscreen],
|
||||
_accessibility: [Accessibility],
|
||||
_frameManager: [FrameManager],
|
||||
_emulationManager: [EmulationManager],
|
||||
_tracing: [Tracing],
|
||||
_coverage: [Coverage],
|
||||
_screenshotTaskQueue: [TaskQueue],
|
||||
_viewport: null
|
||||
}
|
||||
},
|
||||
theMsg: Message {
|
||||
_data: {
|
||||
id: [Object],
|
||||
body: '/Guna',
|
||||
type: 'chat',
|
||||
t: 1675378555,
|
||||
notifyName: 'Alfredo',
|
||||
from: '5215519561677@c.us',
|
||||
to: '5215527026728@c.us',
|
||||
self: 'in',
|
||||
ack: 1,
|
||||
isNewMsg: true,
|
||||
star: false,
|
||||
kicNotified: false,
|
||||
recvFresh: true,
|
||||
isFromTemplate: false,
|
||||
pollInvalidated: false,
|
||||
isSentCagPollCreation: false,
|
||||
latestEditMsgKey: null,
|
||||
latestEditSenderTimestampMs: null,
|
||||
broadcast: false,
|
||||
mentionedJidList: [],
|
||||
isVcardOverMmsDocument: false,
|
||||
isForwarded: false,
|
||||
hasReaction: false,
|
||||
productHeaderImageRejected: false,
|
||||
lastPlaybackProgress: 0,
|
||||
isDynamicReplyButtonsMsg: false,
|
||||
isMdHistoryMsg: false,
|
||||
stickerSentTs: 0,
|
||||
isAvatar: false,
|
||||
requiresDirectConnection: false,
|
||||
pttForwardedFeaturesEnabled: true,
|
||||
isEphemeral: false,
|
||||
isStatusV3: false,
|
||||
links: []
|
||||
},
|
||||
mediaKey: undefined,
|
||||
id: {
|
||||
fromMe: false,
|
||||
remote: '5215519561677@c.us',
|
||||
id: '3A98BA96F6922B404213',
|
||||
_serialized: 'false_5215519561677@c.us_3A98BA96F6922B404213'
|
||||
},
|
||||
ack: 1,
|
||||
hasMedia: false,
|
||||
body: '/Guna',
|
||||
type: 'chat',
|
||||
timestamp: 1675378555,
|
||||
from: '5215519561677@c.us',
|
||||
to: '5215527026728@c.us',
|
||||
author: undefined,
|
||||
deviceType: 'ios',
|
||||
isForwarded: false,
|
||||
forwardingScore: 0,
|
||||
isStatus: false,
|
||||
isStarred: false,
|
||||
broadcast: false,
|
||||
fromMe: false,
|
||||
hasQuotedMsg: false,
|
||||
duration: undefined,
|
||||
location: undefined,
|
||||
vCards: [],
|
||||
inviteV4: undefined,
|
||||
mentionedIds: [],
|
||||
orderId: undefined,
|
||||
token: undefined,
|
||||
isGif: false,
|
||||
isEphemeral: false,
|
||||
links: [],
|
||||
numero: '5215519561677@c.us',
|
||||
key: 'gunaCats',
|
||||
lastStep: null,
|
||||
step: 'gunaCats',
|
||||
trigger: null,
|
||||
replyMessage: 'Mensaje de getGunaCats'
|
||||
},
|
||||
[Symbol(kCapture)]: false
|
||||
}
|
||||
+++++++++++++++++++++++++++++++++++++ INICIO +++++++++++++++++++++++++++++++++++++++
|
||||
HORA:4:56:00 PM FROM:5215519561677@c.us, BODY:DULCES, HASMEDIA:false
|
||||
======= KEY ES NULO USAMOS REGEXP =======
|
||||
KEY=|doblemensaje|
|
||||
Esta Key=doblemensaje - pasoReq=menu - PasoAnt=undefined|gunaCats
|
||||
NO CUMPLE PASO REQ
|
||||
pasoReq=menu - PasoAnt=undefined
|
||||
KEY=|recibenombre|
|
||||
Esta Key=recibenombre - pasoReq=opcion3 - PasoAnt=undefined|gunaCats
|
||||
NO CUMPLE PASO REQ
|
||||
pasoReq=opcion3 - PasoAnt=undefined
|
||||
KEY=|gRevisaCliente|
|
||||
Esta Key=gRevisaCliente - pasoReq=gallina - PasoAnt=undefined|gunaCats
|
||||
NO CUMPLE PASO REQ
|
||||
pasoReq=gallina - PasoAnt=undefined
|
||||
KEY=|gGuardainfo|
|
||||
Esta Key=gGuardainfo - pasoReq=gRevisaCliente - PasoAnt=undefined|gunaCats
|
||||
NO CUMPLE PASO REQ
|
||||
pasoReq=gRevisaCliente - PasoAnt=undefined
|
||||
KEY=|paq3|
|
||||
Esta Key=paq3 - pasoReq=menu - PasoAnt=undefined|gunaCats
|
||||
NO CUMPLE PASO REQ
|
||||
pasoReq=menu - PasoAnt=undefined
|
||||
KEY=|Desbloqueo|
|
||||
Esta Key=Desbloqueo - pasoReq=soporte - PasoAnt=undefined|gunaCats
|
||||
NO CUMPLE PASO REQ
|
||||
pasoReq=soporte - PasoAnt=undefined
|
||||
KEY=|gunaCats2|
|
||||
Esta Key=gunaCats2 - pasoReq=gunaCats - PasoAnt=undefined|gunaCats
|
||||
NUEVA RESPUESTA= Mensaje de getGunaCats2
|
||||
############# Encontramos Funcion, ejecutamos funcion getGunaSubtipo
|
||||
1 { id: 'KINDER', title: 'KINDER' }
|
||||
2 { id: 'CHOCOLATE', title: 'CHOCOLATE' }
|
||||
lasOpciones=undefined
|
||||
+++++++++++++++++++++++++++++++++++++ INICIO +++++++++++++++++++++++++++++++++++++++
|
||||
HORA:4:56:05 PM FROM:5215519561677@c.us, BODY:CHOCOLATE, HASMEDIA:false
|
||||
======= KEY ES NULO USAMOS REGEXP =======
|
||||
KEY=|doblemensaje|
|
||||
Esta Key=doblemensaje - pasoReq=menu - PasoAnt=undefined|gunaCats2
|
||||
NO CUMPLE PASO REQ
|
||||
pasoReq=menu - PasoAnt=undefined
|
||||
KEY=|recibenombre|
|
||||
Esta Key=recibenombre - pasoReq=opcion3 - PasoAnt=undefined|gunaCats2
|
||||
NO CUMPLE PASO REQ
|
||||
pasoReq=opcion3 - PasoAnt=undefined
|
||||
KEY=|gRevisaCliente|
|
||||
Esta Key=gRevisaCliente - pasoReq=gallina - PasoAnt=undefined|gunaCats2
|
||||
NO CUMPLE PASO REQ
|
||||
pasoReq=gallina - PasoAnt=undefined
|
||||
KEY=|gGuardainfo|
|
||||
Esta Key=gGuardainfo - pasoReq=gRevisaCliente - PasoAnt=undefined|gunaCats2
|
||||
NO CUMPLE PASO REQ
|
||||
pasoReq=gRevisaCliente - PasoAnt=undefined
|
||||
KEY=|paq3|
|
||||
Esta Key=paq3 - pasoReq=menu - PasoAnt=undefined|gunaCats2
|
||||
NO CUMPLE PASO REQ
|
||||
pasoReq=menu - PasoAnt=undefined
|
||||
KEY=|Desbloqueo|
|
||||
Esta Key=Desbloqueo - pasoReq=soporte - PasoAnt=undefined|gunaCats2
|
||||
NO CUMPLE PASO REQ
|
||||
pasoReq=soporte - PasoAnt=undefined
|
||||
KEY=|gunaCats2|
|
||||
Esta Key=gunaCats2 - pasoReq=gunaCats - PasoAnt=undefined|gunaCats2
|
||||
NO CUMPLE PASO REQ
|
||||
pasoReq=gunaCats - PasoAnt=undefined
|
||||
KEY=|gunaProds|
|
||||
Esta Key=gunaProds - pasoReq=gunaCats2 - PasoAnt=undefined|gunaCats2
|
||||
NUEVA RESPUESTA= Mensaje de getGunaCats2
|
||||
############# Encontramos Funcion, ejecutamos funcion getGunaProds
|
||||
386
app.js
386
app.js
@@ -5,6 +5,7 @@ require('dotenv').config()
|
||||
const fs = require('fs');
|
||||
const express = require('express');
|
||||
global.siguientePaso = [{"numero":"1", "va":"XXX"}]; //MOD by CHV - Agregamos para pasar el VAMOSA a "index.js"
|
||||
global.pasoAnterior = [];
|
||||
const cors = require('cors')
|
||||
const axios = require('axios').default;//MOD by CHV - Agregamos para el get del "/URL"
|
||||
const qrcode = require('qrcode-terminal');
|
||||
@@ -16,12 +17,14 @@ const { connectionReady, connectionLost } = require('./controllers/connection')
|
||||
const { saveMedia, saveMediaToGoogleDrive } = require('./controllers/save')
|
||||
const { getMessages, responseMessages, bothResponse, waitFor } = require('./controllers/flows')
|
||||
const { sendMedia, sendMessage, lastTrigger, sendMessageButton, sendMessageList, readChat } = require('./controllers/send');
|
||||
const { remplazos, stepsInitial} = require('./adapter/index');//MOD by CHV - Agregamos para utilizar remplazos y stepsInitial
|
||||
const { remplazos, stepsInitial, vamosA } = require('./adapter/index');//MOD by CHV - Agregamos para utilizar remplazos y stepsInitial
|
||||
const { isUndefined } = require('util');
|
||||
const { isSet } = require('util/types');
|
||||
const { Console } = require('console');
|
||||
const { ClientRequest } = require('http');
|
||||
const { guardaXLSDatos, leeXLSDatos} = require('./Excel');
|
||||
const { ContextsClient } = require('@google-cloud/dialogflow');
|
||||
const { ingresarDatos, leerDatos } = require('./implementaciones/sheets')
|
||||
const app = express();
|
||||
app.use(cors())
|
||||
app.use(express.json())
|
||||
@@ -32,9 +35,10 @@ const port = process.env.PORT || 3000
|
||||
var client;
|
||||
var dialogflowFilter = false;
|
||||
var totalMsjs; //MOD by CHV -
|
||||
var vamosA = ""; //MOD by CHV -
|
||||
// var vamosA = ""; //MOD by CHV -
|
||||
var newBody; //MOD by CHV -
|
||||
var nuevaRespuesta; //MOD by CHV - Se agrego para los remplazos
|
||||
var vars = []
|
||||
app.use('/', require('./routes/web'))
|
||||
|
||||
/**
|
||||
@@ -42,14 +46,16 @@ app.use('/', require('./routes/web'))
|
||||
*/
|
||||
const listenMessage = () => client.on('message', async msg => {
|
||||
const { from, body, hasMedia } = msg;
|
||||
if (vars[from] === undefined) vars[from] = []
|
||||
// console.log("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
|
||||
console.log("+++++++++++++++++++++++++++++++++++++ INICIO +++++++++++++++++++++++++++++++++++++++");
|
||||
// console.log("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
|
||||
client.theMsg = msg;
|
||||
console.log("HORA:"+new Date().toLocaleTimeString()+" FROM:"+from+", BODY:"+body+", HASMEDIA:"+hasMedia);
|
||||
// console.log("%%%%%%%%% userAgent = " + client?.options?.userAgent)
|
||||
console.log("HORA:"+new Date().toLocaleTimeString()+" FROM:"+from+", BODY:"+body+", HASMEDIA:"+hasMedia+", DEVICETYPE:"+client.theMsg?.deviceType);
|
||||
newBody = removeDiacritics(body) //MOD by CHV - Agregamos para quitar acentos
|
||||
// newBody = remplazos(newBody);
|
||||
vamosA = "";
|
||||
// vamosA = "";
|
||||
if(!isValidNumber(from)){
|
||||
return
|
||||
}
|
||||
@@ -59,9 +65,16 @@ const listenMessage = () => client.on('message', async msg => {
|
||||
}
|
||||
message = newBody.toLowerCase();
|
||||
const number = cleanNumber(from)
|
||||
client.theMsg['numero'] = number
|
||||
|
||||
// Guardamos el mensaje en Google Sheets
|
||||
ingresarDatos(from, body)
|
||||
|
||||
|
||||
// console.log(stepsInitial)
|
||||
var { key } = stepsInitial.find(k => k.keywords.includes(message)) || { key: null }//MOD by CHV - Se agrega para obtener KEY
|
||||
await readChat(number, message, null , key) //MOD by CHV - Agregamos key/regla para guardarla en "chats/numero.json"
|
||||
client.theMsg['key'] = key
|
||||
|
||||
/**
|
||||
* Guardamos el archivo multimedia que envia
|
||||
@@ -74,7 +87,7 @@ const listenMessage = () => client.on('message', async msg => {
|
||||
/**
|
||||
* Si estas usando dialogflow solo manejamos una funcion todo es IA
|
||||
*/
|
||||
|
||||
|
||||
if (process.env.DATABASE === 'dialogflow') {
|
||||
if (process.env.DIALOGFLOW_MEDIA_FOR_SLOT_FILLING === 'true' && dialogflowFilter) {
|
||||
waitFor(_ => hasMedia, 30000)
|
||||
@@ -102,8 +115,6 @@ const listenMessage = () => client.on('message', async msg => {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
|
||||
if(body=='/listas'){
|
||||
const productList = new List(
|
||||
"Here's our list of products at 50% off",
|
||||
@@ -133,13 +144,13 @@ const listenMessage = () => client.on('message', async msg => {
|
||||
// await sendMessageList(client, '5215527049036@c.us', null, lista);
|
||||
// await sendMessageList(client, '5215554192439@c.us', null, lista);
|
||||
// client.sendMessage(from, lista);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PRUEBA BOTONES NUEVOS
|
||||
*/
|
||||
// if(body=="579"){
|
||||
// const buttons_reply = new Buttons("Por favor vuelve a intentar, mandando *SOLO* la palabra *gallina* con una diagonal al principio 👇🏽 \n\n */gallina*\n ", [{body: "/gallina", id: 'errorGallina'}], 'Error', 'O haz clic en el siguiente botón') // Reply button
|
||||
/**
|
||||
* PRUEBA BOTONES NUEVOS
|
||||
*/
|
||||
// if(body=="579"){
|
||||
// const buttons_reply = new Buttons("Por favor vuelve a intentar, mandando *SOLO* la palabra *gallina* con una diagonal al principio 👇🏽 \n\n */gallina*\n ", [{body: "/gallina", id: 'errorGallina'}], 'Error', 'O haz clic en el siguiente botón') // Reply button
|
||||
// for (const component of [buttons_reply]) await client.sendMessage(from, component);
|
||||
// }
|
||||
|
||||
@@ -149,16 +160,18 @@ const listenMessage = () => client.on('message', async msg => {
|
||||
* a tu gusto!
|
||||
*/
|
||||
|
||||
const lastStep = await lastTrigger(from) || null;
|
||||
// console.log("LAST STEP="+lastStep+", FROM:"+from);
|
||||
if (lastStep) {
|
||||
const response = await responseMessages(lastStep)
|
||||
console.log("CLIENT="+client+", FROM:"+from+", REPLYMESSAGE:"+response.replyMessage);
|
||||
// await sendMessage(client, from, response.replyMessage, lastStep); // Mod by CHV - Para mandar varios mensajes en el mismo response, se cambio esta linea por el forEach de abajo.
|
||||
response.replyMessage.forEach( async messages => {
|
||||
var thisMsg = messages.mensaje
|
||||
if(Array.isArray(messages.mensaje)){thisMsg = messages.mensaje.join('\n')}
|
||||
await sendMessage(client, from, remplazos(thisMsg, client), response.trigger);
|
||||
const lastStep = await lastTrigger(from) || null;
|
||||
client.theMsg['lastStep'] = lastStep
|
||||
// console.log("LAST STEP="+lastStep+", FROM:"+from);
|
||||
if (lastStep) {
|
||||
const response = await responseMessages(lastStep)
|
||||
client.theMsg['trigger'] = response.trigger
|
||||
console.log("CLIENT="+client+", FROM:"+from+", REPLYMESSAGE:"+response.replyMessage);
|
||||
// await sendMessage(client, from, response.replyMessage, lastStep); // Mod by CHV - Para mandar varios mensajes en el mismo response, se cambio esta linea por el forEach de abajo.
|
||||
response.replyMessage.forEach( async messages => {
|
||||
var thisMsg = messages.mensaje
|
||||
if(Array.isArray(messages.mensaje)){thisMsg = messages.mensaje.join('\n')}
|
||||
await sendMessage(client, from, remplazos(thisMsg, client), response.trigger);
|
||||
})
|
||||
}
|
||||
|
||||
@@ -170,17 +183,15 @@ const listenMessage = () => client.on('message', async msg => {
|
||||
// console.log("****** STEP="+step);
|
||||
// console.log("****** MESSAGE:"+message);
|
||||
const step = await getMessages(message, from);
|
||||
client.theMsg['step'] = step
|
||||
if (step) {
|
||||
const response = await responseMessages(step);
|
||||
|
||||
client.theMsg['trigger'] = response.trigger
|
||||
var resps = require('./flow/response.json');
|
||||
nuevaRespuesta = remplazos(resps[step].replyMessage.join(''), client);
|
||||
client.theMsg['replyMessage'] = nuevaRespuesta
|
||||
var pasoRequerido = resps[step].pasoRequerido;
|
||||
// var hayRequest = false;
|
||||
// if(hayRequest==false && nuevaRespuesta.search("/URL")>-1){console.log("Paramos flujo para que no mande el mensaje '/URL'."); return;}//Si el trigger es desbloqueo ya no hace nada mas.
|
||||
|
||||
// nuevaRespuesta = remplazos(resps[step].replyMessage.join(''), client);
|
||||
console.log('NUEVA RESPUESTA=', nuevaRespuesta)
|
||||
// console.log('NUEVA RESPUESTA=', nuevaRespuesta)
|
||||
|
||||
if(nuevaRespuesta.search("/URL")>-1){
|
||||
// Necesita instalado axios version 0.27.2 (npm i axios@0.27.2), si se instala una version mas nueva manda error de "GET no definido" o algo asi.
|
||||
@@ -213,63 +224,201 @@ const listenMessage = () => client.on('message', async msg => {
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Llama el API para tre categoria de Guna.
|
||||
* Llama el API para traer categorias de Guna.
|
||||
* @param {*} ctx El objeto del mensaje.
|
||||
*/
|
||||
async function getGunaCats(ctx) {
|
||||
// let par1 = ctx.theMsg.body
|
||||
// let theUrl = `http://localhost:8888/dbrquery?j={"query":"selectTipoFerreroMty","exec":"ExecuteQuery","params":{"par1":"${par1}"}}`
|
||||
// const RES = await axios.get(theUrl).then(function (response) {
|
||||
// console.log('getGunaCats = ', response.data.respuesta.length, response.data.respuesta)
|
||||
// let elMensaje = "%saludo%,\nEscoge una de nuestras categorías:\n\n"
|
||||
// let lasOpciones = "["
|
||||
// for(reg=0;reg<response.data.respuesta.length;reg++) {
|
||||
// // console.log("*** ", response.data.respuesta[reg])
|
||||
// lasOpciones = lasOpciones + `{id:'${response.data.respuesta[reg].CAT_PT_DESC}', title:'${response.data.respuesta[reg].CAT_PT_DESC}'}`
|
||||
// if(reg<response.data.respuesta.length-1) {lasOpciones=lasOpciones + ','}
|
||||
// elMensaje = elMensaje + (reg+1) + " .- " + response.data.respuesta[reg].CAT_PT_DESC + "\n"
|
||||
// }
|
||||
// lasOpciones = lasOpciones + "]"
|
||||
// console.log("lasOpciones="+lasOpciones)
|
||||
// const productList = new List(
|
||||
// "Aqui está la lista de nuestras categorias",
|
||||
// "Ver las categorías",
|
||||
// [
|
||||
// {
|
||||
// title: "Lista de categprías",
|
||||
// rows: lasOpciones,
|
||||
// }
|
||||
// ],
|
||||
// "Selecciona una categoría"
|
||||
// )
|
||||
|
||||
// client.sendMessage(from, productList)
|
||||
// // sendMessagList(client, from, null, productList);
|
||||
// return "1"
|
||||
// }).catch(function (error) {
|
||||
// console.log(error);
|
||||
// return error
|
||||
// });
|
||||
|
||||
const productList = {
|
||||
"body":"Hola *%primer_nombre%*, estos son ejemplos del uso de expresiones regulares, *todas* las opciones de la *lista* disparan la misma regla:\n\n'*pak*3*|*pak*angular*|*paquete*3*|*paquete*angular*'\n\nAutomáticamente el flujo se regresa al *menú*, asi que puedes poner nuevamente un número del 1 al 5 sin necesidad de volver a iniciar con */menu*.",
|
||||
"buttonText":"Ver los ejemplos de RegEx",
|
||||
"sections": [
|
||||
{"title":"Selecciona un mensaje:",
|
||||
"rows":[
|
||||
{"id": "paq3", "title": "Me gusta el paquete 3"},
|
||||
{"id": "paqA", "title": "Por favor mas info del paquete de Angular"},
|
||||
{"id": "pakA", "title": "Me gustó el pak de Angular"},
|
||||
{"id": "pak3", "title": "Estoy interesado en el pak 3"}
|
||||
]
|
||||
}
|
||||
],
|
||||
"title":"Por favor selecciona un producto"
|
||||
}
|
||||
sendMessageList(client, from, null, productList)
|
||||
// client.sendMessage(from, productList)
|
||||
|
||||
let par1 = ctx.theMsg.body
|
||||
let theUrl = `http://localhost:8888/dbrquery?j={"query":"selectTipoFerreroMty","exec":"ExecuteQuery","params":{"par1":"${par1}"}}`
|
||||
const RES = await axios.get(theUrl).then(function (response) {
|
||||
let lasOpciones = []
|
||||
for(reg=0;reg<response.data.respuesta.length;reg++) {
|
||||
let tempItem = {}
|
||||
tempItem['id']=response.data.respuesta[reg].CAT_PT_DESC
|
||||
tempItem['title']=response.data.respuesta[reg].CAT_PT_DESC
|
||||
lasOpciones.push(tempItem)
|
||||
console.log(lasOpciones.length, tempItem)
|
||||
}
|
||||
// console.log("lasOpciones="+lasOpciones[1])
|
||||
const productList = new List(
|
||||
remplazos("%saludo%, selecciona una categoría 👇🏽"),
|
||||
"Ver las categorías",
|
||||
[
|
||||
{ title: "Categorías",
|
||||
rows: lasOpciones,
|
||||
}
|
||||
],
|
||||
"Categorías",
|
||||
"Selecciona"
|
||||
)
|
||||
console.log(productList)
|
||||
client.sendMessage(from, productList)
|
||||
// console.log(ctx)
|
||||
// sendMessagList(client, from, null, productList);
|
||||
return "1"
|
||||
}).catch(function (error) {
|
||||
console.log(error);
|
||||
return error
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Llama el API para traer subcategorias de Guna.
|
||||
* @param {*} ctx El objeto del mensaje.
|
||||
*/
|
||||
async function getGunaSubtipo(ctx) {
|
||||
let par1 = ctx.theMsg.body
|
||||
vars[from]['tipo'] = ctx.theMsg.body
|
||||
// console.log("V_TIPO=", from, vars[from]['tipo'])
|
||||
let theUrl = `http://localhost:8888/dbrquery?j={"query":"selectSubtipoFerreroMty","exec":"ExecuteQuery","params":{"par1":"${vars[from]['tipo']}"}}`
|
||||
const RES = await axios.get(theUrl).then(function (response) {
|
||||
if( response.data.respuesta.length == 0 ) {
|
||||
console.log("No hay resultados",from)
|
||||
vamosA(from, "gunaCats")
|
||||
client.sendMessage(from, "Esa categoría *no existe*, por favor revisa y vuelve a intentar.")
|
||||
}
|
||||
let elMensaje = "Gracias,\nAhora una subcategoría:\n\n"
|
||||
let lasOpciones = []
|
||||
for(reg=0;reg<response.data.respuesta.length;reg++) {
|
||||
let tempItem = {}
|
||||
tempItem['id']=response.data.respuesta[reg].CAT_PS_DESC
|
||||
tempItem['title']=response.data.respuesta[reg].CAT_PS_DESC
|
||||
lasOpciones.push(tempItem)
|
||||
console.log(lasOpciones.length, tempItem)
|
||||
}
|
||||
// console.log("lasOpciones="+lasOpciones[3])
|
||||
const productList = new List(
|
||||
"Selecciona una subcategoria 👇🏽",
|
||||
"Ver las subcategorías",
|
||||
[
|
||||
{ title: "Subcategorías",
|
||||
rows: lasOpciones,
|
||||
}
|
||||
],
|
||||
`CATEGORÍA ${body}`
|
||||
)
|
||||
client.sendMessage(from, productList)
|
||||
return "1"
|
||||
}).catch(function (error) {
|
||||
console.log(error);
|
||||
return error
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Llama el API para traer productos de Guna.
|
||||
* @param {*} ctx El objeto del mensaje.
|
||||
*/
|
||||
async function getGunaProds(ctx) {
|
||||
if(vars[from]['recompra'] === undefined) vars[from]['subtipo'] = ctx.theMsg.body
|
||||
let theUrl = `http://localhost:8888/dbrquery?j={"query":"selectProdsFerreroMty","exec":"ExecuteQuery","params":{"par1":"${vars[from]['tipo']}", "par2":"${vars[from]['subtipo']}"}}`
|
||||
const RES = await axios.get(theUrl).then(function (response) {
|
||||
let elMensaje = "Gracias,\nAhora un producto:\n\n"
|
||||
let lasOpciones = []
|
||||
for(reg=0;reg<response.data.respuesta.length;reg++) {
|
||||
let tempItem = {}
|
||||
tempItem['id']=response.data.respuesta[reg].CAT_GP_ID
|
||||
tempItem['title']=`${response.data.respuesta[reg].CAT_GP_NOMBRE} $${response.data.respuesta[reg].CAT_GP_PRECIO}, INV:${response.data.respuesta[reg].CAT_GP_ALMACEN} `
|
||||
lasOpciones.push(tempItem)
|
||||
}
|
||||
const productList = new List(
|
||||
"Selecciona un producto 👇🏽",
|
||||
"Ver los productos",
|
||||
[
|
||||
{ title: "Productos",
|
||||
rows: lasOpciones,
|
||||
}
|
||||
],
|
||||
`SUBCATEGORÍA ${body}`,
|
||||
"Footer"
|
||||
)
|
||||
client.sendMessage(from, productList)
|
||||
return "1"
|
||||
}).catch(function (error) {
|
||||
console.log(error);
|
||||
return error
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Llama el API para traer productos de Guna.
|
||||
* @param {*} ctx El objeto del mensaje.
|
||||
*/
|
||||
async function agregaProds(ctx) {
|
||||
// vars[from]['subtipo'] = ctx.theMsg.body
|
||||
if(vars[from]['prods'] === undefined) { vars[from]['prods'] = [] }
|
||||
let elProd = ctx.theMsg.body
|
||||
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'][elProd])
|
||||
let elMensaje = ctx.theMsg.replyMessage
|
||||
let re = ctx.theMsg.body.trim().toLowerCase()
|
||||
elMensaje = elMensaje.replace(re, elProd.toLowerCase())
|
||||
sendMessage(client, from, elMensaje, ctx.theMsg.trigger, ctx.theMsg.step);
|
||||
return
|
||||
}
|
||||
/**
|
||||
* Tomamos la cantidad del producto seleccionado.
|
||||
* @param {*} ctx El objeto del mensaje.
|
||||
*/
|
||||
async function prodCantidad(ctx) {
|
||||
// console.log("Entramos a prodCantidad")
|
||||
let laCant = ctx.theMsg.body.trim()
|
||||
const reg = new RegExp('^[0-9]+$')
|
||||
let elProd = remplazos("%msjant_2%").toLowerCase()
|
||||
elProd = elProd.substring(0, elProd.indexOf(' $')).trim()
|
||||
if(reg.test(laCant)){
|
||||
console.log("Recibimos cant = " + laCant)
|
||||
console.log("EL_PROD=", vars[from]['prods'][elProd])
|
||||
console.log("precio=", vars[from]['prods'][elProd].precio)
|
||||
console.log("precio=", vars[from]['prods'][elProd]['precio'])
|
||||
vars[from]['prods'][elProd] = {"cant":laCant, "precio":vars[from]['prods'][elProd]['precio']}
|
||||
console.log(vars[from]['prods'])
|
||||
var elMensaje = ""
|
||||
const prods = Object.keys(vars[from]['prods']);
|
||||
prods.forEach((prod, index) => {
|
||||
elMensaje = elMensaje + `${vars[from]['prods'][prod].cant} - ${prod[0].toUpperCase() + prod.substring(1)}\n`
|
||||
console.log(`${prod}: ${vars[from]['prods'][prod]}`);
|
||||
});
|
||||
elMensaje = elMensaje + "\n¿Quieres agregar mas productos a tu orden?"
|
||||
// for(pr=0;pr<vars[from]['prods'].length;pr++){
|
||||
// elMensaje = elMensaje + vars[from]['prods'][pr]
|
||||
// }
|
||||
// sendMessage(client, from, elMensaje, response.trigger, step);
|
||||
var bts = {
|
||||
"title":"Tu orden",
|
||||
"message":elMensaje,
|
||||
"buttons":[
|
||||
{"body":"Terminar"},
|
||||
{"body":"Agregar productos"}
|
||||
]
|
||||
}
|
||||
sendMessageButton(client, from, "xxx", bts)
|
||||
}
|
||||
else{
|
||||
console.log("NO SOLO NUMS")
|
||||
vamosA(from, "gunaProdsAgrega")
|
||||
sendMessage(client, from, "Por favor escribe 👉🏽 *solo* 👈🏽 el número.", response.trigger, step);
|
||||
}
|
||||
return "1"
|
||||
}
|
||||
|
||||
/**
|
||||
* Mandamos nuevamente la lista de productos.
|
||||
* @param {*} ctx El objeto del mensaje.
|
||||
*/
|
||||
async function comprarMas(ctx) {
|
||||
console.log("Entramos a comprarMas")
|
||||
vars[from]['recompra'] = true
|
||||
await getGunaProds(ctx)
|
||||
vars[from]['recompra'] = false
|
||||
return "1"
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Llama el API para desbloquear un usuario.
|
||||
* @param {*} ctx El objeto del mensaje.
|
||||
@@ -296,12 +445,11 @@ const listenMessage = () => client.on('message', async msg => {
|
||||
* Si quieres ejecutar una función.
|
||||
*/
|
||||
if(response.hasOwnProperty('funcion')){
|
||||
console.log("############# Encontramos Funcion, ejecutamos funcion " + response.funcion)
|
||||
console.log("############# Encontramos función, ejecutamos la función '" + response.funcion + "'")
|
||||
laFuncion = response.funcion + "(client)"
|
||||
eval(laFuncion)
|
||||
return
|
||||
}
|
||||
|
||||
if(response.hasOwnProperty('urlXXXXXXX') && response.hasOwnProperty('values')){
|
||||
let theURL = response.url;
|
||||
let url0 = theURL
|
||||
@@ -322,7 +470,6 @@ const listenMessage = () => client.on('message', async msg => {
|
||||
desbloqueaUsuario2(url2, step) //Llamamos al API para desbloquear el usuario.
|
||||
return
|
||||
}
|
||||
|
||||
/**
|
||||
* Si quieres enviar imagen.
|
||||
*/
|
||||
@@ -373,45 +520,44 @@ const listenMessage = () => client.on('message', async msg => {
|
||||
if(actions['sections'] === undefined){ //Botones
|
||||
console.log("Botones")
|
||||
await sendMessageButton(client, from, null, actions);
|
||||
}
|
||||
else { //Listas
|
||||
console.log("Listas")
|
||||
// console.log(actions)
|
||||
await sendMessageList(client, from, null, actions);
|
||||
}
|
||||
}
|
||||
else{ //Listas
|
||||
console.log("Listas")
|
||||
// console.log(actions)
|
||||
await sendMessageList(client, from, null, actions);
|
||||
}
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if(body=='trae'){
|
||||
const rows = await leeXLSDatos('x')
|
||||
console.log("RESULTADOS:")
|
||||
// d.forEach(row => async function() {
|
||||
// console.log(row.nombre, row.edad, row.sexo)
|
||||
// client.sendMessage(from, `Hola ${row.nombre}, recuerda que tienes un adeudo pendiente`)
|
||||
// })
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
async function retardo() {
|
||||
for (sp=1;sp<rows.length;sp++) {
|
||||
// console.log(masivo[sp].numero+"@c.us");
|
||||
var rnd = getRandomInt(1,7); // Random entre 1 y 6 segundos.
|
||||
if(sp % 15 === 0){console.log("******** VAN 15, HACEMOS PAUSA DE 10 SEGUNDOS ********"); await sleep(10000);} //
|
||||
console.log(`============= Mandamos el mensaje ${sp} ==============`);
|
||||
var elTextoDelMensaje = `%saludo% ${rows[sp].prefijo} *${rows[sp].nombre}* con CARNET *${rows[sp].carnet}*, le saludamos de _CORPORACION AZUL_ le escribimos para recordarle que tiene un pago *pendiente* que se vence el *02/02/2023*`;
|
||||
await sleep(500);
|
||||
// let elNumero = '51968016860@c.us'
|
||||
let elNumero = '5215554192439@c.us'
|
||||
client.sendMessage(elNumero, remplazos(elTextoDelMensaje, client));
|
||||
console.log(`Esperamos ${rnd} segundos...`);
|
||||
await sleep(rnd*1000);
|
||||
if(body=='trae'){
|
||||
const rows = await leeXLSDatos('x')
|
||||
console.log("RESULTADOS:")
|
||||
// d.forEach(row => async function() {
|
||||
// console.log(row.nombre, row.edad, row.sexo)
|
||||
// client.sendMessage(from, `Hola ${row.nombre}, recuerda que tienes un adeudo pendiente`)
|
||||
// })
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
console.log('Terminamos');
|
||||
async function retardo() {
|
||||
for (sp=1;sp<rows.length;sp++) {
|
||||
// console.log(masivo[sp].numero+"@c.us");
|
||||
var rnd = getRandomInt(1,7); // Random entre 1 y 6 segundos.
|
||||
if(sp % 15 === 0){console.log("******** VAN 15, HACEMOS PAUSA DE 10 SEGUNDOS ********"); await sleep(10000);} //
|
||||
console.log(`============= Mandamos el mensaje ${sp} ==============`);
|
||||
var elTextoDelMensaje = `%saludo% ${rows[sp].prefijo} *${rows[sp].nombre}* con CARNET *${rows[sp].carnet}*, le saludamos de _CORPORACION AZUL_ le escribimos para recordarle que tiene un pago *pendiente* que se vence el *02/02/2023*`;
|
||||
await sleep(500);
|
||||
// let elNumero = '51968016860@c.us'
|
||||
let elNumero = '5215554192439@c.us'
|
||||
client.sendMessage(elNumero, remplazos(elTextoDelMensaje, client));
|
||||
console.log(`Esperamos ${rnd} segundos...`);
|
||||
await sleep(rnd*1000);
|
||||
}
|
||||
console.log('Terminamos');
|
||||
}
|
||||
retardo();
|
||||
}
|
||||
retardo();
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
============================================================================
|
||||
@@ -451,7 +597,7 @@ if(message=='/spam'){
|
||||
console.log('Done');
|
||||
}
|
||||
retardo();
|
||||
}
|
||||
}
|
||||
|
||||
function getRandomInt(min, max) {
|
||||
min = Math.ceil(min);
|
||||
|
||||
@@ -63,7 +63,7 @@ const sendMessage = async (client, number = null, text = null, trigger = null, r
|
||||
number = cleanNumber(number)
|
||||
const message = text
|
||||
client.sendMessage(number, message);
|
||||
console.log(number, message, regla)
|
||||
// console.log(number, message, regla)
|
||||
await readChat(number, message, trigger, regla) //MOD by CHV - Agregamos el parametro "regla"
|
||||
console.log(`⚡⚡⚡ Enviando mensajes....`);
|
||||
// console.log("********************* SEND MESSAGE **************************************");
|
||||
|
||||
@@ -25,7 +25,8 @@
|
||||
],
|
||||
"media":null,
|
||||
"trigger":null,
|
||||
"goto":"menu"
|
||||
"goto":"menu",
|
||||
"pasoRequerido":"menu"
|
||||
},
|
||||
"menu":{
|
||||
"keywords": ["/menu"],
|
||||
@@ -47,7 +48,7 @@
|
||||
"trigger":null
|
||||
},
|
||||
"opcion1":{
|
||||
"keywords": ["1"],
|
||||
"keywords": "1",
|
||||
"replyMessage":[
|
||||
{
|
||||
"mensaje":[
|
||||
@@ -67,7 +68,7 @@
|
||||
"goto":"menu"
|
||||
},
|
||||
"opcion2":{
|
||||
"keywords": ["2"],
|
||||
"keywords": "2",
|
||||
"replyMessage":[
|
||||
{
|
||||
"mensaje":[
|
||||
@@ -85,7 +86,7 @@
|
||||
"goto":"menu"
|
||||
},
|
||||
"opcion3":{
|
||||
"keywords": ["3"],
|
||||
"keywords": "3",
|
||||
"replyMessage":[
|
||||
{
|
||||
"mensaje":[
|
||||
@@ -179,7 +180,7 @@
|
||||
}
|
||||
},
|
||||
"lista":{
|
||||
"keywords": ["4"],
|
||||
"keywords": "4",
|
||||
"replyMessage":[
|
||||
{
|
||||
"mensaje":["*%saludo%*, este es un ejemplo de listas"]
|
||||
@@ -206,7 +207,7 @@
|
||||
"goto":"menu"
|
||||
},
|
||||
"botones":{
|
||||
"keywords": ["5"],
|
||||
"keywords": "5",
|
||||
"replyMessage":[
|
||||
{
|
||||
"mensaje":["*%saludo%*, este es un ejemplo de botones"]
|
||||
@@ -305,7 +306,7 @@
|
||||
"goto":"menu"
|
||||
},
|
||||
"botonespaq3":{
|
||||
"keywords": ["6"],
|
||||
"keywords": "6",
|
||||
"replyMessage":[
|
||||
{
|
||||
"mensaje":["*%saludo%*, este es un ejemplo de botones y regExp"]
|
||||
@@ -350,12 +351,62 @@
|
||||
"pasoRequerido":"soporte"
|
||||
},
|
||||
"gunaCats":{
|
||||
"keywords": "/guna",
|
||||
"keywords": ["/guna", "/demoventa", "/demoguna"],
|
||||
"replyMessage":[
|
||||
"Mensaje de getGunaCats"
|
||||
],
|
||||
"funcion":"getGunaCats",
|
||||
"media":null,
|
||||
"trigger":null
|
||||
},
|
||||
"gunaCats2":{
|
||||
"keywords": "*",
|
||||
"replyMessage":[
|
||||
"Mensaje de getGunaCats2"
|
||||
],
|
||||
"funcion":"getGunaSubtipo",
|
||||
"media":null,
|
||||
"trigger":null,
|
||||
"pasoRequerido":"gunaCats"
|
||||
},
|
||||
"gunaProds":{
|
||||
"keywords": "*",
|
||||
"replyMessage":[
|
||||
"Mensaje de getGunaCats2"
|
||||
],
|
||||
"funcion":"getGunaProds",
|
||||
"media":null,
|
||||
"trigger":null,
|
||||
"pasoRequerido":"gunaCats2"
|
||||
},
|
||||
"gunaProdsAgrega":{
|
||||
"keywords": "*",
|
||||
"replyMessage":[
|
||||
"Seleccionaste *%msjant_0%*, por favor indica la cantidad que quieres comprar (*solo el número*)."
|
||||
],
|
||||
"funcion":"agregaProds",
|
||||
"media":null,
|
||||
"trigger":null,
|
||||
"pasoRequerido":"gunaProds"
|
||||
},
|
||||
"gunaProdsCantidad":{
|
||||
"keywords": "*",
|
||||
"replyMessage":[
|
||||
"Recibi cantidad"
|
||||
],
|
||||
"funcion":"prodCantidad",
|
||||
"media":null,
|
||||
"trigger":null,
|
||||
"pasoRequerido":"gunaProdsAgrega"
|
||||
},
|
||||
"gunaComprarMas":{
|
||||
"keywords": ["Agregar productos"],
|
||||
"replyMessage":[
|
||||
"Quiero comprar mas."
|
||||
],
|
||||
"funcion":"comprarMas",
|
||||
"media":null,
|
||||
"trigger":null,
|
||||
"pasoRequerido":"gunaProdsCantidad"
|
||||
}
|
||||
}
|
||||
12
implementaciones/credenciales.json
Normal file
12
implementaciones/credenciales.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"type": "service_account",
|
||||
"project_id": "strong-maker-107118",
|
||||
"private_key_id": "419c2f761213d11f2f30edab66832a9c475e1d33",
|
||||
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDXlNkR2C9L7mXp\niMfPC4GwOKZcLIAa2XzrigJg3ettAHnWbxFSX4mS9AsmDKjBvkxpRVo+6gBzdtPa\nCZUQVZI6cWE+lCD2fMabwRQMosHxpRTUCruAnb/sku9y1o/KpdDemmqPaAHYxZXV\nex88svqcCPNhivqiPE/cRb1HoVu08IDG31Kgy3+iTpKQux05ngrYwem7wQl2k8dX\nS2SPp7YQID3gZeqWHyC2GVazn3Rz0PuKdp3wMnGB6MMI0yk3vLPHNpsEGyuyNeLG\nya68XBY86y9+LHZ8EwxUdVUmt8hUm0h5bDQftosRhgJakTUHZg9qNTM4iEJ7WYwP\nSao143C/AgMBAAECggEAI6kWxSm5HSWDdyot6cpR+sKhhjgYPW4XiLuCDDWkFsT6\n4nqUkhyFRylBBNttjkA6fI7BJbdojrEBIfKZf/kKYMorggICd94zrkULL3yRegr1\nfePZQ1EU6SnJxnnGkbN0cGDOWrLOMhDxFD4IcJknSmin9c0wYLt69wlpjNqcrw/B\ny6K63hi7M0iXGEHp8nz8Vf1l7VA82hCwUi7D73pkORH98xVY4+MYOTqrCvU0/O2m\nVqP5+mLMG/fPFlMnk8FgL3Q4dqiZ/ds7a6qXND5htSX0sFroINrTYiyXJ73OCgre\nlIbUuAD/92fuHKBdcIaaZvkEEAVTYlainm6LGroeSQKBgQDtq3mUTYO3998GiWO4\nVKnw7yC12WbwOaIDvlccWuTRWByJrRIJmsA1EXg18i9kf9AwxesbRT7xRBCwRMhs\nKUDbKaqvdf4BRARFWe0DSKQZIJpjCQsOtmOaV3yZP5uKLehQKPGgsIVT1A3XmIZW\nNzDAufVM5mjW8KbTNeBmMKRCJwKBgQDoNUMzDTLFl147jOaBJbq99Gd2pB7Aa8dY\n7SI3mXMMX0xCPU06Ym+wI485ybFllm+Bg018/+fJzli3Ko3nNuGcJplYzV8Z/eru\nMWGFCAXq3iWUiwXR9snmTAyO8uYXm7DnnhPxHNr8B3g3v55cTIqEjRn6YF5p7qBD\ntFQrV0ozqQKBgAvqqx/qew5AWWhkfyGA7TxtYQB9NBIbcaoqYwfC7vIoLtYgXWUp\n4zVF+PcLe6DYX8HySoWFhVBnj0anTD1QHDZg8nP1wJSjqmsnxSCDBedUoSkSDQHh\n10Cn3lF4xP26q4lJZEQgVa8MVN1YgnPUNJeVO11tuBf+3P5+FxBIpBPFAoGARxcH\nW7nOsW+GCfU5HJDQexc4FbppL7/PaAoxT5RLBJ6oWh8qZZV9XA+G6co15UQJHz1z\nm7E85SunPWxpxT+oEoY+rFEzrGFwazvy/ydVqHIaTz/AqGdFqJvfvGPgzZl8r2xV\n7ptG76HZzDd95AQK5EnOiji2rve/WPr8SciPjwECgYBf2SejOtRDWo6TOAQtEgvL\ngxU852DwuIW79U/+G2zrJ7qbbRzYCiHtsuaGOgzR5AfqN1+i4PWaJxdIKxymlv4w\nMs+swdsTZCn2/Rj4TndvEXr3OvfMtp0uN68rBNG+pNe1cwi+/+wx/E5ZC3QWxePt\nOwijAJ+obR377HMJOTTOTg==\n-----END PRIVATE KEY-----\n",
|
||||
"client_email": "strong-maker-107118@appspot.gserviceaccount.com",
|
||||
"client_id": "",
|
||||
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
||||
"token_uri": "https://oauth2.googleapis.com/token",
|
||||
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
||||
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/strong-maker-107118%40appspot.gserviceaccount.com"
|
||||
}
|
||||
81
implementaciones/sheets.js
Normal file
81
implementaciones/sheets.js
Normal file
@@ -0,0 +1,81 @@
|
||||
const { getTime, getDate, getFormat, getCompareDate, getFormatMs } = require('util-tiempo')
|
||||
const { GoogleSpreadsheet } = require('google-spreadsheet');
|
||||
const fs = require('fs');
|
||||
const RESPONSES_SHEET_ID = '1tVRX1ojXJadsjRUJ-pNv8DZgziaIMcAdsMtPmWQRBcM'; //Generar en google.cloud
|
||||
const doc = new GoogleSpreadsheet(RESPONSES_SHEET_ID);
|
||||
const CREDENTIALS = JSON.parse(fs.readFileSync('./implementaciones/credenciales.json'));
|
||||
|
||||
async function ingresarDatos(numero, mensaje){
|
||||
let Fecha = getDate();
|
||||
let Hora = getTime(Date.now(), {local: 'es-MX', timeZone: 'America/Mexico_City', hour12:false});
|
||||
elNum = numero.replace('@c.us', '')
|
||||
if(elNum.substring(0,3) == '521') { elNum = elNum.replace('521', '52') }
|
||||
let rows = [{
|
||||
Numero: elNum.trim(),
|
||||
Mensaje: mensaje,
|
||||
Fecha: Fecha,
|
||||
Hora: Hora
|
||||
}];
|
||||
await doc.useServiceAccountAuth({
|
||||
client_email: CREDENTIALS.client_email,
|
||||
private_key: CREDENTIALS.private_key
|
||||
});
|
||||
await doc.loadInfo();
|
||||
let sheet = doc.sheetsByTitle['Mensajes'];
|
||||
// console.log("SHEET=", sheet)
|
||||
for (let index = 0; index < rows.length; index++) {
|
||||
const row = rows[index];
|
||||
await sheet.addRow(row);
|
||||
console.log("Datos guardados (sheets.js)")
|
||||
}
|
||||
// console.log('Fecha:',Fecha,);
|
||||
// console.log('Hora:',Hora);
|
||||
// console.log('Nombre:',nombre);
|
||||
// console.log('Apellidos:',apellido);
|
||||
// console.log('Direccion:',direccion);
|
||||
// console.log('Planta:',planta);
|
||||
// console.log('Codigo Postal:',CP);
|
||||
// console.log('Descripcion:',descripcion);
|
||||
// console.log('Telefono:',telsim);
|
||||
// console.log('Horario deseado:',horario);
|
||||
// console.log('ID_Solicitud: ',ID_Solicitud);
|
||||
// console.log('Estado: ',Estado)
|
||||
// console.log('-----------------------------------');
|
||||
}
|
||||
|
||||
async function leerDatos(telsim){
|
||||
await doc.useServiceAccountAuth({
|
||||
client_email: CREDENTIALS.client_email,
|
||||
private_key: CREDENTIALS.private_key
|
||||
});
|
||||
await doc.loadInfo();
|
||||
let sheet = doc.sheetsByIndex[0];
|
||||
let nya;
|
||||
let cont = 0
|
||||
let found = false
|
||||
nya = [];
|
||||
let rows = await sheet.getRows();
|
||||
console.log(rows.length)
|
||||
// for (let index = 0; index < rows.length; index++) {
|
||||
// const row = rows[index];
|
||||
// if (row.Telefono == telsim) {
|
||||
// nya['Nombre'] = row.Nombre+' '+row.Apellido
|
||||
// nya['Direccion'] = row.Direccion+' '+row.Planta+', '+row.CP
|
||||
// nya['Estado'] = row.Estado
|
||||
// }
|
||||
// }
|
||||
while (!found && cont < rows.length){ //Usamos while para que no recorra TODOS los registros y se pare encuanto lo encuentre.
|
||||
const row = rows[cont];
|
||||
console.log(row.Nombre, found, cont)
|
||||
if (row.Telefono == telsim) {
|
||||
nya['Nombre'] = row.Nombre+' '+row.Apellido
|
||||
nya['Direccion'] = row.Direccion+', '+row.Planta+', CP:'+row.CP
|
||||
nya['Estado'] = row.Estado
|
||||
found = true
|
||||
}
|
||||
cont++
|
||||
}
|
||||
return nya
|
||||
};
|
||||
|
||||
module.exports = {ingresarDatos,leerDatos};
|
||||
101
package-lock.json
generated
101
package-lock.json
generated
@@ -16,6 +16,7 @@
|
||||
"exceljs": "^4.3.0",
|
||||
"express": "^4.18.1",
|
||||
"file-type": "^17.1.6",
|
||||
"google-spreadsheet": "^3.3.0",
|
||||
"googleapis": "^109.0.1",
|
||||
"mime-db": "^1.52.0",
|
||||
"moment": "^2.29.4",
|
||||
@@ -25,6 +26,7 @@
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
"socket.io": "^4.5.1",
|
||||
"stormdb": "^0.6.0",
|
||||
"util-tiempo": "^1.0.41",
|
||||
"whatsapp-web.js": "github:cheveguerra/whatsapp-web.js#WaWJS2",
|
||||
"xlsx": "^0.18.5"
|
||||
},
|
||||
@@ -2351,6 +2353,100 @@
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/google-spreadsheet": {
|
||||
"version": "3.3.0",
|
||||
"resolved": "https://registry.npmjs.org/google-spreadsheet/-/google-spreadsheet-3.3.0.tgz",
|
||||
"integrity": "sha512-ahmRNh14s1i3phfvbF2mxen1lohWJpUaFWgsU6P6bXu7QrmxMaim1Ys/7BU4W5yucWCzphoIrHMbrbeIR5K9mw==",
|
||||
"dependencies": {
|
||||
"axios": "^0.21.4",
|
||||
"google-auth-library": "^6.1.3",
|
||||
"lodash": "^4.17.21"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/google-spreadsheet/node_modules/axios": {
|
||||
"version": "0.21.4",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz",
|
||||
"integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==",
|
||||
"dependencies": {
|
||||
"follow-redirects": "^1.14.0"
|
||||
}
|
||||
},
|
||||
"node_modules/google-spreadsheet/node_modules/gaxios": {
|
||||
"version": "4.3.3",
|
||||
"resolved": "https://registry.npmjs.org/gaxios/-/gaxios-4.3.3.tgz",
|
||||
"integrity": "sha512-gSaYYIO1Y3wUtdfHmjDUZ8LWaxJQpiavzbF5Kq53akSzvmVg0RfyOcFDbO1KJ/KCGRFz2qG+lS81F0nkr7cRJA==",
|
||||
"dependencies": {
|
||||
"abort-controller": "^3.0.0",
|
||||
"extend": "^3.0.2",
|
||||
"https-proxy-agent": "^5.0.0",
|
||||
"is-stream": "^2.0.0",
|
||||
"node-fetch": "^2.6.7"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/google-spreadsheet/node_modules/gcp-metadata": {
|
||||
"version": "4.3.1",
|
||||
"resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-4.3.1.tgz",
|
||||
"integrity": "sha512-x850LS5N7V1F3UcV7PoupzGsyD6iVwTVvsh3tbXfkctZnBnjW5yu5z1/3k3SehF7TyoTIe78rJs02GMMy+LF+A==",
|
||||
"dependencies": {
|
||||
"gaxios": "^4.0.0",
|
||||
"json-bigint": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/google-spreadsheet/node_modules/google-auth-library": {
|
||||
"version": "6.1.6",
|
||||
"resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-6.1.6.tgz",
|
||||
"integrity": "sha512-Q+ZjUEvLQj/lrVHF/IQwRo6p3s8Nc44Zk/DALsN+ac3T4HY/g/3rrufkgtl+nZ1TW7DNAw5cTChdVp4apUXVgQ==",
|
||||
"dependencies": {
|
||||
"arrify": "^2.0.0",
|
||||
"base64-js": "^1.3.0",
|
||||
"ecdsa-sig-formatter": "^1.0.11",
|
||||
"fast-text-encoding": "^1.0.0",
|
||||
"gaxios": "^4.0.0",
|
||||
"gcp-metadata": "^4.2.0",
|
||||
"gtoken": "^5.0.4",
|
||||
"jws": "^4.0.0",
|
||||
"lru-cache": "^6.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/google-spreadsheet/node_modules/google-p12-pem": {
|
||||
"version": "3.1.4",
|
||||
"resolved": "https://registry.npmjs.org/google-p12-pem/-/google-p12-pem-3.1.4.tgz",
|
||||
"integrity": "sha512-HHuHmkLgwjdmVRngf5+gSmpkyaRI6QmOg77J8tkNBHhNEI62sGHyw4/+UkgyZEI7h84NbWprXDJ+sa3xOYFvTg==",
|
||||
"dependencies": {
|
||||
"node-forge": "^1.3.1"
|
||||
},
|
||||
"bin": {
|
||||
"gp12-pem": "build/src/bin/gp12-pem.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/google-spreadsheet/node_modules/gtoken": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/gtoken/-/gtoken-5.3.2.tgz",
|
||||
"integrity": "sha512-gkvEKREW7dXWF8NV8pVrKfW7WqReAmjjkMBh6lNCCGOM4ucS0r0YyXXl0r/9Yj8wcW/32ISkfc8h5mPTDbtifQ==",
|
||||
"dependencies": {
|
||||
"gaxios": "^4.0.0",
|
||||
"google-p12-pem": "^3.1.3",
|
||||
"jws": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/googleapis": {
|
||||
"version": "109.0.1",
|
||||
"resolved": "https://registry.npmjs.org/googleapis/-/googleapis-109.0.1.tgz",
|
||||
@@ -5069,6 +5165,11 @@
|
||||
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
|
||||
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="
|
||||
},
|
||||
"node_modules/util-tiempo": {
|
||||
"version": "1.0.41",
|
||||
"resolved": "https://registry.npmjs.org/util-tiempo/-/util-tiempo-1.0.41.tgz",
|
||||
"integrity": "sha512-HEesdZQpLY3S51xZ6hGbDvH8dVge+k+RnKJrb1mcME5UYXFeOaB7KQHA+sBiLsjls2Z0arseuxO2CZe9ZMCdug=="
|
||||
},
|
||||
"node_modules/utils-merge": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
"exceljs": "^4.3.0",
|
||||
"express": "^4.18.1",
|
||||
"file-type": "^17.1.6",
|
||||
"google-spreadsheet": "^3.3.0",
|
||||
"googleapis": "^109.0.1",
|
||||
"mime-db": "^1.52.0",
|
||||
"moment": "^2.29.4",
|
||||
@@ -27,6 +28,7 @@
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
"socket.io": "^4.5.1",
|
||||
"stormdb": "^0.6.0",
|
||||
"util-tiempo": "^1.0.41",
|
||||
"whatsapp-web.js": "github:cheveguerra/whatsapp-web.js#WaWJS2",
|
||||
"xlsx": "^0.18.5"
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user