【问题标题】:Cancel command with before_invoke without printing error message (discord.py)使用 before_invoke 取消命令而不打印错误消息 (discord.py)
【发布时间】:2021-07-18 19:29:46
【问题描述】:

我有一个不和谐的机器人,除非填写了某个参数,否则我想阻止它运行。

这是机器人的当前代码:

@bot.before_invoke
async def checkguild(message):
    command = message.command
    if command != 'settings':
        if not message.guild.id in globaldb.servers_setup.val:
            for required_setting in REQUIRED_SETTINGS:  # Iterates through the required settings to make sure they're all defined.
                if not get_guild_db(message.guild).settings.has(required_setting):
                    # Prevent command from running, and call the on_command_error function instead of just throwing an error.
            globaldb.set('servers_setup', globaldb.servers_setup.val + [message.guild.id])
            globaldb.save()  # Otherwise add the server to the database as set up.

我想按照中间评论说的做,

# Prevent command from running, and call the on_command_error function instead of just throwing an error.

但是我该怎么做呢? (检查下面的答案)

【问题讨论】:

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


    【解决方案1】:

    为了使用discord.ext.commands提供的错误系统,我们必须抛出它的CommandError异常。

    这将是这样实现的:

    @bot.before_invoke
    async def checkguild(message):
        command = message.command
        if command != 'settings':
            if not message.guild.id in globaldb.servers_setup.val:
                for required_setting in REQUIRED_SETTINGS:  # Iterates through the required settings to make sure they're all defined.
                    if not get_guild_db(message.guild).settings.has(required_setting):
                        # Prevent command from running, and call the on_command_error function instead of just throwing an error.
                        raise discord.ext.commands.CommandError(f'Before using this bot, please set the `{required_setting}` setting.')
                globaldb.set('servers_setup', globaldb.servers_setup.val + [message.guild.id])
                globaldb.save()  # Otherwise add the server to the database as set up.
    

    【讨论】:

    • OP 注释:CommandError 几乎是所有 discord.ext 错误的基类,如果您使用 isinstance 捕获它,所有其他错误也会被捕获(如 CommandNotFound、@ 987654326@ 等),您应该制作自己的自定义错误(继承自 CommandError)并提出该错误。
    • @ŁukaszKwieciński 谢谢,我不知道!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    相关资源
    最近更新 更多