简体   繁体   中英

Procedural Discord.py command usage messages

I am implementing error messages into my Discord.py bot, where am using cogs to implement commands.

When a user incorrectly uses a command, for example passes no arguments into a command that requires them, I would like the bot to inform them of the correct usage of that specific command.

For example, here I have a simple 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))

If the user uses the command incorrectly, for example types !test_command foo , I would like the bot to return a message along the lines of

Correct usage: !test_command <arg1> <arg2>

How would I go about doing this? I would like to do it procedurally, and not have to pick from a list of pre-written usage help messages for each command.

Thanks in advance.

EDIT: Please note I already have the error checking logic in place. I am asking - in the event of an error triggering - how to automatically generate a message to inform the user on how to use the command.

You're looking for Command.signature . This will automatically give you the usage of the command. Just use it in conjunction with the on_command_error and the MissingRequiredArgument error.

Example:

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

This will return Correct Usage: !test_command <arg1> <arg2>

I see a few errors in your code which might stop the bot from working.

First) Why do you use commands.Cog() ? It should be client.command / commands.command . The commands just inherite from commands.Cog

Second) The reply method is a bit deprecated. Instead we use await ctx.send()

Now, to include an error code you have to include your own handler for it.

Have a look at the following code:

@commands.Cog.listener
async def on_command_error(self, ctx, error):
        try:
            if isinstance(error, commands.CommandNotFound):
                pass
            elif isinstance(error, commands.MissingRequiredArgument):
                await ctx.send(str(error))
        except Exception as error:
            pass

This error handler informs you about the required arguments and mentions them.

You can use try except

@commands.command()
async def test_command(self, ctx, arg1: str, arg2: int):
    try:
        msg = f"{arg1} and {arg2 + 5}"
        await ctx.reply(msg)
    except:
        await ctx.send('Correct usage: !test_command <arg1> <arg2>')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM