Skip to content

Commit

Permalink
Migrated cron collection to use ODM
Browse files Browse the repository at this point in the history
  • Loading branch information
Nydauron committed May 31, 2024
1 parent bbcb5f3 commit 5f337e5
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 27 deletions.
2 changes: 2 additions & 0 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from discord.ext import commands
from rich.logging import RichHandler

import src.mongo.models
from env import env
from src.discord.globals import (
CHANNEL_BOTSPAM,
Expand Down Expand Up @@ -164,6 +165,7 @@ async def setup_hook(self) -> None:
await init_beanie(
database=self.mongo_database.client["data"],
document_models=[
src.mongo.models.Cron,
# TODO
],
)
Expand Down
3 changes: 2 additions & 1 deletion src/discord/staffcommands.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
ROLE_WM,
)
from src.discord.invitationals import update_invitational_list
from src.mongo.models import Cron
from src.wiki.mosteditstable import run_table

if TYPE_CHECKING:
Expand Down Expand Up @@ -887,7 +888,7 @@ async def cron(self, interaction: discord.Interaction):
"""
commandchecks.is_staff_from_ctx(interaction)

cron_list = await self.bot.mongo_database.get_cron()
cron_list = await Cron.find_all().to_list()
if not len(cron_list):
return await interaction.response.send_message(
"Unfortunately, there are no items in the CRON list to manage.",
Expand Down
36 changes: 19 additions & 17 deletions src/discord/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from env import env
from src.discord.invitationals import update_invitational_list
from src.discord.views import UnselfmuteView
from src.mongo.models import Cron

if TYPE_CHECKING:
from bot import PiBot
Expand Down Expand Up @@ -204,19 +205,19 @@ async def cron(self) -> None:
"""
logger.debug("Executing CRON...")
# Get the relevant tasks
cron_list = await self.bot.mongo_database.get_cron()
cron_list = await Cron.find_all().to_list()

for task in cron_list:
# If the date has passed, execute task
if discord.utils.utcnow() > task["time"]:
if discord.utils.utcnow() > task.time:
try:
if task["type"] == "UNBAN":
if task.cron_type == "UNBAN":
await self.cron_handle_unban(task)
elif task["type"] == "UNMUTE":
elif task.cron_type == "UNMUTE":
await self.cron_handle_unmute(task)
elif task["type"] == "UNSELFMUTE":
elif task.cron_type == "UNSELFMUTE":
await self.cron_handle_unselfmute(task)
elif task["type"] == "REMOVE_STATUS":
elif task.cron_type == "REMOVE_STATUS":
await self.cron_handle_remove_status(task)
else:
logger.error("ERROR:")
Expand All @@ -227,7 +228,7 @@ async def cron(self) -> None:
reporter_cog: commands.Cog | Reporter = self.bot.get_cog("Reporter")
await reporter_cog.create_cron_task_report(task)

async def cron_handle_unban(self, task: dict):
async def cron_handle_unban(self, task: Cron):
"""
Handles serving CRON tasks with the type of 'UNBAN'.
"""
Expand All @@ -239,7 +240,7 @@ async def cron_handle_unban(self, task: dict):
assert isinstance(server, discord.Guild)

# Attempt to unban user
member = await self.bot.fetch_user(task["user"])
member = await self.bot.fetch_user(task.user)
if member in server.members:
# User is still in server, thus already unbanned
await reporter_cog.create_cron_unban_auto_notice(member, is_present=True)
Expand All @@ -258,9 +259,9 @@ async def cron_handle_unban(self, task: dict):
)

# Remove cron task.
await self.delete_from_cron(task["_id"])
await task.delete()

async def cron_handle_unmute(self, task: dict):
async def cron_handle_unmute(self, task: Cron):
"""
Handles serving CRON tasks with the type of 'UNMUTE'.
"""
Expand All @@ -277,7 +278,7 @@ async def cron_handle_unmute(self, task: dict):
assert isinstance(muted_role, discord.Role)

# Attempt to unmute user
member = server.get_member(task["user"])
member = server.get_member(task.user)
if member in server.members:
# User is still in server, thus can be unmuted
await member.remove_roles(muted_role)
Expand All @@ -287,9 +288,9 @@ async def cron_handle_unmute(self, task: dict):
await reporter_cog.create_cron_unmute_auto_notice(member, is_present=False)

# Remove cron task.
await self.delete_from_cron(task["_id"])
await task.delete()

async def cron_handle_unselfmute(self, task: dict):
async def cron_handle_unselfmute(self, task: Cron):
"""
Handles serving CRON tasks with the type of 'UNSELFMUTE'.
"""
Expand All @@ -306,18 +307,19 @@ async def cron_handle_unselfmute(self, task: dict):
assert isinstance(muted_role, discord.Role)

# Attempt to unmute user
member = server.get_member(task["user"])
member = server.get_member(task.user)
if member in server.members:
# User is still in server, thus can be unmuted
await member.remove_roles(muted_role)

# Remove cron task.
await self.delete_from_cron(task["_id"])
await task.delete()

async def cron_handle_remove_status(self, task: dict):
async def cron_handle_remove_status(self, task: Cron):
"""
Handles serving CRON tasks with the type of 'REMOVE_STATUS'.
"""
# FIXME: Subject to premature removal of status if two /status commands are run with different expirations
# Attempt to remove status
self.bot.settings["custom_bot_status_type"] = None # reset local settings
self.bot.settings["custom_bot_status_text"] = None # reset local settings
Expand All @@ -330,7 +332,7 @@ async def cron_handle_remove_status(self, task: dict):
self.change_bot_status.restart() # update bot now

# Remove cron task.
await self.delete_from_cron(task["_id"])
await task.delete()

@tasks.loop(hours=1)
async def change_bot_status(self):
Expand Down
7 changes: 4 additions & 3 deletions src/discord/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import discord

from src.discord.globals import ROLE_SELFMUTE
from src.mongo.models import Cron

if TYPE_CHECKING:
from bot import PiBot
Expand Down Expand Up @@ -47,10 +48,10 @@ async def unselfmute_button(
try:
item = next(
x
for x in await self.bot.mongo_database.get_cron()
if (x["type"] == "UNSELFMUTE" and x["user"] == interaction.user.id)
for x in await Cron.find_all().to_list()
if (x.cron_type == "UNSELFMUTE" and x.user == interaction.user.id)
)
await self.bot.mongo_database.remove_doc("data", "cron", item["_id"])
await item.delete()
except Exception: # not in the database - maybe was removed!
pass

Expand Down
18 changes: 18 additions & 0 deletions src/mongo/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,21 @@
"""
Contains all database models
"""
from datetime import datetime
from typing import Annotated, Literal

from beanie import Document, Indexed
from pydantic import Field


class Cron(Document):
cron_type: Literal["UNMUTE", "UNBAN", "UNSELFMUTE", "REMOVE_STATUS"] = Field(
alias="type",
)
time: Annotated[datetime, Indexed()]
user: Annotated[int, Indexed()]
tag: str

class Settings:
name = "cron"
use_cache = False
6 changes: 0 additions & 6 deletions src/mongo/mongo.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,6 @@ async def get_invitationals(self):
"""
return await self.get_entire_collection("data", "invitationals")

async def get_cron(self):
"""
Gets all documents in the CRON collection.
"""
return await self.get_entire_collection("data", "cron")

async def get_censor(self):
"""
Gets the document containing censor information from the censor collection.
Expand Down

0 comments on commit 5f337e5

Please sign in to comment.