Nicholas Chen
Nicholas Chen

Reputation: 144

discord.py not executing math/python code

I have this math code that doubles as a python command, and I want it to solve math. When I say p!math 3+13, it should send 16 but it's sending the problem (3+13) back at the user. Can someone help?

@client.command()
async def math(ctx, *, p):
    try:
        exec(p)
        await ctx.send(p)
    except Exception as e:
        await ctx.send(f"```python\nError: {e}```")

Upvotes: 0

Views: 43

Answers (2)

Daniel Scott
Daniel Scott

Reputation: 985

Use eval instead of exec.

# Returns 16
try:
    res = eval('3+13')
    print(res)
except Exception as e:
    print(e)

# Returns None
try:
    res = exec('3+13')
    print(res)
except Exception as e:
    print(e)

Upvotes: 1

Kelo
Kelo

Reputation: 1893

You're using the incorrect function. Instead of using exec, use eval. Additionally, you should set the returned value to a parameter and return that.

For example:

@client.command()
async def math(ctx, *, p):
    try:
        answer = eval(p)
        await ctx.send(answer)
    except Exception as e:
        await ctx.send(f"```python\nError: {e}```")

Upvotes: 1

Related Questions