diff options
Diffstat (limited to 'modules/builtins/eval.py')
-rw-r--r-- | modules/builtins/eval.py | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/modules/builtins/eval.py b/modules/builtins/eval.py new file mode 100644 index 0000000..dfbdd57 --- /dev/null +++ b/modules/builtins/eval.py @@ -0,0 +1,60 @@ +import ast + +from lib import * + + +@name('eval') +@description('evals a given piece of python code') +def eval_command(ctx: CommandContext): + try: + block = ast.parse(ctx.rest_content, mode='exec') + last = ast.Expression(block.body.pop().value) + except KeyboardInterrupt: + raise + except SystemExit: + raise + except BaseException as e: + ctx.respond("Compilation failed: %r" % e) + return + + _globals, _locals = {}, { + 'ctx': ctx, + 'message': ctx.message, + 'client': ctx.client, + 'print': + lambda *content, stdout=False: + print(*content) + if stdout + else ctx.respond('\t'.join(map(str, content))) + } + try: + exec(compile(block, '<string>', mode='exec'), _globals, _locals) + except KeyboardInterrupt: + raise + except SystemExit: + raise + except BaseException as e: + ctx.respond("Evaluation failed: %r" % str(e)) + return + + try: + compiled = compile(last, '<string>', mode='eval') + except KeyboardInterrupt: + raise + except SystemExit: + raise + except BaseException as e: + ctx.respond("Last statement has to be an expression: %r" % str(e)) + return + + try: + result = eval(compiled, _globals, _locals) + except KeyboardInterrupt: + raise + except SystemExit: + raise + except BaseException as e: + ctx.respond("Evaluation failed: %r" % str(e)) + return + + ctx.respond("Evaluation succes: \n```\n%s\n```" % str(result)) |