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

4683 lines
163 KiB
JavaScript
Raw Normal View History

const tools = require('../tools/general');
const appTelegram = [tools.FREEPLANET, tools.RISO];
2023-02-15 21:40:19 +01:00
const appTelegram_TEST = [tools.FREEPLANET, tools.RISO];
//const appTelegram_DEVELOP = [tools.RISO];
const appTelegram_DEVELOP = [tools.PIUCHEBUONO];
const appTelegramFinti = ['2', tools.CNM];
2023-02-15 21:40:19 +01:00
const appTelegramDest = [tools.FREEPLANET, tools.FREEPLANET];
const appTeleg_BotOnGroup = [tools.IDAPP_BOTONGROUP];
2025-08-09 00:48:50 +02:00
const path = require('path');
const fs = require('fs');
2023-11-23 16:06:20 +01:00
//PIPPO
const printf = require('util').format;
const { User, FuncUsers } = require('../models/user');
2023-01-03 16:51:32 +01:00
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');
2022-02-03 00:33:15 +01:00
// const {ListaIngresso} = require('../models/listaingresso');
2023-01-03 16:51:32 +01:00
const { MsgTemplate } = require('../models/msg_template');
const i18n = require('i18n');
let url = process.env.URL || 'https://<PUBLIC-URL>';
const Benvenuto = '💓💓💓 Benvenuto/a!';
const emo = {
JOY: '😂',
JOY2: '🤣',
DANCER: '💃',
STARS: '✨',
FIRE: '🔥',
SUN: '☀️',
TV: '📺',
NEWSPAPER: '🗞',
KISS: '😘',
PENCIL: '✏️',
DREAM: '🏖',
EYES: '😜',
DIZZY: '💫',
ONE_HUNDRED: '💯',
SMILE_STAR: '🤩', // Star-struck
LEFT_FACING_FIST: '🤛', // Left-facing fist
CHECK_VERDE: '✅', // White check mark (verde)
CHECK_GRIGIA: '☑️', // Ballot box with check (grigia)
CROSS_ROSSA: '❌', // X (rossa)
ENVELOPE: '✉️', // Envelope
EXCLAMATION_MARK: '❗', // Exclamation mark
QUESTION_MARK: '❓', // Question mark
ARROW_RIGHT: '➡️', // Arrow pointing to the right
INVITATI: '',
HEART: '❤️',
BLUE_HEART: '💙',
GREEN_HEART: '💚',
YELLOW_HEART: '💛',
PURPLE_HEART: '💜',
GIFT_HEART: '💝',
GIFT: '🎁',
ROBOT_FACE: '🤖',
ADMIN: '💁',
MALE: '💁‍♂️',
FEMALE: '👩‍🦱',
INNOCENT: '😇',
CREDIT_CARD: '💳',
PERSON: '🧑',
};
MsgBot = {
2022-03-10 23:19:56 +01:00
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'],
};
2021-12-29 18:26:08 +01:00
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 '0⃣'; // zero
} else if (number === 1) {
return '1⃣'; // one
} else if (number === 2) {
return '2⃣'; // two
} else if (number === 3) {
return '3⃣'; // three
} else if (number === 4) {
return '4⃣'; // four
} else if (number === 5) {
return '5⃣'; // five
} else if (number === 6) {
return '6⃣'; // six
} else if (number === 7) {
return '7⃣'; // seven
} else if (number === 8) {
return '8⃣'; // eight
} else if (number === 9) {
return '9⃣'; // nine
} else {
return number;
}
}
const Menu = {
LANG_IT: '🇮🇹 Italiano', // Bandiera italiana
LANG_EN: '🇬🇧 English', // Bandiera del Regno Unito
LANG_ES: '🇪🇸 Español', // Bandiera spagnola
LANG_FR: '🇫🇷 Français', // Bandiera francese
LANG_SI: '🇸🇮 Slovenski', // Bandiera slovena
LANG_PT: '🇵🇹 Português', // Bandiera portoghese
LANG: '🌐 Language', // Globo con meridiani
CHAT_PERSONALE: '👩‍💼💻', // Donna impiegata + computer
2020-03-31 20:34:24 +02:00
EXIT_TELEGRAM: 'exittotelegram',
MSG_TO_USER: 'sendmsgto',
ADMIN: '💁‍♀️ Admin', // Persona al banco informazioni
AIUTO: '🔮 Help', // Cristallo magico
ALTRO: '📰 Altro', // Giornale
SETPICPROFILE: '🖼 SetPicProfile', // Cornice con foto
RESETPWD: '🔑 SetResetPwd', // Chiave
MSG_SI_INVITATI_NO_7REQ_INVITATI: '📩Inv e NO 7 Req', // Busta
MSGSTAFF: '📩 Invia a STAFF', // Busta
MSGAPPARTIENE_CIRCUITI_RIS: 'Invia a Utenti dei Circuiti RIS',
MSGPAOLO: '📩 Invia a SURYA', // Busta
RESTART_SRV: '📩Restart-NodeJs', // Busta
REBOOT_SRV: '📩Reboot-VPS!', // Busta
EXECSH: '📩ExecSH', // Busta
LOG_SRV: '🖥Logserver.sh', // Monitor
MSGATUTTI: '📩 Invia a TUTTI', // Busta
2020-03-31 20:34:24 +02:00
it: {
ACCEDI: '👤 Accedi', // Persona
LAVAGNA: '🕉 Lavagna', // Simbolo Om
LINK_CONDIVIDERE: '🔗 Link da condividere', // Link
ZOOM: ' Zoom (Conferenze)', // Informazione
INFO: ' Informazioni', // Informazione
ASSISTENZA: '👐 Le Chat', // Mani aperte
INDIETRO: '🔙 Indietro', // Freccia indietro
SI: '👍 SI', // Pollice su
NO: '👎 NO', // Pollice giù
ESCI_DA_CHAT: '📩 Esci dalla Conversazione', // Busta
NUOVOSITO: '',
2020-03-31 20:34:24 +02:00
},
es: {
ACCEDI: '👤 Entra',
LAVAGNA: '🕉 Tablero',
LINK_CONDIVIDERE: '🔗 Enlaces para compartir',
ZOOM: ' Zoom (Conferencias)',
INFO: ' Información',
ASSISTENZA: '👐 Chats',
INDIETRO: '🔙 Volver',
SI: '👍 SÍ',
NO: '👎 NO',
ESCI_DA_CHAT: '📩 Salir de la conversación',
2020-03-31 20:34:24 +02:00
},
fr: {
ACCEDI: '👤 Entrez',
LAVAGNA: '🕉 Tableau de bord',
LINK_CONDIVIDERE: '🔗 Liens à partager',
ZOOM: ' Zoom (Conférences)',
INFO: ' Informations',
ASSISTENZA: '👐 Les chats',
INDIETRO: '🔙 Retour',
SI: '👍 OUI',
NO: '👎 NON',
ESCI_DA_CHAT: '📩 Quitter la conversation',
2020-03-31 20:34:24 +02:00
},
si: {
ACCEDI: '👤 Prijava',
LAVAGNA: '🕉 Tabla',
LINK_CONDIVIDERE: '🔗 Link za vpis oseb',
ZOOM: ' Zoom (Konference)',
INFO: ' Informacije',
ASSISTENZA: '👐 jev klepet',
INDIETRO: '🔙 Nazaj',
SI: '👍 DA',
NO: '👎 NE',
ESCI_DA_CHAT: '📩 Zaprite pogovor',
2020-03-31 20:34:24 +02:00
},
pt: {
ACCEDI: '👤 Entre',
LAVAGNA: '🕉 Tablero',
LINK_CONDIVIDERE: '🔗 Links para compartilhar',
ZOOM: ' Zoom (Conferências)',
INFO: ' Informações',
ASSISTENZA: '👐 Chats',
INDIETRO: '🔙 Voltar',
SI: '👍 SIM',
NO: '👎 NÃO',
ESCI_DA_CHAT: '📩 Sair da Conversa',
2020-03-31 20:34:24 +02:00
},
enUs: {
ACCEDI: '👤 Enter',
LAVAGNA: '🕉 DashBoard',
LINK_CONDIVIDERE: '🔗 Link to Share',
ZOOM: ' Zoom (Conference)',
INFO: ' Info',
ASSISTENZA: '👐 Chats',
INDIETRO: '🔙 Back',
SI: '👍 YES',
NO: '👎 NO',
ESCI_DA_CHAT: '📩 Exit to the Conversation',
2020-03-31 20:34:24 +02:00
},
};
const CONTA_SOLO = 'contasolo';
const RICEVI_EMAIL = 'riceviemail';
const NOME_COGNOME = 'nomecognome';
const CHEDI_SE_IMBARCARTI = 'chiedi_se_imbarcarti';
const InlineCmd = {
2020-09-04 00:06:49 +02:00
VOGLIO_IMBARCARMI: 'w_imb',
NON_VOGLIO_IMBARCARMI: 'nw_imb',
2020-09-04 00:06:49 +02:00
};
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]] },
// };
2020-03-31 20:34:24 +02:00
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],
],
},
2020-03-31 20:34:24 +02:00
};
const MenuYesNo = {
2023-01-03 16:51:32 +01:00
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]] },
2020-03-31 20:34:24 +02:00
};
const MenuAdmin = {
it: {
menu: [
[Menu.RESTART_SRV + ' 6711', Menu.LOG_SRV + ' 6711'],
[Menu.REBOOT_SRV + ' 6711', Menu.it.INDIETRO],
],
},
2020-03-31 20:34:24 +02:00
};
const MenuSend = {
it: {
menu: [
[CONTA_SOLO, RICEVI_EMAIL, NOME_COGNOME],
[CHEDI_SE_IMBARCARTI, Menu.it.INDIETRO],
],
},
2020-03-31 20:34:24 +02:00
};
const MenuChat = {
2023-01-03 16:51:32 +01:00
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]] },
2020-03-31 20:34:24 +02:00
};
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,
};
2021-12-29 18:26:08 +01:00
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,
2021-12-29 18:26:08 +01:00
DOMANDA: 10,
RISPOSTA: 11,
APPARTIENE_CIRCUITO_RIS: 20,
};
const StatusMSGALL = {
NONE: 0,
ASK: 1,
CONFIRM: 2,
};
const txt = {
MSG_SCEGLI_MENU: '💫' + ' Scegli una voce di menu:' + '💫',
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 Surya (@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 +
2023-01-03 16:51:32 +01:00
'\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:',
2020-01-03 22:02:18 +01:00
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 su %s 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 !',
2023-01-08 02:17:01 +01:00
MSG_HANDSHAKE_NOT_ACCEPTED_CONFIRMED: '🚫 Hai rifiutato la richiesta di Stretta di mano di %s !',
2024-10-22 15:26:29 +02:00
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 +
2023-01-03 16:51:32 +01:00
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.<br>Contattalo per farti abilitare !',
2024-10-22 15:26:29 +02:00
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !',
2022-10-29 17:05:59 +02:00
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: '📨' + ' Messaggi Inviati !',
MSG_MSG_TOSENT: '📨' + ' Messaggi da Inviare',
MSG_MSG_INCORSO: '📨' + ' messaggi in corso... Inviati attualmente',
MSG_SET_USERNAME_TELEGRAM:
'[Prima di continuare con la registrazione in RISO.APP]\n' +
2023-01-03 16:51:32 +01:00
'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" +
2023-01-03 16:51:32 +01:00
'🏁 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:',
};
2020-03-31 20:34:24 +02:00
const txt_es = {
MSG_SCEGLI_MENU: '💫' + ' Elija un elemento del menú:' + '💫',
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:',
2020-03-31 20:34:24 +02:00
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.:',
2020-03-31 20:34:24 +02:00
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!' +
2023-01-03 16:51:32 +01:00
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)',
2020-03-31 20:34:24 +02:00
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 si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
2024-10-22 15:26:29 +02:00
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 +
2023-01-03 16:51:32 +01:00
'🚫 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: '📨' + ' Mensajes enviados !',
MSG_MSG_TOSENT: '📨' + ' Mensajes a enviar',
MSG_MSG_INCORSO: '📨' + ' mensajes en progreso... Enviado actualmente',
2020-03-31 20:34:24 +02:00
};
const txt_fr = {
MSG_SCEGLI_MENU: '💫' + 'Choisissez un élément de menu:' + '💫',
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: ",
2020-03-31 20:34:24 +02:00
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: ",
2020-03-31 20:34:24 +02:00
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!' +
2023-01-03 16:51:32 +01:00
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 si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
2024-10-22 15:26:29 +02:00
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 +
2023-01-03 16:51:32 +01:00
'🚫 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: '📨' + ' Messages envoyés !',
MSG_MSG_TOSENT: '📨' + ' Messages à envoyer',
MSG_MSG_INCORSO: '📨' + ' messages en cours... Actuellement envoyé',
2020-03-31 20:34:24 +02:00
};
const txt_si = {
MSG_SCEGLI_MENU: '💫' + 'Izbirni meni:' + '💫',
2020-04-24 10:29:25 +02:00
MSG_ASK_USERNAME_BO: 'Vpiši svoje uporabniško ime in e-naslov s katerimi si se registriral na spletni strani %s: ',
2020-03-31 20:34:24 +02:00
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: ',
2020-03-31 20:34:24 +02:00
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)',
2020-03-31 20:34:24 +02:00
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 si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
2024-10-22 15:26:29 +02:00
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 +
2023-01-03 16:51:32 +01:00
'🚫 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 !',
2020-03-31 20:34:24 +02:00
};
const txt_en = {
MSG_SCEGLI_MENU: '💫' + ' Choose a menu item:' + '💫',
2020-03-31 20:34:24 +02:00
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:',
2020-03-31 20:34:24 +02:00
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' +
2023-01-03 16:51:32 +01:00
'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)',
2020-03-31 20:34:24 +02:00
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 si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
2024-10-22 15:26:29 +02:00
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 +
2023-01-03 16:51:32 +01:00
'🚫 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: '📨' + ' Sent Messages !',
MSG_MSG_TOSENT: '📨' + ' Messages to Send',
MSG_MSG_INCORSO: '📨' + ' messages in progress... Currently sent',
2020-03-31 20:34:24 +02:00
};
const txt_pt = {
MSG_SCEGLI_MENU: '💫' + ' Escolha um item do menu:' + '💫',
2020-03-31 20:34:24 +02:00
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:',
2020-03-31 20:34:24 +02:00
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!' +
2023-01-03 16:51:32 +01:00
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)',
2020-03-31 20:34:24 +02:00
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 si sta registrando su %s e ti chiede di poter entrare. Confermi di conoscerla ?',
MSG_ACCEPT_NEWENTRY_INGROUP: '❇️👥 🧍‍♂️ Accetta Ingresso nel GRUPPO %s:',
2024-10-22 15:26:29 +02:00
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 +
2023-01-03 16:51:32 +01:00
'🚫 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: '📨' + ' Mensagens Enviadas !',
MSG_MSG_TOSENT: '📨' + ' Mensagens a enviar',
MSG_MSG_INCORSO: '📨' + ' mensagens em progresso... Actualmente enviado',
2020-03-31 20:34:24 +02:00
};
const TelegramBot = require('node-telegram-bot-api');
const ADMIN_IDTELEGRAM_TEST = 5356627050; // 5022837609; //Surya A.
2021-12-29 18:26:08 +01:00
const MyTelegramBot = {
ADMIN_IDTELEGRAM_SERVER: '12429864', //Paolo
ADMIN_USERNAME_TELEGRAM: 'surya1977', //Paolo
2020-01-03 22:02:18 +01:00
ADMIN_USER_NAME_SERVER: 'Paolo',
phase: {
REGISTRATION: 1,
ISCRIZIONE_CONACREIS: 2,
2022-10-29 12:37:50 +02:00
ISCRIZIONE_ARCADEI: 4,
2020-01-03 22:02:18 +01:00
},
2023-01-03 16:51:32 +01:00
getAppTelegram: function () {
if (process.env.appTelegram) {
2023-12-17 19:19:04 +01:00
arrTeleg = JSON.parse(process.env.appTelegram);
} else {
2023-12-17 19:19:04 +01:00
arrTeleg = appTelegram;
}
2024-02-06 20:12:54 +01:00
if (process.env.NODE_ENV === 'development') {
arrTeleg = MyTelegramBot.getAppTelegramDevelop();
2024-02-06 20:12:54 +01:00
} else if (process.env.NODE_ENV === 'test') {
2023-12-17 19:19:04 +01:00
arrTeleg = MyTelegramBot.getAppTelegramTest();
2024-02-06 20:12:54 +01:00
} else {
const arrTelegFromSite = tools.getArrTelegramFromSite();
if (arrTelegFromSite.length > 0) {
arrTeleg = arrTelegFromSite;
}
2023-12-17 19:19:04 +01:00
}
2023-12-17 19:19:04 +01:00
return arrTeleg;
},
getAppTelegramTest: function () {
if (process.env.appTelegram_TEST) {
return JSON.parse(process.env.appTelegram_TEST);
} else {
return appTelegram_TEST;
}
2022-03-12 21:38:19 +01:00
},
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: '' };
},
2023-01-03 16:51:32 +01:00
deleteRecInMemByUsername: function (idapp, username_bo) {
const cl = getclTelegByidapp(idapp);
if (cl) {
cl.arrUsers = cl.arrUsers.filter((rec) => rec.username_bo !== username_bo);
}
},
2023-01-03 16:51:32 +01:00
getFormDaMostrare: function (idapp, myfunc, myuser) {
let FormDaMostrare = null;
2020-09-04 00:06:49 +02:00
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,
2020-09-04 00:06:49 +02:00
},
{
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,
2020-09-04 00:06:49 +02:00
},
]);
}
return FormDaMostrare;
},
getclTelegByidapp: function (idapp) {
const cl = getclTelegByidapp(idapp);
return cl;
},
2023-01-03 16:51:32 +01:00
getCiao: function (idapp, username, lang) {
return tools.gettranslate('CIAO', lang) + ' ' + username + '!\n';
},
2023-01-03 16:51:32 +01:00
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);
}
}
2020-01-03 22:02:18 +01:00
let addtext = '';
let rismsg = null;
2021-12-29 18:26:08 +01:00
if (text) {
await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, addtext + text, false, null);
}
} catch (e) {
console.error('Err notifyToTelegram', e);
}
2020-01-03 22:02:18 +01:00
},
2023-01-03 16:51:32 +01:00
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;
2023-12-02 15:23:35 +01:00
if (!userDest) {
userDest = myuser.username;
}
let userrecDest = await User.getUserShortDataByUsername(idapp, userDest);
let userId = userrecDest._id;
2023-12-02 15:23:35 +01:00
let title = tools.getNomeAppByIdApp(idapp);
let keyb = null;
2023-12-02 15:23:35 +01:00
let openUrl = '';
let domanda = '';
2023-12-02 15:23:35 +01:00
let msg_notifpush = '';
let send_notif = false;
let actions = [];
2023-12-02 15:23:35 +01:00
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 &&
useraportador.tokenreg &&
regexpire &&
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, nomeapp);
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,
},
2023-06-05 16:36:00 +02:00
/*{
text: '🚫 Rifiuta ' + myuser.username,
callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + userDest,
2023-06-05 16:36:00 +02:00
}, */
]);
}
send_notif = true;
} else if (myfunc === shared_consts.CallFunz.RICHIESTA_GRUPPO) {
2023-12-02 15:23:35 +01:00
msg_notifpush = printf(getstr(langdest, 'MSG_ACCEPT_NEWENTRY_INGROUP'), name);
2023-01-12 01:03:10 +01:00
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) {
2023-01-03 16:51:32 +01:00
if (groupname) {
2023-12-02 15:23:35 +01:00
msg_notifpush = i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP', locale: langdest }, groupname);
domanda =
i18n.__({ phrase: 'CIRCUIT_ACCEPT_NEWENTRY_BYGROUP', locale: langdest }, groupname) +
'<br>' +
struserinfomsg;
2023-01-03 16:51:32 +01:00
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,
2023-01-03 16:51:32 +01:00
},
/*{
2023-01-03 16:51:32 +01:00
text: '🚫 Rifiuta ' + groupname,
callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
groupid + tools.SEP + groupname,
},*/
2023-01-03 16:51:32 +01:00
]);
send_notif = true;
2023-01-03 16:51:32 +01:00
} else {
2023-12-02 15:23:35 +01:00
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;
2023-01-03 16:51:32 +01:00
2023-12-02 15:23:35 +01:00
keyb = cl.getInlineKeyboard(myuser.lang, [
2023-01-03 16:51:32 +01:00
{
text: '✅ Abilita fiducia a ' + myuser.username,
callback_data:
InlineConferma.RISPOSTA_SI +
myfunc +
tools.SEP +
myuser.username +
tools.SEP +
'' +
tools.SEP +
'' +
tools.SEP +
groupid,
2023-01-03 16:51:32 +01:00
},
/*{
2023-01-03 16:51:32 +01:00
text: '🚫 Rifiuta ' + myuser.username,
callback_data: InlineConferma.RISPOSTA_NO + myfunc + tools.SEP + myuser.username + tools.SEP + '' + tools.SEP + '' + tools.SEP +
groupid,
}, */
2023-01-03 16:51:32 +01:00
]);
send_notif = true;
2023-01-03 16:51:32 +01:00
}
} 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);
}
2023-12-02 15:23:35 +01:00
if (send_notif && msg_notifpush) {
// SEND PUSH NOTIFICATION
2023-12-17 16:20:44 +01:00
await tools.sendNotificationToUser(userId, title, msg_notifpush, openUrl, '', tag, actions);
2023-12-02 15:23:35 +01:00
}
} catch (e) {
console.error('Error askConfirmationUser', e);
}
},
2023-01-03 16:51:32 +01:00
askConfirmationUserFriend: async function (idapp, myfunc, myuser, userDest = '', username = '') {
try {
const cl = getclTelegByidapp(idapp);
if (!cl) return false;
2023-01-03 16:51:32 +01:00
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 = {};
2023-01-08 19:20:02 +01:00
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;
2023-01-03 16:51:32 +01:00
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 + '',
},
]);
2023-01-06 15:51:48 +01:00
} else if (myfunc === shared_consts.CallFunz.RICHIESTA_HANDSHAKE) {
sendnotif = true;
typedir = shared_consts.TypeNotifs.TYPEDIR_HANDSHAKE;
typeid = shared_consts.TypeNotifs.ID_HANDSHAKE_ACCEPTED;
2023-01-06 15:51:48 +01:00
paramsObj = { usernameDest: userDest };
domanda =
printf(tools.gettranslate('RICHIESTA_HANDSHAKE', langdest), myuser.username) + '<br>' + struserinfomsg;
2023-01-06 15:51:48 +01:00
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 + '',
2023-01-06 15:51:48 +01:00
},
]);
}
// 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) {
2022-09-14 11:32:04 +02:00
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);
2020-05-10 21:07:51 +02:00
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);
}
2020-09-04 00:06:49 +02:00
}
}
}
return true;
2020-09-04 00:06:49 +02:00
},
sendMsgTelegramToTheAdminsOfCircuit: async function (
idapp,
circuitpath,
text,
onlyintofile = false,
MyForm = null,
nottousername = ''
) {
tools.writeManagersLog(text);
let teleg_id = 0;
2020-09-04 00:06:49 +02:00
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);
}
}
2020-05-10 21:07:51 +02:00
}
}
2020-01-03 22:02:18 +01:00
}
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);
}
2020-01-03 22:02:18 +01:00
}
},
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;
}
2020-04-07 14:34:29 +02:00
}
}
2020-01-03 22:02:18 +01:00
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);
}
},
2021-12-29 18:26:08 +01:00
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 {
2025-08-09 00:48:50 +02:00
const globalTables = require('../tools/globalTables');
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);
},
2020-01-03 22:02:18 +01:00
};
async function setVerifiedReg(idapp, lang, usernameorig, usernameDest) {
try {
await User.setVerifiedByAportador(idapp, usernameorig, true);
2023-01-12 01:03:10 +01:00
// 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;
2022-12-09 03:09:08 +01:00
if (cl && teleg_id > 0) {
ris = await cl.sendMsg(teleg_id, text);
}
return ris;
}
function getstr(lang, key, ...params) {
2020-03-31 20:34:24 +02:00
let mystr = '';
if (lang === 'si' || lang === 'sl-si') {
2020-03-31 20:34:24 +02:00
try {
mystr = txt_si[key];
2020-03-31 20:34:24 +02:00
} catch (e) {
mystr = '';
}
} else if (lang === 'en' || lang === 'enUs') {
2020-03-31 20:34:24 +02:00
try {
mystr = txt_en[key];
2020-03-31 20:34:24 +02:00
} catch (e) {
mystr = '';
}
} else if (lang === 'es') {
try {
mystr = txt_es[key];
2020-03-31 20:34:24 +02:00
} catch (e) {
mystr = '';
}
} else if (lang === 'fr') {
try {
mystr = txt_fr[key];
2020-03-31 20:34:24 +02:00
} catch (e) {
mystr = '';
}
} else if (lang === 'pt') {
try {
mystr = txt_pt[key];
2020-03-31 20:34:24 +02:00
} catch (e) {
mystr = '';
}
}
if (!mystr || mystr === '') mystr = txt[key];
2020-04-24 10:29:25 +02:00
if (params.length > 0) {
mystr = printf(mystr, ...params);
2020-04-24 10:29:25 +02:00
}
return mystr;
}
class Telegram {
constructor(idapp, bot) {
this.idapp = idapp;
this.bot = bot;
this.token = bot.token;
this.arrUsers = [];
this.lastid = 0;
2021-12-29 18:26:08 +01:00
//++
}
async createIfNotExist(msg) {
if (!(await this.alreadyExist(msg))) {
if (await this.insertIntoDB(msg)) {
let rec = this.getRecInMem(msg);
2020-03-31 20:34:24 +02:00
if (!!rec) {
if (rec.user) rec.status = Status.VERIFIED;
2020-03-31 20:34:24 +02:00
} else {
return false;
2020-03-31 20:34:24 +02:00
}
}
return true;
} else {
return false;
}
}
async settotheDatabase(msg) {
// Check if Present to the DB
2020-03-31 20:34:24 +02:00
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);
}
2020-05-11 22:43:14 +02:00
geturlfaq() {
return tools.getHostByIdApp(this.idapp) + '/faq';
2020-05-11 22:43:14 +02:00
}
getstrChatHelp() {
return (
'Clicca qui per entrare nella Chat HELP di Supporto\n' +
2023-01-03 16:51:32 +01:00
tools.getTelegramSupportChat(this.idapp) +
'\n\nI miei colleghi umani ti aiuteranno a risolvere !'
);
}
async IsTesto(msg) {
let risp = '';
const id = msg.chat.id;
2025-02-25 18:13:01 +01:00
let testo = msg.text?.toLowerCase()?.trim();
testo = testo.replace('!', '');
testo = testo.replace('?', '');
testo = testo.replace('é', 'è');
let contastiera = false;
let noanswer = false;
2021-12-29 18:26:08 +01:00
let lang = 'it';
const rec = this.getRecInMem(msg);
let myname = '';
if (rec.user) {
myname = rec.user.username;
2021-12-29 18:26:08 +01:00
lang = rec.user.lang;
}
if (rec.statusmsg === Status.WAITFOR_RISPOSTA) {
if (rec.msgcodeprec === MsgBot.COME_STAI) {
risp =
"L'importante è trovare Serenità dentro di noi" +
2023-01-03 16:51:32 +01:00
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 = '';
2021-12-29 18:26:08 +01:00
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 === '') {
2021-12-29 18:26:08 +01:00
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);
2021-12-29 18:26:08 +01:00
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! ' + '💓' + ' 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';
2020-05-10 21:07:51 +02:00
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;
2025-02-25 18:13:01 +01:00
risp += 'Invitato da ' + rec.user.aportador_solidario + tools.ACAPO;
risp += 'Username Telegram ' + rec.user.profile.username_telegram + tools.ACAPO;
risp += 'Telegram ID ' + rec.user.profile.teleg_id + 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. ' +
2023-01-03 16:51:32 +01:00
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;
2022-03-10 23:19:56 +01:00
} 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." +
2023-01-03 16:51:32 +01:00
'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." +
2023-01-03 16:51:32 +01:00
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 +
2023-01-03 16:51:32 +01:00
'\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 +
2023-01-03 16:51:32 +01:00
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;
2022-03-10 23:19:56 +01:00
} 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;
2020-03-25 09:25:31 +01:00
} else if (testo.length >= 10) {
noanswer = true;
2020-05-11 22:43:14 +02:00
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, cliccando sul bottone in basso, con 4 quadratini dentro\n' +
'\nPer <strong>AIUTO</strong>, clicca qui:\n👉🏻👉🏻<a href="' +
myfaq +
2023-01-03 16:51:32 +01:00
'">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);
2020-05-11 22:43:14 +02:00
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) {
2022-03-10 23:19:56 +01:00
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 });
2021-12-29 18:26:08 +01:00
let strlog = 'USER [' + myname + ']: ' + testo + '\n';
tools.writelog(strlog);
}
return risp !== '';
}
async isMenuNotVerified(rec, msg, notlast) {
2020-03-31 20:34:24 +02:00
if (this.isSelMenu(msg, msg.text, 'ASSISTENZA')) {
await this.menuAssistenza(msg);
2020-03-31 20:34:24 +02:00
} 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);
2020-03-31 20:34:24 +02:00
} 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);
}
}
2020-03-31 20:34:24 +02:00
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;
2020-03-31 20:34:24 +02:00
}
async isMenu(rec, msg, testo, notlast) {
2022-03-12 21:38:19 +01:00
try {
if (!msg) return;
if (testo === undefined) return;
2022-03-12 21:38:19 +01:00
const arrtext = testo.split(' ');
let cmd2 = '';
let cmd1 = arrtext[0];
if (arrtext.length > 1) cmd2 = arrtext[1];
2022-03-12 21:38:19 +01:00
let oldusername = rec.msgall_username_specifico;
if (this.isSelMenu(msg, testo, 'ESCI_DA_CHAT') || this.isSelMenu(msg, testo, 'INDIETRO')) {
2022-03-12 21:38:19 +01:00
rec.msgall_username_specifico = '';
} else {
if (rec.msgall_username_specifico !== '') {
await this.SendMsgToUser(msg, rec, rec.msgall_username_specifico, testo);
2022-03-12 21:38:19 +01:00
return true;
}
}
if (this.isSelMenu(msg, testo, 'LAVAGNA') || MsgBot.LAVAGNA.find((rec) => testo.indexOf(rec) > -1)) {
2022-03-12 21:38:19 +01:00
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);
2022-03-12 21:38:19 +01:00
} else if (testo === Menu.MSGPAOLO) {
await this.menumsgPaolo(msg);
} else if (cmd1 === Menu.EXECSH) {
if (rec.user && cmd2) {
2023-12-29 15:19:15 +01:00
let isAdmin = rec.user ? rec.user.profile.admin_telegram : false;
2022-03-12 21:38:19 +01:00
if (isAdmin) {
const ris = await tools.execScriptByTelegram(this.idapp, msg, cmd2, 'Eseguo lo script');
2022-03-12 21:38:19 +01:00
}
}
} else if (cmd1 === Menu.LOG_SRV) {
if (rec.user) {
2023-12-29 15:19:15 +01:00
let isAdmin = rec.user ? rec.user.profile.admin_telegram : false;
2022-03-12 21:38:19 +01:00
if (isAdmin) {
await this.menuLogSrv(rec, msg, cmd2);
}
}
} else if (cmd1 === Menu.REBOOT_SRV) {
if (rec.user) {
2023-12-29 15:19:15 +01:00
let isAdmin = rec.user ? rec.user.profile.admin_telegram : false;
2022-03-12 21:38:19 +01:00
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);
2025-02-05 12:13:27 +01:00
} else if (cmd1 && cmd1.toLowerCase() === Menu.MSG_TO_USER) {
2022-03-12 21:38:19 +01:00
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) {
2022-03-12 21:38:19 +01:00
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) {
2020-07-13 23:35:05 +02:00
/*if (user.profile.paymenttypes.includes('paypal')) {
if (user.profile.email_paypal) {
ispaypal = true
}
2020-07-13 23:35:05 +02:00
}*/
if (!!user.profile)
if (!!user.profile.paymenttypes) {
return user.profile.paymenttypes.length >= 1;
}
}
}
return false;
}
async menuAccedi(msg) {
let status = this.getstatusInMemory(msg);
2020-03-31 20:34:24 +02:00
}
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;
2020-03-31 20:34:24 +02:00
else {
return msg.from.language_code;
2020-03-31 20:34:24 +02:00
}
}
}
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;
2020-03-25 09:25:31 +01:00
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);
2020-03-25 09:25:31 +01:00
if (mystrnave === '' && tuttie9) {
mystr += tools.gettranslate('NO_PROG', user.lang);
}
2020-03-25 09:25:31 +01:00
if (!!mystrnave) {
2020-03-31 20:34:24 +02:00
mystr += '✨✨✨' + tools.get__('TUE_NAVI', this.getlang(msg)) + ':\n';
2020-03-25 09:25:31 +01:00
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));
2020-03-25 09:25:31 +01:00
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));
2020-03-25 09:25:31 +01:00
mystr += '\n\n';
2020-03-31 20:34:24 +02:00
mystr += tools.get__('INFO_LA_MIA_LAVAGNA', this.getlang(msg));
2020-03-25 09:25:31 +01:00
mystr += '\n' + '1. ' + this.getsymb(emo.ENVELOPE, user.verified_email);
2020-03-31 20:34:24 +02:00
mystr += tools.get__('EMAIL', this.getlang(msg)) + ' ';
mystr += user.verified_email
2023-01-03 16:51:32 +01:00
? 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)) + ' ';
2020-03-31 20:34:24 +02:00
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)
) +
2023-01-03 16:51:32 +01:00
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)
) +
2023-01-03 16:51:32 +01:00
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));
2020-03-25 09:25:31 +01:00
}
// } else{
// mystr += tools.get__('TELEGRAM_NOT_CONNECTED', msg) + ' ' + emoji.get('e-mail');
}
// numpersone = 2;
2020-03-25 09:25:31 +01:00
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';
2020-03-25 09:25:31 +01:00
if (numpersone > 0) {
2020-03-31 20:34:24 +02:00
mystr += tools.get__('INVITATI_LISTA', this.getlang(msg)) + ':\n';
2020-03-25 09:25:31 +01:00
let index = 1;
downline.downline.forEach((user) => {
mystr += '🌠' + ` ${index}°: `;
mystr += user.qualified ? emo.CHECK_VERDE : emo.CROSS_ROSSA;
2020-03-25 09:25:31 +01:00
mystr += `${user.name} ${user.surname} (${user.username})\n`;
index++;
});
} else {
mystr += tools.get__('NESSUN_INVITATO', this.getlang(msg)) + tools.ACAPO;
2020-03-25 09:25:31 +01:00
}
}
// 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 '';
2020-05-10 21:07:51 +02:00
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)) {
2020-12-21 02:16:42 +01:00
// 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(
2023-01-03 16:51:32 +01:00
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);
}
}
2020-01-03 22:02:18 +01:00
async menuExitToTelegram(msg) {
const rec = this.getRecInMem(msg);
if (rec.user) {
await User.SetTelegramIdSuccess(this.idapp, rec.user._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);
2020-01-03 22:02:18 +01:00
}
}
async menuInformazioni(msg) {
const mystr = 'Informazioni Aggiuntive: ...';
await this.sendMsg(msg.chat.id, mystr);
}
2020-03-31 20:34:24 +02:00
async getNextZoom(msg) {
2020-01-21 01:37:15 +01:00
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';
2020-01-21 01:37:15 +01:00
2020-05-04 19:34:41 +02:00
// let pwd = 'Password: 123123';
2020-04-07 14:34:29 +02:00
2020-01-21 01:37:15 +01:00
let index = 1;
listazoom.forEach((evento) => {
let iniziata = false;
if (nextzoom) iniziata = nextzoom._id.toString() === evento._id.toString();
2020-01-21 01:37:15 +01:00
2020-07-02 22:00:58 +02:00
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}`;
2020-07-02 22:00:58 +02:00
mystr += `\n${evento.title}\n(${evento.note})`;
mystr += `\n${tools.getlinkzoom(evento)}\n\n`;
if (nextzoom) {
2020-01-21 01:37:15 +01:00
if (iniziata) {
mystr += emo.FIRE + tools.get__('CLICCA_ENTRA', this.getlang(msg)) + ' ' + emo.FIRE + '\n';
2020-07-02 22:00:58 +02:00
mystr += tools.getlinkzoom(evento) + '\n';
2020-05-04 19:34:41 +02:00
mystr += '\n';
//mystr += pwd + '\n\n';
2020-01-21 01:37:15 +01:00
}
}
2020-01-21 01:37:15 +01:00
index++;
});
if (!nextzoom && index > 1) {
mystr +=
'✨✨✨✨✨✨✨✨✨✨✨✨\n' +
tools.get__('CLICCA_PER_ZOOM', this.getlang(msg)) +
'\n' +
2023-01-03 16:51:32 +01:00
'✨✨✨✨✨✨✨✨✨✨✨✨\n';
}
2020-01-21 01:37:15 +01:00
return mystr;
}
async menuZoom(msg) {
2020-03-31 20:34:24 +02:00
let mystr = await this.getNextZoom(msg);
2020-01-21 01:37:15 +01:00
await this.sendMsg(msg.chat.id, mystr);
2020-01-21 01:37:15 +01:00
}
async menuAiuto(msg) {
const mystr = this.getstrChatHelp();
await this.sendMsg(msg.chat.id, mystr);
}
async menuAdmin(msg) {
2020-03-31 20:34:24 +02:00
const mystr = tools.get__('SCEGLI_VOCE', this.getlang(msg));
await this.sendMsg(msg.chat.id, mystr, MenuAdmin);
}
2020-03-31 20:34:24 +02:00
async menuLang(msg) {
const mystr = tools.get__('SCEGLI_VOCE', this.getlang(msg));
await this.sendMsg(msg.chat.id, mystr, MenuLang);
2020-03-31 20:34:24 +02:00
}
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;
2021-12-29 18:26:08 +01:00
} else if (destin === Destin.DOMANDA) {
const rec = this.getRecInMem(msg);
return rec.msg_username_domanda;
2021-12-29 18:26:08 +01:00
} 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);
}
2022-03-12 21:38:19 +01:00
nonAbilitato(msg) {
MyTelegramBot.local_sendMsgTelegramByIdTelegram(
this.idapp,
msg.chat.id,
'Utente Non abilitato o codice non valido ad eseguire questa funzione'
);
2022-03-12 21:38:19 +01:00
}
chisono(rec) {
if (rec && rec.user) {
return 'Eseguito da ' + rec.user.username + ': ';
}
}
async menuRestartSrv(rec, msg, cmd2) {
if (cmd2 === '6711') {
const freeSpace = await tools.getFreeDiskSpace();
const strfree = `Spazio libero su disco: ${freeSpace}`;
await MyTelegramBot.sendMsgTelegramToTheAdminAllSites(
this.chisono(rec) + ' ha rilanciato il Server NODE.JS... \n' + strfree
);
2023-02-20 02:19:53 +01:00
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);
2022-03-12 21:38:19 +01:00
} else {
this.nonAbilitato(msg);
2022-03-12 21:38:19 +01:00
}
}
async menuLogSrv(rec, msg, cmd2) {
if (cmd2 === '6711') {
const freeSpace = await tools.getFreeDiskSpace();
const strfree = `Spazio libero su disco: ${freeSpace}`;
console.log(strfree);
const ris = await tools.execScriptByTelegram(
this.idapp,
msg,
'~/batch/logserver.sh',
this.chisono(rec) + ' Visualizzo il Log del Server... \n' + strfree
);
2022-03-12 21:38:19 +01:00
} else {
this.nonAbilitato(msg);
2022-03-12 21:38:19 +01:00
}
}
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 !...'
);
2022-03-12 21:38:19 +01:00
} else {
this.nonAbilitato(msg);
2022-03-12 21:38:19 +01:00
}
}
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
) {
2021-12-29 18:26:08 +01:00
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);
}
}
2020-05-10 21:07:51 +02:00
getlink(qualelink) {
if (qualelink === 'website') {
return '';
2020-05-10 21:07:51 +02:00
} else if (qualelink === 'biblio') {
return '';
2020-05-10 21:07:51 +02:00
} else if (qualelink === 'help') {
2020-07-02 22:00:58 +02:00
return tools.HELP_CHAT;
2020-05-10 21:07:51 +02:00
} else if (qualelink === 'faq') {
return '';
2020-05-10 21:07:51 +02:00
}
}
async menuAssistenza(msg) {
2020-05-10 21:07:51 +02:00
const sito = this.getlink('website');
const empower = this.getlink('empower');
const biblio = this.getlink('biblio');
const faq = this.getlink('faq');
let help = '';
2020-05-10 21:07:51 +02:00
let helpaperta = true;
/*if (tools.isMonToFri() && tools.isBetweenTwoTime('9:00:00', '19:00:00')) {
2020-05-10 21:07:51 +02:00
help = '✅ ' + this.getlink('help');
} else {
help = "🔴 [ORA CHIUSA - NOW CLOSED]";
helpaperta = false;
}*/
help = '✅ ' + this.getlink('help');
2020-05-10 21:07:51 +02:00
let mytext = '';
2020-05-10 21:07:51 +02:00
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) {
2021-12-29 18:26:08 +01:00
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;
}
}
2020-01-03 22:02:18 +01:00
deleteRecInMem(msg) {
this.arrUsers = this.arrUsers.filter((rec) => rec.id !== this.getchatid(msg));
2020-01-03 22:02:18 +01:00
}
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);
2020-03-31 20:34:24 +02:00
const lang = this.getlang(msg);
2020-05-10 21:07:51 +02:00
// 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;
}
2023-01-03 16:51:32 +01:00
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);
2022-11-10 19:33:23 +01:00
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 {
2025-02-25 18:13:01 +01:00
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);
2022-05-05 23:56:37 +02:00
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 {
2020-04-24 10:29:25 +02:00
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);
2020-04-24 10:29:25 +02:00
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;
2020-04-24 10:29:25 +02:00
}
if (code.length < 7) {
if (rec) {
if (code === telegcode) {
2022-01-26 01:31:22 +01:00
try {
await User.setUsernameTelegram(
this.idapp,
user._id,
msg.from.username || '',
msg.from.first_name || '',
msg.from.last_name || ''
);
} catch (e) {}
2020-04-24 10:29:25 +02:00
// let ris = await this.getUser(msg, rec, false);
2022-01-26 01:31:22 +01:00
2020-04-24 10:29:25 +02:00
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);
2020-04-24 10:29:25 +02:00
} else {
console.log(" ... MA GLI MANCA L'USERNAME TELEGRAM !! ");
2020-04-24 10:29:25 +02:00
}
// 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'));
}
2020-04-24 10:29:25 +02:00
} 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 {
2020-04-24 10:29:25 +02:00
rec.status = Status.NONE;
await this.sendMsgLog(msg.from.id, getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_ANNULLA'));
2020-04-24 10:29:25 +02:00
this.deleteRecInMem(msg);
}
}
}
2020-04-24 10:29:25 +02:00
} 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'));
2020-04-24 10:29:25 +02:00
} 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;
}
2021-12-29 18:26:08 +01:00
async setCmdToUsername(rec, username, cmd_to_set, valuebool) {
if (cmd_to_set === Cmd.VALIDATE_REGISTRATION) {
return await User.setVerifiedByAportador(rec.user.idapp, username, valuebool);
2021-12-29 18:26:08 +01:00
}
}
async sendMsgToAll(rec, msg, texttosend, destin) {
try {
if (texttosend.length < 3 && destin !== Destin.A_UTENTE) {
2021-12-29 18:26:08 +01:00
// NOTHING
} else {
let contanumutenti = 0;
let usersall = null;
2021-12-29 18:26:08 +01:00
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 = '';
2020-03-31 20:34:24 +02:00
if (this.isSelMenu(msg, texttosend, 'ZOOM')) {
texttosend = await this.getNextZoom(msg);
}
2025-02-25 18:13:01 +01:00
const cmd = texttosend?.toLowerCase();
if (usersall) {
2020-03-31 20:34:24 +02:00
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;
2020-04-24 10:29:25 +02:00
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 {
2020-04-24 10:29:25 +02:00
textdainviare = texttosend;
}
2020-04-24 10:29:25 +02:00
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);
2020-04-24 10:29:25 +02:00
} else if (destin === Destin.TUTTI) {
invia = true;
} else if (destin === Destin.PAOLO) {
2025-01-12 21:29:05 +01:00
invia = utente.username === shared_consts.ADMIN_USER_SERVER;
2020-04-24 10:29:25 +02:00
} else if (destin === Destin.A_UTENTE) {
invia = utente.username === rec.msgall_username_specifico;
2021-12-29 18:26:08 +01:00
} else if (destin === Destin.DOMANDA) {
invia = utente.username === rec.msg_username_domanda;
} else if (destin === Destin.RISPOSTA) {
invia = utente.username === rec.msg_username_risposta;
2020-04-24 10:29:25 +02:00
} else if (destin === Destin.NO_7_REQ) {
invia = !(await User.isUserQualified7(this.idapp, utente.username));
2020-04-24 10:29:25 +02:00
} else if (destin === Destin.MSG_TO_NAVE) {
2022-02-03 00:33:15 +01:00
// invia = !await Nave.findDonatoreByNave(this.idapp, rec.extraparam);
2020-04-24 10:29:25 +02:00
}
// TEST invia = true;
2020-04-24 10:29:25 +02:00
if (invia) {
let inviaveramente = false;
2020-04-24 10:29:25 +02:00
if (cmd === RICEVI_EMAIL) {
preparatesto += utente.email + ', ';
} else if (cmd === NOME_COGNOME) {
preparatesto += utente.name + ' ' + utente.surname + '(' + utente.username + ')' + '\n';
2020-04-24 10:29:25 +02:00
} else if (cmd === CONTA_SOLO) {
contanumutenti++;
2020-04-24 10:29:25 +02:00
// Niente
} else if (cmd === CHEDI_SE_IMBARCARTI) {
textdainviare = tools.gettranslate('VUOI_IMBARCARTI', lang);
FormDaMostrare = this.getInlineKeyboard(lang, [
2020-07-13 23:35:05 +02:00
{
text: Menu[lang].SI,
callback_data: InlineCmd.VOGLIO_IMBARCARMI + tools.SEP + utente.username,
2020-07-13 23:35:05 +02:00
},
{
text: Menu[lang].NO,
callback_data: InlineCmd.NON_VOGLIO_IMBARCARMI + tools.SEP + utente.username,
2020-07-13 23:35:05 +02:00
},
]);
inviaveramente = true;
2020-04-24 10:29:25 +02:00
} else {
inviaveramente = true;
}
if (inviaveramente) {
textdainviare = await tools.convertSpecialTags(utente, textdainviare);
2020-04-24 10:29:25 +02:00
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
);
2020-04-24 10:29:25 +02:00
} 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;
2020-04-24 10:29:25 +02:00
}
2020-09-04 00:06:49 +02:00
await tools.snooze(100);
nummsgsent++;
}
2020-04-24 10:29:25 +02:00
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);
2020-04-24 10:29:25 +02:00
}
}
}
}
}
}
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 {
2021-12-29 18:26:08 +01:00
if (destin !== Destin.DOMANDA && destin !== Destin.RISPOSTA) {
msgris = nummsgsent + ' ' + getstr(this.getlang(msg), 'MSG_MSG_SENT');
2021-12-29 18:26:08 +01:00
}
}
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 {
2021-12-29 18:26:08 +01:00
if (msgris) {
tools.writeEventsLog(msgris);
2021-12-29 18:26:08 +01:00
await this.sendMsg(msg.chat.id, msgris);
}
}
}
rec.start_write_msgall = false;
} catch (e) {
2020-05-04 19:34:41 +02:00
console.error(e.message);
}
}
selectMenuHelp(msg) {
return this.isSelMenu(msg, msg.text, 'INFO') || this.isSelMenu(msg, msg.text, 'ASSISTENZA');
2020-03-31 20:34:24 +02:00
}
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);
2020-01-03 22:02:18 +01:00
let status = this.getstatusInMemory(msg);
if (status !== Status.VERIFIED) return Status.EXIT;
} else {
await this.setUser(msg);
}
return status;
}
getInvitanteByMsg(msg) {
try {
2025-02-05 12:13:27 +01:00
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];
2023-08-27 23:55:31 +02:00
if (mymsg.startsWith('inv' + sep)) {
let arrparams = mymsg.split(sep);
if (arrparams.length > 2) {
invitante = arrparams[1];
regexpire = arrparams[3];
}
2023-01-03 16:51:32 +01:00
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);
2025-02-25 18:13:01 +01:00
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) {
2020-03-31 20:34:24 +02:00
if (this.isSelMenu(msg, msg.text, 'SI')) {
// Take msg to send to ALL
await this.sendMsgToAll(rec, msg, rec.msgtosent, rec.msgall_achi);
} else {
2021-12-29 18:26:08 +01:00
let msgout = rec.msgNo;
if (!msgout) msgout = getstr(this.getlang(msg), 'MSG_OPERAZ_ANNULLATA');
2021-12-29 18:26:08 +01:00
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);
2021-12-29 18:26:08 +01:00
if (ris) {
await this.sendMsgToAll(rec, msg, rec.msg_toDest_yes, rec.msgall_achi);
2021-12-29 18:26:08 +01:00
}
} 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);
2021-12-29 18:26:08 +01:00
}
}
}
rec.msgall_status = StatusMSGALL.NONE;
normale = false;
} else if (rec.msgall_status === StatusMSGALL.ASK) {
2020-03-31 20:34:24 +02:00
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;
2025-02-25 18:13:01 +01:00
const cmd = rec?.msgtosent?.toString()?.toLowerCase() ?? '';
let achi = this.getDestinStr(msg, rec.msgall_achi, rec);
let domanda = '';
2021-12-29 18:26:08 +01:00
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 + '?';
2021-12-29 18:26:08 +01:00
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;
2021-12-29 18:26:08 +01:00
}
}
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) {
2022-05-05 23:56:37 +02:00
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);
2020-01-03 22:02:18 +01:00
}
return !!rec;
}
2021-12-29 18:26:08 +01:00
updateMenuBot() {
for (let rec of this.arrUsers) {
rec.menuDb = null;
2021-12-29 18:26:08 +01:00
rec.datemenu_updated = null;
}
}
async addUser(msg) {
2020-03-31 20:34:24 +02:00
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,
2021-12-29 18:26:08 +01:00
msgall_domanda: '',
msgall_achi: 0,
msgall_username_specifico: '',
2021-12-29 18:26:08 +01:00
cmd_to_set: 0,
msg_username_domanda: '',
msg_username_risposta: '',
extraparam: '',
msgtosent: '',
entities: [],
2021-12-29 18:26:08 +01:00
msgNo: '',
msg_toDest_yes: '',
msg_toDest_no: '',
msg_wait: false,
lastmenu: null,
2021-12-29 18:26:08 +01:00
datemenu_updated: null,
pageChange: false,
menuSaved: {},
pagenow: 1,
parse_mode: 'HTML',
menuDb: null,
aportador_solidario: '',
};
rec.status = Status.NONE;
if (!msg.from.username) {
2023-12-17 16:20:44 +01:00
// Non ha l'Username:
2023-12-17 19:19:04 +01:00
2023-12-17 16:20:44 +01:00
// Chiedi l'username sul Bot:
if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskUsernameSulBot)) {
rec.status = Status.WAITFOR_USERNAME_TELEGRAM;
}
} else {
2023-12-17 16:20:44 +01:00
// Ha l'Username
2023-12-17 19:19:04 +01:00
2023-12-17 16:20:44 +01:00
// Chiedi l'invitante ?
if (tools.getConfSiteOptionEnabledByIdApp(this.idapp, shared_consts.ConfSite.AskInvitantesulBot)) {
rec.status = Status.WAITFOR_USERNAME_INVITANTE;
}
}
2023-12-17 16:20:44 +01:00
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) {}
2021-12-29 18:26:08 +01:00
async loadMenuFromDb(idapp, id) {
try {
let load = false;
const check = true;
2020-12-21 02:16:42 +01:00
2021-12-29 18:26:08 +01:00
const recuser = this.getRecInMemById(id);
if (recuser) {
if (!recuser.datemenu_updated) load = true;
2021-12-29 18:26:08 +01:00
}
if (check) {
if (recuser) {
if (!recuser.menuSaved[idapp]) load = true;
if (recuser.menuDb || recuser.pageChange) load = true;
}
2021-12-29 18:26:08 +01:00
}
if (load) {
2021-12-29 18:26:08 +01:00
// Check if you are Admin
const user = await User.UserByIdTelegram(idapp, id);
2023-12-29 15:19:15 +01:00
let isAdmin = user ? user.profile.admin_telegram : false;
const isManager = user ? user.profile.manage_telegram : false;
2022-03-10 23:19:56 +01:00
const isVerified = user ? user.profile.teleg_id > 0 && user.verified_by_aportador : false;
2021-12-29 18:26:08 +01:00
recuser.menuDb = await MyBot.findAllIdApp(idapp);
2021-12-29 18:26:08 +01:00
let arrlang = {};
2021-12-29 18:26:08 +01:00
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 = [];
}
2021-12-29 18:26:08 +01:00
arrtemp.push(rec.label);
2021-12-29 18:26:08 +01:00
}
}
}
if (arrtemp.length > 0) arrlang[lang].menu.push(arrtemp);
2021-12-29 18:26:08 +01:00
if (recuser) recuser.datemenu_updated = new Date();
2021-12-29 18:26:08 +01:00
recuser.pageChange = false;
recuser.menuSaved[idapp] = arrlang;
2021-12-29 18:26:08 +01:00
}
return recuser ? recuser.menuSaved[idapp] : null;
2021-12-29 18:26:08 +01:00
} catch (e) {
console.log('Err loadMenuFromDb: ' + e);
2020-12-21 02:16:42 +01:00
}
2021-12-29 18:26:08 +01:00
}
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);
2021-12-29 18:26:08 +01:00
}
2020-12-21 02:16:42 +01:00
}
2021-12-29 18:26:08 +01:00
for (const rec of recuser.menuDb) {
if (rec.active_mem) {
if (rec.idapp === idapp && rec.lang === lang && rec.label?.toLowerCase() === testo) {
return true;
}
2021-12-29 18:26:08 +01:00
}
}
} catch (e) {
return false;
}
return false;
}
async getValueMenu(idapp, recuser, msg, testo, lang) {
2021-12-29 18:26:08 +01:00
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;
}
}
}
2021-12-29 18:26:08 +01:00
}
}
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 [];
}
}
2021-12-29 18:26:08 +01:00
async getKeyboard(id, menu, lang) {
let keyb = null;
this.lastid = id;
2021-12-29 18:26:08 +01:00
if (menu) {
keyb = menu;
2021-12-29 18:26:08 +01:00
} else {
keyb = await this.loadMenuFromDb(this.idapp, id);
}
2020-03-31 20:34:24 +02:00
let mykeyb = undefined;
if (!!keyb) {
mykeyb = this.getmenuKey(keyb, lang);
}
if (mykeyb === null) {
mykeyb = [];
}
// console.log('mykeyboard', mykeyb);
2020-03-31 20:34:24 +02:00
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;
}
}
}
async sendImageToTelegram(chatId, imageUrl, opt) {
try {
2025-08-09 00:48:50 +02:00
// Primo tentativo: invia direttamente l'URL
try {
return await this.bot.sendPhoto(chatId, imageUrl, opt);
} catch (error) {
console.log('Primo tentativo fallito, provo a convertire...');
}
2025-08-09 00:48:50 +02:00
console.log('imageUrl', imageUrl);
// Secondo tentativo: scarica e converte con sharp
try {
const response = await axios.get(imageUrl, { responseType: 'arraybuffer' });
const contentType = response.headers['content-type'];
const imageBuffer = Buffer.from(response.data);
if (!contentType.startsWith('image/')) {
console.warn('Non è un formato immagine:', contentType);
return await this.bot.sendDocument(chatId, imageBuffer, opt);
}
2025-08-09 00:48:50 +02:00
try {
const jpgBuffer = await sharp(imageBuffer).jpeg({ quality: 90 }).toBuffer();
return await this.bot.sendPhoto(chatId, jpgBuffer, opt);
} catch (err) {
console.warn('Sharp conversion failed:', err.message);
return await this.bot.sendDocument(chatId, imageBuffer, opt);
}
} catch (err) {
console.warn("Errore nel download dell'immagine, provo con file locale...");
}
2025-08-09 00:48:50 +02:00
// Terzo tentativo: accedi al file localmente
try {
2025-08-09 00:48:50 +02:00
if (!imageUrl.includes('/upload/')) {
throw new Error('URL non contiene "/upload/", impossibile determinare il path locale.');
}
let dirmain = '';
if (!tools.sulServer()) {
dirmain = server_constants.DIR_PUBLIC_LOCALE;
}
const relativePath = imageUrl.split('/upload/')[1]; // es. "profile/surya1977/mygoods/1_module.jpg"
const mydir = tools.getdirByIdApp(opt.idapp) + dirmain + server_constants.DIR_UPLOAD;
const localPath = path.join(mydir, relativePath);
console.log('Cerco il file localmente:', localPath);
const localBuffer = fs.readFileSync(localPath);
return await this.bot.sendDocument(chatId, localBuffer, opt);
} catch (err) {
console.error('Lettura file locale fallita:', err.message);
}
2025-08-09 00:48:50 +02:00
// Se tutto fallisce
console.error('Tutti i tentativi di invio sono falliti');
return false;
} catch (error) {
2025-08-09 00:48:50 +02:00
console.error('Errore generale:', error);
return false;
}
}
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;
2021-12-29 18:26:08 +01:00
id = '12429864';
}
2020-07-02 22:00:58 +02:00
}
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;
}
}
2020-04-07 14:34:29 +02:00
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 = tools.fixUrl(opt.img, opt.idapp);
console.log('opt.img', opt.img);
2025-08-09 00:48:50 +02:00
risSendPhoto = await this.sendImageToTelegram(id, opt.img, { caption: text, ...form, ...opt }).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.substring(0, 200));
}
if (blocked) {
User.SetTelegramWasBlocked(this.idapp, id);
}
});
}
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.substring(0, 200));
}
if (blocked) {
User.SetTelegramWasBlocked(this.idapp, id);
// ++Todo: DA FARE ! local_sendMsgTelegramToTheManagers(this.idapp, addtext + text);
}
return 0;
});
}
return risSendPhoto;
} catch (e) {
if (e.message.indexOf('OK') === 0) {
console.log('INFO INVIAMSG:', e.message);
} else {
console.error('ERROR INVIAMSG:', e.message, 'text', text.substring(0, 100));
}
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);
}
2020-03-31 20:34:24 +02:00
getmenuKey(mymenu, lang) {
let mymenuout = null;
try {
mymenuout = mymenu[lang].menu;
} catch (e) {
if (!!mymenu['it']) mymenuout = mymenu['it'].menu;
2020-03-31 20:34:24 +02:00
}
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) {
2024-02-03 23:04:56 +01:00
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(async 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);
await tools.mkdirpath(pathfile);
// console.log('2) myfileprofile', pathfile);
return tools
.downloadImage(photo_url, myfileprofile)
.then((ris) => {
2023-01-03 16:51:32 +01:00
try {
let resized_img_small =
tools.extractFilePath(myfileprofile) + '/' + server_constants.PREFIX_IMG_SMALL + filename;
2023-01-03 16:51:32 +01:00
// 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);
2023-01-03 16:51:32 +01:00
} catch (e) {
console.error('setPhotoProfile sharp', e);
}
2023-01-03 16:51:32 +01:00
// 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));
}
});
2023-01-03 16:51:32 +01:00
// console.log('scaricato');
})
.catch((err) => {
2023-01-03 16:51:32 +01:00
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) {
2020-03-31 20:34:24 +02:00
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),
},
});
}
}
2020-01-03 22:02:18 +01:00
2020-03-31 20:34:24 +02:00
async ScegliLang(msg, lang) {
const rec = this.getRecInMem(msg);
if (rec) {
if (rec.user) {
2022-11-13 22:39:07 +01:00
User.SetLang(null, this.idapp, rec.user._id, lang);
2020-03-31 20:34:24 +02:00
rec.user.lang = lang;
}
rec.lang = lang;
// await this.sendMsg(msg.chat.id, lang);
this.msgScegliMenu(msg);
}
}
async msgScegliMenu(msg) {
2020-03-31 20:34:24 +02:00
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)),
},
2020-04-24 10:29:25 +02:00
});
2020-01-03 22:02:18 +01:00
}
}
const arrTelegram = [];
function getclTelegBytoken(token) {
2020-01-03 22:02:18 +01:00
const rec = arrTelegram.find((rec) => rec.cl.token === token);
if (!!rec) return rec.cl;
else return null;
2020-01-03 22:02:18 +01:00
}
// 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;
}
}
2020-01-03 22:02:18 +01:00
function getclTelegByidapp(idapp) {
// ****************************
if (appTelegramFinti.includes(idapp)) {
const ind = appTelegramFinti.indexOf(idapp);
if (ind >= 0) idapp = appTelegramDest[ind]; // Invia
}
2020-01-03 22:02:18 +01:00
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();
2023-12-17 16:20:44 +01:00
2022-09-03 13:06:58 +02:00
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);
});
}
2022-09-03 13:06:58 +02:00
});
}
}
}
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) });
2022-09-03 13:06:58 +02:00
bot.onText(/\/start/, (msg) => {
console.log('*** BOT PARTITO CORRETTAMENTE !!! (Start Cmd)');
2022-09-03 13:06:58 +02:00
const myclTelegram = getclTelegBytoken(bot.token);
myclTelegram.start(msg);
});
2022-03-10 23:19:56 +01:00
// 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);
// RISPOSTE ALLE CALLBACK (Bottoni)
2025-08-09 00:48:50 +02:00
let testo_notifica_di_risposta = '';
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}`
);
2022-09-03 13:06:58 +02:00
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);
2022-09-03 13:06:58 +02:00
}
} 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);
}
2022-09-03 13:06:58 +02:00
}
} 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);
}
2022-09-03 13:06:58 +02:00
}
} 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);
}
2023-01-03 16:51:32 +01:00
}
} 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,
});
2022-09-03 13:06:58 +02:00
}
} else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_CIRCUIT) {
console.log(' CLICK per Aggiungere ', data.username, 'nel circuito', circuit?.name);
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,
});
2022-09-03 13:06:58 +02:00
}
} 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,
});
}
2023-01-08 02:17:01 +01:00
}
} 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
2023-01-08 02:17:01 +01:00
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);
}
2023-01-08 02:17:01 +01:00
}
}
} else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.ENTRA_RIS_ITALIA) {
}
}
// CALLBACK DI RISPOSTA AL BOT
2025-08-09 00:48:50 +02:00
bot.answerCallbackQuery(callbackQuery.id, { text: testo_notifica_di_risposta });
} catch (e) {
console.error('Error BOT callback_query', e);
}
/*
2022-09-03 13:06:58 +02:00
let text;
2022-09-03 13:06:58 +02:00
if (action === 'edit') {
text = 'Edited Text';
}
2022-09-03 13:06:58 +02:00
bot.editMessageText(text, opts);
*/
// bot.answerCallbackQuery(callbackQuery.id, { url });
});
}
} catch (e) {
console.error('Error Telegram LOOP : ' + e.message);
2022-09-03 13:06:58 +02:00
}
}
})
.catch((e) => {
arrTeleg = [];
console.error('Error internetAvailable:' + e);
});
}
module.exports = MyTelegramBot;