Erfan commited on
Commit
06e9041
·
1 Parent(s): 0cf9dca

fix: robust yt download with fallback formats

Browse files
Files changed (1) hide show
  1. bot/youtube.py +28 -23
bot/youtube.py CHANGED
@@ -24,7 +24,7 @@ def _base_opts():
24
  }
25
 
26
 
27
- def _get_ydl_opts(format_spec: str, ext: str):
28
  opts = {
29
  "format": format_spec,
30
  "outtmpl": os.path.join(DOWNLOAD_DIR, f"{uuid.uuid4()}.%(ext)s"),
@@ -34,6 +34,14 @@ def _get_ydl_opts(format_spec: str, ext: str):
34
  return opts
35
 
36
 
 
 
 
 
 
 
 
 
37
  async def get_video_info(url: str):
38
  ydl_opts = _base_opts()
39
  ydl_opts.update(_cookies_opts())
@@ -49,26 +57,23 @@ async def get_video_info(url: str):
49
 
50
  async def download_yt(url: str, quality: str = "audio"):
51
  if quality == "audio":
52
- opts = _get_ydl_opts("bestaudio", "mp4")
53
- elif quality == "720p":
54
- opts = _get_ydl_opts("best", "mp4")
55
- elif quality == "1080p":
56
- opts = _get_ydl_opts("best", "mp4")
57
  else:
58
- opts = _get_ydl_opts("best", "mp4")
59
-
60
- with yt_dlp.YoutubeDL(opts) as ydl:
61
- info = ydl.extract_info(url, download=True)
62
- file_path = ydl.prepare_filename(info)
63
- base, _ = os.path.splitext(file_path)
64
- if quality == "audio":
65
- file_path = base + ".mp3"
66
- else:
67
- file_path = base + ".mp4"
68
- if os.path.exists(file_path):
69
- return file_path, info.get("title", "video")
70
- for f in os.listdir(DOWNLOAD_DIR):
71
- p = os.path.join(DOWNLOAD_DIR, f)
72
- if os.path.isfile(p):
73
- return p, info.get("title", "video")
74
- return None, None
 
 
24
  }
25
 
26
 
27
+ def _get_ydl_opts(format_spec: str):
28
  opts = {
29
  "format": format_spec,
30
  "outtmpl": os.path.join(DOWNLOAD_DIR, f"{uuid.uuid4()}.%(ext)s"),
 
34
  return opts
35
 
36
 
37
+ def _find_downloaded_file():
38
+ for f in os.listdir(DOWNLOAD_DIR):
39
+ p = os.path.join(DOWNLOAD_DIR, f)
40
+ if os.path.isfile(p):
41
+ return p
42
+ return None
43
+
44
+
45
  async def get_video_info(url: str):
46
  ydl_opts = _base_opts()
47
  ydl_opts.update(_cookies_opts())
 
57
 
58
  async def download_yt(url: str, quality: str = "audio"):
59
  if quality == "audio":
60
+ formats = ["bestaudio", "best"]
 
 
 
 
61
  else:
62
+ formats = ["best", "worst"]
63
+
64
+ for fmt in formats:
65
+ try:
66
+ opts = _get_ydl_opts(fmt)
67
+ with yt_dlp.YoutubeDL(opts) as ydl:
68
+ info = ydl.extract_info(url, download=True)
69
+ file_path = ydl.prepare_filename(info)
70
+ if os.path.exists(file_path):
71
+ return file_path, info.get("title", "video")
72
+ found = _find_downloaded_file()
73
+ if found:
74
+ return found, info.get("title", "video")
75
+ except Exception as e:
76
+ print(f"[youtube] Format {fmt} failed: {e}")
77
+ continue
78
+
79
+ return None, None