【问题标题】:Python command error passedPython 命令错误通过
【发布时间】:2018-12-11 11:29:36
【问题描述】:

您好,我尝试在 await bot.send_message 中添加 {0.subcommand_passed},但出现错误,因此如何添加以捕获在回复中传递的错误命令。

所以如果成员输入?helol 而不是?hello,机器人应该回复helol is a wrong command

@bot.event
async def on_command_error(error, ctx):
    if isinstance(error, commands.CommandNotFound):
        await bot.send_message(ctx.message.channel, "**Wrong command ** " + ctx.invoked_with)

如果成员在子命令中输入?cool girl 而不是?cool boy,机器人应该回复girl is a wrong sub command

@bot.group(pass_context=True)
async def cool(ctx):
    if ctx.invoked_subcommand is None:
        if ctx.subcommand_passed:
            await bot.say("**Wrong sub command: **{}".format(ctx.subcommand_passed))
        else:
            await bot.say("**Subcommand required**. {0.author.mention}".format(ctx.message))

@cool.command(pass_context=True)
async def boy(ctx):
    msg = "Hello ...".format(ctx.message)
    await bot.say(msg)

【问题讨论】:

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


    【解决方案1】:

    使用Context.subcommand_passed 获取尝试的子命令的文本。

    @bot.group(pass_context=True)
    async def cool(ctx):
        if ctx.invoked_subcommand is None:
            if ctx.subcommand_passed:
                await bot.say("**Wrong sub command: **{}".format(ctx.subcommand_passed))
            else:
                await bot.say("Subcommand required")
    
    @cool.command(pass_context=True, name="bot")
    async def _bot(ctx):
        msg = "Hello ...".format(ctx.message)
        await bot.say(msg)
    

    无法识别的顶级命令将引发CommandNotFound,您必须在on_command_error 中处理它。我相信它仍然应该使用尝试的命令填充ctx.command,但我目前无法检查。你也可以试试ctx.invoked_with

    @bot.event
    async def on_command_error(error, ctx):
        if isinstance(error, commands.CommandNotFound):
            await bot.send_message(ctx.message.channel, "**Wrong command ** " + ctx.command)
    

    【讨论】:

    • 得到错误Traceback (most recent call last): File "D:\Bot.py", line 31, in <module> bot.run(token) AttributeError: 'Command' object has no attribute 'run' Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x0276BC70>
    • 那是因为你的命令被命名为bot。我们可以很容易地更改对象的名称。
    • 我在on_command_error 中遇到错误,像这样in on_command_error await bot.send_message(ctx.message.channel, "**Wrong command ** " + ctx.command) TypeError: must be str, not NoneType
    • 你试过ctx.invoked_with吗?
    • 您是否更改了格式字符串以包含作者字段? "{0.message.author.mention}, {0.subcommand_passed} is not a subcommand".format(ctx)
    猜你喜欢
    • 2022-12-05
    • 2017-09-08
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多