错误消息不起作用 100% Discord bot

Error messsage not working 100% Discord bot

我用音乐机器人命令扩展了我的机器人。一切正常,除了一件事。当机器人加入语音频道并且用户键入 !play (url) 时,它应该播放音乐。它就是这样做的。但是当用户忘记输入 url 或输入错误的 url 时,我想发送一条错误消息。当它为空时它可以工作,但当它无效时它不会发送消息。

所以它在@play.error 中出错了。它执行最后一个 elif 但不执行第一个 if 语句。有人知道为什么吗?

  @commands.command()
  async def play(self,ctx,url):
    ctx.voice_client.stop()
    FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
    YDL_OPTIONS = {'format':"bestaudio"}
    vc = ctx.voice_client

    with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
      info = ydl.extract_info(url, download=False)
      url2 = info['formats'][0]['url']
      source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
      vc.play(source)

  @play.error
  async def play_error(self, ctx, error):
    if isinstance(error, commands.BadArgument):
        await ctx.send("Please make sure it's a valid youtube url.")
    elif isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("Please enter a youtube url.")

当给ydl.extract_info(url, download=False)的URL无效时, youtube_dl 抛出异常 youtube_dl.utils.ExtractorError(我认为)。

但是在你的错误捕捉器中,你只寻找 BadArgument, MissingRequiredArgument.

我会尝试添加另一个:到 @play.error 并捕获您可能遗漏的其他错误。

@play.error
  async def play_error(self, ctx, error):
    if isinstance(error, commands.BadArgument):
        await ctx.send("Please make sure it's a valid youtube url.")
    elif isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("Please enter a youtube URL.")
    else:
        print(f"Unknowen Error: {repr(error)}")  # If you want to send the error to discord just replace print with await ctx.send()