How can I make my discord bot generate a random number between 2 given values?

Question:

@bot.command(name='randnum')
async def randnum(ctx, arg1, arg2):
  randnum = random.randint(*arg1, *arg2)
  await ctx.send('spinning...')
  time.sleep(2)
  await ctx.send('your random number is', randnum)

arg1 and arg2 will be the numbers the user enters, then the bot picks a random one from between these values.

When i run it it gives me the TypeError: randnum() missing 1 required keyword-only argument: ‘arg2’
Why does this happen and how can i fix it?

Asked By: golger

||

Answers:

The issue with your code is that the random.randint() method requires two integer arguments, but arg1 and arg2 are strings that need to be converted into integers before they can be used in the random.randint() method.

You can fix the error by changing the randnum line to the following:

randnum = random.randint(int(arg1), int(arg2))

This will convert the arg1 and arg2 strings into integers before passing them to random.randint().

Additionally, the await ctx.send(‘your random number is’, randnum) line will raise a TypeError because you’re passing two arguments to ctx.send() instead of one. You can fix this by concatenating the string and the random number using the + operator like this:

await ctx.send('your random number is ' + str(randnum))

So to sum up, your code should look like this:

@bot.command(name='randnum')
async def randnum(ctx, arg1, arg2):
  randnum = random.randint(int(arg1), int(arg2))
  await ctx.send('spinning...')
  time.sleep(2)
  await ctx.send('your random number is ' + str(randnum))
Answered By: Mehmet Serdar Uz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.