Поднять пользовательское сообщение об ошибке для - PullRequest
0 голосов
/ 30 июня 2018

Поэтому ниже код блокирует сервер и идентификатор пользователя в списке, когда они используют ?hello, поэтому я пытаюсь вызвать пользовательское сообщение об ошибке. Если идентификатор пользователя находится в списке, он скажет User Blacklisted, а если идентификатор сервера находится в списке, он скажет 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 голосов
/ 30 июня 2018

Вместо возврата 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))
...