如何在youtube-dl和discord.py中使用关键字而不是网址? [英] how to use a key words instead of a url with youtube-dl and discord.py?
本文介绍了如何在youtube-dl和discord.py中使用关键字而不是网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我基本上是在编写一个通用机器人,我想先键入命令,然后输入歌曲名称示例:?play song-name
,它将搜索youtube和弹出它的第一个视频将下载音频
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])
我以前没有使用过youtube-dl,所以我不知道它是如何工作的.
i did not use youtube-dl before so I donot know how it works.
推荐答案
一旦获得不和谐搜索查询,您可以使用:
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")
这篇关于如何在youtube-dl和discord.py中使用关键字而不是网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文