telegram-video-downloader/main.py

64 lines
1.9 KiB
Python
Raw Normal View History

2017-07-23 10:17:25 +02:00
import logging
2017-08-14 20:42:37 +02:00
from time import sleep
2017-07-23 10:17:25 +02:00
2017-08-09 14:49:25 +02:00
from telegram import InlineKeyboardMarkup
from telegram.ext import Updater, CallbackQueryHandler, MessageHandler, Filters
2017-08-06 15:49:22 +02:00
2017-08-14 20:42:37 +02:00
from vid_utils import Video, VideoQueue, BadLink
2017-07-23 10:17:25 +02:00
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
2017-07-23 10:17:25 +02:00
logger = logging.getLogger(__name__)
2017-08-14 20:42:37 +02:00
VIDEOS = VideoQueue()
def get_format(bot, update):
2017-08-14 20:42:37 +02:00
logger.info("from {}: {}".format(update.message.chat_id, update.message.text)) # "history"
2017-08-14 20:42:37 +02:00
try:
video = Video(update.message.text, update.message.chat_id)
except BadLink:
update.message.reply_text("Bad link")
else:
2017-08-19 17:34:53 +02:00
for i, v in enumerate(VIDEOS):
if v.chat_id == video.chat_id:
VIDEOS[i] = video # remove old video not downloaded...
break
else:
VIDEOS.append(video)
2017-08-14 20:42:37 +02:00
reply_markup = InlineKeyboardMarkup(video.keyboard)
update.message.reply_text('Choose format:', reply_markup=reply_markup)
def download_choosen_format(bot, update):
query = update.callback_query
bot.edit_message_text(text="Downloading...",
chat_id=query.message.chat_id,
message_id=query.message.message_id)
2017-08-14 20:42:37 +02:00
while VIDEOS.lock: sleep(1) # finish old download
VIDEOS.lock = True # maybe we can use a contextmanager?
for i, video in enumerate(VIDEOS):
if video.chat_id == query.message.chat_id:
VIDEOS.pop(i)
video.download(query.data)
2017-08-09 14:49:25 +02:00
with video.send() as files:
for f in files:
bot.send_document(chat_id=query.message.chat_id, document=open(f, 'rb'))
2017-08-14 20:42:37 +02:00
VIDEOS.lock = False
2017-08-09 14:49:25 +02:00
updater = Updater(token=YOUR_TOKEN)
2017-07-23 10:17:25 +02:00
updater.dispatcher.add_handler(MessageHandler(Filters.text, get_format))
updater.dispatcher.add_handler(CallbackQueryHandler(download_choosen_format))
2017-07-23 10:17:25 +02:00
# Start the Bot
2017-07-23 10:17:25 +02:00
updater.start_polling()
updater.idle()