Gaming4me
Gaming4me

Reputation: 15

Discord.py how to check if input has a decimal

i made this command it will purge the amount of messages that you said ie >purge 10 it will delete 10 messages i don't know how to check if the input was a decimal can you help Code:

@client.command(pass_context=True)
async def purge(ctx, amount=300):
    if ctx.message.author.server_permissions.manage_messages:
        channel = ctx.message.channel
        messages = []
        async for message in client.logs_from(channel, limit=int(amount) + 1):
            messages.append(message)
        await client.delete_messages(messages)
        await client.say('Purged {} message(s)!'.format(len(messages)-1)) 
    else:
        embed = discord.Embed(
            title = ':x: Insufficient Permissions',
            description = 'You need to have the Manage Messages premission to execute this command.',
            colour = 0xff0000
        )
        await client.say(embed=embed)

Upvotes: 1

Views: 411

Answers (2)

Patrick Haugh
Patrick Haugh

Reputation: 61042

You can use type annotations to supply a converter (note that this is the documentation, but this also works in the async branch) to your coroutine. You can then specify another error handler that can implement your logic for dealing with bad input.

@client.command(pass_context=True)
async def purge(ctx, amount: int=300):
    ...

@purge.error
async def purge_error(error, ctx):
    if isinstance(error, commands.BadArgument):
        await client.send_message(ctx.message.channel, "Cannot convert input to integer")

You may also want to look at Client.purge_from. I didn't read all of your coroutine, but it looks like you're reinventing the wheel a little.

Upvotes: 2

Tristo
Tristo

Reputation: 2408

You can remove the default value for the amount and catch the ValueError that is thrown when the user writes something wrong

@client.command(pass_context=True)
async def purge(ctx, amount):
  try:
    if ctx.message.author.server_permissions.manage_messages:
        channel = ctx.message.channel
        messages = []
        async for message in client.logs_from(channel, limit=int(amount) + 1):
            messages.append(message)
        try:
          await client.delete_messages(messages)
          await client.say('Purged {} message(s)!'.format(len(messages)-1))
        except Exception as inst:
          await client.say("One or more messages older than 14 days\n{}".format(inst))
    else:
        embed = discord.Embed(
            title = ':x: Insufficient Permissions',
            description = 'You need to have the Manage Messages premission to execute this command.',
            colour = 0xff0000
        )
        await client.say(embed=embed)
  except ValueError as va:
    await client.say(va)

I've also added the try/except for when at least one of the messages is 14 days old and thus cannot be deleted

Upvotes: 0

Related Questions