Discord.py-Rewrite 在出现未知命令或其他错误时发送错误消息

问题描述

我希望能够发送类似 await ctx.send("Error: Unknown command. Do -help for accepted commands." 之类的消息(仅供参考,我我不问如何删除 Help is already a defined function 或类似的东西.);但我不知道如何为不是命令的东西制作错误消息,比如 if命令有一个错误,就像他们没有输入任何参数然后我可以为那个 @command.error 出错然后我定义它.但我不知道如何开始这个.如果可能的话,是否有一种方法可以在代码底部检查错误是什么?比如如果他们需要管理员但他们缺少它然后 if isinstance(error, commands.MissingPermissions): 或者如果他们需要允许服务器成员向他们发送消息,也许需要检查不同的事情?

I want to be able to send a message like await ctx.send("Error: Unknown command. Do -help for acceptable commands." or something like that (FYI, I'm not asking how to remove the Help is already a defined function or something like that.); But I don't know how to make an error message for something that isn't a command, Like if there is an error with a command like they didn't put any parameters then I'm able to make an error for that @command.error then i define it. But I'm not sure how to start this. And if possible, would there be a way where at the bottom of the code, is checked what the error is? like if they need admin but they are missing it then if isinstance(error, commands.MissingPermissions): or if they need to allow server members to message them, maybe it would have a different thing to check?

TLDR;我希望能够在我的代码底部有一个东西来检查是否有错误,如果有,如果它是由命令不存在引起的(然后它用 ctx.send) 但如果它是由于缺少管理员或缺少角色造成的,或者他们可能需要允许服务器成员在隐私设置中对他们进行 dm,那么它也会说明一些事情.我不想为每个命令都定义一个错误.

TLDR; I want to be able to have at the bottom of my code a thing that checks if there was an error and if so, if its caused by the command not existing (then it says something with ctx.send) but if its caused by missing admin or missing role, or possibly them needing to allow server members to dm them in privacy settings, then it also says something. I don't want to have to define an error for every command.

我还有一个需要数字才能工作的命令,我想要一个代码块来检查它是否为整数,如果不是,则给出一个错误,指出它需要是一个数字.然后检查它是否为正数,如果不是,则给出错误.

I also have a command that requires numbers to work, and i want a block of code that checks if its an integer, and if not, gives an error saying that it needs to be a number. Then checks if its a positive number, and if not, gives an error.


解决方案

Discord.py 有一个 on_command_error 事件,以错误为参数.你可以这样使用它:

Discord.py has a on_command_error event, which takes the error as argument. You can use it this way:

@bot.event
async def on_command_error(ctx, error):
    await ctx.send(f"An error occured: {str(error)}")

这是每个 的列表不和谐的例外.
如果您想为每个错误提供自定义消息,您可以这样做:

Here's a list of every discord exeptions.
If you want a custom message for each error, you can do it this way:

@bot.event
async def on_message_error(ctx, error):
    if isinstance(error, discord.ext.commands.errors.CommandNotFound):
        await ctx.send("Unknown command")

相关文章