Migrate eval to OwnerCog, restrict to DMChannel. Bump to v1.0.0. No show help on bad non-slash command.

This commit is contained in:
Zeva Rose 2021-07-16 18:08:29 -06:00
parent 6af3099b47
commit cb9b4272ed
4 changed files with 85 additions and 76 deletions

View file

@ -9,12 +9,13 @@ from discord.ext import commands
from discord.ext.tasks import loop from discord.ext.tasks import loop
from discord.utils import find, get from discord.utils import find, get
from discord_slash import SlashCommand from discord_slash import SlashCommand
from psutil import Process
from jarvis import logo, utils from jarvis import logo, utils
from jarvis.config import get_config from jarvis.config import get_config
from jarvis.utils import build_embed from jarvis.utils import build_embed
from jarvis.utils.db import DBManager from jarvis.utils.db import DBManager
from jarvis.utils.field import Field from jarvis.utils.field import Field
from psutil import Process
if asyncio.get_event_loop().is_closed(): if asyncio.get_event_loop().is_closed():
asyncio.set_event_loop(asyncio.new_event_loop()) asyncio.set_event_loop(asyncio.new_event_loop())
@ -31,7 +32,7 @@ invites = re.compile(
jarvis = commands.Bot(command_prefix=utils.get_prefix, intents=intents) jarvis = commands.Bot(command_prefix=utils.get_prefix, intents=intents)
slash = SlashCommand(jarvis, sync_commands=True, sync_on_cog_reload=True) slash = SlashCommand(jarvis, sync_commands=True, sync_on_cog_reload=True)
jarvis_self = Process() jarvis_self = Process()
__version__ = "0.9.9" __version__ = "1.0.0"
db = DBManager(get_config().mongo).mongo db = DBManager(get_config().mongo).mongo

View file

@ -1,13 +1,8 @@
import base64 import base64
import hashlib import hashlib
import os
import re import re
import subprocess import subprocess
import sys
import traceback
import uuid import uuid
from inspect import getsource
from time import time
import discord import discord
import ulid import ulid
@ -18,7 +13,6 @@ from discord_slash import cog_ext
import jarvis import jarvis
from jarvis.utils import build_embed, convert_bytesize from jarvis.utils import build_embed, convert_bytesize
from jarvis.utils.field import Field from jarvis.utils.field import Field
from jarvis.utils.permissions import user_is_bot_admin
supported_hashes = { supported_hashes = {
x for x in hashlib.algorithms_guaranteed if "shake" not in x x for x in hashlib.algorithms_guaranteed if "shake" not in x
@ -298,67 +292,6 @@ class DevCog(commands.Cog):
await ctx.defer() await ctx.defer()
await self._cloc(ctx) await self._cloc(ctx)
def resolve_variable(self, variable):
if hasattr(variable, "__iter__"):
var_length = len(list(variable))
if (var_length > 100) and (not isinstance(variable, str)):
return f"<a {type(variable).__name__} iterable with more than 100 values ({var_length})>"
elif not var_length:
return f"<an empty {type(variable).__name__} iterable>"
if (not variable) and (not isinstance(variable, bool)):
return f"<an empty {type(variable).__name__} object>"
return (
variable
if (len(f"{variable}") <= 1000)
else f"<a long {type(variable).__name__} object with the length of {len(f'{variable}'):,}>"
)
def prepare(self, string):
arr = (
string.strip("```")
.replace("py\n", "")
.replace("python\n", "")
.split("\n")
)
if not arr[::-1][0].replace(" ", "").startswith("return"):
arr[len(arr) - 1] = "return " + arr[::-1][0]
return "".join(f"\n\t{i}" for i in arr)
@commands.command(pass_context=True, aliases=["eval", "exec", "evaluate"])
@user_is_bot_admin()
async def _eval(self, ctx, *, code: str):
code = self.prepare(code)
args = {
"discord": discord,
"sauce": getsource,
"sys": sys,
"os": os,
"imp": __import__,
"this": self,
"ctx": ctx,
}
try:
exec(f"async def func():{code}", globals().update(args), locals())
a = time()
response = await eval("func()", globals().update(args), locals())
if response is None or isinstance(response, discord.Message):
del args, code
return
if isinstance(response, str):
response = response.replace("`", "")
await ctx.send(
f"```py\n{self.resolve_variable(response)}```"
+ f"`{type(response).__name__} | {(time() - a) / 1000} ms`"
)
except Exception:
await ctx.send(f"Error occurred:```\n{traceback.format_exc()}```")
del args, code
def setup(bot): def setup(bot):
bot.add_cog(DevCog(bot)) bot.add_cog(DevCog(bot))

View file

@ -12,9 +12,7 @@ class ErrorHandlerCog(commands.Cog):
if isinstance(error, commands.errors.MissingPermissions): if isinstance(error, commands.errors.MissingPermissions):
await ctx.send("I'm afraid I can't let you do that.") await ctx.send("I'm afraid I can't let you do that.")
elif isinstance(error, commands.errors.CommandNotFound): elif isinstance(error, commands.errors.CommandNotFound):
await ctx.send( return
"Command does not exist. Run `>help` to get a list of commands"
)
else: else:
await ctx.send(f"Error processing command:\n```{error}```") await ctx.send(f"Error processing command:\n```{error}```")
@ -25,9 +23,7 @@ class ErrorHandlerCog(commands.Cog):
): ):
await ctx.send("I'm afraid I can't let you do that.") await ctx.send("I'm afraid I can't let you do that.")
elif isinstance(error, commands.errors.CommandNotFound): elif isinstance(error, commands.errors.CommandNotFound):
await ctx.send( return
"Command does not exist. Run `>help` to get a list of commands"
)
else: else:
await ctx.send(f"Error processing command:\n```{error}```") await ctx.send(f"Error processing command:\n```{error}```")

View file

@ -1,5 +1,11 @@
import os
import sys
import traceback
from inspect import getsource
from time import time
import discord import discord
from discord import User from discord import DMChannel, User
from discord.ext import commands from discord.ext import commands
import jarvis import jarvis
@ -192,6 +198,79 @@ class OwnerCog(commands.Cog):
reload_config() reload_config()
await ctx.send(f"{user.mention} is no longer an admin.") await ctx.send(f"{user.mention} is no longer an admin.")
def resolve_variable(self, variable):
if hasattr(variable, "__iter__"):
var_length = len(list(variable))
if (var_length > 100) and (not isinstance(variable, str)):
return f"<a {type(variable).__name__} iterable with more than 100 values ({var_length})>"
elif not var_length:
return f"<an empty {type(variable).__name__} iterable>"
if (not variable) and (not isinstance(variable, bool)):
return f"<an empty {type(variable).__name__} object>"
return (
variable
if (len(f"{variable}") <= 1000)
else f"<a long {type(variable).__name__} object with the length of {len(f'{variable}'):,}>"
)
def prepare(self, string):
arr = (
string.strip("```")
.replace("py\n", "")
.replace("python\n", "")
.split("\n")
)
if not arr[::-1][0].replace(" ", "").startswith("return"):
arr[len(arr) - 1] = "return " + arr[::-1][0]
return "".join(f"\n\t{i}" for i in arr)
@commands.command(
pass_context=True, aliases=["eval", "exec", "evaluate"]
)
@user_is_bot_admin()
async def _eval(self, ctx, *, code: str):
if not isinstance(ctx.message.channel, DMChannel):
return
code = self.prepare(code)
args = {
"discord": discord,
"sauce": getsource,
"sys": sys,
"os": os,
"imp": __import__,
"this": self,
"ctx": ctx,
}
try:
exec(
f"async def func():{code}",
globals().update(args),
locals(),
)
a = time()
response = await eval(
"func()", globals().update(args), locals()
)
if response is None or isinstance(response, discord.Message):
del args, code
return
if isinstance(response, str):
response = response.replace("`", "")
await ctx.send(
f"```py\n{self.resolve_variable(response)}```"
+ f"`{type(response).__name__} | {(time() - a) / 1000} ms`"
)
except Exception:
await ctx.send(
f"Error occurred:```\n{traceback.format_exc()}```"
)
del args, code
def setup(bot): def setup(bot):
bot.add_cog(OwnerCog(bot)) bot.add_cog(OwnerCog(bot))