python - 更改命令 discord.py 所需的角色
问题描述
这不是完整的代码,但这只是我需要解释的,如果一个人想使用这个命令,他需要角色'Admin'但是假设我想用另一个命令将'Admin'更改为'Mod',怎么能我这样做而不从代码本身更改它?
@bot.command(pass_context=True)
@commands.has_role("Admin")
解决方案
如果你真的想使用装饰器,你应该创建自己的
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)
这主要是从源代码中复制的,只是做了一些调整
要编辑运行命令所需的角色,您可以简单地执行以下操作:
@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")
推荐阅读
- python - 带有硒测试的 Django 频道 2 失败
- html - Bootstrap nav-justified 不占用全宽
- go - Windows 如何为 Golang 制作
- r - 比 r 中的 ifelse() 更快的函数
- intellij-idea - 在 IntelliJ 中启用自定义 CheckStyle
- php - array_merge():参数 #1 不是 laravel 5.5 中的数组
- javascript - 不能要求 npm 安装的模块
- sql - 从“with table as”CTE 表达式创建临时表
- javascript - 如何计算角度或javascript中分组数组的长度?
- powershell - 如何从打开的文件对话框控件中保存选定的路径