【问题标题】:Change needed role for command discord.py更改命令 discord.py 所需的角色
【发布时间】:2021-07-29 12:03:12
【问题描述】:

这不是完整的代码,但这只是我需要解释的,如果一个人想使用这个命令,他需要角色'Admin',但假设我想用另一个命令将'Admin'更改为'Mod' ,如何在不从代码本身更改的情况下做到这一点?

@bot.command(pass_context=True)
    @commands.has_role("Admin")

【问题讨论】:

  • 你不能用装饰器
  • 如果您将“Admin”设置为变量并稍后使用一些代码对其进行编辑,也许这会起作用?但我不确定这是否可行
  • 不,你不能我已经试过了,你需要重新启动机器人才能识别变量@FlexGames

标签: python command discord.py


【解决方案1】:

如果你真的想使用装饰器,你应该创建自己的

role_name = "Admin"

def has_role(item=None):
    def predicate(ctx):
        nonlocal item # So we can edit it's value
        if item is None or item != role_name: # If either the `item` is `None` or it's not the same as the global `role_name` variable, update it
            item = role_name 

        if not isinstance(ctx.channel, discord.abc.GuildChannel):
            raise commands.NoPrivateMessage()

        if isinstance(item, int):
            role = discord.utils.get(ctx.author.roles, id=item)
        else:
            role = discord.utils.get(ctx.author.roles, name=item)
        if role is None:
            raise commands.MissingRole(item)
        return True

    return commands.check(predicate)

这主要是从source code复制而来的,只是做了一些调整

要编辑运行命令所需的角色,您可以简单地执行以下操作:

@bot.command()
async def change(ctx, role: discord.Role):
    global role_name
    role_name = role.name
    await ctx.send(f"Updated to {role.name}")


@bot.command()
@has_role()
async def foo(ctx):
    await ctx.send("Whatever")

【讨论】:

  • 为什么我们需要创建谓词?我们不能直接返回has_role(item)吗?
  • 不是真的,最外面的函数只会被调用一次(装饰命令时),我们需要在每次命令运行时“更新” item 变量,这是装饰器的基本原理跨度>
猜你喜欢
  • 2021-02-07
  • 2021-07-06
  • 2021-04-09
  • 2020-09-26
  • 2021-06-02
  • 1970-01-01
  • 2021-07-17
  • 2022-01-10
  • 2021-10-03
相关资源
最近更新 更多