首页 > 解决方案 > 程序 Discord.py 命令使用消息

问题描述

我正在将错误消息实现到我的Discord.py机器人中,在那里我使用 cogs 来实现命令。

当用户错误地使用命令时,例如没有将参数传递给需要它们的命令,我希望机器人通知他们该特定命令的正确用法。

例如,这里我有一个简单的 cog test.py

from discord.ext import commands

class Test(commands.Cog):
  def __init__(self, client): 
    self.client = client

  @commands.command()
  async def test_command(self, ctx, arg1: str, arg2: int):
    msg = f"{arg1} and {arg2 + 5}"
    await ctx.reply(msg)

def setup(client):
  client.add_cog(Test(client))

如果用户错误地使用了命令,例如 types !test_command foo,我希望机器人返回一条消息,如下所示

正确用法:!test_command <arg1> <arg2>

我该怎么做呢?我想按程序进行,而不必从每个命令的预先编写的使用帮助消息列表中进行选择。

提前致谢。

编辑:请注意我已经有了错误检查逻辑。我在问 - 在错误触发的情况下 - 如何自动生成一条消息以通知用户如何使用该命令。

标签: pythondiscorddiscord.py

解决方案


您正在寻找Command.signature。这将自动为您提供命令的用法。只需将它与on_command_errorMissingRequiredArgument错误结合使用即可。

例子:

if isinstance(error, commands.MissingRequiredArgument):
    await ctx.send(f"Correct Usage: {ctx.prefix}{ctx.command.name} {ctx.command.signature}")

这将返回Correct Usage: !test_command <arg1> <arg2>


推荐阅读