Search code examples
pythondiscorddiscord.py

discord.py how to get the integer from a message


I am making a bot using discord.py and I am making a coinflip function for it but I want to use

if message.content == "g! coinflip":
  await message.channel.send("<the coinflip function>")

instead of

@bot.command()
async def coinflip():
  await message.channel.send("<the coinflip function>")

because the prefix for it is g! and in discord I want the command to look something like this g! coinflip 10000 but obviously the user will pick the amount they want to gamble which is what makes it hard.


Solution

  • If you insist on using the on_message event, one method you could try would be to use the .split() method. Then, you can check if there are enough arguments or not. After that, you can turn the last argument, which would be the number, into an integer. Though not shown here, you should check if the last argument is actually an integer first, otherwise you will receive errors. The code is shown below.

    if message.content.lower() == "g! coinflip":
        con = message.content.lower().split(" ") 
        # returned con example: ["g!", "coinflip", "3"]
        if len(con) < 3:
            await message.channel.send("Not enough arguments! Please give a number") # send the necessary feedback
            return # end this function
        elif len(con) > 3:
            await message.channel.send("Too many arguments! Please only give a number")
            return
    
        num = int(con[-1]) # turn the last number into an integer
        # then use this number for the rest of your function