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

487 lines
13 KiB
JavaScript
Raw Normal View History

const tools = require('../tools/general');
const appTelegram = ['7'];
const printf = require('util').format;
const { User } = require('../models/user');
2020-01-03 22:02:18 +01:00
const emoji = require('node-emoji');
const Benvenuto = emoji.get('heartbeat') + emoji.get('heartbeat') + emoji.get('heartbeat') + ' Benvenuto!';
const Menu = {
2020-01-03 22:02:18 +01:00
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',
EXIT_TELEGRAM: 'exittotelegram',
};
2020-01-03 22:02:18 +01:00
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 = {
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: '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',
2020-01-03 22:02:18 +01:00
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 con il tuo link:\n%s',
};
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
},
notifyToTelegram: async function (phase, mylocalsconf) {
let userdest = mylocalsconf.user.aportador_solidario;
let NameFrom = `${mylocalsconf.user.name} ${mylocalsconf.user.surname} (${userdest})`;
let text = '';
if (phase === this.phase.REGISTRATION) {
NameFrom = await User.getNameSurnameByUsername(mylocalsconf.idapp, userdest) + ` (${userdest})`;
if (!!mylocalsconf.user.aportador_solidario)
text = printf(txt.MSG_APORTADOR_USER_REGISTERED, `${mylocalsconf.user.name} ${mylocalsconf.user.surname} (${mylocalsconf.user.username})`);
}
await this.sendMsgTelegram(mylocalsconf.idapp, userdest, text);
await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, '[Inviato a ' + NameFrom + ']:' + '\n' + text);
},
sendMsgTelegramToTheManagers: async function (idapp, text) {
const usersmanagers = await User.getusersManagers(idapp);
// console.log('usersmanagers', usersmanagers);
if (usersmanagers) {
usersmanagers.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) {
cl.sendMsg(teleg_id, text)
}
},
sendMsgTelegramByIdTelegram: function (idapp, idtelegram, text) {
const cl = getclTelegByidapp(idapp);
if (cl && idtelegram) {
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 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)
2020-01-03 22:02:18 +01:00
} else if (msg.text === Menu.LINK_CONDIVIDERE) {
this.menuLinkCondividere(msg)
2020-01-03 22:02:18 +01:00
} else if (msg.text === Menu.ASSISTENZA) {
this.menuAssistenza(msg)
2020-01-03 22:02:18 +01:00
} else if (msg.text === Menu.INFO) {
this.menuInformazioni(msg)
2020-01-03 22:02:18 +01:00
} else if (msg.text === Menu.EXIT_TELEGRAM) {
this.menuExitToTelegram(msg)
} else {
this.msgScegliMenu(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) {
2020-01-03 22:02:18 +01:00
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 (numpersone > 0) {
mystr += `Persone che hai invitato (${numpersone}):\n`;
let index = 1;
dashboard.downline.forEach((user) => {
2020-01-03 22:02:18 +01:00
mystr += emoji.get('star-struck') + ` ${index}°: ${user.username} (${user.name} ${user.surname})\n`;
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);
}
}
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.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: ...';
this.sendMsg(msg.chat.id, mystr);
}
async menuAssistenza(msg) {
2020-01-03 22:02:18 +01:00
const mystr = 'Per contattarci usa la chat di gruppo al seguente link: ....';
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);
}
2020-01-03 22:02:18 +01:00
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
2020-01-03 22:02:18 +01:00
const user = await User.findByUsername(this.idapp, rec.username_bo);
if (!user) {
this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND)
} else {
2020-01-03 22:02:18 +01:00
rec.user = user;
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);
2020-01-03 22:02:18 +01:00
const user = await User.findByUsername(this.idapp, rec.username_bo);
const code = msg.text.toString().trim();
2020-01-03 22:02:18 +01:00
let telegcode = 0;
if (user) {
telegcode = user.profile.teleg_checkcode.toString();
} else {
this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND);
return
}
if (msg.text.length < 7) {
if (rec) {
2020-01-03 22:02:18 +01:00
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 {
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);
2020-01-03 22:02:18 +01:00
let status = this.getstatusInMemory(msg);
if (status !== Status.VERIFIED)
return
}
status = this.getstatusInMemory(msg);
if (status === Status.WAITFOR_USERNAME_BO) {
2020-01-03 22:02:18 +01:00
await this.setUsernameBo(msg)
} else if (status === Status.WAITFOR_VERIFY_CODE) {
2020-01-03 22:02:18 +01:00
await this.setVerifyCode(msg)
} else if (status === Status.NONE) {
2020-01-03 22:02:18 +01:00
await this.start(msg);
} else if (status === Status.VERIFIED) {
// Check Menu
2020-01-03 22:02:18 +01:00
await 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);
}
2020-01-03 22:02:18 +01:00
if (rec) {
rec.user = user;
2020-01-03 22:02:18 +01:00
rec.username_bo = user.username_bo
}
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
}
});
}
2020-01-03 22:02:18 +01:00
msgScegliMenu(msg) {
this.bot.sendMessage(msg.from.id, txt.MSG_SCEGLI_MENU, {
"reply_markup": {
"keyboard": MenuStandard
}
});
}
}
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) {
const rec = arrTelegram.find((rec) => rec.idapp === idapp);
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 });
});
}
}