【问题标题】:discord.py - showing correct syntax of command whenever there is a MissingRequiredArgument errordiscord.py - 出现 MissingRequiredArgument 错误时显示正确的命令语法
【发布时间】:2021-10-16 11:11:47
【问题描述】:

我已经开始开发一个新的不和谐机器人。目前每当出现错误时,我都会调用on_command_error 函数来发送消息。现在,每当出现 MissingRequiredArgument 错误时,我希望机器人显示错误消息和命令的正确语法。目前我已经尝试手动添加所有这些,但是非常耗时且不值得。我知道 discord.py 可以显示命令语法,因为默认的帮助命令也会这样做。

那么有什么方法可以将相同的逻辑导入到我的代码中?

【问题讨论】:

  • 命令行参数的帮助和函数调用之间存在一些差异。一般来说,您应该在缺少参数时咨询API documentation
  • @KlausD。 .已经尝试查看文档。找不到任何对这个特定问题有帮助的东西
  • 您提交的是X Y problem。您在调用时遇到问题,但您不是向我们展示相关代码和完整的错误回溯,而是要求一种可以(可能)为您提供已经存在的文档的自动化文档系统。

标签: python error-handling discord discord.py


【解决方案1】:

您可以为此使用一些commands.Command 类属性。
查看文档,这个类有一个usage 属性,您可以使用commands.command 装饰器进行设置。

假设我想做一个圆形命令:

from discord.ext import commands

bot = commands.Bot(command_prefix='!')

# Setting the command's name in the decorator to avoir overwriting the built-in round function
@bot.command(name='round', usage='3.14159265359')
async def _round(ctx, to_round: float):
    number = round(to_round, 1)
    await ctx.send(f'Rounded to one decimal: {number}')

如果我发送!round e,我会收到以下错误:

BadArgument: Converting to "float" failed for parameter "to_round"

但我可以处理它,就像你做的那样,on_command_error

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.BadArgument):
        usage = f'{bot.command_prefix}{ctx.command.name} {ctx.command.usage}'
        await ctx.send('Failed converting an argument\nCorrect usage: {usage}')

现在,如果我发送 !round e,机器人会发送:

转换参数失败
正确用法:!round 3.14159265359

【讨论】:

  • 你好。这确实有效!但仅适用于 BadArgument。如标题中所述,我正在寻找 MissingRequiredArgument 的解决方案。你也忘了把on_command_error的最后一行串起来,所以它会打印{usage}而不是它需要的
  • 代替ctx.command.usage,对于MissingRequiredArgument 使用ctx.command.signature
  • 你可以用它来处理你想要的任何错误,我只是举了一个例子,所以你可以理解如何使用它^^'我还说你可以使用其他属性。
猜你喜欢
  • 2013-12-05
  • 1970-01-01
  • 2016-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
  • 2017-10-02
  • 1970-01-01
相关资源
最近更新 更多