This commit is contained in:
2025-04-28 03:51:34 +02:00
parent 0eb7a26439
commit 45a9d2655c
6 changed files with 166 additions and 134 deletions

View File

@ -10,19 +10,18 @@ from discord_reminder_bot.settings import scheduler
if TYPE_CHECKING:
import datetime
import discord
from apscheduler.job import Job
from discord.interactions import InteractionChannel
async def add_reminder_job(
interaction: discord.Interaction,
def add_reminder_job(
message: str,
time: str,
channel: discord.TextChannel | None = None,
user: discord.User | None = None,
channel_id: int,
author_id: int,
user_id: int | None = None,
guild_id: int | None = None,
dm_and_current_channel: bool | None = None,
) -> None:
) -> str:
"""Adds a reminder job to the scheduler based on user input.
Schedules a message to be sent at a specified time either to a specific channel,
@ -30,87 +29,63 @@ async def add_reminder_job(
time parsing, and job creation using the APScheduler instance.
Args:
interaction: The discord interaction object initiated by the user command.
message: The content of the reminder message to be sent.
time: A string representing the date and time for the reminder.
This string will be parsed to a datetime object.
channel: The target text channel for the reminder. If None, defaults
to the channel where the interaction occurred.
user: The target user to send a direct message reminder to. If None,
no direct message is scheduled.
channel_id: The ID of the channel where the reminder will be sent.
user_id: The Discord ID of the user to send a DM to. If None, no DM is sent.
guild_id: The ID of the guild (server) where the reminder is set.
author_id: The ID of the user who created the reminder.
dm_and_current_channel: If True and a user is specified, sends the
reminder to both the user's DM and the target channel. If False
and a user is specified, only sends the DM. Defaults to None,
behaving like False if only a user is specified, or sending only
to the channel if no user is specified.
Returns:
The response message indicating the status of the reminder job creation.
"""
logger.info(f"New reminder from {interaction.user} ({interaction.user.id}) in {interaction.channel}")
logger.info(f"Arguments: {locals()}")
# Check if we have access to the specified channel or the current channel
target_channel: InteractionChannel | discord.TextChannel | None = channel or interaction.channel
if target_channel and interaction.guild and not target_channel.permissions_for(interaction.guild.me).send_messages:
await interaction.followup.send(content=f"I don't have permission to send messages in <#{target_channel.id}>.", ephemeral=True)
# Get the channel ID
channel_id: int | None = channel.id if channel else (interaction.channel.id if interaction.channel else None)
if not channel_id:
await interaction.followup.send(content="Failed to get channel.", ephemeral=True)
return
# Ensure the guild is valid
guild: discord.Guild | None = interaction.guild or None
if not guild:
await interaction.followup.send(content="Failed to get guild.", ephemeral=True)
return
dm_message: str = ""
if user:
if user_id:
parsed_time: datetime.datetime | None = parse_time(date_to_parse=time)
if not parsed_time:
await interaction.followup.send(content=f"Failed to parse time: {time}.", ephemeral=True)
return
return f"Failed to parse time: {time}."
user_reminder: Job = scheduler.add_job(
func="discord_reminder_bot.main:send_to_user",
trigger="date",
run_date=parsed_time,
kwargs={
"user_id": user.id,
"guild_id": guild.id,
"user_id": user_id,
"guild_id": guild_id,
"message": message,
},
)
logger.info(f"User reminder job created: {user_reminder} for {user.id} at {parsed_time}")
logger.info(f"User reminder job created: {user_reminder} for {user_id} at {parsed_time}")
dm_message = f" and a DM to {user.display_name}"
dm_message = f" and a DM to <@{user_id}>"
if not dm_and_current_channel:
msg = (
f"Hello {interaction.user.display_name},\n"
f"I will send a DM to {user.display_name} at:\n"
return (
f"Hello <@{author_id}>,\n"
f"I will send a DM to <@{user_id}> at:\n"
f"First run in {calculate(user_reminder)} with the message:\n**{message}**."
)
await interaction.followup.send(content=msg)
return
# Create channel reminder job
channel_job: Job = scheduler.add_job(
func="discord_reminder_bot.main:send_to_channel",
func="discord_reminder_bot.main:send_to_discord",
trigger="date",
run_date=parse_time(date_to_parse=time),
kwargs={
"channel_id": channel_id,
"message": message,
"author_id": interaction.user.id,
"author_id": author_id,
},
)
logger.info(f"Channel reminder job created: {channel_job} for {channel_id}")
msg: str = (
f"Hello {interaction.user.display_name},\n"
return (
f"Hello <@{author_id}>,\n"
f"I will notify you in <#{channel_id}>{dm_message}.\n"
f"First run in {calculate(channel_job)} with the message:\n**{message}**."
)
await interaction.followup.send(content=msg)

View File

@ -111,7 +111,7 @@ async def cron_reminder_job(
# Create channel reminder job
channel_job: Job = scheduler.add_job(
func="discord_reminder_bot.main:send_to_channel",
func="discord_reminder_bot.main:send_to_discord",
trigger="cron",
year=year,
month=month,

View File

@ -108,9 +108,9 @@ async def interval_reminder_job(
)
# Create channel reminder job
# TODO(TheLovinator): Test that "discord_reminder_bot.main:send_to_channel" is always there # noqa: TD003
# TODO(TheLovinator): Test that "discord_reminder_bot.main:send_to_discord" is always there # noqa: TD003
channel_job: Job = scheduler.add_job(
func="discord_reminder_bot.main:send_to_channel",
func="discord_reminder_bot.main:send_to_discord",
trigger="interval",
weeks=weeks,
days=days,

View File

@ -44,7 +44,7 @@ async def list_reminder_job(interaction: discord.Interaction, scheduler: AsyncIO
message: discord.InteractionMessage = await interaction.original_response()
job_summary: list[str] = generate_reminder_summary(ctx=interaction)
job_summary: list[str] = generate_reminder_summary(ctx=interaction, bot=interaction.client, scheduler=scheduler)
for i, msg in enumerate(job_summary):
if i == 0:

View File

@ -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}")

View File

@ -9,12 +9,11 @@ from apscheduler.triggers.date import DateTrigger
from apscheduler.triggers.interval import IntervalTrigger
from loguru import logger
from discord_reminder_bot.main import bot
from discord_reminder_bot.parsers import get_human_readable_time
from discord_reminder_bot.settings import scheduler
from interactions.api.models.misc import Snowflake
if TYPE_CHECKING:
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from discord.guild import GuildChannel
from discord.types.channel import _BaseChannel
@ -53,11 +52,13 @@ def generate_markdown_state(state: dict[str, Any]) -> str:
return "```json\n" + msg + "\n```"
def generate_reminder_summary(ctx: discord.Interaction) -> list[str]: # noqa: PLR0912
def generate_reminder_summary(ctx: discord.Interaction, bot: discord.Client, scheduler: AsyncIOScheduler) -> list[str]: # noqa: PLR0912
"""Create a message with all the jobs, splitting messages into chunks of up to 2000 characters.
Args:
ctx (discord.Interaction): The context of the interaction.
bot (discord.Client): The Discord bot client.
scheduler (AsyncIOScheduler): The scheduler to get the jobs from.
Returns:
list[str]: A list of messages with all the jobs.