telegram-image-uploader-bot/index.js

83 lines
3 KiB
JavaScript
Raw Normal View History

2017-08-18 10:04:14 +00:00
const TelegramBot = require('node-telegram-bot-api');
const config = require('./config');
// Be sure to replace YOUR_BOT_TOKEN with your actual bot token on this line.
let telegram = new TelegramBot(config.botId, {
polling: true
});
let admin_chatId = config.admin.id;
const SLIDESHOW_LOCATION = config.slideShowFolderPath; // Ends with '/'
telegram.on('message', (msg) => {
const chatId = msg.chat.id;
if (userAllowd(msg)) {
handleMessage(msg);
} else {
telegram.sendMessage(chatId, 'Sorry ' + msg.from.username + ' My master says I can\'t talk to strangers...');
console.log('Unauthorized user: ', msg.from.username, 'Message:');
console.log(JSON.stringify(msg, null, 2));
notifyAdmin('Unauthorized user: ' + msg.from.username + ' Message:\n' + JSON.stringify(msg, null, 2));
}
});
// Location Of HardDrive - /media/64C6A9C4724C63E5/slideshow
function storeFile(fileId, callback) {
telegram.downloadFile(fileId, SLIDESHOW_LOCATION)
.then((filePath) => {
callback(null, "YAYYY!!! file saved at: " + filePath);
})
.catch((err) => {
callback(err);
});
}
let storeFileCallback = (err, message, chatId, photo_id) => {
if (err) {
telegram.sendMessage(chatId, 'Failed to store your photo! - ' + err);
if (admin_chatId !== chatId) notifyAdmin('Hi Master!!,\nA Failed attemt to save a file to slideshow', photo_id);
} else {
telegram.sendMessage(chatId, message);
if (admin_chatId !== chatId) notifyAdmin('Hi Master!!,\nA photo was saved to your slideshow', photo_id);
}
};
let handleMessage = (msg) => {
const chatId = msg.chat.id;
if (msg.photo || (msg.document && msg.document.mime_type.indexOf('image/') === 0)) {
if (msg.photo) {
storeFile(msg.photo[msg.photo.length - 1].file_id, (err, message) => {
storeFileCallback(err, message, chatId, msg.photo[msg.photo.length - 1].file_id);
});
} else { // document - uncompressed photo
storeFile(msg.document.file_id, (err, message) => {
storeFileCallback(err, message, chatId, msg.document.file_id);
});
}
} else if(msg.contact) {
notifyAdmin('User with ID of: ' + msg.contact.user_id + ' Should be added/removed!');
}
else {
// send a message to the chat acknowledging receipt of their message
telegram.sendMessage(chatId, 'Hey dude... I can only help you save photos to your home slideshow.... other functions later :)');
}
};
let userAllowd = (msg)=>{
if(msg.from.username === config.admin.username) {
admin_chatId = msg.chat.id;
return true;
}
if(config.permissions.allowAll) return true;
if(config.permissions.usernames.indexOf(msg.from.username) >= 0) return true;
if(config.permissions.userIds.indexOf(msg.from.id) >= 0) return true;
return false;
};
let notifyAdmin = (msg, photo_id) => {
console.log(admin_chatId);
if (admin_chatId != null && config.admin.notifyActivity){
telegram.sendMessage(admin_chatId, msg);
if(photo_id) telegram.sendPhoto(admin_chatId, photo_id);
}
};