Discord.py 机器人的权限系统

Permission System for Discord.py Bot

我正在使用 discord.py 和 asyncio 制作一个 discord 机器人。该机器人有像 kickban 这样的命令,这显然不应该对普通用户可用。

我想制作一个简单的系统,它将使用 ctx.message.author 检测用户角色具有哪些权限,以获取发送命令的用户。

我不希望机器人检测特定的角色名称,因为这些角色名称因服务器而异。我也不希望机器人有多个文件以保持简单。

我看过 discord.py 文档和各种其他来源,但 none 包含如何实施他们谈论的各种方法的示例。

例如,这是来自我的机器人的单个命令:

async def kick(ctx, userName: discord.User):
    if True: #ctx.message.author.Permissions.administrator
        await BSL.kick(userName)
    else:
        permission_error = str('Sorry ' + ctx.message.author + ' you do not have permissions to do that!')
        await BSL.send_message(ctx.message.channel, permission_error)

其中 if else 声明是我自己尝试做的。 #ctx.message.author.Permissions.administrator 被注释掉,因为它不起作用并被替换为 True 用于测试目的。

感谢您提前提供的任何帮助和建议。

Permissions is the name of the class. To get the message authors permissions, you should access the guild_permissions属性作者

if ctx.message.author.guild_permissions.administrator:
 # you could also use guild_permissions.kick_members

更新:

验证调用命令的人的权限的更好方法是使用 check feature of the commands extension, specifically the has_permissions 检查。例如,如果你想只对拥有 manage_roles 权限或 ban_members 权限的人开放你的命令,你可以这样写你的命令:

from discord import Member
from discord.ext.commands import has_permissions, MissingPermissions

@bot.command(name="kick", pass_context=True)
@has_permissions(manage_roles=True, ban_members=True)
async def _kick(ctx, member: Member):
    await bot.kick(member)

@_kick.error
async def kick_error(ctx, error):
    if isinstance(error, MissingPermissions):
        text = "Sorry {}, you do not have permissions to do that!".format(ctx.message.author)
        await bot.send_message(ctx.message.channel, text)

找到已接受答案的提示可能无效:

  1. discord.py 库的重写版本和重写前的版本可能存在兼容性问题,这些版本仍未过时、未弃用且仍在使用。

  2. 机器人还应该检查自己的权限,以排除错误的原因之一。

  3. 如果出现错误,或者机器人本身的权限无效,机器人应该说些什么,对吗?

  4. 需要实施一些措施来防止机器人尝试在 DM 或组上下文中执行此命令。它几乎总是会出错。

我提出以下预重写解决方案(假设您使用命令扩展):

import discord
from discord.ext import commands
import time
@bot.command(pass_context=True,description="Kicks the given member. Please ensure both the bot and the command invoker have the permission 'Kick Members' before running this command.")
async def kick(ctx, target:discord.Member):
    """(GUILD ONLY) Boot someone outta the server. See 's!kick' for more."""
    if not str(ctx.message.channel).startswith("Direct Message with "):
        msg=await bot.say("Checking perms...")
        time.sleep(0.5)
        if ctx.message.server.me.server_permissions.kick_members:
            if ctx.message.author.server_permissions.kick_members:
                await bot.edit_message(msg,new_content="All permissions valid, checking issues with target...")
                time.sleep(0.5)
                if target==ctx.message.server.owner:
                    await bot.edit_message(msg, new_content="All permissions are correct, but you're attempting to kick the server owner, whom you can't kick no matter how hard you try. Whoops!")
                else:
                    if target==ctx.message.server.me:
                        await bot.edit_message(msg, new_content="Whoops! All permissions are corrent, but you just tried to make me kick myself, which is not possible. Perhaps you meant someone else, not poor me?")
                    else:
                        await bot.edit_message(msg, new_content="All permissions correct, and no issues with target being self or server owner, attempting to kick.")
                        time.sleep(2)
                        try:
                            await bot.kick(target)
                            await bot.edit_message(msg, ":boom: BAM! ***kicc'd***")
                        except Exception:
                            await bot.edit_message(msg, new_content="I was unable to kick the passed member. The member may have a higher role than me, I may have crashed into a rate-limit, or an unknown error may have occured. In that case, try again.")
            else:
                await bot.edit_message(msg, new_content="I've the correct permissions, {}, but you do not. Perhaps ask for them?").format(ctx.message.author.mention)
        else:
            await bot.edit_message(msg, new_content="I'm just a poor bot with no permissions. Could you kindly grant me the permission `Kick Members`? Thanks! :slight_smile:")
    else:
        await bot.say("'Tis a DM! This command is for servers only... try this again in a server maybe? :slight_smile:")

你也可以使用装饰器。

@bot.command(name = "Kick")
@bot.has_permissions(kick_user = True)
@bot.bot_has_permissions(kick_user = True)
async def _kick(ctx, member: Member):
    #Do stuff...

检查用户和 bot 权限的优势意味着通过提供有用的 "Insufficient Permission" 错误消息更容易处理错误。