python - 限制命令

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

我得到了这段代码,它阻止除了 LIST_OF_ID 中的用户 ID 之外的所有人对 ?hello 命令的访问,因此我通过替换 ctx.message.author 来修改此代码.idctx.message.server.id 现在它也绕过服务器。所以我添加了这两个代码,但现在它不适用于用户和服务器,只适用于任何人。如何使其适用于服务器和用户。

LIST_OF_SERVER_IDS = ['3557657657647676', '36567565756766767']
LIST_OF_USER_IDS = ['3557657657647676', '36567565756766767'] 

def is_any_user(ids):
    def predicate(ctx):
        return ctx.message.author.id in ids
    return commands.check(predicate)

def is_any_server(ids):
    def predicate(ctx):
        return ctx.message.server.id in ids
    return commands.check(predicate)

@bot.command(pass_context=True)
@is_any_user(LIST_OF_USER_IDS)
@is_any_server(LIST_OF_SERVER_IDS)
async def hello(ctx):
     await bot.say("Hello {}".format(ctx.message.author.mention))

最佳答案

通过定义两个 is_any_user 装饰器,您只需保留最近定义的装饰器,并丢失第一个装饰器。给服务器检查一个更具代表性的名称(毕竟,它不是检查User,为什么名称中有“user”)。然后我们可以保留两个id白名单。由于commands.check可以链接,我们只需用这两个检查来装饰我们的命令。

LIST_OF_SERVER_IDS = [3557657657647676, 36567565756766767, 343657687786435432]
LIST_OF_USER_IDS = [1, 2, 3]  
# Replace as needed.  Keep in mind that 0.16 ids are strings and 1.0 ids are integers


def is_any_user(ids):
    def predicate(ctx):
        return ctx.message.author.id in ids
    return commands.check(predicate)

def is_any_server(ids):
    def predicate(ctx):
        return ctx.message.server.id in ids
    return commands.check(predicate)

@bot.command(pass_context=True)
@is_any_user(LIST_OF_USER_IDS)
@is_any_server(LIST_OF_SERVER_IDS)
async def hello(ctx):
     await bot.say("Hello {}".format(ctx.message.author.mention))

编辑:

使用这些版本的检查来尝试调试正在发生的事情

def is_any_user(ids):
    def predicate(ctx):
        if ctx.message.author.id in ids:
            print("Good author")
            return True
        else:
            print("Bad author")
            return False
    return commands.check(predicate)

def is_any_server(ids):
    def predicate(ctx):
        if ctx.message.server.id in ids:
            print("Good server")
            return True
        else:
            print("Bad server")
            return False
    return commands.check(predicate)

编辑2:

您可以编写一个检查来查看某人是否在用户白名单中是否从服务器白名单上的服务器访问命令。

def whitelists(users, servers):
    def predicate(ctx):
        return ctx.message.author.id in users or ctx.message.server.id in servers
    return commands.check(predicate)

@bot.command(pass_context=True)
@whitelists(LIST_OF_USER_IDS, LIST_OF_SERVER_IDS)
async def hello(ctx):
     await bot.say("Hello {}".format(ctx.message.author.mention))

关于python - 限制命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50932470/

相关文章:

python - 把一个名词变成它的代词

python - 如何查找并替换文本文件中的一行?

python - 为什么类方法/静态方法的 cls.__dict__[meth] 与 getattr(cls, meth) 不同?

javascript - 当机器人进入语音 channel 时发送 mp3 文件时出错

javascript - 没有提及的命令

python - 是否可以将 kwargs 传递给 Tkinter 中的 after() 函数?

python - 如何使用 NLTK(pos 标记)获取动词的不定式形式

python - 返回列表的自定义 django 标签?

python - 使用 message.content 发送消息

python - 如何从 imdb 业务页面抓取数据?