Aaron
Aaron

Reputation: 237

Discord.py - How to make a simple calculator?

I'd like to add a simple calculator to my bot but I can't use the command.

Here's my code:

@bot.command
async def calc(ctx):
    def check(m):
        return len(m.content) >= 1 and m.author != client.user

    await ctx.send("Number 1: ")
    number_1 = await client.wait_for("message", check=check)
    await ctx.send("Operator: ")
    operator = await client.wait_for("message", check=check)
    await ctx.send("Number 2: ")
    number_2 = await client.wait_for("message", check=check)
    try:
        number_1 = float(number_1.content)
        operator = operator.content
        number_2 = float(number_2.content)
    except:
        await ctx.send("Invalid input")
        return
    if operator == "+":
        output = number_1 + number_2
    elif operator == "-":
        output = number_1 - number_2
    elif operator == "/":
        output = number_1 / number_2
    elif operator == "*":
        output = number_1 * number_2
    else:
        await ctx.send("invalid input")
        return
    await ctx.send("Answer: " + str(output))

As I can see, there're no errors, but the bot ignores me inputting the command. I tried to use _calc (as my bot's prefix is _) but nothing works. I'd be grateful for your help!

Upvotes: 2

Views: 833

Answers (1)

Ghost Ops
Ghost Ops

Reputation: 1734

As you are having on_message in your bot code, all your bot prefix commands will get end up processed in the on_message function, overriding every other bot.command functions

So, To fix this, add a bot.process_commands(message) line at the end of your on_message. For example:

@bot.event
async def on_message(message):
    # do some extra stuff here
    await bot.process_commands(message)

But you can better place your on_message inside a listener. This also allows you to do multiple things asynchronously in response to a message. For example:

@bot.listen('on_message')
async def whatever_you_want_to_call_it(message):
    # do stuff here
    # do not process commands here

For more reference, Why does on-message make my commands stop working?

Tell me if its not working...

Upvotes: 2

Related Questions