Reputation: 156
I am trying to build a Discord Music Bot and I need to search the YouTube using keywords given by the user. Currently I know how to play from a url.
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor( None, lambda: ytdl.extract_info(url, download=not stream))
if "entries" in data:
data = data["entries"][0]
filename = data["url"] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
Upvotes: 3
Views: 17737
Reputation: 3994
Youtube_DL has a extract_info
method that you can use. Instead of giving it a link, you just have to pass ytsearch:args
like so:
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
A few important things with this function:
video_infos = search("30 sec video")
#Doesn't contain all the data, some keys are not very important
cleared_data = {
'channel': video['uploader'],
'channel_url': video['uploader_url'],
'title': video['title'],
'description': video['description'],
'video_url': video['webpage_url'],
'duration': video['duration'], #in seconds
'upload_date': video['upload_data'], #YYYYDDMM
'thumbnail': video['thumbnail'],
'audio_source': video['formats'][0]['url'],
'view_count': video['view_count'],
'like_count': video['like_count'],
'dislike_count': video['dislike_count'],
}
Upvotes: 10
Reputation: 394
I'm not sure youtube-dl is good to search for youtube urls using keywords. You should probably take a look at youtube-search for this.
Upvotes: 0