-1

I have a discord bot that is limited to me and a few friends. I want to make an eval command so I can show off to them since they know nothing about code, but also for me to use in general (I have a permissions system setup so it's usage is limited to me, don't worry).

I've done a lot of googling and the closest I've gotten is this:

@commands.command()
@commands.guild_only()
async def eval(self, ctx, *, args):
    result = eval(args)
    await ctx.send(result)

This doesn't work with multi-line code though. For example, I tried this code:

&eval a=2
b=2
c=a*b
print(str(a), str(b), str(c))

It returns this error: Invalid syntax and points to a=2 as the error. With other solutions like the ones from the creator's github, it said that eval() takes 1 positional argument but 2 were given. I'm using the commands extension and the eval command will be in a cog. Thanks!

finalerock44
  • 65
  • 2
  • 11

1 Answers1

0

The eval function is supposed to execute only one expression, for dynamic execution use exec

>>> code = """
... a = 2
... b = 2
... c = a * b
... print(a, b, c)
... """
>>> exec(code)
2 2 4

You can also use aioconsole.aexec for a non-blocking way

>>> from aioconsole import aexec
>>> 
>>> code = """
... a = 2
... b = 2
... c = a * b
... print(a, b, c)
... """
>>> await aexec(code) # It should be awaited inside another coroutine, not doing so for explanation purposes
2 2 4

aioconsole pypi page

Łukasz Kwieciński
  • 14,992
  • 4
  • 21
  • 39
  • For both methods, it calls an error labelled `cannot send an empty message`. Any ideas? – finalerock44 Feb 28 '21 at 21:07
  • yes, the value you're getting is `None`, neither `exec` and `aexec` return any values, you shouldn't assign them to a variable, there are a couple of ways of catching the output from the console, for more info refer to this post: https://stackoverflow.com/questions/25621134/python-pss-e-get-output-as-variable – Łukasz Kwieciński Feb 28 '21 at 21:11