Skip to content

Commit

Permalink
Update logging look and move some logic to bot.py.
Browse files Browse the repository at this point in the history
  • Loading branch information
Sachaa-Thanasius committed Oct 16, 2023
1 parent d88c114 commit 262de0b
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 28 deletions.
51 changes: 51 additions & 0 deletions core/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
from __future__ import annotations

import logging
import sys
import time
import traceback
from typing import TYPE_CHECKING, Any

import aiohttp
Expand Down Expand Up @@ -118,6 +120,55 @@ async def get_context(
# Figure out if there's a way to type-hint this better to allow cls to actually work.
return await super().get_context(origin, cls=Context)

async def on_error(self, event_method: str, /, *args: Any, **kwargs: Any) -> None:
exc_type, exception, tb = sys.exc_info()
tb_text = "".join(traceback.format_exception(exc_type, exception, tb, chain=False))
embed = (
discord.Embed(
title="Event Error",
description=f"```py\n{tb_text}\n```",
colour=discord.Colour.dark_gold(),
timestamp=discord.utils.utcnow(),
)
.add_field(name="Event", value=event_method, inline=False)
.add_field(
name="Args",
value="```py\n" + "\n".join(f"{i}: {arg!r}" for i, arg in enumerate(args)) + "\n```",
inline=False,
)
.add_field(
name="Kwargs",
value="```py\n" + "\n".join(f"{name}: {kwarg!r}" for name, kwarg in kwargs.items()) + "\n```",
inline=False,
)
)
LOGGER.exception("Ignoring exception in %s", event_method, extra={"embed": embed})

async def on_command_error(self, context: Context, exception: commands.CommandError) -> None: # type: ignore [reportIncompatibleMethodOverride]
assert context.command # Pre-condition for being here.

exception = getattr(exception, "original", exception)

tb_text = "".join(traceback.format_exception(type(exception), exception, exception.__traceback__, chain=False))
embed = (
discord.Embed(
title="Command Error",
description=f"```py\n{tb_text}\n```",
colour=discord.Colour.dark_magenta(),
timestamp=discord.utils.utcnow(),
)
.set_author(name=context.author, icon_url=context.author.display_avatar.url)
.add_field(name="Name", value=context.command.qualified_name, inline=False)
.add_field(
name="Parameters",
value=f"```json\n{context.args}\n{context.kwargs.items()}\n```",
inline=False,
)
.add_field(name="Guild", value=f"{context.guild.name if context.guild else '-----'}", inline=False)
.add_field(name="Channel", value=f"{context.channel}", inline=False)
)
LOGGER.exception("Ignoring exception in command %s", context.command, extra={"embed": embed})

@property
def owner(self) -> discord.User:
""":class:`discord.User`: The user that owns the bot."""
Expand Down
31 changes: 3 additions & 28 deletions exts/webhook_logging.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from __future__ import annotations

import traceback

import discord
from discord.ext import commands, tasks

Expand All @@ -12,42 +10,19 @@ class LoggingCog(commands.Cog):
def __init__(self, bot: core.Beira) -> None:
self.bot = bot
self.webhook = discord.Webhook.from_url(core.CONFIG.discord.logging_webhook, client=bot)
self.username = "Beira Logging"
self.avatar_url = "https://cdn.dribbble.com/users/1065420/screenshots/3751686/gwen-taking-notes.gif"
self.webhook_logging_loop.start()

async def cog_unload(self) -> None:
self.webhook_logging_loop.cancel()

@commands.Cog.listener("on_command_error")
async def log_command_error(self, ctx: core.Context, error: commands.CommandError) -> None:
assert ctx.command # Pre-condition for being here.

exc = "".join(traceback.format_exception(type(error), error, error.__traceback__, chain=False))

embed = (
discord.Embed(
title="Command Failure",
description=f"```py\n{exc}\n```",
colour=0xC70039,
timestamp=discord.utils.utcnow(),
)
.set_author(name=ctx.author, icon_url=ctx.author.default_avatar.url)
.add_field(name="Name", value=ctx.command.qualified_name)
.add_field(
name="Parameters",
value=f"{', '.join(ctx.args)}, {', '.join(f'{key}: {value}' for key, value in ctx.kwargs.items())}",
inline=True,
)
.add_field(name="Server", value=f"{ctx.guild.name if ctx.guild else '-----'}", inline=True)
.add_field(name="Channel", value=f"{ctx.channel}", inline=True)
)
self.bot.logging_manager.log.exception("Ignoring command error", extra={"embed": embed})

@tasks.loop(seconds=0.0)
async def webhook_logging_loop(self) -> None:
log_record = await self.bot.logging_manager.log_queue.get()
log_embed = log_record.__dict__.get("embed")
if log_embed:
await self.webhook.send(embed=log_embed)
await self.webhook.send(username=self.username, avatar_url=self.avatar_url, embed=log_embed)


async def setup(bot: core.Beira) -> None:
Expand Down

0 comments on commit 262de0b

Please sign in to comment.