import os
import logging
from pathlib import Path
from functools import wraps
from dotenv import load_dotenv
from utils import Video, BadLink
from telegram import InlineKeyboardMarkup, ChatAction
from telegram.ext import Updater, CallbackQueryHandler, MessageHandler, Filters
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
def send_action(action):
def decorator(func):
@wraps(func)
def command_func(update, context, *args, **kwargs):
context.bot.send_chat_action(chat_id=update.effective_message.chat_id, action=action)
return func(update, context, *args, **kwargs)
return command_func
return decorator
send_typing_action = send_action(ChatAction.TYPING)
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
@send_typing_action
def get_format(update, context):
logger.info("from {}: {}".format(update.message.chat_id, update.message.text))
try:
video = Video(update.message.text, init_keyboard=True)
except BadLink:
update.message.reply_text("Your link is not valid")
else:
reply_markup = InlineKeyboardMarkup(video.keyboard)
update.message.reply_text('Choose format:', reply_markup=reply_markup)
@send_typing_action
def download_desired_format(update, context):
query = update.callback_query
resolution_code, link, merge_formats = query.data.split(' ', 2)
print('chat_id: ', query.message.chat_id)
print('Merge formats: ', merge_formats)
query.edit_message_text(text="Downloading")
video = Video(link)
video.download(resolution_code, merge_formats)
with video.send() as files:
for f in files:
context.bot.send_document(chat_id=query.message.chat_id, document=open(f, 'rb'))
updater = Updater(token=os.getenv("TG_BOT_TOKEN"), use_context=True)
updater.dispatcher.add_handler(MessageHandler(Filters.text, get_format))
updater.dispatcher.add_handler(CallbackQueryHandler(download_desired_format))
updater.start_polling()
updater.idle()