0

I'm trying to make a Discord bot in Python that plays Youtube videos as audios in a voice channel. Right now, my bot uses a combination using yt_dlp and youtube_search. It firstly uses youtube_search to get the URL of the video searched by keyword. Then, yt_dlp gets the direct audio link given to discord.FFmpegPCMAudio. However, this takes multiple seconds and I feel like it could be made shorter.

I found this post : Searching Youtube videos using youtube-dl that suggests to use this :

from requests import get
from youtube_dl import YoutubeDL

YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist':'True'}

def search(arg):
    with YoutubeDL(YDL_OPTIONS) as ydl:
        try:
            get(arg) 
        except:
            video = ydl.extract_info(f"ytsearch:{arg}", download=False)['entries'][0]
        else:
            video = ydl.extract_info(arg, download=False)

    return video

This looks great to me, however I'm trying to get the top 5 results. I found the equivalent of that command from the same module, but on my terminal, which is, for the keyword hello

yt-dlp ytsearch5:hello --get-url --get-title --print uploader

Can anyone help me turning that into a Python command? Thanks

Aza
  • 17
  • 1
  • 6

1 Answers1

0

According to the source code, extract_info will:

Return a list with a dictionary for each video extracted.

In your case, you need the top 5 from this list but in your code you only take the very first one with [0]. Change this to [0:5] to get the top 5.

from requests import get
from youtube_dl import YoutubeDL

YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist':'True'}

def search(arg):
    with YoutubeDL(YDL_OPTIONS) as ydl:
        try:
            get(arg) 
        except:
            video = ydl.extract_info(f"ytsearch:{arg}", download=False)['entries'][0:5]
        else:
            video = ydl.extract_info(arg, download=False)

    return video
viggnah
  • 1,709
  • 1
  • 3
  • 12
  • Yep it's this, except i needed to transform `ytsearch:` into `ytsearch5:` so it'd look up 5 results – Aza Jul 27 '22 at 21:21