aboutsummaryrefslogtreecommitdiff
path: root/modules/builtins/eval.py
blob: dfbdd57de28c9883a421505182463e5443fa03d1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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))