Reputation: 13
i am writing an all purpose bot basicly i want to to type the command and then a song name example:?play song-name
and it will search youtube and the first video that pops up it will download the audio of it
I got the bot to work with normal links but if i have to get the link to play the music it defeats the purpose
client = discord.Client()
@client.event
async def on_message(message):
ydl_opts = {
'format': 'beataudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192'
}]
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
print("Downloading audio now\n")
url: str = message.content.replace('?play ', '')
print(url)
ydl.download([url])
i did not use youtube-dl before so I donot know how it works.
Upvotes: 1
Views: 1810
Reputation: 99011
Once you get the discord search query, you can use:
import youtube_dl # youtube-dl-2020.3.1
import traceback, os, json
from youtube_search import YoutubeSearch # pip install youtube_search
"""
sources :
https://github.com/ytdl-org/youtube-dl/blob/master/README.md#embedding-youtube-dl
https://stackoverflow.com/questions/23727943/how-to-get-information-from-youtube-dl-in-python/31184514#31184514
https://stackoverflow.com/a/43143553/797495
"""
search = 'carlos paiao playback'
ydl_opts = {
'format': 'beataudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192'
}]
}
yt = YoutubeSearch(search, max_results=1).to_json()
try:
yt_id = str(json.loads(yt)['videos'][0]['id'])
yt_url = 'https://www.youtube.com/watch?v='+yt_id
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([yt_url])
info = ydl.extract_info(yt_url)
songname = info.get('title', None) + "-" + yt_id + ".mp3"
if os.path.isfile(songname):
print("Song Downloaded: " + songname)
else:
print("Error: " + songname)
except:
pass
print(traceback.print_exc())
print("no results")
Upvotes: 1