Search code examples
pythonpython-telegram-botpytube

a python-telegram-bot Unsupported url protocol


So, I was Trying To Create a Telegram Bot That By Using The PyTube Moudle, Will Download The Video To My Computer And Then Send It To The User By The send_document Function.

My Problem Is When I Need To Send The Video, I Get This Error:

telegram.error.BadRequest: Invalid file http url specified: unsupported url protocol

I've Tried It On a Regular Text File And Got The Same Results.

I Assume It's Because The Url of The File Is Breaking Some Rules of How It Should Look Like, But I Don't Know How To Fix It...

Also Here Is My Code:

import telegram.ext
import telegram
from telegram.ext.messagehandler import MessageHandler
from telegram.ext.commandhandler import CommandHandler
from telegram.ext.filters import Filters
import time
import pytube
import os

with open('C:/Users/EvilTwin/Desktop/stuff/Python/API/Telegram/Download Youtube Videos Bot/token.txt')as file:
    API_KEY = file.read()


updater = telegram.ext.Updater(token=API_KEY, use_context=True)


def start(update, context):
    update.message.reply_text(f'Hello {update.effective_user.first_name}, I\'m Roee\'s Video Downloader!')
    time.sleep(1)
    update.message.reply_text(    
    f'''
To Download Videos Please Enter:
/download + Video URL  + Format
    
    ''')

def download(update, context):
    URL = context.args[0]
    FORMAT = context.args[1]
    VIDEO = pytube.YouTube(URL)
    FILE = VIDEO.streams.filter(progressive=True, file_extension=FORMAT).order_by('resolution').desc().first() 
    VD = 'C:/Users/EvilTwin/Desktop/stuff/Python/API/Telegram/Download Youtube Videos Bot/Videos'
    FILE.download(VD)
    banned = ['/', '/-\\', ':', '?', '!', '*', '>', '<', '"', '|']
    for ban in  banned:
        VIDEO.title = VIDEO.title.replace(ban, '')
    time.sleep(1)
    DOC = f'{VD}/{VIDEO.title}.{FORMAT}'
    chat_id=update.effective_chat.id
    context.bot.send_document(chat_id = chat_id ,document=DOC, filename = f'video.{FORMAT}')
    os.remove(DOC)



updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CommandHandler('download', download))

updater.start_polling()
updater.idle()

If Anyone Knows How To Fix It Please Help Me....


Solution

  • For local file you have to use file object (file handler) instead of file name
    so you have to open it document=open(DOC, 'rb')

    context.bot.send_document(chat_id=chat_id, document=open(DOC, 'rb'), filename=f'video.{FORMAT}')
    

    Documentation shows also that you can use pathlib.Path or bytes (so it needs to read it document=open(DOC, 'rb').read()) but I didn't test it.

    See doc: send_document()