检查用户是否拥有管理员权限 -- Discord.py

3
我想创建一个命令,需要用户具有管理员权限才能执行该命令。
例如,当用户首次邀请机器人进入服务器时,成员不能使用所谓的“权限”命令。但是,拥有 moderator 角色的成员应该可以访问它并执行其余的命令。
有人能帮忙在我的命令中实现这个功能吗?

1
请你能否进一步解释一下。很难确切理解你的意思。 - Cohen
如果你是成员,就不能使用“permissions”命令来更改命令权限。但服务器管理员可以使用它。那么,受欢迎的机器人如何获得服务器管理员角色呢? - Arda Yılmaz
你想创建一个命令,只有具备特定权限的成员才能使用吗? - Cohen
是的,我想要它。 - Arda Yılmaz
你在使用 discord.ext.commands.Bot 吗? - Lukas Thaler
是的,我正在使用它。 - Arda Yılmaz
2个回答

4

目前还不清楚您想保留哪些内容或者指定谁可以使用命令,但是 has_permissions 装饰器允许您设置用户可以使用的权限以访问命令。这可以在参数中进行设置。

例如,如果您只想让具有管理员权限的成员访问您的命令,可以在命令装饰器后添加 @commands.has_permissions(administrator=True)。以下是一个示例:

@bot.command()
@commands.has_permissions(administrator = True)
async def permission(ctx):
    await ctx.send('You have administrator access...')

Discord 的文档中可以找到更多信息: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html

编辑:

但是,在命令中使用 if 语句可以通过以下方式完成:

if ctx.author.guild_permissions.administrator:
...

0

虽然这个问题是针对 discord.py 的 - 但当我在搜索如何使用它的“半继承库”Discord Interactions时,这个问题也出现了,因为 discord.py 相当有限 - 所以我会告诉大家如何在 interactions 中实现这个功能。

所以对于那些想知道的人,这就是如何检查调用用户是否是 interactions 上的服务器管理员:

import interactions
bot = interactions.Client(token=TOKEN)

@bot.command(scope=SERVER_IDS)
async def my_command(ctx):
    perms = (await ctx.author.get_guild_permissions(ctx.guild_id))
    if interactions.Permissions.ADMINISTRATOR in perms:
        return await ctx.send("You are an admin")
    
    await ctx.send("You are NOT an admin")

此外,这里有一个函数片段,可以在您的命令中使用,快速检查调用者是否为服务器管理员:
async def is_server_admin(ctx: Union[CommandContext, ComponentContext]) -> bool:
    """Returns :bool:`True` if the calling user is a Discord Server Administrator"""
    perms = (await ctx.author.get_guild_permissions(ctx.guild_id))
    return interactions.Permissions.ADMINISTRATOR in perms

该函数的示例用法:

@bot.command(scope=SERVER_IDS)
async def my_command(ctx):
    if await is_server_admin(ctx):
        return await ctx.send("You are an admin")
    await ctx.send("You are NOT an admin")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接