-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.py
132 lines (106 loc) · 4.04 KB
/
exec.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
"""
Handy exec (eval, debug) cog. Allows you to run code on the bot during runtime. This cog
is a combination of the exec commands of other bot authors:
Credit:
- Rapptz (Danny)
- https://github.com/Rapptz/RoboDanny/blob/master/cogs/repl.py#L31-L75
- b1naryth1ef (B1nzy, Andrei)
- https://github.com/b1naryth1ef/b1nb0t/blob/master/plugins/util.py#L220-L257
Features:
- Strips code markup (code blocks, inline code markup)
- Access to last result with _
- _get and _find instantly available without having to import discord
- Redirects stdout so you can print()
- Sane syntax error reporting
"""
import io
import logging
import textwrap
import traceback
from contextlib import redirect_stdout
import discord
from discord.ext import commands
log = logging.getLogger(__name__)
class Exec:
def __init__(self, bot):
self.bot = bot
self.last_result = None
def strip_code_markup(self, content: str) -> str:
""" Strips code markup from a string. """
# ```py
# code
# ```
if content.startswith('```') and content.endswith('```'):
# grab the lines in the middle
return '\n'.join(content.split('\n')[1:-1])
# `code`
return content.strip('` \n')
def format_syntax_error(self, e: SyntaxError) -> str:
""" Formats a SyntaxError. """
if e.text is None:
return '```py\n{0.__class__.__name__}: {0}\n```'.format(e)
# display a nice arrow
return '```py\n{0.text}{1:>{0.offset}}\n{2}: {0}```'.format(e, '^', type(e).__name__)
@commands.command(name='eval', aliases=['exec', 'debug'])
@commands.is_owner()
async def _eval(self, ctx, *, code: str):
""" Executes Python code. """
log.info('Eval: %s', code)
env = {
'bot': ctx.bot,
'ctx': ctx,
'msg': ctx.message,
'guild': ctx.guild,
'channel': ctx.channel,
'me': ctx.message.author,
# utilities
'_get': discord.utils.get,
'_find': discord.utils.find,
# last result
'_': self.last_result
}
env.update(globals())
# remove any markup that might be in the message
code = self.strip_code_markup(code)
# add an implicit return at the end
lines = code.split('\n')
if not lines[-1].startswith('return'):
lines[-1] = 'return ' + lines[-1]
code = '\n'.join(lines)
# simulated stdout
stdout = io.StringIO()
# wrap the code in a function, so that we can use await
wrapped_code = 'async def func():\n' + textwrap.indent(code, ' ')
try:
exec(compile(wrapped_code, '<exec>', 'exec'), env)
except SyntaxError as e:
return await ctx.send(self.format_syntax_error(e))
func = env['func']
try:
with redirect_stdout(stdout):
ret = await func()
except Exception as e:
# something went wrong
stream = stdout.getvalue()
await ctx.send('```py\n{}{}\n```'.format(stream, traceback.format_exc()))
else:
# successful
stream = stdout.getvalue()
try:
await ctx.message.add_reaction('\u2705')
except:
# couldn't add the reaction, ignore
log.warning('Failed to add reaction to eval message, ignoring.')
try:
self.last_result = self.last_result if ret is None else ret
await ctx.send('```py\n{}{}\n```'.format(stream, repr(ret)))
except discord.HTTPException:
# too long
try:
url = await haste(ctx.bot.session, stream + repr(ret))
await ctx.send('Result was too long. ' + url)
except KeyError:
# even hastebin couldn't handle it
await ctx.send('Result was too long, even for Hastebin.')
def setup(bot):
bot.add_cog(Exec(bot))