如何在 youtube-dl 和 discord.py 中使用关键字而不是 url?
how to use a key words instead of a url with youtube-dl and discord.py?
我正在编写一个通用机器人,基本上我想输入命令,然后输入歌曲名称示例:?play song-name
它将搜索 youtube,弹出的第一个视频将下载它
我让机器人与正常的 link 一起工作,但如果我必须让 link 来播放音乐,那就达不到目的了
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])
我之前没有用过youtube-dl,所以我不知道它是如何工作的。
获得不和谐搜索查询后,您可以使用:
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
"""
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")
我正在编写一个通用机器人,基本上我想输入命令,然后输入歌曲名称示例:?play song-name
它将搜索 youtube,弹出的第一个视频将下载它
我让机器人与正常的 link 一起工作,但如果我必须让 link 来播放音乐,那就达不到目的了
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])
我之前没有用过youtube-dl,所以我不知道它是如何工作的。
获得不和谐搜索查询后,您可以使用:
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
"""
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")