问题描述
我有一个命令可以删除用户输入的指定数量的消息.我希望只有我和具有管理员角色的人才能访问此命令.我以前用 if 语句实现过这个,它工作得很好.但是,现在我正在尝试使用命令装饰器来做同样的事情,它只允许管理员使用命令 - 而不是我.这是我正在使用的代码:
I have a command that deletes a specified number of messages entered in by the user. I want this command to be accessible only to me and those with the *****istrator role. I had implemented this before with if-statements, and it was working perfectly fine. However, now I'm trying to use command decorators to do the same, and it only lets *****istrators use the command - not me. Here's the code I'm working with:
@bot.command(description="clears entered amount of messages") @commands.is_owner() # checks if user is owner @commands.has_permissions(*****istrator=True) # checks if user is ***** async def delete(ctx, amount : int): await ctx.channel.purge(limit = amount + 1)
我认为 @commands.has_permissions(*****istrator=True) 阻止了我使用该命令,因为我不是其中一台服务器的管理员.我试过切换他们的订单,is_owner() 检查低于 has_permissions() 检查;尽管如此,它仍然不允许我使用该命令.如何使用装饰器克服这个问题?
The @commands.has_permissions(*****istrator=True), I think, is blocking me from using the command, since I'm not an *****istrator in one of the servers. I've tried switching their orders, with the is_owner() check being below the has_permissions() check; nonetheless, it still doesn't allow me to use the command. How can I overcome this using decorators?
推荐答案
您可以创建一个自定义装饰器来检查您是机器人的所有者还是管理员
You can create a custom decorator that will check if you're either the owner of the bot, or you are an *****
def owner_or_*****(): def predicate(ctx): owner = ctx.author.id == bot.owner_id # Comparing the author of the message with the owner of the bot perms = ctx.author.guild_permissions.administrator # Checking for ***** perms return owner or perms return commands.check(predicate) @bot.command(description="clears entered amount of messages") @owner_or_*****() async def delete(ctx, amount : int): await ctx.channel.purge(limit = amount + 1)
我刚刚发现 commands.check_any - 检查是否有任何通过的检查将通过,即使用逻辑 OR.
@bot.command() @commands.check_any(commands.is_owner(), commands.has_permissions(*****istrator=True)) async def delete(ctx, amount: int): await ctx.channel.purge(limit=amount + 1)