Reintegrate Sentry for error logging

This commit is contained in:
2025-05-17 16:35:09 +02:00
parent e2c7a08188
commit 49771ddde9

View File

@ -5,6 +5,8 @@ import os
from typing import TYPE_CHECKING, Any
import discord
import sentry_sdk
from apscheduler import events
from discord.abc import PrivateChannel
from discord_webhook import DiscordWebhook
from loguru import logger
@ -22,45 +24,42 @@ from discord_reminder_bot.commands.unpause import unpause_reminder
from discord_reminder_bot.settings import scheduler
if TYPE_CHECKING:
from apscheduler.events import JobExecutionEvent
from apscheduler.job import Job
from discord.interactions import InteractionChannel
from requests import Response
# def my_listener(event: JobExecutionEvent) -> None:
# """Listener for job events.
#
# Args:
# event: The event that occurred.
# """
# # TODO(TheLovinator): We should save the job state to a file and send it to Discord. # noqa: TD003
# if event.code == events.EVENT_JOB_MISSED:
# scheduled_time: str = event.scheduled_run_time.strftime("%Y-%m-%d %H:%M:%S")
# msg: str = f"Job {event.job_id} was missed! Was scheduled at {scheduled_time}"
# send_webhook(message=msg)
#
# if event.exception:
# logger.error(f"discord-reminder-bot failed to send message to Discord\n{event}")
# with sentry_sdk.push_scope() as scope:
# scope.set_extra("job_id", event.job_id)
# scope.set_extra("scheduled_run_time", event.scheduled_run_time.isoformat() if event.scheduled_run_time else "None")
# scope.set_extra("event_code", event.code)
# sentry_sdk.capture_exception(event.exception)
#
# err_msg: str = (
# f"discord-reminder-bot failed to send message to Discord\n"
# f"Job ID: {event.job_id}\n"
# f"Scheduled run time: {event.scheduled_run_time.isoformat() if event.scheduled_run_time else 'None'}\n"
# f"Event code: {event.code}\n"
# f"Exception: {event.exception}\n"
# "```python\n"
# f"{event.traceback}\n"
# "```"
# )
#
# send_webhook(message=err_msg)
#
# raise event.exception
def my_listener(event: JobExecutionEvent) -> None:
"""Listener for job events.
Args:
event: The event that occurred.
"""
# TODO(TheLovinator): We should save the job state to a file and send it to Discord. # noqa: TD003
if event.code == events.EVENT_JOB_MISSED:
scheduled_time: str = event.scheduled_run_time.strftime("%Y-%m-%d %H:%M:%S")
msg: str = f"Job {event.job_id} was missed! Was scheduled at {scheduled_time}"
send_webhook(message=msg)
if event.exception:
logger.error(f"discord-reminder-bot failed to send message to Discord\n{event}")
with sentry_sdk.push_scope() as scope:
scope.set_extra("job_id", event.job_id)
scope.set_extra("scheduled_run_time", event.scheduled_run_time.isoformat() if event.scheduled_run_time else "None")
scope.set_extra("event_code", event.code)
sentry_sdk.capture_exception(event.exception)
err_msg: str = (
f"discord-reminder-bot failed to send message to Discord\n"
f"Job ID: {event.job_id}\n"
f"Scheduled run time: {event.scheduled_run_time.isoformat() if event.scheduled_run_time else 'None'}\n"
f"Event code: {event.code}\n"
f"Exception: {event.exception}\n"
"```python\n"
f"{event.traceback}\n"
"```"
)
send_webhook(message=err_msg)
raise event.exception
class RemindBotClient(discord.Client):
@ -75,40 +74,41 @@ class RemindBotClient(discord.Client):
super().__init__(intents=intents)
self.tree = discord.app_commands.CommandTree(self)
# async def on_error(self, event_method: str, *args: list[Any], **kwargs: dict[str, Any]) -> None:
# """Log errors that occur in the bot."""
# logger.exception(f"An error occurred in {event_method} with args: {args} and kwargs: {kwargs}")
# with sentry_sdk.push_scope() as scope:
# # Add event details
# scope.set_tag("event_method", event_method)
# scope.set_extra("args", args)
# scope.set_extra("kwargs", kwargs)
# # Add bot state
# scope.set_tag("bot_user_id", self.user.id if self.user else "Unknown")
# scope.set_tag("bot_user_name", str(self.user) if self.user else "Unknown")
# scope.set_tag("bot_latency", self.latency)
# # If specific arguments are available, extract and add details
# if args:
# interaction = next((arg for arg in args if isinstance(arg, discord.Interaction)), None)
# if interaction:
# scope.set_extra("interaction_id", interaction.id)
# scope.set_extra("interaction_user", interaction.user.id)
# scope.set_extra("interaction_user_tag", str(interaction.user))
# scope.set_extra("interaction_command", interaction.command.name if interaction.command else None)
# scope.set_extra("interaction_channel", str(interaction.channel))
# scope.set_extra("interaction_guild", str(interaction.guild) if interaction.guild else None)
# # Add Sentry tags for interaction details
# scope.set_tag("interaction_id", interaction.id)
# scope.set_tag("interaction_user_id", interaction.user.id)
# scope.set_tag("interaction_user_tag", str(interaction.user))
# scope.set_tag("interaction_command", interaction.command.name if interaction.command else "None")
# scope.set_tag("interaction_channel_id", interaction.channel.id if interaction.channel else "None")
# scope.set_tag("interaction_channel_name", str(interaction.channel))
# scope.set_tag("interaction_guild_id", interaction.guild.id if interaction.guild else "None")
# scope.set_tag("interaction_guild_name", str(interaction.guild) if interaction.guild else "None")
# # Add APScheduler context
# scope.set_extra("scheduler_jobs", [job.id for job in scheduler.get_jobs()])
# sentry_sdk.capture_exception()
async def on_error(self, event_method: str, *args: list[Any], **kwargs: dict[str, Any]) -> None:
"""Log errors that occur in the bot."""
logger.exception(f"An error occurred in {event_method} with args: {args} and kwargs: {kwargs}")
with sentry_sdk.push_scope() as scope:
# Add event details
scope.set_tag("event_method", event_method)
scope.set_extra("args", args)
scope.set_extra("kwargs", kwargs)
# Add bot state
scope.set_tag("bot_user_id", self.user.id if self.user else "Unknown")
scope.set_tag("bot_user_name", str(self.user) if self.user else "Unknown")
scope.set_tag("bot_latency", self.latency)
# If specific arguments are available, extract and add details
if args:
interaction = next((arg for arg in args if isinstance(arg, discord.Interaction)), None)
if interaction:
scope.set_extra("interaction_id", interaction.id)
scope.set_extra("interaction_user", interaction.user.id)
scope.set_extra("interaction_user_tag", str(interaction.user))
scope.set_extra("interaction_command", interaction.command.name if interaction.command else None)
scope.set_extra("interaction_channel", str(interaction.channel))
scope.set_extra("interaction_guild", str(interaction.guild) if interaction.guild else None)
# Add Sentry tags for interaction details
scope.set_tag("interaction_id", interaction.id)
scope.set_tag("interaction_user_id", interaction.user.id)
scope.set_tag("interaction_user_tag", str(interaction.user))
scope.set_tag("interaction_command", interaction.command.name if interaction.command else "None")
scope.set_tag("interaction_channel_id", interaction.channel.id if interaction.channel else "None")
scope.set_tag("interaction_channel_name", str(interaction.channel))
scope.set_tag("interaction_guild_id", interaction.guild.id if interaction.guild else "None")
scope.set_tag("interaction_guild_name", str(interaction.guild) if interaction.guild else "None")
# Add APScheduler context
scope.set_extra("scheduler_jobs", [job.id for job in scheduler.get_jobs()])
sentry_sdk.capture_exception()
async def on_ready(self) -> None:
"""Log when the bot is ready."""
@ -117,7 +117,8 @@ class RemindBotClient(discord.Client):
async def setup_hook(self) -> None:
"""Setup the bot."""
scheduler.start()
# scheduler.add_listener(my_listener, EVENT_JOB_MISSED | EVENT_JOB_ERROR)
scheduler.add_listener(my_listener, events.EVENT_JOB_MISSED | events.EVENT_JOB_ERROR)
jobs: list[Job] = scheduler.get_jobs()
if not jobs:
logger.info("No jobs available.")