discord.py - 在出现 MissingRequiredArgument 错误时显示正确的命令语法
discord.py - showing correct syntax of command whenever there is a MissingRequiredArgument error
我已经开始开发一个新的 discord 机器人。目前,每当出现错误时,我都会调用 on_command_error
函数来发送消息。现在,每当出现 MissingRequiredArgument 错误时,我希望机器人显示错误消息和命令的正确语法。目前我已经尝试手动添加所有这些,但是非常耗时而且不值得。我知道 discord.py 可以显示命令语法,因为默认帮助命令也可以显示命令语法。
那么有什么方法可以将相同的逻辑导入到我的代码中吗?
您可以为此使用一些 commands.Command
class 属性。
查看文档,这个 class 有一个 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
,机器人将发送:
Failed converting an argument
Correct usage: !round 3.14159265359
我已经开始开发一个新的 discord 机器人。目前,每当出现错误时,我都会调用 on_command_error
函数来发送消息。现在,每当出现 MissingRequiredArgument 错误时,我希望机器人显示错误消息和命令的正确语法。目前我已经尝试手动添加所有这些,但是非常耗时而且不值得。我知道 discord.py 可以显示命令语法,因为默认帮助命令也可以显示命令语法。
那么有什么方法可以将相同的逻辑导入到我的代码中吗?
您可以为此使用一些 commands.Command
class 属性。
查看文档,这个 class 有一个 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
,机器人将发送:
Failed converting an argument
Correct usage: !round 3.14159265359