pironc
pironc

Reputation: 51

User inputs gives "ValueError: invalid literal for int() with base 10:"

I've been trying to code a discord bot that checks for use inputs and commands, with arguments, but I would like to check whether it's a string or a number. Let me explain clearly :

In my code :

@client.command()
async def create(ctx, *args): # create a lobby
    firstarg = (int)(args[0])
    if (firstarg >= 4 and firstarg <= 10):
        await ctx.send("Max players : " + args[0])
        return (0)
    else:
        await ctx.send("Error. Please enter a maximum number of players between 4 and 10.")
        return (84)

The arguments are always strings, so I thought I could just cast them as integers and it works. But, there is one catch.

When I'm using anything else than numbers in my command, not any error message will show up, because it couldn't cast it into an integer.

So, I would like to know if there is a way to check for this specific error and if it's the same for other kinds of errors that I would encounter in the future.

I'm not sure about how to "check whether it's a string, and if it's not cast it as an int and use it in the rest of the code".

It might not be 100% clear, so if something is not clear please tell me and I'll try to clarify as good as I can.

Thanks.

Upvotes: 1

Views: 638

Answers (1)

Viper
Viper

Reputation: 505

I think you need to look at how exceptions works in Python and how to handle them

In your case, you need to catch the ValueError, which would give something like that :

@client.command()
async def create(ctx, *args): # create a lobby
    try:
      firstarg = (int)(args[0])
    except ValueError:
      # the string was not a number
      await ctx.send("Error. Please enter a number.")
      return (84)
    else:
      # the string was a number
      if (firstarg >= 4 and firstarg <= 10):
        await ctx.send("Max players : " + args[0])
        return (0)
      else:
        await ctx.send("Error. Please enter a maximum number of players between 4 and 10.")
        return (84)

Upvotes: 1

Related Questions