PyTube开发Telegram下载机器人调用send_document报错不支持URL协议
问题原因
- python-telegram-bot 库的
send_document方法对传入的字符串类型参数,默认会判定为网络HTTP/HTTPS URL,直接传入本地磁盘路径会被识别为非法协议,触发Invalid file http url specified: unsupported url protocol报错 - 原有代码存在逻辑顺序错误:先执行文件下载,再清洗视频标题中的非法字符,导致下载生成的实际文件名和后续拼接的路径不匹配,也会引发文件读取异常
修复方案
核心修复点
将send_document方法的document参数从本地路径字符串,改为二进制读取的文件对象,即可解决协议识别错误问题。
逻辑优化点
调整非法字符清洗的顺序,先处理文件名再下载文件,同时直接使用pytube的download方法返回的实际保存路径,避免手动拼接路径出错。
修改后的完整
download函数代码 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' # 先清洗文件名非法字符 banned = ['/', '/-\\', ':', '?', '!', '*', '>', '<', '"', '|'] clean_title = VIDEO.title for ban in banned: clean_title = clean_title.replace(ban, '') # 下载时指定文件名,直接获取实际保存路径 save_path = FILE.download(output_path=VD, filename=f"{clean_title}.{FORMAT}") chat_id=update.effective_chat.id # 传入文件对象替代路径字符串,解决协议报错 with open(save_path, 'rb') as f: context.bot.send_document(chat_id = chat_id ,document=f, filename = f'video.{FORMAT}') os.remove(save_path)
普通本地文件测试也可以使用相同逻辑,按document=open('本地文件路径', 'rb')格式传参即可。
内容的提问来源于stack exchange,提问作者roee1454
相关产品推荐
相关产品推荐

