Move custom Jarvis client class to own file

This commit is contained in:
Zeva Rose 2022-02-21 01:27:55 -07:00
parent 6349321e5c
commit 33440f6150
2 changed files with 83 additions and 82 deletions

View file

@ -1,15 +1,12 @@
"""Main J.A.R.V.I.S. package."""
import json
import logging
import traceback
from datetime import datetime
from aiohttp import ClientSession
from dis_snek import Context, Intents, Snake, listen
from dis_snek import Intents
from jarvis_core.db import connect
# from jarvis import logo # noqa: F401
from jarvis import utils
from jarvis.client import Jarvis
from jarvis.config import get_config
from jarvis.events import member, message
@ -24,84 +21,12 @@ logger.addHandler(file_handler)
intents = Intents.DEFAULT | Intents.MESSAGES | Intents.GUILD_MEMBERS
restart_ctx = None
DEFAULT_GUILD = 862402786116763668
DEFAULT_ERROR_CHANNEL = 943395824560394250
DEFAULT_URL = "https://paste.zevs.me/documents"
ERROR_MSG = """
Command Information:
Name: {invoked_name}
Args:
{arg_str}
Callback:
Args:
{callback_args}
Kwargs:
{callback_kwargs}
"""
class Jarvis(Snake):
async def on_command_error(
self, ctx: Context, error: Exception, *args: list, **kwargs: dict
) -> None:
"""Lepton on_command_error override."""
guild = await jarvis.fetch_guild(DEFAULT_GUILD)
channel = await guild.fetch_channel(DEFAULT_ERROR_CHANNEL)
error_time = datetime.utcnow().strftime("%d-%m-%Y %H:%M-%S.%f UTC")
timestamp = int(datetime.now().timestamp())
timestamp = f"<t:{timestamp}:T>"
arg_str = (
"\n".join(f" {k}: {v}" for k, v in ctx.kwargs.items()) if ctx.kwargs else " None"
)
callback_args = "\n".join(f" - {i}" for i in args) if args else " None"
callback_kwargs = (
"\n".join(f" {k}: {v}" for k, v in kwargs.items()) if kwargs else " None"
)
full_message = ERROR_MSG.format(
error_time=error_time,
invoked_name=ctx.invoked_name,
arg_str=arg_str,
callback_args=callback_args,
callback_kwargs=callback_kwargs,
)
if len(full_message) >= 1900:
error_message = " ".join(traceback.format_exception(error))
full_message += "Exception: |\n " + error_message
async with ClientSession() as session:
resp = await session.post(DEFAULT_URL, data=full_message)
data = await resp.read()
data = json.loads(data.decode("UTF8"))
await channel.send(
f"JARVIS encountered an error at {timestamp}. Log too big to send over Discord."
f"\nPlease see log at https://paste.zevs.me/{data['key']}"
)
else:
error_message = "".join(traceback.format_exception(error))
await channel.send(
f"JARVIS encountered an error at {timestamp}:"
f"\n```yaml\n{full_message}\n```"
f"\nException:\n```py\n{error_message}\n```"
)
await ctx.send("Whoops! Encountered an error. The error has been logged.", ephemeral=True)
return await super().on_command_error(ctx, error, *args, **kwargs)
jarvis = Jarvis(intents=intents, default_prefix="!", sync_interactions=jconfig.sync)
__version__ = "2.0.0a1"
@listen()
async def on_ready() -> None:
"""Lepton on_ready override."""
global restart_ctx
print(" Logged in as {0.user}".format(jarvis)) # noqa: T001
print(" Connected to {} guild(s)".format(len(jarvis.guilds))) # noqa: T001
def run() -> None:
"""Run J.A.R.V.I.S."""
connect(**jconfig.mongo["connect"], testing=jconfig.mongo["database"] != "jarvis")
@ -110,11 +35,6 @@ def run() -> None:
for extension in utils.get_extensions():
jarvis.load_extension(extension)
print( # noqa: T001
" https://discord.com/api/oauth2/authorize?client_id="
"{}&permissions=8&scope=bot%20applications.commands".format(jconfig.client_id)
)
jarvis.max_messages = jconfig.max_messages
# Add event listeners

81
jarvis/client.py Normal file
View file

@ -0,0 +1,81 @@
"""Custom JARVIS client."""
import json
import traceback
from datetime import datetime
from aiohttp import ClientSession
from dis_snek import Context, Snake, listen
DEFAULT_GUILD = 862402786116763668
DEFAULT_ERROR_CHANNEL = 943395824560394250
DEFAULT_URL = "https://paste.zevs.me/documents"
ERROR_MSG = """
Command Information:
Name: {invoked_name}
Args:
{arg_str}
Callback:
Args:
{callback_args}
Kwargs:
{callback_kwargs}
"""
class Jarvis(Snake):
@listen()
async def on_ready(self) -> None:
"""Lepton on_ready override."""
print("Logged in as {}".format(self.user)) # noqa: T001
print("Connected to {} guild(s)".format(len(self.guilds))) # noqa: T001
print( # noqa: T001
"https://discord.com/api/oauth2/authorize?client_id="
"{}&permissions=8&scope=bot%20applications.commands".format(self.user.id)
)
async def on_command_error(
self, ctx: Context, error: Exception, *args: list, **kwargs: dict
) -> None:
"""Lepton on_command_error override."""
guild = await self.fetch_guild(DEFAULT_GUILD)
channel = await guild.fetch_channel(DEFAULT_ERROR_CHANNEL)
error_time = datetime.utcnow().strftime("%d-%m-%Y %H:%M-%S.%f UTC")
timestamp = int(datetime.now().timestamp())
timestamp = f"<t:{timestamp}:T>"
arg_str = (
"\n".join(f" {k}: {v}" for k, v in ctx.kwargs.items()) if ctx.kwargs else " None"
)
callback_args = "\n".join(f" - {i}" for i in args) if args else " None"
callback_kwargs = (
"\n".join(f" {k}: {v}" for k, v in kwargs.items()) if kwargs else " None"
)
full_message = ERROR_MSG.format(
error_time=error_time,
invoked_name=ctx.invoked_name,
arg_str=arg_str,
callback_args=callback_args,
callback_kwargs=callback_kwargs,
)
if len(full_message) >= 1900:
error_message = " ".join(traceback.format_exception(error))
full_message += "Exception: |\n " + error_message
async with ClientSession() as session:
resp = await session.post(DEFAULT_URL, data=full_message)
data = await resp.read()
data = json.loads(data.decode("UTF8"))
await channel.send(
f"JARVIS encountered an error at {timestamp}. Log too big to send over Discord."
f"\nPlease see log at https://paste.zevs.me/{data['key']}"
)
else:
error_message = "".join(traceback.format_exception(error))
await channel.send(
f"JARVIS encountered an error at {timestamp}:"
f"\n```yaml\n{full_message}\n```"
f"\nException:\n```py\n{error_message}\n```"
)
await ctx.send("Whoops! Encountered an error. The error has been logged.", ephemeral=True)
return await super().on_command_error(ctx, error, *args, **kwargs)