Dylan Mac
Dylan Mac

Reputation: 65

How to send message if there is no argument passed in python

so I tried to make a discord bot, and whenever I type the .clear command it will delete the message but I have to type the number of messages I want to delete in the command e.g .clear 5. However, I want to send a message whenever someone types the command without defining the number, and I use try exceptions but it still doesn't work as I expected

here's the code

@client.command()
async def clear(ctx, amount):
    try:
        await ctx.channel.purge(limit=int(amount))
    except MissingRequiredArgument:
        await ctx.send(f"give the number of message you want to delete - e.g '.clear 5' ")

error messages

Traceback (most recent call last):
  File "/home/yves/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/yves/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 855, in invoke
    await self.prepare(ctx)
  File "/home/yves/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "/home/yves/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "/home/yves/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 542, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: amount is a required argument that is missing.

Upvotes: 1

Views: 1268

Answers (2)

jarmod
jarmod

Reputation: 78753

You can write a command extension that accepts a variable number of arguments. You can then test len(args) in your code.

For example:

@client.command()
async def clear(ctx, *args):
    if len(args) != 1:
        await ctx.send(f"give the number of message you want to delete - e.g '.clear 5' ")
    else:
        await ctx.channel.purge(limit=int(args[0]))

Upvotes: 1

ForceBru
ForceBru

Reputation: 44858

Python supports default arguments:

@client.command()
async def clear(ctx, amount=None):
    if amount is None:
        await ctx.send(f"give the number of message you want to delete - e.g '.clear 5' ")
    else:
        await ctx.channel.purge(limit=int(amount))
        

Basically, if amount is None, you know that the user didn't supply the amount argument in their command.

Upvotes: 1

Related Questions