Files
freeplanet_serverside/src/server/telegram/telegrambot.js

1839 lines
60 KiB
JavaScript
Raw Normal View History

const tools = require('../tools/general');
const appTelegram = [tools.AYNI];
const appTelegramFinti = ['2'];
const appTelegramDest = [tools.AYNI];
const printf = require('util').format;
const { User } = require('../models/user');
2020-01-21 01:37:15 +01:00
const { CalZoom } = require('../models/calzoom');
const { Nave } = require('../models/nave');
const shared_consts = require('../tools/shared_nodejs');
2020-01-03 22:02:18 +01:00
const emoji = require('node-emoji');
const i18n = require("i18n");
2020-01-03 22:02:18 +01:00
const Benvenuto = emoji.get('heartbeat') + emoji.get('heartbeat') + emoji.get('heartbeat') + ' Benvenuto!';
const emo = {
JOY: emoji.get('joy'),
JOY2: emoji.get('rolling_on_the_floor_laughing'),
DANCER: emoji.get('dancer'),
2020-01-21 01:37:15 +01:00
STARS: emoji.get('stars'),
FIRE: emoji.get('fire'),
SUN: emoji.get('sunrise'),
TV: emoji.get('tv'),
NEWSPAPER: emoji.get('newspaper'),
KISS: emoji.get('kiss'),
PENCIL: emoji.get('pencil2'),
DREAM: emoji.get('beach_with_umbrella'),
EYES: emoji.get('eyes'),
DIZZY: emoji.get('dizzy'),
ONE_HUNDRED: emoji.get('100'),
SMILE_STAR: emoji.get('star-struck'),
LEFT_FACING_FIST: emoji.get('left-facing_fist'),
CHECK_VERDE: emoji.get('white_check_mark'),
CHECK_GRIGIA: emoji.get('ballot_box_with_check'),
CROSS_ROSSA: emoji.get('x'),
ENVELOPE: emoji.get('envelope'),
EXCLAMATION_MARK: emoji.get('exclamation'),
QUESTION_MARK: emoji.get('question'),
ARROW_RIGHT: emoji.get('arrow_right'),
INVITATI: emoji.get('man_and_woman_holding_hands'),
HEART: emoji.get('heart'),
BLUE_HEART: emoji.get('blue_heart'),
GREEN_HEART: emoji.get('green_heart'),
YELLOW_HEART: emoji.get('yellow_heart'),
PURPLE_HEART: emoji.get('purple_heart'),
GIFT_HEART: emoji.get('gift_heart'),
GIFT: emoji.get('gift'),
ROBOT_FACE: emoji.get('robot_face'),
ADMIN: emoji.get('information_desk_person'),
MALE: emoji.get('man-tipping-hand'),
FEMALE: emoji.get('female-guard'),
INNOCENT: emoji.get('innocent'),
CREDIT_CARD: emoji.get('credit_card'),
PERSON: emoji.get('man-tipping-hand'),
};
MsgBot = {
MIANAVE: ['Nave'],
CIAO: ['ciao', 'ciaoo', 'hola', 'holaa', 'hey', 'salve', 'buongiorno', 'buondi', 'ciao ❤️'],
CI_SEI: ['ci sei', 'c\'è qualcuno', 'c\'è nessuno'],
CHI_SONO_IO: ['chi sono io', 'chi sono'],
COME_STAI: ['tutto bene', 'come stai', 'come stai', 'come va', 'come butta', 'come va oggi'],
COME_TI_CHIAMI: ['chi sei', 'come ti chiami', 'qual\'è il tuo nome', 'qual\'e\' il tuo nome', 'che lavoro fai', 'di cosa ti occupi'],
COSA_FAI: ['cosa fai', 'cosa combini', 'che fai'],
QUANTI_ANNI_HAI: ['quanti anni hai', 'che età hai'],
SEI_LIBERO_STASERA: ['sei libera stasera', 'sei libero stasera', 'usciamo insieme', 'fare l\'amore con me', 'fare sesso', 'vuoi scopare', 'vuoi trombare'],
MI_TROVI_UN_MOROSO: ['trovi un moroso', 'una morosa', 'fidanzato', 'fidanzata', 'trovi un marito', 'trovi una moglie'],
CHAT_EMPOWER: ['chat empower'],
MASCHIO_FEMMINA: ['sei uomo o donna', 'sei maschio o femmina', 'sei ragazzo o ragazza', 'che sesso hai'],
DAMMI_UN_BACIO: ['dammi un bacio', 'baciami'],
HAHA: ['hahaha', 'ahah', '😂'],
MI_AMI: ['mi ami'],
TI_AMO: ['ti amo', 'ti adoro', 'ti lovvo'],
GRAZIE: ['grazie ainy', 'grazie', 'grazie mille', 'graziee', 'grazie 😘', 'grazie😘'],
PRINCIPE_AZZURRO: ['principe azzurro'],
SPOSAMI: ['sposami', 'vuoi sposar', 'sei sposat', 'ci sposiamo', 'ti sposo', 'sei sposat', 'mi sposi'],
CHE_TEMPO_FA: ['che tempo'],
NON_TROO_INVITATI: ['non trovo invitati', 'non riesco a trovare invitati'],
PAROLACCE: ['stronz', 'fanculo'],
COME_SI_CHIAMA: ['come si chiama'],
PROSSIMO_ZOOM: ['prossimo zoom', 'fare lo zoom', 'gli zoom', 'conferenz', 'zoom'],
LAVAGNA: ['lavagna', 'Lavagna', 'LAVAGNA'],
SEI_LIBERO: ['sei liber', 'sei sposat', 'sei fidanzat', 'sei single'],
AIUTO: ['ayni help', 'help', 'aiuto', 'ho bisogno di', 'ho problemi', 'non riesco', 'mi puoi aiutare', 'mi aiuti', 'aiutami', 'posso chiederti', 'puoi aiutarmi'],
UOMO: ['uomo', 'maschio'],
SORPRESA: ['noo', 'davvero', 'sii', 'facciamo festa', 'è qui la festa', 'festa'],
UGUALE: ['👍🏻', '✨', '❤🏻', '⭐', '❤', '❤❤', '🤩'],
SI: ['si', 'yes'],
NO: ['no', 'noo'],
DONNA: ['donna', 'femmina'],
FARE_DOMANDA: ['fare una domanda', 'posso farti una domanda'],
DIVENTERO_RICCA: ['diventerò ricc'],
MA_ALLORA: ['ma allora'],
CHI_E_VISTAR: ['chi è vistar'],
CHI_E_PAOLO: ['chi è paolo'],
};
MsgRisp = {
CHAT_EMPOWER: 'Entra nella Chat EMPOWER !!!\n' + 'https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g ' + emo.PURPLE_HEART + emo.GIFT_HEART + emo.BLUE_HEART
};
function getemojibynumber(number) {
if (number === 0) {
return emoji.get('zero')
} else if (number === 1) {
return emoji.get('one')
} else if (number === 2) {
return emoji.get('two')
} else if (number === 3) {
return emoji.get('three')
} else if (number === 4) {
return emoji.get('four')
} else if (number === 5) {
return emoji.get('five')
} else if (number === 6) {
return emoji.get('six')
} else if (number === 7) {
return emoji.get('seven')
} else if (number === 8) {
return emoji.get('height')
} else if (number === 9) {
return emoji.get('nine')
} else {
return number;
}
}
strNave = "Nave";
const Menu = {
ACCEDI: emo.PERSON + ' Accedi',
2020-03-25 09:25:31 +01:00
LAVAGNA: emoji.get('om_symbol') + ' Lavagna',
2020-01-03 22:02:18 +01:00
LINK_CONDIVIDERE: emoji.get('link') + ' Link da condividere',
2020-01-21 01:37:15 +01:00
ZOOM: emoji.get('information_source') + ' Zoom (Conferenze)',
2020-01-03 22:02:18 +01:00
INFO: emoji.get('information_source') + ' Informazioni',
ASSISTENZA: emoji.get('open_hands') + ' Le Chat di AYNI',
2020-01-03 22:02:18 +01:00
ADMIN: emoji.get('information_desk_person') + ' Admin',
ALTRO: emoji.get('newspaper') + ' Altro',
MSGATUTTI: emoji.get('incoming_envelope') + ' Invia a TUTTI',
MSG_TO_NAVE: emoji.get('incoming_envelope') + 'Msg_to_Navi',
MSG_NO_7_REQ: emoji.get('incoming_envelope') + 'No 7 Req.',
MSG_NO_9_REQ: emoji.get('incoming_envelope') + 'No 9 Req',
MSG_TO_USER: 'sendmsgto',
MSG_SI_INVITATI_NO_7REQ_INVITATI: emoji.get('incoming_envelope') + 'Inv e NO 7 Req',
MSGSTAFF: emoji.get('incoming_envelope') + ' Invia a STAFF',
INDIETRO: emoji.get('back') + ' Indietro',
SI: emoji.get('thumbsup') + ' SI',
NO: emoji.get('thumbsdown') + ' NO',
CHAT_PERSONALE: emoji.get('female-office-worker') + emoji.get('computer'),
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Esci dalla Conversazione',
2020-01-03 22:02:18 +01:00
EXIT_TELEGRAM: 'exittotelegram',
MIANAVE: emo.GIFT + ' ' + strNave,
};
const CONTA_SOLO = 'contasolo';
const RICEVI_EMAIL = 'riceviemail';
const SendMsgCmd = [CONTA_SOLO, RICEVI_EMAIL];
const MenuNoLogin = [[Menu.ACCEDI], [Menu.ASSISTENZA]];
2020-01-21 01:37:15 +01:00
const MenuStandard = [[Menu.LAVAGNA, Menu.LINK_CONDIVIDERE], [Menu.ZOOM, Menu.ASSISTENZA]];
2020-03-25 09:25:31 +01:00
const MenuPerAdmin = [[Menu.LAVAGNA, Menu.LINK_CONDIVIDERE], [Menu.ZOOM, Menu.ASSISTENZA], [Menu.ADMIN, Menu.ALTRO]];
const MenuYesNo = [[Menu.SI, Menu.NO]];
const MenuAdmin = [[Menu.MSGSTAFF, Menu.MSGATUTTI, Menu.INDIETRO], [Menu.MSG_NO_7_REQ, Menu.MSG_NO_9_REQ], [Menu.MSG_TO_NAVE, Menu.MSG_SI_INVITATI_NO_7REQ_INVITATI]];
const MenuSend = [[CONTA_SOLO, RICEVI_EMAIL], [Menu.INDIETRO]];
const MenuYes = [[Menu.MSGSTAFF, Menu.INDIETRO], ['', '']];
const MenuChat = [[Menu.ESCI_DA_CHAT, Menu.INDIETRO]];
const Sex = {
MALE: 1,
FEMALE: -1,
};
const Status = {
NONE: 0,
VERIFIED: 1,
WAITFOR_USERNAME_BO: 102,
WAITFOR_VERIFY_CODE: 103,
WAITFOR_RISPOSTA: 110,
};
const Destin = {
STAFF: 1,
TUTTI: 2,
NO_7_REQ: 3,
NO_9_REQ: 4,
SI_INVITATI_NO_7REQ_INVITATI: 5,
A_UTENTE: 6,
MSG_TO_NAVE: 7,
};
const StatusMSGALL = {
NONE: 0,
ASK: 1,
CONFIRM: 2,
};
const txt = {
2020-01-03 22:02:18 +01:00
MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Scegli una voce di menu:' + emoji.get('dizzy'),
MSG_ASK_USERNAME_BO: 'Scrivi nel messaggio lo username o la email con cui ti sei registrato sul sito di %s:',
MSG_ERRORE_USERNAME: 'Attenzione! Devi inserire solo lo username (40 caratteri massimo)',
MSG_ERRORE_USERNAME_NOT_FOUND: 'Per Completare la Verifica Telegram BOT, devi ora scrivere qui sotto nel messaggio l\'Username OPPURE la email con cui ti sei registrato sul sito di AYNI:',
MSG_ERRORE_USERNAME_ANNULLA: 'Inserimento Annullato. Riprovare',
MSG_OPERAZ_ANNULLATA: 'Operazione Annullata',
MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attenzione! Devi inserire solo il codice a 6 cifre',
MSG_VERIFY_CODE: '1. Ora ritorna sul sito di AYNI:\n%s\n2. Copia il codice di Autenticazione (di 6 cifre) che troverai scritto in alto\n3. Scrivilo (o incollalo) qui sotto come messaggio:',
MSG_ERR_VERIFY_CODE: 'Codice di Verifica Errato!' + emo.EXCLAMATION_MARK + '\nControlla sul sito %s e riscrivi il nuovo codice di 6 cifre.',
MSG_VERIFY_OK: emoji.get('grinning') + ' Benvenuto %s! Ti sei correttamente verificato con AYNI BOT. ' + '\nSono il tuo assistente virtuale.\n' +
'Continua la guida passo passo tornando sul sito di AYNI.\n\nQuesta chat ti servirà per vedere velocemente la tua Lavagna e per ricevere Importanti avvisi su come procedere il tuo cammino.\n\nUsa il menu qui sotto per controllare la tua situazione.' + emo.GREEN_HEART,
2020-01-03 22:02:18 +01:00
MSG_ERR_UNKNOWN_VERIFY_CODE: 'Errore durante il salvataggio sul Server. Riprovare piú tardi',
MSG_EXIT_TELEGRAM: 'L\'account è stato ora scollegato da questo Telegram BOT.',
MSG_APORTADOR_USER_REGISTERED: emo.FIRE + ' Si è appena Registrato "%s (n. %s)"\n(Invitato da %s)',
MSG_MSG_SENT: emoji.get('envelope') + ' Messaggi Inviati !',
MSG_MSG_TOSENT: emoji.get('envelope') + ' Messaggi da Inviare',
MSG_MSG_INCORSO: emoji.get('envelope') + ' messaggi in corso... Inviati attualmente',
};
const TelegramBot = require('node-telegram-bot-api');
2020-01-03 22:02:18 +01:00
module.exports = {
ADMIN_IDTELEGRAM_SERVER: '12429864',
ADMIN_USER_SERVER: 'paoloar77',
ADMIN_USER_NAME_SERVER: 'Paolo',
phase: {
REGISTRATION: 1
},
getCiao: function (idapp, username, lang) {
return tools.gettranslate('CIAO', lang) + ' ' + username + '!\n';
},
2020-01-03 22:02:18 +01:00
notifyToTelegram: async function (phase, mylocalsconf) {
let userdest = mylocalsconf.user.aportador_solidario;
let NameFrom = `${mylocalsconf.user.name} ${mylocalsconf.user.surname}`;
const ind_order = mylocalsconf.user.ind_order;
let aportador = '';
if (userdest) {
aportador = ` (${userdest})`;
NameFrom += aportador;
} else {
aportador = mylocalsconf.user.aportador_solidario_nome_completo;
}
2020-01-03 22:02:18 +01:00
let text = '';
if (phase === this.phase.REGISTRATION) {
if (userdest) {
NameFrom = await User.getNameSurnameByUsername(mylocalsconf.idapp, userdest) + aportador;
aportador = NameFrom;
}
text = printf(txt.MSG_APORTADOR_USER_REGISTERED, `${mylocalsconf.user.name} ${mylocalsconf.user.surname} (${mylocalsconf.user.username})`, ind_order, aportador);
2020-01-03 22:02:18 +01:00
}
let addtext = "";
if (!!mylocalsconf.user.aportador_solidario) {
addtext = '[Inviato a ' + NameFrom + ']:' + '\n';
await this.sendMsgTelegram(mylocalsconf.idapp, userdest, text);
}
2020-01-03 22:02:18 +01:00
await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, addtext + text);
2020-01-03 22:02:18 +01:00
},
sendMsgTelegramToTheManagers: async function (idapp, text) {
const usersmanagers = await User.getusersManagers(idapp);
// console.log('usersmanagers', usersmanagers);
tools.writeManagersLog(text);
2020-01-03 22:02:18 +01:00
if (usersmanagers) {
for (const rec of usersmanagers) {
await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, emo.ROBOT_FACE + '[BOT-STAFF]' + emo.ADMIN + ': ' + text, undefined, undefined, true);
await tools.snooze(300)
}
2020-01-03 22:02:18 +01:00
}
return true
2020-01-03 22:02:18 +01:00
},
getMsgByTipoMsg: function (mydata, lang, user) {
if (!!mydata.msgextra) {
return mydata.msgextra;
}
if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) {
return printf(tools.gettranslate('SEND_LINK_CHAT_DONATORI', lang), user.name, mydata.msgpar1);
2020-03-25 09:25:31 +01:00
} else if (mydata.tipomsg === tools.TipoMsg.SEND_MSG || mydata.tipomsg === tools.TipoMsg.SEND_MSG_SINGOLO) {
return mydata.msgpar1;
}
2020-03-25 09:25:31 +01:00
},
sendMsgTelegramToNave: async function (idapp, mydata) {
let nummsgsent = 0;
let strout = '';
try {
const arrnavi = await Nave.getusersByNave(idapp, mydata.navemediatore);
// console.log('usersmanagers', usersmanagers);
tools.writeManagersLog('sendMsgTelegramToNave');
if (arrnavi) {
for (const nave of arrnavi) {
const user = await User.findByIndOrder(idapp, nave.ind_order);
2020-03-25 09:25:31 +01:00
if (!!user) {
const lang = user.lang;
const idteleg = user.profile.teleg_id;
const mymsg = this.getMsgByTipoMsg(mydata, lang, user);
if (!!idteleg) {
strout += '\n' + user.name + ' ' + user.surname + ':';
if (mydata.inviareale) {
await this.sendMsgTelegramByIdTelegram(idapp, idteleg, mymsg, undefined, undefined, true);
await tools.snooze(300);
strout += ' -> MSG INVIATO';
} else {
strout += ' (Pronto da Inviare)';
}
nummsgsent++;
}
2020-03-21 10:28:26 +01:00
if ((nummsgsent === 1) && (mydata.inviareale)) {
try {
this.sendMsgTelegramToTheManagers(idapp, 'Inviato messaggio a tutti i Donatori della Nave ' + mydata.navemediatore.riga + '.' + mydata.navemediatore.col + '\n' + mymsg)
2020-03-25 09:25:31 +01:00
} catch (e) {
2020-03-21 10:28:26 +01:00
}
}
}
}
if (nummsgsent > 0) {
if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) {
const fields_to_update = {
sent_msg_howto_make_gift: true
};
await Nave.findOneAndUpdate({ _id: mydata.navemediatore.id }, { $set: fields_to_update }, { new: false });
}
}
}
return { nummsgsent, strout };
} catch (e) {
console.error(e);
2020-03-25 09:25:31 +01:00
return { nummsgsent, strout };
}
},
2020-03-21 10:28:26 +01:00
sendMsgTelegramToTheAdmin: async function (idapp, text, senzaintestazione) {
const usersmanagers = await User.getusersManagers(idapp);
2020-03-21 10:28:26 +01:00
let intestaz = emo.ROBOT_FACE + '[BOT-ADMIN]' + emo.ADMIN + ': ';
if (senzaintestazione)
intestaz = '';
if (usersmanagers) {
for (const rec of usersmanagers) {
if (User.isAdmin(rec.perm)) {
2020-03-21 10:28:26 +01:00
this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, intestaz + text, undefined, undefined, true);
await tools.snooze(300)
}
}
}
return true
},
sendMsgTelegramToALL: async function (idapp, text) {
const usersall = await User.getUsersTelegALL(idapp);
if (usersall) {
for (const rec of usersall) {
this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, text);
await tools.snooze(300)
}
}
},
sendMsgTelegram: async function (idapp, username, text, alsotomanagers) {
2020-01-03 22:02:18 +01:00
const teleg_id = await User.TelegIdByUsername(idapp, username);
const cl = getclTelegByidapp(idapp);
2020-03-25 09:25:31 +01:00
let ris = null;
2020-01-03 22:02:18 +01:00
if (cl && teleg_id) {
2020-03-25 09:25:31 +01:00
ris = await cl.sendMsg(teleg_id, text)
2020-01-03 22:02:18 +01:00
}
2020-03-25 09:25:31 +01:00
if (cl && teleg_id) {
if (alsotomanagers) {
await this.sendMsgTelegramToTheManagers(idapp, text)
}
}
2020-03-25 09:25:31 +01:00
return ris;
2020-01-03 22:02:18 +01:00
},
sendMsgTelegramByIdTelegram: async function (idapp, idtelegram, text, message_id, chat_id, ripr_menuPrec) {
if (!idtelegram)
return;
2020-01-03 22:02:18 +01:00
const cl = getclTelegByidapp(idapp);
if (cl && idtelegram) {
let myform = null;
return await cl.sendMsg(idtelegram, text, null, null, message_id, chat_id, ripr_menuPrec)
2020-01-03 22:02:18 +01:00
}
}
};
async function sendMsgTelegramToTheAdmin(idapp, text, msg) {
const usersmanagers = await User.getusersManagers(idapp);
const clorig = getclTelegByidapp(idapp);
const rec = clorig.getRecInMem(msg);
let username = '';
if (!!rec) {
username = rec.username_bo;
} else {
username = msg.chat.username;
}
text = emo.ROBOT_FACE + '[BOT-ADMIN]' + emo.ADMIN + ': Da ' + msg.chat.first_name + ' ' + msg.chat.last_name + ' [' + username + ']: \n' + text;
tools.writeEventsLog(text);
if (usersmanagers) {
for (const rec of usersmanagers) {
if (User.isAdmin(rec.perm)) {
const idtelegram = rec.profile.teleg_id;
const cl = getclTelegByidapp(idapp);
if (cl && idtelegram) {
await cl.sendMsg(idtelegram, text)
}
await tools.snooze(300)
}
}
}
return true
}
function getusernameByUser(idapp, msg) {
let username = '';
let rec = this.getRecInMem(msg);
if (!!rec)
username = rec.username_bo;
if (username === '') {
username = msg.chat.username;
}
return username;
}
async function local_sendMsgTelegramToTheManagers(idapp, text, msg, username_bo) {
const usersmanagers = await User.getusersManagers(idapp);
let username = msg.chat.username;
if (username_bo)
username = username_bo;
text = emo.ROBOT_FACE + '[BOT-STAFF]' + emo.ADMIN + ': Da ' + msg.chat.first_name + ' ' + msg.chat.last_name + ' (' + username + '): \n' + text;
tools.writeEventsLog(text);
if (usersmanagers) {
for (const rec of usersmanagers) {
const idtelegram = rec.profile.teleg_id;
const cl = getclTelegByidapp(idapp);
if (cl && idtelegram) {
await cl.sendMsg(idtelegram, text, undefined, undefined, undefined, undefined, true)
}
await tools.snooze(300)
}
}
return true
}
function getstr(lang, text) {
return text;
}
class Telegram {
constructor(idapp, bot) {
this.idapp = idapp;
this.bot = bot;
this.token = bot.token;
this.arrUsers = [];
}
async createIfNotExist(msg) {
if (!await this.alreadyExist(msg)) {
if (await this.insertIntoDB(msg)) {
let rec = this.getRecInMem(msg);
if (rec.user)
rec.status = Status.VERIFIED
}
return true
} else {
return false
}
}
async start(msg) {
// Check if Present to the DB
if (!await this.createIfNotExist(msg)) {
let rec = this.getRecInMem(msg);
if (!rec)
rec = this.addUser(msg);
if (rec.user)
rec.status = Status.VERIFIED
}
}
async IsTesto(msg) {
let risp = '';
const id = msg.chat.id;
let testo = msg.text.toLowerCase().trim();
testo = testo.replace('!', '');
testo = testo.replace('?', '');
testo = testo.replace('é', 'è');
let contastiera = false;
let noanswer = false;
const rec = this.getRecInMem(msg);
let myname = '';
if (rec.user) {
myname = rec.user.name + ' ' + rec.user.surname + ' (n.' + rec.user.ind_order + ')';
}
if (rec.statusmsg === Status.WAITFOR_RISPOSTA) {
if (rec.msgcodeprec === MsgBot.COME_STAI) {
risp = 'L\'importante è trovare Serenità dentro di noi' + emo.GIFT_HEART + '\nNutrirsi di Sole e Viaggiare il più possibile ! ' + emo.DREAM;
} else if (rec.msgcodeprec === MsgBot.QUANTI_ANNI_HAI) {
const eta = testo.match(/\d+/g);
if (!eta) {
risp = 'Mmmh, non me lo vuoi dire...';
} else {
if (eta < 20) {
risp = 'Woww! Sei molto giovane!';
} else if ((eta > 20) && (eta < 30)) {
risp = 'Sei giovane anche tu!';
} else if ((eta > 30) && (eta < 50)) {
risp = 'Sono i migliori anni questi !';
} else if ((eta > 50) && (eta < 60)) {
risp = 'Complimenti !';
} else if (eta > 60) {
risp = 'Però! Ti mantieni in forma!' + emo.SMILE_STAR;
}
risp = 'Ah ' + eta + ' anni !\n' + risp;
}
} else if (rec.msgcodeprec === MsgBot.CHAT_EMPOWER) {
if (!MsgBot.SI.includes(testo)) {
risp = MsgRisp.CHAT_EMPOWER
} else {
risp = 'Bene ! Allora divertiti conoscendo persone nuove ! ';
}
} else if (rec.msgcodeprec === MsgBot.MASCHIO_FEMMINA) {
if (MsgBot.UOMO.includes(testo)) {
rec.sex = Sex.MALE;
risp = 'Ok, sarò il tuo uomo ' + emo.MALE;
} else {
rec.sex = Sex.FEMALE;
risp = 'Ok, sarò la tua donna ' + emo.ADMIN;
}
}
rec.statusmsg = 0;
}
rec.msgcodeprec = '';
if (risp === '') {
if (MsgBot.CIAO.includes(testo.replace('!', ''))) {
risp = 'Ciao ';
if (rec)
if (rec.user)
risp += rec.user.name;
risp += '!';
} else if (MsgBot.COME_STAI.includes(testo.replace('?', ''))) {
risp = 'Io Benone Grazie! ' + emoji.get('heartbeat') + ' E tu?';
rec.statusmsg = Status.WAITFOR_RISPOSTA;
rec.msgcodeprec = MsgBot.COME_STAI
} else if (MsgBot.CHI_SONO_IO.includes(testo.replace('?', ''))) {
risp = 'Su Telegram ti chiami "' + msg.chat.first_name + ' ' + msg.chat.last_name + '"\n';
if (!!rec.user) {
risp += '\nSul sito ti sei registrato come:\n\n[N. ' + rec.user.ind_order + ']: ' + rec.user.name + ' ' + rec.user.surname + '\nUsername: ' + rec.user.username + '\n' + 'Email: ' + rec.user.email;
} else {
risp = 'Ancora non ti sei Attivato su AYNI BOT';
}
} else if (MsgBot.CI_SEI.includes(testo.replace('?', ''))) {
risp = 'Io Si, ci sono !';
} else if (MsgBot.QUANTI_ANNI_HAI.includes(testo.replace('?', ''))) {
risp = 'Io sono abbastanza Giovane ! ' + emo.SMILE_STAR + '\nNon posso dirti che età ho. E tu?';
rec.statusmsg = Status.WAITFOR_RISPOSTA;
rec.msgcodeprec = MsgBot.QUANTI_ANNI_HAI
} else if (MsgBot.DAMMI_UN_BACIO.includes(testo)) {
risp = emo.KISS;
} else if (MsgBot.COSA_FAI.includes(testo)) {
risp = 'Ora sto chattando con te!\nSolitamente sono in attesa di ricevere messaggi ' + emo.ENVELOPE;
} else if (MsgBot.MASCHIO_FEMMINA.includes(testo.replace('?', ''))) {
risp = 'Cosa vorresti che fossi? Uomo o donna?';
rec.msgcodeprec = MsgBot.MASCHIO_FEMMINA;
rec.statusmsg = Status.WAITFOR_RISPOSTA;
} else if (MsgBot.COME_TI_CHIAMI.includes(testo.replace('?', ''))) {
risp = 'Io mi chiamo AYNI BOT e sono il tuo assistente Virtuale. ' + emo.EYES + '\nPuoi usare il menu che compare qui sotto per sapere tutto sulle mie funzionalità ' + emo.GREEN_HEART;
contastiera = true;
} else if (MsgBot.UGUALE.includes(testo)) {
risp = testo;
// } else if (MsgBot.CHI_E_VISTAR.includes(testo)) {
// risp = 'Vistar è un nomade che vive in Perù tra i selvaggi, filosofeggiando e cazzeggiando qua e la... Per questo è un Fico ed è adulato dalle ragazze di tutto il Globo ' + emo.JOY + emo.JOY + emo.JOY;
// } else if (MsgBot.CHI_E_PAOLO.includes(testo)) {
// risp = 'Paolo è il Programmatore Sborone di AYNI. Anche lui Fico quanto Vistar (ma chi è Vistar) ' + emo.JOY + ' che anzichè creare la Nave cazzeggia su AYNI BOT, trovando risposte alle domande più assurde.' + emo.JOY2 + emo.JOY2;
} else if (MsgBot.COME_SI_CHIAMA.includes(testo)) {
risp = 'Eh non te lo posso dire! ' + emo.JOY;
} else if (MsgBot.GRAZIE.includes(testo.replace('!', ''))) {
risp = 'Prego ! ' + emo.KISS + emo.KISS + emo.KISS;
} else if (MsgBot.MI_AMI.find((rec) => testo.indexOf(rec) > -1)) {
risp = ' Tantissimo! ' + emo.KISS + emo.GIFT_HEART + emo.GIFT_HEART + emo.GIFT_HEART;
} else if (MsgBot.TI_AMO.find((rec) => testo.indexOf(rec) > -1)) {
risp = ' Anche IO! ' + emo.KISS + emo.SMILE_STAR + emo.GIFT_HEART + emo.BLUE_HEART + emo.GREEN_HEART;
} else if (MsgBot.PRINCIPE_AZZURRO.find((rec) => testo.indexOf(rec) > -1)) {
risp = 'Chissà... Forse si!\nAnche se meglio averne un\'altro di scorta, nel caso il Principe non sia disponibile.';
} else if (MsgBot.AIUTO.find((rec) => testo.indexOf(rec) > -1)) {
risp = 'Clicca qui per entrare nella Chat AYNI - HELP di Supporto\n' + 'https://t.me/joinchat/C741mlVmB_RMcOUpNqWC8w' + '\n\nI miei colleghi umani ti aiuteranno a risolvere !';
} else if (MsgBot.SPOSAMI.find((rec) => testo.indexOf(rec) > -1)) {
risp = 'No Grazie! Sono per la Libertà a Vita! ' + emo.JOY + '\nMa se vuoi possiamo conoscerci meglio!' + emo.DANCER + emo.FIRE;
} else if (MsgBot.CHE_TEMPO_FA.find((rec) => testo.indexOf(rec) > -1)) {
risp = 'Il tempo oggi è Sereno da me! ' + emo.SUN;
} else if (MsgBot.NON_TROO_INVITATI.find((rec) => testo.indexOf(rec) > -1)) {
risp = MsgRisp.CHAT_EMPOWER;
} else if (MsgBot.SEI_LIBERO.find((rec) => testo.indexOf(rec) > -1)) {
risp = 'Io? Sono per la Libertà! ' + emo.JOY + '\nMa se vuoi possiamo conoscerci meglio!' + emo.DANCER + emo.FIRE;
} else if (MsgBot.FARE_DOMANDA.find((rec) => testo.indexOf(rec) > -1)) {
risp = 'Dipende ' + emo.SMILE_STAR + '\nProvaci!';
} else if (MsgBot.DIVENTERO_RICCA.find((rec) => testo.indexOf(rec) > -1)) {
risp = 'Mmmmh... Perchè non pensi di Vivere già nell\'Abbondanza ?\nCosa ti manca veramente?\nForse di realizzare che la ricchezza è un sentirlo, non un diventarlo.' + emo.GIFT_HEART;
} else if (MsgBot.MA_ALLORA.find((rec) => testo.indexOf(rec) > -1)) {
risp = 'Ma allora cosa?';
} else if (MsgBot.SEI_LIBERO_STASERA.find((rec) => testo.indexOf(rec) > -1)) {
risp = 'Si vabbeh, non è che puoi prendere subito tutta questa confidenza' + emo.EXCLAMATION_MARK + emo.SMILE_STAR + '\nIntanto inizia ad invitare altre persone a conoscermi, poi ne riparliamo ' + emo.GIFT_HEART;
} else if (MsgBot.MI_TROVI_UN_MOROSO.find((rec) => testo.indexOf(rec) > -1)) {
risp = emo.SMILE_STAR + emo.SMILE_STAR + emo.SMILE_STAR + emo.SMILE_STAR + '\nMagari! Così la smetteresti di scrivere a me (ad un BOT Virtuale) e tromberesti di più ' + emo.DANCER + emo.DANCER;
risp += '\n\n' + MsgRisp.CHAT_EMPOWER;
} else if (MsgBot.SORPRESA.find((rec) => testo.indexOf(rec) > -1) && testo.length < 15) {
risp = 'Siiiii ! Davvero! ' + emo.DREAM + '\nTi ricordo che nella CHAT EMPOWER si fa FESTA!\n\nChat AYNI - EMPOWER: Entra ⛩ nella nostra Community chat:\n https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g';
} else if (MsgBot.PAROLACCE.find((rec) => testo.indexOf(rec) > -1)) {
risp = 'Da te non me l\'aspettavo proprio !! ' + emo.INNOCENT + emo.CROSS_ROSSA;
} else if (MsgBot.HAHA.find((rec) => testo.indexOf(rec) > -1) && testo.length < 8) {
risp = emo.JOY + emo.JOY + emo.JOY;
2020-03-25 09:25:31 +01:00
} else if (testo.length >= 10) {
noanswer = true;
2020-03-25 09:25:31 +01:00
risp = '[Messaggio inviato allo Staff]\nD\'altronde io sono solo un Robot ' + emo.ROBOT_FACE + emo.JOY2 + '\n\n(Per AIUTO, contatta la Chat AYNI - HELP)';
// risp += '\nClicca qui per entrare nella Chat AYNI - HELP di Supporto\n' + 'https://t.me/joinchat/C741mlVmB_RMcOUpNqWC8w' + '\n\nI miei colleghi umani ti aiuteranno a risolvere !';
await local_sendMsgTelegramToTheManagers(this.idapp, testo, msg, rec.username_bo);
}
}
let keyboard = {};
if (contastiera) {
keyboard = {
"reply_markup": {
"resize_keyboard": true,
"keyboard": await this.getKeyboard(id)
}
}
}
if (rec.numdomande > 3 && rec.msgcodeprec === '') {
// if (rec.user) {
// const dashboard = await User.getDashboard(this.idapp, rec.user.aportador_solidario, rec.user.username, rec.user.aportador_solidario_name_surname);
//
// risp += '\n\nNel frattempo ti ricordo che ';
// if (dashboard.myself.numinvitati === 1)
// risp += 'hai solo ' + dashboard.myself.numinvitati + ' invitato!';
// else if (dashboard.myself.numinvitati === 0)
// risp += 'ancora non hai portato nessun Invitato! ' + emo.LEFT_FACING_FIST;
// else if (dashboard.myself.numinvitati > 2)
// risp += 'hai ' + dashboard.myself.numinvitati + ' invitati !' + emo.STARS;
//
// risp += '\n\nSei già entrato nella Chat di EMPOWER?';
// rec.msgcodeprec = MsgBot.CHAT_EMPOWER;
// rec.statusmsg = Status.WAITFOR_RISPOSTA;
// rec.numdomande = 0;
// }
}
if (risp !== '') {
rec.numdomande++;
await tools.snooze(600);
this._inviaMsg(id, '[AYNI BOT' + emo.ROBOT_FACE + ' scrive]:\n' + risp, keyboard);
let strlog = 'USER [' + myname + ']: ' + testo + '\n';
if (!noanswer) {
strlog += 'BOT: ' + risp + '\n';
}
tools.writelog(strlog);
}
return risp !== '';
}
async isMenuNotVerified(rec, msg) {
if (msg.text === Menu.ASSISTENZA) {
await this.menuAssistenza(msg)
} else if (msg.text === Menu.INFO) {
await this.menuInformazioni(msg)
} else if (msg.text === Menu.ZOOM || MsgBot.PROSSIMO_ZOOM.find((rec) => msg.text.indexOf(rec) > -1)) {
2020-01-21 01:37:15 +01:00
await this.menuZoom(msg)
} else if (await this.IsTesto(msg)) {
// OK
} else {
await this.msgScegliMenu(msg);
}
}
async isMenu(rec, msg) {
if (!msg)
return;
if (msg.text === undefined)
return;
const arrtext = msg.text.split(" ");
let cmd2 = "";
let cmd1 = arrtext[0];
if (arrtext.length > 1)
cmd2 = arrtext[1];
let oldusername = rec.msgall_username_specifico;
if ((msg.text === Menu.ESCI_DA_CHAT) || (msg.text === Menu.INDIETRO)) {
rec.msgall_username_specifico = '';
} else {
if (rec.msgall_username_specifico !== '') {
await this.SendMsgToUser(msg, rec, rec.msgall_username_specifico, msg.text);
return true;
}
}
if (msg.text === Menu.LAVAGNA || MsgBot.LAVAGNA.find((rec) => msg.text.indexOf(rec) > -1)) {
await this.menuLavagna(msg);
} else if (msg.text === Menu.MIANAVE || (cmd2 === strNave) || MsgBot.MIANAVE.find((rec) => msg.text.indexOf(rec) > -1)) {
await this.menuNave(msg)
} else if (msg.text === Menu.ACCEDI) {
await this.menuAccedi(msg)
2020-01-03 22:02:18 +01:00
} else if (msg.text === Menu.LINK_CONDIVIDERE) {
await this.menuLinkCondividere(msg)
2020-01-03 22:02:18 +01:00
} else if (msg.text === Menu.EXIT_TELEGRAM) {
await this.menuExitToTelegram(msg)
} else if (msg.text === Menu.ADMIN) {
await this.menuAdmin(msg)
} else if (msg.text === Menu.MSGATUTTI) {
await this.menumsgAll(msg)
} else if (msg.text === Menu.MSGSTAFF) {
await this.menumsgStaff(msg)
} else if (msg.text === Menu.MSG_NO_7_REQ) {
await this.menumsg_No_7_Req(msg)
} else if (msg.text === Menu.MSG_NO_9_REQ) {
await this.menumsg_No_9_Req(msg)
} else if (cmd1 === Menu.MSG_TO_NAVE) {
await this.menumsg_to_Nave(msg, cmd2)
} else if (msg.text === Menu.MSG_SI_INVITATI_NO_7REQ_INVITATI) {
await this.menumsg_Si_Invitati_No_7Req(msg)
} else if (cmd1.toLowerCase() === Menu.MSG_TO_USER) {
await this.menumsg_A_Utente(msg)
} else if (msg.text === Menu.INDIETRO) {
await this.msgScegliMenu(msg);
} else if (msg.text === Menu.ESCI_DA_CHAT) {
await this.sendMsg(msg.chat.id, 'Uscito dalla Chat con ' + oldusername);
rec.msgall_username_specifico = '';
2020-01-03 22:02:18 +01:00
} else {
await this.isMenuNotVerified(rec, msg);
}
}
getsymb(symb, valid, isnum, num, smileif) {
let str = symb + ': ';
if (valid)
str += emo.CHECK_VERDE;
else
str += emo.CROSS_ROSSA;
if (isnum) {
str += ' ' + getemojibynumber(num);
if (smileif)
str += emo.SMILE_STAR;
}
return str + ' ';
}
isdreamset(user) {
if (user) {
if (user.profile.my_dream)
if (user.profile.my_dream.length > 10)
return true
}
return false
}
ispayment(user) {
if (user) {
let ispaypal = false;
if (!!user.profile.paymenttypes) {
if (user.profile.paymenttypes.includes('paypal')) {
if (user.profile.email_paypal) {
ispaypal = true
}
}
if (!!user.profile)
if (!!user.profile.paymenttypes) {
return (user.profile.paymenttypes.length >= 1) && ispaypal;
}
}
}
return false
}
async menuAccedi(msg) {
let status = this.getstatusInMemory(msg);
if (status === Status.WAITFOR_USERNAME_BO) {
await this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND, MenuNoLogin);
}
}
async getLavagnaByUser(user, msg) {
let mystr = '';
const dashboard = await User.getDashboard(this.idapp, user.aportador_solidario, user.username, user.aportador_solidario_name_surname);
let numpersone = (dashboard.downline) ? dashboard.downline.length : 0;
let invitati_attivi = dashboard.myself.numinvitatiattivi;
mystr = "";
// if (dashboard.aportador) {
// mystr = emoji.get('seedling') + ` Chi ti ha invitato: ${dashboard.aportador.username} (${dashboard.aportador.name} ${dashboard.aportador.surname})\n`;
// } else {
// mystr = 'Chi ti ha invitato: Sei il Primo! ';
// }
// mystr += `____________________________________________\n`;
let tuttie9 = false;
2020-03-25 09:25:31 +01:00
let mystrnave = '';
if (user) {
mystr += tools.get__('BENVENUTO', msg) + ' ' + user.name + ' (' + user.username + ') ' + emo.DIZZY + '\n\n';
tuttie9 = dashboard.myself.qualified && (numpersone >= 2) && invitati_attivi >= 2;
2020-03-25 09:25:31 +01:00
mystrnave = await Nave.getNaveByUser(this.idapp, user.ind_order, user.lang, true);
if (mystrnave === '' && tuttie9) {
mystr += tools.gettranslate('NO_PROG', user.lang);
}
2020-03-25 09:25:31 +01:00
if (!!mystrnave) {
mystr += '✨✨✨' + tools.get__('TUE_NAVI', msg) + ':\n';
mystr += mystrnave;
} else {
2020-03-25 09:25:31 +01:00
if (!tuttie9) {
mystr += dashboard.myself.qualified ? emo.SMILE_STAR + tools.get__('HAI_I_7_REQUISITI', msg) + emo.SMILE_STAR : emo.EXCLAMATION_MARK + tools.get__('NON_HAI_I_7_REQUISITI', msg);
mystr += '\n\n';
}
mystr += tuttie9 ? emo.SMILE_STAR + tools.get__('HAI_I_9_REQUISITI', msg) + emo.SMILE_STAR : emo.EXCLAMATION_MARK + tools.get__('NON_HAI_I_9_REQUISITI', msg);
mystr += '\n\n';
mystr += tools.get__('INFO_LA_MIA_LAVAGNA', msg);
2020-03-25 09:25:31 +01:00
mystr += '\n' + '1. ' + this.getsymb(emo.ENVELOPE, user.verified_email);
mystr += tools.get__('EMAIL', msg) + ' ';
mystr += user.verified_email ? tools.get__('VERIF', msg) : tools.get__('EMAIL_NON_VERIF', msg);
2020-03-25 09:25:31 +01:00
mystr += '\n2. ' + this.getsymb(emo.ROBOT_FACE, true) + tools.get__('BOT', msg) + ' ';
mystr += tools.get__('VERIF', msg);
2020-03-25 09:25:31 +01:00
mystr += '\n3. ' + this.getsymb(emo.PENCIL, tools.isBitActive(user.profile.saw_and_accepted, shared_consts.Accepted.CHECK_READ_GUIDELINES)) + tools.get__('LINEE_GUIDA', msg);
mystr += '\n4. ' + this.getsymb(emo.TV, tools.isBitActive(user.profile.saw_and_accepted, shared_consts.Accepted.CHECK_SEE_VIDEO_PRINCIPI)) + tools.get__('VIDEO_INTRO', msg);
mystr += '\n5. ' + this.getsymb(emo.EYES, user.profile.saw_zoom_presentation) + tools.get__('ZOOM_PARTECIPATO', msg);
mystr += '\n6. ' + this.getsymb(emo.DREAM, this.isdreamset(user)) + tools.get__('SCRITTO_SOGNO', msg);
mystr += '\n7. ' + this.getsymb(emo.CREDIT_CARD, this.ispayment(user)) + tools.get__('PAYMENTS', msg);
}
// } else{
// mystr += tools.get__('TELEGRAM_NOT_CONNECTED', msg) + ' ' + emoji.get('e-mail');
}
// numpersone = 2;
2020-03-25 09:25:31 +01:00
if (!mystrnave) {
mystr += '\n8. ' + this.getsymb(emo.INVITATI, numpersone >= 2, numpersone, numpersone, numpersone >= 3) + tools.get__('INVITATI', msg);
mystr += '\n9. ' + this.getsymb(emo.INVITATI, invitati_attivi >= 2, invitati_attivi, invitati_attivi, invitati_attivi >= 3) + tools.get__('INVITATI_ATTIVI', msg) + '\n' + '\n';
if (numpersone > 0) {
mystr += tools.get__('INVITATI_LISTA') + ':\n';
let index = 1;
dashboard.downline.forEach((user) => {
mystr += emoji.get('star-struck') + ` ${index}°: `;
mystr += (user._doc.qualified) ? emo.CHECK_VERDE : emo.CROSS_ROSSA;
mystr += `${user.name} ${user.surname} (${user.username})\n`;
index++;
});
} else {
mystr += tools.get__('NESSUN_INVITATO') + tools.ACAPO;
}
}
// if (dashboard.downnotreg) {
// if (dashboard.downnotreg.length > 0) {
// mystr += '\n' + emo.QUESTION_MARK + ' ' + tools.get__('NONREG', msg) + ':' + emo.QUESTION_MARK + '\n';
// let index = 1;
// dashboard.downnotreg.forEach((user) => {
// mystr += ` - ${index}°: ${user.name} ${user.surname} (tel: ${user.cell_complete})\n`;
// index++;
// });
// }
// }
if (tuttie9)
mystr += '\n' + printf(tools.get__('INFO_LAVAGNA_SITO', msg));
else
mystr += '\n' + printf(tools.get__('INFO_LAVAGNA_SITO_COMPLETARE', msg), tools.getHostByIdApp(this.idapp));
return mystr;
}
async menuLavagna(msg) {
const rec = this.getRecInMem(msg);
let mystr = '';
if (rec.user) {
mystr = await this.getLavagnaByUser(rec.user, msg)
}
if (!!mystr)
await this.sendMsg(msg.chat.id, mystr);
}
async menuNave(msg) {
const rec = this.getRecInMem(msg);
let mystr = '';
if (!rec.user)
return "";
let ind_order_to_check = rec.user.ind_order;
let arrstringa = msg.text.split(" ");
if (!!arrstringa) {
if (arrstringa.length > 1) {
let last = arrstringa.slice(-1)[0];
if (!isNaN(last)) {
ind_order_to_check = last;
}
}
}
mystr = await Nave.getNaveByUser(this.idapp, ind_order_to_check, rec.user.lang, true);
if (!!mystr)
await this.sendMsg(msg.chat.id, mystr);
}
async menuLinkCondividere(msg) {
const rec = this.getRecInMem(msg);
let mystr = '';
if (rec.user) {
mystr += printf(tools.get__('INFO_LINK_DA_CONDIVIDERE', msg), tools.getHostByIdApp(this.idapp) + '/signup/' + rec.user.username, tools.getlinkzoom(''));
await this.sendMsg(msg.chat.id, mystr);
}
}
2020-01-03 22:02:18 +01:00
async menuExitToTelegram(msg) {
const rec = this.getRecInMem(msg);
if (rec.user) {
await User.SetTelegramIdSuccess(this.idapp, rec.user._id, 0).then((recuser) => {
2020-01-03 22:02:18 +01:00
if (recuser) {
this.deleteRecInMem(msg);
this.sendMsg(msg.chat.id, txt.MSG_EXIT_TELEGRAM);
}
})
} else {
this.deleteRecInMem(msg);
2020-01-03 22:02:18 +01:00
}
}
async menuInformazioni(msg) {
const mystr = 'Informazioni Aggiuntive: ...';
await this.sendMsg(msg.chat.id, mystr);
}
async getNextZoom() {
2020-01-21 01:37:15 +01:00
const listazoom = await CalZoom.findAllIdApp(this.idapp);
const nextzoom = await CalZoom.getNextZoom(this.idapp);
let mystr = '';
mystr += emo.STARS + tools.get__('ZOOM_CONFERENCE') + emo.STARS + '\n\n';
2020-01-21 01:37:15 +01:00
let index = 1;
listazoom.forEach((evento) => {
let iniziata = false;
if (nextzoom)
iniziata = (nextzoom._id.toString() === evento._id.toString());
2020-01-21 01:37:15 +01:00
if (iniziata) {
mystr += emo.CHECK_VERDE + ' ' + tools.get__('ZOOM_INIZIATO') + ' ' + emo.CHECK_VERDE + '\n';
}
mystr += `${emo.EYES} ${tools.getstrDateTimeShort(evento.date_start)} ${emo.EYES}`;
mystr += `\n${evento.title}\n(${evento.note})\n\n`;
if (nextzoom) {
2020-01-21 01:37:15 +01:00
if (iniziata) {
mystr += emo.FIRE + tools.get__('CLICCA_ENTRA') + ' ' + emo.FIRE + '\n';
mystr += tools.getlinkzoom(evento.id_conf_zoom) + '\n\n';
2020-01-21 01:37:15 +01:00
}
}
2020-01-21 01:37:15 +01:00
index++;
});
if (!nextzoom && index > 1) {
mystr += "✨✨✨✨✨✨✨✨✨✨✨✨\n" +
tools.get__('CLICCA_PER_ZOOM') + ':\n' + tools.getlinkzoom(listazoom[0].id_conf_zoom) + '\n' + "✨✨✨✨✨✨✨✨✨✨✨✨\n" + '\n';
}
2020-01-21 01:37:15 +01:00
return mystr
}
async menuZoom(msg) {
let mystr = await this.getNextZoom();
2020-01-21 01:37:15 +01:00
await this.sendMsg(msg.chat.id, mystr);
2020-01-21 01:37:15 +01:00
}
async menuAdmin(msg) {
const mystr = tools.get__('SCEGLI_VOCE');
2020-01-21 01:37:15 +01:00
await
this.sendMsg(msg.chat.id, mystr, MenuAdmin);
}
getDestinStr(msg, destin, rec) {
if (destin === Destin.TUTTI)
return 'TUTTI';
else if (destin === Destin.STAFF)
return 'STAFF';
else if (destin === Destin.NO_7_REQ)
return 'No 7 Requisiti';
else if (destin === Destin.NO_9_REQ)
return 'No 9 Requisiti';
else if (destin === Destin.SI_INVITATI_NO_7REQ_INVITATI)
return '2 Invitati ma NO Requisiti';
else if (destin === Destin.MSG_TO_NAVE)
return 'Nave ' + rec.extraparam;
else if (destin === Destin.A_UTENTE) {
const rec = this.getRecInMem(msg);
return rec.msgall_username_specifico
}
}
async menumsgAll(msg) {
await this.menumsgGenerico(msg, Destin.TUTTI);
}
async menumsgStaff(msg) {
await this.menumsgGenerico(msg, Destin.STAFF);
}
async menumsg_No_7_Req(msg) {
await this.menumsgGenerico(msg, Destin.NO_7_REQ);
}
async menumsg_No_9_Req(msg) {
await this.menumsgGenerico(msg, Destin.NO_9_REQ);
}
async menumsg_to_Nave(msg, nave) {
await this.menumsgGenerico(msg, Destin.MSG_TO_NAVE, undefined, nave);
}
async menumsg_Si_Invitati_No_7Req(msg) {
await this.menumsgGenerico(msg, Destin.SI_INVITATI_NO_7REQ_INVITATI);
}
async menumsg_A_Utente(msg) {
const arr = msg.text.split(' ');
if (!!arr && arr.length > 1) {
const username = arr[1];
const rec = this.getRecInMem(msg);
rec.msg_wait = true;
await this.SendMsgToUser(msg, rec, username, msg.text);
}
}
async menumsgGenerico(msg, dest, username, extraparam) {
const rec = this.getRecInMem(msg);
if (rec.user) {
rec.msgall_status = StatusMSGALL.ASK;
rec.msgall_achi = dest;
rec.extraparam = extraparam;
if (!!username) {
rec.msgall_username_specifico = username;
}
const mystr = 'Scrivi qui un Messaggio da inviare a' + ' [' + this.getDestinStr(msg, dest, rec) + ']:';
await this.sendMsg(msg.chat.id, mystr, MenuSend);
}
}
async menuAssistenza(msg) {
const mytext = tools.get__('TESTO_ASSISTENZA', msg);
let menu = null;
const rec = this.getRecInMem(msg);
if (!rec.user) {
menu = MenuNoLogin
}
2020-01-21 01:37:15 +01:00
await
this.sendMsg(msg.chat.id, mytext, menu);
}
existInMemory(msg) {
const rec = this.getRecInMem(msg);
return !!rec
}
getstatus(rec) {
if (!!rec)
return rec.status;
else
return Status.NONE;
}
getstatusInMemory(msg) {
const rec = this.getRecInMem(msg);
return this.getstatus(rec);
}
getRecInMem(msg) {
return this.arrUsers.find((rec) => rec.id === msg.from.id);
}
getRecInMemById(id) {
return this.arrUsers.find((rec) => rec.id === id);
}
getRecByUsername(username) {
return this.arrUsers.find((rec) => rec.username_bo === username);
}
getRecInMemById(id) {
return this.arrUsers.find((rec) => rec.id === id);
}
2020-01-03 22:02:18 +01:00
deleteRecInMem(msg) {
this.arrUsers = this.arrUsers.filter((rec) => rec.id !== msg.from.id);
}
async getUser(msg, rec, conmsg) {
let myid = 0;
let ok = false;
let mystruser = tools.getFirstWord(msg.text.trim());
const user = await User.findByUsername(this.idapp, mystruser, true);
if (!user) {
if (conmsg) {
await this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND, MenuNoLogin);
const textman = msg.chat.first_name + ' ' + msg.chat.last_name + ' sta tentando di autenticarsi con il BOT (username che scrive: ' + msg.text + ') ';
await local_sendMsgTelegramToTheManagers(this.idapp, textman, msg);
rec.username_bo = '';
}
} else {
rec.username_bo = user.username;
myid = user._id;
ok = true;
}
return { rec, user, myid, ok };
}
async setUsernameBo(msg) {
try {
let rec = this.getRecInMem(msg);
if (msg.text === undefined)
return false;
console.log('msg.text', msg.text);
const text = msg.text;
if (text.length < 40) {
if (rec) {
let ris = await this.getUser(msg, rec, true);
rec = ris.rec;
if (ris.ok) {
rec.user = ris.user;
await User.SetTelegramCheckCode(this.idapp, ris.myid.toString(), rec.code);
rec.status = Status.WAITFOR_VERIFY_CODE;
await this.sendMsg(msg.from.id, printf(txt.MSG_VERIFY_CODE, tools.getHostByIdApp(this.idapp)), MenuNoLogin)
}
}
} else if (text.length === 0) {
if (rec)
rec.status = Status.NONE;
await this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_ANNULLA);
this.deleteRecInMem(msg)
} else {
await this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME)
}
} catch (e) {
console.error('Error setUsernameBo:', e)
}
}
async setVerifyCode(msg) {
try {
const code = msg.text.toString().trim();
const rec = this.getRecInMem(msg);
const user = await User.findByUsername(this.idapp, rec.username_bo, true);
2020-01-03 22:02:18 +01:00
let telegcode = 0;
if (user) {
telegcode = user.profile.teleg_checkcode.toString();
} else {
2020-01-21 01:37:15 +01:00
await
this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND, MenuNoLogin);
2020-01-03 22:02:18 +01:00
return
}
if (code.length < 7) {
if (rec) {
2020-01-03 22:02:18 +01:00
if (code === telegcode) {
// let ris = await this.getUser(msg, rec, false);
rec.status = Status.VERIFIED;
await User.SetTelegramIdSuccess(this.idapp, user._id, msg.from.id).then((recuser) => {
if (recuser) {
let name = recuser.name;
this.sendMsg(msg.from.id, printf(txt.MSG_VERIFY_OK, name));
local_sendMsgTelegramToTheManagers(this.idapp, recuser.name + ' ' + recuser.surname + ' si è Verificato a Telegram BOT!' + emo.STARS, msg);
} else {
this.sendMsg(msg.from.id, txt.MSG_ERR_UNKNOWN_VERIFY_CODE);
}
});
} else {
if (rec.retry < 2) {
rec.retry++;
2020-01-21 01:37:15 +01:00
await
this.sendMsg(msg.from.id, printf(txt.MSG_ERR_VERIFY_CODE, tools.getHostByIdApp(this.idapp)));
} else {
rec.status = Status.NONE;
2020-01-21 01:37:15 +01:00
await
this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_ANNULLA);
this.deleteRecInMem(msg);
}
}
}
} else if (msg.text.length === 0) {
if (rec)
rec.status = Status.NONE;
2020-01-21 01:37:15 +01:00
await
this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_ANNULLA)
} else {
2020-01-21 01:37:15 +01:00
await
this.sendMsg(msg.from.id, txt.MSG_ERRORE_VERIFY_CODE_MAXLEN)
}
} catch (e) {
console.error('Error setVerifyCode', e);
}
}
async sistemaRecDest(rec, msg) {
let recdest = this.getRecByUsername(rec.msgall_username_specifico);
if (!recdest) {
const userdest = await User.findByUsername(this.idapp, rec.msgall_username_specifico);
if (!!userdest) {
let msgdest = msg;
msgdest.from.id = userdest.profile.teleg_id;
await this.createIfNotExist(msgdest);
recdest = this.getRecByUsername(rec.msgall_username_specifico);
}
}
if (!!recdest) {
recdest.msgall_username_specifico = rec.username_bo;
} else {
rec.msgall_username_specifico = '';
}
return recdest
}
async sendMsgToAll(rec, msg, texttosend, destin) {
try {
if ((texttosend.length < 3) && (destin !== Destin.A_UTENTE)) {
} else {
let usersall = null;
if (destin === Destin.A_UTENTE)
usersall = await User.getUsersTelegALL(rec.user.idapp, rec.msgall_username_specifico);
else
usersall = await User.getUsersTelegALL(rec.user.idapp);
let nummsgsent = 0;
let textdainviare = "";
let preparatesto = '';
let myid = '';
if (texttosend === Menu.ZOOM) {
texttosend = await this.getNextZoom()
}
const cmd = texttosend.toLowerCase();
if (usersall) {
if (cmd === Menu.INDIETRO) {
rec.msgall_status = StatusMSGALL.NONE;
return
}
tools.writeEventsLog(this.getDestinStr(msg, destin, rec) + ':\n' + texttosend);
for (const utente of usersall) {
if (texttosend === Menu.LAVAGNA) {
textdainviare = await this.getLavagnaByUser(utente, msg);
} else if (destin === Destin.A_UTENTE) {
textdainviare = texttosend;
} else {
textdainviare = texttosend;
}
let invia = false;
if (destin === Destin.STAFF) {
invia = User.isManager(utente.perm);
} else if (destin === Destin.TUTTI) {
invia = true;
} else if (destin === Destin.A_UTENTE) {
invia = utente.username === rec.msgall_username_specifico;
} else if (destin === Destin.NO_7_REQ) {
invia = !await User.isUserQualified7(this.idapp, utente.username);
} else if (destin === Destin.NO_9_REQ) {
invia = !await User.isUserQualified9(this.idapp, utente.username);
} else if (destin === Destin.MSG_TO_NAVE) {
invia = !await Nave.findDonatoreByNave(this.idapp, rec.extraparam);
} else if (destin === Destin.SI_INVITATI_NO_7REQ_INVITATI) {
const numinvitati = await User.getnumInvitati(this.idapp, utente.username);
const numinvitatiattivi = await User.getnumInvitatiAttivi(this.idapp, utente.username);
invia = (numinvitati >= 2) && (numinvitatiattivi < 2);
}
if (invia) {
if (cmd === RICEVI_EMAIL) {
preparatesto += utente.email + ', ';
} else if (cmd === CONTA_SOLO) {
// Niente
} else {
if (destin === Destin.A_UTENTE) {
await this.sistemaRecDest(rec, msg);
await this.sendMsg(utente.profile.teleg_id, '[' + rec.username_bo + ' ti scrive]:\n' + textdainviare, MenuChat);
} else {
await this.sendMsg(utente.profile.teleg_id, textdainviare);
}
await tools.snooze(300)
}
nummsgsent++;
if (!SendMsgCmd.includes(cmd)) {
if ((nummsgsent % 50) === 0) {
myid = await this.sendMsg(msg.chat.id, nummsgsent + ' ' + getstr(msg.from.language_code, txt.MSG_MSG_INCORSO), null, { message_id: myid });
await tools.snooze(300)
}
}
}
}
}
let msgris = "";
if (cmd === CONTA_SOLO) {
msgris = nummsgsent + ' ' + getstr(msg.from.language_code, txt.MSG_MSG_TOSENT);
} else if (cmd === RICEVI_EMAIL) {
msgris = nummsgsent + ' ' + 'Email';
await this.sendMsg(msg.chat.id, msgris);
msgris = preparatesto;
} else {
msgris = nummsgsent + ' ' + getstr(msg.from.language_code, txt.MSG_MSG_SENT);
}
if (destin === Destin.A_UTENTE) {
const recdest = await this.sistemaRecDest(rec);
if (!!recdest) {
await this.sendMsg(msg.chat.id, 'Conversazione Iniziata con ' + rec.msgall_username_specifico + ' !', MenuChat);
} else {
await this.sendMsg(msg.chat.id, 'Utente ' + rec.msgall_username_specifico + ' non presente sul BOT !');
}
} else {
tools.writeEventsLog(msgris);
await this.sendMsg(msg.chat.id, msgris);
}
}
rec.start_write_msgall = false;
} catch (e) {
console.error(e);
}
}
selectMenuHelp(msg) {
return ((msg.text === Menu.INFO) || (msg.text === Menu.ASSISTENZA))
}
async receiveMsg(msg) {
let status = this.getstatusInMemory(msg);
if (status === Status.NONE) {
await this.start(msg);
2020-01-03 22:02:18 +01:00
let status = this.getstatusInMemory(msg);
if (status !== Status.VERIFIED)
return
} else {
await this.setUser(msg)
}
const rec = this.getRecInMem(msg);
status = this.getstatus(rec);
if (status === Status.WAITFOR_USERNAME_BO && !this.selectMenuHelp(msg)) {
await this.setUsernameBo(msg)
} else if (status === Status.WAITFOR_VERIFY_CODE) {
await this.setVerifyCode(msg)
} else if (status === Status.NONE) {
await this.start(msg);
} else if (status === Status.VERIFIED) {
let normale = true;
if (rec.msgall_status === StatusMSGALL.CONFIRM) {
if (msg.text === Menu.SI) {
// Take msg to send to ALL
await this.sendMsgToAll(rec, msg, rec.msgtosent, rec.msgall_achi)
} else {
this.sendMsg(msg.chat.id, txt.MSG_OPERAZ_ANNULLATA);
}
rec.msgall_status = StatusMSGALL.NONE;
normale = false;
} else if (rec.msgall_status === StatusMSGALL.ASK) {
if (msg.text !== Menu.INDIETRO) {
rec.msgtosent = msg.text;
rec.msgall_status = StatusMSGALL.CONFIRM;
const cmd = rec.msgtosent.toLowerCase();
let achi = this.getDestinStr(msg, rec.msgall_achi, rec);
let domanda = '';
if (cmd === CONTA_SOLO)
domanda = 'Confermi di vedere a quante persone arriverebbe questo messaggio, a ' + achi + ' ?\n' + rec.msgtosent;
else if (cmd === RICEVI_EMAIL)
domanda = 'Confermi di vedere la lista delle email di ' + achi + '?';
else {
if (rec.msgall_achi === Destin.A_UTENTE)
domanda = 'Confermi d\'Iniziare una Chat messaggi con ' + achi + ' ?\n' + rec.msgtosent;
else
domanda = 'Confermi d\'Inviare questo messaggio a ' + achi + ' ?\n' + rec.msgtosent;
}
this.ChiediSINO(msg, domanda);
} else {
rec.msgall_status = StatusMSGALL.NONE;
2020-01-21 01:37:15 +01:00
await
this.msgScegliMenu(msg);
}
normale = false
}
if (normale) {
// Check Menu
await this.isMenu(rec, msg);
}
} else {
2020-01-21 01:37:15 +01:00
await
this.isMenuNotVerified(rec, msg);
}
}
async askVerifiedCode(msg) {
const rec = this.arrUsers.find((rec) => rec.id === msg.from.id);
if (!rec) {
await this.addUser(msg);
// await this.sendMsg(msg.chat.id, getstr(msg.from.language_code, printf(txt.MSG_ASK_USERNAME_BO, tools.getHostByIdApp(this.idapp))));
await this.sendMsg(msg.chat.id, getstr(msg.from.language_code, printf(txt.MSG_ASK_USERNAME_BO, tools.getNomeAppByIdApp(this.idapp))), MenuNoLogin);
return false;
}
return true;
}
async setUser(msg) {
const id = msg.from.id;
const user = await User.UserByIdTelegram(this.idapp, id);
let rec = this.arrUsers.find((rec) => rec.id === msg.from.id);
if (user && rec) {
rec.user = user;
}
}
async setUserbyUsername(username) {
const user = await User.findByUsername(this.idapp, username);
let rec = this.arrUsers.find((rec) => rec.username_bo === username);
if (user && rec) {
rec.user = user;
}
}
async alreadyExist(msg) {
const id = msg.from.id;
let rec = null;
try {
const user = await User.UserByIdTelegram(this.idapp, id);
let rec = this.arrUsers.find((rec) => rec.id === msg.from.id);
if (user && !rec) {
rec = this.addUser(msg);
}
if (rec) {
rec.user = user;
if (user)
rec.username_bo = user.username;
else
rec.username_bo = ''
}
} catch (e) {
console.error('Error: ', e);
2020-01-03 22:02:18 +01:00
}
return !!rec
}
addUser(msg) {
const lang = msg.from.language_code;
const code = 100000 + Math.round(Math.random() * 899999);
const rec = {
id: msg.from.id,
code,
lang,
status: Status.WAITFOR_USERNAME_BO,
statusmsg: 0,
msgcodeprec: '',
sex: 0,
numdomande: 0,
retry: 0,
username_bo: '',
msgall_status: StatusMSGALL.NONE,
msgall_achi: 0,
msgall_username_specifico: '',
extraparam: '',
msgtosent: '',
msg_wait: false,
lastmenu: null,
};
this.arrUsers.push(rec);
return rec;
}
async insertIntoDB(msg) {
return await this.askVerifiedCode(msg);
}
async getKeyboard(id, menu) {
let keyb = MenuStandard;
// Check if you are Admin
const ismanager = await User.isAdminByIdTeleg(this.idapp, id);
if (ismanager && menu !== MenuChat)
keyb = MenuPerAdmin;
if (menu) {
keyb = menu
}
return keyb
}
modificaMsg(chatid, idmodif, text) {
const form = {
"chat_id": chatid,
"message_id": idmodif,
};
try {
return this.bot.editMessageText(text, form);
} catch (e) {
console.log('Err Telegram: ' + e);
}
}
async _inviaMsg(id, text, form, menu, msg_id, chat_id, ripr_menuPrec) {
if (!text)
return 0;
if (!!msg_id) {
return this.modificaMsg(chat_id, msg_id, text);
}
const recmem = this.getRecInMemById(id);
if (!menu) {
if (recmem) {
if (recmem.msgall_username_specifico !== '') {
menu = MenuChat
}
}
}
if (recmem) {
recmem.lastmenu = menu
}
if (ripr_menuPrec) {
if (recmem && !!recmem.lastmenu) {
menu = recmem.lastmenu
}
}
try {
if (!form) {
form = {
"message_id": msg_id,
"reply_markup": {
"resize_keyboard": true,
"keyboard": await this.getKeyboard(id, menu)
}
};
}
const res = this.bot.sendMessage(id, text, form)
.catch((e) => {
let blocked = false;
if ((e.message.indexOf('Forbidden') > 0) || (e.message.indexOf('chat not found') > 0)) {
blocked = true;
}
if (!blocked) {
console.error(e.message);
}
if (blocked) {
User.SetTelegramWasBlocked(this.idapp, id);
}
return 0;
});
return res;
} catch (e) {
return 0
}
}
async SendMsgToUser(msg, rec, username, text) {
if (rec.msg_wait) {
await this.menumsgGenerico(msg, Destin.A_UTENTE, username);
rec.msg_wait = false;
} else {
const telegid = await User.TelegIdByUsername(this.idapp, username);
if (telegid > 0) {
await this.sistemaRecDest(rec, msg);
// await this.sendMsg(msg.chat.id, '[Msg inviato a ' + username + ']: ');
await this.sendMsg(telegid, Menu.CHAT_PERSONALE + '[' + rec.username_bo + ' ti scrive]:\n' + text, MenuChat);
} else {
await this.sendMsg(msg.chat.id, 'Username non valido');
rec.msgall_username_specifico = ''
}
}
}
async sendMsg(id, text, menu, form, msg_id, chat_id, ripr_menuPrec) {
return this._inviaMsg(id, text, form, menu, msg_id, chat_id, ripr_menuPrec);
}
async msgBenvenuto(id) {
return this._inviaMsg(id, Benvenuto, {
"reply_markup": {
"resize_keyboard": true,
"keyboard": await this.getKeyboard(id)
}
});
}
async ChiediSINO(msg, domanda) {
this._inviaMsg(msg.from.id, domanda, {
"reply_markup": {
"resize_keyboard": true,
'one_time_keyboard': true,
"keyboard": MenuYesNo
}
});
}
2020-01-03 22:02:18 +01:00
async msgScegliMenu(msg) {
// const rec = this.getRecInMem(msg);
this._inviaMsg(msg.from.id, txt.MSG_SCEGLI_MENU, {
2020-01-03 22:02:18 +01:00
"reply_markup": {
"resize_keyboard": true,
"keyboard": await this.getKeyboard(msg.from.id)
2020-01-03 22:02:18 +01:00
}
2020-01-21 01:37:15 +01:00
})
;
2020-01-03 22:02:18 +01:00
}
}
const arrTelegram = [];
function getclTelegBytoken(token) {
2020-01-03 22:02:18 +01:00
const rec = arrTelegram.find((rec) => rec.cl.token === token);
if (!!rec)
return rec.cl;
else
return null;
}
function getclTelegByidapp(idapp) {
// ****************************
if (appTelegramFinti.includes(idapp)) {
const ind = appTelegramFinti.indexOf(idapp);
if (ind >= 0)
idapp = appTelegramDest[ind]; // Invia
}
2020-01-03 22:02:18 +01:00
const rec = arrTelegram.find((rec) => rec.idapp === idapp);
if (!!rec)
return rec.cl;
else
return null;
}
if (!tools.testing()) {
console.log('TELEGRAM STARTING.... ');
for (const idapp of appTelegram) {
const token = tools.getTelegramKeyByIdApp(idapp);
// console.log('idapp', idapp, 'token', token);
if (!!token) {
const bot = new TelegramBot(token, { polling: true });
arrTelegram.push({ idapp, cl: new Telegram(idapp, bot) });
bot.onText(/\/start/, (msg) => {
const myclTelegram = getclTelegBytoken(bot.token);
myclTelegram.start(msg);
});
// Matches "/echo [whatever]"
bot.onText(/\/echo (.+)/, (msg, match) => {
// 'msg' is the received Message from Telegram
// 'match' is the result of executing the regexp above on the text content
// of the message
const chatId = msg.chat.id;
const resp = match[1]; // the captured "whatever"
// send back the matched "whatever" to the chat
bot.sendMessage(chatId, resp);
});
// Listen for any kind of message. There are different kinds of
// messages.
bot.on('message', (msg) => {
const myclTelegram = getclTelegBytoken(bot.token);
// console.log('msg', msg);
const chatId = msg.chat.id;
myclTelegram.receiveMsg(msg);
// var bye = "bye";
// if (msg.text.toString().toLowerCase().includes(bye)) {
// bot.sendMessage(msg.chat.id, "Hope to see you around again , Bye");
// }
// send a message to the chat acknowledging receipt of their message
// bot.sendMessage(chatId, 'Received your message');
});
// Handle callback queries
bot.on('callback_query', function onCallbackQuery(callbackQuery) {
console.log('callback_query', callbackQuery);
bot.answerCallbackQuery(callbackQuery.id, { url });
});
}
}
}