main.py 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import os
  2. import logging
  3. from glob import glob
  4. from subprocess import Popen, PIPE
  5. from telegram import InlineKeyboardButton, InlineKeyboardMarkup
  6. from telegram.ext import (Updater, CommandHandler, CallbackQueryHandler,
  7. MessageHandler, Filters)
  8. from vid_utils import check_dimension
  9. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  10. level=logging.INFO)
  11. logger = logging.getLogger(__name__)
  12. #TODO I don't like these global vars...
  13. formats = [] # aviable format of the video
  14. link = '' #link of the video
  15. def generate_keyboard(l):
  16. """ return a keyboard fom list l """
  17. kb = []
  18. for code, extension, resolution in l:
  19. kb.append([InlineKeyboardButton("{0}, {1}".format(extension, resolution),
  20. callback_data=code)])
  21. return kb
  22. def get_format(bot, update):
  23. global link
  24. link = update.message.text # saving link in global var
  25. formats[:] = [] # remove old formats
  26. for f in glob('*.mp4*') + glob('*.webm*'): # with glob it is not possible check multiple extension in one regex
  27. os.remove(f) # remove old video(s)
  28. try:
  29. """
  30. p = subprocess.Popen("youtube-dl -F {}".format(update.message.text), shell=True, stdout=subprocess.PIPE) # this line can be very dangerous, there is a serious command-injection problem
  31. p = p.communicate()
  32. """
  33. cmd = "youtube-dl -F {}".format(update.message.text) # this line can be very dangerous, there is a serious command-injection problem
  34. p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
  35. p = p.communicate()
  36. it = iter(str(p[0], 'utf-8').split('\n'))
  37. while not "code extension" in next(it): # Remove garbage lines, i need only the formats
  38. pass
  39. while True: # save the formats in the formats list
  40. try:
  41. line = next(it)
  42. if not line: # the last line is empty...
  43. raise StopIteration
  44. except StopIteration:
  45. break
  46. else:
  47. format_code, extension, resolution, *_ = line.strip().split()
  48. formats.append([format_code, extension, resolution])
  49. except Exception as e:
  50. bot.sendMessage(chat_id=update.message.chat_id, text='Error: {}'.format(e))
  51. logger.info(e)
  52. raise e
  53. else:
  54. reply_markup = InlineKeyboardMarkup(generate_keyboard(formats))
  55. update.message.reply_text('Choose format:', reply_markup=reply_markup)
  56. def download_choosen_format(bot, update):
  57. query = update.callback_query
  58. bot.edit_message_text(text="Downloading...",
  59. chat_id=query.message.chat_id,
  60. message_id=query.message.message_id)
  61. os.system("youtube-dl -f {0} {1}".format(query.data, link))
  62. for f in glob('*.mp4*') + glob('*.webm*'):
  63. check_dimension(f)
  64. break # check first file
  65. for f in glob('*.mp4*') + glob('*.webm*'): # send document(s)
  66. bot.send_document(chat_id=query.message.chat_id, document=open(f, 'rb'))
  67. updater = Updater(token=INSERT_YOUR_TOKEN_HERE)
  68. updater.dispatcher.add_handler(MessageHandler(Filters.text, get_format))
  69. updater.dispatcher.add_handler(CallbackQueryHandler(download_choosen_format))
  70. # Start the Bot
  71. updater.start_polling()
  72. updater.idle()