首页 > 解决方案 > 如何在没有 MissingRequiredArgument 错误的情况下操作 @client.command() 部分中的 message.content

问题描述

我创建了一个工单命令,其中一个人发送“工单”,然后是一个问题。但是,当我在同一个函数中有 ctx 和 msg 时,我得到了错误:
discord.ext.commands.errors.MissingRequiredArgument: msg is a required argument that is missing. 当我在函数中切换 ctx 和 msg 的顺序时,ctx 发生错误。

@client.command()
async def ticket(ctx, msg):
    if msg.content.startswith('>ticket'):
        print('ticket was made')

我尝试了在 2 之间使用 * 的方法,这给了我同样的错误。我也尝试将这个 if 语句放在on_message函数中,但这使得当我输入“>ticket”时命令不会运行,并且只执行on_message函数中的代码。

标签: python-3.xdiscorddiscord.py

解决方案


“消息的其余部分”将在msg变量中,因此您不必将其删除。如果您仅将其用作>ticket,则不会有额外的参数传递给函数,因此missing正如您的错误所暗示的那样,它将是 。

阻止错误出现的一种方法是optional给它一个默认值,然后检查是否传递了任何内容。

@client.command()
async def ticket(ctx, *, msg=None):
    if msg is None:
        print("No arguments were passed!")
    else:
        print(f"The rest of the message is: {msg}")
>ticket

>>> No arguments were passed!

>ticket something something

>>> The rest of the message is: something something

推荐阅读