Discord.py:如何在play命令上实现ytsearch?

2024-06-25 23:34:51 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,伙计们,我创建了这个音乐机器人,我想在播放按钮上实现ytsearch,就像机器人“Rythm”。目前,它只能通过url播放音乐,但我希望我的机器人能够使用相同的命令从url和关键字(比如!play never Toll Gill you)播放音乐,但我不知道如何做到这一点。你们能帮帮我吗

musics= {}
ytdl = youtube_dl.YoutubeDL()

class Video:
    def __init__(self, link):
        video = ytdl.extract_info(link, download = False)
        video_format = video["formats"][0]
        self.url =video["webpage_url"]
        self.stream_url =video_format["url"]

def play_song(client, queue, song):
    source= discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(song.stream_url
    , before_options = "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5"))
    
    def next(_):
        if len(queue)>0:
            new_song= queue[0]
            del queue[0]
            play_song(client, queue, new_song)
        else:
            asyncio.run_coroutine_threadsafe(client.disconnect(), bot.loop)
    
    
    client.play(source, after=next)


@bot.command()
async def play (ctx, url):
    client = ctx.guild.voice_client
    if client and client.channel:
        video = Video(url)
        musics[ctx.guild].append(video)
    else:
        channel = ctx.author.voice.channel
        video = Video(url)
        musics[ctx.guild] = []
        client = await channel.connect()
        await ctx.send(f"Playing : {video.url}")
        play_song(client, musics[ctx.guild], video)

编辑: 因此,在triying添加ytdl_选项后,它会给我这个错误,即使没有--noplaylist,它也会给我同样的错误(我triying要播放的音乐是眩目的灯光)

ytdl_options = {
    'noplaylist': True,
    'default_search': 'auto'
}


ytdl = youtube_dl.YoutubeDL(ytdl_options)
[download] Downloading playlist: blinding
[youtube:search] query "blinding": Downloading page 1
[youtube:search] playlist blinding: Downloading 1 videos
[download] Downloading video 1 of 1
[youtube] 4NRXx6U8ABQ: Downloading webpage
[youtube] Downloading just video 4NRXx6U8ABQ because of --no-playlist
[download] Finished downloading playlist: blinding
Ignoring exception in command play:
Traceback (most recent call last):
  File "C:\Users\pietr\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\pietr\Desktop\Discord bot\Discord bot", line 152, in play
    video = Video(url)
  File "c:\Users\pietr\Desktop\Discord bot\Discord bot", line 93, in __init__
    video_format = video["formats"][0]
KeyError: 'formats'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\pietr\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\pietr\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\pietr\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'formats'

Tags: inclienturlplaysongyoutubevideobot
2条回答

创建YoutubeDL对象时,可以通过设置default_search选项来指定其默认搜索行为

引自here(重点矿山):

Use this prefix for unqualified URLs. For example "gvsearch2:" downloads two videos from google videos for youtube-dl "large apple". Use the value "auto" to let youtube-dl guess ("auto_warning" to emit a warning when guessing). "error" just throws an error. The default value "fixup_error" repairs broken URLs, but emits an error if this is not possible instead of searching.

ytdl_options = {'default_search': 'auto'}
ytdl = youtube_dl.YoutubeDL(ytdl_options)

您需要处理完成搜索的情况,因为返回的格式与提供有效URL时不同

import youtube_dl

ytdl_options = {
    'noplaylist': True,
    'default_search': 'auto'
}

ytdl = youtube_dl.YoutubeDL(ytdl_options)

link = 'test search'

video = ytdl.extract_info(link, download = False)

if 'entries' in video:
    video_format = video['entries'][0]["formats"][0]
elif 'formats' in video:
    video_format = video["formats"][0]

url = video["webpage_url"]
stream_url = video_format["url"]

可能想看看Youtube API。将resource更改为search,然后单击list (by keyword)。您将在上面获得示例代码

您首先需要Obtain authorization credentials以使其正常工作

相关问题 更多 >