Files
freeplanet_serverside/src/server/telegram/telegrambot.js
Paolo Arena eccb5bbb57 - Nuovi Passi da completare: Leggere le Linee Guida e accettare le condizioni
- Aggiunti i Video e confermare di averli visti
 - In "La tua Lavagna" sono stati aggiunti come requisiti: (Accetto le Linee Guida e Vedo il Video di AYNI)
 - Aggiunto bottone "Invita Persone": apre la pagina dove c'è il messaggio da inviare alle persone.
 - La nuova pagina di registrazione https://test.gifteconomy.app/signup/paoloar77, comprende ora il testo delle Linee Guida + i Video, ed in fondo i campi per registrarsi.
2020-02-07 22:08:46 +01:00

941 lines
27 KiB
JavaScript

const tools = require('../tools/general');
const appTelegram = ['7'];
const appTelegramFinti = ['2'];
const appTelegramDest = ['7'];
const printf = require('util').format;
const { User } = require('../models/user');
const { CalZoom } = require('../models/calzoom');
const shared_consts = require('../tools/shared_nodejs');
const emoji = require('node-emoji');
const i18n = require("i18n");
const Benvenuto = emoji.get('heartbeat') + emoji.get('heartbeat') + emoji.get('heartbeat') + ' Benvenuto!';
const emo = {
STARS: emoji.get('stars'),
FIRE: emoji.get('fire'),
TV: emoji.get('tv'),
NEWSPAPER: emoji.get('newspaper'),
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'),
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'),
ROBOT_FACE: emoji.get('robot_face'),
ADMIN: emoji.get('information_desk_person'),
};
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',
ZOOM: emoji.get('information_source') + ' Zoom (Conferenze)',
INFO: emoji.get('information_source') + ' Informazioni',
ASSISTENZA: emoji.get('open_hands') + ' Chat e Assistenza',
ADMIN: emoji.get('information_desk_person') + ' Admin',
ALTRO: emoji.get('newspaper') + ' Altro',
MSGATUTTI: emoji.get('incoming_envelope') + ' Invia a TUTTI',
MSGSTAFF: emoji.get('incoming_envelope') + ' Invia a STAFF',
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.ZOOM, Menu.ASSISTENZA]];
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], ['', '']];
const MenuYes = [[Menu.MSGSTAFF, 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: '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 (20 caratteri massimo)',
MSG_ERRORE_USERNAME_NOT_FOUND: 'Attenzione! Username o email non trovata in archivio.\nVerifica che sia corretta e riscrivila nuovamente.',
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: 'Copia il codice di Autenticazione che troverai visualizzato sul sito %s, ed incollalo qui sotto',
MSG_ERR_VERIFY_CODE: 'Codice di Verifica Errato! Controlla sul sito %s e riscrivi il nuovo codice di 6 cifre.',
MSG_VERIFY_OK: emoji.get('grinning') + ' Benvenuto %s! Sono AYNI BOT, il tuo assistente virtuale.\n' +
'Clicca nei menu qui sotto, per accedere alle mie funzioni.',
// ' - In "La tua Lavagna" puoi controllare se hai completato la lista dei requisiti per entrare in programmazione Bigliettera.\n' +
// ' - in "Zoom (Conferenze) troverai le date dei prossimi Zoom da condividere con i tuoi invitati.\n' +
// ' - in "Link da condividere" trovi i link ',
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 !',
};
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}`;
const ind_order = mylocalsconf.user.ind_order;
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})`, ind_order, 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, emo.ROBOT_FACE + '[BOT-STAFF]' + emo.ADMIN + ': ' + text)
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) {
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 if (msg.text === Menu.ZOOM) {
await this.menuZoom(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.MSGSTAFF) {
await this.menumsgStaff(msg)
} else if (msg.text === Menu.INDIETRO) {
await this.msgScegliMenu(msg);
} 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
}
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, rec.user.aportador_solidario_name_surname);
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 + ' (' + rec.user.username + ') ' + emo.DIZZY + '\n\n';
mystr += tools.get__('INFO_LA_MIA_LAVAGNA', msg);
mystr += '\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.PENCIL, tools.isBitActive(rec.user.profile.saw_and_accepted, shared_consts.Accepted.CHECK_READ_GUIDELINES)) + tools.get__('LINEE_GUIDA', msg);
mystr += '\n' + '\n' + this.getsymb(emo.TV, tools.isBitActive(rec.user.profile.saw_and_accepted, shared_consts.Accepted.CHECK_SEE_VIDEO_PRINCIPI)) + tools.get__('VIDEO_INTRO', 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 = 2;
mystr += '\n' + '\n' + this.getsymb(emo.INVITATI, numpersone >= 2, numpersone, numpersone, numpersone >= 3) + tools.get__('INVITATI', msg) + '\n';
if (numpersone > 0) {
let index = 1;
dashboard.downline.forEach((user) => {
mystr += emoji.get('star-struck') + ` ${index}°: ${user.name} ${user.surname} (${user.username})\n`;
index++;
});
}
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++;
});
}
}
mystr += '\n' + printf(tools.get__('INFO_LAVAGNA_SITO', msg), tools.getHostByIdApp(this.idapp));
}
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);
}
}
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 menuZoom(msg) {
let mystr = '';
const listazoom = await CalZoom.findAllIdApp(this.idapp);
const nextzoom = await CalZoom.getNextZoom(this.idapp);
mystr += emo.STARS + tools.get__('ZOOM_CONFERENCE') + emo.STARS + '\n\n';
let index = 1;
listazoom.forEach((evento) => {
let iniziata = false;
if (nextzoom)
iniziata = (nextzoom._id.toString() === evento._id.toString());
if (iniziata) {
mystr += emo.CHECK_VERDE + ' QUESTA CONFERENZA E\' INIZIATA! ' + 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) {
if (iniziata) {
mystr += emo.FIRE + 'CLICCA QUI PER ENTRARE ! ' + emo.FIRE + '\n';
mystr += tools.getlinkzoom(evento.id_conf_zoom) + '\n\n';
}
}
index++;
});
if (!nextzoom && index > 1) {
mystr += "LINK ZOOM DA CONDIVIDERE :\n" + tools.getlinkzoom(listazoom[0].id_conf_zoom) + '\n\n';
}
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;
rec.msgall_staff = false;
await this.sendMsg(msg.chat.id, mystr, MenuAdmin);
}
}
async menumsgStaff(msg) {
const rec = this.getRecInMem(msg);
if (rec.user) {
const mystr = 'Scrivi qui un Messaggio da inviare allo STAFF:';
rec.msgall_status = StatusMSGALL.ASK;
rec.msgall_staff = true;
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);
if (msg.text === undefined)
return false;
console.log('msg.text', msg.text);
const text = msg.text;
if (text.length < 20) {
if (rec) {
rec.username_bo = text.trim();
// Check if username exist
const user = await User.findByUsername(this.idapp, rec.username_bo);
if (!user) {
rec.username_bo = text.toLowerCase().trim();
const user = await User.findByEmail(this.idapp, rec.username_bo);
if (!user) {
await this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND);
rec.username_bo = '';
}
} 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, printf(txt.MSG_VERIFY_CODE, tools.getHostByIdApp(this.idapp)))
}
}
} 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, printf(txt.MSG_ERR_VERIFY_CODE, tools.getHostByIdApp(this.idapp)));
} 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, solostaff) {
if (texttosend.length < 3) {
} else {
const usersall = await
User.getUsersTelegALL(rec.user.idapp);
let nummsgsent = 0;
if (usersall) {
for (const rec of usersall) {
let invia = true;
if (solostaff) {
invia = User.isManager(rec.perm)
}
if (invia) {
await this.sendMsg(rec.profile.teleg_id, texttosend);
nummsgsent++;
tools.snooze(300)
}
// ++Todo: SLEEP ??? sleep(0.03)
}
}
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, rec.msgall_staff)
} 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;
let achi = "TUTTI";
if (rec.msgall_staff)
achi = "STAFF";
const domanda = 'Confermi d\'Inviare questo messaggio a ' + achi + ' ?\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, 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))));
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.isAdminByIdTeleg(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) {
// ****************************
if (appTelegramFinti.includes(idapp)) {
const ind = appTelegramFinti.indexOf(idapp);
if (ind >= 0)
idapp = appTelegramDest[ind]; // Invia
}
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 });
});
}
}
}