const tools = require('../tools/general'); const appTelegram = ['7']; const printf = require('util').format; const { User } = require('../models/user'); const Benvenuto = 'Benvenuto'; const Menu = { LAVAGNA: 'La tua Lavagna', LINK_CONDIVIDERE: 'Tuo Link da condividere', INFO: 'Informazioni', ASSISTENZA: 'Assistenza', }; const MenuStandard = [[Menu.LAVAGNA, Menu.LINK_CONDIVIDERE], [Menu.INFO], [Menu.ASSISTENZA]]; const Status = { NONE: 0, VERIFIED: 1, WAITFOR_USERNAME_BO: 102, WAITFOR_VERIFY_CODE: 103, }; const txt = { 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.', MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attenzione! Devi inserire solo il codice a 6 cifre', MSG_VERIFY_CODE: 'Vai sul sito e aggiorna la pagina (REFRESH) e scrivi qui il Codice di Autenticazione che vedrai visualizzato', MSG_ERR_VERIFY_CODE: 'Codice di Verifica Errato! Reinserire il codice di 6 cifre.', MSG_VERIFY_OK: 'Benvenuto %s. Ora sei correttamente verificato!', MSG_ERR_UNKNOWN_VERIFY_CODE: 'Errore durante il salvataggio sul Server. Riprovare piú tardi' }; const TelegramBot = require('node-telegram-bot-api'); function getstr(lang, text) { return text; } class Telegram { constructor(idapp, bot) { this.idapp = idapp; this.bot = bot; this.token = bot.token; this.arrUsers = []; } async start(msg) { // this.msgBenvenuto(msg.chat.id); // Check if Present to the DB if (!await this.alreadyExist(msg)) { this.insertIntoDB(msg); } else { let rec = this.getRecInMem(msg); if (!rec) rec = this.addUser(msg); rec.status = Status.VERIFIED } } isMenu(msg) { if (msg.text === Menu.LAVAGNA) { this.menuLavagna(msg) }else if (msg.text === Menu.LINK_CONDIVIDERE) { this.menuLinkCondividere(msg) }else if (msg.text === Menu.ASSISTENZA) { this.menuAssistenza(msg) }else if (msg.text === Menu.INFO) { this.menuInformazioni(msg) } } 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); const numpersone = (dashboard.downline) ? dashboard.downline.length : 0; if (dashboard.aportador) { mystr = `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 (numpersone > 0) { mystr += `Persone che hai invitato (${numpersone}):\n`; let index = 1; dashboard.downline.forEach((user) => { mystr += `${index}°: ${user.username} (${user.name} ${user.surname})`; index++; }); } else { mystr += `Attualmente non hai invitato nessuna persona.\n`; } } if (!!mystr) 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; this.sendMsg(msg.chat.id, mystr); } } async menuInformazioni(msg) { const mystr = 'Informazioni Aggiuntive: ...'; this.sendMsg(msg.chat.id, mystr); } async menuAssistenza(msg) { const mystr = 'Per contattarci usa questa chat di gruppo: ....'; this.sendMsg(msg.chat.id, mystr); } existInMemory(msg) { const rec = this.getRecInMem(msg); return !!rec } getstatusInMemory(msg) { const rec = this.getRecInMem(msg); if (!!rec) return rec.status; else return Status.NONE; } getRecInMem(msg) { return this.arrUsers.find((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.toLowerCase()); if (!user) { this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND) } else { await User.SetTelegramCheckCode(this.idapp, rec.username_bo, rec.code); rec.status = Status.WAITFOR_VERIFY_CODE; this.sendMsg(msg.from.id, txt.MSG_VERIFY_CODE) } } } else if (text.length === 0) { if (rec) rec.status = Status.NONE; this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_ANNULLA) } else { 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 code = msg.text.toString().trim(); if (msg.text.length < 7) { if (rec) { if (code === msg.text) { 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 { rec.retry++; this.sendMsg(msg.from.id, txt.MSG_ERR_VERIFY_CODE) } } } else if (msg.text.length === 0) { if (rec) rec.status = Status.NONE; this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_ANNULLA) } else { this.sendMsg(msg.from.id, txt.MSG_ERRORE_VERIFY_CODE_MAXLEN) } } catch (e) { console.error('Error setVerifyCode', e); } } async receiveMsg(msg) { let status = this.getstatusInMemory(msg); if (status === Status.NONE) { await this.start(msg); } status = this.getstatusInMemory(msg); if (status === Status.WAITFOR_USERNAME_BO) { this.setUsernameBo(msg) } else if (status === Status.WAITFOR_VERIFY_CODE) { this.setVerifyCode(msg) } else if (status === Status.NONE) { this.start(msg); } else if (status === Status.VERIFIED) { // Check Menu this.isMenu(msg); } } async askVerifiedCode(msg) { const rec = this.arrUsers.find((rec) => rec.id === msg.from.id); if (!rec) { await this.addUser(msg); this.sendMsg(msg.chat.id, getstr(msg.from.language_code, txt.MSG_ASK_USERNAME_BO)); } } async alreadyExist(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 = this.addUser(msg); } if (rec) rec.user = user; 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: '' }; this.arrUsers.push(rec); return rec; } insertIntoDB(msg) { this.askVerifiedCode(msg); } sendMsg(id, text) { this.bot.sendMessage(id, text, { "reply_markup": { "keyboard": MenuStandard } }); } msgBenvenuto(id) { this.bot.sendMessage(id, Benvenuto, { "reply_markup": { "keyboard": MenuStandard } }); } } const arrTelegram = []; function getclTelegBytoken(token) { const rec = arrTelegram.find((rec) => rec.cl.token === token) if (!!rec) return rec.cl; else return null; } 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 }); }); } }