-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPythonEval.py
107 lines (94 loc) · 3.48 KB
/
PythonEval.py
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import inspect
import io
import textwrap
import traceback
from contextlib import redirect_stdout
import os
import aiohttp
from discord.ext import commands
import logging
logger = logging.getLogger(__name__)
class Eval(commands.Cog):
def __init__(self, bot):
self.bot = bot
logger.info("EvalCMD: Cog Loaded!")
@commands.command(name='eval')
@commands.is_owner()
async def _eval(self, ctx, *, body):
"""Evaluates python code"""
env = {
'ctx': ctx,
'bot': self.bot,
'channel': ctx.channel,
'author': ctx.author,
'guild': ctx.guild,
'message': ctx.message,
'source': inspect.getsource
}
def cleanup_code(content):
"""Automatically removes code blocks from the code."""
# remove ```py\n```
if content.startswith('```') and content.endswith('```'):
return '\n'.join(content.split('\n')[1:-1])
# remove `foo`
return content.strip('` \n')
env.update(globals())
body = cleanup_code(body)
stdout = io.StringIO()
err = out = None
to_compile = f'async def func():\n{textwrap.indent(body, " ")}'
def paginate(text: str):
'''Simple generator that paginates text.'''
last = 0
pages = []
for curr in range(0, len(text)):
if curr % 1980 == 0:
pages.append(text[last:curr])
last = curr
appd_index = curr
if appd_index != len(text)-1:
pages.append(text[last:curr])
return list(filter(lambda a: a != '', pages))
try:
exec(to_compile, env)
except Exception as e:
err = await ctx.send(f'```py\n{e.__class__.__name__}: {e}\n```')
return await ctx.message.add_reaction('\u2049')
func = env['func']
try:
with redirect_stdout(stdout):
ret = await func()
except Exception as e:
value = stdout.getvalue()
err = await ctx.send(f'```py\n{value}{traceback.format_exc()}\n```')
else:
value = stdout.getvalue()
if ret is None:
if value:
try:
out = await ctx.send(f'```py\n{value}\n```')
except:
paginated_text = paginate(value)
for page in paginated_text:
if page == paginated_text[-1]:
out = await ctx.send(f'```py\n{page}\n```')
break
await ctx.send(f'```py\n{page}\n```')
else:
try:
out = await ctx.send(f'```py\n{value}{ret}\n```')
except:
paginated_text = paginate(f"{value}{ret}")
for page in paginated_text:
if page == paginated_text[-1]:
out = await ctx.send(f'```py\n{page}\n```')
break
await ctx.send(f'```py\n{page}\n```')
if out:
await ctx.message.add_reaction('\u2705') # tick
elif err:
await ctx.message.add_reaction('\u2049') # x
else:
await ctx.message.add_reaction('\u2705')
def setup(bot):
bot.add_cog(Eval(bot))