WIP Cleaning up the code base + impl slash commands

This commit is contained in:
2021-10-30 22:05:40 +02:00
parent 425d3a3a92
commit bcf3d957a8
16 changed files with 973 additions and 541 deletions
+74 -62
View File
@@ -11,32 +11,36 @@ from io import BytesIO
from platform import python_version
from contextlib import redirect_stdout
from discord.ext.commands.context import Context
from bot import ChristmasBot
class OwnerCog(commands.Cog):
def __init__(self, bot):
def __init__(self, bot: ChristmasBot):
self.bot = bot
self._last_result = None
@staticmethod
def cleanup_code(content):
if content.startswith('```') and content.endswith('```'):
return '\n'.join(content.split('\n')[1:-1])
return content.strip('` \n')
if content.startswith("```") and content.endswith("```"):
return "\n".join(content.split("\n")[1:-1])
return content.strip("` \n")
# Hidden means it won't show up on the default help.
@commands.command(name='load', hidden=True)
@commands.command(name="load", hidden=True)
@commands.is_owner()
async def _cog_load(self, ctx, *, cog: str):
async def _cog_load(self, ctx: Context, *, cog: str):
"""Command which Loads a Module."""
try:
self.bot.load_extension(cog)
except Exception as e:
await ctx.send(f'**`ERROR:`** {type(e).__name__} - {e}')
await ctx.send(f"**`ERROR:`** {type(e).__name__} - {e}")
else:
await ctx.send('**`SUCCESS`**')
await ctx.send("**`SUCCESS`**")
@commands.command(name='unload', hidden=True)
@commands.command(name="unload", hidden=True)
@commands.is_owner()
async def _cog_unload(self, ctx, *, cog: str):
"""Command which Unloads a Module."""
@@ -44,11 +48,11 @@ class OwnerCog(commands.Cog):
try:
self.bot.unload_extension(cog)
except Exception as e:
await ctx.send(f'**`ERROR:`** {type(e).__name__} - {e}')
await ctx.send(f"**`ERROR:`** {type(e).__name__} - {e}")
else:
await ctx.send('**`SUCCESS`**')
await ctx.send("**`SUCCESS`**")
@commands.command(name='reload', hidden=True)
@commands.command(name="reload", hidden=True)
@commands.is_owner()
async def _cog_reload(self, ctx, *, cog: str):
"""Command which Reloads a Module."""
@@ -57,35 +61,29 @@ class OwnerCog(commands.Cog):
self.bot.unload_extension(cog)
self.bot.load_extension(cog)
except Exception as e:
await ctx.send(f'**`ERROR:`** {type(e).__name__} - {e}')
await ctx.send(f"**`ERROR:`** {type(e).__name__} - {e}")
else:
await ctx.send('**`SUCCESS`**')
await ctx.send("**`SUCCESS`**")
@commands.command(name='shutdown', hidden=True)
@commands.command(name="shutdown", hidden=True)
@commands.is_owner()
async def shutdown(self, ctx):
"""Command which shutdowns the bot."""
await ctx.bot.logout()
@commands.is_owner()
@commands.command(pass_context=True,
hidden=True,
name='eval',
aliases=['evaluate'])
@commands.command(pass_context=True, hidden=True, name="eval", aliases=["evaluate"])
async def _eval(self, ctx, *, body: str):
env = {
'bot': self.bot,
'ctx': ctx,
'channel': ctx.channel,
'author': ctx.author,
'guild': ctx.guild,
'message': ctx.message,
'_': self._last_result
"bot": self.bot,
"ctx": ctx,
"channel": ctx.channel,
"author": ctx.author,
"guild": ctx.guild,
"message": ctx.message,
"_": self._last_result,
}
if "import os" in body and ctx.author.id == 190875175460405249:
return await ctx.send("Ah ah ah, you didn't say the magic word.")
env.update(globals())
body = self.cleanup_code(body)
@@ -98,26 +96,34 @@ class OwnerCog(commands.Cog):
exec(to_compile, env)
except Exception as e:
# await ctx.message.add_reaction('naokoerror:447495055603662849')
fooem = discord.Embed(color=0xff0000)
fooem.add_field(name="Code evaluation was not successful.",
value=f'```\n{e.__class__.__name__}: {e}\n```')
fooem.set_footer(text=f"Evaluated using Python {python_version()}",
icon_url="http://i.imgur.com/9EftiVK.png")
fooem = discord.Embed(color=0xFF0000)
fooem.add_field(
name="Code evaluation was not successful.",
value=f"```\n{e.__class__.__name__}: {e}\n```",
)
fooem.set_footer(
text=f"Evaluated using Python {python_version()}",
icon_url="http://i.imgur.com/9EftiVK.png",
)
await ctx.send(embed=fooem)
# await ctx.message.remove_reaction('a:loading:452489773396000778', member=ctx.me)
func = env['func']
func = env["func"]
try:
with redirect_stdout(stdout):
ret = await func()
except Exception as e:
value = stdout.getvalue()
# await ctx.message.add_reaction('naokoerror:447495055603662849')
fooem = discord.Embed(color=0xff0000)
fooem.add_field(name="Code evaluation was not successful.",
value=f'```\n{value}{traceback.format_exc()}\n```')
fooem.set_footer(text=f"Evaluated using Python {python_version()}",
icon_url="http://i.imgur.com/9EftiVK.png")
fooem = discord.Embed(color=0xFF0000)
fooem.add_field(
name="Code evaluation was not successful.",
value=f"```\n{value}{traceback.format_exc()}\n```",
)
fooem.set_footer(
text=f"Evaluated using Python {python_version()}",
icon_url="http://i.imgur.com/9EftiVK.png",
)
await ctx.send(embed=fooem)
try:
# await ctx.message.remove_reaction('a:loading:452489773396000778', member=ctx.me)
@@ -129,7 +135,8 @@ class OwnerCog(commands.Cog):
value = stdout.getvalue()
try:
await ctx.message.remove_reaction(
'a:loading:452489773396000778', member=ctx.me)
"a:loading:452489773396000778", member=ctx.me
)
# await ctx.message.add_reaction('naokotick:447494238872141827')
except Exception:
pass
@@ -137,37 +144,42 @@ class OwnerCog(commands.Cog):
if ret is None:
if value:
sfooem = discord.Embed(color=0x170041)
sfooem.add_field(name="Code evaluation was successful!",
value=f'```\n{value}\n```')
sfooem.add_field(
name="Code evaluation was successful!",
value=f"```\n{value}\n```",
)
sfooem.set_footer(
text=f"Evaluated using Python {python_version()}",
icon_url="http://i.imgur.com/9EftiVK.png")
icon_url="http://i.imgur.com/9EftiVK.png",
)
await ctx.send(embed=sfooem)
else:
self._last_result = ret
ssfooem = discord.Embed(color=0x170041)
ssfooem.add_field(name="Code evaluation was successful!",
value=f'```\n{value}{ret}\n```')
ssfooem.add_field(
name="Code evaluation was successful!",
value=f"```\n{value}{ret}\n```",
)
ssfooem.set_footer(
text=f"Evaluated using Python {python_version()}",
icon_url="http://i.imgur.com/9EftiVK.png")
icon_url="http://i.imgur.com/9EftiVK.png",
)
await ctx.send(embed=ssfooem)
@commands.is_owner()
@commands.command(hidden=True, aliases=['exec'])
@commands.command(hidden=True, aliases=["exec"])
async def execute(self, ctx, *, text: str):
""" Do a shell command. """
"""Do a shell command."""
message = await ctx.send(f"Loading...")
proc = await asyncio.create_subprocess_shell(text,
stdin=None,
stderr=PIPE,
stdout=PIPE)
out = (await proc.stdout.read()).decode('utf-8').strip()
err = (await proc.stderr.read()).decode('utf-8').strip()
proc = await asyncio.create_subprocess_shell(
text, stdin=None, stderr=PIPE, stdout=PIPE
)
out = (await proc.stdout.read()).decode("utf-8").strip()
err = (await proc.stderr.read()).decode("utf-8").strip()
if not out and not err:
await message.delete()
return await ctx.message.add_reaction('👌')
return await ctx.message.add_reaction("👌")
content = ""
@@ -178,12 +190,12 @@ class OwnerCog(commands.Cog):
if len(content) > 1500:
try:
data = BytesIO(content.encode('utf-8'))
data = BytesIO(content.encode("utf-8"))
await message.delete()
await ctx.send(content=f"The result was a bit too long..",
file=discord.File(
data,
filename=f"result_{int(time.time())}.txt"))
await ctx.send(
content=f"The result was a bit too long..",
file=discord.File(data, filename=f"result_{int(time.time())}.txt"),
)
except asyncio.TimeoutError as e:
await message.delete()
return await ctx.send(e)
@@ -191,5 +203,5 @@ class OwnerCog(commands.Cog):
await message.edit(content=f"```fix\n{content}\n```")
def setup(bot):
def setup(bot: ChristmasBot):
bot.add_cog(OwnerCog(bot))