python bot阻止对命令的访问

时间:2018-07-03 18:43:04

标签: python python-3.x discord discord.py

如果命令不是特定Discord服务器的成员,是否可以阻止对命令的访问。例如:

如果bot已安装在多台服务器中。

因此,如果来自任何服务器的任何成员都键入?ping,则只有他是主服务器的成员才可以工作。否则,机器人会通过自定义消息进行回复。

class NonMember(commands.CommandError):
    def __init__(self, server_id, *args, **kwargs):
        self.server_id = server_id
        super().__init__(*args, **kwargs)

def is_member_of(server_id):
    def predicate(ctx):
        server = bot.get_server(server_id)
        if not server:
            raise commands.CommandError("Cannot poll members of server with id {}".format(server_id))
        if bool(server.get_member(ctx.message.author.id)):
            return True
        else:
            raise NonMember
    return commands.check(predicate)

@bot.event
async def on_command_error(error, ctx):
    if isinstance(error, NonMember):
        await bot.send_message(ctx.message.channel, "{} Not an member. ".format(error.user.mention))

@bot.command(pass_context=True)
@is_member_of("1234")
async def ping(ctx):
    msg = "Pong {0.author.mention}".format(ctx.message)
    await bot.say(msg)

1 个答案:

答案 0 :(得分:3)

您可以编写commands.check来使用Server.get_member来查找给定服务器中的成员。像

class NonMember(commands.CommandError):
    def __init__(self, server_id, *args, **kwargs):
        self.server_id = server_id
        super().__init__(*args, **kwargs)

@bot.event
async def on_command_error(error, ctx):
    if isinstance(error, NonMember):
        await bot.send_message(ctx.message.channel, "{} Not an member. ".format(error.user.mention))

def is_member_of(server_id):
    def predicate(ctx):
        server = bot.get_server(server_id)
        if not server:
            raise commands.CommandError("Cannot poll members of server with id {}".format(server_id))
        if bool(server.get_member(ctx.message.author.id)):
            return True
        else:
            raise NonMember(server_id)
    return commands.check(predicate)

@bot.command(pass_context=True)
@is_member_of("1234")
async def ping(ctx):
    msg = "Pong {0.author.mention}".format(ctx.message)
    await bot.say(msg)