const tools = require('../tools/general'); const appTelegram = ['7']; const printf = require('util').format; const { User } = require('../models/user'); const emoji = require('node-emoji'); const i18n = require("i18n"); const Benvenuto = emoji.get('heartbeat') + emoji.get('heartbeat') + emoji.get('heartbeat') + ' Benvenuto!'; const emo = { 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'), 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'), }; 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') } } const Menu = { LAVAGNA: emoji.get('om_symbol') + ' La tua Lavagna', LINK_CONDIVIDERE: emoji.get('link') + ' Link da condividere', INFO: emoji.get('information_source') + ' Informazioni', ASSISTENZA: emoji.get('open_hands') + ' Assistenza', ADMIN: emoji.get('information_desk_person') + ' Admin', ALTRO: emoji.get('newspaper') + ' Altro', MSGATUTTI: emoji.get('incoming_envelope') + ' Invia a TUTTI', INDIETRO: emoji.get('back') + ' Indietro', SI: emoji.get('thumbsup') + ' SI', NO: emoji.get('thumbsdown') + ' NO', EXIT_TELEGRAM: 'exittotelegram', }; const MenuStandard = [[Menu.LAVAGNA, Menu.LINK_CONDIVIDERE], [Menu.INFO, Menu.ASSISTENZA]]; const MenuPerAdmin = [[Menu.LAVAGNA, Menu.LINK_CONDIVIDERE], [Menu.INFO, Menu.ASSISTENZA], [Menu.ADMIN, Menu.ALTRO]]; const MenuYesNo = [[Menu.SI, Menu.NO]]; const MenuAdmin = [[Menu.MSGATUTTI, Menu.INDIETRO], ['', '']]; const MenuYes = [[Menu.MSGATUTTI, Menu.INDIETRO], ['', '']]; const Status = { NONE: 0, VERIFIED: 1, WAITFOR_USERNAME_BO: 102, WAITFOR_VERIFY_CODE: 103, }; const StatusMSGALL = { NONE: 0, ASK: 1, CONFIRM: 2, }; const txt = { MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Scegli una voce di menu:' + emoji.get('dizzy'), MSG_ASK_USERNAME_BO: 'Inserire lo username con cui ti sei registrato sul sito:', MSG_ERRORE_USERNAME: 'Attenzione! Devi inserire solo lo username (20 caratteri massimo)', MSG_ERRORE_USERNAME_NOT_FOUND: 'Attenzione! Username non trovato in archivio. Verifica che sia corretto.', 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: 'Vai sul sito e scrivi qui il Codice di Autenticazione che vedrai visualizzato', MSG_ERR_VERIFY_CODE: 'Codice di Verifica Errato! Controllare sul Sito e reinserire il nuovo codice di 6 cifre.', MSG_VERIFY_OK: emoji.get('grinning') + ' Benvenuto %s. Ora sei correttamente verificato!', 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: emoji.get('heart_eyes') + ' Si è appena Registrato %s\n(Invitato da %s)', MSG_MSG_SENT: emoji.get('envelope') + ' Messaggi Inviati !', }; const TelegramBot = require('node-telegram-bot-api'); module.exports = { ADMIN_IDTELEGRAM_SERVER: '12429864', ADMIN_USER_SERVER: 'paoloar77', ADMIN_USER_NAME_SERVER: 'Paolo', phase: { REGISTRATION: 1 }, notifyToTelegram: async function (phase, mylocalsconf) { let userdest = mylocalsconf.user.aportador_solidario; let NameFrom = `${mylocalsconf.user.name} ${mylocalsconf.user.surname}`; let aportador = ''; if (userdest) { aportador = ` (${userdest})`; NameFrom += aportador; } else { aportador = mylocalsconf.user.aportador_solidario_nome_completo; } 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})`, aportador); } let addtext = ""; if (!!mylocalsconf.user.aportador_solidario) { addtext = '[Inviato a ' + NameFrom + ']:' + '\n'; await this.sendMsgTelegram(mylocalsconf.idapp, userdest, text); } await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, addtext + text); }, sendMsgTelegramToTheManagers: async function (idapp, text) { const usersmanagers = await User.getusersManagers(idapp); // console.log('usersmanagers', usersmanagers); if (usersmanagers) { for (const rec of usersmanagers) { this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, text) } } }, sendMsgTelegramToALL: async function (idapp, text) { const usersall = await User.getUsersTelegALL(idapp); if (usersall) { usersall.forEach((rec) => { this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, text) }); } }, sendMsgTelegram: async function (idapp, username, text) { const teleg_id = await User.TelegIdByUsername(idapp, username); const cl = getclTelegByidapp(idapp); if (cl && teleg_id) { await cl.sendMsg(teleg_id, text) } }, sendMsgTelegramByIdTelegram: async function (idapp, idtelegram, text) { if (!idtelegram) return; const cl = getclTelegByidapp(idapp); if (cl && idtelegram) { await cl.sendMsg(idtelegram, text) } } }; 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 (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 isMenuNotVerified(rec, msg) { if (msg.text === Menu.ASSISTENZA) { await this.menuAssistenza(msg) } else if (msg.text === Menu.INFO) { await this.menuInformazioni(msg) } else { await this.msgScegliMenu(msg); } } async isMenu(rec, msg) { if (msg.text === Menu.LAVAGNA) { await this.menuLavagna(msg) } else if (msg.text === Menu.LINK_CONDIVIDERE) { await this.menuLinkCondividere(msg) } 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.INDIETRO) { await this.msgScegliMenu(msg); } else { await this.isMenuNotVerified(rec, msg); } } getsymb(symb, valid, isnum, verdeif, smileif) { let str = symb + ': '; if (valid) str += emo.CHECK_VERDE; else str += emo.CROSS_ROSSA; if (isnum) { str += ' ' + getemojibynumber(valid); 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 } async menuLavagna(msg) { const rec = this.getRecInMem(msg); // console.log('rec', rec); let mystr = ''; if (rec.user) { const dashboard = await User.getDashboard(this.idapp, rec.user.aportador_solidario, rec.user.username); let numpersone = (dashboard.downline) ? dashboard.downline.length : 0; 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`; if (rec.user) { mystr += tools.get__('BENVENUTO', msg) + ' ' + rec.user.name + ' ' + emo.DIZZY; mystr += '\n' + '\n' + this.getsymb(emo.ENVELOPE, rec.user.verified_email); mystr += rec.user.verified_email ? tools.get__('EMAIL_VERIF', msg) : tools.get__('EMAIL_NON_VERIF', msg); mystr += '\n' + '\n' + this.getsymb(emo.EYES, rec.user.profile.saw_zoom_presentation) + tools.get__('ZOOM_PARTECIPATO', msg); mystr += '\n' + '\n' + this.getsymb(emo.DREAM, this.isdreamset(rec.user)) + tools.get__('SCRITTO_SOGNO', msg); // } else{ // mystr += tools.get__('TELEGRAM_NOT_CONNECTED', msg) + ' ' + emoji.get('e-mail'); } // numpersone = 3; mystr += '\n' + '\n' + this.getsymb(emo.INVITATI, numpersone, true, numpersone >= 2, numpersone >= 3) + tools.get__('INVITATI', msg) + '\n'; if (numpersone > 0) { let index = 1; dashboard.downline.forEach((user) => { mystr += emoji.get('star-struck') + ` ${index}°: ${user.username} (${user.name} ${user.surname})\n`; index++; }); } } if (!!mystr) await this.sendMsg(msg.chat.id, mystr); } async menuLinkCondividere(msg) { const rec = this.getRecInMem(msg); if (rec.user) { const mystr = tools.getHostByIdApp(this.idapp) + '/signup/' + rec.user.username; await this.sendMsg(msg.chat.id, mystr); } } async menuExitToTelegram(msg) { const rec = this.getRecInMem(msg); if (rec.user) { await User.SetTelegramIdSuccess(this.idapp, rec.user.username, 0).then((recuser) => { if (recuser) { this.deleteRecInMem(msg); this.sendMsg(msg.chat.id, txt.MSG_EXIT_TELEGRAM); } }) } } async menuInformazioni(msg) { const mystr = 'Informazioni Aggiuntive: ...'; await this.sendMsg(msg.chat.id, mystr); } async menuAdmin(msg) { const mystr = 'scegli una voce:'; await this.sendMsg(msg.chat.id, mystr, MenuAdmin); } async menumsgAll(msg) { const rec = this.getRecInMem(msg); if (rec.user) { const mystr = 'Scrivi qui un Messaggio da inviare a TUTTI:'; rec.msgall_status = StatusMSGALL.ASK; await this.sendMsg(msg.chat.id, mystr, MenuAdmin); } } async menuAssistenza(msg) { const mytext = tools.get__('TESTO_ASSISTENZA', msg); await this.sendMsg(msg.chat.id, mytext); } 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); } deleteRecInMem(msg) { this.arrUsers = this.arrUsers.filter((rec) => rec.id !== msg.from.id); } async setUsernameBo(msg) { try { const rec = this.getRecInMem(msg); console.log('msg.text', msg.text); const text = msg.text; if (text.length < 20) { if (rec) { rec.username_bo = text; // Check if username exist const user = await User.findByUsername(this.idapp, rec.username_bo); if (!user) { await this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND) } else { rec.user = user; await User.SetTelegramCheckCode(this.idapp, rec.username_bo, rec.code); rec.status = Status.WAITFOR_VERIFY_CODE; await this.sendMsg(msg.from.id, txt.MSG_VERIFY_CODE) } } } 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 rec = this.getRecInMem(msg); const user = await User.findByUsername(this.idapp, rec.username_bo); const code = msg.text.toString().trim(); let telegcode = 0; if (user) { telegcode = user.profile.teleg_checkcode.toString(); } else { await this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND); return } if (msg.text.length < 7) { if (rec) { if (code === telegcode) { rec.status = Status.VERIFIED; await User.SetTelegramIdSuccess(this.idapp, rec.username_bo, msg.from.id).then((recuser) => { if (recuser) { let name = recuser.name; this.sendMsg(msg.from.id, printf(txt.MSG_VERIFY_OK, name)) } else { this.sendMsg(msg.from.id, txt.MSG_ERR_UNKNOWN_VERIFY_CODE); } }); } else { if (rec.retry < 2) { rec.retry++; await this.sendMsg(msg.from.id, txt.MSG_ERR_VERIFY_CODE) } else { rec.status = Status.NONE; 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; await this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_ANNULLA) } else { await this.sendMsg(msg.from.id, txt.MSG_ERRORE_VERIFY_CODE_MAXLEN) } } catch (e) { console.error('Error setVerifyCode', e); } } async sendMsgToAll(rec, msg, texttosend) { if (texttosend.length < 3) { } else { const usersall = await User.getUsersTelegALL(rec.user.idapp); let nummsgsent = 0; if (usersall) { for (const rec of usersall) { await this.sendMsg(rec.profile.teleg_id, texttosend); nummsgsent++; } } await this.sendMsg(msg.chat.id, nummsgsent + ' ' + getstr(msg.from.language_code, txt.MSG_MSG_SENT)); } rec.start_write_msgall = false; } 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); 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) } 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 domanda = 'Confermi d\'Inviare questo messaggio a TUTTI ?\n' + rec.msgtosent; this.ChiediSINO(msg, domanda); } else { rec.msgall_status = StatusMSGALL.NONE; await this.msgScegliMenu(msg); } normale = false } if (normale) { // Check Menu await this.isMenu(rec, msg); } } else { 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, txt.MSG_ASK_USERNAME_BO)); 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 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); } 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, retry: 0, username_bo: '', msgall_status: StatusMSGALL.NONE, msgtosent: '', }; this.arrUsers.push(rec); return rec; } insertIntoDB(msg) { return this.askVerifiedCode(msg); } async getKeyboard(id, menu) { let keyb = MenuStandard; // Check if you are Admin const ismanager = await User.isManagerByIdTeleg(this.idapp, id); if (ismanager) keyb = MenuPerAdmin; if (menu) { keyb = menu } return keyb } async sendMsg(id, text, menu) { if (!text) return; this.bot.sendMessage(id, text, { "reply_markup": { "resize_keyboard": true, "keyboard": await this.getKeyboard(id, menu) } }); } async msgBenvenuto(id) { this.bot.sendMessage(id, Benvenuto, { "reply_markup": { "resize_keyboard": true, "keyboard": await this.getKeyboard(id) } }); } async ChiediSINO(msg, domanda) { this.bot.sendMessage(msg.from.id, domanda, { "reply_markup": { "resize_keyboard": true, 'one_time_keyboard': true, "keyboard": MenuYesNo } }); } async msgScegliMenu(msg) { // const rec = this.getRecInMem(msg); this.bot.sendMessage(msg.from.id, txt.MSG_SCEGLI_MENU, { "reply_markup": { "resize_keyboard": true, "keyboard": await this.getKeyboard(msg.from.id) } }); } } const arrTelegram = []; function getclTelegBytoken(token) { const rec = arrTelegram.find((rec) => rec.cl.token === token); if (!!rec) return rec.cl; else return null; } function getclTelegByidapp(idapp) { 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 }); }); } } }