首页 > 解决方案 > discord.py 针对不同的检查失败引发不同的错误

问题描述

我有一个带有命令的 discord.py 机器人test。我想运行两次检查,首先检查运行它的人是否是机器人所有者,然后检查命令是否在 dm 中运行。如果机器人在 dm 中运行,我希望它发送一条消息,但如果它不是所有者,我希望它运行一条不同的消息。我该怎么做?

@bot.command()
@commands.guild_only()
@commands.check(is_owner)
async def test(ctx):
    await ctx.send("Good job you passed the checks!")
@test.error
async def test_error(ctx, error):
    if failed guild_only():
        await ctx.send("Hey only use this in a guild")
    if failed is_owner():
        await ctx.send("You're not the owner!!")

标签: pythondiscorddiscord.py

解决方案


使用isinstance().

isinstance检查对象是否具有指定的类型。例如,isinstance(3, int)检查 3 是否为整数(它是整数,因此返回True)。在您的情况下,您可以检查错误是否commands.NoPrivateMessage是由 引发的guild_only,或者错误是否commands.NotOwner是由引发的is_owner。正确的代码是:

@test.error
async def test_error(ctx, error):
    if isinstance(error, commands.NoPrivateChannel):
        await ctx.send("Hey only use this in a guild")
    if isinstance(error, commands.NotOwner):
        await ctx.send("You're not the owner!!")

推荐阅读