main.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import os
  2. import logging
  3. from glob import glob
  4. import youtube_dl
  5. from telegram.ext import Updater, MessageHandler, Filters
  6. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  7. level=logging.INFO)
  8. logger = logging.getLogger(__name__)
  9. updater = Updater(token='TOKEN') # put here the bot's token
  10. dispatcher = updater.dispatcher
  11. ydl_opts = {
  12. 'restrictfilenames': True,
  13. }
  14. def download(bot, update):
  15. for f in glob('*.mp4'):
  16. os.remove(f) # remove old video(s)
  17. try:
  18. with youtube_dl.YoutubeDL(ydl_opts) as ydl:
  19. ydl.download([update.message.text])
  20. for f in glob('*.mp4'): # TODO this way for find the file(s) IMHO is not elegant
  21. bot.send_document(chat_id=update.message.chat_id, document=open(f, 'rb'))
  22. except Exception as e:
  23. bot.sendMessage(chat_id=update.message.chat_id, text='Error')
  24. logger.info(e)
  25. download_handler = MessageHandler(Filters.text, download)
  26. dispatcher.add_handler(download_handler)
  27. updater.start_polling()
  28. updater.idle()