問題描述
我有一個命令可以刪除用戶輸入的指定數量的消息.我希望只有我和具有管理員角色的人才能訪問此命令.我以前用 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 administrator 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 administrators 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(administrator=True) # checks if user is admin
async def delete(ctx, amount : int):
await ctx.channel.purge(limit = amount + 1)
我認為 @commands.has_permissions(administrator=True)
阻止了我使用該命令,因為我不是其中一臺服務器的管理員.我試過切換他們的訂單,is_owner()
檢查低于 has_permissions()
檢查;盡管如此,它仍然不允許我使用該命令.如何使用裝飾器克服這個問題?
The @commands.has_permissions(administrator=True)
, I think, is blocking me from using the command, since I'm not an administrator 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 admin
def owner_or_admin():
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 admin perms
return owner or perms
return commands.check(predicate)
@bot.command(description="clears entered amount of messages")
@owner_or_admin()
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(administrator=True))
async def delete(ctx, amount: int):
await ctx.channel.purge(limit=amount + 1)
這篇關于我怎樣才能有兩個相互對抗的命令裝飾器?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!