問題描述
我正在開發(fā)一個機(jī)器人.對于某個 cog,我希望創(chuàng)建一個自定義檢查裝飾器來檢查運行命令的人是否具有特定角色.角色作為實例變量存儲為角色類.當(dāng)我嘗試運行它時,它不起作用.裝飾器是怎么做的?
I am working on a bot. For a certain cog, I wish to create a custom check decorator that checks to see if the person running the command has a certain role. The role is stored as a role class as an instance variable. When I tried running it, it doesn't work. How do you make the decorator?
class Moderation(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
self.mod_role = None # Assume there's already a role here
class Decorator:
@classmethod
def requires_mod(cls, func):
async def decorator(self, ctx: commands.Context, *args, **kwargs):
if self.mod_role not in ctx.author.roles:
await ctx.send("You do not have permission to use this command")
func(ctx, *args, **kwargs)
return decorator
@commands.command()
@Decorator.requires_mod
async def purge(self, ctx: commands.Context, amt: int):
await ctx.channel.purge(limit=amt+1)
await ctx.send(f":white_check_mark: | Deleted {amt} messages.")
推薦答案
這個概念被內(nèi)置到 commands
擴(kuò)展中作為 檢查
This concept is built into the commands
extension as Checks
即使是特定于 cog 的檢查,例如 cog_check
不知道 cog 本身:它們都不接收 self
作為參數(shù).
Even the cog-specific checks like cog_check
aren't aware of the cog itself: none of them receive self
as an argument.
您需要重寫您的支票,使其不依賴于self
.如果您現(xiàn)在知道角色名稱或 ID,或者在創(chuàng)建 Moderation
類時,可以使用內(nèi)置的 has_any_role
檢查.
You need to rewrite your check such that it doesn't rely on self
. If you know the role names or ids now, or when creating the Moderation
class, you can use the built-in has_any_role
check.
否則最簡單的方法可能是使用 Moderation
的類屬性或全局值來存儲角色:
Otherwise the easiest way is probably to use either a class attribute of Moderation
or a global value to store the role:
from discord.ext import commands
def predicate(ctx):
return Moderation.mod_role in ctx.author.roles
has_mod_role = commands.check(predicate)
class Moderation(commands.Cog):
mod_role = None
def __init__(bot):
self.bot = bot
Moderation.mod_role = ...
@commands.command()
@has_mod_role
async def yourcommand(ctx, ...):
...
這篇關(guān)于如何為 discord.py 創(chuàng)建自定義裝飾器?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!