Say for example I have a command that requires 2 arguments, I have an if statement already that checks to see if all arguments are present, however, in this scenario; the first argument should be a number. This is roughly what the code is:
@bot.command()
async def rand(ctx,*args):
if len(args) < 2:
await ctx.send("you are missing arguements")
elif isinstance(args[0], int) == False:
await ctx.send("You have not provided an integer")
However the isinstance(args[0], int) == False:
is always triggered, I'm guessing this is because the argument is initially taken as a string. Instead of checking the variable type, is it possible to check if the variable is souly a number?
CodePudding user response:
If you want to check whether the string represents a numeric value, try:
if not args[0].isnumeric():
await ctx.send("You have not provided an integer")
CodePudding user response:
if you're sure it's a string use isdigit()
elif args[0].isdigit() is False:
or you can check both objects and string:
elif (args[0].isdigit() == False) and (isinstance(args[0], int) == False):
CodePudding user response:
args[0].isnumeric()
I think you could try this function.
https://docs.python.org/3/library/stdtypes.html
CodePudding user response:
Whenever you're declaring arguments in a question, I wouldn't put them into a list unless you have no idea how many given arguments a user is going to put in. This module is built to take a command like !command arg1 arg2
and parse those to be used as individual arguments, so I would advise using the intended argument feature. Within that feature, you are also able to declare types that you need your arguments to be in.
In this example, the @rand.error
decorator will intercept any errors coming from the command and process them there. This allows us to have a much cleaner code that is much easier to read and understand.
from discord.ext import commands
@bot.command()
async def rand(ctx, arg1: int, arg2):
await ctx.send(f"{arg1}, {arg2}")
@rand.error
async def rand_error(ctx, error):
if isinstance(error, commands.errors.MissingRequiredArgument):
await ctx.send("You have not provided two arguments")
elif isinstance(error, commands.errors.BadArgument):
await ctx.send("You have provided a bad argument")