没有正确角色的人使用命令会使机器人崩溃discord.py

问题描述 投票:0回答:1

我正在尝试这个

@commands.has_role("Buying/Selling Support")
@bot.hybrid_command(name="cookie_recipe", description="Sends Cookie  Recipe")

async def cookie_recipe(ctx):
   await ctx.send("Currently Uploading...")
   file = (discord.File("SHOP/src/cookie_recipe.txt"))
   await ctx.send(file=file)

当具有正确角色(“购买/销售支持”)的人使用它时,它工作正常,但一旦没有该角色的人使用它,它就会收到错误“discord.ext.commands.errors.MissingRole:角色”运行此命令需要“购买/销售支持”。”

帮助

我查看了堆栈溢出上的所有内容,并询问了一些朋友,但他们都不知道

python discord discord.py roles
1个回答
0
投票

通常,当您需要处理 Python 中的错误时,您可以使用

try/except
来避免崩溃。但如果我猜对了,您正在使用discord.py,那么您应该检查有关如何处理错误检查的文档。

另请阅读commands.has_role()

上的文档,它说:

此检查会引发两个特殊异常之一:如果用户缺少角色,则为 MissingRole;如果在私人消息中使用角色,则为 NoPrivateMessage。两者都继承自CheckFailure

根据文档处理用户在没有正确角色的情况下使用命令时出现的错误,您应该创建一个函数来处理它。在这种情况下,我们使用

CheckFailure
来处理可能出现的错误并避免崩溃机器人。

@commands.has_role("Buying/Selling Support")
@bot.hybrid_command(name="cookie_recipe", description="Sends Cookie  Recipe")

async def cookie_recipe(ctx):
   await ctx.send("Currently Uploading...")
   file = (discord.File("SHOP/src/cookie_recipe.txt"))
   await ctx.send(file=file)


@cookie_recipe.error
async def cookie_recipe_error(ctx, error):
    if isinstance(error, commands.CheckFailure):
        await ctx.send("You don't have the correct role or sent a private message.")
© www.soinside.com 2019 - 2024. All rights reserved.