const fs = require('fs') function alertas(ctx){ console.log("LISTO - ALERTAS") console.log(ctx) } /** * Regresa un número random entre los parametros min y max dados. * @param {*} min * @param {*} max * @returns */ function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min) + min); // The maximum is exclusive and the minimum is inclusive } /** * Revisa que exista el archivo "chats/numero.json" * @param {*} theFile * @returns */ function chkFile(theFile){ //MOD by CHV - Agregamos para revisar que exista el archivo "chats/numero.json" const fs = require('fs'); if (fs.existsSync(theFile)) { // console.log("Si existe el archivo "+ theFile); var h = true; } else{ // console.log("No existe el archivo "+ theFile); var h = false; } return h; } /** * Reemplaza texto en la respuesta con variables predefinidas. */ function remplazos(elTexto, extraInfo){ if(elTexto == null){elTexto = '';} // console.log("EXTRAINFO_THEMSG", extraInfo.theMsg) // console.log(extraInfo.theMsg.messages) const { from, body, name } = extraInfo.theMsg laLista = elTexto.toString().split(' '); // console.log(laLista); // console.log('============= remplazos ============'); for (var i = 0; i < laLista.length; i++) { // console.log('Revisamos: '+laLista[i]); if (laLista[i].search('%dia_semana%')>-1){//Remplaza con el dia de hoy. var dia = new Date().getDay(); if(dia==0){diaSemana='domingo';} else if(dia==1){diaSemana='lunes';} else if(dia==2){diaSemana='martes';} else if(dia==3){diaSemana='miercoles';} else if(dia==4){diaSemana='jueves';} else if(dia==5){diaSemana='viernes';} else {diaSemana='sábado';} elTexto = elTexto.replace('%dia_semana%', diaSemana); } if (laLista[i].search('%saludo%')>-1){//Remplaza con "Buenos dias, tardes o noches" dependiendo de la hora. var hora = new Date().getHours() if(hora>0 && hora < 12){saludo='Buenos días';} else if(hora>11 && hora < 19){saludo='Buenas tardes';} else {saludo='Buenas noches';} elTexto = elTexto.toString().replace('%saludo%', saludo); } if (laLista[i].search('%hora24%')>-1){//Remplaza con la hora a 24 hrs. var hora = new Date().getHours(); if (hora.toString().length < 2){hora = "0" + hora;} elTexto = elTexto.toString().replace('%hora24%', hora); } if (laLista[i].search('%hora12%')>-1){//Remplaza con la hora a 12 hrs. var hora = new Date().getHours(); var ampm = hora >= 12 ? 'pm' : 'am'; hora = hora % 12; hora = hora ? hora : 12; // the hour '0' should be '12' if (hora.toString().length < 2){hora = "0" + hora;} elTexto = elTexto.toString().replace('%hora12%', hora); } if (laLista[i].search('%minutos%')>-1){//Remplaza con los minutos de la hora actual. var mins = new Date().getMinutes(); if (mins.toString().length < 2){mins = "0" + mins;} elTexto = elTexto.toString().replace('%minutos%', mins); } if (laLista[i].search('%ampm%')>-1){//Remplaza con am o pm. var hours = new Date().getHours(); var ampm = hours >= 12 ? 'pm' : 'am'; elTexto = elTexto.toString().replace('%ampm%', ampm); } if (laLista[i].search('%rnd_')>-1){//Remplaza con opción al azar dentro de las especificadas. var inicio = laLista[i].search('%rnd_'); var final = laLista[i].indexOf("%", inicio+1); // console.log(inicio, final); var subStr = laLista[i].substring(inicio, final+1); // console.log("El substring="+subStr); var partes = subStr.toString().split('_'); if(partes.length > 1){ var opciones = partes[1].toString().substring(0,partes[1].toString().length-1).split(","); var elRand = Math.floor(Math.random() * (opciones.length)); if(elRand == opciones.length){elRand = elRand - 1;} // console.log(opciones.length, elRand, opciones[elRand]); elTexto = elTexto.toString().replace(subStr, opciones[elRand]); } else{ elTexto = elTexto.toString().replace(subStr, ""); } } if(laLista[i].search('%msjant_')>-1){//Remplaza con el mensaje anterior especificado. var histlMsjs = {}; console.log("entramos a msjant", from) var hayHistorial = (chkFile(`${__dirname}/chats/`+from+".json")); if(chkFile(`${__dirname}/../chats/`+from+".json")){ let rawdata = fs.readFileSync(`./chats/${from}.json`); let elHistorial0 = JSON.parse(rawdata); elHistorial = elHistorial0["messages"]; elHistorial = elHistorial.filter(x => x.message != "") //Quitamos mensajes en blanco. 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 + "|"); var partes = subStr.toString().split('_'); if(partes.length > 1){ // console.log("Partes[1] = |" + partes[1] + "|"); let posicion0 = partes[1].substring(0, partes[1].length-1) // 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"].trim()); } // histlMsjs = elHistorial["messages"]; // totalMsjs = histlMsjs.length-1; // ultimoMensaje = histlMsjs[histlMsjs.length-1]; // let mensajeAnterior = elHistorial["messages"][totalMsjs-1]; // console.log("Mensajes:"+totalMsjs+", Ultimo:"+JSON.stringify(ultimoMensaje)); // console.log("Anterior:"+JSON.stringify(mensajeAnterior)); } // return histlMsjs; } if (laLista[i].search('%body%')>-1){//Remplaza con el body del ctx. elTexto = elTexto.toString().replace('%body%', body); } if (laLista[i].search('%from%')>-1){//Remplaza con el from del ctx. elTexto = elTexto.toString().replace('%from%', from); } if (laLista[i].search('%solonumero%')>-1){//Remplaza con el from del ctx. elTexto = elTexto.toString().replace('%solonumero%', from.replace('@c.us', '')); } if (laLista[i].search('%nombre%')>-1){//Remplaza con el nombre del remitente. if(typeof extraInfo !== undefined){ if(name !== undefined){ elTexto = elTexto.toString().replace('%nombre%', name); } } } if (laLista[i].search('%primer_nombre%')>-1){//Remplaza con el nombre del remitente. if(typeof extraInfo !== undefined){ // console.log("EXRAINFO:", extraInfo.theMsg) if(name !== undefined){ elTexto = elTexto.toString().replace('%primer_nombre%', name.split(' ')[0]); } } } } // console.log("EL TEXTO="+elTexto); return elTexto.trim() } /** * Regresa el historial de mensajes del número especificado del directorio "chats". */ function traeMensajes(from){ //MOD by CHV - Agregamos para traer el historial de mensajes var histlMsjs = {}; var hayHistorial = (chkFile(`${__dirname}/chats/`+from+".json")); console.log(hayHistorial) // var hayHistorialNoBlanks = hayHistorial.find(k => k.messages.message != "") // console.log(hayHistorialNoBlanks) // var {keywords} = stepsInitial.find(k => k.key.includes(key)) if(hayHistorial){ let rawdata = fs.readFileSync(`./chats/${from}.json`); let elHistorial = JSON.parse(rawdata); histlMsjs = elHistorial["messages"]; // totalMsjs = histlMsjs.length-1; ultimoMensaje = histlMsjs[histlMsjs.length-1]; // let mensajeAnterior = elHistorial["messages"][totalMsjs-1]; // console.log("Mensajes:"+totalMsjs+", Ultimo:"+JSON.stringify(ultimoMensaje)); // console.log("Anterior:"+JSON.stringify(mensajeAnterior)); } console.log(histlMsjs) // var histlMsjsNoBlanks = histlMsjs.find(k => k.message != "") var histlMsjsNoBlanks = histlMsjs.filter(x => x.message != "") console.log(histlMsjsNoBlanks) return histlMsjs; } /** * Regresa las variables from, body, name y hasMedia del objeto del mensaje. * @param {*} msg * @returns from, body, name, hasMedia */ function traeVariablesFromMsg(msg){ if(provider == 'baileys'){return traeVariablesFromMsgBaileys(msg)} else{return traeVariablesFromMsgWWebJS(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?.templateButtonReplyMessage?.selectedDisplayText || msg.messages[0].message?.buttonsResponseMessage?.selectedDisplayText || msg.messages[0].message?.listResponseMessage?.title let from = remoteJid let body = theBody let name = pushName let hasMedia = false let timestamp = msg.messages[0].messageTimestamp // console.log("fromBody=", from, body, name) return {"from":from, "body":body, "name":name, "hasMedia":hasMedia, "timestamp":timestamp} } function traeVariablesFromMsgWWebJS(msg){ const { from, body, hasMedia, timestamp } = msg; let name = msg?._data?.notifyName // console.log("fromBody=", msg?._data) return {"from":from, "body":body, "name":name, "hasMedia":hasMedia, "timestamp":timestamp} } /** * Regresa las variables from, body, name, hasMedia, step y number del objeto del cliente. * @param {*} client * @returns from, body, name, hasMedia, step y number */ function traeVariablesFromClient(client){ // console.log(client) 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} } /** * Regresa el número limpio, sin @x.xxx * @param {*} from * @returns */ function soloNumero(from){ let soloNum if(provider == 'baileys'){soloNum = from.replace('@s.whatsapp.net', '')} else if(provider == 'wwebjs'){soloNum = from.replace('@c.us', '')} return soloNum } /** * Agrega las variables msg, body, from, hasMedia, name y numero al objeto del cliente. * @param {*} client * @param {*} msg * @param {*} vars * @returns */ function agregaVars(client, msg, vars){ const { from, body, name, hasMedia } = vars client.theMsg = msg; client.theMsg['body'] = body client.theMsg['from'] = from client.theMsg['hasMedia'] = hasMedia client.theMsg['name'] = name client.theMsg['number'] = soloNumero(from) return client } async function variousFuncs(){ /** * Trae información desde un archivo de excel y le manda a cada número un mensaje. (Envío masivo) */ if(body=='traeXLS'){ const rows = await leeXLSDatos('x') console.log("RESULTADOS:") function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)) } async function retardo() { for (sp=1;sp setTimeout(resolve, ms)); } async function retardo() { for (sp=0;sp