首页 > 解决方案 > discord.py 如何使命令具有权限

问题描述

我正在制作一个不和谐的机器人,并制作了一段代码,可以让语音频道中的每个人都静音。我想确保只有 Mod 或具有管理员权限的人才能使用此命令。

这是我的静音命令代码:

@client.command()
async def vcmute(ctx):
    vc = ctx.author.voice.channel
    for member in vc.members:
        await member.edit(mute=True)
    await ctx.send('Mics are closed!')

这是我的取消静音命令(这将使用仅管理员或 Mod 使用它的相同概念):

@client.command()
async def vcunmute(ctx):
    vc = ctx.author.voice.channel
    for member in vc.members:
        await member.edit(mute=False)
    await ctx.send('Mics are opened!')

标签: pythondiscord.pydiscord.py-rewrite

解决方案


使用has_permissions装饰器

@client.command()
@commands.has_permissions(administrator=True) # Or whatever perms you want
async def vcmute(ctx):
    ...


# If you wanna send some message if the user doesn't have the needed permissions
@vcmute.error
async def vcmute_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f"You need {error.missing_perms} permissions to use this command.")

推荐阅读