68 lines
2.2 KiB
JavaScript
68 lines
2.2 KiB
JavaScript
const TelegramBot = require("node-telegram-bot-api");
|
|
const fs = require("fs");
|
|
const DownloadVideo = require("./download");
|
|
|
|
const config = {
|
|
token: process.env.BOT_TOKEN,
|
|
admins: process.env.ADMIN_LIST?.split(/\s*,\s*/g).map(x => +x) ?? [],
|
|
};
|
|
config.whitelist = [].concat(
|
|
process.env.WHITELIST?.split(/\s*,\s*/g).map(x => +x) ?? [],
|
|
config.admins,
|
|
);
|
|
config.whitelist = Object.keys(
|
|
Object.fromEntries(config.whitelist.map(x => [x, true]))
|
|
).map(x => +x);
|
|
|
|
console.info(config);
|
|
|
|
config.admins = Object.fromEntries(config.admins.map(x => [x, true]));
|
|
config.whitelist = Object.fromEntries(config.whitelist.map(x => [x, true]));
|
|
|
|
const ytLinkRegexp = /^https:\/\/www\.youtube\.com/m;
|
|
class TgBot {
|
|
constructor () {
|
|
this.bot = new TelegramBot(config.token, {
|
|
polling: true
|
|
});
|
|
this.bot.on('text', m => this.newMessageHandler(m));
|
|
}
|
|
|
|
async newMessageHandler (msg) {
|
|
console.debug(msg);
|
|
if (msg.chat.id === msg.from.id) {
|
|
if (config.whitelist[msg.from.id]) {
|
|
if (ytLinkRegexp.test(msg.text)) {
|
|
const video = new DownloadVideo(msg.text);
|
|
// Download only video with best quality
|
|
this.download(msg, video);
|
|
} else {
|
|
this.bot.sendMessage(msg.chat.id, "Invalid youtube link");
|
|
}
|
|
}
|
|
else {
|
|
this.bot.sendMessage(msg.chat.id, "Permission denied");
|
|
}
|
|
}
|
|
}
|
|
|
|
async download (msg, video, quality=DownloadVideo.qualities.mp4_best) {
|
|
this.bot.sendMessage(msg.chat.id, "Start download");
|
|
await video.setupQuality(quality, false);
|
|
video.download()
|
|
.then(downloaded => {
|
|
if (/^video\//m.test(downloaded.format.mime)) {
|
|
this.bot.sendVideo(msg.chat.id, downloaded.data, { caption: "Download complete" }, {
|
|
filename: `downloaded.${downloaded.format.exc}`,
|
|
contentType: downloaded.format.mime
|
|
});
|
|
}
|
|
})
|
|
.catch(() => {
|
|
this.bot.sendMessage(msg.chat.id, "Download failed");
|
|
});
|
|
}
|
|
}
|
|
|
|
const bot = new TgBot();
|