lomstfer
lomstfer

Reputation: 79

How do I store input in my python discord bot?

I want to make a discord bot where you can get a random number with the max being what you type. Like this:

number = input("")

number = int(number)

print(random.randint(1, number))

But my problem is storing the input the user typed. All I've done this far is making it only certain max numbers like 2 and 100.

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  if message.content == ("r100"):
    await message.channel.send(random.randint(1, 100))

  if message.content == ("r2"):
    await message.channel.send(random.randint(1, 2))

Upvotes: 0

Views: 487

Answers (3)

LoahL
LoahL

Reputation: 2613

You can use max_random= int(message.content[1:]) to get the number after the "r":

@client.event
async def on_message(message):
  if message.author == client.user:
    return
  max_random = int(message.content[1:])
  await message.channel.send(random.randint(1, max_random))

Upvotes: 2

lomstfer
lomstfer

Reputation: 79

The code Chuaat posted helped me but with that you could type (for example) 101 and it would say 1. I got to a solution to put it like this instead:

if message.content.startswith("r"):
    maxnum = int(message.content[1:])
    await message.channel.send(random.randint(1, maxnum))

The mistake I made when trying to do exactly this was putting == after startswith.

Upvotes: 0

Guddi
Guddi

Reputation: 644

The simplest way to do this is with a commands.Bot Command

you can set different parameters to a command, and can convert them super easy

from discord.ext import commands  # import commands

# instead of client = discord.Client()
client = discord.Client()
# use this
client = commands.Bot(command_prefix="!")

remove the on_message event, or add client.process_commands to it

@client.event
async def on_message(message):
    await client.process_commands(message) # add this line
    # you can also add other stuff here
# add a command
@client.command()
async def random(ctx, max_number: int): 
    await ctx.send(f"Your number is: {random.randint(1, max_number)}")


# you can also add a second arg
@client.command()
async def random2(ctx, min_number: int, max_number: int): 
    await ctx.send(f"Your number is: {random.randint(min_number, max_number)}")

to use the command you can type !random 50 or !random2 20 50

Upvotes: 0

Related Questions