【问题标题】:Discord.py: How to implement ytsearch on the play command?Discord.py:如何在播放命令上实现 ytsearch?
【发布时间】:2021-07-14 02:01:28
【问题描述】:

大家好,我创建了这个音乐机器人,我想在播放按钮上实现 ytsearch,比如机器人“Rythm”。目前它只能使用 url 播放音乐,但我希望我的机器人能够使用相同的命令从 url 和关键字播放(比如!play 永远不会放弃你),但我不知道该怎么做.你们能帮帮我吗?

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)

编辑: 因此,在尝试添加 ytdl_options 后,它给了我这个错误,即使没有 --noplaylist,它仍然给我同样的错误(我试图播放的音乐是眩目的灯光)。

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'

【问题讨论】:

    标签: python discord discord.py bots youtube-dl


    【解决方案1】:

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

    引自here(强调我的):

    对不合格的 URL 使用此前缀。例如“gvsearch2:”为 youtube-dl“大苹果”从谷歌视频下载两个视频。 使用值“auto”让 youtube-dl 猜测(“auto_warning”在猜测时发出警告)。 “错误”只是抛出一个错误。默认值“fixup_error”修复损坏的 URL,但如果无法执行此操作,则会发出错误,而不是搜索。

    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"]
    

    【讨论】:

    • 我试过了,但它给了我一个关键错误:“格式”。我该怎么办??
    • 你能告诉我你正在尝试什么以及你得到的确切错误吗?
    • 我在编辑帖子时遇到了错误,希望您能帮助我。
    【解决方案2】:

    可能想看看Youtube API。将resource 更改为search,然后单击list (by keyword)。你会得到它的示例代码。

    您首先需要Obtain authorization credentials 才能使其正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      • 2014-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多