提出以下的自定义错误消息

时间:2018-06-30 12:45:12

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

因此,下面的代码在使用?hello时会阻止列表中的服务器和用户ID,因此我试图提出自定义错误消息。如果用户ID在列表中,它将告诉User Blacklisted,如果服务器ID在列表中,它将告诉Server has been Blacklisted

LIST_OF_USER_IDS = ['34534545546', '34534545546']
LIST_OF_SERVER_IDS = ['34534545546', '34534545546']

def blacklists(users, servers):
    def predicate(ctx):
        return ctx.message.author.id not in users and ctx.message.server.id not in servers
    return commands.check(predicate)

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

所以我尝试了下面的代码,但是出错了。我只是一个初学者,所以我的代码不正确,因此我需要帮助来解决此问题。

def blacklists(users, servers):
    def predicate(ctx):
        return ctx.message.author.id not in users and ctx.message.server.id not in servers
    return commands.check(predicate)
try:
       if ctx.message.author.id in LIST_OF_USER_IDS:
           raise UserBlacklisted
       elif ctx.message.server.id in LIST_OF_SERVER_IDS:
           raise ServerBlacklisted
       break
   except UserBlacklisted:
       await bot.send_message(ctx.message.channel, "User Blacklisted")
   except ServerBlacklisted:
       await bot.send_message(ctx.message.channel, "Server has been Blacklisted")

1 个答案:

答案 0 :(得分:1)

如果检查失败,则不返回False,而是引发CommandError的子类,然后在on_command_error事件中处理该错误。

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

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


def blacklists(users, servers):
    def predicate(ctx):
        if ctx.message.author.id in users:
            raise UserBlacklisted(ctx.message.author)
        elif ctx.message.server.id in servers:
            raise ServerBlacklisted(ctx.message.server)
        else:
            return True
    return commands.check(predicate)

@bot.event
async def on_command_error(error, ctx):
    if isinstance(error, UserBlacklisted):
        await bot.send_message(ctx.message.channel, "User {} has been blacklisted".format(error.user.mention))
    elif isinstance(error, ServerBlacklisted):
        await bot.send_message(ctx.message.channel, "Server {} has been blacklisted".format(error.server.name))



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