WIP: Refactor Aurora (3.0.0) #29

Draft
cswimr wants to merge 347 commits from aurora-pydantic into main
3 changed files with 41 additions and 15 deletions
Showing only changes of commit e7e8d60f3b - Show all commits

View file

@ -1,5 +1,5 @@
from datetime import datetime, timedelta
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing import Any, ClassVar, Dict, List, Literal, Optional, Union
from discord import Forbidden, HTTPException, InvalidData, NotFound
from pydantic import BaseModel
@ -10,6 +10,11 @@ from aurora.utilities.utils import generate_dict
class AuroraBaseModel(BaseModel):
"""Base class for all models in Aurora."""
def to_json(self, indent: int = None, file: Any = None, **kwargs):
from aurora.utilities.json import dump, dumps
return dump(self.model_dump(), file, indent=indent, **kwargs) if file else dumps(self.model_dump(), indent=indent, **kwargs)
class Moderation(AuroraBaseModel):
bot: ClassVar[Red]
moderation_id: int
@ -86,6 +91,21 @@ class Moderation(AuroraBaseModel):
return dump(self.model_dump(exclude={"bot", "guild_id"}), file, indent=indent, **kwargs) if file else dumps(self.model_dump(exclude={"bot", "guild_id"}), indent=indent, **kwargs)
class Change(AuroraBaseModel):
type: Literal["ORIGINAL", "RESOLVE", "EDIT"]
timestamp: datetime
reason: str
user_id: int
duration: Optional[timedelta]
end_timestamp: Optional[datetime]
def __str__(self):
return f"{self.type} {self.user_id} {self.reason}"
@classmethod
def from_dict(cls, data: dict) -> "Change":
return cls(**data)
class PartialUser(AuroraBaseModel):
id: int
username: str
@ -108,6 +128,7 @@ class PartialUser(AuroraBaseModel):
except NotFound:
return cls(id=user_id, username="Deleted User", discriminator=0)
class PartialChannel(AuroraBaseModel):
id: int
name: str

View file

@ -2,17 +2,13 @@
from datetime import datetime, timedelta
from typing import Union
from discord import (Color, Embed, Guild, Interaction, InteractionMessage,
Member, Role, User)
from discord import Color, Embed, Guild, Interaction, InteractionMessage, Member, Role, User
from redbot.core import commands
from redbot.core.utils.chat_formatting import (bold, box, error,
humanize_timedelta, warning)
from redbot.core.utils.chat_formatting import bold, box, error, humanize_timedelta, warning
from aurora.models import Moderation
from aurora.utilities.config import config
from aurora.utilities.utils import (fetch_channel_dict, fetch_user_dict,
get_bool_emoji, get_next_case_number,
get_pagesize_str)
from aurora.utilities.utils import fetch_channel_dict, fetch_user_dict, get_bool_emoji, get_next_case_number, get_pagesize_str
async def message_factory(
@ -212,22 +208,22 @@ async def case_factory(interaction: Interaction, moderation: Moderation) -> Embe
return embed
async def changes_factory(interaction: Interaction, case_dict: dict) -> Embed:
async def changes_factory(interaction: Interaction, moderation: Moderation) -> Embed:
"""This function creates a changes embed from set parameters.
Args:
interaction (Interaction): The interaction object.
case_dict (dict): The case dictionary.
interaction (discord.Interaction): The interaction object.
moderation (aurora.models.Moderation): The moderation object.
"""
embed = Embed(
title=f"📕 Case #{case_dict['moderation_id']:,} Changes",
title=f"📕 Case #{moderation.id:,} Changes",
color=await interaction.client.get_embed_color(interaction.channel),
)
memory_dict = {}
if case_dict["changes"]:
for change in case_dict["changes"]:
if moderation.changes:
for change in moderation.changes:
if change["user_id"] not in memory_dict:
memory_dict[str(change["user_id"])] = await fetch_user_dict(
interaction.client, change["user_id"]

View file

@ -9,9 +9,11 @@ from discord.errors import Forbidden, NotFound
from redbot.core import commands, data_manager
from redbot.core.utils.chat_formatting import error
from aurora.models import Change
from aurora.utilities.config import config
def check_permissions(
user: User,
permissions: list,
@ -130,6 +132,13 @@ def generate_dict(result: dict, guild_id: int) -> dict:
duration = timedelta(hours=hours, minutes=minutes, seconds=seconds)
else:
duration = None
if result[14] is not None:
changes = json.loads(result[14].strip('"').replace('\\"', '"'))
change_obj_list = []
for change in changes:
change_obj_list.append(Change(**change))
case = {
"moderation_id": int(result[0]),
"guild_id": int(guild_id),
@ -146,7 +155,7 @@ def generate_dict(result: dict, guild_id: int) -> dict:
"resolved_by": result[11],
"resolve_reason": result[12],
"expired": bool(result[13]),
"changes": json.loads(result[14].strip('"').replace('\\"', '"')) if result[14] else [],
"changes": change_obj_list if result[14] else [],
"metadata": json.loads(result[15].strip('"').replace('\\"', '"')) if result[15] else {},
}
return case