WIP
This commit is contained in:
@ -5,9 +5,6 @@ import os
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import discord
|
||||
import sentry_sdk
|
||||
from apscheduler import events
|
||||
from apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_MISSED, JobExecutionEvent
|
||||
from discord.abc import PrivateChannel
|
||||
from discord_webhook import DiscordWebhook
|
||||
from loguru import logger
|
||||
@ -26,30 +23,44 @@ from discord_reminder_bot.settings import scheduler
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from apscheduler.job import Job
|
||||
from discord.guild import GuildChannel
|
||||
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:
|
||||
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)
|
||||
|
||||
send_webhook(f"discord-reminder-bot failed to send message to Discord\n{event}")
|
||||
# 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):
|
||||
@ -64,45 +75,40 @@ 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."""
|
||||
@ -111,7 +117,7 @@ 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, EVENT_JOB_MISSED | EVENT_JOB_ERROR)
|
||||
jobs: list[Job] = scheduler.get_jobs()
|
||||
if not jobs:
|
||||
logger.info("No jobs available.")
|
||||
@ -161,15 +167,31 @@ class RemindGroup(discord.app_commands.Group):
|
||||
user (discord.User, optional): Send reminder as a DM to this user. Defaults to None.
|
||||
dm_and_current_channel (bool, optional): Send reminder as a DM to the user and in this channel. Defaults to False.
|
||||
"""
|
||||
await interaction.response.defer()
|
||||
return await add_reminder_job(
|
||||
interaction=interaction,
|
||||
logger.info(f"New reminder from {interaction.user} ({interaction.user.id}) in {interaction.channel}")
|
||||
logger.debug(f"Arguments: {locals()}")
|
||||
|
||||
if not interaction.guild:
|
||||
await interaction.response.send_message(content="Failed to get guild.", ephemeral=True)
|
||||
return
|
||||
|
||||
# Check if we should send the reminder to the specified channel or the current channel
|
||||
# TODO(TheLovinator): Check if we have access to the specified channel or the current channel # noqa: TD003
|
||||
target_channel: InteractionChannel | None = channel or interaction.channel
|
||||
channel_id: int | None = target_channel.id if target_channel else None
|
||||
if not channel_id:
|
||||
await interaction.response.send_message(content="Failed to get channel.", ephemeral=True)
|
||||
return
|
||||
|
||||
msg: str = add_reminder_job(
|
||||
author_id=interaction.user.id,
|
||||
message=message,
|
||||
time=time,
|
||||
channel=channel,
|
||||
user=user,
|
||||
channel_id=channel_id,
|
||||
guild_id=interaction.guild.id,
|
||||
user_id=user.id if user else None,
|
||||
dm_and_current_channel=dm_and_current_channel,
|
||||
)
|
||||
await interaction.response.send_message(content=msg)
|
||||
|
||||
# /remind event
|
||||
@discord.app_commands.command(name="event", description="Add a new Discord event.")
|
||||
@ -421,9 +443,12 @@ class RemindGroup(discord.app_commands.Group):
|
||||
)
|
||||
|
||||
|
||||
intents: discord.Intents = discord.Intents.default()
|
||||
intents.guild_scheduled_events = True
|
||||
# intents: discord.Intents = discord.Intents.none()
|
||||
# intents.guild_scheduled_events = True # For creating events
|
||||
# intents.guilds = True # For getting the channel to send the reminder to
|
||||
# intents.members = True # For getting the user to send the reminder to
|
||||
|
||||
intents = discord.Intents.all()
|
||||
bot = RemindBotClient(intents=intents)
|
||||
|
||||
# Add the group to the bot
|
||||
@ -454,7 +479,12 @@ def send_webhook(custom_url: str = "", message: str = "") -> None:
|
||||
webhook: DiscordWebhook = DiscordWebhook(url=url, content=message, rate_limit_retry=True)
|
||||
webhook_response: Response = webhook.execute()
|
||||
|
||||
logger.info(f"Webhook response: {webhook_response}")
|
||||
if not webhook_response.ok:
|
||||
webhook_json: dict[str, Any] = webhook.json
|
||||
logger.error(f"Failed to send {webhook_json}.\nStatus code: {webhook_response.status_code}.\n{webhook_response.text}.\n")
|
||||
return
|
||||
|
||||
logger.info(f"Webhook sent successfully. Status code: {webhook_response.status_code}.")
|
||||
|
||||
|
||||
async def send_to_discord(channel_id: int, message: str, author_id: int) -> None:
|
||||
@ -462,18 +492,44 @@ async def send_to_discord(channel_id: int, message: str, author_id: int) -> None
|
||||
|
||||
Args:
|
||||
channel_id: The Discord channel ID.
|
||||
message: The message.
|
||||
message: The reminder message.
|
||||
author_id: User we should ping.
|
||||
"""
|
||||
logger.info(f"Sending message to channel '{channel_id}' with message: '{message}'")
|
||||
logger.info(f"Sending message to '{channel_id=}' with '{message=}' and '{author_id=}'")
|
||||
|
||||
channels = list(bot.get_all_channels())
|
||||
logger.debug(f"We are in {len(channels)} channels.")
|
||||
|
||||
channel = None
|
||||
try:
|
||||
if not bot.is_closed():
|
||||
channel: discord.guild.GuildChannel | discord.threads.Thread | discord.abc.PrivateChannel | None = bot.get_channel(channel_id)
|
||||
else:
|
||||
logger.info("Bot is closed, skipping...")
|
||||
except AttributeError as e:
|
||||
e.add_note(str(bot))
|
||||
logger.exception(e)
|
||||
|
||||
channel: GuildChannel | discord.Thread | PrivateChannel | None = bot.get_channel(channel_id)
|
||||
if channel is None:
|
||||
channel = await bot.fetch_channel(channel_id)
|
||||
try:
|
||||
await bot.wait_until_ready()
|
||||
channel = await bot.fetch_channel(channel_id)
|
||||
except discord.NotFound:
|
||||
logger.exception(f"Channel not found. Current channels: {bot.get_all_channels()}")
|
||||
return
|
||||
except discord.Forbidden:
|
||||
logger.exception(f"We do not have access to the channel. Channel: {channel_id}")
|
||||
return
|
||||
except discord.HTTPException:
|
||||
logger.exception(f"Fetching the channel failed. Channel: {channel_id}")
|
||||
return
|
||||
except discord.InvalidData:
|
||||
logger.exception(f"Invalid data. Channel: {channel_id}")
|
||||
return
|
||||
|
||||
# Channels we can't send messages to
|
||||
if isinstance(channel, discord.ForumChannel | discord.CategoryChannel | PrivateChannel):
|
||||
logger.warning(f"We haven't implemented sending messages to this channel type {type(channel)}")
|
||||
logger.error(f"We haven't implemented sending messages to this channel type {type(channel)}")
|
||||
return
|
||||
|
||||
await channel.send(f"<@{author_id}>\n{message}")
|
||||
|
Reference in New Issue
Block a user