- Bot Telegram ...

This commit is contained in:
Paolo Arena
2020-01-03 22:02:18 +01:00
parent f359f8f723
commit 8f784df4fa
10 changed files with 208 additions and 36 deletions

View File

@@ -6,4 +6,8 @@
- [Display Unlock Captcha](https://accounts.google.com/b/0/displayunlockcaptcha) ✔
EMOJI:<br>
https://listemoji.com/symbols-emoji
</div>

View File

@@ -35,6 +35,7 @@
"mongoose": "^4.13.19",
"mysql": "^2.17.1",
"node-cron": "^2.0.3",
"node-emoji": "^1.10.0",
"node-pre-gyp": "^0.11.0",
"node-telegram-bot-api": "^0.40.0",
"nodemailer": "^4.6.8",

View File

@@ -184,8 +184,8 @@ if (process.env.NODE_ENV === 'production') {
dir: '/var/www/testnotevole.freeplanet.app',
email_from: 'info.pianetalibero@gmail.com',
email_pwd: '2df135e2b6c02b2c68ec6bf6b103751fcb4dfc48c57d0acb302482358ee8141fmaDuooPabDvlThiBI2XMyA==',
telegram_key:'1037577457:AAGQbdIuYoB838v61ewJ0Hearx9UPpTBhMI',
telegram_bot_name: 'notevoleaynibot',
telegram_key:'1011893908:AAEThZB3fVPw8P5gTCFgTEsDmY21DdbV1Cw',
telegram_bot_name: 'testnotevoleaynibot',
},
];
} else {

View File

@@ -146,6 +146,9 @@ var UserSchema = new mongoose.Schema({
teleg_checkcode: {
type: Number
},
manage_telegram: {
type: Boolean
},
dateofbirth: {
type: Date,
},
@@ -207,15 +210,15 @@ UserSchema.statics.setPermissionsById = function (id, perm) {
UserSchema.statics.isAdmin = function (user) {
try {
return ((user.perm & shared_consts.Permissions.Admin) === shared_consts.Permissions.Admin);
return ((perm & shared_consts.Permissions.Admin) === shared_consts.Permissions.Admin);
} catch (e) {
return false
}
};
UserSchema.statics.isManager = function (user) {
UserSchema.statics.isManager = function (perm) {
try {
return ((user.perm & shared_consts.Permissions.Manager) === shared_consts.Permissions.Manager);
return ((perm & shared_consts.Permissions.Manager) === shared_consts.Permissions.Manager);
} catch (e) {
return false
}
@@ -422,6 +425,17 @@ UserSchema.statics.UserByIdTelegram = async function (idapp, teleg_id) {
});
};
UserSchema.statics.TelegIdByUsername = async function (idapp, username) {
const User = this;
return await User.findOne({ idapp, username }, {'profile.teleg_id': 1})
.then((rec) => {
return (!!rec) ? rec.profile.teleg_id : null;
}).catch((e) => {
console.error('TelegIdByUsername', e);
});
};
UserSchema.statics.SetTelegramCheckCode = async function (idapp, username, teleg_checkcode) {
const User = this;
@@ -455,6 +469,29 @@ UserSchema.statics.SetTelegramIdSuccess = async function (idapp, username, teleg
};
UserSchema.statics.getNameSurnameByUsername = async function (idapp, username) {
const User = this;
return await User.findOne({ idapp, username }, {name: 1, surname: 1})
.then((rec) => {
return (!!rec) ? `${rec.name} ${rec.surname}` : '';
}).catch((e) => {
console.error('getNameSurnameByUsername', e);
});
};
UserSchema.statics.getusersManagers = async function (idapp) {
const User = this;
return await User.find({ idapp, 'profile.manage_telegram': true }, {'profile.teleg_id': 1})
.then((arrrec) => {
return (!!arrrec) ? arrrec : null;
}).catch((e) => {
console.error('getusersManagers', e);
});
};
UserSchema.statics.getUsersList = function (idapp) {
const User = this;
@@ -474,6 +511,7 @@ UserSchema.statics.getUsersList = function (idapp) {
};
UserSchema.statics.getUsersListByParams = function (params) {
const User = this;

View File

@@ -250,7 +250,7 @@ router.patch('/chval', authenticate, (req, res) => {
tools.mylogshow('PATCH CHVAL: ', id, fieldsvalue);
// If I change my record...
if ((!User.isAdmin(req.user) && !User.isManager(req.user)) && !(req.user._id.toString() === id)) {
if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) && !(req.user._id.toString() === id)) {
// If without permissions, exit
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
@@ -278,7 +278,7 @@ router.delete('/delrec/:table/:id', authenticate, (req, res) => {
const mytable = getTableByTableName(tablename);
if (!User.isAdmin(req.user) && !User.isManager(req.user)) {
if (!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) {
// If without permissions, exit
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
@@ -315,7 +315,11 @@ router.post('/duprec/:table/:id', authenticate, (req, res) => {
const mytable = getTableByTableName(tablename);
if (!User.isAdmin(req.user) && !User.isManager(req.user)) {
if (!req.user) {
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
if (!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) {
// If without permissions, exit
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
@@ -447,7 +451,7 @@ router.get(process.env.LINK_CHECK_UPDATES, authenticate, (req, res) => {
if (req.user) {
// If User is Admin, then send user Lists
if (User.isAdmin(req.user)) {
if (User.isAdmin(req.user.perm)) {
// Send UsersList
usersList = User.getUsersList(req.user.idapp)
}

View File

@@ -338,7 +338,7 @@ router.post('/unsubscribe', (req, res) => {
router.post('/testemail', authenticate, async (req, res) => {
if (!User.isAdmin(req.user)) {
if (!User.isAdmin(req.user.perm)) {
// If without permissions, exit
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}

View File

@@ -122,7 +122,7 @@ router.patch('/:id', authenticate, (req, res) => {
tools.mylogshow('PATCH USER: ', id);
if (!User.isAdmin(req.user)) {
if (!User.isAdmin(req.user.perm)) {
// If without permissions, exit
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}

View File

@@ -1,4 +1,5 @@
const tools = require('./tools/general');
const telegrambot = require('./telegram/telegrambot');
require('./config/config');
@@ -171,6 +172,8 @@ module.exports = {
// Send to the Admin an Email
this.sendEmail_base('admin/registration/' + tools.LANGADMIN, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
telegrambot.notifyToTelegram(telegrambot.phase.REGISTRATION, mylocalsconf);
if (tools.isManagAndAdminDifferent(idapp)) {
this.sendEmail_base('admin/registration/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
}

View File

@@ -58,6 +58,8 @@ const admin_router = require('./router/admin_router');
const { MyEvent } = require('./models/myevent');
const telegrambot = require('./telegram/telegrambot');
require('./db/mongoose');
console.log("DB: " + process.env.DATABASE);
@@ -137,6 +139,7 @@ if (app.get('env') === 'development') {
// error: err
// });
});
}
require('./telegram/telegrambot');
@@ -263,4 +266,9 @@ cron.schedule('*/2 * * * *', () => {
// console.log(`Server started at port ${port}`);
//});
telegrambot.sendMsgTelegram('7', telegrambot.ADMIN_USER_SERVER, `Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}!`);
telegrambot.sendMsgTelegramByIdTelegram('7', telegrambot.ADMIN_IDTELEGRAM_SERVER, `Il Server ${process.env.DATABASE} è appena ripartito!`);
// telegrambot.sendMsgTelegramToTheManagers('7', 'PROVAAA!');
module.exports = { app };

View File

@@ -6,16 +6,20 @@ const printf = require('util').format;
const { User } = require('../models/user');
const Benvenuto = 'Benvenuto';
const emoji = require('node-emoji');
const Benvenuto = emoji.get('heartbeat') + emoji.get('heartbeat') + emoji.get('heartbeat') + ' Benvenuto!';
const Menu = {
LAVAGNA: 'La tua Lavagna',
LINK_CONDIVIDERE: 'Tuo Link da condividere',
INFO: 'Informazioni',
ASSISTENZA: 'Assistenza',
LAVAGNA: emoji.get('om_symbol') + ' La tua Lavagna',
LINK_CONDIVIDERE: emoji.get('link') + ' Link da condividere',
INFO: emoji.get('information_source') + ' Informazioni',
ASSISTENZA: emoji.get('open_hands') + ' Assistenza',
EXIT_TELEGRAM: 'exittotelegram',
};
const MenuStandard = [[Menu.LAVAGNA, Menu.LINK_CONDIVIDERE], [Menu.INFO], [Menu.ASSISTENZA]];
const MenuStandard = [[Menu.LAVAGNA, Menu.LINK_CONDIVIDERE], [Menu.INFO, Menu.ASSISTENZA]];
const Status = {
NONE: 0,
@@ -25,19 +29,79 @@ const Status = {
};
const txt = {
MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Scegli una voce di menu:' + emoji.get('dizzy'),
MSG_ASK_USERNAME_BO: 'Inserire lo username con cui ti sei registrato sul sito:',
MSG_ERRORE_USERNAME: 'Attenzione! Devi inserire solo lo username (20 caratteri massimo)',
MSG_ERRORE_USERNAME_NOT_FOUND: 'Attenzione! Username non trovato in archivio. Verifica che sia corretto.',
MSG_ERRORE_USERNAME_ANNULLA: 'Inserimento Annullato.',
MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attenzione! Devi inserire solo il codice a 6 cifre',
MSG_VERIFY_CODE: 'Vai sul sito e aggiorna la pagina (REFRESH) e scrivi qui il Codice di Autenticazione che vedrai visualizzato',
MSG_ERR_VERIFY_CODE: 'Codice di Verifica Errato! Reinserire il codice di 6 cifre.',
MSG_VERIFY_OK: 'Benvenuto %s. Ora sei correttamente verificato!',
MSG_ERR_UNKNOWN_VERIFY_CODE: 'Errore durante il salvataggio sul Server. Riprovare piú tardi'
MSG_ERR_VERIFY_CODE: 'Codice di Verifica Errato! Controllare sul Sito e reinserire il nuovo codice di 6 cifre.',
MSG_VERIFY_OK: emoji.get('grinning') + ' Benvenuto %s. Ora sei correttamente verificato!',
MSG_ERR_UNKNOWN_VERIFY_CODE: 'Errore durante il salvataggio sul Server. Riprovare piú tardi',
MSG_EXIT_TELEGRAM: 'L\'account è stato ora scollegato da questo Telegram BOT.',
MSG_APORTADOR_USER_REGISTERED: emoji.get('heart_eyes') + ' Si è appena Registrato con il tuo link:\n%s',
};
const TelegramBot = require('node-telegram-bot-api');
module.exports = {
ADMIN_IDTELEGRAM_SERVER: '12429864',
ADMIN_USER_SERVER: 'paoloar77',
ADMIN_USER_NAME_SERVER: 'Paolo',
phase: {
REGISTRATION: 1
},
notifyToTelegram: async function (phase, mylocalsconf) {
let userdest = mylocalsconf.user.aportador_solidario;
let NameFrom = `${mylocalsconf.user.name} ${mylocalsconf.user.surname} (${userdest})`;
let text = '';
if (phase === this.phase.REGISTRATION) {
NameFrom = await User.getNameSurnameByUsername(mylocalsconf.idapp, userdest) + ` (${userdest})`;
if (!!mylocalsconf.user.aportador_solidario)
text = printf(txt.MSG_APORTADOR_USER_REGISTERED, `${mylocalsconf.user.name} ${mylocalsconf.user.surname} (${mylocalsconf.user.username})`);
}
await this.sendMsgTelegram(mylocalsconf.idapp, userdest, text);
await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, '[Inviato a ' + NameFrom + ']:' + '\n' + text);
},
sendMsgTelegramToTheManagers: async function (idapp, text) {
const usersmanagers = await User.getusersManagers(idapp);
// console.log('usersmanagers', usersmanagers);
if (usersmanagers) {
usersmanagers.forEach((rec) => {
this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, text)
});
}
},
sendMsgTelegram: async function (idapp, username, text) {
const teleg_id = await User.TelegIdByUsername(idapp, username);
const cl = getclTelegByidapp(idapp);
if (cl && teleg_id) {
cl.sendMsg(teleg_id, text)
}
},
sendMsgTelegramByIdTelegram: function (idapp, idtelegram, text) {
const cl = getclTelegByidapp(idapp);
if (cl && idtelegram) {
cl.sendMsg(idtelegram, text)
}
}
};
function getstr(lang, text) {
return text;
@@ -70,12 +134,16 @@ class Telegram {
isMenu(msg) {
if (msg.text === Menu.LAVAGNA) {
this.menuLavagna(msg)
}else if (msg.text === Menu.LINK_CONDIVIDERE) {
} else if (msg.text === Menu.LINK_CONDIVIDERE) {
this.menuLinkCondividere(msg)
}else if (msg.text === Menu.ASSISTENZA) {
} else if (msg.text === Menu.ASSISTENZA) {
this.menuAssistenza(msg)
}else if (msg.text === Menu.INFO) {
} else if (msg.text === Menu.INFO) {
this.menuInformazioni(msg)
} else if (msg.text === Menu.EXIT_TELEGRAM) {
this.menuExitToTelegram(msg)
} else {
this.msgScegliMenu(msg);
}
}
@@ -89,7 +157,7 @@ class Telegram {
const numpersone = (dashboard.downline) ? dashboard.downline.length : 0;
if (dashboard.aportador) {
mystr = `Chi ti ha invitato: ${dashboard.aportador.username} (${dashboard.aportador.name} ${dashboard.aportador.surname})\n`;
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! ';
}
@@ -98,7 +166,7 @@ class Telegram {
mystr += `Persone che hai invitato (${numpersone}):\n`;
let index = 1;
dashboard.downline.forEach((user) => {
mystr += `${index}°: ${user.username} (${user.name} ${user.surname})`;
mystr += emoji.get('star-struck') + ` ${index}°: ${user.username} (${user.name} ${user.surname})\n`;
index++;
});
} else {
@@ -119,13 +187,26 @@ class Telegram {
this.sendMsg(msg.chat.id, mystr);
}
}
async menuExitToTelegram(msg) {
const rec = this.getRecInMem(msg);
if (rec.user) {
await User.SetTelegramIdSuccess(this.idapp, rec.user.username, 0).then((recuser) => {
if (recuser) {
this.deleteRecInMem(msg);
this.sendMsg(msg.chat.id, txt.MSG_EXIT_TELEGRAM);
}
})
}
}
async menuInformazioni(msg) {
const mystr = 'Informazioni Aggiuntive: ...';
this.sendMsg(msg.chat.id, mystr);
}
async menuAssistenza(msg) {
const mystr = 'Per contattarci usa questa chat di gruppo: ....';
const mystr = 'Per contattarci usa la chat di gruppo al seguente link: ....';
this.sendMsg(msg.chat.id, mystr);
}
@@ -146,6 +227,10 @@ class Telegram {
return this.arrUsers.find((rec) => rec.id === msg.from.id);
}
deleteRecInMem(msg) {
this.arrUsers = this.arrUsers.filter((rec) => rec.id !== msg.from.id);
}
async setUsernameBo(msg) {
try {
const rec = this.getRecInMem(msg);
@@ -156,10 +241,11 @@ class Telegram {
rec.username_bo = text;
// Check if username exist
const user = await User.findByUsername(this.idapp, rec.username_bo.toLowerCase());
const user = await User.findByUsername(this.idapp, rec.username_bo);
if (!user) {
this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND)
} else {
rec.user = user;
await User.SetTelegramCheckCode(this.idapp, rec.username_bo, rec.code);
rec.status = Status.WAITFOR_VERIFY_CODE;
this.sendMsg(msg.from.id, txt.MSG_VERIFY_CODE)
@@ -180,10 +266,18 @@ class Telegram {
async setVerifyCode(msg) {
try {
const rec = this.getRecInMem(msg);
const user = await User.findByUsername(this.idapp, rec.username_bo);
const code = msg.text.toString().trim();
let telegcode = 0;
if (user) {
telegcode = user.profile.teleg_checkcode.toString();
} else {
this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND);
return
}
if (msg.text.length < 7) {
if (rec) {
if (code === msg.text) {
if (code === telegcode) {
rec.status = Status.VERIFIED;
await User.SetTelegramIdSuccess(this.idapp, rec.username_bo, msg.from.id).then((recuser) => {
if (recuser) {
@@ -215,18 +309,21 @@ class Telegram {
let status = this.getstatusInMemory(msg);
if (status === Status.NONE) {
await this.start(msg);
let status = this.getstatusInMemory(msg);
if (status !== Status.VERIFIED)
return
}
status = this.getstatusInMemory(msg);
if (status === Status.WAITFOR_USERNAME_BO) {
this.setUsernameBo(msg)
await this.setUsernameBo(msg)
} else if (status === Status.WAITFOR_VERIFY_CODE) {
this.setVerifyCode(msg)
await this.setVerifyCode(msg)
} else if (status === Status.NONE) {
this.start(msg);
await this.start(msg);
} else if (status === Status.VERIFIED) {
// Check Menu
this.isMenu(msg);
await this.isMenu(msg);
}
}
@@ -249,8 +346,10 @@ class Telegram {
if (user && !rec) {
rec = this.addUser(msg);
}
if (rec)
if (rec) {
rec.user = user;
rec.username_bo = user.username_bo
}
return !!rec
}
@@ -295,12 +394,29 @@ class Telegram {
}
});
}
msgScegliMenu(msg) {
this.bot.sendMessage(msg.from.id, txt.MSG_SCEGLI_MENU, {
"reply_markup": {
"keyboard": MenuStandard
}
});
}
}
const arrTelegram = [];
function getclTelegBytoken(token) {
const rec = arrTelegram.find((rec) => rec.cl.token === token)
const rec = arrTelegram.find((rec) => rec.cl.token === token);
if (!!rec)
return rec.cl;
else
return null;
}
function getclTelegByidapp(idapp) {
const rec = arrTelegram.find((rec) => rec.idapp === idapp);
if (!!rec)
return rec.cl;
else
@@ -368,5 +484,3 @@ for (const idapp of appTelegram) {
}