Files
freeplanet_serverside/src/server/telegram/telegrambot.js
2025-01-12 21:29:05 +01:00

4744 lines
161 KiB
JavaScript
Executable File
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const tools = require('../tools/general');
const appTelegram = [tools.FREEPLANET, tools.RISO];
const appTelegram_TEST = [tools.FREEPLANET, tools.RISO];
//const appTelegram_DEVELOP = [tools.RISO];
const appTelegram_DEVELOP = [tools.PIUCHEBUONO];
const appTelegramFinti = ['2', tools.CNM];
const appTelegramDest = [tools.FREEPLANET, tools.FREEPLANET];
const appTeleg_BotOnGroup = [tools.IDAPP_BOTONGROUP];
//PIPPO
const printf = require('util').format;
const { User, FuncUsers } = require('../models/user');
const { MyGroup } = require('../models/mygroup');
const { Circuit } = require('../models/circuit');
const { CalZoom } = require('../models/calzoom');
const { MyBot } = require('../models/bot');
const shared_consts = require('../tools/shared_nodejs');
const sharp = require('sharp');
const axios = require('axios');
const server_constants = require('../tools/server_constants');
// const {ListaIngresso} = require('../models/listaingresso');
const { MsgTemplate } = require('../models/msg_template');
const globalTables = require('../tools/globalTables');
const emoji = require('node-emoji');
const i18n = require('i18n');
let url = process.env.URL || 'https://<PUBLIC-URL>';
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'),
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 = {
OK: ['si', 'ok'],
CUORE: ['❤️', '💚️', '💜'],
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'],
PREGO: ['prego', 'Prego ! 💋💋💋'],
GRAZIE: [
'grazie ainy',
'grazie',
'grazie mille',
'graziee',
'grazie ❤',
'grazie❤',
'grazie 😘',
'grazie😘'],
PRINCIPE_AZZURRO: ['principe azzurro'],
START_INV: ['/start inv'],
COSE_COVID: [
'cos\'è il covid',
'cosa è il covid',
],
COVID: [
'covid',
],
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'],
TROVAMI_UN_UOMO_DONNA: [
'trovami un uomo',
'trovami una donna',
'esiste una donna per me',
'esiste un uomo per me'],
PAROLACCE: [
'stronz',
'fanculo',
'fottiti',
'cagare',
'ammazzat',
'muori',
'cretino',
'stupido'],
COME_SI_CHIAMA: ['come si chiama'],
PROSSIMO_ZOOM: [
'prossimo zoom',
'fare lo zoom',
'gli zoom',
'conferenz',
'zoom'],
LAVAGNA: ['lavagna', 'Lavagna', 'LAVAGNA'],
SEI_LIBERO_DI_RESPIRARE: ['sei libero di respirare'],
SEI_LIBERO: ['sei liber', 'sei sposat', 'sei fidanzat', 'sei single'],
AIUTO: [
'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'],
DOVE_VUOI_VIVERE: ['dove vuoi vivere'],
MA_ALLORA: ['ma allora'],
};
const 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;
}
}
const Menu = {
LANG_IT: emoji.get('flag-it') + ' Italiano',
LANG_EN: emoji.get('flag-gb') + ' English',
LANG_ES: emoji.get('flag-es') + ' Español',
LANG_FR: emoji.get('flag-fr') + ' Français',
LANG_SI: emoji.get('flag-si') + ' Slovenski',
LANG_PT: emoji.get('flag-pt') + ' Português',
LANG: emoji.get('globe_with_meridians') + ' Language',
CHAT_PERSONALE: emoji.get('female-office-worker') + emoji.get('computer'),
EXIT_TELEGRAM: 'exittotelegram',
MSG_TO_USER: 'sendmsgto',
ADMIN: emoji.get('information_desk_person') + ' Admin',
AIUTO: '🔮 Help',
ALTRO: emoji.get('newspaper') + ' Altro',
SETPICPROFILE: '🖼 SetPicProfile',
RESETPWD: '🔑 SetResetPwd',
// 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',
// NESSUN_IMBARCO_7REQ: emoji.get('incoming_envelope') + 'No Imbarco (7 Req)',
MSG_SI_INVITATI_NO_7REQ_INVITATI: emoji.get('incoming_envelope') +
'Inv e NO 7 Req',
MSGSTAFF: emoji.get('incoming_envelope') + ' Invia a STAFF',
MSGAPPARTIENE_CIRCUITI_RIS: 'Invia a Utenti dei Circuiti RIS',
MSGPAOLO: emoji.get('incoming_envelope') + ' Invia a PAOLO',
RESTART_SRV: emoji.get('incoming_envelope') + 'Restart-NodeJs',
REBOOT_SRV: emoji.get('incoming_envelope') + 'Reboot-VPS!',
EXECSH: emoji.get('incoming_envelope') + 'ExecSH',
LOG_SRV: '🖥Logserver.sh',
MSGATUTTI: emoji.get('incoming_envelope') + ' Invia a TUTTI',
it: {
ACCEDI: emo.PERSON + ' Accedi',
LAVAGNA: emoji.get('om_symbol') + ' 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') + ' Le Chat',
INDIETRO: emoji.get('back') + ' Indietro',
SI: emoji.get('thumbsup') + ' SI',
NO: emoji.get('thumbsdown') + ' NO',
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Esci dalla Conversazione',
NUOVOSITO: '',
},
es: {
ACCEDI: emo.PERSON + ' Entra',
LAVAGNA: emoji.get('om_symbol') + ' Tablero',
LINK_CONDIVIDERE: emoji.get('link') + ' Enlaces para compartir',
ZOOM: emoji.get('information_source') + ' Zoom (Conferencias)',
INFO: emoji.get('information_source') + ' Información',
ASSISTENZA: emoji.get('open_hands') + ' Chats',
INDIETRO: emoji.get('back') + ' Volver',
SI: emoji.get('thumbsup') + ' SÍ',
NO: emoji.get('thumbsdown') + ' NO',
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Salir de la conversación',
},
fr: {
ACCEDI: emo.PERSON + ' Entrez',
LAVAGNA: emoji.get('om_symbol') + ' Tableau de bord',
LINK_CONDIVIDERE: emoji.get('link') + ' Liens à partager',
ZOOM: emoji.get('information_source') + ' Zoom (Conférences)',
INFO: emoji.get('information_source') + ' Informations',
ASSISTENZA: emoji.get('open_hands') + ' Les chats',
INDIETRO: emoji.get('back') + ' Retour',
SI: emoji.get('thumbsup') + ' OUI',
NO: emoji.get('thumbsdown') + ' NON',
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Quitter la conversation',
},
si: {
ACCEDI: emo.PERSON + ' Prijava',
LAVAGNA: emoji.get('om_symbol') + ' Tabla',
LINK_CONDIVIDERE: emoji.get('link') + ' Link za vpis oseb',
ZOOM: emoji.get('information_source') + ' Zoom (Konference)',
INFO: emoji.get('information_source') + ' Informacije',
ASSISTENZA: emoji.get('open_hands') + ' jev klepet',
INDIETRO: emoji.get('back') + ' Nazaj',
SI: emoji.get('thumbsup') + ' DA',
NO: emoji.get('thumbsdown') + ' NE',
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Zaprite pogovor',
},
pt: {
ACCEDI: emo.PERSON + ' Entre',
LAVAGNA: emoji.get('om_symbol') + ' Tablero',
LINK_CONDIVIDERE: emoji.get('link') + ' Links para compartilhar',
ZOOM: emoji.get('information_source') + ' Zoom (Conferências)',
INFO: emoji.get('information_source') + ' Informações',
ASSISTENZA: emoji.get('open_hands') + ' Chats',
INDIETRO: emoji.get('back') + ' Voltar',
SI: emoji.get('thumbsup') + ' SIM',
NO: emoji.get('thumbsdown') + ' NÃO',
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Sair da Conversa',
},
enUs: {
ACCEDI: emo.PERSON + ' Enter',
LAVAGNA: emoji.get('om_symbol') + ' DashBoard',
LINK_CONDIVIDERE: emoji.get('link') + ' Link to Share',
ZOOM: emoji.get('information_source') + ' Zoom (Conference)',
INFO: emoji.get('information_source') + ' Info',
ASSISTENZA: emoji.get('open_hands') + ' Chats',
INDIETRO: emoji.get('back') + ' Back',
SI: emoji.get('thumbsup') + ' YES',
NO: emoji.get('thumbsdown') + ' NO',
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Exit to the Conversation',
},
};
const CONTA_SOLO = 'contasolo';
const RICEVI_EMAIL = 'riceviemail';
const NOME_COGNOME = 'nomecognome';
const CHEDI_SE_IMBARCARTI = 'chiedi_se_imbarcarti';
const InlineCmd = {
VOGLIO_IMBARCARMI: 'w_imb',
NON_VOGLIO_IMBARCARMI: 'nw_imb',
};
const InlineZoomConferma = {
CONFERMA_ZOOM_PRESENZA: 'conf_pres',
NON_CONFERMA_ZOOM_PRESENZA: 'nonconf_pres',
};
const InlineConferma = {
RISPOSTA_SI: 'r_s',
RISPOSTA_NO: 'r_n',
};
const SendMsgCmd = [
CONTA_SOLO,
RICEVI_EMAIL,
NOME_COGNOME,
CHEDI_SE_IMBARCARTI];
// const MenuNoLogin = {
// it: { menu: [[Menu.LANG], [Menu.it.ASSISTENZA]] },
// es: { menu: [[Menu.LANG], [Menu.es.ASSISTENZA]] },
// fr: { menu: [[Menu.LANG], [Menu.fr.ASSISTENZA]] },
// si: { menu: [[Menu.LANG], [Menu.si.ASSISTENZA]] },
// pt: { menu: [[Menu.LANG], [Menu.pt.ASSISTENZA]] },
// enUs: { menu: [[Menu.LANG], [Menu.enUs.ASSISTENZA]] },
// };
// const MenuStandard = {
// it: { menu: [[Menu.it.LAVAGNA, Menu.it.LINK_CONDIVIDERE], [Menu.it.ZOOM, Menu.it.ASSISTENZA], [Menu.LANG]] },
// };
const MenuLang = {
it: {
menu: [
[Menu.LANG_IT, Menu.LANG_EN],
[Menu.LANG_ES, Menu.LANG_FR],
[Menu.LANG_SI, Menu.LANG_PT, Menu.it.INDIETRO]],
},
};
const MenuYesNo = {
it: { menu: [[Menu.it.SI, Menu.it.NO]] },
es: { menu: [[Menu.es.SI, Menu.es.NO]] },
fr: { menu: [[Menu.fr.SI, Menu.fr.NO]] },
si: { menu: [[Menu.si.SI, Menu.si.NO]] },
pt: { menu: [[Menu.pt.SI, Menu.pt.NO]] },
enUs: { menu: [[Menu.enUs.SI, Menu.enUs.NO]] },
};
const MenuAdmin = {
it: {
menu: [
[Menu.RESTART_SRV + ' 6711', Menu.LOG_SRV + ' 6711'],
[Menu.REBOOT_SRV + ' 6711', Menu.it.INDIETRO]],
},
};
const MenuSend = {
it: {
menu: [
[CONTA_SOLO, RICEVI_EMAIL, NOME_COGNOME],
[CHEDI_SE_IMBARCARTI, Menu.it.INDIETRO]],
},
};
const MenuChat = {
it: { menu: [[Menu.it.ESCI_DA_CHAT, Menu.it.INDIETRO]] },
es: { menu: [[Menu.es.ESCI_DA_CHAT, Menu.es.INDIETRO]] },
fr: { menu: [[Menu.fr.ESCI_DA_CHAT, Menu.fr.INDIETRO]] },
si: { menu: [[Menu.si.ESCI_DA_CHAT, Menu.si.INDIETRO]] },
pt: { menu: [[Menu.pt.ESCI_DA_CHAT, Menu.pt.INDIETRO]] },
enUs: { menu: [[Menu.enUs.ESCI_DA_CHAT, Menu.enUs.INDIETRO]] },
};
const Sex = {
MALE: 1,
FEMALE: -1,
};
const Status = {
EXIT: -5,
NONE: 0,
VERIFIED: 1,
WAITFOR_USERNAME_TELEGRAM: 101,
WAITFOR_USERNAME_INVITANTE: 104,
SET_USERNAME_INVITANTE: 105,
CLICK_LINK_REG: 106,
WAITFOR_RISPOSTA: 110,
};
const Cmd = {
VALIDATE_REGISTRATION: 1,
};
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,
NESSUN_IMBARCO_7REQ: 8,
PAOLO: 9,
DOMANDA: 10,
RISPOSTA: 11,
APPARTIENE_CIRCUITO_RIS: 20,
};
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: 'Scrivete nel messaggio l\'username (SENZA SPAZI) o la email con cui vi siete registrati sul sito di %s:',
MSG_ASK_USERNAME_INVITANTE: 'Scrivi nel messaggio <b>l\'USERNAME TELEGRAM</b> di chi ti ha INVITATO',
MSG_NEW_REG: '<br><br>⁉️🙈 Per aiuto scrivi sulla <a href="https://t.me/riso_gruppo">Chat RISO</a><br>oppure direttamente a Paolo (@surya1977) ☀️.',
MSG_ERRORE_INVITANTE_NOT_FOUND: 'L\'username dell\'invitante appena digitato non sembra essere corretto! Ti ricordo che dev\'essere l\'username con cui si è registrato su %s',
MSG_ERRORE_USERNAME: 'Attenzione! Devi inserire solo lo username (40 caratteri massimo)',
MSG_ERRORE_USERNAME_NOT_FOUND: 'Per Completare la Verifica Telegram BOT, dovete ora scrivere qui sotto nel messaggio l\'Username (senza spazi) OPPURE la email con cui vi siete registrati sul sito',
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:\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_SET_PICPROFILE: '🖼 Abbiamo impostato <b>la tua foto del Profilo</b>, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
MSG_RESETPWD: 'Clicca qui per impostare una nuova password per accedere alla APP:',
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)\nInvitato da %s',
MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ %s si sta registrando alla App %d e ti chiede di poter entrare. Confermi di conoscerla ?',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_FRIENDS_NOT_ACCEPTED_CONFIRMED: '🚫 Hai rifiutato la richiesta di Amicizia di %s !',
MSG_HANDSHAKE_NOT_ACCEPTED_CONFIRMED: '🚫 Hai rifiutato la richiesta di Stretta di mano di %s !',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ La tua registrazione a %s è stata accettata da %s!\n' +
'Vai sulla App oppure clicca qui per entrare\n👉🏻 %s',
MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!',
MSG_APORTADOR_DEST_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.<br>Contattalo per farti abilitare !',
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !',
MSG_ISCRITTO_CONACREIS: emo.FIRE + '[%s] Si è appena Iscritto al Conacreis "%s"',
MSG_ISCRITTO_ARCADEI: emo.FIRE + '[%s] Si è appena Iscritto ad Arcadei "%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',
MSG_SET_USERNAME_TELEGRAM: '[Prima di continuare con la registrazione in RISO.APP]\n' +
'Segui questi passi per <b>IMPOSTARE UN USERNAME IN TELEGRAM</b>: \n\n' +
'1. premi sull\'icona con <b>3 linee orizzontali</b>, in alto a sinistra (sull\'iPhone si chiama "Impostazioni").\n' +
'premi il tasto INDIETRO del cellulare (si chiuderà questa chat).\n\n' +
'2. Seleziona la voce <b>IMPOSTAZIONI</b> dalla lista.\n\n' +
'3.Premi su <b>USERNAME</b> nella sezione account.\n\n' +
'4. Digita un username (o nome utente) qualsiasi a tua scelta, se è già usato aggiungi dei numeri.\n\n' +
'5. Per confermare premi sull\'icona con la spunta (V) in alto a destra.\n\n' +
'🏁 6. Infine ritorna su questa chat BOT e scrivi OK nel messaggio. \n\n' +
' Se non riesci a fare questi passaggi, clicca qui: \n' +
'👉🏻 https://www.nigiara.it/telegram/come-impostare-uno-username-su-telegram.htm ',
MSG_SIGNUP: 'Per registrarti su %s:',
};
const txt_es = {
MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Elija un elemento del menú:' +
emoji.get('dizzy'),
MSG_ASK_USERNAME_BO: 'Escriba en el mensaje el nombre de usuario o el correo electrónico con el que se registró en el sitio de %s:',
MSG_ERRORE_USERNAME: '¡Atención! Debes introducir sólo el nombre de usuario (40 caracteres como máximo)',
MSG_ERRORE_USERNAME_NOT_FOUND: 'Para completar la verificación del telegrama BOT, ahora debe escribir en el mensaje el nombre de usuario o el correo electrónico con el que se registró en el sitio.:',
MSG_ERRORE_USERNAME_ANNULLA: 'Inserción cancelada. Inténtalo de nuevo.',
MSG_OPERAZ_ANNULLATA: 'Operación cancelada',
MSG_ERRORE_VERIFY_CODE_MAXLEN: '¡Atención! Sólo tienes que introducir el código de 6 dígitos',
MSG_VERIFY_CODE: '1. Ahora, de vuelta en el sitio web:\n%s\n2. Copie el código de autenticación (6 dígitos) que encontrará escrito en la parte superior de la página\n3. Escríbelo (o pégalo) abajo como un mensaje:',
MSG_ERR_VERIFY_CODE: 'Código de verificación incorrecto!' +
emo.EXCLAMATION_MARK +
'\nComprueba en el sitio %s y reescribe el nuevo código de 6 dígitos.',
MSG_SET_PICPROFILE: '🖼 Abbiamo impostato <b>la tua foto del Profilo</b>, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
MSG_ERR_UNKNOWN_VERIFY_CODE: 'Error al guardar en el servidor. Inténtalo de nuevo más tarde.',
MSG_EXIT_TELEGRAM: 'La cuenta ha sido desconectada de Telegram BOT.',
MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
' Acaba de registrarse "%s (n. %s)"\n(Invitado de %s)',
MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ %s Abilita Nuova Registrazione:',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Ammesso correttamente da %s!',
MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!',
MSG_APORTADOR_DEST_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.<br>Contattalo per farti abilitare !',
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
'🚫 %s Non è stato Ammesso !',
MSG_MSG_SENT: emoji.get('envelope') + ' Mensajes enviados !',
MSG_MSG_TOSENT: emoji.get('envelope') + ' Mensajes a enviar',
MSG_MSG_INCORSO: emoji.get('envelope') +
' mensajes en progreso... Enviado actualmente',
};
const txt_fr = {
MSG_SCEGLI_MENU: emoji.get('dizzy') + 'Choisissez un élément de menu:' +
emoji.get('dizzy'),
MSG_ASK_USERNAME_BO: 'Écrivez dans le message l\'username ou l\'e-mail avec lequel vous vous êtes enregistré sur le site de %s: ',
MSG_ERRORE_USERNAME: 'Attention! Vous devez insérer seulement lusername (40 caractères maximum)',
MSG_ERRORE_USERNAME_NOT_FOUND: 'Pour Compléter la Vérification Telegram BOT, vous devez maintenant écrire dans le message ci-dessous l\'Username ou l\'adresse e-mail avec lequel vous vous êtes inscrit sur le site: ',
MSG_ERRORE_USERNAME_ANNULLA: 'Saisie des données Annullée.Essayez à nouveau ',
MSG_OPERAZ_ANNULLATA: 'Opération Annullée',
MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attention! Vous devez insérer seulement le code à 6 chiffres',
MSG_VERIFY_CODE: '1. Ᾱ présent retournez sur le site:\n%s\n2. Copiez le Code dAuthentification (de 6 chiffres) che vous trouverez écrit en haut \n3. Ecrivez-le (ou copiez-le) ci-dessous comme message:',
MSG_ERR_VERIFY_CODE: ' Code de vérification incorrect!' +
emo.EXCLAMATION_MARK +
'\nControllez sur le site %s et réécrivez le nouveau code à 6 chiffres.',
MSG_SET_PICPROFILE: '🖼 Abbiamo impostato <b>la tua foto del Profilo</b>, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
MSG_ERR_UNKNOWN_VERIFY_CODE: 'Erreur lors de l\'enregistrement sur le serveur. Retentez plus tard',
MSG_EXIT_TELEGRAM: 'L\'account a été déconnecté de Telegram BOT.',
MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
' Vous venez à peine de vous inscrire "%s (n. %s) %s',
MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ %s Abilita Nuova Registrazione:',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Ammesso correttamente da %s!',
MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!',
MSG_APORTADOR_DEST_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.<br>Contattalo per farti abilitare !',
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
'🚫 %s Non è stato Ammesso !',
MSG_MSG_SENT: emoji.get('envelope') + ' Messages envoyés !',
MSG_MSG_TOSENT: emoji.get('envelope') + ' Messages à envoyer',
MSG_MSG_INCORSO: emoji.get('envelope') +
' messages en cours... Actuellement envoyé',
};
const txt_si = {
MSG_SCEGLI_MENU: emoji.get('dizzy') + 'Izbirni meni:' + emoji.get('dizzy'),
MSG_ASK_USERNAME_BO: 'Vpiši svoje uporabniško ime in e-naslov s katerimi si se registriral na spletni strani %s: ',
MSG_ERRORE_USERNAME: 'Pozor! Vpiši samo uporabniško ime (40 znakov) maksimalno',
MSG_ERRORE_USERNAME_NOT_FOUND: 'Ponovno preverite telegram BOT Uporabniško ime ali e-poštno sporočilo, s katerim ste registrirali na spletni strani: ',
MSG_ERRORE_USERNAME_ANNULLA: 'Preklic. Poskusi ponovno ',
MSG_OPERAZ_ANNULLATA: 'Operacija preklicana',
MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Pozor! Vstavi D mestno kodo',
MSG_VERIFY_CODE: '1. Vrni se na spletno strani: \n%s\n2. Kopiraj kodo Authenticazione (6 mestno) ki jo najdeš zgoraj zapisano\n3. Napiši (ali prilepi) tu spodaj kot sporočilo: ',
MSG_ERR_VERIFY_CODE: 'Napačna koda za preverjanje!' + emo.EXCLAMATION_MARK +
'\nPreveri na strani %s in ponovno napiši 6 mestno kodo.',
MSG_SET_PICPROFILE: '🖼 Abbiamo impostato <b>la tua foto del Profilo</b>, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
MSG_ERR_UNKNOWN_VERIFY_CODE: 'Napaka strežnika.Poskusi kasneje ',
MSG_EXIT_TELEGRAM: 'Račun se nahaja v programu Telegram BOT.',
MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
'Registracija registracije %s (n. %s)\n(povabil ga %s)',
MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ %s Abilita Nuova Registrazione:',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Ammesso correttamente da %s!',
MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!',
MSG_APORTADOR_DEST_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.<br>Contattalo per farti abilitare !',
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
'🚫 %s Non è stato Ammesso !',
};
const txt_en = {
MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Choose a menu item:' +
emoji.get('dizzy'),
MSG_ASK_USERNAME_BO: 'Write in the message the username or email with which you registered on the site of %s:',
MSG_ERRORE_USERNAME: 'Attention! You must enter only the username (40 characters maximum)',
MSG_ERRORE_USERNAME_NOT_FOUND: 'To complete the Telegram BOT Verification, you must now write below in the message the Username OR the email with which you registered on the website:',
MSG_ERRORE_USERNAME_ANNULLA: 'Insertion Cancelled. Try again',
MSG_OPERAZ_ANNULLATA: 'Operation Cancelled',
MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attention! You only need to enter the 6-digit code',
MSG_VERIFY_CODE: '1. Now return to the website: %s\n' +
'2. Copy the Authentication code (of 6 digits) that you will find written at the top\n' +
'3. Write it (or paste it) below as a message:',
MSG_ERR_VERIFY_CODE: 'Incorrect Verification Code!' + emo.EXCLAMATION_MARK +
'\nCheck on the site %s and rewrite the new 6-digit code.',
MSG_SET_PICPROFILE: '🖼 Abbiamo impostato <b>la tua foto del Profilo</b>, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
MSG_ERR_UNKNOWN_VERIFY_CODE: 'Error while saving to the Server. Try again later',
MSG_EXIT_TELEGRAM: 'The account has now been disconnected from this Telegram BOT.',
MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
' He/She\'s just registered "%s (n. %s)"\n(Invited from %s)',
MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ %s Abilita Nuova Registrazione:',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Ammesso correttamente da %s!',
MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!',
MSG_APORTADOR_DEST_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.<br>Contattalo per farti abilitare !',
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
'🚫 %s Non è stato Ammesso !',
MSG_MSG_SENT: emoji.get('envelope') + ' Sent Messages !',
MSG_MSG_TOSENT: emoji.get('envelope') + ' Messages to Send',
MSG_MSG_INCORSO: emoji.get('envelope') +
' messages in progress... Currently sent',
};
const txt_pt = {
MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Escolha um item do menu:' +
emoji.get('dizzy'),
MSG_ASK_USERNAME_BO: 'Escreva na mensagem o nome de usuário ou e-mail com o qual se registrou no site de %s:',
MSG_ERRORE_USERNAME: 'Atenção! Você deve inserir apenas o nome de usuário (40 caracteres no máximo)',
MSG_ERRORE_USERNAME_NOT_FOUND: 'Para completar a Verificação do Telegrama BOT, você deve agora escrever abaixo na mensagem o Nome de Usuário OU o e-mail com o qual você se registrou no site:',
MSG_ERRORE_USERNAME_ANNULLA: 'Inserção Cancelada. Tente novamente',
MSG_OPERAZ_ANNULLATA: 'Operação Cancelada',
MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Atenção! Você só precisa digitar o código de 6 dígitos',
MSG_VERIFY_CODE: '1. Agora de volta ao site:\n%s\n2. Copie o código de autenticação (6 dígitos) que você encontrará escrito na parte superior da página\n3. Escreva-o (ou cole-o) abaixo como uma mensagem:',
MSG_ERR_VERIFY_CODE: 'Código de Verificação Incorrecto!' +
emo.EXCLAMATION_MARK +
'\nCódigo de Verificação ErradoCheque no local %s e reescreva o novo código de 6 dígitos.',
MSG_SET_PICPROFILE: '🖼 Abbiamo impostato <b>la tua foto del Profilo</b>, copiandola dalla foto profilo di Telegram. Potrai comunque cambiarla dalla APP (%s)',
MSG_ERR_UNKNOWN_VERIFY_CODE: 'Erro ao salvar no Servidor. Tente novamente mais tarde.',
MSG_EXIT_TELEGRAM: 'A conta foi agora desconectada deste Telegrama BOT.',
MSG_APORTADOR_USER_REGISTERED: emo.FIRE +
' Acabou de se registar "%s (n. %s)"\n(Convidado por %s)',
MSG_APORTADOR_ASK_CONFIRM: '🆕💥 🧍‍♂️ %s Abilita Nuova Registrazione:',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
MSG_APORTADOR_CONFIRMED: '✅ %s è stato Ammesso correttamente (da %s)!',
MSG_APORTADOR_DEST_CONFIRMED: '✅ Sei stato Ammesso correttamente da %s!',
MSG_GROUP_CONFIRMED: '✅ Sei stato Aggiunto sul Gruppo %s!',
MSG_APORTADOR_DEST_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.<br>Contattalo per farti abilitare !',
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
'🚫 %s Non è stato Ammesso !',
MSG_MSG_SENT: emoji.get('envelope') + ' Mensagens Enviadas !',
MSG_MSG_TOSENT: emoji.get('envelope') + ' Mensagens a enviar',
MSG_MSG_INCORSO: emoji.get('envelope') +
' mensagens em progresso... Actualmente enviado',
};
const TelegramBot = require('node-telegram-bot-api');
const ADMIN_IDTELEGRAM_TEST = 5356627050; // 5022837609; //Surya Arena
const MyTelegramBot = {
ADMIN_IDTELEGRAM_SERVER: '12429864', //Paolo
ADMIN_USERNAME_TELEGRAM: 'surya1977', //Paolo
ADMIN_USER_NAME_SERVER: 'Paolo',
phase: {
REGISTRATION: 1,
ISCRIZIONE_CONACREIS: 2,
ISCRIZIONE_ARCADEI: 4,
},
getAppTelegram: function () {
if (process.env.appTelegram) {
arrTeleg = JSON.parse(process.env.appTelegram);
} else {
arrTeleg = appTelegram;
}
if (process.env.NODE_ENV === 'development') {
arrTeleg = MyTelegramBot.getAppTelegramDevelop();
} else if (process.env.NODE_ENV === 'test') {
arrTeleg = MyTelegramBot.getAppTelegramTest();
} else {
const arrTelegFromSite = tools.getArrTelegramFromSite();
if (arrTelegFromSite.length > 0) {
arrTeleg = arrTelegFromSite;
}
}
return arrTeleg;
},
getAppTelegramTest: function () {
if (process.env.appTelegram_TEST) {
return JSON.parse(process.env.appTelegram_TEST);
} else {
return appTelegram_TEST;
}
},
getAppTelegramDevelop: function () {
if (process.env.appTelegram_DEVELOP) {
return JSON.parse(process.env.appTelegram_DEVELOP);
} else {
return appTelegram_DEVELOP;
}
},
local_sendMsgTelegramByIdTelegram: async function (idapp, idtelegram, text,
message_id, chat_id, ripr_menuPrec,
MyForm = null, img = '') {
if (!idtelegram)
return { text: '' };
const cl = getclTelegByidapp(idapp);
if (cl && idtelegram) {
return await cl.sendMsg(idtelegram, text, null, MyForm, message_id,
chat_id, ripr_menuPrec, img, { idapp });
}
return { text: '' };
},
deleteRecInMemByUsername: function (idapp, username_bo) {
const cl = getclTelegByidapp(idapp);
if (cl) {
cl.arrUsers = cl.arrUsers.filter(
(rec) => rec.username_bo !== username_bo);
}
},
getFormDaMostrare: function (idapp, myfunc, myuser) {
let FormDaMostrare = null;
const cl = getclTelegByidapp(idapp);
if (myfunc === shared_consts.CallFunz.ZOOM_GIA_PARTECIPATO) {
FormDaMostrare = cl.getInlineKeyboard(myuser.lang, [
{
text: 'Conferma Presenza Zoom',
// callback_data: { action: InlineZoomConferma.CONFERMA_ZOOM_PRESENZA, username: myuser.username }
callback_data: InlineZoomConferma.CONFERMA_ZOOM_PRESENZA + tools.SEP +
myuser.username,
},
{
text: 'Annulla Presenza Zoom',
// callback_data: { action: InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA, username: myuser.username }
callback_data: InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA +
tools.SEP +
myuser.username,
},
]);
}
return FormDaMostrare;
},
getclTelegByidapp: function (idapp) {
const cl = getclTelegByidapp(idapp);
return cl;
},
getCiao: function (idapp, username, lang) {
return tools.gettranslate('CIAO', lang) + ' ' + username + '!\n';
},
notifyToTelegram: async function (phase, mylocalsconf) {
try {
let userdest = mylocalsconf.user.aportador_solidario;
let langdest = mylocalsconf.user.lang;
let NameFrom = `${mylocalsconf.user.name} ${mylocalsconf.user.surname}`;
if (!mylocalsconf.user.name) {
NameFrom = `${mylocalsconf.user.username}`;
}
const index = mylocalsconf.user.index;
let aportador = '';
if (userdest) {
aportador = `${userdest}`;
NameFrom += aportador;
} else {
aportador = mylocalsconf.user.aportador_solidario_nome_completo
? mylocalsconf.user.aportador_solidario_nome_completo
: mylocalsconf.user.aportador_solidario;
}
let text = '';
if (phase === this.phase.REGISTRATION) {
if (tools.getConfSiteOptionEnabledByIdApp(mylocalsconf.idapp,
shared_consts.ConfSite.Notif_Reg_Bot_ToManagers)) {
if (userdest) {
NameFrom = await User.getNameSurnameByUsername(mylocalsconf.idapp,
userdest, true);
aportador = NameFrom ? NameFrom + ' ' + aportador : aportador;
}
const numutenti = await User.getNumUsers(mylocalsconf.idapp);
let nome = tools.getNomeCognomeEUserNameByUser(mylocalsconf.user);
text = printf(getstr(langdest, 'MSG_APORTADOR_USER_REGISTERED'), nome,
numutenti, aportador);
}
}
let addtext = '';
let rismsg = null;
if (text) {
await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp,
addtext + text, false, null);
}
} catch (e) {
console.error('Err notifyToTelegram', e);
}
},
notifyIscrizioneToTelegram: async function (phase, mylocalsconf, msg) {
try {
let langdest = mylocalsconf.iscritto.lang;
let NameFrom = `${mylocalsconf.iscritto.name} ${mylocalsconf.iscritto.surname}`;
let nomeapp = tools.getHostByIdApp(mylocalsconf.idapp);
let text = printf(getstr(langdest, msg), NameFrom, nomeapp);
let addtext = '';
await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, addtext + text);
} catch (e) {
console.error('notifyIscrizioneToTelegram', e);
}
},
askConfirmationUser: async function (idapp, myfunc, myuser, userDest = '', name = '', groupid = '', regexpire = '', groupname = '') {
try {
const cl = getclTelegByidapp(idapp);
if (!cl)
return false;
const langdest = myuser.lang;
const telegid = myuser.profile.teleg_id;
if (!userDest) {
userDest = myuser.username;
}
let userrecDest = await User.getUserShortDataByUsername(idapp, userDest);
let userId = userrecDest._id;
let title = tools.getNomeAppByIdApp(idapp);
let keyb = null;
let openUrl = '';
let domanda = '';
let msg_notifpush = '';
let send_notif = false;
let actions = [];
let tag = '';
const struserinfomsg = tools.getUserInfoMsg(idapp, myuser);
const nomeapp = myuser.idapp ? tools.getNomeAppByIdApp(myuser.idapp) : tools.getNomeAppByIdApp(idapp);
if (myfunc === shared_consts.CallFunz.REGISTRATION) {
if (telegid > 0) {
cl.setPhotoProfile(myuser, telegid, false);
const rismsg = await MsgTemplate.getMsgByLang(idapp, myuser, shared_consts.TypeMsgTemplate.MSG_BENVENUTO, myuser.lang);
const rismsg2 = await MsgTemplate.getMsgByLang(idapp, myuser, shared_consts.TypeMsgTemplate.MS_SHARE_LINK, myuser.lang);
await cl.sendMsgLog(telegid, rismsg.body);
await cl.sendMsg(telegid, rismsg2.body);
}
userDest = myuser.aportador_solidario;
let notask_verif = await User.notAsk_VerifByUsername(idapp, userDest);
let useraportador = await User.getUserShortDataByUsername(idapp, userDest);
if (useraportador && useraportador.tokenreg && (regexpire.toLowerCase() === useraportador.tokenreg.toLowerCase())) {
const nonchiedereverifica = await User.getifRegTokenIsValid(idapp, useraportador.tokenreg);
if (nonchiedereverifica)
notask_verif = true;
}
if (notask_verif) {
// Non chiedi la verifica Registrazione
await setVerifiedReg(myuser.idapp, myuser.lang, myuser.username, userDest);
} else {
msg_notifpush = getstr(langdest, 'MSG_APORTADOR_ASK_CONFIRM', myuser.username);
domanda = getstr(langdest, 'MSG_APORTADOR_ASK_CONFIRM', myuser.username, nomeapp) + '<br>' + struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅ Ammetti ' + myuser.username,
callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + userDest,
},
/*{
text: '🚫 Rifiuta ' + myuser.username,
callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + userDest,
}, */
]);
}
send_notif = true;
} else if (myfunc === shared_consts.CallFunz.RICHIESTA_GRUPPO) {
msg_notifpush = printf(getstr(langdest, 'MSG_ACCEPT_NEWENTRY_INGROUP'), name);
domanda = printf(getstr(langdest, 'MSG_ACCEPT_NEWENTRY_INGROUP'), name) + '<br>' + struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅ Accetta ' + myuser.username,
callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + groupid,
},
{
text: '🚫 Rifiuta ' + myuser.username,
callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + groupid,
},
]);
} else if (myfunc === shared_consts.CallFunz.RICHIESTA_FIDO) {
if (groupname) {
msg_notifpush = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP', locale: langdest }, groupname);
domanda = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP', locale: langdest }, groupname) + '<br>' + struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅ Abilita fiducia a ' + groupname,
callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
groupid + tools.SEP + groupname,
},
/*{
text: '🚫 Rifiuta ' + groupname,
callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
groupid + tools.SEP + groupname,
},*/
]);
send_notif = true;
} else {
msg_notifpush = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY', locale: langdest }, myuser.username, name);
domanda = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY', locale: langdest }, myuser.username, name) + '<br>' + struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅ Abilita fiducia a ' + myuser.username,
callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
groupid,
},
/*{
text: '🚫 Rifiuta ' + myuser.username,
callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
groupid,
}, */
]);
send_notif = true;
}
} else if (myfunc === shared_consts.CallFunz.RICHIESTA_CIRCUIT) {
if (groupname) {
msg_notifpush = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP_CIRC', locale: langdest }, groupname);
domanda = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP_CIRC', locale: langdest }, groupname) + '<br>' + struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅ Fai entrare a ' + groupname,
callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
groupid + tools.SEP + groupname,
},
/*{
text: '🚫 Rifiuta ' + groupname,
callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
groupid + tools.SEP + groupname,
},*/
]);
send_notif = true;
} else {
msg_notifpush = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_CIRC', locale: langdest }, myuser.username, name);
domanda = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_CIRC', locale: langdest }, myuser.username, name) + '<br>' + struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅ Fai entrare a ' + myuser.username,
callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
groupid,
},
/*{
text: '🚫 Rifiuta ' + myuser.username,
callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
groupid,
}, */
]);
send_notif = true;
}
}
// Invia Msg
if (domanda) {
const teleg_id = await User.TelegIdByUsername(idapp, userDest);
await this.local_sendMsgTelegramByIdTelegram(idapp, teleg_id, domanda, undefined, undefined, true, keyb);
}
if (send_notif && msg_notifpush) {
// SEND PUSH NOTIFICATION
await tools.sendNotificationToUser(userId, title, msg_notifpush, openUrl, '', tag, actions);
}
} catch (e) {
console.error('Error askConfirmationUser', e);
}
},
askConfirmationUserFriend: async function (idapp, myfunc, myuser, userDest = '', username = '') {
try {
const cl = getclTelegByidapp(idapp);
if (!cl)
return false;
const { SendNotif } = require('../models/sendnotif');
const langdest = myuser.lang;
let keyb = null;
let domanda = '';
let sendnotif = false;
let typedir = 0;
let typeid = 0;
let paramsObj = {};
const struserinfomsg = tools.getUserShortInfoMsg(idapp, myuser);
if (myfunc === shared_consts.CallFunz.RICHIESTA_AMICIZIA) {
sendnotif = true;
typedir = shared_consts.TypeNotifs.TYPEDIR_FRIENDS;
typeid = shared_consts.TypeNotifs.ID_FRIENDS_NEW_REC;
paramsObj = { usernameDest: userDest };
domanda = printf(tools.gettranslate('RICHIESTA_AMICIZIA', langdest), myuser.username) + '<br>' + struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅👤 Accetta Amicizia',
callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + userDest + tools.SEP + '',
},
{
text: '🚫👤 Rifiuta Amicizia',
callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + userDest + tools.SEP + '',
},
]);
} else if (myfunc === shared_consts.CallFunz.RICHIESTA_HANDSHAKE) {
sendnotif = true;
typedir = shared_consts.TypeNotifs.TYPEDIR_HANDSHAKE;
typeid = shared_consts.TypeNotifs.ID_HANDSHAKE_ACCEPTED;
paramsObj = { usernameDest: userDest };
domanda = printf(tools.gettranslate('RICHIESTA_HANDSHAKE', langdest), myuser.username) + '<br>' + struserinfomsg;
keyb = cl.getInlineKeyboard(myuser.lang, [
{
text: '✅🤝 Ricambia la stretta di mano',
callback_data: InlineConferma.RISPOSTA_SI + myfunc + tools.SEP + myuser.username + tools.SEP + userDest + tools.SEP + '',
},
]);
}
// Invia Msg
if (domanda) {
const teleg_id = await User.TelegIdByUsername(idapp, userDest);
await this.local_sendMsgTelegramByIdTelegram(idapp, teleg_id, domanda, undefined, undefined, true, keyb);
}
if (sendnotif) {
const req = tools.getReqByPar(idapp, username);
// CREATE NOTIFICATION IN TABLE SENDNOTIF
await SendNotif.createNewNotifToSingleUser(req, null, paramsObj, true, typedir, typeid);
}
} catch (e) {
console.error('Error askConfirmationUser', e);
}
},
sendMsgTelegramToTheManagers: async function (
idapp, text, onlyintofile = false, MyForm = null, nottousername = '') {
tools.writeManagersLog(text);
if (!onlyintofile) {
const usersmanagers = await User.getusersManagers(idapp);
if (usersmanagers) {
for (const rec of usersmanagers) {
if (rec.username !== nottousername) {
await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id,
emo.ROBOT_FACE + ': ' + text, undefined, undefined, true,
MyForm);
await tools.snooze(100);
}
}
}
}
return true;
},
sendMsgTelegramToTheAdminsOfCircuit: async function (
idapp, circuitpath, text, onlyintofile = false, MyForm = null, nottousername = '') {
tools.writeManagersLog(text);
let teleg_id = 0;
if (!onlyintofile) {
const usersmanagers = await Circuit.getListAdminsByCircuitPath(idapp, circuitpath);
if (usersmanagers) {
for (const rec of usersmanagers) {
if (rec.username !== nottousername) {
teleg_id = await User.TelegIdByUsername(idapp, rec.username);
if (teleg_id) {
await this.sendMsgTelegramByIdTelegram(idapp, teleg_id,
emo.ROBOT_FACE + ': ' + text, undefined, undefined, true,
MyForm);
await tools.snooze(100);
}
}
}
}
}
return true;
},
sendMsgTelegramToTheManagersAndZoomeri: async function (
idapp, text, onlyintofile, MyForm = null) {
tools.writeManagersLog(text);
if (!onlyintofile) {
// const usersmanagers = await User.getusersManagersAndZoomeri(idapp);
const usersmanagers = await User.getusersManagers(idapp);
if (usersmanagers) {
for (const rec of usersmanagers) {
await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id,
emo.ROBOT_FACE + ': ' + text, undefined, undefined, true, MyForm);
await tools.snooze(100);
}
}
}
return true;
},
getMsgByTipoMsg: async function (mydata, lang, user, sonosognatore) {
if (!!mydata.msgextra) {
return { body: mydata.msgextra, title: '' };
}
let title = '';
let msg = '';
if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) {
if (sonosognatore)
msg = printf(tools.gettranslate('SEND_LINK_CHAT_SOGNATORE', lang),
user.name,
mydata.navemediatore.riga + '.' + mydata.navemediatore.col,
mydata.msgpar1);
else
msg = printf(tools.gettranslate('SEND_LINK_CHAT_DONATORI', lang),
user.name,
mydata.navemediatore.riga + '.' + mydata.navemediatore.col,
mydata.msgpar1);
} else if (mydata.tipomsg === tools.TipoMsg.SEND_MSG || mydata.tipomsg ===
tools.TipoMsg.SEND_MSG_SINGOLO) {
if (!!mydata.username_mitt) {
msg = '[' + tools.gettranslate('MSG_SEND_FROM', lang) + ' ' +
mydata.username_mitt + ']:' + tools.ACAPO;
}
msg += mydata.msgpar1;
} else if (mydata.tipomsg >= 1000) {
const ris = await MsgTemplate.getMsgByLang(user.idapp, user, mydata.tipomsg,
lang);
msg = ris.body;
title = ris.title;
}
const cl = getclTelegByidapp(user.idapp);
if (cl) {
msg = await tools.convertSpecialTags(rec.user, msg);
}
if (!!mydata.flotta) {
// SOSTITUISCI LE PAROLE CHIAVI
if (!!mydata.flotta.date_start)
msg = msg.replace('{date_start}',
tools.getstrDateLongTot(new Date(mydata.flotta.date_start),
user.lang));
if (!!mydata.flotta.date_close)
msg = msg.replace('{date_close}',
tools.getstrDateLongTot(new Date(mydata.flotta.date_close),
user.lang));
if (!!mydata.flotta.link_superchat)
msg = msg.replace('{link_superchat}', mydata.flotta.link_superchat);
if (!!mydata.flotta.tutor1)
msg = msg.replace('{tutor1}', mydata.flotta.tutor1);
if (!!mydata.flotta.tutor2)
msg = msg.replace('{tutor2}', mydata.flotta.tutor2);
if (!!mydata.flotta.tutor3)
msg = msg.replace('{tutor3}', mydata.flotta.tutor3);
if (!!mydata.flotta.tutorslo)
msg = msg.replace('{tutorslo}', mydata.flotta.tutorslo);
if (!!mydata.flotta.sognatore_nomecognome)
msg = msg.replace('{sognatore}', mydata.flotta.sognatore_nomecognome);
if (!!mydata.flotta.sognatore_nomecognome)
msg = msg.replace('{flotta}',
mydata.flotta.riga + '.' + Math.ceil(mydata.flotta.col_prima / 8) +
' - ' + mydata.flotta.riga + '.' +
Math.ceil(mydata.flotta.col_ultima / 8));
}
return { body: msg, title };
},
sendMsgTelegramToTheAdminAllSites: async function (text, senzaintestazione) {
for (const idapp of this.getAppTelegram()) {
text = text.replace('{appname}', tools.getNomeAppByIdApp(idapp));
await this.sendMsgTelegramToTheAdmin(idapp, text, senzaintestazione);
}
},
sendMsgTelegramToTheAdmin: async function (idapp, text, senzaintestazione) {
const usersmanagers = await User.getusersAdmin(idapp);
let intestaz = emo.ROBOT_FACE + '[BOT-ADMIN]' + emo.ADMIN + ': ';
if (senzaintestazione)
intestaz = '';
if (usersmanagers) {
for (const rec of usersmanagers) {
if (User.isAdmin(rec.perm)) {
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 = false, username_mitt = '') {
const { User } = require('../models/user');
const teleg_id = await User.TelegIdByUsername(idapp, username);
const cl = getclTelegByidapp(idapp);
let ris = null;
if (cl && teleg_id) {
ris = await cl.sendMsg(teleg_id, text);
}
if (cl && teleg_id) {
if (alsotomanagers) {
await this.sendMsgTelegramToTheManagers(idapp, text);
}
if (!!username_mitt) {
const rec = cl.getRecByUsername(username);
if (rec) {
rec.msgall_username_specifico = username_mitt;
}
}
}
return ris;
},
sendMsgTelegramByIdTelegram: async function (
idapp, idtelegram, text, message_id, chat_id, ripr_menuPrec,
MyForm = null, img = '') {
if (!idtelegram)
return;
const cl = getclTelegByidapp(idapp);
if (cl && idtelegram) {
let myform = null;
return await cl.sendMsg(idtelegram, text, null, MyForm, message_id,
chat_id, ripr_menuPrec, img);
}
},
reloadMenuBot: async function (idapp) {
const cl = getclTelegByidapp(idapp);
if (cl) {
return cl.updateMenuBot();
}
},
reloadSites: async function () {
tools.loadApps();
},
sendMsgFromSite: async function (idapp, user, params) {
try {
let ris = {
numrec: 0,
nummsgsent: 0,
text: '',
};
let invia = false;
let content = '';
let tipomsgtempl = 0;
params.sendreally = true;
if (params.typemsg === shared_consts.TypeMsg.SEND_TO_MYSELF) {
params.usernameDest = user.username;
}
if (params.cmd === shared_consts.MsgTeleg.SHARE_MSGREG) {
tipomsgtempl = shared_consts.TypeMsgTemplate.MS_SHARE_LINK;
invia = true;
} else if (params.cmd === shared_consts.MsgTeleg.SHARE_TEXT) {
invia = !!params.content;
} else if (params.cmd === shared_consts.MsgTeleg.SHARE_ANNUNCIO) {
const mytable = globalTables.getTableByTableName(params.tablerec);
if (params.idrec && params.idrec !== '0') {
// const myrectableorig = await mytable.findOne({ _id: myrecnotifpass.idrec }).lean();
const myrectableorig = await mytable.getCompleteRecord(params.idapp, params.idrec);
if (myrectableorig) {
const eventobj = await tools.getAnnuncioForTelegram(myrectableorig, params.tablerec, '', user.username, false);
if (eventobj) {
params.textcontent_Telegram = eventobj.newdescrtelegram;
params.typesend = shared_consts.TypeSend.TELEGRAM;
//const rismsg =
params.content = eventobj.newdescr;
params.title = '';
params.img = eventobj.img;
invia = true;
}
}
}
}
if (tipomsgtempl > 0) {
const rismsg = await MsgTemplate.getMsgByLang(idapp, user, tipomsgtempl, user.lang);
params.content = rismsg.body;
params.title = rismsg.title;
}
if (invia) {
ris = await globalTables.SendMsgToParam(idapp, params);
}
return ris;
} catch (e) {
console.error('sendMsgFromSite', e);
}
},
sendMsgFromSiteToBotTelegram: async function (idapp, user, params) {
if (!params.typesend) {
params.typesend = shared_consts.TypeSend.TELEGRAM;
}
return this.sendMsgFromSite(idapp, user, params);
},
};
async function setVerifiedReg(idapp, lang, usernameorig, usernameDest) {
try {
await User.setVerifiedByAportador(idapp, usernameorig, true);
// await User.setFriendsCmd(null, idapp, usernameorig, usernameDest, shared_consts.FRIENDSCMD.SETFRIEND);
const msgDest = printf(getstr(lang, 'MSG_APORTADOR_CONFIRMED'),
`${usernameorig}`, usernameDest);
await local_sendMsgTelegram(idapp, usernameDest, msgDest);
} catch (e) {
console.log('e', e);
}
}
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 + ': Da ' + tools.getNomeCognomeTelegram(msg) + ' (' + 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(100);
}
}
return true;
}
async function local_sendMsgTelegramToTheAdmin(
idapp, text, msg, username_bo) {
const usersAdmin = await User.getusersAdmin(idapp);
let username = msg.chat.username;
if (username_bo)
username = username_bo;
text = emo.ROBOT_FACE + ': Da ' + msg.chat.first_name + ' ' +
msg.chat.last_name + ' (' + username + '): \n' + text;
tools.writeEventsLog(text);
if (usersAdmin) {
for (const rec of usersAdmin) {
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(100);
}
}
return true;
}
async function local_sendMsgTelegram(idapp, username, text) {
const teleg_id = await User.TelegIdByUsername(idapp, username);
const cl = getclTelegByidapp(idapp);
let ris = null;
if (cl && teleg_id > 0) {
ris = await cl.sendMsg(teleg_id, text);
}
return ris;
}
function getstr(lang, key, param1) {
let mystr = '';
if ((lang === 'si') || (lang === 'sl-si')) {
try {
mystr = txt_si[key];
} catch (e) {
mystr = '';
}
} else if ((lang === 'en') || (lang === 'enUs')) {
try {
mystr = txt_en[key];
} catch (e) {
mystr = '';
}
} else if (lang === 'es') {
try {
mystr = txt_es[key];
} catch (e) {
mystr = '';
}
} else if (lang === 'fr') {
try {
mystr = txt_fr[key];
} catch (e) {
mystr = '';
}
} else if (lang === 'pt') {
try {
mystr = txt_pt[key];
} catch (e) {
mystr = '';
}
}
if (!mystr || mystr === '')
mystr = txt[key];
if (!!param1) {
mystr = printf(mystr, param1);
}
return mystr;
}
class Telegram {
constructor(idapp, bot) {
this.idapp = idapp;
this.bot = bot;
this.token = bot.token;
this.arrUsers = [];
this.lastid = 0;
//++
}
async createIfNotExist(msg) {
if (!await this.alreadyExist(msg)) {
if (await this.insertIntoDB(msg)) {
let rec = this.getRecInMem(msg);
if (!!rec) {
if (rec.user)
rec.status = Status.VERIFIED;
} else {
return false;
}
}
return true;
} else {
return false;
}
}
async settotheDatabase(msg) {
// Check if Present to the DB
const riscreate = await this.createIfNotExist(msg);
if (!riscreate) {
let rec = this.getRecInMem(msg);
if (!rec)
rec = await this.addUser(msg);
if (rec.user)
rec.status = Status.VERIFIED;
}
}
async start(msg) {
// Check if Username Telegram Present
if (!msg.from.username) {
return false;
}
await this.settotheDatabase(msg);
}
geturlfaq() {
return tools.getHostByIdApp(this.idapp) + '/faq';
}
getstrChatHelp() {
return 'Clicca qui per entrare nella Chat HELP di Supporto\n' +
tools.getTelegramSupportChat(this.idapp) +
'\n\nI miei colleghi umani ti aiuteranno a risolvere !';
}
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;
let lang = 'it';
const rec = this.getRecInMem(msg);
let myname = '';
if (rec.user) {
myname = rec.user.username;
lang = rec.user.lang;
}
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 = '';
const menusite = await this.isMenuSite(this.idapp, testo, lang, id);
if (rec.status === Status.VERIFIED) {
if (rec.user) {
if (rec.user.profile.username_telegram && msg.from.id > 0 && !msg.from.username) {
rec.user.profile.username_telegram = msg.from.username;
await User.setUsernameTelegram(this.idapp, rec.user._id,
msg.from.username || '', msg.from.first_name || '',
msg.from.last_name || '');
}
if (!rec.user.profile.username_telegram && !!msg.from.username) {
rec.user.profile.username_telegram = msg.from.username;
await User.setUsernameTelegram(this.idapp, rec.user._id,
msg.from.username || '', msg.from.first_name || '',
msg.from.last_name || '');
await this.sendMsgByTemplate('MSG_SET_USERNAME_OK', rec.user);
if (rec.user) {
if (!rec.user.verified_by_aportador) {
MyTelegramBot.askConfirmationUser(this.idapp, shared_consts.CallFunz.REGISTRATION, rec.user);
}
}
/*} else {
if (!rec.user.profile.username_telegram) {
return this.checkIfUsernameTelegramSet(msg, rec.user);
}*/
}
}
}
let parse_mode = 'HTML';
let arr_bott_inline = []
if (risp === '') {
if (menusite) {
risp = await this.getValueMenu(this.idapp, rec, msg, testo, lang);
parse_mode = await this.getParseModeByMenu(this.idapp, rec, msg, testo, lang);
arr_bott_inline = await this.getArrBottInlineByMenu(this.idapp, rec, msg, testo, lang);
noanswer = true;
} else 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) {
const myrec = await User.getUserShortDataByUsername(this.idapp,
rec.user.username);
risp += `\nSul sito ti sei registrato come ${rec.user.username}:\n\n[N. ` +
rec.user.index + ']: ' + rec.user.name + ' ' + rec.user.surname +
'\nUsername: ' + rec.user.username + '\n' + 'Email: ' +
rec.user.email + '\nLang: ' + rec.user.lang + tools.ACAPO;
risp += 'Num Invitati: ' + myrec.numinvitati + tools.ACAPO;
risp += 'Num Invitati Attivi: ' + myrec.numinvitatiattivi +
tools.ACAPO;
} else {
risp = 'Ancora non ti sei Attivato sul 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 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)) {
// } else if (MsgBot.CHI_E_PAOLO.includes(testo)) {
} 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.PREGO.includes(testo.replace('!', ''))) {
risp = 'Grazie a te ! ' + 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.START_INV.find(
(rec) => testo.indexOf(rec) > -1)) {
risp = 'Sei già registrato. Per accedere alla App, aprila dall\'icona sul tuo schermo, oppure vai sul sito ed installa la App.\n\nSe hai dimenticato la password: \n clicca sul menu in basso su "⚒ Strumenti" e poi "🔑 Cambio Password"'
} else if (MsgBot.COSE_COVID.find(
(rec) => testo.indexOf(rec) > -1)) {
risp = 'Un \'influenza più "grave", dovuta a paure e a fattori interiori di evoluzione, oltre ad una pulizia del corpo. ';
} else if (MsgBot.COVID.find(
(rec) => testo.indexOf(rec) > -1)) {
risp = 'Guarda, è meglio che sorvoliamo questo argomento. Anche un robot capisce che è stato realizzato ' +
'il più grande esperimento dell\'Uomo di ipnosi di massa, riempiendo di bugie i media mondiali, che servono sostanzialmente a controllare i popoli.' +
'E con questo ti ho detto tutto. :D ';
} else if (MsgBot.AIUTO.find((rec) => testo.indexOf(rec) > -1)) {
risp = this.getstrChatHelp();
} 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.SEI_LIBERO_DI_RESPIRARE.find(
(rec) => testo.indexOf(rec) > -1)) {
risp = 'Assolutamente Sì ! Respirare è fondamentale per l\'essere umano !' +
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.DOVE_VUOI_VIVERE.find(
(rec) => testo.indexOf(rec) > -1)) {
risp = 'Mah a me piacerebbe vivere al mare, ma anche vicino al verde, in montagna. Sarebbe l\'ideale 😄';
} else if (MsgBot.TROVAMI_UN_UOMO_DONNA.find(
(rec) => testo.indexOf(rec) > -1)) {
risp = 'Eh non è cosi facile. Ma se t\'impegni a cercare ci riuscirai. Nel frattempo trova la tua strada, fai il tuo percorso interiore, e magari arriva proprio quando meno te l\'aspetti';
} 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;
} 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.OK.find((rec) => testo.indexOf(rec) > -1)) {
risp = '👍🏻';
} else if (MsgBot.CUORE.find((rec) => testo.indexOf(rec) > -1)) {
risp = '❤️💚💜';
} else if (MsgBot.HAHA.find((rec) => testo.indexOf(rec) > -1) && testo.length < 8) {
risp = emo.JOY + emo.JOY + emo.JOY;
} else if (testo.length >= 10) {
noanswer = true;
let myfaq = this.geturlfaq();
risp = 'Ciao {username}, Io mi chiamo BOT e sono il tuo assistente Virtuale ' + emo.ROBOT_FACE + emo.JOY2 + '\n' +
'Usa il menu qui sotto per interagire col BOT\n' +
'\nPer <strong>AIUTO</strong>, clicca qui:\n👉🏻👉🏻<a href="' + myfaq +
'">FAQ di AIUTO</a> (risposte alle domande più frequenti)\n\nSe non trovi risposta allora contatta la <a href="' +
tools.getTelegramSupportChat(this.idapp) + '">Chat di HELP</a>.\nGrazie';
// risp += '\nClicca qui per entrare nella Chat - HELP di Supporto\n' + 'https://t.me/joinchat/AL2qKE80rxDkgbeMGO-0bw' + '\n\nI miei colleghi umani ti aiuteranno a risolvere !';
await local_sendMsgTelegramToTheManagers(this.idapp, testo, msg,
rec.username_bo);
}
}
risp = await tools.convertSpecialTags(rec.user, risp);
let keyboard = null;
if (contastiera) {
keyboard = {
'parse_mode': parse_mode,
'reply_markup': {
'resize_keyboard': true,
'keyboard': await this.getKeyboard(id, undefined, this.getlang(msg)),
},
};
}
let keyboard_inline = undefined;
if (arr_bott_inline.length > 0) {
keyboard_inline = cl.getInlineKeyboard(myuser.lang, arr_bott_inline);
}
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 !== '' && risp !== shared_consts.RIS_OK) {
rec.numdomande++;
if (!noanswer) {
await tools.snooze(300);
risp = '[BOT' + emo.ROBOT_FACE + ' scrive]:\n' + risp;
}
this._inviaMsg(id, risp, keyboard, undefined, undefined, undefined, undefined, { parse_mode, keyboard_inline });
let strlog = 'USER [' + myname + ']: ' + testo + '\n';
tools.writelog(strlog);
}
return risp !== '';
}
async isMenuNotVerified(rec, msg, notlast) {
if (this.isSelMenu(msg, msg.text, 'ASSISTENZA')) {
await this.menuAssistenza(msg);
} else if (msg.text === Menu.LANG_IT) {
await this.ScegliLang(msg, 'it');
} else if (msg.text === Menu.LANG_ES) {
await this.ScegliLang(msg, 'es');
} else if (msg.text === Menu.LANG_SI) {
await this.ScegliLang(msg, 'si');
} else if (msg.text === Menu.LANG_FR) {
await this.ScegliLang(msg, 'fr');
} else if (msg.text === Menu.LANG_EN) {
await this.ScegliLang(msg, 'enUs');
} else if (msg.text === Menu.LANG_PT) {
await this.ScegliLang(msg, 'pt');
} else if (this.isSelMenu(msg, msg.text, 'INFO')) {
await this.menuInformazioni(msg);
} else if (msg.text === Menu.LANG) {
await this.menuLang(msg);
} else if (this.isSelMenu(msg, msg.text, 'ZOOM') ||
MsgBot.PROSSIMO_ZOOM.find((rec) => msg.text.indexOf(rec) > -1)) {
await this.menuZoom(msg);
} else if (!notlast && await this.IsTesto(msg)) {
// OK
} else {
await this.msgScegliMenu(msg);
}
}
isSelMenu(msg, menuselect, key) {
let miomenu = '';
try {
let lang = this.getlang(msg);
miomenu = Menu[lang][key];
} catch (e) {
miomenu = Menu['it'][key];
}
let trovato = (miomenu === menuselect);
if (!trovato) {
try {
let miomenu2 = Menu['it'][key];
trovato = (miomenu2 === menuselect);
} catch (e) {
}
}
return trovato;
}
async isMenu(rec, msg, testo, notlast) {
try {
if (!msg)
return;
if (testo === undefined)
return;
const arrtext = testo.split(' ');
let cmd2 = '';
let cmd1 = arrtext[0];
if (arrtext.length > 1)
cmd2 = arrtext[1];
let oldusername = rec.msgall_username_specifico;
if ((this.isSelMenu(msg, testo, 'ESCI_DA_CHAT')) ||
(this.isSelMenu(msg, testo, 'INDIETRO'))) {
rec.msgall_username_specifico = '';
} else {
if (rec.msgall_username_specifico !== '') {
await this.SendMsgToUser(msg, rec, rec.msgall_username_specifico,
testo);
return true;
}
}
if (this.isSelMenu(msg, testo, 'LAVAGNA') ||
MsgBot.LAVAGNA.find((rec) => testo.indexOf(rec) > -1)) {
await this.menuLavagna(msg);
} else if (this.isSelMenu(msg, testo, 'ACCEDI')) {
await this.menuAccedi(msg);
} else if (this.isSelMenu(msg, testo, 'LINK_CONDIVIDERE')) {
await this.menuLinkCondividere(msg);
} else if (testo === Menu.EXIT_TELEGRAM) {
await this.menuExitToTelegram(msg);
} else if (testo === Menu.ADMIN) {
await this.menuAdmin(msg);
} else if (testo === Menu.AIUTO) {
await this.menuAiuto(msg);
} else if (testo === Menu.LANG) {
await this.menuLang(msg);
} else if (testo === Menu.MSGATUTTI) {
await this.menumsgAll(msg);
} else if (testo === Menu.MSGSTAFF) {
await this.menumsgStaff(msg);
} else if (testo === Menu.MSGAPPARTIENE_CIRCUITI_RIS) {
await this.menumsgAppartieneCircuitiRis(msg);
} else if (testo === Menu.MSGPAOLO) {
await this.menumsgPaolo(msg);
} else if (cmd1 === Menu.EXECSH) {
if (rec.user && cmd2) {
let isAdmin = rec.user ? rec.user.profile.admin_telegram : false;
if (isAdmin) {
const ris = await tools.execScriptByTelegram(this.idapp, msg, cmd2, 'Eseguo lo script');
}
}
} else if (cmd1 === Menu.LOG_SRV) {
if (rec.user) {
let isAdmin = rec.user ? rec.user.profile.admin_telegram : false;
if (isAdmin) {
await this.menuLogSrv(rec, msg, cmd2);
}
}
} else if (cmd1 === Menu.REBOOT_SRV) {
if (rec.user) {
let isAdmin = rec.user ? rec.user.profile.admin_telegram : false;
if (isAdmin) {
await this.menuRebootSrv(rec, msg, cmd2);
}
}
} else if (cmd1 === Menu.RESTART_SRV) {
if (rec.user) {
let isAdmin = rec.user ? rec.user.profile.manage_telegram : false;
if (isAdmin) {
await this.menuRestartSrv(rec, msg, cmd2);
}
}
// } else if (testo === Menu.MSG_NO_7_REQ) {
// await this.menumsg_No_7_Req(msg);
// } else if (testo === Menu.MSG_NO_9_REQ) {
// await this.menumsg_No_9_Req(msg);
// } else if (testo === Menu.NESSUN_IMBARCO_7REQ) {
// await this.menumsgGenerico(msg, Destin.NESSUN_IMBARCO_7REQ);
// } else if (cmd1 === Menu.MSG_TO_NAVE) {
// await this.menumsg_to_Nave(msg, cmd2);
// } else if (testo === 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 (testo === Menu.SETPICPROFILE) {
await this.setPhotoProfile(rec.user, msg.from.id);
} else if (testo === Menu.RESETPWD) {
await this.setResetPwd(rec, msg);
} else if (this.isSelMenu(msg, testo, 'INDIETRO') ||
(testo === Menu.it.INDIETRO)) {
await this.msgScegliMenu(msg);
} else if (this.isSelMenu(msg, testo, 'ESCI_DA_CHAT')) {
await this.sendMsg(msg.chat.id, 'Uscito dalla Chat con ' + oldusername);
rec.msgall_username_specifico = '';
} else {
await this.isMenuNotVerified(rec, msg, notlast);
}
} catch (e) {
console.error('isMenu', e);
}
}
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) {
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);
}
}
}
return false;
}
async menuAccedi(msg) {
let status = this.getstatusInMemory(msg);
}
getlang(msg) {
const rec = this.getRecInMem(msg);
if (!!rec) {
if (rec.user) {
rec.lang = rec.user.lang;
}
if (rec.lang !== '' && rec.lang !== undefined)
return rec.lang;
else {
return msg.from.language_code;
}
}
}
async getLavagnaByUser(user, msg) {
let mystr = '';
const dashboard = await User.getDashboard(this.idapp,
user.aportador_solidario, user.username,
user.aportador_solidario_name_surname);
const downline = await User.getDownline(this.idapp,
user.aportador_solidario, user.username);
let numpersone = (downline.downline) ? downline.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;
let mystrnave = '';
if (user) {
mystr += tools.get__('BENVENUTO', this.getlang(msg)) + ' ' + user.name +
' (' + user.username + ') ' + emo.DIZZY + '\n\n';
tuttie9 = dashboard.myself.qualified && (numpersone >= 2) &&
invitati_attivi >= 2;
mystrnave = await Nave.getNaveByUser(this.idapp, user.username, user.lang,
true);
if (mystrnave === '' && tuttie9) {
mystr += tools.gettranslate('NO_PROG', user.lang);
}
if (!!mystrnave) {
mystr += '✨✨✨' + tools.get__('TUE_NAVI', this.getlang(msg)) + ':\n';
mystr += mystrnave;
} else {
if (!tuttie9) {
mystr += dashboard.myself.qualified ? emo.SMILE_STAR +
tools.get__('HAI_I_7_REQUISITI', this.getlang(msg)) +
emo.SMILE_STAR : emo.EXCLAMATION_MARK +
tools.get__('NON_HAI_I_7_REQUISITI', this.getlang(msg));
mystr += '\n\n';
}
// mystr += tuttie9 ? emo.SMILE_STAR + tools.get__('HAI_I_9_REQUISITI', this.getlang(msg)) + emo.SMILE_STAR : emo.EXCLAMATION_MARK + tools.get__('NON_HAI_I_9_REQUISITI', this.getlang(msg));
mystr += '\n\n';
mystr += tools.get__('INFO_LA_MIA_LAVAGNA', this.getlang(msg));
mystr += '\n' + '1. ' + this.getsymb(emo.ENVELOPE, user.verified_email);
mystr += tools.get__('EMAIL', this.getlang(msg)) + ' ';
mystr += user.verified_email
? tools.get__('VERIF', this.getlang(msg))
: tools.get__('EMAIL_NON_VERIF', this.getlang(msg));
mystr += '\n2. ' + this.getsymb(emo.ROBOT_FACE, true) +
tools.get__('BOT', this.getlang(msg)) + ' ';
mystr += tools.get__('VERIF', this.getlang(msg));
mystr += '\n3. ' + this.getsymb(emo.PENCIL,
tools.isBitActive(user.profile.saw_and_accepted,
shared_consts.Accepted.CHECK_READ_GUIDELINES)) +
tools.get__('LINEE_GUIDA', this.getlang(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', this.getlang(msg));
// mystr += '\n5. ' + this.getsymb(emo.EYES, user.profile.saw_zoom_presentation) + tools.get__('ZOOM_PARTECIPATO', this.getlang(msg));
// mystr += '\n6. ' + this.getsymb(emo.DREAM, this.isdreamset(user)) + tools.get__('SCRITTO_SOGNO', this.getlang(msg));
mystr += '\n7. ' + this.getsymb(emo.CREDIT_CARD, this.ispayment(user)) +
tools.get__('PAYMENTS', this.getlang(msg));
}
// } else{
// mystr += tools.get__('TELEGRAM_NOT_CONNECTED', msg) + ' ' + emoji.get('e-mail');
}
// numpersone = 2;
if (!mystrnave) {
mystr += '\n8. ' +
this.getsymb(emo.INVITATI, numpersone >= 2, numpersone, numpersone,
numpersone >= 3) + tools.get__('INVITATI', this.getlang(msg));
mystr += '\n9. ' +
this.getsymb(emo.INVITATI, invitati_attivi >= 2, invitati_attivi,
invitati_attivi, invitati_attivi >= 3) +
tools.get__('INVITATI_ATTIVI', this.getlang(msg)) + '\n' + '\n';
if (numpersone > 0) {
mystr += tools.get__('INVITATI_LISTA', this.getlang(msg)) + ':\n';
let index = 1;
downline.downline.forEach((user) => {
mystr += emoji.get('star-struck') + ` ${index}°: `;
mystr += (user.qualified) ? emo.CHECK_VERDE : emo.CROSS_ROSSA;
mystr += `${user.name} ${user.surname} (${user.username})\n`;
index++;
});
} else {
mystr += tools.get__('NESSUN_INVITATO', this.getlang(msg)) +
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', this.getlang(msg)));
else
mystr += '\n' +
printf(tools.get__('INFO_LAVAGNA_SITO_COMPLETARE', this.getlang(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 username_to_check = rec.user.username;
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, username_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', this.getlang(msg)),
tools.getHostByIdApp(this.idapp) + '/registrati/' + rec.user.username);
mystr += tools.ACAPO + tools.ACAPO +
printf(tools.get__('INFO_LINK_ZOOM', this.getlang(msg)),
tools.getlinkzoom(null));
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._id, 0).
then((recuser) => {
if (recuser) {
this.deleteRecInMem(msg);
this.sendMsg(msg.chat.id,
getstr(rec.user.lang, 'MSG_EXIT_TELEGRAM'));
}
});
} else {
this.deleteRecInMem(msg);
}
}
async menuInformazioni(msg) {
const mystr = 'Informazioni Aggiuntive: ...';
await this.sendMsg(msg.chat.id, mystr);
}
async getNextZoom(msg) {
const listazoom = await CalZoom.findAllIdApp(this.idapp);
const nextzoom = await CalZoom.getNextZoom(this.idapp);
let mystr = '';
mystr += emo.STARS + tools.get__('ZOOM_CONFERENCE', this.getlang(msg)) +
emo.STARS + '\n\n';
// let pwd = 'Password: 123123';
let index = 1;
listazoom.forEach((evento) => {
let iniziata = false;
if (nextzoom)
iniziata = (nextzoom._id.toString() === evento._id.toString());
let lang = this.getlang(msg);
if (iniziata) {
mystr += emo.CHECK_VERDE + ' ' + tools.get__('ZOOM_INIZIATO', lang) +
' ' + emo.CHECK_VERDE + '\n';
}
mystr += tools.getflagtelegrambyLang(evento.lang) +
` ${emo.EYES} ${tools.getstrDateTimeShort(evento.date_start,
this.getlang(msg))} ${emo.EYES}`;
mystr += `\n${evento.title}\n(${evento.note})`;
mystr += `\n${tools.getlinkzoom(evento)}\n\n`;
if (nextzoom) {
if (iniziata) {
mystr += emo.FIRE + tools.get__('CLICCA_ENTRA', this.getlang(msg)) +
' ' + emo.FIRE + '\n';
mystr += tools.getlinkzoom(evento) + '\n';
mystr += '\n';
//mystr += pwd + '\n\n';
}
}
index++;
});
if (!nextzoom && index > 1) {
mystr += '✨✨✨✨✨✨✨✨✨✨✨✨\n' +
tools.get__('CLICCA_PER_ZOOM', this.getlang(msg)) + '\n' +
'✨✨✨✨✨✨✨✨✨✨✨✨\n';
}
return mystr;
}
async menuZoom(msg) {
let mystr = await this.getNextZoom(msg);
await this.sendMsg(msg.chat.id, mystr);
}
async menuAiuto(msg) {
const mystr = this.getstrChatHelp();
await this.sendMsg(msg.chat.id, mystr);
}
async menuAdmin(msg) {
const mystr = tools.get__('SCEGLI_VOCE', this.getlang(msg));
await
this.sendMsg(msg.chat.id, mystr, MenuAdmin);
}
async menuLang(msg) {
const mystr = tools.get__('SCEGLI_VOCE', this.getlang(msg));
await
this.sendMsg(msg.chat.id, mystr, MenuLang);
}
getDestinStr(msg, destin, rec) {
if (destin === Destin.TUTTI)
return 'TUTTI';
else if (destin === Destin.STAFF)
return 'STAFF';
else if (destin === Destin.PAOLO)
return 'PAOLO';
else if (destin === Destin.APPARTIENE_CIRCUITO_RIS)
return 'APPARTIENE_CIRCUITO_RIS';
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.NESSUN_IMBARCO_7REQ)
return 'No Imbarcati (7 Req) ';
else if (destin === Destin.A_UTENTE) {
const rec = this.getRecInMem(msg);
return rec.msgall_username_specifico;
} else if (destin === Destin.DOMANDA) {
const rec = this.getRecInMem(msg);
return rec.msg_username_domanda;
} else if (destin === Destin.RISPOSTA) {
const rec = this.getRecInMem(msg);
return rec.msg_username_risposta;
}
}
async menumsgAll(msg) {
await this.menumsgGenerico(msg, Destin.TUTTI);
}
async menumsgStaff(msg) {
await this.menumsgGenerico(msg, Destin.STAFF);
}
async menumsgAppartieneCircuitiRis(msg) {
await this.menumsgGenerico(msg, Destin.APPARTIENE_CIRCUITO_RIS);
}
async menumsgPaolo(msg) {
await this.menumsgGenerico(msg, Destin.PAOLO);
}
nonAbilitato(msg) {
MyTelegramBot.local_sendMsgTelegramByIdTelegram(this.idapp, msg.chat.id,
'Utente Non abilitato o codice non valido ad eseguire questa funzione');
}
chisono(rec) {
if (rec && rec.user) {
return 'Eseguito da ' + rec.user.username + ': ';
}
}
async menuRestartSrv(rec, msg, cmd2) {
if (cmd2 === '6711') {
await MyTelegramBot.sendMsgTelegramToTheAdminAllSites(this.chisono(rec) + ' ha rilanciato il Server NODE.JS...');
let file = '~/batch/production_restart_server.sh';
if (process.env.NODE_ENV === 'test') {
file = '~/batch/test_restart_server.sh';
}
let messaggio = this.chisono(rec) + ' Restart il Server (Node.Js) : ' + process.version;
messaggio += '\nVersione Server: ' + await tools.getVersServer();
const ris = await tools.execScriptByTelegram(this.idapp, msg, file, messaggio);
} else {
this.nonAbilitato(msg);
}
}
async menuLogSrv(rec, msg, cmd2) {
if (cmd2 === '6711') {
const ris = await tools.execScriptByTelegram(this.idapp, msg, '~/batch/logserver.sh', this.chisono(rec) + ' Visualizzo il Log del Server...');
} else {
this.nonAbilitato(msg);
}
}
async menuRebootSrv(rec, msg, cmd2) {
if (cmd2 === '6711') {
await MyTelegramBot.sendMsgTelegramToTheAdminAllSites(this.chisono(rec) + ' ha effettuato il Reboot del Server! ...');
const ris = await tools.execScriptByTelegram(this.idapp, msg, '~/batch/esegui_reboot.sh',
this.chisono(rec) + ' Eseguo il Reboot del Server !...');
} else {
this.nonAbilitato(msg);
}
}
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);
}
}
permitSendMsg(user) {
return User.isAdmin(user.perm);
}
async menumsgGenerico(msg, dest, username, extraparam) {
const rec = this.getRecInMem(msg);
if (rec.user) {
if (this.permitSendMsg(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 menumsgDomanda(
msg, cmd, dest, username, extraparam, domanda, msgYes, msgNo, destYes,
destNo, username_risposta) {
const rec = this.getRecInMem(msg);
if (rec.user) {
rec.msgall_status = StatusMSGALL.CONFIRM;
rec.msgall_achi = dest;
rec.extraparam = extraparam;
rec.cmd_to_set = cmd;
rec.msg_username_domanda = username;
rec.msg_username_risposta = username_risposta;
rec.msgtosent = msgYes;
rec.msgNo = msgNo;
rec.msg_toDest_yes = destYes;
rec.msg_toDest_no = destNo;
return this.ChiediSINO(msg, domanda);
}
}
getlink(qualelink) {
if (qualelink === 'website') {
return '';
} else if (qualelink === 'biblio') {
return '';
} else if (qualelink === 'help') {
return tools.HELP_CHAT;
} else if (qualelink === 'faq') {
return '';
}
}
async menuAssistenza(msg) {
const sito = this.getlink('website');
const empower = this.getlink('empower');
const biblio = this.getlink('biblio');
const faq = this.getlink('faq');
let help = '';
let helpaperta = true;
/*if (tools.isMonToFri() && tools.isBetweenTwoTime('9:00:00', '19:00:00')) {
help = '✅ ' + this.getlink('help');
} else {
help = "🔴 [ORA CHIUSA - NOW CLOSED]";
helpaperta = false;
}*/
help = '✅ ' + this.getlink('help');
let mytext = '';
if (this.getlang(msg) === 'it')
mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito,
biblio, empower, faq, help);
else
mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito,
biblio, empower, help);
let menu = null;
const rec = this.getRecInMem(msg);
if (!rec.user) {
menu = null;
}
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 === this.getchatid(msg));
}
getRecInMemById(id) {
return this.arrUsers.find((rec) => rec.id.toString() === id.toString());
}
getRecByUsername(username) {
return this.arrUsers.find((rec) => rec.username_bo === username);
}
setRecByUsername(username, myrec) {
const ind = this.arrUsers.findIndex((rec) => rec.username_bo === username);
if (ind >= 0) {
this.arrUsers[ind] = myrec;
}
}
deleteRecInMem(msg) {
this.arrUsers = this.arrUsers.filter(
(rec) => rec.id !== this.getchatid(msg));
}
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,
getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_NOT_FOUND'), null);
const lang = this.getlang(msg);
// const textman = msg.chat.first_name + ' ' + msg.chat.last_name + ' sta tentando di autenticarsi con il BOT (lang=' + lang + ') (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) {
}
async askUsernameInvitante(msg, linkreg) {
try {
let rec = this.getRecInMem(msg);
if (msg.text === undefined || msg.text === 'undefined')
return false;
if (rec && !rec.aportador_solidario) {
rec.status = Status.SET_USERNAME_INVITANTE;
let mystr = getstr(this.getlang(msg), 'MSG_ASK_USERNAME_INVITANTE', null);
if (this.idapp === tools.RISO) {
mystr += getstr(this.getlang(msg), 'MSG_NEW_REG');
}
await this.sendMsg(msg.chat.id, mystr);
} else {
// if (linkreg)
// this.asktoRegistrationByLink(msg);
}
} catch (e) {
console.error('Error setUsernameBo:', e);
}
}
async sendMsgByTemplate(title, myuser) {
try {
const msg = await MsgTemplate.getMsgByTitleAndLang(myuser.idapp, title, myuser.lang);
const mytext = await tools.convertSpecialTags(myuser, msg.body);
return await this.sendMsg(myuser.profile.teleg_id, mytext);
} catch (e) {
console.error('ERR sendMsgByTemplate', e);
}
}
async sendMsgByTemplateByMsgStrutt(title, msg) {
try {
let langcode = 'it';
let id = 0;
try {
langcode = msg.from.language_code;
id = msg.from.id;
} catch (e) {
}
const mymsg = await MsgTemplate.getMsgByTitleAndLang(tools.RISO, title, langcode);
const mytext = await tools.convertSpecialTags(null, mymsg.body);
if (id > 0)
return await this.sendMsg(id, mytext);
} catch (e) {
console.error('ERR sendMsgByTemplateByMsgStrutt', e);
}
}
async sendMsgByTextByMsgStrutt(keytext, msg) {
try {
let langcode = 'it';
let id = 0;
try {
id = msg.from.id;
langcode = msg.from.language_code;
} catch (e) {
}
const text = getstr(langcode, keytext);
const mytext = await tools.convertSpecialTags(null, text);
if (id > 0)
return await this.sendMsg(id, mytext);
} catch (e) {
console.error('ERR sendMsgByTextByMsgStrutt', e);
}
}
async checkIfUsernameTelegramSet(msg) {
try {
if (!msg.from.username) {
await this.sendMsgByTemplateByMsgStrutt('MSG_SET_USERNAME', msg);
// await this.sendMsgByTextByMsgStrutt('MSG_SET_USERNAME_TELEGRAM', msg);
return false;
//await this.sendMsgByTemplate('MSG_SET_USERNAME', myuser);
}
return true;
} catch (e) {
console.error('e');
return false;
}
}
async setUsernameInvitante(msg) {
try {
let mymsg = msg.text.toString().trim().toLowerCase();
let nomeapp = tools.getNomeAppByIdApp(this.idapp);
if (!!mymsg) {
const rec = this.getRecInMem(msg);
let aportador_solidario = rec.aportador_solidario;
if (!aportador_solidario) {
aportador_solidario = mymsg;
aportador_solidario = tools.removeAtChar(aportador_solidario);
let user = await User.getUserShortDataByUsername(this.idapp, aportador_solidario);
if (!user) {
// check if is username telegram inserted
user = await User.getUserShortDataByUsernameTelegram(this.idapp, aportador_solidario);
}
if (user)
rec.aportador_solidario = user.username;
}
if (rec.aportador_solidario) {
// Link per Registrarsi
this.asktoRegistrationByLink(msg);
} else {
// rec.status = Status.WAITFOR_USERNAME_INVITANTE;
rec.status = Status.SET_USERNAME_INVITANTE;
const str2 = '\n' + getstr(this.getlang(msg), 'MSG_ASK_USERNAME_INVITANTE', nomeapp);
if (msg.from.username)
console.log(msg.from.username + ' ha digitato: ' + msg.text);
await this.sendMsg(msg.from.id, getstr(this.getlang(msg), 'MSG_ERRORE_INVITANTE_NOT_FOUND', nomeapp) + str2, null);
}
}
} catch (e) {
console.error('Error setUsernameInvitante', e);
}
}
async setVerifyCode(msg) {
try {
if (!!msg.text) {
const code = msg.text.toString().trim();
const rec = this.getRecInMem(msg);
let user = await User.findByUsername(this.idapp, rec.username_bo, true);
let telegcode = 0;
if (user) {
telegcode = user.profile.teleg_checkcode.toString();
} else {
await
this.sendMsg(msg.from.id,
getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_NOT_FOUND'),
null);
return;
}
if (code.length < 7) {
if (rec) {
if (code === telegcode) {
try {
await User.setUsernameTelegram(this.idapp, user._id,
msg.from.username || '', msg.from.first_name || '',
msg.from.last_name || '');
} catch (e) { }
// let ris = await this.getUser(msg, rec, false);
rec.status = Status.VERIFIED;
rec.datemenu_updated = null;
rec.menuDb = null;
const recuser = await User.SetTelegramIdSuccess(this.idapp, user._id, msg.from.id);
if (recuser) {
console.log(recuser.username, ' SI E\' VERIFICATO CON TELEGRAM !');
let username = recuser.name;
if (!!msg.from.username) {
await MyTelegramBot.askConfirmationUser(this.idapp, shared_consts.CallFunz.REGISTRATION, recuser);
} else {
console.log(' ... MA GLI MANCA L\'USERNAME TELEGRAM !! ');
}
// this.checkIfUsernameTelegramSet(msg, recuser);
// local_sendMsgTelegramToTheManagers(this.idapp, recuser.name + ' ' + recuser.surname + ' si è Verificato a Telegram BOT! (lang=' + recuser.lang + ')' + emo.STARS, msg);
} else {
this.sendMsgLog(msg.from.id, getstr(this.getlang(msg), 'MSG_ERR_UNKNOWN_VERIFY_CODE'));
}
} else {
if (rec.retry < 2) {
rec.retry++;
await
this.sendMsgLog(msg.from.id,
printf(getstr(this.getlang(msg), 'MSG_ERR_VERIFY_CODE'),
tools.getHostByIdApp(this.idapp)));
} else {
rec.status = Status.NONE;
await
this.sendMsgLog(msg.from.id, getstr(this.getlang(msg),
'MSG_ERRORE_USERNAME_ANNULLA'));
this.deleteRecInMem(msg);
}
}
}
} else if (msg.text.length === 0) {
if (rec)
rec.status = Status.NONE;
await
this.sendMsgLog(msg.from.id,
getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_ANNULLA'));
} else {
await
this.sendMsgLog(msg.from.id,
getstr(this.getlang(msg), 'MSG_ERRORE_VERIFY_CODE_MAXLEN'));
}
}
} catch (e) {
console.error('Error setVerifyCode', e);
}
}
async addUserInDB_enteringInTelegramBot(msg) {
try {
// cerca se esiste già l'utente in Memoria
const rec = this.getRecInMem(msg);
if (!rec.user) {
// cerca se esiste già l'utente con il suo ID Telegram
const user = await User.UserByIdTelegram(this.idapp, msg.from.id);
if (!user) {
// Se non esiste già, creo la registrazione dell'Utente, senza password:
const myuserdata = {
idapp: this.idapp,
username: msg.from.username || msg.from.id,
name: msg.from.first_name || '',
lang: msg.from.language_code || 'it',
surname: msg.from.last_name || '',
profile: {
teleg_id: msg.from.id,
}
}
const recuser = await FuncUsers.createRegistration_withTelegram(myuserdata);
if (recuser) {
rec.user = recuser;
console.log(recuser.username, ' SI E\' VERIFICATO CON TELEGRAM !');
// let username = recuser.name;
/*if (!!msg.from.username) {
await MyTelegramBot.askConfirmationUser(this.idapp, shared_consts.CallFunz.REGISTRATION, recuser);
} else {
console.log(' ... MA GLI MANCA L\'USERNAME TELEGRAM !! ');
} */
}
}
}
return { ris: !!rec.user, recuser: rec.user };
} catch (e) {
console.error('Error addUserInDB_enteringInTelegramBot', e);
}
return { ris: false, recuser: null };
}
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 setCmdToUsername(rec, username, cmd_to_set, valuebool) {
if (cmd_to_set === Cmd.VALIDATE_REGISTRATION) {
return await User.setVerifiedByAportador(rec.user.idapp, username, valuebool);
}
}
async sendMsgToAll(rec, msg, texttosend, destin) {
try {
if ((texttosend.length < 3) && (destin !== Destin.A_UTENTE)) {
// NOTHING
} else {
let contanumutenti = 0;
let usersall = null;
let myusername = '';
if (destin === Destin.A_UTENTE) {
myusername = rec.msgall_username_specifico;
} else if (destin === Destin.DOMANDA) {
myusername = rec.msg_username_domanda;
} else if (destin === Destin.RISPOSTA) {
myusername = rec.msg_username_risposta;
}
if (myusername)
usersall = await User.getUsersTelegALL(rec.user.idapp, myusername);
else
usersall = await User.getUsersTelegALL(rec.user.idapp);
let nummsgsent = 0;
let textdainviare = '';
let preparatesto = '';
let myid = '';
if (this.isSelMenu(msg, texttosend, 'ZOOM')) {
texttosend = await this.getNextZoom(msg);
}
const cmd = texttosend.toLowerCase();
if (usersall) {
if (this.isSelMenu(msg, cmd, 'INDIETRO')) {
rec.msgall_status = StatusMSGALL.NONE;
return;
}
tools.writeEventsLog(
this.getDestinStr(msg, destin, rec) + ':\n' + texttosend);
// let chiedisino = false;
for (const utente of usersall) {
let FormDaMostrare = null;
const lang = utente.lang;
if (!utente.deleted && !utente.sospeso) {
if (this.isSelMenu(msg, texttosend === '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.APPARTIENE_CIRCUITO_RIS) {
invia = await User.ExistAtLeastOneCircuit(utente.idapp, utente.username);
} else if (destin === Destin.TUTTI) {
invia = true;
} else if (destin === Destin.PAOLO) {
invia = utente.username === shared_consts.ADMIN_USER_SERVER;
} else if (destin === Destin.A_UTENTE) {
invia = utente.username === rec.msgall_username_specifico;
} else if (destin === Destin.DOMANDA) {
invia = utente.username === rec.msg_username_domanda;
} else if (destin === Destin.RISPOSTA) {
invia = utente.username === rec.msg_username_risposta;
} else if (destin === Destin.NO_7_REQ) {
invia = !await User.isUserQualified7(this.idapp,
utente.username);
} else if (destin === Destin.MSG_TO_NAVE) {
// invia = !await Nave.findDonatoreByNave(this.idapp, rec.extraparam);
}
// TEST invia = true;
if (invia) {
let inviaveramente = false;
if (cmd === RICEVI_EMAIL) {
preparatesto += utente.email + ', ';
} else if (cmd === NOME_COGNOME) {
preparatesto += utente.name + ' ' + utente.surname + '(' +
utente.username + ')' + '\n';
} else if (cmd === CONTA_SOLO) {
contanumutenti++;
// Niente
} else if (cmd === CHEDI_SE_IMBARCARTI) {
textdainviare = tools.gettranslate('VUOI_IMBARCARTI', lang);
FormDaMostrare = this.getInlineKeyboard(lang, [
{
text: Menu[lang].SI,
callback_data: InlineCmd.VOGLIO_IMBARCARMI + tools.SEP +
utente.username,
},
{
text: Menu[lang].NO,
callback_data: InlineCmd.NON_VOGLIO_IMBARCARMI +
tools.SEP +
utente.username,
},
]);
inviaveramente = true;
} else {
inviaveramente = true;
}
if (inviaveramente) {
textdainviare = await tools.convertSpecialTags(utente, textdainviare);
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 {
// if (chiedisino) {
// this.ChiediSINO(msg, textdainviare);
// } else {
// TEST
let telegid = utente.profile.teleg_id;
// if (process.env.PROD === "0") {
// telegid = 12429864;
// }
if (rec.forwardMessage && rec.chatId && rec.messageId) {
// Inoltra il messaggio alla stessa chat o ad un'altra
this.bot.forwardMessage(rec.chatId, telegid, rec.messageId);
} else {
await this.sendMsg(telegid, textdainviare, null,
FormDaMostrare);
}
// break;
}
await tools.snooze(100);
nummsgsent++;
}
if (!SendMsgCmd.includes(cmd)) {
if ((nummsgsent % 100) === 0) {
myid = await this.sendMsg(msg.chat.id, nummsgsent + ' ' +
getstr(this.getlang(msg), 'MSG_MSG_INCORSO'), null,
null, myid);
await tools.snooze(100);
}
}
}
}
}
}
let msgris = '';
if (cmd === CONTA_SOLO) {
msgris = contanumutenti + ' ' +
getstr(this.getlang(msg), 'MSG_MSG_TOSENT');
} else if (cmd === NOME_COGNOME) {
msgris = nummsgsent + ' ' + 'Utenti';
await this.sendMsg(msg.chat.id, msgris);
msgris = preparatesto;
} else if (cmd === RICEVI_EMAIL) {
msgris = nummsgsent + ' ' + 'Email';
await this.sendMsg(msg.chat.id, msgris);
msgris = preparatesto;
} else {
if (destin !== Destin.DOMANDA && destin !== Destin.RISPOSTA) {
msgris = nummsgsent + ' ' +
getstr(this.getlang(msg), '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 {
if (msgris) {
tools.writeEventsLog(msgris);
await this.sendMsg(msg.chat.id, msgris);
}
}
}
rec.start_write_msgall = false;
} catch (e) {
console.error(e.message);
}
}
selectMenuHelp(msg) {
return ((this.isSelMenu(msg, msg.text, 'INFO')) ||
(this.isSelMenu(msg, msg.text, 'ASSISTENZA')));
}
selectMenuLang(msg) {
return ((msg.text === Menu.LANG) || (msg.text === Menu.LANG_EN) ||
(msg.text === Menu.LANG_IT) || (msg.text === Menu.LANG_ES)
|| (msg.text === Menu.LANG_FR) || (msg.text === Menu.LANG_SI) ||
(msg.text === Menu.LANG_PT));
}
async setInit(msg) {
let status = this.getstatusInMemory(msg);
if (status === Status.NONE) {
await this.start(msg);
let status = this.getstatusInMemory(msg);
if (status !== Status.VERIFIED)
return Status.EXIT;
} else {
await this.setUser(msg);
}
return status;
}
getInvitanteByMsg(msg) {
try {
let mymsg = msg.text.toString().trim().toLowerCase();
let invitante = '';
let regexpire = '';
const sep = '-'
if (mymsg.startsWith('/start')) {
let myarrmsg = mymsg.split(' ');
if (myarrmsg.length > 0) {
mymsg = myarrmsg[1];
if (mymsg.startsWith('inv' + sep)) {
let arrparams = mymsg.split(sep);
if (arrparams.length > 2) {
invitante = arrparams[1];
regexpire = arrparams[3];
}
return { invitante, regexpire };
}
}
}
} catch (e) {
}
return '';
}
async setInvitante(msg, ris, crea) {
let rec = this.getRecInMem(msg);
if (!rec && crea) {
let status = await this.setInit(msg);
rec = this.getRecInMem(msg);
}
if (rec) {
if (!rec.aportador_solidario && ris && ris.invitante) {
rec.aportador_solidario = ris.invitante;
rec.regexpire = ris.regexpire;
rec.status = Status.SET_USERNAME_INVITANTE;
}
}
}
async receiveMsg(msg) {
// Check if Username Telegram Present
if (!this.checkIfUsernameTelegramSet(msg)) {
return;
}
let status = await this.setInit(msg);
if (status === Status.EXIT) {
return;
}
const rec = this.getRecInMem(msg);
let testo = msg.text.toLowerCase().trim();
status = this.getstatus(rec);
if (testo === Menu.EXIT_TELEGRAM) {
await this.menuExitToTelegram(msg);
} else if (status === Status.WAITFOR_USERNAME_TELEGRAM && !this.selectMenuHelp(msg) && !this.selectMenuLang(msg)) {
// await this.setUsernameBo(msg);
await this.settotheDatabase(msg);
} else if (status === Status.WAITFOR_USERNAME_INVITANTE && !this.selectMenuHelp(msg) && !this.selectMenuLang(msg)) {
await this.askUsernameInvitante(msg, true);
// await this.settotheDatabase(msg);
} else if (status === Status.SET_USERNAME_INVITANTE) {
const ris = this.getInvitanteByMsg(msg);
if (ris.invitante) {
await this.setInvitante(msg, ris, true);
}
await this.setUsernameInvitante(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 (this.isSelMenu(msg, msg.text, 'SI')) {
// Take msg to send to ALL
await this.sendMsgToAll(rec, msg, rec.msgtosent, rec.msgall_achi);
} else {
let msgout = rec.msgNo;
if (!msgout)
msgout = getstr(this.getlang(msg), 'MSG_OPERAZ_ANNULLATA');
this.sendMsg(msg.chat.id, msgout);
}
if (rec.msgall_achi === Destin.DOMANDA) {
if (rec.msg_toDest_yes) {
rec.msgall_achi = Destin.RISPOSTA;
if (this.isSelMenu(msg, msg.text, 'SI')) {
const ris = await this.setCmdToUsername(rec,
rec.msg_username_risposta, rec.cmd_to_set, true);
if (ris) {
await this.sendMsgToAll(rec, msg, rec.msg_toDest_yes,
rec.msgall_achi);
}
} else if (this.isSelMenu(msg, msg.text, 'NO')) {
const ris = await this.setCmdToUsername(rec,
rec.msg_username_risposta, rec.cmd_to_set, false);
await this.sendMsgToAll(rec, msg, rec.msg_toDest_no,
rec.msgall_achi);
}
}
}
rec.msgall_status = StatusMSGALL.NONE;
normale = false;
} else if (rec.msgall_status === StatusMSGALL.ASK) {
if (!this.isSelMenu(msg, msg.text, 'INDIETRO')) {
rec.msgtosent = msg.text;
rec.entities = msg.entities;
// Se contiene della formattazione allora fai il FORWARD DEL MESSAGGIO
//rec.forwardMessage = !!rec.entities;
rec.forwardMessage = false;
rec.chatId = msg.chat.id;
rec.messageId = msg.message_id;
rec.msgall_status = StatusMSGALL.CONFIRM;
const cmd = rec.msgtosent.toLowerCase();
let achi = this.getDestinStr(msg, rec.msgall_achi, rec);
let domanda = '';
if (rec.msgall_domanda) {
domanda = rec.msgall_domanda;
} else {
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 (cmd === NOME_COGNOME)
domanda = 'Confermi di vedere la lista di persone ' + 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;
await
this.msgScegliMenu(msg);
}
normale = false;
}
if (normale) {
// Check Menu
await this.isMenu(rec, msg, msg.text, false);
}
} else {
await this.isMenuNotVerified(rec, msg, false);
}
}
async asktoRegistrationByLink(msg) {
let rec = this.getRecInMem(msg);
let visu = false;
if (!rec) {
rec = await this.addUser(msg);
visu = true;
}
if (rec && !rec.username_bo)
visu = true;
if (visu) {
const status = this.getstatus(rec);
if (status === Status.SET_USERNAME_INVITANTE && rec.aportador_solidario) {
let linkreg = tools.getLinkRegByIdAppAndMsgStrutt(this.idapp, msg, rec);
if (process.env.LOCALE === '1') {
// linkreg = 'http://localhost:8084/signup/' + rec.aportador_solidario + '/' + msg.from.username + '/' + msg.from.id;
}
const keyb = this.getInlineKeyboard(this.getlang(msg), [
{
text: '✅ ' + i18n.__('CLICCA_QUI'),
url: linkreg,
},
]);
// await this.sendMsg(msg.chat.id, getstr(this.getlang(msg), printf(txt.MSG_ASK_USERNAME_BO, tools.getHostByIdApp(this.idapp))));
await this.sendMsg(msg.chat.id, getstr(this.getlang(msg), 'MSG_SIGNUP', tools.getNomeAppByIdApp(this.idapp)), null, keyb);
} else if (status === Status.WAITFOR_USERNAME_INVITANTE) {
await this.askUsernameInvitante(msg, false);
}
return false;
}
return true;
}
async setUser(msg) {
let id = this.getchatid(msg);
const user = await User.UserByIdTelegram(this.idapp, id);
let rec = this.getRecInMem(msg);
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;
}
}
getchatid(msg) {
if (msg.from.is_bot)
return msg.chat.id;
else
return msg.from.id;
}
async alreadyExist(msg) {
const id = this.getchatid(msg);
let rec = null;
try {
let user = await User.UserByIdTelegram(this.idapp, id);
let rec = this.getRecInMem(msg);
if (user && !rec) {
rec = await 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;
}
updateMenuBot() {
for (let rec of this.arrUsers) {
rec.menuDb = null;
rec.datemenu_updated = null;
}
}
async addUser(msg) {
const lang = this.getlang(msg);
const code = 100000 + Math.round(Math.random() * 899999);
const rec = {
id: this.getchatid(msg),
code,
lang,
statusmsg: 0,
msgcodeprec: '',
sex: 0,
numdomande: 0,
retry: 0,
username_bo: '',
msgall_status: StatusMSGALL.NONE,
msgall_domanda: '',
msgall_achi: 0,
msgall_username_specifico: '',
cmd_to_set: 0,
msg_username_domanda: '',
msg_username_risposta: '',
extraparam: '',
msgtosent: '',
entities: [],
msgNo: '',
msg_toDest_yes: '',
msg_toDest_no: '',
msg_wait: false,
lastmenu: null,
datemenu_updated: null,
pageChange: false,
menuSaved: {},
pagenow: 1,
parse_mode: 'HTML',
menuDb: null,
aportador_solidario: '',
};
rec.status = Status.NONE;
if (!msg.from.username) {
// Non ha l'Username:
// Chiedi l'username sul Bot:
if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskUsernameSulBot)) {
rec.status = Status.WAITFOR_USERNAME_TELEGRAM;
}
} else {
// Ha l'Username
// Chiedi l'invitante ?
if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskInvitantesulBot)) {
rec.status = Status.WAITFOR_USERNAME_INVITANTE;
}
}
if (rec.status === Status.NONE) {
// Se il Sito non chiede di autenticarsi o l'invitante, allora lo Verifico direttamente !
rec.status = Status.VERIFIED;
}
this.arrUsers.push(rec);
if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskInvitantesulBot)) {
// Aportador
this.setInvitante(msg, this.getInvitanteByMsg(msg), false);
}
if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.registerUserWithBot)) {
const ris = await this.addUserInDB_enteringInTelegramBot(msg);
if (ris && ris.recuser) {
rec.recuser = ris.recuser;
rec.status = Status.VERIFIED;
}
}
return rec;
}
async insertIntoDB(msg) {
return this.asktoRegistrationByLink(msg);
}
menuisVisible(idapp, menu) {
}
async loadMenuFromDb(idapp, id) {
try {
let load = false;
const check = true;
const recuser = this.getRecInMemById(id);
if (recuser) {
if (!recuser.datemenu_updated)
load = true;
}
if (check) {
if (recuser) {
if (!(recuser.menuSaved[idapp]))
load = true;
if (recuser.menuDb || recuser.pageChange)
load = true;
}
}
if (load) {
// Check if you are Admin
const user = await User.UserByIdTelegram(idapp, id);
let isAdmin = user ? user.profile.admin_telegram : false;
const isManager = user ? user.profile.manage_telegram : false;
const isVerified = user ? user.profile.teleg_id > 0 && user.verified_by_aportador : false;
recuser.menuDb = await MyBot.findAllIdApp(idapp);
let arrlang = {};
let riga = 0;
let arrtemp = [];
let lang = '';
for (const rec of recuser.menuDb) {
rec.active_mem = false;
const visibilita = (tools.isBitAttivoESelez(rec.visibility, shared_consts.VISIB_ONLY_ADMIN, isAdmin)
&& tools.isBitAttivoESelez(rec.visibility, shared_consts.VISIB_ONLY_MANAGER, isManager)
&& tools.isBitAttivoESelez(rec.visibility, shared_consts.VISIB_ONLYIF_VERIFIED, isVerified))
|| rec.visibility === 0;
if (rec.active && rec.page === recuser.pagenow
&& visibilita
) {
rec.active_mem = true;
if (true) {
lang = rec.lang;
if (!arrlang[rec.lang])
arrlang[rec.lang] = { menu: [] };
if (riga !== rec.riga) {
if (arrtemp.length > 0)
arrlang[rec.lang].menu.push(arrtemp);
riga = rec.riga;
arrtemp = [];
}
arrtemp.push(rec.label);
}
}
}
if (arrtemp.length > 0)
arrlang[lang].menu.push(arrtemp);
if (recuser)
recuser.datemenu_updated = new Date();
recuser.pageChange = false;
recuser.menuSaved[idapp] = arrlang;
}
return recuser ? recuser.menuSaved[idapp] : null;
} catch (e) {
console.log('Err loadMenuFromDb: ' + e);
}
}
async isMenuSite(idapp, testo, lang, id) {
try {
// Check if Reload
const recuser = await this.getRecInMemById(id);
if (recuser) {
if (!recuser.datemenu_updated) {
await this.loadMenuFromDb(this.idapp, id);
}
}
for (const rec of recuser.menuDb) {
if (rec.active_mem) {
if (rec.idapp === idapp && rec.lang === lang &&
rec.label.toLowerCase() === testo) {
return true;
}
}
}
} catch (e) {
return false;
}
return false;
}
async getValueMenu(idapp, recuser, msg, testo, lang) {
try {
if (recuser) {
for (const recdb of recuser.menuDb) {
if (recdb.active_mem) {
if (recdb.idapp === idapp && recdb.lang === lang &&
recdb.label.toLowerCase() === testo) {
if (recdb.type === shared_consts.BOTTYPE_TEXT) {
return recdb.value;
} else if (recdb.type === shared_consts.BOTTYPE_LINK) {
//++TODO: Link diretto !?
return recdb.value;
} else if (recdb.type === shared_consts.BOTTYPE_PAGE) {
if (tools.isNumber(recdb.value)) {
recuser.pagenow = parseInt(recdb.value);
recuser.pageChange = true;
// this.setRecByUsername(recuser.username, recuser);
}
return '';
} else if (recdb.type === shared_consts.BOTTYPE_MENU) {
if (recdb.value) {
this.isMenu(recuser, msg, recdb.value, true);
return shared_consts.RIS_OK;
}
} else if (recdb.type === shared_consts.BOTTYPE_MARKDOWN) {
return recdb.value;
}
}
}
}
}
return '';
} catch (e) {
return '';
}
}
async getParseModeByMenu(idapp, recuser, msg, testo, lang) {
try {
let parse_mode = 'HTML';
if (recuser) {
for (const recdb of recuser.menuDb) {
if (recdb.active_mem) {
if (recdb.idapp === idapp && recdb.lang === lang &&
recdb.label.toLowerCase() === testo) {
if (recdb.type === shared_consts.BOTTYPE_MARKDOWN) {
return 'Markdown'
} else {
return parse_mode;
}
}
}
}
}
return '';
} catch (e) {
return '';
}
}
async getArrBottInlineByMenu(idapp, recuser, msg, testo, lang) {
try {
let arr_bott_inline = [];
if (recuser) {
for (const recdb of recuser.menuDb) {
if (recdb.active_mem) {
if (recdb.idapp === idapp && recdb.lang === lang &&
recdb.label.toLowerCase() === testo) {
if (recdb.type === shared_consts.BOTTYPE_BOTTONI_INLINE) {
const jsonString = '[{"text": "primo", "callback_data": "1"}, {"text": "sec", "callback_data": "2"}]';
const jsonObject = JSON.parse(jsonString);
let myobj = JSON.parse(recdb.value);
arr_bott_inline.push(myobj);
}
}
}
}
}
return arr_bott_inline;
} catch (e) {
console.error(e);
return [];
}
}
async getKeyboard(id, menu, lang) {
let keyb = null;
this.lastid = id;
if (menu) {
keyb = menu;
} else {
keyb = await this.loadMenuFromDb(this.idapp, id);
}
let mykeyb = undefined;
if (!!keyb) {
mykeyb = this.getmenuKey(keyb, lang);
}
if (mykeyb === null) {
mykeyb = [];
}
// console.log('mykeyboard', mykeyb);
return mykeyb;
}
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);
}
}
// Soluzione 1: Converti PNG in JPG prima dell'invio
async sendPhoto(chatId, imageUrl, opt) {
try {
// Scarica l'immagine
const response = await axios.get(imageUrl, { responseType: 'arraybuffer' });
const imageBuffer = Buffer.from(response.data);
// Controlla il formato e converti se necessario
const metadata = await sharp(imageBuffer).metadata();
if (metadata.format === 'png') {
console.log('Conversione PNG in JPG...');
const jpgBuffer = await sharp(imageBuffer)
.jpeg({ quality: 90 })
.toBuffer();
return await this.bot.sendPhoto(chatId, jpgBuffer, opt);
}
// Se non è PNG, invia direttamente
return await this.bot.sendPhoto(chatId, imageBuffer, opt);
} catch (error) {
console.error('Errore nell\'invio della foto:', error);
throw error;
}
}
// Soluzione 2: Prova prima come PNG, se fallisce invia come documento
async sendPhotoWithFallback(chatId, imageUrl, opt) {
try {
// Prova prima a inviare come foto
await this.bot.sendPhoto(chatId, imageUrl, opt);
} catch (error) {
console.log('Invio come foto fallito, provo come documento...');
try {
// Se fallisce, invia come documento
await this.bot.sendDocument(chatId, imageUrl, opt);
} catch (docError) {
console.error('Anche l\'invio come documento è fallito:', docError);
throw docError;
}
}
}
// Soluzione 3: Implementazione completa con gestione errori e tentativi multipli
async sendImageToTelegram(chatId, imageUrl, opt) {
try {
// Prima prova: invia direttamente l'URL
try {
return await this.bot.sendPhoto(chatId, imageUrl, opt);
} catch (error) {
console.log('Primo tentativo fallito, provo a convertire...');
}
// Seconda prova: scarica e converti in JPG
const response = await axios.get(imageUrl, { responseType: 'arraybuffer' });
const imageBuffer = Buffer.from(response.data);
const jpgBuffer = await sharp(imageBuffer)
.jpeg({ quality: 90 })
.toBuffer();
try {
return await this.bot.sendPhoto(chatId, jpgBuffer, opt);
} catch (error) {
console.log('Secondo tentativo fallito, provo come documento...');
}
// Ultima prova: invia come documento
return await this.bot.sendDocument(chatId, imageBuffer, opt);
} catch (error) {
console.error('Tutti i tentativi di invio sono falliti:', error);
return false;
//throw error;
}
}
async _inviaMsg(id, text, form, menu, msg_id, chat_id, ripr_menuPrec, opt) {
if (!text)
return 0;
if (process.env.LOCALE === '1') {
if (id !== ADMIN_IDTELEGRAM_TEST) {
text = '[Msg da inviare ipoteticamente a : ' + id + ']' + '\n' + text;
id = '12429864';
}
}
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;
}
}
let mylang = 'it';
if (!!recmem) {
mylang = recmem.lang;
}
try {
console.log('<<< SEND MSG TELEGRAM: >>> [id=', id, ']', text.substring(0, 100));
text = text.replace(/<br>/g, '\n');
text = text.replace(/<br\/>/g, '\n');
text = text.replace(/<div>/g, '');
text = text.replace(/<font/g, '<pre');
text = text.replace(/<\/font>/g, '</pre>');
text = text.replace(/<span/g, '<pre');
text = text.replace(/<\/span>/g, '</pre>');
text = text.replace(/<p /g, '<pre ');
text = text.replace(/<\/p>/g, '</pre>');
text = text.replace(/<\/div>/g, '\n');
// text = text.replace(/<\/div>/g, '');
text = text.replace(/&nbsp;/g, ' ');
if (!form) {
form = {
parse_mode: opt && opt.parse_mode ? opt.parse_mode : 'HTML',
message_id: msg_id,
disable_web_page_preview: true,
reply_markup: {
resize_keyboard: true,
keyboard: await this.getKeyboard(id, menu, mylang),
keyboard_inline: (opt && opt.keyboard_inline) ? opt.keyboard_inline : undefined,
},
};
}
let inviato = false;
let risSendPhoto = null;
if (opt && opt.img) {
if (false) {
opt.img = 'https://riso.app/upload/profile/paoloar77/mybachecas/Fermentazione-Ruello-sito.png';
//opt.img = 'https://riso.app/upload/profile/paoloar77/mybachecas/Fermentazione-Ruello-sito.jpg';
// opt.img = 'https://riso.app/upload/profile/SoniaVioletFlame/myskills/1000133092.jpg';
}
opt.img = tools.fixUrl(opt.img, opt.idapp);
console.log('opt.img', opt.img)
risSendPhoto = await this.sendImageToTelegram(id, opt.img, { caption: text, ...form });
/*return this.bot.sendPhoto(id, opt.img, { caption: 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);
// ++Todo: DA FARE ! local_sendMsgTelegramToTheManagers(this.idapp, addtext + text);
}
return 0;
});*/
}
if (risSendPhoto) {
inviato = true;
}
if (!inviato) {
return 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);
// ++Todo: DA FARE ! local_sendMsgTelegramToTheManagers(this.idapp, addtext + text);
}
return 0;
});
}
return risSendPhoto
} catch (e) {
console.error(e, 'text', text);
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, img = '', opzioni = null) {
if (!id || !text)
return false;
try {
if (text.length > 4090) {
let text1 = text.slice(0, 4090);
let text2 = text.slice(4090, text.length);
await this._inviaMsg(id, text1, form, menu, msg_id, chat_id,
ripr_menuPrec, { img, ...opzioni });
return await this._inviaMsg(id, text2, form, menu, msg_id, chat_id,
ripr_menuPrec, { img, ...opzioni });
} else {
return await this._inviaMsg(id, text, form, menu, msg_id, chat_id,
ripr_menuPrec, { img, ...opzioni });
}
} catch (e) {
console.error('Error sendMsg', e);
return null;
}
}
async sendMsgLog(id, text, menu, form, msg_id, chat_id, ripr_menuPrec) {
const rec = this.getRecInMemById(id);
let username = rec ? rec.username_bo : '';
if (!username) {
}
console.log('Msg inviato a ', username, '(', id, ')', text);
return await this.sendMsg(id, text, menu, form, msg_id, chat_id, ripr_menuPrec);
}
getmenuKey(mymenu, lang) {
let mymenuout = null;
try {
mymenuout = mymenu[lang].menu;
} catch (e) {
if (!!mymenu['it'])
mymenuout = mymenu['it'].menu;
}
return mymenuout;
}
async setResetPwd(rec, msg) {
try {
if (rec.user) {
const idapp = this.idapp;
const username = rec.user.username;
const lang = rec.user.lang;
const link = await User.createNewRequestPwdByUsernameAndGetLink(idapp, username);
if (link) {
local_sendMsgTelegram(idapp, username, getstr(lang, 'MSG_RESETPWD') + '\n' + link);
}
}
} catch (e) {
console.error('Err', e);
}
}
async setPhotoProfile(user, telegid, showmsg = true) {
try {
console.log('setPhotoProfile', user ? user.username : '')
if (user) {
const idapp = this.idapp;
const bot = this.bot;
const username = user.username;
const lang = user.lang;
const token = this.token;
const editprofile = tools.getHostByIdApp(idapp, true) + '/editprofile';
let myfileprofile = tools.getdirByIdApp(idapp, true) +
server_constants.DIR_UPLOAD + '/profile/' + username + '/';
let user_profile = bot.getUserProfilePhotos(telegid);
user_profile.then(function (res) {
if (res.total_count === 0) {
// Non ho l'accesso oppure sono davvero senza foto !
}
if (res.photos[0]) {
var file_id = res.photos[0][2].file_id;
var file = bot.getFile(file_id);
file.then(function (result) {
const file_path = result.file_path;
const photo_url = 'https://api.telegram.org/file/bot' + token +
'/' + file_path;
// console.log('1) photo_url', photo_url);
let filename = tools.extractFileName(photo_url);
myfileprofile += filename;
const pathfile = tools.extractFilePath(myfileprofile);
tools.mkdirpath(pathfile);
// console.log('2) myfileprofile', pathfile);
return tools.downloadImage(photo_url, myfileprofile).
then((ris) => {
try {
let resized_img_small = tools.extractFilePath(myfileprofile) + '/' + server_constants.PREFIX_IMG_SMALL + filename;
// SMALL
// questa opzione 'failOnError' serve per risolvere l'errore (Error: VipsJpeg: Invalid SOS parameters for sequential JPEG
sharp(myfileprofile, { failOnError: false }).
resize(64, 64).
withMetadata().
toFile(resized_img_small);
} catch (e) {
console.error('setPhotoProfile sharp', e);
}
// console.log('3) setPicProfile ris', ris);
return User.setPicProfile(idapp, username, filename).
then((ris) => {
// console.log('4) sendMsg picprofile Copied !');
if (showmsg) {
local_sendMsgTelegram(idapp, username, printf(getstr(lang, 'MSG_SET_PICPROFILE'), editprofile));
}
});
// console.log('scaricato');
}).catch((err) => {
console.error('Error setPhotoProfile', err);
});
});
}
});
}
} catch (e) {
console.error('Error setPhotoProfile', e);
}
}
getInlineKeyboard(lang, arrrisp1, arrrisp2, arrrisp3) {
let mykeyb = {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [],
},
};
// text
// callback_data
// url
const arrriga1 = [];
if (!!arrrisp1) {
for (const ris of arrrisp1) {
arrriga1.push(ris);
}
}
const arrriga2 = [];
if (!!arrrisp2) {
for (const ris of arrrisp2) {
arrriga2.push(ris);
}
}
const arrriga3 = [];
if (!!arrrisp3) {
for (const ris of arrrisp3) {
arrriga3.push(ris);
}
}
if (arrriga1.length > 0)
mykeyb.reply_markup.inline_keyboard.push(arrriga1);
if (arrriga2.length > 0)
mykeyb.reply_markup.inline_keyboard.push(arrriga2);
if (arrriga3.length > 0)
mykeyb.reply_markup.inline_keyboard.push(arrriga3);
return mykeyb;
}
async ChiediSINO(msg, domanda) {
const lang = this.getlang(msg);
if (msg.forwardMessage && msg.chatId && msg.messageId) {
// Inoltra il messaggio alla stessa chat o ad un'altra
this.bot.forwardMessage(msg.chatId, msg.chatId, msg.messageId);
} else {
this._inviaMsg(msg.from.id, domanda, {
disable_web_page_preview: true,
reply_markup: {
resize_keyboard: true,
one_time_keyboard: true,
keyboard: this.getmenuKey(MenuYesNo, lang),
},
});
}
}
async ScegliLang(msg, lang) {
const rec = this.getRecInMem(msg);
if (rec) {
if (rec.user) {
User.SetLang(null, this.idapp, rec.user._id, lang);
rec.user.lang = lang;
}
rec.lang = lang;
// await this.sendMsg(msg.chat.id, lang);
this.msgScegliMenu(msg);
}
}
async msgScegliMenu(msg) {
this._inviaMsg(msg.from.id, getstr(this.getlang(msg), 'MSG_SCEGLI_MENU'), {
parse_mode: 'HTML',
disable_web_page_preview: true,
reply_markup: {
resize_keyboard: true,
keyboard: await this.getKeyboard(msg.from.id, undefined,
this.getlang(msg)),
},
});
}
}
const arrTelegram = [];
function getclTelegBytoken(token) {
const rec = arrTelegram.find((rec) => rec.cl.token === token);
if (!!rec)
return rec.cl;
else
return null;
}
// Funzione per ottenere il nome del gruppo
async function getGroupName(bot, groupId) {
try {
const chat = await bot.getChat(groupId);
return chat.title;
} catch (error) {
console.error('Errore durante l\'ottenimento del nome del gruppo:', error);
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() || true) {
if (true) {
let arrTeleg = MyTelegramBot.getAppTelegram();
var internetAvailable = require('internet-available');
internetAvailable().then(() => {
// ..
if (appTeleg_BotOnGroup.length > 0) {
console.log('TELEGRAM BOT GROUP .... ');
for (const idapp of appTeleg_BotOnGroup) {
const token = tools.getTelegramKeyByIdApp(idapp);
const nomebot = tools.getTelegramBotNameByIdApp(idapp);
if (token && nomebot) {
const bot = new TelegramBot(token, { polling: true });
// Gestisce il comando /start
bot.onText(/\/start/, (msg) => {
console.log('START BOT GROUP ... ');
/*
const chatId = msg.chat.id;
const message = 'Benvenuto! Usa il comando /request per inviare una richiesta di accesso al gruppo.';
bot.sendMessage(chatId, message);
*/
});
bot.onText(/\/request/, (msg) => {
const chatId = msg.chat.id;
const fromId = msg.from.id;
const fromUsername = msg.from.username;
const groupId = chatId;
if (chatId == groupId) {
const message = `Richiesta di accesso al gruppo da parte di ${msg.from.first_name} ${msg.from.last_name} (@${fromUsername})`;
bot.sendMessage(groupId, message);
} else {
console.log('Comando /request ricevuto in una chat privata.');
}
});
bot.on('text', (msg) => {
console.log('TEXT...');
const chatId = msg.chat.id;
const userName = msg.from.username || msg.from.first_name;
const userId = msg.from.id;
});
bot.on('new_chat_members', async (msg) => {
const chatId = msg.chat.id;
const newMembers = msg.new_chat_members;
const groupId = chatId;
const nomegruppo = await getGroupName(bot, groupId);
// Ottiene la lista degli amministratori del gruppo
const admins = await bot.getChatAdministrators(chatId);
// Trova l'ID dell'amministratore del gruppo
const adminId = admins.find(admin => admin.status === 'administrator').user.id;
// Verifica se il nuovo membro è stato aggiunto al gruppo
if (chatId == groupId) {
newMembers.forEach(async (member) => {
//const message = `🔑 Nuova Richiesta di accesso al gruppo ${nomegruppo} da parte di ${member.username} (` + member.first_name + ' ' + member.last_name + ')';
const message = `Benvenuto/a ${member.first_name} (${member.username}) sul gruppo "${nomegruppo}" !`;
bot.sendMessage(adminId, message);
// bot.sendMessage(groupId, message);
});
}
});
}
}
}
console.log('TELEGRAM STARTING.... ', process.env.NODE_ENV);
for (const idapp of arrTeleg) {
try {
const token = tools.getTelegramKeyByIdApp(idapp);
const nomebot = tools.getTelegramBotNameByIdApp(idapp);
// console.log('idapp', idapp, 'token', token);
if (!!token) {
console.log('-------------------------------------');
console.log('*** STARTING BOT ' + nomebot);
console.log('-------------------------------------');
const bot = new TelegramBot(token, { polling: true });
if (url === '0') {
const ngrok = require('ngrok');
ngrok.connect(port, function onConnect(error, u) {
if (error) throw error;
url = u;
console.log(`Game tunneled at ${url}`);
});
}
arrTelegram.push({ idapp, cl: new Telegram(idapp, bot) });
bot.onText(/\/start/, (msg) => {
console.log('*** BOT PARTITO CORRETTAMENTE !!! (Start Cmd)');
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', async (msg) => {
const myclTelegram = getclTelegBytoken(bot.token);
// const chatId = msg.chat.id;
myclTelegram.receiveMsg(msg);
});
// Handle callback queries
bot.on('callback_query', async (callbackQuery) => {
// console.log('callback_query', callbackQuery);
try {
const myclTelegram = getclTelegBytoken(bot.token);
let dataarr = [];
let data = {
action: '',
username: '',
userDest: '',
groupId: 0,
circuitId: '',
groupname: '',
};
const datastr = callbackQuery.data;
if (!!datastr) {
dataarr = datastr.split(tools.SEP);
if (!!dataarr) {
data = {
action: dataarr[0],
username: dataarr[1] ? dataarr[1] : '',
userDest: dataarr[2] ? dataarr[2] : '',
groupId: dataarr[3] ? parseInt(dataarr[3]) : '',
circuitId: dataarr[4] ? dataarr[4] : '',
groupname: dataarr[5] ? dataarr[5] : '',
};
}
}
const msg = callbackQuery.message;
const opts = {
chat_id: msg.chat.id,
message_id: msg.message_id,
};
const status = await myclTelegram.setInit(msg);
const rec = myclTelegram.getRecInMem(msg);
const username_action = rec.user ? rec.user.username : '';
data.username = await User.getRealUsernameByUsername(idapp, data.username);
data.userDest = await User.getRealUsernameByUsername(idapp, data.userDest);
const user = await User.getUserShortDataByUsername(idapp, data.username);
const userDest = data.userDest ? await User.getUserShortDataByUsername(idapp, data.userDest) : null;
let group = null;
let circuit = null;
if (data.groupId) {
group = await MyGroup.findOne({ idapp, _id: data.groupId }).lean();
}
if (data.circuitId) {
circuit = await Circuit.findOne({ idapp, _id: data.circuitId }).lean();
}
let cmd = 0;
if (!!rec) {
if (!!user) {
if (data.action === InlineCmd.VOGLIO_IMBARCARMI) {
// Controlla se è qualificato!
const mydata = tools.AddDate(user.date_reg, 7);
// bot.editMessageText(tools.gettranslate('ADDED_TOLISTAINGRESSO', user.lang), opts);
} else if (data.action === InlineCmd.NON_VOGLIO_IMBARCARMI) {
await User.NonVoglioImbarcarmi(user.idapp, user.username);
const msgadd = '[' + user.username + '] ' + user.name + ' ' +
user.surname + ' ha risposto che NON VUOLE IMBARCARSI !';
await local_sendMsgTelegramToTheManagers(user.idapp, msgadd,
msg, false); // Anche a STAFF
} else if (data.action ===
InlineZoomConferma.CONFERMA_ZOOM_PRESENZA) {
await User.setZoomPresenza(user.idapp, user._id, true);
} else if (data.action ===
InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA) {
await User.setZoomPresenza(user.idapp, user._id, false);
} else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.REGISTRATION) {
const changed = await myclTelegram.setCmdToUsername(rec,
data.username,
Cmd.VALIDATE_REGISTRATION, true);
if (changed) {
const req = tools.getReqByPar(user.idapp, username_action);
nomeapp = tools.getNomeAppByIdApp(user.idapp);
// await User.setFriendsCmd(req, user.idapp, data.username, userDest.username, shared_consts.FRIENDSCMD.SETFRIEND, null, true);
await User.setaportador_solidario(user.idapp, data.username, userDest.username);
const msgOrig = printf(getstr(userDest.lang, 'MSG_APORTADOR_DEST_CONFIRMED', nomeapp), `${userDest.username}`,
tools.getHostByIdApp(user.idapp));
const msgDest = printf(getstr(user.lang, 'MSG_APORTADOR_CONFIRMED'), `${user.username}`, `${userDest.username}`);
await local_sendMsgTelegram(user.idapp, data.username, msgOrig);
await local_sendMsgTelegram(user.idapp, data.userDest, msgDest);
// Invia questo msg anche all'Admin
await local_sendMsgTelegramToTheAdmin(user.idapp, msgDest, msg, data.userDest);
}
} else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.REGISTRATION) {
if (userDest.username === user.aportador_solidario) {
const changed = await myclTelegram.setCmdToUsername(rec, data.username,
Cmd.VALIDATE_REGISTRATION, false);
if (changed) {
const nomeDest = tools.getNomeCognomeEUserNameByUser(userDest);
const nomestr = tools.getNomeCognomeEUserNameByUser(user);
const msgOrig = printf(getstr(userDest.lang, 'MSG_APORTADOR_DEST_NOT_CONFIRMED', nomeDest));
const msgDest = printf(getstr(user.lang, 'MSG_APORTADOR_NOT_CONFIRMED'), nomestr);
await local_sendMsgTelegram(user.idapp, data.username, msgOrig);
await local_sendMsgTelegram(user.idapp, data.userDest, msgDest);
}
}
} else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_GRUPPO) {
if (group) {
cmd = shared_consts.GROUPSCMD.SETGROUP;
const foundIfAlreadyGroup = await User.ifAlreadyInGroup(user.idapp, data.username, group.groupname);
if (!foundIfAlreadyGroup) {
// Aggiungilo nel Gruppo
await User.setGroupsCmd(user.idapp, data.username, group.groupname, cmd, 0, username_action);
}
}
} else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_GRUPPO) {
if (group) {
cmd = shared_consts.GROUPSCMD.REFUSE_REQ_GROUP;
const foundIfAlreadyGroup = await User.ifAlreadyInGroup(user.idapp, data.username, group.groupname);
if (foundIfAlreadyGroup) {
// Rimuovilo nel Gruppo
await User.setGroupsCmd(user.idapp, data.username, group.groupname, cmd, 0, username_action);
}
}
} else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_FIDO) {
if (circuit) {
// Abiglitagli il Fido
cmd = shared_consts.CIRCUITCMD.SETFIDO;
await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, { groupname: data.groupname });
}
} else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_CIRCUIT) {
if (circuit) {
// Aggiungilo nel Circuito
cmd = shared_consts.CIRCUITCMD.SET;
await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, { groupname: data.groupname });
}
} else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_CIRCUIT) {
if (circuit) {
cmd = shared_consts.CIRCUITCMD.REFUSE_REQ;
let foundIfAlreadyCircuit = false;
if (data.groupname) {
foundIfAlreadyCircuit = await MyGroup.ifCircuitAlreadyInGroup(user.idapp, data.groupname, circuit.name);
} else {
foundIfAlreadyCircuit = await User.ifAlreadyInCircuit(user.idapp, data.username, circuit.name);
}
if (foundIfAlreadyCircuit) {
// Rimuovilo nel Circuito
await User.setCircuitCmd(user.idapp, data.username, circuit.name, cmd, 0, username_action, { groupname: data.groupname });
}
}
} else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_AMICIZIA) {
if (userDest) {
cmd = shared_consts.FRIENDSCMD.SETFRIEND;
const foundIfAlreadyFriend = await User.isMyFriend(user.idapp, data.username, data.userDest);
if (!foundIfAlreadyFriend) {
// Aggiungilo nelle Amicizie
const req = tools.getReqByPar(user.idapp, username_action);
const ris = await User.setFriendsCmd(req, user.idapp, data.username, data.userDest, cmd);
}
}
} else if (data.action === InlineConferma.RISPOSTA_NO + shared_consts.CallFunz.RICHIESTA_AMICIZIA) {
if (userDest) {
cmd = shared_consts.FRIENDSCMD.REMOVE_FROM_MYFRIENDS;
// Rimuovilo nelle Amicizie
const req = tools.getReqByPar(user.idapp, username_action);
const ris = await User.setFriendsCmd(req, user.idapp, data.username, data.userDest, cmd);
if (ris) {
const msgDest = printf(getstr(user.lang, 'MSG_FRIENDS_NOT_ACCEPTED_CONFIRMED'), data.username);
await local_sendMsgTelegram(user.idapp, data.userDest, msgDest);
}
}
} else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_HANDSHAKE) {
if (userDest) {
cmd = shared_consts.FRIENDSCMD.SETHANDSHAKE;
const foundIfAlreadyFriend = await User.isMyHandShake(user.idapp, data.userDest, data.username);
if (!foundIfAlreadyFriend) {
// Aggiungilo nelle HandShake
const req = tools.getReqByPar(user.idapp, username_action);
const ris = await User.setFriendsCmd(req, user.idapp, data.userDest, data.username, cmd);
}
}
}
} else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.ENTRA_RIS_ITALIA) {
url = '';
bot.answerCallbackQuery(callbackQuery.id, { url });
}
}
} catch (e) {
console.error('Error BOT callback_query', e);
}
/*
let text;
if (action === 'edit') {
text = 'Edited Text';
}
bot.editMessageText(text, opts);
*/
// bot.answerCallbackQuery(callbackQuery.id, { url });
});
}
} catch (e) {
console.error('Error Telegram LOOP : ' + e.message);
}
}
}).catch((e) => {
arrTeleg = [];
console.error('Error internetAvailable:' + e);
});
}
module.exports = MyTelegramBot;