From ba7a427dad2306dbeb1cde9e9d4874de0e9df69e Mon Sep 17 00:00:00 2001 From: cswimr Date: Sat, 25 Jan 2025 20:04:02 +0000 Subject: [PATCH 1/6] feat(aurora): v3 --- aurora/aurora.py | 1933 ++++++++++------------------- aurora/importers/aurora.py | 146 ++- aurora/importers/galacticbot.py | 85 +- aurora/info.json | 1 + aurora/menus/addrole.py | 18 +- aurora/menus/guild.py | 44 +- aurora/menus/immune.py | 18 +- aurora/menus/overrides.py | 32 +- aurora/menus/types.py | 71 ++ aurora/models/base.py | 34 + aurora/models/change.py | 79 ++ aurora/models/moderation.py | 576 +++++++++ aurora/models/moderation_types.py | 964 ++++++++++++++ aurora/models/partials.py | 90 ++ aurora/models/type.py | 98 ++ aurora/utilities/config.py | 10 + aurora/utilities/factory.py | 553 ++++----- aurora/utilities/json.py | 108 ++ aurora/utilities/utils.py | 332 +++-- 19 files changed, 3219 insertions(+), 1973 deletions(-) create mode 100644 aurora/menus/types.py create mode 100644 aurora/models/base.py create mode 100644 aurora/models/change.py create mode 100644 aurora/models/moderation.py create mode 100644 aurora/models/moderation_types.py create mode 100644 aurora/models/partials.py create mode 100644 aurora/models/type.py create mode 100644 aurora/utilities/json.py diff --git a/aurora/aurora.py b/aurora/aurora.py index 131d2bd..2cfd78a 100644 --- a/aurora/aurora.py +++ b/aurora/aurora.py @@ -6,32 +6,38 @@ # |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_| import json +import logging as py_logging import os -import sqlite3 import time from datetime import datetime, timedelta, timezone from math import ceil +from typing import List, Union import discord -from discord import Object +from class_registry.registry import RegistryKeyError +from dateutil.parser import ParserError, parse from discord.ext import tasks from redbot.core import app_commands, commands, data_manager from redbot.core.app_commands import Choice from redbot.core.bot import Red from redbot.core.commands.converter import parse_relativedelta, parse_timedelta -from redbot.core.utils.chat_formatting import box, error, humanize_list, humanize_timedelta, warning +from redbot.core.utils.chat_formatting import bold, box, error, humanize_list, humanize_timedelta, warning -from aurora.importers.aurora import ImportAuroraView -from aurora.importers.galacticbot import ImportGalacticBotView -from aurora.menus.addrole import Addrole -from aurora.menus.guild import Guild -from aurora.menus.immune import Immune -from aurora.menus.overrides import Overrides -from aurora.utilities.config import config, register_config -from aurora.utilities.database import connect, create_guild_table, fetch_case, mysql_log -from aurora.utilities.factory import addrole_embed, case_factory, changes_factory, evidenceformat_factory, guild_embed, immune_embed, message_factory, overrides_embed -from aurora.utilities.logger import logger -from aurora.utilities.utils import check_moddable, check_permissions, convert_timedelta_to_str, fetch_channel_dict, fetch_user_dict, generate_dict, get_footer_image, log, send_evidenceformat, timedelta_from_relativedelta +from .importers.aurora import ImportAuroraView +from .importers.galacticbot import ImportGalacticBotView +from .menus.addrole import Addrole +from .menus.guild import Guild +from .menus.immune import Immune +from .menus.overrides import Overrides +from .menus.types import Types +from .models.change import Change +from .models.moderation import Moderation +from .models.type import Type, type_registry +from .utilities.config import config, register_config +from .utilities.factory import addrole_embed, case_factory, changes_factory, evidenceformat_factory, guild_embed, immune_embed, overrides_embed, type_embed +from .utilities.json import dump +from .utilities.logger import logger +from .utilities.utils import check_moddable, check_permissions, create_guild_table, log, timedelta_from_relativedelta, timedelta_to_string class Aurora(commands.Cog): @@ -39,29 +45,24 @@ class Aurora(commands.Cog): It is heavily inspired by GalacticBot, and is designed to be a more user-friendly alternative to Red's core Mod cogs. This cog stores all of its data in an SQLite database.""" - __author__ = ["cswimr"] - __version__ = "2.1.3" + __author__ = ["[cswimr](https://www.coastalcommits.com/cswimr)"] + __version__ = "3.0.0-indev27" + __git__ = "https://www.coastalcommits.com/cswimr/SeaCogs" __documentation__ = "https://seacogs.coastalcommits.com/aurora/" async def red_delete_data_for_user(self, *, requester, user_id: int): if requester == "discord_deleted_user": await config.user_from_id(user_id).clear() - database = connect() - cursor = database.cursor() - - cursor.execute("SHOW TABLES;") - tables = [table[0] for table in cursor.fetchall()] + results = await Moderation.execute(query="SHOW TABLES;", return_obj=False) + tables = [table[0] for table in results] condition = "target_id = %s OR moderator_id = %s;" for table in tables: delete_query = f"DELETE FROM {table[0]} WHERE {condition}" - cursor.execute(delete_query, (user_id, user_id)) + await Moderation.execute(query=delete_query, parameters=(user_id, user_id), return_obj=False) - database.commit() - cursor.close() - database.close() if requester == "owner": await config.user_from_id(user_id).clear() if requester == "user": @@ -69,24 +70,29 @@ class Aurora(commands.Cog): if requester == "user_strict": await config.user_from_id(user_id).clear() else: - logger.warning( - "Invalid requester passed to red_delete_data_for_user: %s", requester - ) + logger.warning("Invalid requester passed to red_delete_data_for_user: %s", requester) - def __init__(self, bot: Red): + def __init__(self, bot: Red) -> None: super().__init__() self.bot = bot + self.type_registry = type_registry register_config(config) self.handle_expiry.start() + # If we don't override aiosqlite's logging level, it will spam the console with dozens of debug messages per query. + # This is unnecessary because Aurora already logs all of its SQL queries (or at least, most of them), + # and the information that aiosqlite logs is not useful to the bot owner. + # This is a bad solution though as it overrides it for any other cogs that are using aiosqlite too. + # If there's a better solution that you're aware of, please let me know in Discord or in a CoastalCommits issue. + py_logging.getLogger("aiosqlite").setLevel(py_logging.INFO) def format_help_for_context(self, ctx: commands.Context) -> str: pre_processed = super().format_help_for_context(ctx) or "" n = "\n" if "\n\n" not in pre_processed else "" text = [ f"{pre_processed}{n}", - f"Cog Version: **{self.__version__}**", - f"Author: {humanize_list(self.__author__)}", - f"Documentation: {self.__documentation__}", + f"{bold('Cog Version:')} [{self.__version__}]({self.__git__})", + f"{bold('Author:')} {humanize_list(self.__author__)}", + f"{bold('Documentation:')} {self.__documentation__}", ] return "\n".join(text) @@ -105,8 +111,37 @@ class Aurora(commands.Cog): async def cog_unload(self): self.handle_expiry.cancel() + @staticmethod + async def moderate(ctx: Union[commands.Context, discord.Interaction], target: discord.Member | discord.User | discord.abc.Messageable, permissions: List[str], moderation_type: Type | str, silent: bool | None = None, **kwargs) -> None | Type: + """This function is used to moderate users. + It checks if the target can be moderated, then calls the handler method of the moderation type specified. + + Args: + ctx (Union[commands.Context, discord.Interaction]): The context of the command. If this is a `discord.Interaction` object, it will be converted to a `commands.Context` object. Additionally, if the interaction originated from a context menu the `ctx.author` attribute will be overridden to `interaction.user`. + target (discord.Member, discord.User, discord.abc.Messageable): The target user or channel to moderate. + permissions (List[str]): The permissions required to moderate the target. + moderation_type (Type): The moderation type (handler) to use. See `aurora.models.moderation_types` for some examples. + silent (bool, optional): Whether or not to message the target. Defaults to None. + **kwargs: The keyword arguments to pass to the handler method. + """ + if isinstance(moderation_type, str): + moderation_type = type_registry[str.lower(moderation_type)] + if isinstance(ctx, discord.Interaction): + interaction = ctx + ctx = await commands.Context.from_interaction(interaction) + if isinstance(interaction.command, app_commands.ContextMenu): + ctx.author = interaction.user + if not await check_moddable(target=target, ctx=ctx, permissions=permissions, moderation_type=moderation_type): + return + if silent is None: + dm_users = await config.custom("types", ctx.guild.id, moderation_type.key).dm_users() + if dm_users is None: + dm_users = await config.guild(ctx.guild).dm_users() + silent = not dm_users + return await moderation_type.handler(ctx=ctx, target=target, silent=silent, **kwargs) + @commands.Cog.listener("on_guild_join") - async def db_generate_guild_join(self, guild: discord.Guild): + async def db_generate_on_guild_join(self, guild: discord.Guild): """This method prepares the database schema whenever the bot joins a guild.""" if not await self.bot.cog_disabled_in_guild(self, guild): try: @@ -119,69 +154,66 @@ class Aurora(commands.Cog): """This method automatically adds roles to users when they join the server.""" if not await self.bot.cog_disabled_in_guild(self, member.guild): query = f"""SELECT moderation_id, role_id, reason FROM moderation_{member.guild.id} WHERE target_id = ? AND moderation_type = 'ADDROLE' AND expired = 0 AND resolved = 0;""" - database = connect() - cursor = database.cursor() - cursor.execute(query, (member.id,)) - results = cursor.fetchall() - for result in results: - role = member.guild.get_role(result[1]) - reason = result[2] - await member.add_roles(role, reason=f"Role automatically added on member rejoin for: {reason} (Case #{result[0]:,})") + results = await Moderation.execute(query, (member.id,)) + for row in results: + role = member.guild.get_role(row[1]) + reason = row[2] + await member.add_roles(role, reason=f"Role automatically added on member rejoin for: {reason} (Case #{row[0]:,})") @commands.Cog.listener("on_audit_log_entry_create") async def autologger(self, entry: discord.AuditLogEntry): """This method automatically logs moderations done by users manually ("right clicks").""" - if not await self.bot.cog_disabled_in_guild(self, entry.guild): - if await config.guild(entry.guild).ignore_other_bots() is True: - if entry.user.bot or entry.target.bot: - return - else: - if entry.user.id == self.bot.user.id: - return - - duration = "NULL" - - if entry.reason: - reason = entry.reason + " (This action was performed without the bot.)" - - else: - reason = "This action was performed without the bot." - - if entry.action == discord.AuditLogAction.kick: - moderation_type = "KICK" - - elif entry.action == discord.AuditLogAction.ban: - moderation_type = "BAN" - - elif entry.action == discord.AuditLogAction.unban: - moderation_type = "UNBAN" - - elif entry.action == discord.AuditLogAction.member_update: - if entry.after.timed_out_until is not None: - timed_out_until_aware = entry.after.timed_out_until.replace( - tzinfo=timezone.utc - ) - duration_datetime = timed_out_until_aware - datetime.now( - tz=timezone.utc - ) - minutes = round(duration_datetime.total_seconds() / 60) - duration = timedelta(minutes=minutes) - moderation_type = "MUTE" + try: + if not await self.bot.cog_disabled_in_guild(self, entry.guild): + if await config.guild(entry.guild).ignore_other_bots() is True: + if entry.user.bot or entry.target.bot: + return else: - moderation_type = "UNMUTE" - else: - return + if entry.user.id == self.bot.user.id: + return - await mysql_log( - entry.guild.id, - entry.user.id, - moderation_type, - "USER", - entry.target.id, - 0, - duration, - reason, - ) + duration = None + + if entry.reason: + reason = entry.reason + " (This action was performed without the bot.)" + + else: + reason = "This action was performed without the bot." + + if entry.action == discord.AuditLogAction.kick: + moderation_type = type_registry["kick"] + + elif entry.action == discord.AuditLogAction.ban: + moderation_type = type_registry["ban"] + + elif entry.action == discord.AuditLogAction.unban: + moderation_type = type_registry["unban"] + + elif entry.action == discord.AuditLogAction.member_update: + if entry.after.timed_out_until is not None: + timed_out_until_aware = entry.after.timed_out_until.replace(tzinfo=timezone.utc) + duration_datetime = timed_out_until_aware - datetime.now(tz=timezone.utc) + minutes = round(duration_datetime.total_seconds() / 60) + duration = timedelta(minutes=minutes) + moderation_type = type_registry["mute"] + else: + moderation_type = type_registry["unmute"] + else: + return + + await Moderation.log( + bot=self.bot, + guild_id=entry.guild.id, + moderator_id=entry.user.id, + moderation_type=moderation_type, + target_type="USER", + target_id=entry.target.id, + role_id=None, + duration=duration, + reason=reason, + ) + except AttributeError: + return ####################################################################################################################### ### COMMANDS @@ -193,7 +225,7 @@ class Aurora(commands.Cog): interaction: discord.Interaction, target: discord.User, reason: str, - silent: bool = None, + silent: bool | None = None, ): """Add a note to a user. @@ -205,54 +237,22 @@ class Aurora(commands.Cog): Why are you noting this user? silent: bool Should the user be messaged?""" - if not await check_moddable(target, interaction, ["moderate_members"]): - return - - await interaction.response.send_message( - content=f"{target.mention} has recieved a note!\n**Reason** - `{reason}`" + await self.moderate( + ctx=interaction, + target=target, + silent=silent, + permissions=["moderate_members"], + moderation_type=type_registry["note"], + reason=reason, ) - if silent is None: - silent = not await config.guild(interaction.guild).dm_users() - if silent is False: - try: - embed = await message_factory( - await self.bot.get_embed_color(interaction.channel), - guild=interaction.guild, - moderator=interaction.user, - reason=reason, - moderation_type="note", - response=await interaction.original_response(), - ) - await target.send(embed=embed, file=get_footer_image(self)) - except discord.errors.HTTPException: - pass - - moderation_id = await mysql_log( - interaction.guild.id, - interaction.user.id, - "NOTE", - "USER", - target.id, - 0, - "NULL", - reason, - ) - await interaction.edit_original_response( - content=f"{target.mention} has received a note! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`" - ) - await log(interaction, moderation_id) - - case = await fetch_case(moderation_id, interaction.guild.id) - await send_evidenceformat(interaction, case) - @app_commands.command(name="warn") async def warn( self, interaction: discord.Interaction, target: discord.Member, reason: str, - silent: bool = None, + silent: bool | None = None, ): """Warn a user. @@ -264,47 +264,15 @@ class Aurora(commands.Cog): Why are you warning this user? silent: bool Should the user be messaged?""" - if not await check_moddable(target, interaction, ["moderate_members"]): - return - - await interaction.response.send_message( - content=f"{target.mention} has been warned!\n**Reason** - `{reason}`" + await self.moderate( + ctx=interaction, + target=target, + silent=silent, + permissions=["moderate_members"], + moderation_type=type_registry["warn"], + reason=reason, ) - if silent is None: - silent = not await config.guild(interaction.guild).dm_users() - if silent is False: - try: - embed = await message_factory( - await self.bot.get_embed_color(interaction.channel), - guild=interaction.guild, - moderator=interaction.user, - reason=reason, - moderation_type="warned", - response=await interaction.original_response(), - ) - await target.send(embed=embed, file=get_footer_image(self)) - except discord.errors.HTTPException: - pass - - moderation_id = await mysql_log( - interaction.guild.id, - interaction.user.id, - "WARN", - "USER", - target.id, - 0, - "NULL", - reason, - ) - await interaction.edit_original_response( - content=f"{target.mention} has been warned! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`" - ) - await log(interaction, moderation_id) - - case = await fetch_case(moderation_id, interaction.guild.id) - await send_evidenceformat(interaction, case) - @app_commands.command(name="addrole") async def addrole( self, @@ -312,8 +280,8 @@ class Aurora(commands.Cog): target: discord.Member, role: discord.Role, reason: str, - duration: str = None, - silent: bool = None, + duration: str | None = None, + silent: bool | None = None, ): """Add a role to a user. @@ -329,87 +297,7 @@ class Aurora(commands.Cog): How long are you adding this role for? silent: bool Should the user be messaged?""" - addrole_whitelist = await config.guild(interaction.guild).addrole_whitelist() - - if not addrole_whitelist: - await interaction.response.send_message( - content=error("There are no whitelisted roles set for this server!"), - ephemeral=True, - ) - return - - if duration is not None: - parsed_time = parse_timedelta(duration) - if parsed_time is None: - await interaction.response.send_message( - content=error("Please provide a valid duration!"), ephemeral=True - ) - return - else: - parsed_time = "NULL" - - if role.id not in addrole_whitelist: - await interaction.response.send_message( - content=error("That role isn't whitelisted!"), ephemeral=True - ) - return - - if not await check_moddable( - target, interaction, ["moderate_members", "manage_roles"] - ): - return - - if role.id in [user_role.id for user_role in target.roles]: - await interaction.response.send_message( - content=error(f"{target.mention} already has this role!"), - ephemeral=True, - ) - return - - await interaction.response.defer() - if silent is None: - silent = not await config.guild(interaction.guild).dm_users() - if silent is False: - try: - embed = await message_factory( - await self.bot.get_embed_color(interaction.channel), - guild=interaction.guild, - moderator=interaction.user, - reason=reason, - moderation_type="addrole", - response=await interaction.original_response(), - duration=parsed_time, - role=role, - ) - await target.send(embed=embed, file=get_footer_image(self)) - except discord.errors.HTTPException: - pass - - await target.add_roles( - role, - reason=f"Role added by {interaction.user.id}{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''} for: {reason}", - ) - response: discord.WebhookMessage = await interaction.followup.send( - content=f"{target.mention} has been given the {role.mention} role{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''}!\n**Reason** - `{reason}`" - ) - - moderation_id = await mysql_log( - interaction.guild.id, - interaction.user.id, - "ADDROLE", - "USER", - target.id, - role.id, - parsed_time, - reason, - ) - await response.edit( - content=f"{target.mention} has been given the {role.mention} role{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''}! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`", - ) - await log(interaction, moderation_id) - - case = await fetch_case(moderation_id, interaction.guild.id) - await send_evidenceformat(interaction, case) + await self.moderate(ctx=interaction, target=target, silent=silent, permissions=["moderate_members", "manage_roles"], moderation_type=type_registry["addrole"], reason=reason, role=role, duration=duration) @app_commands.command(name="removerole") async def removerole( @@ -418,8 +306,8 @@ class Aurora(commands.Cog): target: discord.Member, role: discord.Role, reason: str, - duration: str = None, - silent: bool = None, + duration: str | None = None, + silent: bool | None = None, ): """Remove a role from a user. @@ -435,87 +323,7 @@ class Aurora(commands.Cog): How long are you removing this role for? silent: bool Should the user be messaged?""" - addrole_whitelist = await config.guild(interaction.guild).addrole_whitelist() - - if not addrole_whitelist: - await interaction.response.send_message( - content=error("There are no whitelisted roles set for this server!"), - ephemeral=True, - ) - return - - if duration is not None: - parsed_time = parse_timedelta(duration) - if parsed_time is None: - await interaction.response.send_message( - content=error("Please provide a valid duration!"), ephemeral=True - ) - return - else: - parsed_time = "NULL" - - if role.id not in addrole_whitelist: - await interaction.response.send_message( - content=error("That role isn't whitelisted!"), ephemeral=True - ) - return - - if not await check_moddable( - target, interaction, ["moderate_members", "manage_roles"] - ): - return - - if role.id not in [user_role.id for user_role in target.roles]: - await interaction.response.send_message( - content=error(f"{target.mention} does not have this role!"), - ephemeral=True, - ) - return - - await interaction.response.defer() - if silent is None: - silent = not await config.guild(interaction.guild).dm_users() - if silent is False: - try: - embed = await message_factory( - await self.bot.get_embed_color(interaction.channel), - guild=interaction.guild, - moderator=interaction.user, - reason=reason, - moderation_type="removerole", - response=await interaction.original_response(), - duration=parsed_time, - role=role, - ) - await target.send(embed=embed, file=get_footer_image(self)) - except discord.errors.HTTPException: - pass - - await target.remove_roles( - role, - reason=f"Role removed by {interaction.user.id}{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''} for: {reason}", - ) - response: discord.WebhookMessage = await interaction.followup.send( - content=f"{target.mention} has had the {role.mention} role removed{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''}!\n**Reason** - `{reason}`" - ) - - moderation_id = await mysql_log( - interaction.guild.id, - interaction.user.id, - "REMOVEROLE", - "USER", - target.id, - role.id, - parsed_time, - reason, - ) - await response.edit( - content=f"{target.mention} has had the {role.mention} role removed{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time != 'NULL' else ''}! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`", - ) - await log(interaction, moderation_id) - - case = await fetch_case(moderation_id, interaction.guild.id) - await send_evidenceformat(interaction, case) + await self.moderate(ctx=interaction, target=target, silent=silent, permissions=["moderate_members", "manage_roles"], moderation_type=type_registry["removerole"], reason=reason, role=role, duration=duration) @app_commands.command(name="mute") async def mute( @@ -524,7 +332,7 @@ class Aurora(commands.Cog): target: discord.Member, duration: str, reason: str, - silent: bool = None, + silent: bool | None = None, ): """Mute a user. @@ -538,80 +346,23 @@ class Aurora(commands.Cog): Why are you unbanning this user? silent: bool Should the user be messaged?""" - if not await check_moddable(target, interaction, ["moderate_members"]): - return - - if target.is_timed_out() is True: - await interaction.response.send_message( - error(f"{target.mention} is already muted!"), - allowed_mentions=discord.AllowedMentions(users=False), - ephemeral=True, - ) - return - - try: - parsed_time = parse_timedelta(duration, maximum=timedelta(days=28)) - if parsed_time is None: - await interaction.response.send_message( - error("Please provide a valid duration!"), ephemeral=True - ) - return - except commands.BadArgument: - await interaction.response.send_message( - error("Please provide a duration that is less than 28 days."), ephemeral=True - ) - return - - await target.timeout( - parsed_time, reason=f"Muted by {interaction.user.id} for: {reason}" + await self.moderate( + ctx=interaction, + target=target, + silent=silent, + permissions=["moderate_members"], + moderation_type=type_registry["mute"], + duration=duration, + reason=reason, ) - await interaction.response.send_message( - content=f"{target.mention} has been muted for {humanize_timedelta(timedelta=parsed_time)}!\n**Reason** - `{reason}`" - ) - - if silent is None: - silent = not await config.guild(interaction.guild).dm_users() - if silent is False: - try: - embed = await message_factory( - await self.bot.get_embed_color(interaction.channel), - guild=interaction.guild, - moderator=interaction.user, - reason=reason, - moderation_type="muted", - response=await interaction.original_response(), - duration=parsed_time, - ) - await target.send(embed=embed, file=get_footer_image(self)) - except discord.errors.HTTPException: - pass - - moderation_id = await mysql_log( - interaction.guild.id, - interaction.user.id, - "MUTE", - "USER", - target.id, - 0, - parsed_time, - reason, - ) - await interaction.edit_original_response( - content=f"{target.mention} has been muted for {humanize_timedelta(timedelta=parsed_time)}! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`" - ) - await log(interaction, moderation_id) - - case = await fetch_case(moderation_id, interaction.guild.id) - await send_evidenceformat(interaction, case) - @app_commands.command(name="unmute") async def unmute( self, interaction: discord.Interaction, target: discord.Member, - reason: str = None, - silent: bool = None, + reason: str | None = None, + silent: bool | None = None, ): """Unmute a user. @@ -623,70 +374,22 @@ class Aurora(commands.Cog): Why are you unmuting this user? silent: bool Should the user be messaged?""" - if not await check_moddable(target, interaction, ["moderate_members"]): - return - - if target.is_timed_out() is False: - await interaction.response.send_message( - error(f"{target.mention} is not muted!"), - allowed_mentions=discord.AllowedMentions(users=False), - ephemeral=True, - ) - return - - if reason: - await target.timeout( - None, reason=f"Unmuted by {interaction.user.id} for: {reason}" - ) - else: - await target.timeout(None, reason=f"Unbanned by {interaction.user.id}") - reason = "No reason given." - - await interaction.response.send_message( - content=f"{target.mention} has been unmuted!\n**Reason** - `{reason}`" + await self.moderate( + ctx=interaction, + target=target, + silent=silent, + permissions=["moderate_members"], + moderation_type=type_registry["unmute"], + reason=reason, ) - if silent is None: - silent = not await config.guild(interaction.guild).dm_users() - if silent is False: - try: - embed = await message_factory( - await self.bot.get_embed_color(interaction.channel), - guild=interaction.guild, - moderator=interaction.user, - reason=reason, - moderation_type="unmuted", - response=await interaction.original_response(), - ) - await target.send(embed=embed, file=get_footer_image(self)) - except discord.errors.HTTPException: - pass - - moderation_id = await mysql_log( - interaction.guild.id, - interaction.user.id, - "UNMUTE", - "USER", - target.id, - 0, - "NULL", - reason, - ) - await interaction.edit_original_response( - content=f"{target.mention} has been unmuted! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`" - ) - await log(interaction, moderation_id) - - case = await fetch_case(moderation_id, interaction.guild.id) - await send_evidenceformat(interaction, case) - @app_commands.command(name="kick") async def kick( self, interaction: discord.Interaction, target: discord.Member, reason: str, - silent: bool = None, + silent: bool | None = None, ): """Kick a user. @@ -698,49 +401,15 @@ class Aurora(commands.Cog): Why are you kicking this user? silent: bool Should the user be messaged?""" - if not await check_moddable(target, interaction, ["kick_members"]): - return - - await interaction.response.send_message( - content=f"{target.mention} has been kicked!\n**Reason** - `{reason}`" + await self.moderate( + ctx=interaction, + target=target, + silent=silent, + permissions=["kick_members"], + moderation_type=type_registry["kick"], + reason=reason, ) - if silent is None: - silent = not await config.guild(interaction.guild).dm_users() - if silent is False: - try: - embed = await message_factory( - await self.bot.get_embed_color(interaction.channel), - guild=interaction.guild, - moderator=interaction.user, - reason=reason, - moderation_type="kicked", - response=await interaction.original_response(), - ) - await target.send(embed=embed, file=get_footer_image(self)) - except discord.errors.HTTPException: - pass - - await target.kick(reason=f"Kicked by {interaction.user.id} for: {reason}") - - moderation_id = await mysql_log( - interaction.guild.id, - interaction.user.id, - "KICK", - "USER", - target.id, - 0, - "NULL", - reason, - ) - await interaction.edit_original_response( - content=f"{target.mention} has been kicked! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`" - ) - await log(interaction, moderation_id) - - case = await fetch_case(moderation_id, interaction.guild.id) - await send_evidenceformat(interaction, case) - @app_commands.command(name="ban") @app_commands.choices( delete_messages=[ @@ -757,9 +426,9 @@ class Aurora(commands.Cog): interaction: discord.Interaction, target: discord.User, reason: str, - duration: str = None, - delete_messages: Choice[int] = None, - silent: bool = None, + duration: str | None = None, + delete_messages: Choice[int] | None = None, + silent: bool | None = None, ): """Ban a user. @@ -775,131 +444,35 @@ class Aurora(commands.Cog): How many days of messages to delete? silent: bool Should the user be messaged?""" - if not await check_moddable(target, interaction, ["ban_members"]): - return - - if delete_messages is None: - delete_messages_seconds = 0 - else: - delete_messages_seconds = delete_messages.value - - try: - await interaction.guild.fetch_ban(target) - await interaction.response.send_message( - content=error(f"{target.mention} is already banned!"), ephemeral=True - ) - return - except discord.errors.NotFound: - pass - if duration: - parsed_time = parse_relativedelta(duration) - if parsed_time is None: - await interaction.response.send_message( - content=error("Please provide a valid duration!"), ephemeral=True - ) - return - try: - parsed_time = timedelta_from_relativedelta(parsed_time) - except ValueError: - await interaction.response.send_message( - content=error("Please provide a valid duration!"), ephemeral=True - ) - return - - await interaction.response.send_message( - content=f"{target.mention} has been banned for {humanize_timedelta(timedelta=parsed_time)}!\n**Reason** - `{reason}`" + await self.moderate( + ctx=interaction, + target=target, + silent=silent, + permissions=["ban_members"], + moderation_type=type_registry["tempban"], + reason=reason, + duration=duration, + delete_messages=delete_messages, ) - - try: - embed = await message_factory( - await self.bot.get_embed_color(interaction.channel), - guild=interaction.guild, - moderator=interaction.user, - reason=reason, - moderation_type="tempbanned", - response=await interaction.original_response(), - duration=parsed_time, - ) - await target.send(embed=embed, file=get_footer_image(self)) - except discord.errors.HTTPException: - pass - - await interaction.guild.ban( - target, - reason=f"Tempbanned by {interaction.user.id} for: {reason} (Duration: {parsed_time})", - delete_message_seconds=delete_messages_seconds, - ) - - moderation_id = await mysql_log( - interaction.guild.id, - interaction.user.id, - "TEMPBAN", - "USER", - target.id, - 0, - parsed_time, - reason, - ) - await interaction.edit_original_response( - content=f"{target.mention} has been banned for {humanize_timedelta(timedelta=parsed_time)}! (Case `#{moderation_id}`)\n**Reason** - `{reason}`" - ) - await log(interaction, moderation_id) - - case = await fetch_case(moderation_id, interaction.guild.id) - await send_evidenceformat(interaction, case) else: - await interaction.response.send_message( - content=f"{target.mention} has been banned!\n**Reason** - `{reason}`" + await self.moderate( + ctx=interaction, + target=target, + silent=silent, + permissions=["ban_members"], + moderation_type=type_registry["ban"], + reason=reason, + delete_messages=delete_messages, ) - if silent is None: - silent = not await config.guild(interaction.guild).dm_users() - if silent is False: - try: - embed = embed = await message_factory( - await self.bot.get_embed_color(interaction.channel), - guild=interaction.guild, - moderator=interaction.user, - reason=reason, - moderation_type="banned", - response=await interaction.original_response(), - ) - await target.send(embed=embed, file=get_footer_image(self)) - except discord.errors.HTTPException: - pass - - await interaction.guild.ban( - target, - reason=f"Banned by {interaction.user.id} for: {reason}", - delete_message_seconds=delete_messages_seconds, - ) - - moderation_id = await mysql_log( - interaction.guild.id, - interaction.user.id, - "BAN", - "USER", - target.id, - 0, - "NULL", - reason, - ) - await interaction.edit_original_response( - content=f"{target.mention} has been banned! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`" - ) - await log(interaction, moderation_id) - - case = await fetch_case(moderation_id, interaction.guild.id) - await send_evidenceformat(interaction, case) - @app_commands.command(name="unban") async def unban( self, interaction: discord.Interaction, target: discord.User, - reason: str = None, - silent: bool = None, + reason: str | None = None, + silent: bool | None = None, ): """Unban a user. @@ -911,75 +484,61 @@ class Aurora(commands.Cog): Why are you unbanning this user? silent: bool Should the user be messaged?""" - if not await check_moddable(target, interaction, ["ban_members"]): - return - - try: - await interaction.guild.fetch_ban(target) - except discord.errors.NotFound: - await interaction.response.send_message( - content=error(f"{target.mention} is not banned!"), ephemeral=True - ) - return - - if reason: - await interaction.guild.unban( - target, reason=f"Unbanned by {interaction.user.id} for: {reason}" - ) - else: - await interaction.guild.unban( - target, reason=f"Unbanned by {interaction.user.id}" - ) - reason = "No reason given." - - await interaction.response.send_message( - content=f"{target.mention} has been unbanned!\n**Reason** - `{reason}`" + await self.moderate( + ctx=interaction, + target=target, + silent=silent, + permissions=["ban_members"], + moderation_type=type_registry["unban"], + reason=reason, ) - if silent is None: - silent = not await config.guild(interaction.guild).dm_users() - if silent is False: - try: - embed = await message_factory( - await self.bot.get_embed_color(interaction.channel), - guild=interaction.guild, - moderator=interaction.user, - reason=reason, - moderation_type="unbanned", - response=await interaction.original_response(), - ) - await target.send(embed=embed, file=get_footer_image(self)) - except discord.errors.HTTPException: - pass + @app_commands.command(name="slowmode") + async def slowmode( + self, + interaction: discord.Interaction, + interval: int, + channel: discord.TextChannel | None = None, + reason: str | None = None, + ): + """Set the slowmode of a channel. - moderation_id = await mysql_log( - interaction.guild.id, - interaction.user.id, - "UNBAN", - "USER", - target.id, - 0, - "NULL", - reason, - ) - await interaction.edit_original_response( - content=f"{target.mention} has been unbanned! (Case `#{moderation_id:,}`)\n**Reason** - `{reason}`" - ) - await log(interaction, moderation_id) + Parameters + ----------- + interval: int + The slowmode interval in seconds + channel: discord.TextChannel + The channel to set the slowmode in + reason: str + Why are you setting the slowmode?""" + if channel is None: + channel = interaction.channel - case = await fetch_case(moderation_id, interaction.guild.id) - await send_evidenceformat(interaction, case) + await self.moderate( + ctx=interaction, + target=channel, + silent=True, + permissions=["manage_channel"], + moderation_type=type_registry["slowmode"], + interval=interval, + reason=reason, + ) @app_commands.command(name="history") async def history( self, interaction: discord.Interaction, - target: discord.User = None, - moderator: discord.User = None, - pagesize: app_commands.Range[int, 1, 20] = None, + target: discord.User | None = None, + moderator: discord.User | None = None, + pagesize: app_commands.Range[int, 1, 20] | None = None, page: int = 1, - ephemeral: bool = None, - inline: bool = None, + on: str | None = None, + before: str | None = None, + after: str | None = None, + expired: bool | None = None, + types: str | None = None, + ephemeral: bool | None = None, + inline: bool | None = None, export: bool = False, ): """List previous infractions. @@ -994,222 +553,195 @@ class Aurora(commands.Cog): Amount of infractions to list per page page: int Page to select + on: str + List infractions on a certain date + before: str + List infractions before a certain date + after: str + List infractions after a certain date + expired: bool + List expired or unexpired infractions + types: str + List infractions of specific types, comma separated ephemeral: bool Hide the command response inline: bool Display infractions in a grid arrangement (does not look very good) export: bool - Exports the server's entire moderation history to a JSON file""" + Exports the server's moderation history to a JSON file""" if ephemeral is None: - ephemeral = ( - await config.user(interaction.user).history_ephemeral() - or await config.guild(interaction.guild).history_ephemeral() - or False - ) + ephemeral = await config.user(interaction.user).history_ephemeral() or await config.guild(interaction.guild).history_ephemeral() or False if inline is None: - inline = ( - await config.user(interaction.user).history_inline() - or await config.guild(interaction.guild).history_inline() - or False - ) + inline = await config.user(interaction.user).history_inline() or await config.guild(interaction.guild).history_inline() or False if pagesize is None: if inline is True: - pagesize = ( - await config.user(interaction.user).history_inline_pagesize() - or await config.guild(interaction.guild).history_inline_pagesize() - or 6 - ) + pagesize = await config.user(interaction.user).history_inline_pagesize() or await config.guild(interaction.guild).history_inline_pagesize() or 6 else: - pagesize = ( - await config.user(interaction.user).history_pagesize() - or await config.guild(interaction.guild).history_pagesize() - or 5 - ) + pagesize = await config.user(interaction.user).history_pagesize() or await config.guild(interaction.guild).history_pagesize() or 5 + + if before and not on: + try: + before = parse(before) + except (ParserError, OverflowError) as e: + if isinstance(e, ParserError): + await interaction.response.send_message(content=error("Invalid date format for `before` parameter!"), ephemeral=True) + return + if isinstance(e, OverflowError): + await interaction.response.send_message(content=error("Date is too far in the future!"), ephemeral=True) + return + + if after and not on: + try: + after = parse(after) + except (ParserError, OverflowError) as e: + if isinstance(e, ParserError): + await interaction.response.send_message(content=error("Invalid date format for `after` parameter!"), ephemeral=True) + return + if isinstance(e, OverflowError): + await interaction.response.send_message(content=error("Date is too far in the future!"), ephemeral=True) + return + + if on: + try: + on = parse(on) + except (ParserError, OverflowError) as e: + if isinstance(e, ParserError): + await interaction.response.send_message(content=error("Invalid date format for `on` parameter!"), ephemeral=True) + return + if isinstance(e, OverflowError): + await interaction.response.send_message(content=error("Date is too far in the future!"), ephemeral=True) + return + + before = datetime.combine(on, datetime.max.time()) + after = datetime.combine(on, datetime.min.time()) await interaction.response.defer(ephemeral=ephemeral) - permissions = check_permissions( - interaction.client.user, ["embed_links"], interaction - ) + permissions = check_permissions(interaction.client.user, ["embed_links"], interaction) if permissions: await interaction.followup.send( - error( - f"I do not have the `{permissions}` permission, required for this action." - ), + error(f"I do not have the `{permissions}` permission, required for this action."), ephemeral=True, ) return - database = connect() + if export and not types: + types = "all" - if export: - database.row_factory = sqlite3.Row - cursor = database.cursor() - - query = f"""SELECT * - FROM moderation_{interaction.guild.id} - ORDER BY moderation_id DESC;""" - cursor.execute(query) - - results = cursor.fetchall() - - cases = [] - for result in results: - case = dict(result) - cases.append(case) - - try: - filename = ( - str(data_manager.cog_data_path(cog_instance=self)) - + str(os.sep) - + f"moderation_{interaction.guild.id}.json" - ) - - with open(filename, "w", encoding="utf-8") as f: - json.dump(cases, f, indent=2) - - await interaction.followup.send( - file=discord.File( - filename, f"moderation_{interaction.guild.id}.json" - ), - ephemeral=ephemeral, - ) - - os.remove(filename) - except json.JSONDecodeError as e: - await interaction.followup.send( - content=error( - "An error occured while exporting the moderation history.\nError:\n" - ) - + box(e, "py"), - ephemeral=ephemeral, - ) - cursor.close() - database.close() - return - - cursor = database.cursor() + type_list = [] + registry_values = type_registry.values() + if types: + for t in types.split(","): + stripped = t.strip().lower() + if stripped == "all": + type_list.clear() + type_list.extend((t for t in registry_values)) + break + try: + type_list.append(type_registry[stripped]) + except RegistryKeyError: + continue + else: + for t in registry_values: + if await config.custom("types", interaction.guild.id, t.key).show_in_history() is True: + type_list.append(t) if target: - query = f"""SELECT * - FROM moderation_{interaction.guild.id} - WHERE target_id = ? - ORDER BY moderation_id DESC;""" - cursor.execute(query, (target.id,)) + filename = f"moderation_target_{str(target.id)}_{str(interaction.guild.id)}.json" + moderations = await Moderation.find_by_target(bot=interaction.client, guild_id=interaction.guild.id, target=target.id, before=before, after=after, types=type_list, expired=expired) elif moderator: - query = f"""SELECT * - FROM moderation_{interaction.guild.id} - WHERE moderator_id = ? - ORDER BY moderation_id DESC;""" - cursor.execute(query, (moderator.id,)) + filename = f"moderation_moderator_{str(moderator.id)}_{str(interaction.guild.id)}.json" + moderations = await Moderation.find_by_moderator(bot=interaction.client, guild_id=interaction.guild.id, moderator=moderator.id, before=before, after=after, types=type_list, expired=expired) else: - query = f"""SELECT * - FROM moderation_{interaction.guild.id} - ORDER BY moderation_id DESC;""" - cursor.execute(query) + filename = f"moderation_{str(interaction.guild.id)}.json" + moderations = await Moderation.get_latest(bot=interaction.client, guild_id=interaction.guild.id, before=before, after=after, types=type_list, expired=expired) - results = cursor.fetchall() - result_dict_list = [] + if export: + try: + filepath = str(data_manager.cog_data_path(cog_instance=self)) + str(os.sep) + filename - for result in results: - case_dict = generate_dict(result) - if case_dict["moderation_id"] == 0: - continue - result_dict_list.append(case_dict) + with open(filepath, "w", encoding="utf-8") as f: + dump(obj=moderations, fp=f) - case_quantity = len(result_dict_list) + await interaction.followup.send( + file=discord.File(fp=filepath, filename=filename), + ephemeral=ephemeral, + ) + + os.remove(filepath) + except json.JSONDecodeError as e: + await interaction.followup.send( + content=error("An error occurred while exporting the moderation history.\nError:\n") + box(text=e, lang="py"), + ephemeral=ephemeral, + ) + return + + case_quantity = len(moderations) page_quantity = ceil(case_quantity / pagesize) start_index = (page - 1) * pagesize end_index = page * pagesize embed = discord.Embed(color=await self.bot.get_embed_color(interaction.channel)) embed.set_author(icon_url=interaction.guild.icon.url, name="Infraction History") - embed.set_footer( - text=f"Page {page:,}/{page_quantity:,} | {case_quantity:,} Results" - ) + embed.set_footer(text=f"Page {page:,}/{page_quantity:,} | {case_quantity:,} Results") memory_dict = {} - for case in result_dict_list[start_index:end_index]: - if case["target_id"] not in memory_dict: - if case["target_type"] == "USER": - memory_dict[str(case["target_id"])] = await fetch_user_dict( - interaction.client, case["target_id"] - ) - elif case["target_type"] == "CHANNEL": - memory_dict[str(case["target_id"])] = await fetch_channel_dict( - interaction.guild, case["target_id"] - ) - target_user = memory_dict[str(case["target_id"])] + for mod in moderations[start_index:end_index]: + if mod.target_id not in memory_dict: + memory_dict.update({str(mod.target_id): await mod.get_target()}) + target = memory_dict[str(mod.target_id)] - if case["target_type"] == "USER": - target_name = ( - f"`{target_user['name']}`" - if target_user["discriminator"] == "0" - else f"`{target_user['name']}#{target_user['discriminator']}`" - ) - elif case["target_type"] == "CHANNEL": - target_name = f"`{target_user['mention']}`" + if mod.moderator_id not in memory_dict: + memory_dict.update({str(mod.moderator_id): await mod.get_moderator()}) + moderator = memory_dict[str(mod.moderator_id)] - if case["moderator_id"] not in memory_dict: - memory_dict[str(case["moderator_id"])] = await fetch_user_dict( - interaction.client, case["moderator_id"] - ) - moderator_user = memory_dict[str(case["moderator_id"])] - moderator_name = ( - f"`{moderator_user['name']}`" - if moderator_user["discriminator"] == "0" - else f"`{moderator_user['name']}#{moderator_user['discriminator']}`" - ) + field_name = f"Case #{mod.id:,} ({mod.type.string.title()})" + field_value = f"**Target:** `{target.name}` ({target.id})\n**Moderator:** `{moderator.name}` ({moderator.id})" - field_name = f"Case #{case['moderation_id']:,} ({str.title(case['moderation_type'])})" - field_value = f"**Target:** {target_name} ({target_user['id']})\n**Moderator:** {moderator_name} ({moderator_user['id']})" - - if len(case["reason"]) > 125: - field_value += f"\n**Reason:** `{str(case['reason'])[:125]}...`" + if len(str(mod.reason)) > 125: + field_value += f"\n**Reason:** `{str(mod.reason)[:125]}...`" else: - field_value += f"\n**Reason:** `{str(case['reason'])}`" + field_value += f"\n**Reason:** `{str(mod.reason)}`" - if case["duration"] != "NULL": - td = timedelta( - **{ - unit: int(val) - for unit, val in zip( - ["hours", "minutes", "seconds"], case["duration"].split(":") - ) - } - ) - duration_embed = ( - f"{humanize_timedelta(timedelta=td)} | " - if bool(case["expired"]) is False - else f"{humanize_timedelta(timedelta=td)} | Expired" - ) + if mod.duration: + duration_embed = f"{humanize_timedelta(timedelta=mod.duration)} | " if mod.expired is False else f"{humanize_timedelta(timedelta=mod.duration)} | Expired" field_value += f"\n**Duration:** {duration_embed}" - field_value += ( - f"\n**Timestamp:** | " - ) + field_value += f"\n**Timestamp:** | " - if case["role_id"] != "0": - role = interaction.guild.get_role(int(case["role_id"])) - if role is not None: - field_value += f"\n**Role:** {role.mention}" - else: - field_value += f"\n**Role:** Deleted Role ({case['role_id']})" + if mod.role_id: + role = await mod.get_role() + field_value += f"\n**Role:** {role.mention} ({role.id})" - if bool(case["resolved"]): + if mod.resolved: field_value += "\n**Resolved:** True" embed.add_field(name=field_name, value=field_value, inline=inline) await interaction.followup.send(embed=embed, ephemeral=ephemeral) + @history.autocomplete("types") + async def _history_types(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]: # pylint: disable=unused-argument + types: List[str] = sorted(self.type_registry.keys()) + choices = [] + if current.endswith(","): + for c in current.split(","): + if c in types: + types.remove(c) + for t in types: + choices.append(app_commands.Choice(name=current + t, value=current + t)) + else: + choices.append(app_commands.Choice(name="all", value="all")) + for t in types: + if t.startswith(current): + choices.append(app_commands.Choice(name=t, value=t)) + return choices[:25] + @app_commands.command(name="resolve") - async def resolve( - self, interaction: discord.Interaction, case: int, reason: str = None - ): + async def resolve(self, interaction: discord.Interaction, case: int, reason: str = "No reason provided."): """Resolve a specific case. Parameters @@ -1220,148 +752,59 @@ class Aurora(commands.Cog): Reason for resolving case""" permissions = check_permissions( interaction.client.user, - ["embed_links", "moderate_members", "ban_members"], + ("embed_links", "moderate_members", "ban_members"), interaction, ) if permissions: await interaction.response.send_message( - error( - f"I do not have the `{permissions}` permission, required for this action." - ), + error(f"I do not have the `{permissions}` permission, required for this action."), ephemeral=True, ) return - database = connect() - cursor = database.cursor() - - query_1 = ( - f"SELECT * FROM moderation_{interaction.guild.id} WHERE moderation_id = ?;" - ) - cursor.execute(query_1, (case,)) - result_1 = cursor.fetchone() - if result_1 is None or case == 0: + try: + moderation = await Moderation.find_by_id(interaction.client, case, interaction.guild.id) + except ValueError: + await interaction.response.send_message(content=error(f"Case #{case:,} does not exist!"), ephemeral=True) + return + if len(moderation.changes) > 25: await interaction.response.send_message( - content=error(f"There is no moderation with a case number of {case}."), + content=error("Due to limitations with Discord's embed system, you cannot edit a case more than 25 times."), ephemeral=True, ) return - query_2 = f"SELECT * FROM moderation_{interaction.guild.id} WHERE moderation_id = ? AND resolved = 0;" - cursor.execute(query_2, (case,)) - result_2 = cursor.fetchone() - if result_2 is None: - await interaction.response.send_message( - content=error( - f"This moderation has already been resolved!\nUse `/case {case}` for more information." - ), - ephemeral=True, - ) - return - - case_dict = generate_dict(result_2) - if reason is None: - reason = "No reason given." - - changes: list = case_dict["changes"] - if len(changes) > 25: - await interaction.response.send_message( - content=error( - "Due to limitations with Discord's embed system, you cannot edit a case more than 25 times." - ), - ephemeral=True, - ) - return - if not changes: - changes.append( - { - "type": "ORIGINAL", - "timestamp": case_dict["timestamp"], - "reason": case_dict["reason"], - "user_id": case_dict["moderator_id"], - } - ) - changes.append( - { - "type": "RESOLVE", - "timestamp": int(time.time()), - "reason": reason, - "user_id": interaction.user.id, - } - ) - - if case_dict["moderation_type"] in ["UNMUTE", "UNBAN"]: - await interaction.response.send_message( - content=error("You cannot resolve this type of moderation!"), - ephemeral=True, - ) - return - - if case_dict["moderation_type"] in ["MUTE", "TEMPBAN", "BAN"]: - if case_dict["moderation_type"] == "MUTE": - try: - member = await interaction.guild.fetch_member( - case_dict["target_id"] - ) - - await member.timeout( - None, reason=f"Case #{case:,} resolved by {interaction.user.id}" - ) - except discord.NotFound: - pass - - if case_dict["moderation_type"] in ["TEMPBAN", "BAN"]: - try: - user = await interaction.client.fetch_user(case_dict["target_id"]) - - await interaction.guild.unban( - user, reason=f"Case #{case} resolved by {interaction.user.id}" - ) - except discord.NotFound: - pass - - resolve_query = f"UPDATE `moderation_{interaction.guild.id}` SET resolved = 1, changes = ?, resolved_by = ?, resolve_reason = ? WHERE moderation_id = ?" - else: - resolve_query = f"UPDATE `moderation_{interaction.guild.id}` SET resolved = 1, changes = ?, resolved_by = ?, resolve_reason = ? WHERE moderation_id = ?" - - cursor.execute( - resolve_query, - ( - json.dumps(changes), - interaction.user.id, - reason, - case_dict["moderation_id"], - ), - ) - database.commit() + try: + success, msg = await moderation.resolve(interaction.user.id, reason) + except (ValueError, TypeError) as e: + if isinstance(e, ValueError): + await interaction.response.send_message(content=error("This case has already been resolved!"), ephemeral=True) + elif isinstance(e, TypeError): + await interaction.response.send_message(content=error("This case type cannot be resolved!"), ephemeral=True) embed = await case_factory( interaction=interaction, - case_dict=await fetch_case(case, interaction.guild.id), + moderation=moderation, ) - await interaction.response.send_message( - content=f"✅ Moderation #{case:,} resolved!", embed=embed - ) - await log(interaction, case, resolved=True) - - cursor.close() - database.close() + await interaction.response.send_message(content=f"✅ Moderation #{case:,} resolved!\n" + error(f"Resolve handler returned an error message: `{msg}`") if success is False else "", embed=embed) + ctx = await self.bot.get_context(interaction, cls=commands.Context) + await log(ctx=ctx, moderation_id=case, resolved=True) @app_commands.command(name="case") @app_commands.choices( - export=[ - Choice(name="Export as File", value="file"), + raw=[ Choice(name="Export as Codeblock", value="codeblock"), + Choice(name="Export as File", value="file"), ] ) async def case( self, interaction: discord.Interaction, case: int, - ephemeral: bool = None, + ephemeral: bool | None = None, evidenceformat: bool = False, changes: bool = False, - export: Choice[str] = None, + raw: Choice[str] | None = None, ): """Check the details of a specific case. @@ -1371,99 +814,74 @@ class Aurora(commands.Cog): What case are you looking up? ephemeral: bool Hide the command response + evidenceformat: bool + Display the evidence format of the case changes: bool List the changes made to the case - export: bool + raw: bool Export the case to a JSON file or codeblock""" - permissions = check_permissions( - interaction.client.user, ["embed_links"], interaction - ) + permissions = check_permissions(interaction.client.user, ["embed_links"], interaction) if permissions: await interaction.response.send_message( - error( - f"I do not have the `{permissions}` permission, required for this action." - ), + error(f"I do not have the `{permissions}` permission, required for this action."), ephemeral=True, ) return if ephemeral is None: - ephemeral = ( - await config.user(interaction.user).history_ephemeral() - or await config.guild(interaction.guild).history_ephemeral() - or False - ) + ephemeral = await config.user(interaction.user).history_ephemeral() or await config.guild(interaction.guild).history_ephemeral() or False - if case != 0: - case_dict = await fetch_case(case, interaction.guild.id) - if case_dict: - if export: - if export.value == "file" or len(str(case_dict)) > 1800: - filename = ( - str(data_manager.cog_data_path(cog_instance=self)) - + str(os.sep) - + f"moderation_{interaction.guild.id}_case_{case}.json" - ) + try: + mod = await Moderation.find_by_id(interaction.client, case, interaction.guild.id) + except ValueError: + await interaction.response.send_message(content=error(f"Case #{case:,} does not exist!"), ephemeral=True) + return - with open(filename, "w", encoding="utf-8") as f: - json.dump(case_dict, f, indent=2) + if raw: + if raw.value == "file" or len(mod.to_json(2)) > 1800: + filename = str(data_manager.cog_data_path(cog_instance=self)) + str(os.sep) + f"moderation_{interaction.guild.id}_case_{case}.json" - if export.value == "codeblock": - content = f"Case #{case:,} exported.\n" + warning( - "Case was too large to export as codeblock, so it has been uploaded as a `.json` file." - ) - else: - content = f"Case #{case:,} exported." - - await interaction.response.send_message( - content=content, - file=discord.File( - filename, - f"moderation_{interaction.guild.id}_case_{case}.json", - ), - ephemeral=ephemeral, - ) - - os.remove(filename) - return - await interaction.response.send_message( - content=box(json.dumps(case_dict, indent=2), 'json'), - ephemeral=ephemeral, - ) - return - if changes: - embed = await changes_factory( - interaction=interaction, case_dict=case_dict - ) - await interaction.response.send_message( - embed=embed, ephemeral=ephemeral - ) - elif evidenceformat: - content = await evidenceformat_factory( - interaction=interaction, case_dict=case_dict - ) - await interaction.response.send_message( - content=content, ephemeral=ephemeral - ) + with open(filename, "w", encoding="utf-8") as f: + mod.to_json(2, f) + if raw.value == "codeblock": + content = f"Case #{case:,} exported.\n" + warning("Case was too large to export as codeblock, so it has been uploaded as a `.json` file.") else: - embed = await case_factory( - interaction=interaction, case_dict=case_dict - ) - await interaction.response.send_message( - embed=embed, ephemeral=ephemeral - ) + content = f"Case #{case:,} exported." + + await interaction.response.send_message( + content=content, + file=discord.File( + filename, + f"moderation_{interaction.guild.id}_case_{case}.json", + ), + ephemeral=ephemeral, + ) + + os.remove(filename) return - await interaction.response.send_message( - content=f"No case with case number `{case}` found.", ephemeral=True - ) + await interaction.response.send_message( + content=box(mod.to_json(2), "json"), + ephemeral=ephemeral, + ) + return + if changes: + embed = await changes_factory(interaction=interaction, moderation=mod) + await interaction.response.send_message(embed=embed, ephemeral=ephemeral) + elif evidenceformat: + content = await evidenceformat_factory(moderation=mod) + await interaction.response.send_message(content=content, ephemeral=ephemeral) + else: + embed = await case_factory(interaction=interaction, moderation=mod) + await interaction.response.send_message(embed=embed, ephemeral=ephemeral) + return @app_commands.command(name="edit") async def edit( self, interaction: discord.Interaction, case: int, - reason: str, - duration: str = None, + reason: str | None = None, + duration: str | None = None, ): """Edit the reason of a specific case. @@ -1476,302 +894,147 @@ class Aurora(commands.Cog): duration: str What is the new duration? Does not reapply the moderation if it has already expired. """ - permissions = check_permissions( - interaction.client.user, ["embed_links"], interaction - ) + permissions = check_permissions(interaction.client.user, ["embed_links"], interaction) if permissions: await interaction.response.send_message( - error( - f"I do not have the `{permissions}` permission, required for this action." - ), + error(f"I do not have the `{permissions}` permission, required for this action."), ephemeral=True, ) return - if case != 0: - parsed_time = None - case_dict = await fetch_case(case, interaction.guild.id) - if case_dict: - if duration: - parsed_time = parse_timedelta(duration) - if parsed_time is None: - await interaction.response.send_message( - error("Please provide a valid duration!"), ephemeral=True - ) - return + try: + moderation = await Moderation.find_by_id(interaction.client, case, interaction.guild.id) + old_moderation = moderation.model_copy() + except ValueError: + await interaction.response.send_message(content=error(f"Case #{case:,} does not exist!"), ephemeral=True) + return - end_timestamp = case_dict["timestamp"] + parsed_time.total_seconds() + if len(moderation.changes) > 25: + return await interaction.response.send_message( + content=error("Due to limitations with Discord's embed system, you cannot edit a case more than 25 times."), + ephemeral=True, + ) - if case_dict["moderation_type"] == "MUTE": - if ( - time.time() - case_dict["timestamp"] - ) + parsed_time.total_seconds() > 2419200: - await interaction.response.send_message( - error( - "Please provide a duration that is less than 28 days from the initial moderation." - ) - ) - return + if duration: + try: + parsed_time = parse_relativedelta(argument=duration) + if parsed_time is None: + raise commands.BadArgument() + moderation.duration = timedelta_from_relativedelta(relativedelta=parsed_time) + except (commands.BadArgument, ValueError): + return await interaction.response.send_message(error("Please provide a valid duration!"), ephemeral=True) - try: - member = await interaction.guild.fetch_member( - case_dict["target_id"] - ) + moderation.end_timestamp = moderation.timestamp + timedelta(seconds=moderation.duration.total_seconds()) - await member.timeout( - parsed_time, - reason=f"Case #{case:,} edited by {interaction.user.id}", - ) - except discord.NotFound: - pass - - changes: list = case_dict["changes"] - if len(changes) > 25: - await interaction.response.send_message( - content=error( - "Due to limitations with Discord's embed system, you cannot edit a case more than 25 times." - ), - ephemeral=True, - ) - return - if not changes: - changes.append( - { - "type": "ORIGINAL", - "timestamp": case_dict["timestamp"], - "reason": case_dict["reason"], - "user_id": case_dict["moderator_id"], - "duration": case_dict["duration"], - "end_timestamp": case_dict["end_timestamp"], - } - ) - if parsed_time: - changes.append( - { - "type": "EDIT", - "timestamp": int(time.time()), - "reason": reason, - "user_id": interaction.user.id, - "duration": convert_timedelta_to_str(parsed_time), - "end_timestamp": end_timestamp, - } - ) - else: - changes.append( - { - "type": "EDIT", - "timestamp": int(time.time()), - "reason": reason, - "user_id": interaction.user.id, - "duration": case_dict["duration"], - "end_timestamp": case_dict["end_timestamp"], - } - ) - - database = connect() - cursor = database.cursor() - - if parsed_time: - update_query = f"UPDATE `moderation_{interaction.guild.id}` SET changes = ?, reason = ?, duration = ?, end_timestamp = ? WHERE moderation_id = ?" - cursor.execute( - update_query, - ( - json.dumps(changes), - reason, - convert_timedelta_to_str(parsed_time), - end_timestamp, - case, - ), - ) - else: - update_query = f"UPDATE `moderation_{interaction.guild.id}` SET changes = ?, reason = ? WHERE moderation_id = ?" - cursor.execute(update_query, (json.dumps(changes), reason, case)) - database.commit() - - new_case = await fetch_case(case, interaction.guild.id) - embed = await case_factory(interaction=interaction, case_dict=new_case) - - await interaction.response.send_message( - content=f"✅ Moderation #{case:,} edited!", - embed=embed, - ephemeral=True, - ) - await log(interaction, case) - - cursor.close() - database.close() + try: + success = await moderation.type.duration_edit_handler(interaction=interaction, old_moderation=old_moderation, new_moderation=moderation) + except NotImplementedError: + return await interaction.response.send_message(error("This case type does not support duration editing!"), ephemeral=True) + if not success: return - await interaction.response.send_message( - content=error(f"No case with case number `{case}` found."), ephemeral=True + + if reason: + moderation.reason = reason + + if not reason and not duration: + return await interaction.response.send_message(error("Please provide a new reason or duration to edit this case!"), ephemeral=True) + + if not moderation.changes: + moderation.changes.append( + Change.from_dict( + interaction.client, + { + "type": "ORIGINAL", + "timestamp": old_moderation.timestamp, + "reason": old_moderation.reason, + "user_id": old_moderation.moderator_id, + "duration": timedelta_to_string(old_moderation.duration) if old_moderation.duration else None, + "end_timestamp": old_moderation.end_timestamp, + }, + ) + ) + moderation.changes.append( + Change.from_dict( + interaction.client, + { + "type": "EDIT", + "timestamp": int(time.time()), + "reason": reason if reason else None, + "user_id": interaction.user.id, + "duration": timedelta_to_string(moderation.duration) if duration else None, + "end_timestamp": moderation.end_timestamp if duration else None, + }, + ) ) + await moderation.update() + embed = await case_factory(interaction=interaction, moderation=moderation) + + await interaction.response.send_message( + content=f"✅ Moderation #{case:,} edited!", + embed=embed, + ephemeral=True, + ) + await log(await self.bot.get_context(interaction), case) + + return + @tasks.loop(minutes=1) async def handle_expiry(self): await self.bot.wait_until_red_ready() current_time = time.time() - database = connect() - cursor = database.cursor() global_unban_num = 0 global_addrole_num = 0 global_removerole_num = 0 + global_other_num = 0 + global_err_num = 0 guilds: list[discord.Guild] = self.bot.guilds for guild in guilds: if not await self.bot.cog_disabled_in_guild(self, guild): time_per_guild = time.time() - tempban_query = f"SELECT target_id, moderation_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'TEMPBAN' AND expired = 0" - - try: - cursor.execute(tempban_query, (time.time(),)) - result = cursor.fetchall() - except sqlite3.OperationalError: - continue - - target_ids = [row[0] for row in result] - moderation_ids = [row[1] for row in result] + query = f"SELECT * FROM moderation_{guild.id} WHERE end_timestamp IS NOT NULL AND end_timestamp <= ? AND expired = 0" + moderations = await Moderation.execute(bot=self.bot, guild_id=guild.id, query=query, parameters=(time.time(),)) unban_num = 0 - for target_id, moderation_id in zip(target_ids, moderation_ids): - user: discord.User = await self.bot.fetch_user(target_id) - name = ( - f"{user.name}#{user.discriminator}" - if user.discriminator != "0" - else user.name - ) - try: - await guild.unban( - user, reason=f"Automatic unban from case #{moderation_id}" - ) - - embed = await message_factory( - await self.bot.get_embed_color(guild.channels[0]), - guild=guild, - reason=f"Automatic unban from case #{moderation_id}", - moderation_type="unbanned", - ) - - try: - await user.send(embed=embed, file=get_footer_image(self)) - except discord.errors.HTTPException: - pass - - logger.debug( - "Unbanned %s (%s) from %s (%s)", - name, - user.id, - guild.name, - guild.id, - ) - unban_num = unban_num + 1 - except ( - discord.errors.NotFound, - discord.errors.Forbidden, - discord.errors.HTTPException, - ) as e: - logger.error( - "Failed to unban %s (%s) from %s (%s)\n%s", - name, - user.id, - guild.name, - guild.id, - e, - ) - removerole_num = 0 - addrole_query = f"SELECT target_id, moderation_id, role_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'ADDROLE' AND expired = 0" - try: - cursor.execute(addrole_query, (time.time(),)) - result = cursor.fetchall() - except sqlite3.OperationalError: - continue - target_ids = [row[0] for row in result] - moderation_ids = [row[1] for row in result] - role_ids = [row[2] for row in result] - - for target_id, moderation_id, role_id in zip( - target_ids, moderation_ids, role_ids - ): - try: - member = await guild.fetch_member(target_id) - - await member.remove_roles( - Object(role_id), reason=f"Automatic role removal from case #{moderation_id}" - ) - - removerole_num = removerole_num + 1 - except ( - discord.errors.NotFound, - discord.errors.Forbidden, - discord.errors.HTTPException, - ) as e: - logger.error( - "Removing the role %s from user %s failed due to: \n%s", - role_id, - target_id, - e, - ) - continue - addrole_num = 0 - removerole_query = f"SELECT target_id, moderation_id, role_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'REMOVEROLE' AND expired = 0" - try: - cursor.execute(removerole_query, (time.time(),)) - result = cursor.fetchall() - except sqlite3.OperationalError: - continue - target_ids = [row[0] for row in result] - moderation_ids = [row[1] for row in result] - role_ids = [row[2] for row in result] - - for target_id, moderation_id, role_id in zip( - target_ids, moderation_ids, role_ids - ): + other_num = 0 + error_num = 0 + for moderation in moderations: try: - member = await guild.fetch_member(target_id) - - await member.add_roles( - Object(role_id), reason=f"Automatic role addition from case #{moderation_id}" - ) - - addrole_num = addrole_num + 1 - except ( - discord.errors.NotFound, - discord.errors.Forbidden, - discord.errors.HTTPException, - ) as e: - logger.error("Adding the role %s to user %s failed due to: \n%s", role_id, target_id, e) + num = await moderation.type.expiry_handler(moderation) + except NotImplementedError: + logger.warning("Expiry handler not implemented for expirable moderation type %s", moderation.type.key) continue + except Exception as e: # pylint: disable=broad-except + logger.exception("Expiry handler failed for moderation %s with the type %s", moderation.id, moderation.type.key, exc_info=e) + error_num += 1 + continue + match moderation.type.key: + case "tempban": + unban_num += num + case "addrole": + removerole_num += num + case "removerole": + addrole_num += num + case _: + other_num += num if isinstance(num, int) else 0 - expiry_query = f"UPDATE `moderation_{guild.id}` SET expired = 1 WHERE (end_timestamp != 0 AND end_timestamp <= ? AND expired = 0) OR (expired = 0 AND resolved = 1);" - cursor.execute(expiry_query, (time.time(),)) + expiry_query = f"UPDATE `moderation_{guild.id}` SET expired = 1 WHERE (end_timestamp IS NOT NULL AND end_timestamp <= ? AND expired = 0) OR (expired = 0 AND resolved = 1);" + await Moderation.execute(bot=self.bot, guild_id=guild.id, query=expiry_query, parameters=(time.time(),), return_obj=False) per_guild_completion_time = (time.time() - time_per_guild) * 1000 - logger.debug( - "Completed expiry loop for %s (%s) in %sms with %s users unbanned, %s roles added, and %s roles removed", - guild.name, - guild.id, - f"{per_guild_completion_time:.6f}", - unban_num, - addrole_num, - removerole_num, - ) + logger.debug("Completed expiry loop for %s (%s) in %sms with %s errors, %s users unbanned, %s roles added, and %s roles removed (%s other cases expired)", guild.name, guild.id, f"{per_guild_completion_time:.6f}", error_num, unban_num, addrole_num, removerole_num, other_num) global_unban_num = global_unban_num + unban_num global_addrole_num = global_addrole_num + addrole_num global_removerole_num = global_removerole_num + removerole_num - - database.commit() - cursor.close() - database.close() + global_other_num = global_other_num + other_num + global_err_num = global_err_num + error_num completion_time = (time.time() - current_time) * 1000 - logger.debug( - "Completed expiry loop in %sms with %s users unbanned, %s roles added, and %s roles removed", - f"{completion_time:.6f}", - global_unban_num, - global_addrole_num, - global_removerole_num, - ) + logger.debug("Completed expiry loop in %sms with %s errors, %s users unbanned, %s roles added, and %s roles removed (%s other cases expired)", f"{completion_time:.6f}", global_err_num, global_unban_num, global_addrole_num, global_removerole_num, global_other_num) ######################################################################################################################## ### Configuration Commands # @@ -1787,7 +1050,7 @@ class Aurora(commands.Cog): @aurora_settings.command(name="overrides", aliases=["override", "user"]) async def aurora_settings_overrides(self, ctx: commands.Context): - """Manage Aurora's user overriddable settings.""" + """Manage Aurora's user overridable settings.""" msg = await ctx.send(embed=await overrides_embed(ctx)) await msg.edit(view=Overrides(ctx, msg, 60)) @@ -1799,6 +1062,22 @@ class Aurora(commands.Cog): msg = await ctx.send(embed=await guild_embed(ctx)) await msg.edit(view=Guild(ctx, msg, 60)) + @aurora_settings.command(name="type") + @commands.admin_or_permissions(manage_guild=True) + @commands.guild_only() + async def aurora_settings_type(self, ctx: commands.Context, moderation_type: str): + """Manage configuration options for specific moderation types. + + See [the documentation](https://seacogs.coastalcommits.com/Aurora/Types) for a list of built-in moderation types, or run this command with a junk argument (`awasd` or something) to see a list of valid types.""" + try: + registered_type = type_registry.get(moderation_type) + except RegistryKeyError: + types = "`, `".join(type_registry.keys()) + await ctx.send(error(f"`{moderation_type}` is not a valid moderation type.\nValid types are:\n`{types}`")) + return + msg = await ctx.send(embed=await type_embed(ctx, registered_type)) + await msg.edit(view=Types(ctx, msg, registered_type)) + @aurora_settings.command(name="addrole", aliases=["removerole"]) @commands.admin_or_permissions(manage_guild=True) @commands.guild_only() @@ -1827,17 +1106,11 @@ class Aurora(commands.Cog): @commands.admin() async def aurora_import_aurora(self, ctx: commands.Context): """Import moderation history from another bot using Aurora.""" - if ( - ctx.message.attachments - and ctx.message.attachments[0].content_type - == "application/json; charset=utf-8" - ): - message = await ctx.send( - warning( - "Are you sure you want to import moderations from another bot?\n**This will overwrite any moderations that already exist in this guild's moderation table.**\n*The import process will block the rest of your bot until it is complete.*" - ) - ) - await message.edit(view=ImportAuroraView(60, ctx, message)) + if ctx.message.attachments and ctx.message.attachments[0].content_type == "application/json; charset=utf-8": + file = await ctx.message.attachments[0].read() + data: list[dict] = sorted(json.loads(file), key=lambda x: x["moderation_id"]) + message = await ctx.send(warning("Are you sure you want to import moderations from another bot?\n**This will overwrite any moderations that already exist in this guild's moderation table.**\n*The import process will block the rest of your bot until it is complete.*")) + await message.edit(view=ImportAuroraView(60, ctx, message, data)) else: await ctx.send(error("Please provide a valid Aurora export file.")) @@ -1845,23 +1118,36 @@ class Aurora(commands.Cog): @commands.admin() async def aurora_import_galacticbot(self, ctx: commands.Context): """Import moderation history from GalacticBot.""" - if ( - ctx.message.attachments - and ctx.message.attachments[0].content_type - == "application/json; charset=utf-8" - ): - message = await ctx.send( - warning( - "Are you sure you want to import GalacticBot moderations?\n**This will overwrite any moderations that already exist in this guild's moderation table.**\n*The import process will block the rest of your bot until it is complete.*" - ) - ) + if ctx.message.attachments and ctx.message.attachments[0].content_type == "application/json; charset=utf-8": + message = await ctx.send(warning("Are you sure you want to import GalacticBot moderations?\n**This will overwrite any moderations that already exist in this guild's moderation table.**\n*The import process will block the rest of your bot until it is complete.*")) await message.edit(view=ImportGalacticBotView(60, ctx, message)) else: - await ctx.send( - error("Please provide a valid GalacticBot moderation export file.") - ) + await ctx.send(error("Please provide a valid GalacticBot moderation export file.")) - @aurora.command(aliases=["tdc", "td", "timedeltaconvert"]) + @aurora.group(autohelp=True, name="convert") + async def aurora_convert(self, ctx: commands.Context): + """Convert strings to various Python objects.""" + + @aurora_convert.command(aliases=["dt"]) + async def datetime(self, ctx: commands.Context, *, date: str) -> None: + """Convert a string to a datetime object. + + This command converts a date to a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) Python object. + + **Example usage** + `[p]aurora datetime 08/20/2024` + **Output** + `2024-08-20 12:00:00`""" + try: + parsed_date = parse(date) + await ctx.send(f"`{parsed_date}`") + except (ParserError, OverflowError) as e: + if isinstance(e, ParserError): + await ctx.send(error("Invalid date format!")) + if isinstance(e, OverflowError): + await ctx.send(error("Date is too far in the future!")) + + @aurora_convert.command(aliases=["td"]) async def timedelta(self, ctx: commands.Context, *, duration: str) -> None: """Convert a string to a timedelta. @@ -1878,7 +1164,7 @@ class Aurora(commands.Cog): return await ctx.send(f"`{parsed_time}`") - @aurora.command(aliases=["rdc", "rd", "relativedeltaconvert"]) + @aurora_convert.command(aliases=["rd"]) async def relativedelta(self, ctx: commands.Context, *, duration: str) -> None: """Convert a string to a relativedelta. @@ -1893,3 +1179,34 @@ class Aurora(commands.Cog): await ctx.send(error("Please provide a convertible value!")) return await ctx.send(f"`{parsed_time}`") + + @aurora.command(name="info") + async def aurora_info(self, ctx: commands.Context): + """Get information about Aurora.""" + embed = discord.Embed( + title="Aurora Information", + color=await self.bot.get_embed_color(ctx.channel), + timestamp=datetime.now(), + ) + embed.set_thumbnail(url=self.bot.user.avatar.url) + embed.add_field(name="Version", value=f"[{self.__version__}]({self.__git__})") + embed.add_field(name="Author", value=", ".join(self.__author__)) + if ctx.author.id in self.bot.owner_ids: + results = await Moderation.execute(query="SELECT name FROM sqlite_master WHERE type='table';", return_obj=False) + tables = [table[0] for table in results] + table_count = len(tables) + row_count = 0 + + for table in tables: + count_query = f"SELECT COUNT() FROM {table}" + result = await Moderation.execute(query=count_query, return_obj=False) + row_count += result[0][0] + + filesize = os.path.getsize(str(data_manager.cog_data_path(cog_instance=self) / "aurora.db")) / 1024 + + embed.add_field( + name="Database Stats", + value=f"{bold('Table Count:')} {table_count:,}\n{bold('Row Count:')} {row_count:,}\n{bold('File Size:')} {filesize:,.0f} KB", + ) + embed.add_field(name="Moderation Types", value=f"{len(type_registry)} registered types\n{box(', '.join(type_registry.keys()))}", inline=False) + await ctx.send(embed=embed) diff --git a/aurora/importers/aurora.py b/aurora/importers/aurora.py index 44cab98..6064873 100644 --- a/aurora/importers/aurora.py +++ b/aurora/importers/aurora.py @@ -1,38 +1,33 @@ # pylint: disable=duplicate-code import json -from datetime import timedelta -from typing import Dict +import os +from time import time +from typing import Dict, List -from discord import ButtonStyle, Interaction, Message, ui -from redbot.core import commands -from redbot.core.utils.chat_formatting import box, warning +from discord import ButtonStyle, File, Interaction, Message, ui +from redbot.core import commands, data_manager +from redbot.core.utils.chat_formatting import warning -from ..utilities.database import connect, create_guild_table, mysql_log +from ..models.moderation import Moderation +from ..models.type import Type, type_registry +from ..utilities.json import dump +from ..utilities.utils import create_guild_table, timedelta_from_string class ImportAuroraView(ui.View): - def __init__(self, timeout, ctx, message): + def __init__(self, timeout, ctx, message, data: List[Dict[str, any]]): super().__init__() self.ctx: commands.Context = ctx self.message: Message = message + self.data: List[Dict[str, any]] = data @ui.button(label="Yes", style=ButtonStyle.success) - async def import_button_y( - self, interaction: Interaction, button: ui.Button - ): # pylint: disable=unused-argument + async def import_button_y(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument await self.message.delete() - await interaction.response.send_message( - "Deleting original table...", ephemeral=True - ) - - database = connect() - cursor = database.cursor() + await interaction.response.send_message("Deleting original table...", ephemeral=True) query = f"DROP TABLE IF EXISTS moderation_{self.ctx.guild.id};" - cursor.execute(query) - - cursor.close() - database.commit() + await Moderation.execute(query=query, return_obj=False) await interaction.edit_original_response(content="Creating new table...") @@ -40,77 +35,94 @@ class ImportAuroraView(ui.View): await interaction.edit_original_response(content="Importing moderations...") - file = await self.ctx.message.attachments[0].read() - data: list[dict] = sorted(json.loads(file), key=lambda x: x["moderation_id"]) - - user_mod_types = ["NOTE", "WARN", "ADDROLE", "REMOVEROLE", "MUTE", "UNMUTE", "KICK", "TEMPBAN", "BAN", "UNBAN"] - - channel_mod_types = ["SLOWMODE", "LOCKDOWN"] - failed_cases = [] - for case in data: + for case in self.data: if case["moderation_id"] == 0: continue + moderation_type: Type = type_registry[case["moderation_type"].lower()] if "target_type" not in case or not case["target_type"]: - if case["moderation_type"] in user_mod_types: - case["target_type"] = "USER" - elif case["moderation_type"] in channel_mod_types: - case["target_type"] = "CHANNEL" + if moderation_type.channel: + case["target_type"] = "channel" else: - case["target_type"] = "USER" + case["target_type"] = "user" if "role_id" not in case or not case["role_id"]: - case["role_id"] = 0 + case["role_id"] = None + else: + case["role_id"] = int(case["role_id"]) - if "changes" not in case or not case["changes"]: - case["changes"] = [] + case["target_id"] = int(case["target_id"]) + case["moderator_id"] = int(case["moderator_id"]) + + changes = case.get("changes", None) + if not changes: + changes = [] + else: + if not isinstance(changes, list): + changes = json.loads(changes) + if isinstance(changes, str): + changes: list[dict] = json.loads(changes) + + for change in changes: + if "bot" in change: + del change["bot"] if "metadata" not in case: metadata = {} else: - metadata: Dict[str, any] = json.loads(case["metadata"]) + if isinstance(case["metadata"], str): + metadata: Dict[str, any] = json.loads(case["metadata"]) + else: + metadata = case["metadata"] if not metadata.get("imported_from"): metadata.update({"imported_from": "Aurora"}) + metadata.update({"imported_timestamp": int(time())}) - if case["duration"] != "NULL": - hours, minutes, seconds = map(int, case["duration"].split(":")) - duration = timedelta(hours=hours, minutes=minutes, seconds=seconds) + if case["duration"] != "NULL" and case["duration"] is not None: + duration = timedelta_from_string(case["duration"]) + if moderation_type.key == "ban": + moderation_type = type_registry["tempban"] else: - duration = "NULL" + duration = None - await mysql_log( - self.ctx.guild.id, - case["moderator_id"], - case["moderation_type"], - case["target_type"], - case["target_id"], - case["role_id"], - duration, - case["reason"], - timestamp=case["timestamp"], - resolved=case["resolved"], - resolved_by=case["resolved_by"], - resolved_reason=case["resolve_reason"], - expired=case["expired"], - changes=case["changes"], - metadata=metadata, - database=database, - ) + try: + await Moderation.log( + bot=interaction.client, + guild_id=self.ctx.guild.id, + moderator_id=case["moderator_id"], + moderation_type=moderation_type, + target_type=case["target_type"].lower(), + target_id=case["target_id"], + role_id=case["role_id"], + duration=duration, + reason=case["reason"], + timestamp=case["timestamp"], + resolved=case["resolved"], + resolved_by=case["resolved_by"], + resolved_reason=case["resolve_reason"], + expired=case["expired"], + changes=changes, + metadata=metadata, + return_obj=False, + ) + except Exception as e: # pylint: disable=broad-exception-caught + failed_cases.append(str(case["moderation_id"]) + f": {e}") await interaction.edit_original_response(content="Import complete.") if failed_cases: - await interaction.edit_original_response( - content="Import complete.\n" - + warning("Failed to import the following cases:\n") - + box(failed_cases) - ) + filename = str(data_manager.cog_data_path(cog_instance=self)) + str(os.sep) + f"failed_cases_{interaction.guild.id}.json" + + with open(filename, "w", encoding="utf-8") as f: + dump(obj=failed_cases, fp=f, indent=2) + + await interaction.channel.send(content="Import complete.\n" + warning("Failed to import the following cases:\n"), file=File(filename, f"failed_cases_{interaction.guild.id}.json")) + + os.remove(filename) @ui.button(label="No", style=ButtonStyle.danger) - async def import_button_n( - self, interaction: Interaction, button: ui.Button - ): # pylint: disable=unused-argument + async def import_button_n(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument await self.message.edit(content="Import cancelled.", view=None) await self.message.delete(10) await self.ctx.message.delete(10) diff --git a/aurora/importers/galacticbot.py b/aurora/importers/galacticbot.py index c6e0b99..c62a05d 100644 --- a/aurora/importers/galacticbot.py +++ b/aurora/importers/galacticbot.py @@ -1,37 +1,36 @@ # pylint: disable=duplicate-code import json from datetime import timedelta +from time import time from discord import ButtonStyle, Interaction, Message, ui from redbot.core import commands from redbot.core.utils.chat_formatting import box, warning -from ..utilities.database import connect, create_guild_table, mysql_log +from ..models.moderation import Change, Moderation +from ..utilities.utils import create_guild_table class ImportGalacticBotView(ui.View): def __init__(self, timeout, ctx, message): super().__init__() self.ctx: commands.Context = ctx + self.timeout = timeout self.message: Message = message @ui.button(label="Yes", style=ButtonStyle.success) - async def import_button_y( - self, interaction: Interaction, button: ui.Button - ): # pylint: disable=unused-argument + async def import_button_y(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument await self.message.delete() - await interaction.response.send_message( - "Deleting original table...", ephemeral=True - ) + await interaction.response.send_message("Deleting original table...", ephemeral=True) - database = connect() - cursor = database.cursor() + database = await Moderation.connect() + cursor = await database.cursor() query = f"DROP TABLE IF EXISTS moderation_{self.ctx.guild.id};" - cursor.execute(query) + await cursor.execute(query) - cursor.close() - database.commit() + await cursor.close() + await database.commit() await interaction.edit_original_response(content="Creating new table...") @@ -67,12 +66,12 @@ class ImportGalacticBotView(ui.View): if case["duration"] is not None and float(case["duration"]) != 0: duration = timedelta(seconds=round(float(case["duration"]) / 1000)) else: - duration = "NULL" + duration = None except OverflowError: failed_cases.append(case["case"]) continue - metadata = {"imported_from": "GalacticBot"} + metadata = {"imported_from": "GalacticBot", "imported_timestamp": int(time())} if case["type"] == "SLOWMODE": metadata["seconds"] = case["data"]["seconds"] @@ -92,43 +91,47 @@ class ImportGalacticBotView(ui.View): if resolved_by is None: resolved_by = "?" if resolved_reason is None: - resolved_reason = ( - "Could not get resolve reason during moderation import." - ) + resolved_reason = "Could not get resolve reason during moderation import." if resolved_timestamp is None: resolved_timestamp = timestamp changes = [ - { - "type": "ORIGINAL", - "reason": case["reason"], - "user_id": case["executor"], - "timestamp": timestamp, - }, - { - "type": "RESOLVE", - "reason": resolved_reason, - "user_id": resolved_by, - "timestamp": resolved_timestamp, - }, + Change.from_dict( + interaction.client, + { + "type": "ORIGINAL", + "reason": case["reason"], + "user_id": case["executor"], + "timestamp": timestamp, + }, + ), + Change.from_dict( + interaction.client, + { + "type": "RESOLVE", + "reason": resolved_reason, + "user_id": resolved_by, + "timestamp": resolved_timestamp, + }, + ), ] else: - resolved = 0 - resolved_by = "NULL" - resolved_reason = "NULL" - changes = [] + resolved = None + resolved_by = None + resolved_reason = None + changes = None if case["reason"] and case["reason"] != "N/A": reason = case["reason"] else: - reason = "NULL" + reason = None - await mysql_log( + await Moderation.log( self.ctx.guild.id, case["executor"], case["type"], case["targetType"], case["target"], - 0, + None, duration, reason, timestamp=timestamp, @@ -142,16 +145,10 @@ class ImportGalacticBotView(ui.View): await interaction.edit_original_response(content="Import complete.") if failed_cases: - await interaction.edit_original_response( - content="Import complete.\n" - + warning("Failed to import the following cases:\n") - + box(failed_cases) - ) + await interaction.edit_original_response(content="Import complete.\n" + warning("Failed to import the following cases:\n") + box(failed_cases)) @ui.button(label="No", style=ButtonStyle.danger) - async def import_button_n( - self, interaction: Interaction, button: ui.Button - ): # pylint: disable=unused-argument + async def import_button_n(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument await self.message.edit(content="Import cancelled.", view=None) await self.message.delete(10) await self.ctx.message.delete(10) diff --git a/aurora/info.json b/aurora/info.json index de475f2..8229183 100644 --- a/aurora/info.json +++ b/aurora/info.json @@ -9,6 +9,7 @@ "disabled": false, "min_bot_version": "3.5.0", "min_python_version": [3, 10, 0], + "requirements": ["pydantic", "aiosqlite", "phx-class-registry==5.0.0"], "tags": [ "mod", "moderate", diff --git a/aurora/menus/addrole.py b/aurora/menus/addrole.py index 11f6b32..0338a41 100644 --- a/aurora/menus/addrole.py +++ b/aurora/menus/addrole.py @@ -1,20 +1,24 @@ from discord import ButtonStyle, Interaction, Message, ui +from discord.errors import NotFound from redbot.core import commands from redbot.core.utils.chat_formatting import error -from aurora.utilities.config import config -from aurora.utilities.factory import addrole_embed +from ..utilities.config import config +from ..utilities.factory import addrole_embed class Addrole(ui.View): - def __init__(self, ctx: commands.Context, message: Message, timeout: int = None): + def __init__(self, ctx: commands.Context, message: Message, timeout: int | None = None): super().__init__() self.ctx = ctx self.message = message self.timeout = timeout async def on_timeout(self): - await self.message.edit(view=None) + try: + await self.message.edit(view=None) + except NotFound: + pass @ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25) async def addrole_select(self, interaction: Interaction, select: ui.RoleSelect): @@ -23,7 +27,7 @@ class Addrole(ui.View): return await interaction.response.defer() async with config.guild(self.ctx.guild).addrole_whitelist() as addrole_whitelist: - addrole_whitelist: list # type hint + addrole_whitelist: list # type hint for value in select.values: if value.id in addrole_whitelist: addrole_whitelist.remove(value.id) @@ -32,7 +36,7 @@ class Addrole(ui.View): await interaction.message.edit(embed=await addrole_embed(self.ctx)) @ui.button(label="Clear", style=ButtonStyle.red, row=1) - async def clear(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def clear(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: await interaction.response.send_message(error("You must have the manage guild permission to clear the guild's addrole whitelist."), ephemeral=True) return @@ -41,7 +45,7 @@ class Addrole(ui.View): await interaction.message.edit(embed=await addrole_embed(self.ctx)) @ui.button(label="Close", style=ButtonStyle.gray) - async def close(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def close(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: await interaction.response.send_message(error("You can't do that!"), ephemeral=True) return diff --git a/aurora/menus/guild.py b/aurora/menus/guild.py index f99e552..e7562b5 100644 --- a/aurora/menus/guild.py +++ b/aurora/menus/guild.py @@ -1,23 +1,27 @@ from discord import ButtonStyle, Interaction, Message, ui +from discord.errors import NotFound from redbot.core import commands -from aurora.utilities.config import config -from aurora.utilities.factory import guild_embed -from aurora.utilities.utils import create_pagesize_options +from ..utilities.config import config +from ..utilities.factory import guild_embed +from ..utilities.utils import create_pagesize_options class Guild(ui.View): - def __init__(self, ctx: commands.Context, message: Message, timeout: int = None): + def __init__(self, ctx: commands.Context, message: Message, timeout: int | None = None): super().__init__() self.ctx = ctx self.message = message self.timeout = timeout async def on_timeout(self): - await self.message.edit(view=None) + try: + await self.message.edit(view=None) + except NotFound: + pass @ui.button(label="Show Moderator", style=ButtonStyle.green, row=0) - async def show_moderator(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def show_moderator(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) return @@ -27,7 +31,7 @@ class Guild(ui.View): await interaction.message.edit(embed=await guild_embed(self.ctx)) @ui.button(label="Use Discord Permissions", style=ButtonStyle.green, row=0) - async def use_discord_permissions(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def use_discord_permissions(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) return @@ -37,7 +41,7 @@ class Guild(ui.View): await interaction.message.edit(embed=await guild_embed(self.ctx)) @ui.button(label="Respect Hierarchy", style=ButtonStyle.green, row=0) - async def respect_heirarchy(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def respect_hierarchy(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) return @@ -47,7 +51,7 @@ class Guild(ui.View): await interaction.message.edit(embed=await guild_embed(self.ctx)) @ui.button(label="Ignore Modlog", style=ButtonStyle.green, row=0) - async def ignore_modlog(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def ignore_modlog(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) return @@ -57,7 +61,7 @@ class Guild(ui.View): await interaction.message.edit(embed=await guild_embed(self.ctx)) @ui.button(label="Ignore Other Bots", style=ButtonStyle.green, row=0) - async def ignore_other_bots(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def ignore_other_bots(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) return @@ -67,7 +71,7 @@ class Guild(ui.View): await interaction.message.edit(embed=await guild_embed(self.ctx)) @ui.button(label="DM Users", style=ButtonStyle.green, row=1) - async def dm_users(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def dm_users(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) return @@ -77,7 +81,7 @@ class Guild(ui.View): await interaction.message.edit(embed=await guild_embed(self.ctx)) @ui.button(label="Auto Evidence Format", style=ButtonStyle.green, row=1) - async def auto_evidenceformat(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def auto_evidenceformat(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) return @@ -87,7 +91,7 @@ class Guild(ui.View): await interaction.message.edit(embed=await guild_embed(self.ctx)) @ui.button(label="Ephemeral", style=ButtonStyle.green, row=1) - async def ephemeral(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def ephemeral(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) return @@ -97,7 +101,7 @@ class Guild(ui.View): await interaction.message.edit(embed=await guild_embed(self.ctx)) @ui.button(label="History Inline", style=ButtonStyle.green, row=1) - async def inline(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def inline(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) return @@ -107,7 +111,11 @@ class Guild(ui.View): await interaction.message.edit(embed=await guild_embed(self.ctx)) @ui.select(placeholder="History Pagesize", options=create_pagesize_options(), row=2) - async def pagesize(self, interaction: Interaction, select: ui.Select,): + async def pagesize( + self, + interaction: Interaction, + select: ui.Select, + ): if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) return @@ -119,7 +127,11 @@ class Guild(ui.View): await interaction.message.edit(embed=await guild_embed(self.ctx)) @ui.select(placeholder="History Inline Pagesize", options=create_pagesize_options(), row=3) - async def inline_pagesize(self, interaction: Interaction, select: ui.Select,): + async def inline_pagesize( + self, + interaction: Interaction, + select: ui.Select, + ): if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) return diff --git a/aurora/menus/immune.py b/aurora/menus/immune.py index 2a5c007..ecd1b2f 100644 --- a/aurora/menus/immune.py +++ b/aurora/menus/immune.py @@ -1,20 +1,24 @@ from discord import ButtonStyle, Interaction, Message, ui +from discord.errors import NotFound from redbot.core import commands from redbot.core.utils.chat_formatting import error -from aurora.utilities.config import config -from aurora.utilities.factory import immune_embed +from ..utilities.config import config +from ..utilities.factory import immune_embed class Immune(ui.View): - def __init__(self, ctx: commands.Context, message: Message, timeout: int = None): + def __init__(self, ctx: commands.Context, message: Message, timeout: int | None = None): super().__init__() self.ctx = ctx self.message = message self.timeout = timeout async def on_timeout(self): - await self.message.edit(view=None) + try: + await self.message.edit(view=None) + except NotFound: + pass @ui.select(cls=ui.RoleSelect, placeholder="Select a role", min_values=0, max_values=25) async def immune_select(self, interaction: Interaction, select: ui.RoleSelect): @@ -23,7 +27,7 @@ class Immune(ui.View): return await interaction.response.defer() async with config.guild(self.ctx.guild).immune_roles() as immune_roles: - immune_roles: list # type hint + immune_roles: list # type hint for value in select.values: if value.id in immune_roles: immune_roles.remove(value.id) @@ -32,7 +36,7 @@ class Immune(ui.View): await interaction.message.edit(embed=await immune_embed(self.ctx)) @ui.button(label="Clear", style=ButtonStyle.red, row=1) - async def clear(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def clear(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: await interaction.response.send_message(error("You must have the manage guild permission to clear the guild's immune roles."), ephemeral=True) return @@ -41,7 +45,7 @@ class Immune(ui.View): await interaction.message.edit(embed=await immune_embed(self.ctx)) @ui.button(label="Close", style=ButtonStyle.gray) - async def close(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def close(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: await interaction.response.send_message(error("You can't do that!"), ephemeral=True) return diff --git a/aurora/menus/overrides.py b/aurora/menus/overrides.py index c5d0e68..23d83d5 100644 --- a/aurora/menus/overrides.py +++ b/aurora/menus/overrides.py @@ -1,23 +1,27 @@ from discord import ButtonStyle, Interaction, Message, ui +from discord.errors import NotFound from redbot.core import commands -from aurora.utilities.config import config -from aurora.utilities.factory import overrides_embed -from aurora.utilities.utils import create_pagesize_options +from ..utilities.config import config +from ..utilities.factory import overrides_embed +from ..utilities.utils import create_pagesize_options class Overrides(ui.View): - def __init__(self, ctx: commands.Context, message: Message, timeout: int = None): + def __init__(self, ctx: commands.Context, message: Message, timeout: int | None = None): super().__init__() self.ctx = ctx self.message = message self.timeout = timeout async def on_timeout(self): - await self.message.edit(view=None) + try: + await self.message.edit(view=None) + except NotFound: + pass @ui.button(label="Auto Evidence Format", style=ButtonStyle.green, row=0) - async def auto_evidenceformat(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def auto_evidenceformat(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if self.ctx.author != interaction.user: await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True) return @@ -32,7 +36,7 @@ class Overrides(ui.View): await interaction.message.edit(embed=await overrides_embed(self.ctx)) @ui.button(label="Ephemeral", style=ButtonStyle.green, row=0) - async def ephemeral(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def ephemeral(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if self.ctx.author != interaction.user: await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True) return @@ -47,7 +51,7 @@ class Overrides(ui.View): await interaction.message.edit(embed=await overrides_embed(self.ctx)) @ui.button(label="Inline", style=ButtonStyle.green, row=0) - async def inline(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + async def inline(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument if self.ctx.author != interaction.user: await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True) return @@ -62,7 +66,11 @@ class Overrides(ui.View): await interaction.message.edit(embed=await overrides_embed(self.ctx)) @ui.select(placeholder="Inline Pagesize", options=create_pagesize_options(), row=1) - async def inline_pagesize(self, interaction: Interaction, select: ui.Select,): + async def inline_pagesize( + self, + interaction: Interaction, + select: ui.Select, + ): if self.ctx.author != interaction.user: await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True) return @@ -74,7 +82,11 @@ class Overrides(ui.View): await interaction.message.edit(embed=await overrides_embed(self.ctx)) @ui.select(placeholder="Pagesize", options=create_pagesize_options(), row=2) - async def pagesize(self, interaction: Interaction, select: ui.Select,): + async def pagesize( + self, + interaction: Interaction, + select: ui.Select, + ): if self.ctx.author != interaction.user: await interaction.response.send_message("You cannot change this setting for other users.", ephemeral=True) return diff --git a/aurora/menus/types.py b/aurora/menus/types.py new file mode 100644 index 0000000..ef55887 --- /dev/null +++ b/aurora/menus/types.py @@ -0,0 +1,71 @@ +from discord import ButtonStyle, Interaction, Message, ui +from discord.errors import NotFound +from redbot.core import commands + +from ..models.type import Type +from ..utilities.config import config +from ..utilities.factory import type_embed + + +class Types(ui.View): + def __init__(self, ctx: commands.Context, message: Message, moderation_type: Type, timeout: int | None = None): + super().__init__() + self.ctx = ctx + self.message = message + self.type = moderation_type + self.timeout = timeout + + async def on_timeout(self): + try: + await self.message.edit(view=None) + except NotFound: + pass + + @ui.button(label="Show in History", style=ButtonStyle.green, row=0) + async def show_in_history(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: + await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) + return + await interaction.response.defer() + current_setting = await config.custom("types", interaction.guild.id, self.type.key).show_in_history() + await config.custom("types", interaction.guild.id, self.type.key).show_in_history.set(not current_setting) + await interaction.message.edit(embed=await type_embed(self.ctx, self.type)) + + @ui.button(label="Show Moderator", style=ButtonStyle.green, row=0) + async def show_moderator(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: + await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) + return + await interaction.response.defer() + current_setting = await config.custom("types", interaction.guild.id, self.type.key).show_moderator() + await config.custom("types", interaction.guild.id, self.type.key).show_moderator.set(not current_setting) + await interaction.message.edit(embed=await type_embed(self.ctx, self.type)) + + @ui.button(label="Use Discord Permissions", style=ButtonStyle.green, row=0) + async def use_discord_permissions(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: + await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) + return + await interaction.response.defer() + current_setting = await config.custom("types", interaction.guild.id, self.type.key).use_discord_permissions() + await config.custom("types", interaction.guild.id, self.type.key).use_discord_permissions.set(not current_setting) + await interaction.message.edit(embed=await type_embed(self.ctx, self.type)) + + @ui.button(label="DM Users", style=ButtonStyle.green, row=0) + async def dm_users(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: + await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) + return + await interaction.response.defer() + current_setting = await config.custom("types", interaction.guild.id, self.type.key).dm_users() + await config.custom("types", interaction.guild.id, self.type.key).dm_users.set(not current_setting) + await interaction.message.edit(embed=await type_embed(self.ctx, self.type)) + + @ui.button(label="Reset", style=ButtonStyle.red, row=1) + async def reset(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument + if not interaction.user.guild_permissions.manage_guild and not interaction.user.guild_permissions.administrator: + await interaction.response.send_message("You must have the manage guild permission to change this setting.", ephemeral=True) + return + await interaction.response.defer() + await config.custom("types", interaction.guild.id, self.type.key).clear() + await interaction.message.edit(embed=await type_embed(self.ctx, self.type)) diff --git a/aurora/models/base.py b/aurora/models/base.py new file mode 100644 index 0000000..86fa59a --- /dev/null +++ b/aurora/models/base.py @@ -0,0 +1,34 @@ +from typing import Any, Optional + +from discord import Guild +from pydantic import BaseModel, ConfigDict +from redbot.core.bot import Red + + +class AuroraBaseModel(BaseModel): + """Base class for all models in Aurora.""" + + model_config = ConfigDict(ignored_types=(Red,), arbitrary_types_allowed=True) + bot: Red + + def dump(self) -> dict: + return self.model_dump(exclude={"bot"}) + + def to_json(self, indent: int | None = None, file: Any | None = None, **kwargs) -> str: + from ..utilities.json import dump, dumps # pylint: disable=cyclic-import + + return dump(self.dump(), file, indent=indent, **kwargs) if file else dumps(self.dump(), indent=indent, **kwargs) + + +class AuroraGuildModel(AuroraBaseModel): + """Subclass of AuroraBaseModel that includes a guild_id attribute and a guild attribute.""" + + model_config = ConfigDict(ignored_types=(Red, Guild), arbitrary_types_allowed=True) + guild_id: int + guild: Optional[Guild] = None + + def dump(self) -> dict: + return self.model_dump(exclude={"bot", "guild_id", "guild"}) + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} guild_id={self.guild_id}>" diff --git a/aurora/models/change.py b/aurora/models/change.py new file mode 100644 index 0000000..f6a86a0 --- /dev/null +++ b/aurora/models/change.py @@ -0,0 +1,79 @@ +import json +from datetime import datetime, timedelta +from typing import Literal, Optional + +from redbot.core.bot import Red + +from ..utilities.utils import timedelta_from_string +from .base import AuroraBaseModel +from .partials import PartialUser + + +class Change(AuroraBaseModel): + type: Literal["ORIGINAL", "RESOLVE", "EDIT"] + timestamp: datetime + user_id: int + reason: Optional[str] = None + duration: Optional[timedelta] = None + end_timestamp: Optional[datetime] = None + + @property + def unix_timestamp(self) -> int: + return int(self.timestamp.timestamp()) + + @property + def unix_end_timestamp(self) -> Optional[int]: + if self.end_timestamp: + return int(self.end_timestamp.timestamp()) + return None + + def __str__(self): + return f"{self.type} {self.user_id} {self.reason}" + + def __repr__(self) -> str: + attrs = [ + ("type", self.type), + ("timestamp", self.timestamp), + ("user_id", self.user_id), + ("reason", self.reason), + ("duration", self.duration), + ("end_timestamp", self.end_timestamp), + ] + joined = " ".join(f"{key}={value!r}" for key, value in attrs) + return f"<{self.__class__.__name__} {joined}>" + + async def get_user(self) -> "PartialUser": + return await PartialUser.from_id(self.bot, self.user_id) + + @classmethod + def from_dict(cls, bot: Red, data: dict) -> "Change": + if isinstance(data, str): + data = json.loads(data) + if data.get("duration") and not isinstance(data["duration"], timedelta) and not data["duration"] == "NULL": + duration = timedelta_from_string(data["duration"]) + elif data.get("duration") and isinstance(data["duration"], timedelta): + duration = data["duration"] + else: + duration = None + + if data.get("end_timestamp") and not isinstance(data["end_timestamp"], datetime): + end_timestamp = datetime.fromtimestamp(data["end_timestamp"]) + elif data.get("end_timestamp") and isinstance(data["end_timestamp"], datetime): + end_timestamp = data["end_timestamp"] + else: + end_timestamp = None + + if not isinstance(data["timestamp"], datetime): + timestamp = datetime.fromtimestamp(data["timestamp"]) + else: + timestamp = data["timestamp"] + + try: + data["user_id"] = int(data["user_id"]) + except ValueError: + data["user_id"] = 0 + + data.update({"timestamp": timestamp, "end_timestamp": end_timestamp, "duration": duration}) + if "bot" in data: + del data["bot"] + return cls(bot=bot, **data) diff --git a/aurora/models/moderation.py b/aurora/models/moderation.py new file mode 100644 index 0000000..da48ba2 --- /dev/null +++ b/aurora/models/moderation.py @@ -0,0 +1,576 @@ +import json +import sqlite3 +from datetime import datetime, timedelta +from time import time +from typing import Dict, Iterable, List, Optional, Tuple, Union + +import discord +from aiosqlite import Connection, Cursor, OperationalError, Row +from aiosqlite import connect as aiosqlite_connect +from redbot.core import data_manager +from redbot.core.bot import Red + +from ..utilities.logger import logger +from ..utilities.utils import timedelta_to_string +from .base import AuroraGuildModel +from .change import Change +from .partials import PartialChannel, PartialRole, PartialUser +from .type import Type, type_registry + + +class Moderation(AuroraGuildModel): + """This class represents a moderation case in the database. + + Attributes: + bot (Red): The bot instance. + guild (discord.Guild): The guild the case belongs to. + moderation_id (int): The ID of the moderation case. + timestamp (datetime): The timestamp of the case. + moderation_type (Type): The type of moderation case. + target_type (str): The type of target. Should be either `user` or `channel`. + target_id (int): The ID of the target. + moderator_id (int): The ID of the moderator who issued the case. + role_id (int): The ID of the role, if applicable. + duration (timedelta): The duration of the case, if applicable. + end_timestamp (datetime): The end timestamp of the case, if applicable. + reason (str): The reason for the case. + resolved (bool): Whether the case is resolved. + resolved_by (int): The ID of the user who resolved the case. + resolve_reason (str): The reason the case was resolved. + expired (bool): Whether the case is expired. + changes (List[Change]): A list of changes to the case. + metadata (Dict): A dictionary of metadata stored with the case. + + Properties: + id (int): The ID of the case. + type (Type): The type of the case. + unix_timestamp (int): The timestamp of the case as a Unix timestamp. + + Methods: + get_moderator: Gets the moderator who issued the case. + get_target: Gets the target of the case. + get_resolved_by: Gets the user who resolved the case. + get_role: Gets the role, if applicable. + resolve: Resolves the case. + update: Updates the case in the database. + + Class Methods: + from_dict: Creates a `Moderation` object from a dictionary. + from_result: Creates a `Moderation` object from a database result. + execute: Executes a query on the database. + get_latest: Gets the latest cases from the database. + get_next_case_number: Gets the next case number to use. + find_by_id: Finds a case by its ID. + find_by_target: Finds cases by the target. + find_by_moderator: Finds cases by the moderator. + log: Logs a moderation case in the database. + + Static Methods: + connect: Connects to the SQLite database. + """ + + moderation_id: int + timestamp: datetime + moderation_type: Type + target_type: str + target_id: int + moderator_id: int + role_id: Optional[int] = None + duration: Optional[timedelta] = None + end_timestamp: Optional[datetime] = None + reason: Optional[str] = None + resolved: bool + resolved_by: Optional[int] = None + resolve_reason: Optional[str] = None + expired: bool + changes: List["Change"] + metadata: Dict + + @property + def id(self) -> int: + return self.moderation_id + + @property + def type(self) -> Type: + return self.moderation_type + + @property + def unix_timestamp(self) -> int: + return int(self.timestamp.timestamp()) + + async def get_moderator(self) -> "PartialUser": + return await PartialUser.from_id(self.bot, self.moderator_id) + + async def get_target(self) -> Union["PartialUser", "PartialChannel"]: + if self.target_type.lower() == "user": + return await PartialUser.from_id(self.bot, self.target_id) + return await PartialChannel.from_id(self.bot, self.target_id, self.guild) + + async def get_resolved_by(self) -> Optional["PartialUser"]: + if self.resolved_by: + return await PartialUser.from_id(self.bot, self.resolved_by) + return None + + async def get_role(self) -> Optional["PartialRole"]: + if self.role_id: + return await PartialRole.from_id(self.bot, self.guild, self.role_id) + return None + + def __str__(self) -> str: + return f"{self.moderation_type} {self.target_type} {self.target_id} {self.reason}" + + def __int__(self) -> int: + return self.moderation_id + + def __repr__(self) -> str: + attrs = [ + ("guild_id", self.guild_id), + ("moderation_id", self.moderation_id), + ("timestamp", self.timestamp), + ("type", self.type), + ("target_type", self.target_type), + ("target_id", self.target_id), + ("moderator_id", self.moderator_id), + ("role_id", self.role_id), + ("duration", self.duration), + ("end_timestamp", self.end_timestamp), + ("reason", self.reason), + ("resolved", self.resolved), + ("resolved_by", self.resolved_by), + ("resolve_reason", self.resolve_reason), + ("expired", self.expired), + ("changes", self.changes), + ("metadata", self.metadata), + ] + joined = " ".join(f"{key}={value!r}" for key, value in attrs) + return f"<{self.__class__.__name__} {joined}>" + + async def resolve(self, resolved_by: int, reason: str) -> Tuple[bool, str]: + if self.resolved: + raise ValueError("Case is already resolved!") + + self.resolved = True + self.resolved_by = resolved_by + self.resolve_reason = reason + + success, msg = await self.type.resolve_handler(moderation=self, reason=reason) + + if not self.changes: + self.changes.append( + Change.from_dict( + self.bot, + { + "type": "ORIGINAL", + "timestamp": self.timestamp, + "reason": self.reason, + "user_id": self.moderator_id, + "duration": self.duration, + "end_timestamp": self.end_timestamp, + }, + ) + ) + self.changes.append( + Change.from_dict( + self.bot, + { + "type": "RESOLVE", + "timestamp": datetime.now(), + "reason": reason, + "user_id": resolved_by, + }, + ) + ) + + await self.update() + return success, msg + + async def update(self) -> None: + from ..utilities.json import dumps + + query = f"UPDATE moderation_{self.guild_id} SET timestamp = ?, moderation_type = ?, target_type = ?, moderator_id = ?, role_id = ?, duration = ?, end_timestamp = ?, reason = ?, resolved = ?, resolved_by = ?, resolve_reason = ?, expired = ?, changes = ?, metadata = ? WHERE moderation_id = ?;" + + await self.execute( + query, + ( + self.timestamp.timestamp(), + self.moderation_type.key, + self.target_type, + self.moderator_id, + self.role_id, + timedelta_to_string(self.duration) if self.duration else None, + self.end_timestamp.timestamp() if self.end_timestamp else None, + self.reason, + self.resolved, + self.resolved_by, + self.resolve_reason, + self.expired, + dumps(self.changes), + dumps(self.metadata), + self.moderation_id, + ), + ) + + logger.verbose( + "Row updated in moderation_%s!\n%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s", + self.moderation_id, + self.guild_id, + self.timestamp.timestamp(), + self.moderation_type.key, + self.target_type, + self.moderator_id, + self.role_id, + timedelta_to_string(self.duration) if self.duration else None, + self.end_timestamp.timestamp() if self.end_timestamp else None, + self.reason, + self.resolved, + self.resolved_by, + self.resolve_reason, + self.expired, + dumps(self.changes), + dumps(self.metadata), + ) + + @classmethod + async def from_dict(cls, bot: Red, data: dict) -> "Moderation": + if data.get("guild_id"): + try: + guild = bot.get_guild(data["guild_id"]) + if not guild: + guild = await bot.fetch_guild(data["guild_id"]) + except (discord.Forbidden, discord.HTTPException): + guild = None + data.update({"guild": guild}) + return cls(bot=bot, **data) + + @classmethod + async def from_result(cls, bot: Red, result: Iterable, guild_id: int) -> "Moderation": + if result[7] is not None and result[7] != "NULL": + try: + hours, minutes, seconds = map(int, result[7].split(":")) + duration = timedelta(hours=hours, minutes=minutes, seconds=seconds) + except ValueError as e: + logger.error("Error parsing duration for case %s: %s", result[0], result[7]) + raise e + else: + duration = None + + if result[14] is not None: + changes = json.loads(result[14]) + change_obj_list = [] + if changes: + for change in changes: + change_obj_list.append(Change.from_dict(bot=bot, data=change)) + + if result[15] is not None: + metadata = json.loads(result[15]) + else: + metadata = {} + + moderation_type = str.lower(result[2]) + if moderation_type in type_registry: + moderation_type = type_registry[moderation_type] + else: + logger.error("Unknown moderation type in case %s: %s", result[0], result[2]) + + case = { + "moderation_id": int(result[0]), + "guild_id": int(guild_id), + "timestamp": datetime.fromtimestamp(result[1]), + "moderation_type": moderation_type, + "target_type": str(result[3]), + "target_id": int(result[4]), + "moderator_id": int(result[5]), + "role_id": int(result[6]) if result[6] is not None else None, + "duration": duration, + "end_timestamp": datetime.fromtimestamp(result[8]) if result[8] is not None else None, + "reason": result[9], + "resolved": bool(result[10]), + "resolved_by": result[11], + "resolve_reason": result[12], + "expired": bool(result[13]), + "changes": change_obj_list, + "metadata": metadata if metadata else {}, + } + return await cls.from_dict(bot=bot, data=case) + + @staticmethod + async def connect() -> Connection: + """Connects to the SQLite database, and returns a connection object.""" + try: + connection = await aiosqlite_connect(database=data_manager.cog_data_path(raw_name="Aurora") / "aurora.db") + return connection + + except OperationalError as e: + logger.error("Unable to access the SQLite database!\nError:\n%s", e.msg) + raise ConnectionRefusedError(f"Unable to access the SQLite Database!\n{e.msg}") from e + + @classmethod + async def execute(cls, query: str, parameters: tuple | None = None, bot: Red | None = None, guild_id: int | None = None, cursor: Cursor | None = None, return_obj: bool = True) -> Union[Tuple["Moderation"], Iterable[Row]]: + """Executes a query on the database. + + Arguments: + query (str): The query to execute. + parameters (tuple): The parameters to pass to the query. + bot (Red): The bot instance. + guild_id (int): The ID of the guild to execute the query on. + cursor (Cursor): The cursor to use for the query. + return_obj (bool): Whether to return the case object(s). Defaults to `True`. If `False`, returns a `Iterable` of `aiosqlite.Row` objects. + Returns: The result of the query, either as a `Tuple` of `Moderation` objects or an `Iterable` of `aiosqlite.Row` objects. + """ + logger.trace('Executing query: "%s" with parameters "%s"', query, parameters) + if not parameters: + parameters = () + if not cursor: + no_cursor = True + database = await cls.connect() + cursor = await database.cursor() + else: + no_cursor = False + + try: + await cursor.execute(query, parameters) + except OperationalError as e: + logger.error('Error executing query: "%s" with parameters "%s"\nError:\n%s', query, parameters, e) + raise OperationalError(f'Error executing query: "{query}" with parameters "{parameters}"') from e + results = await cursor.fetchall() + await database.commit() + if no_cursor: + await cursor.close() + await database.close() + + if results and return_obj and bot and guild_id: + cases = [] + for result in results: + if result[0] == 0: + continue + case = await cls.from_result(bot=bot, result=result, guild_id=guild_id) + cases.append(case) + return tuple(cases) + return results + + @classmethod + async def get_latest(cls, bot: Red, guild_id: int, before: datetime | None = None, after: datetime | None = None, limit: int | None = None, offset: int = 0, types: Iterable[Type] | None = None, expired: bool | None = None, cursor: Cursor | None = None) -> Tuple["Moderation"]: + params = [] + query = f"SELECT * FROM moderation_{guild_id}" + conditions = [] + + if types: + conditions.append(f"moderation_type IN ({', '.join(['?' for _ in types])})") + params.extend([t.key for t in types]) + if before: + conditions.append("timestamp < ?") + params.append(int(before.timestamp())) + if after: + conditions.append("timestamp > ?") + params.append(int(after.timestamp())) + if expired is not None: + conditions.append("expired = ?") + params.append(int(expired)) + + if conditions: + query += " WHERE " + " AND ".join(conditions) + + query += " ORDER BY moderation_id DESC" + + if limit: + query += " LIMIT ? OFFSET ?" + params.extend((limit, offset)) + query += ";" + return await cls.execute(bot=bot, guild_id=guild_id, query=query, parameters=tuple(params) if params else (), cursor=cursor) + + @classmethod + async def get_next_case_number(cls, bot: Red, guild_id: int, cursor: Cursor | None = None) -> int: + result = await cls.get_latest(bot=bot, guild_id=guild_id, cursor=cursor, limit=1) + return (result[0].moderation_id + 1) if result else 1 + + @classmethod + async def find_by_id(cls, bot: Red, moderation_id: int, guild_id: int, cursor: Cursor | None = None) -> "Moderation": + query = f"SELECT * FROM moderation_{guild_id} WHERE moderation_id = ?;" + case = await cls.execute(bot=bot, guild_id=guild_id, query=query, parameters=(moderation_id,), cursor=cursor) + if case: + return case[0] + raise ValueError(f"Case {moderation_id} not found in moderation_{guild_id}!") + + @classmethod + async def find_by_target(cls, bot: Red, guild_id: int, target: int, before: datetime = None, after: datetime = None, types: Iterable[Type] | None = None, expired: bool | None = None, cursor: Cursor | None = None) -> Tuple["Moderation"]: + query = f"SELECT * FROM moderation_{guild_id} WHERE target_id = ?" + params = [target] + if types: + query += f" AND moderation_type IN ({', '.join(['?' for _ in types])})" + for t in types: + params.append(t.key) + if before: + query += " AND timestamp < ?" + params.append(int(before.timestamp())) + if after: + query += " AND timestamp > ?" + params.append(int(after.timestamp())) + if expired is not None: + query += " AND expired = ?" + params.append(int(expired)) + + query += " ORDER BY moderation_id DESC;" + + return await cls.execute(bot=bot, guild_id=guild_id, query=query, parameters=params, cursor=cursor) + + @classmethod + async def find_by_moderator(cls, bot: Red, guild_id: int, moderator: int, before: datetime = None, after: datetime = None, types: Iterable[Type] | None = None, expired: bool | None = None, cursor: Cursor | None = None) -> Tuple["Moderation"]: + query = f"SELECT * FROM moderation_{guild_id} WHERE moderator_id = ?" + params = [moderator] + if types: + query += f" AND moderation_type IN ({', '.join(['?' for _ in types])})" + for t in types: + params.append(t.key) + if before: + query += " AND timestamp < ?" + params.append(int(before.timestamp())) + if after: + query += " AND timestamp > ?" + params.append(int(after.timestamp())) + if expired is not None: + query += " AND expired = ?" + params.append(int(expired)) + + query += " ORDER BY moderation_id DESC;" + + return await cls.execute(bot=bot, guild_id=guild_id, query=query, parameters=params, cursor=cursor) + + @classmethod + async def log( + cls, + bot: Red, + guild_id: int, + moderator_id: int, + moderation_type: Type, + target_type: str, + target_id: int, + role_id: int | None = None, + duration: timedelta | None = None, + reason: str | None = None, + database: sqlite3.Connection | None = None, + timestamp: datetime | None = None, + resolved: bool = False, + resolved_by: int | None = None, + resolved_reason: str | None = None, + expired: bool | None = None, + changes: list | None = None, + metadata: dict | None = None, + return_obj: bool = True, + ) -> Union["Moderation", int]: + """Logs a moderation case in the database. + + Args: + bot (Red): The bot instance. + guild_id (int): The ID of the guild to log the case in. + moderator_id (int): The ID of the moderator who issued the case. + moderation_type (Type): The type of moderation case. See `aurora.models.moderation_types` for the built-in options. + target_type (str): The type of target. Should be either `user` or `channel`. + target_id (int): The ID of the target. + role_id (int): The ID of the role, if applicable. + duration (timedelta): The duration of the case, if applicable. + reason (str): The reason for the case. + database (sqlite3.Connection): The database connection to use to log the case. A connection will be automatically created if not provided. + timestamp (datetime): The timestamp of the case. Will be automatically generated if not provided. + resolved (bool): Whether the case is resolved. + resolved_by (int): The ID of the user who resolved the case. + resolved_reason (str): The reason the case was resolved. + expired (bool): Whether the case is expired. + changes (list): A list of changes to log. You usually shouldn't pass this, as it's automatically generated by the `/edit` and `/resolve` commands. + metadata (dict): A dictionary of metadata to store with the case. + return_obj (bool): Whether to return the case object. Defaults to `True`. If `False`, returns the case ID. + + Returns: + Union[Moderation, int]: The `Moderation` object if `return_obj` is `True`, otherwise the case ID. + """ + from ..utilities.json import dumps + + if not timestamp: + timestamp = datetime.fromtimestamp(time()) + elif not isinstance(timestamp, datetime): + timestamp = datetime.fromtimestamp(timestamp) + + if duration == "NULL": + duration = None + + if duration is not None: + end_timestamp = timestamp + duration + else: + duration = None + end_timestamp = None + + if not expired: + if end_timestamp: + expired = bool(timestamp > end_timestamp) + else: + expired = False + + if reason == "NULL": + reason = None + + if resolved_by in ["NULL", "?"]: + resolved_by = None + + if resolved_reason == "NULL": + resolved_reason = None + + if role_id == 0: + role_id = None + + if not database: + database = await cls.connect() + close_db = True + else: + close_db = False + + moderation_id = await cls.get_next_case_number(bot=bot, guild_id=guild_id) + + case = { + "moderation_id": moderation_id, + "timestamp": timestamp.timestamp(), + "moderation_type": moderation_type.key, + "target_type": target_type, + "target_id": target_id, + "moderator_id": moderator_id, + "role_id": role_id, + "duration": timedelta_to_string(duration) if duration else None, + "end_timestamp": end_timestamp.timestamp() if end_timestamp else None, + "reason": reason, + "resolved": resolved, + "resolved_by": resolved_by, + "resolve_reason": resolved_reason, + "expired": expired, + "changes": dumps(changes), + "metadata": dumps(metadata), + } + + sql = f"INSERT INTO `moderation_{guild_id}` (moderation_id, timestamp, moderation_type, target_type, target_id, moderator_id, role_id, duration, end_timestamp, reason, resolved, resolved_by, resolve_reason, expired, changes, metadata) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + await database.execute(sql, tuple(case.values())) + + await database.commit() + if close_db: + await database.close() + + logger.verbose( + "Row inserted into moderation_%s!\n%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s", + guild_id, + case["moderation_id"], + case["timestamp"], + case["moderation_type"], + case["target_type"], + case["target_id"], + case["moderator_id"], + case["role_id"], + case["duration"], + case["end_timestamp"], + case["reason"], + case["resolved"], + case["resolved_by"], + case["resolve_reason"], + case["expired"], + case["changes"], + case["metadata"], + ) + + if return_obj: + return await cls.find_by_id(bot=bot, moderation_id=moderation_id, guild_id=guild_id) + return moderation_id diff --git a/aurora/models/moderation_types.py b/aurora/models/moderation_types.py new file mode 100644 index 0000000..9db3b3b --- /dev/null +++ b/aurora/models/moderation_types.py @@ -0,0 +1,964 @@ +# pylint: disable=abstract-method +from datetime import timedelta +from math import ceil +from time import time +from typing import Tuple + +from discord import AllowedMentions, File, Interaction, Member, Object, Role, TextChannel, User +from discord.abc import Messageable +from discord.errors import Forbidden, HTTPException, NotFound +from redbot.core import app_commands, commands +from redbot.core.bot import Red +from redbot.core.commands.converter import parse_relativedelta, parse_timedelta +from redbot.core.utils.chat_formatting import bold, error, humanize_timedelta, inline + +from ..utilities.config import config +from ..utilities.factory import message_factory, resolve_factory +from ..utilities.logger import logger +from ..utilities.utils import get_footer_image, log, send_evidenceformat, timedelta_from_relativedelta +from .moderation import Moderation +from .type import Type, type_registry + + +def get_icon(bot: Red) -> File: + cog = bot.get_cog("Aurora") + if cog: + return get_footer_image(cog) + raise ValueError("Aurora cog not found. How was this managed?") + + +class Note(Type): + key = "note" + string = "note" + verb = "noted" + + def void(self) -> None: + return None + + @classmethod + async def handler(cls, ctx: commands.Context, target: Member | User, silent: bool, reason: str) -> "Note": + response = await ctx.send(content=f"{target.mention} has {cls.embed_desc}{cls.verb}!\n**Reason** - `{reason}`") + + if silent is False: + try: + embed = await message_factory( + bot=ctx.bot, + color=await ctx.embed_color(), + guild=ctx.guild, + moderator=ctx.author, + reason=reason, + moderation_type=cls(), + response=response, + ) + await target.send(embed=embed, file=get_icon(ctx.bot)) + except HTTPException: + pass + + moderation = await Moderation.log( + bot=ctx.bot, + guild_id=ctx.guild.id, + moderator_id=ctx.author.id, + moderation_type=cls(), + target_type="user", + target_id=target.id, + role_id=None, + duration=None, + reason=reason, + ) + await response.edit(content=f"{target.mention} has {cls.embed_desc}{cls.verb}! (Case `#{moderation.id:,}`)\n**Reason** - `{reason}`") + await log(ctx=ctx, moderation_id=moderation.id) + await send_evidenceformat(ctx=ctx, moderation_id=moderation.id) + return cls() + + @classmethod + async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]: + if await config.guild(moderation.guild).dm_users() is True: + try: + target = await moderation.bot.fetch_user(moderation.target_id) + embed = await resolve_factory(moderation=moderation, reason=reason) + await target.send(embed=embed, file=get_icon(bot=moderation.bot)) + except (Forbidden, HTTPException, NotFound): + pass + return True, "" + + +class Warn(Type): + key = "warn" + string = "warn" + verb = "warned" + + def void(self) -> None: + return None + + @classmethod + async def handler(cls, ctx: commands.Context, target: Member | User, silent: bool, reason: str) -> "Warn": + response = await ctx.send(content=f"{target.mention} has {cls.embed_desc}{cls.verb}!\n**Reason** - `{reason}`") + + if silent is False: + try: + embed = await message_factory( + bot=ctx.bot, + color=await ctx.embed_color(), + guild=ctx.guild, + moderator=ctx.author, + reason=reason, + moderation_type=cls(), + response=response, + ) + await target.send(embed=embed, file=get_icon(ctx.bot)) + except HTTPException: + pass + + moderation = await Moderation.log( + bot=ctx.bot, + guild_id=ctx.guild.id, + moderator_id=ctx.author.id, + moderation_type=cls(), + target_type="user", + target_id=target.id, + role_id=None, + duration=None, + reason=reason, + ) + await response.edit(content=f"{target.mention} has {cls.embed_desc}{cls.verb}! (Case `#{moderation.id:,}`)\n**Reason** - `{reason}`") + await log(ctx=ctx, moderation_id=moderation.id) + await send_evidenceformat(ctx=ctx, moderation_id=moderation.id) + return cls() + + @classmethod + async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]: + if await config.guild(moderation.guild).dm_users() is True: + try: + target = await moderation.bot.fetch_user(moderation.target_id) + embed = await resolve_factory(moderation=moderation, reason=reason) + await target.send(embed=embed, file=get_icon(bot=moderation.bot)) + except (Forbidden, HTTPException, NotFound): + pass + return True, "" + + +class AddRole(Type): + key = "addrole" + string = "addrole" + verb = "added a role to" + embed_desc = "been given the " + + def void(self) -> None: + return None + + @classmethod + async def handler(cls, ctx: commands.Context, target: Member, role: Role, silent: bool, duration: str | None = None, reason: str | None = None): + addrole_whitelist = await config.guild(ctx.guild).addrole_whitelist() + + if not addrole_whitelist: + await ctx.send( + content=error("There are no whitelisted roles set for this server!"), + ephemeral=True, + ) + return + + if duration is not None: + try: + parsed_time = parse_relativedelta(argument=duration) + if parsed_time is None: + raise commands.BadArgument() + parsed_time = timedelta_from_relativedelta(relativedelta=parsed_time) + except (commands.BadArgument, ValueError): + await ctx.send(content=error(text="Please provide a valid duration!"), ephemeral=True) + return cls() + else: + parsed_time = None + + if role.id not in addrole_whitelist: + await ctx.send(content=error("That role isn't whitelisted!"), ephemeral=True) + return + + if role.id in [user_role.id for user_role in target.roles]: + await ctx.send( + content=error(f"{target.mention} already has this role!"), + ephemeral=True, + ) + return + + response = await ctx.send(content=f"{target.mention} has {cls.embed_desc}{role.mention} role{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time else ''}!\n**Reason** - `{reason}`") + + if silent is False: + try: + embed = await message_factory( + bot=ctx.bot, + color=await ctx.embed_color(), + guild=ctx.guild, + moderator=ctx.author, + reason=reason, + moderation_type=cls(), + response=response, + duration=parsed_time, + ) + await target.send(embed=embed, file=get_icon(ctx.bot)) + except HTTPException: + pass + + await target.add_roles( + role, + reason=f"Role added by {ctx.author.id}{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time else ''} for: {reason}", + ) + + moderation = await Moderation.log( + bot=ctx.bot, + guild_id=ctx.guild.id, + moderator_id=ctx.author.id, + moderation_type=cls(), + target_type="user", + target_id=target.id, + role_id=role.id, + duration=parsed_time, + reason=reason, + ) + await response.edit( + content=f"{target.mention} has {cls.embed_desc}{role.mention} role{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time else ''}! (Case `#{moderation.id:,}`)\n**Reason** - `{reason}`", + ) + await log(ctx=ctx, moderation_id=moderation.id) + await send_evidenceformat(ctx=ctx, moderation_id=moderation.id) + return cls() + + @classmethod + async def duration_edit_handler(cls, interaction: Interaction, old_moderation: Moderation, new_moderation: Moderation) -> bool: # pylint: disable=unused-argument + return True + + @classmethod + async def expiry_handler(cls, moderation: Moderation) -> int: + try: + target = moderation.guild.get_member(moderation.target_id) + if not target: + try: + target = await moderation.guild.fetch_member(moderation.target_id) + except NotFound: + return 0 + + await target.remove_roles(Object(moderation.role_id), reason=f"Automatic role removal from case #{moderation.id}") + + if await config.guild(moderation.guild).dm_users() is True: + try: + embed = await message_factory( + bot=moderation.bot, + color=await moderation.bot.get_embed_color(moderation.guild.channels[0]), + guild=moderation.guild, + reason=f"Automatic role removal from case #{moderation.id}", + moderation_type=type_registry["removerole"], + moderator=None, + duration=None, + response=None, + case=False, + ) + await target.send(embed=embed, file=get_icon(bot=moderation.bot)) + except HTTPException: + pass + logger.trace( + "Removed role %s from %s (%s)", + moderation.role_id, + target.name, + target.id, + ) + return 1 + except ( + NotFound, + Forbidden, + HTTPException, + ) as e: + logger.error( + "Removing the role %s from user %s failed due to: \n%s", + moderation.role_id, + moderation.target_id, + e, + ) + return 0 + + @classmethod + async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]: + try: + target = await moderation.guild.fetch_member(moderation.target_id) + await target.remove_roles(Object(moderation.role_id), reason=reason) + if await config.guild(moderation.guild).dm_users() is True: + try: + embed = await resolve_factory(moderation=moderation, reason=reason) + await target.send(embed=embed, file=get_icon(bot=moderation.bot)) + except HTTPException: + pass + logger.trace( + "Removed role %s from %s (%s)", + moderation.role_id, + target.name, + target.id, + ) + return True, "" + except (NotFound, Forbidden, HTTPException) as e: + logger.error( + "Failed to remove role %s from user %s (%s)\n%s", + moderation.role_id, + target.name, + target.id, + e, + ) + return False, "Failed to remove role from user." + + +class RemoveRole(Type): + key = "removerole" + string = "removerole" + verb = "removed a role from" + embed_desc = "had the " + + def void(self) -> None: + return None + + @classmethod + async def handler(cls, ctx: commands.Context, target: Member, role: Role, silent: bool, duration: str | None = None, reason: str | None = None): + addrole_whitelist = await config.guild(ctx.guild).addrole_whitelist() + + if not addrole_whitelist: + await ctx.send( + content=error("There are no whitelisted roles set for this server!"), + ephemeral=True, + ) + return + + if duration is not None: + try: + parsed_time = parse_relativedelta(argument=duration) + if parsed_time is None: + raise commands.BadArgument() + parsed_time = timedelta_from_relativedelta(relativedelta=parsed_time) + except (commands.BadArgument, ValueError): + await ctx.send(content=error(text="Please provide a valid duration!"), ephemeral=True) + return cls() + else: + parsed_time = None + + if role.id not in addrole_whitelist: + await ctx.send(content=error("That role isn't whitelisted!"), ephemeral=True) + return + + if role.id not in [user_role.id for user_role in target.roles]: + await ctx.send( + content=error(f"{target.mention} does not have this role!"), + ephemeral=True, + ) + return + + response = await ctx.send(content=f"{target.mention} has {cls.embed_desc}{role.mention} role removed{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time else ''}!\n**Reason** - `{reason}`") + + if silent is False: + try: + embed = await message_factory( + bot=ctx.bot, + color=await ctx.embed_color(), + guild=ctx.guild, + moderator=ctx.author, + reason=reason, + moderation_type=cls(), + response=response, + duration=parsed_time, + ) + await target.send(embed=embed, file=get_icon(ctx.bot)) + except HTTPException: + pass + + await target.remove_roles( + role, + reason=f"Role removed by {ctx.author.id}{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time else ''} for: {reason}", + ) + + moderation = await Moderation.log( + bot=ctx.bot, + guild_id=ctx.guild.id, + moderator_id=ctx.author.id, + moderation_type=cls(), + target_type="user", + target_id=target.id, + role_id=role.id, + duration=parsed_time, + reason=reason, + ) + await response.edit( + content=f"{target.mention} has {cls.embed_desc}{role.mention} role removed{' for ' + humanize_timedelta(timedelta=parsed_time) if parsed_time else ''}! (Case `#{moderation.id:,}`)\n**Reason** - `{reason}`", + ) + await log(ctx=ctx, moderation_id=moderation.id) + await send_evidenceformat(ctx=ctx, moderation_id=moderation.id) + return cls() + + @classmethod + async def duration_edit_handler(cls, interaction: Interaction, old_moderation: Moderation, new_moderation: Moderation) -> bool: # pylint: disable=unused-argument + return True + + @classmethod + async def expiry_handler(cls, moderation: Moderation) -> int: + try: + target = moderation.guild.get_member(moderation.target_id) + if not target: + try: + target = await moderation.guild.fetch_member(moderation.target_id) + except NotFound: + return 0 + + await target.add_roles(Object(moderation.role_id), reason=f"Automatic role addition from case #{moderation.id}") + if await config.guild(moderation.guild).dm_users() is True: + try: + embed = await message_factory( + bot=moderation.bot, + color=await moderation.bot.get_embed_color(moderation.guild.channels[0]), + guild=moderation.guild, + reason=f"Automatic role addition from case #{moderation.id}", + moderation_type=type_registry["addrole"], + moderator=None, + duration=None, + response=None, + case=False, + ) + await target.send(embed=embed, file=get_icon(bot=moderation.bot)) + except HTTPException: + pass + logger.trace( + "Added role %s to %s (%s)", + moderation.role_id, + target.name, + target.id, + ) + return 1 + except ( + NotFound, + Forbidden, + HTTPException, + ) as e: + logger.error( + "Adding the role %s to user %s failed due to: \n%s", + moderation.role_id, + moderation.target_id, + e, + ) + return 0 + + @classmethod + async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]: + try: + target = await moderation.get_target() + await target.add_roles(Object(moderation.role_id), reason=reason) + if await config.guild(moderation.guild).dm_users() is True: + try: + embed = await resolve_factory(moderation=moderation, reason=reason) + await target.send(embed=embed, file=get_icon(bot=moderation.bot)) + except HTTPException: + pass + logger.trace( + "Added role %s to %s (%s)", + moderation.role_id, + target.name, + target.id, + ) + return True, "" + except (NotFound, Forbidden, HTTPException) as e: + logger.error( + "Failed to add role %s to user %s (%s)\n%s", + moderation.role_id, + target.name, + target.id, + e, + ) + return False, "Failed to add role to user." + + +class Mute(Type): + key = "mute" + string = "mute" + verb = "muted" + + def void(self) -> None: + return None + + @classmethod + async def handler(cls, ctx: commands.Context, target: Member, silent: bool, duration: str, reason: str = None): + if target.is_timed_out() is True: + await ctx.send( + error(f"{target.mention} is already muted!"), + allowed_mentions=AllowedMentions(users=False), + ephemeral=True, + ) + return + + try: + parsed_time = parse_timedelta(duration, maximum=timedelta(days=28)) + if parsed_time is None: + await ctx.send(error("Please provide a valid duration!"), ephemeral=True) + return + except commands.BadArgument: + await ctx.send(error("Please provide a duration that is less than 28 days."), ephemeral=True) + return + + await target.timeout(parsed_time, reason=f"Muted by {ctx.author.id} for: {reason}") + + response = await ctx.send(content=f"{target.mention} has been muted for {humanize_timedelta(timedelta=parsed_time)}!\n**Reason** - `{reason}`") + + if silent is False: + try: + embed = await message_factory( + bot=ctx.bot, + color=await ctx.embed_color(), + guild=ctx.guild, + moderator=ctx.author, + reason=reason, + moderation_type=cls(), + response=response, + duration=parsed_time, + ) + await target.send(embed=embed, file=get_icon(ctx.bot)) + except HTTPException: + pass + + moderation = await Moderation.log( + bot=ctx.bot, + guild_id=ctx.guild.id, + moderator_id=ctx.author.id, + moderation_type=cls(), + target_type="user", + target_id=target.id, + role_id=None, + duration=parsed_time, + reason=reason, + ) + await response.edit(content=f"{target.mention} has been muted for {humanize_timedelta(timedelta=parsed_time)}! (Case `#{moderation.id:,}`)\n**Reason** - `{reason}`") + await log(ctx=ctx, moderation_id=moderation.id) + await send_evidenceformat(ctx=ctx, moderation_id=moderation.id) + return cls() + + @classmethod + async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]: + try: + target = await moderation.guild.fetch_member(moderation.target_id) + except (Forbidden, HTTPException, NotFound): + return False, "User is not in the server, so I cannot unmute them." + if target.is_timed_out() is False: + return True, "" + await target.timeout(None, reason=reason) + + if await config.guild(moderation.guild).dm_users() is True: + try: + embed = await resolve_factory(moderation=moderation, reason=reason) + await target.send(embed=embed, file=get_icon(bot=moderation.bot)) + except (Forbidden, HTTPException): + pass + return True, "" + + @classmethod + async def duration_edit_handler(cls, interaction: Interaction, old_moderation: Moderation, new_moderation: Moderation) -> bool: # pylint: disable=unused-argument + if (time() - new_moderation.unix_timestamp) + new_moderation.duration.total_seconds() > 2419200: + await interaction.response.send_message(content=error("Please provide a duration that is less than 28 days from the initial moderation."), ephemeral=True) + return False + + try: + member = await interaction.guild.fetch_member(new_moderation.target_id) + + await member.timeout( + new_moderation.duration, + reason=f"Case #{new_moderation.id:,} edited by {interaction.user.id}", + ) + except NotFound: + pass + return True + + +class Unmute(Type): + key = "unmute" + string = "unmute" + verb = "unmuted" + + def void(self) -> None: + return None + + @classmethod + async def handler(cls, ctx: commands.Context, target: Member, silent: bool, reason: str = None): + if target.is_timed_out() is False: + await ctx.send( + content=error(f"{target.mention} is not muted!"), + allowed_mentions=AllowedMentions(users=False), + ephemeral=True, + ) + return + + if reason: + await target.timeout(None, reason=f"{cls.verb.title()} by {ctx.author.id} for: {reason}") + else: + await target.timeout(None, reason=f"{cls.verb.title()} by {ctx.author.id}") + reason = "No reason given." + + response_message = await ctx.send(content=f"{target.mention} has been {cls.verb}!\n**Reason** - `{reason}`") + + if silent is False: + try: + embed = await message_factory( + bot=ctx.bot, + color=await ctx.embed_color(), + guild=ctx.guild, + moderator=ctx.author, + reason=reason, + moderation_type=cls(), + response=response_message, + ) + await target.send(embed=embed, file=get_icon(ctx.bot)) + except HTTPException: + pass + + moderation = await Moderation.log( + bot=ctx.bot, + guild_id=ctx.guild.id, + moderator_id=ctx.author.id, + moderation_type=cls(), + target_type="user", + target_id=target.id, + role_id=None, + duration=None, + reason=reason, + ) + await response_message.edit(content=f"{target.mention} has been {cls.verb}! (Case `#{moderation.id:,}`)\n**Reason** - `{reason}`") + await log(ctx=ctx, moderation_id=moderation.id) + await send_evidenceformat(ctx=ctx, moderation_id=moderation.id) + + +class Kick(Type): + key = "kick" + string = "kick" + verb = "kicked" + removes_from_guild = True + + def void(self) -> None: + return None + + @classmethod + async def handler(cls, ctx: commands.Context, target: Member | User, silent: bool, reason: str = None) -> "Kick": + """Kick a user.""" + bot = ctx.bot + response_message = await ctx.send(f"{target.mention} has been {cls.verb}!\n{bold('Reason:')} {inline(reason)}") + + if silent is False: + try: + embed = await message_factory(bot=bot, color=await ctx.embed_color(), guild=ctx.guild, reason=reason, moderation_type=cls(), moderator=ctx.author, duration=None, response=response_message) + await target.send(embed=embed, file=get_icon(bot)) + except HTTPException: + pass + + await target.kick(reason=f"{str.title(cls.verb)} by {ctx.author.id} for: {reason}") + moderation = await Moderation.log(bot=bot, guild_id=ctx.guild.id, moderator_id=ctx.author.id, moderation_type=cls(), target_type="user", target_id=target.id, role_id=None, duration=None, reason=reason) + await response_message.edit(content=f"{target.mention} has been {cls.verb}! (Case {inline(f'#{moderation.id}')})\n{bold('Reason:')} {inline(reason)}") + await log(ctx=ctx, moderation_id=moderation.id) + await send_evidenceformat(ctx=ctx, moderation_id=moderation.id) + return cls() + + @classmethod + async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]: + if await config.guild(moderation.guild).dm_users() is True: + try: + target = await moderation.bot.fetch_user(moderation.target_id) + embed = await resolve_factory(moderation=moderation, reason=reason) + await target.send(embed=embed, file=get_icon(bot=moderation.bot)) + except (Forbidden, HTTPException, NotFound): + pass + return True, "" + + +class Ban(Type): + key = "ban" + string = "ban" + verb = "banned" + removes_from_guild = True + + def void(self) -> None: + return None + + @classmethod + async def handler(cls, ctx: commands.Context, target: Member | User, silent: bool, reason: str = None, delete_messages: app_commands.Choice | None = None) -> "Ban": + """Ban a user.""" + bot = ctx.bot + try: + await ctx.guild.fetch_ban(target) + await ctx.send(content=error(f"{target.mention} is already {cls.verb}!"), ephemeral=True) + return + except NotFound: + pass + + if delete_messages is None: + delete_messages_seconds = 0 + else: + delete_messages_seconds = delete_messages.value + + response_message = await ctx.send(f"{target.mention} has been {cls.verb}!\n{bold('Reason:')} {inline(reason)}") + + if silent is False: + try: + embed = await message_factory(bot=bot, color=await ctx.embed_color(), guild=ctx.guild, reason=reason, moderation_type=cls(), moderator=ctx.author, duration=None, response=response_message) + await target.send(embed=embed, file=get_icon(bot)) + except HTTPException: + pass + + await ctx.guild.ban(target, reason=f"{str.title(cls.verb)} by {ctx.author.id} for: {reason}", delete_message_seconds=delete_messages_seconds) + moderation = await Moderation.log(bot=bot, guild_id=ctx.guild.id, moderator_id=ctx.author.id, moderation_type=cls(), target_type="user", target_id=target.id, role_id=None, duration=None, reason=reason) + await response_message.edit(content=f"{target.mention} has been {cls.verb}! (Case {inline(f'#{moderation.id}')})\n{bold('Reason:')} {inline(reason)}") + await log(ctx=ctx, moderation_id=moderation.id) + await send_evidenceformat(ctx=ctx, moderation_id=moderation.id) + return cls() + + @classmethod + async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]: + try: + target = await moderation.bot.fetch_user(moderation.target_id) + except (HTTPException, NotFound): + return False, "Fetching the target failed, so I cannot unban them." + + try: + await moderation.guild.unban(user=target, reason=reason) + except (NotFound, Forbidden, HTTPException) as e: + if e == NotFound: + return True, "" + return False, "I do not have permission to unban this user." + + if await config.guild(moderation.guild).dm_users() is True: + try: + embed = await resolve_factory(moderation=moderation, reason=reason) + await target.send(embed=embed, file=get_icon(bot=moderation.bot)) + except (Forbidden, HTTPException): + pass + return True, "" + + +class Tempban(Ban): + key = "tempban" + string = "tempban" + verb = "tempbanned" + removes_from_guild = True + + def void(self) -> None: + return None + + @classmethod + async def handler(cls, ctx: commands.Context, target: Member | User, silent: bool, duration: str, reason: str = None, delete_messages: app_commands.Choice | None = None) -> "Ban": # pylint: disable=arguments-renamed + """Ban a user.""" + bot = ctx.bot + try: + await ctx.guild.fetch_ban(target) + await ctx.send(content=error(f"{target.mention} is already {Ban.verb}!"), ephemeral=True) + return + except NotFound: + pass + + if delete_messages is None: + delete_messages_seconds = 0 + else: + delete_messages_seconds = delete_messages.value + + try: + parsed_time = parse_relativedelta(argument=duration) + if parsed_time is None: + raise commands.BadArgument() + parsed_time = timedelta_from_relativedelta(relativedelta=parsed_time) + except (commands.BadArgument, ValueError): + await ctx.send(content=error(text="Please provide a valid duration!"), ephemeral=True) + return cls() + + response_message = await ctx.send(content=f"{target.mention} has been {cls.verb} for {humanize_timedelta(timedelta=parsed_time)}!\n{bold(text='Reason:')} {inline(text=reason)}") + + if silent is False: + try: + embed = await message_factory(bot=bot, color=await ctx.embed_color(), guild=ctx.guild, reason=reason, moderation_type=cls(), moderator=ctx.author, duration=parsed_time, response=response_message) + await target.send(embed=embed, file=get_icon(bot)) + except HTTPException: + pass + + await ctx.guild.ban(target, reason=f"{str.title(cls.verb)} by {ctx.author.id} for: {reason} (Duration: {parsed_time})", delete_message_seconds=delete_messages_seconds) + moderation = await Moderation.log(bot=bot, guild_id=ctx.guild.id, moderator_id=ctx.author.id, moderation_type=cls(), target_type="user", target_id=target.id, role_id=None, duration=parsed_time, reason=reason) + await response_message.edit(content=f"{target.mention} has been {cls.verb} for {humanize_timedelta(timedelta=parsed_time)}! (Case {inline(text=f'#{moderation.id}')})\n{bold(text='Reason:')} {inline(reason)}") + await log(ctx, moderation.id) + await send_evidenceformat(ctx, moderation.id) + return cls() + + @classmethod + async def expiry_handler(cls, moderation: Moderation) -> int: + reason = f"Automatic {Unban.string} from case #{moderation.id}" + try: + target = moderation.bot.get_user(moderation.target_id) + if not target: + try: + target = await moderation.bot.fetch_user(moderation.target_id) + except NotFound: + return 0 + await moderation.guild.unban(user=target, reason=reason) + + if await config.guild(moderation.guild).dm_users() is True: + try: + embed = await message_factory( + bot=moderation.bot, + color=await moderation.bot.get_embed_color(moderation.guild.channels[0]), + guild=moderation.guild, + reason=reason, + moderation_type=type_registry["unban"], + moderator=None, + duration=None, + response=None, + case=False, + ) + await target.send(embed=embed, file=get_icon(bot=moderation.bot)) + except HTTPException: + pass + logger.trace( + "%s %s (%s) from %s (%s)", + Unban.verb.title(), + target.name, + target.id, + moderation.guild.name, + moderation.guild.id, + ) + return 1 + except (NotFound, Forbidden, HTTPException) as e: + logger.error( + "Failed to %s %s (%s) from %s (%s)\n%s", + Unban.string, + target.name, + target.id, + moderation.guild.name, + moderation.guild.id, + e, + ) + return 0 + + @classmethod + async def duration_edit_handler(cls, interaction: Interaction, old_moderation: Moderation, new_moderation: Moderation) -> bool: # pylint: disable=unused-argument + return True + + +class Softban(Type): + key = "softban" + string = "softban" + verb = "softbanned" + removes_from_guild = True + + def void(self) -> None: + return None + + @classmethod + async def handler(cls, ctx: commands.Context, target: Member | User, silent: bool, reason: str = None, delete_messages: app_commands.Choice | None = None) -> "Softban": + """Softban a user.""" + bot = ctx.bot + try: + await ctx.guild.fetch_ban(target) + await ctx.send(content=error(f"{target.mention} is already {Ban.verb}!"), ephemeral=True) + except NotFound: + pass + + if delete_messages is None: + delete_messages_seconds = 0 + else: + delete_messages_seconds = delete_messages.value + + response_message = await ctx.send(f"{target.mention} has been {cls.verb}!\n{bold('Reason:')} {inline(reason)}") + + if silent is False: + try: + embed = await message_factory(bot=bot, color=await ctx.embed_color(), guild=ctx.guild, reason=reason, moderation_type=cls(), moderator=ctx.author, duration=None, response=response_message) + await target.send(embed=embed, file=get_icon(bot)) + except HTTPException: + pass + + await ctx.guild.ban(target, reason=f"{str.title(cls.verb)} by {ctx.author.id} for: {reason}", delete_message_seconds=delete_messages_seconds) + await ctx.guild.unban(target, reason=f"{str.title(cls.verb)} by {ctx.author.id} for: {reason}") + moderation = await Moderation.log(bot=bot, guild_id=ctx.guild.id, moderator_id=ctx.author.id, moderation_type=cls(), target_type="user", target_id=target.id, role_id=None, duration=None, reason=reason) + await response_message.edit(content=f"{target.mention} has been {cls.verb}! (Case {inline(f'#{moderation.id}')})\n{bold('Reason:')} {inline(reason)}") + await log(ctx, moderation.id) + await send_evidenceformat(ctx, moderation.id) + return cls() + + @classmethod + async def resolve_handler(cls, moderation: Moderation, reason: str) -> Tuple[bool, str]: + if await config.guild(moderation.guild).dm_users() is True: + try: + target = await moderation.bot.fetch_user(moderation.target_id) + embed = await resolve_factory(moderation=moderation, reason=reason) + await target.send(embed=embed, file=get_icon(bot=moderation.bot)) + except (Forbidden, HTTPException, NotFound): + pass + return True, "" + + +class Unban(Type): + key = "unban" + string = "unban" + verb = "unbanned" + removes_from_guild = True + + def void(self) -> None: + return None + + @classmethod + async def handler(cls, ctx: commands.Context, target: Member | User, silent: bool, reason: str = None) -> "Unban": + """Unban a user.""" + bot = ctx.bot + try: + await ctx.guild.fetch_ban(target) + except NotFound: + await ctx.send(content=error(f"{target.mention} is not {Ban.verb}!"), ephemeral=True) + return + + response_message = await ctx.send(f"{target.mention} has been {cls.verb}!\n{bold('Reason:')} {inline(reason)}") + + if silent is False: + try: + embed = await message_factory(bot=bot, color=await ctx.embed_color(), guild=ctx.guild, reason=reason, moderation_type=cls(), moderator=ctx.author, duration=None, response=response_message) + await target.send(embed=embed, file=get_icon(bot)) + except HTTPException: + pass + + await ctx.guild.unban(target, reason=f"{str.title(cls.verb)} by {ctx.author.id} for: {reason}") + moderation = await Moderation.log(bot=bot, guild_id=ctx.guild.id, moderator_id=ctx.author.id, moderation_type=cls(), target_type="user", target_id=target.id, role_id=None, duration=None, reason=reason) + await response_message.edit(content=f"{target.mention} has been {cls.verb}! (Case {inline(f'#{moderation.id}')})\n{bold('Reason:')} {inline(reason)}") + await log(ctx, moderation.id) + await send_evidenceformat(ctx, moderation.id) + return cls() + + +class Slowmode(Type): + key = "slowmode" + string = "slowmode" + verb = "set the slowmode in" + channel = True + + def void(self) -> None: + return None + + @classmethod + async def handler(cls, ctx: commands.Context, target: Messageable, silent: bool, duration: str, reason: str) -> "Slowmode": # pylint: disable=unused-argument + """Set the slowmode in a channel.""" + bot = ctx.bot + try: + parsed_time = parse_relativedelta(argument=duration) + if parsed_time is None: + raise commands.BadArgument() + parsed_time = timedelta_from_relativedelta(relativedelta=parsed_time) + except (commands.BadArgument, ValueError): + await ctx.send(content=error(text="Please provide a valid duration!"), ephemeral=True) + return cls() + + if ceil(parsed_time.total_seconds()) > 21600: + await ctx.send(content=error(text="The slowmode duration cannot exceed 6 hours!"), ephemeral=True) + return cls() + + if isinstance(target, TextChannel): + await target.edit(slowmode_delay=ceil(parsed_time.total_seconds())) + moderation = await Moderation.log(bot=bot, guild_id=ctx.guild.id, moderator_id=ctx.author.id, moderation_type=cls(), target_type="channel", target_id=target.id, role_id=None, duration=parsed_time, reason=None) + await ctx.send(content=f"{ctx.author.mention} has {cls.verb} {target.mention} to {humanize_timedelta(timedelta=parsed_time)}!\n{bold(text='Reason:')} {inline(text=reason)}") + await log(ctx=ctx, moderation_id=moderation.id) + return cls() + + +class Lockdown(Type): + key = "lockdown" + string = "lockdown" + verb = "locked down" + channel = True + + def void(self) -> None: + return None diff --git a/aurora/models/partials.py b/aurora/models/partials.py new file mode 100644 index 0000000..9fe0471 --- /dev/null +++ b/aurora/models/partials.py @@ -0,0 +1,90 @@ +from discord import ChannelType, Forbidden, Guild, HTTPException, InvalidData, NotFound, Role, User +from discord.abc import Messageable +from redbot.core.bot import Red + +from .base import AuroraBaseModel, AuroraGuildModel + + +class PartialUser(AuroraBaseModel): + id: int + username: str + discriminator: int + _obj: User | None + + @property + def name(self): + return f"{self.username}#{self.discriminator}" if self.discriminator != 0 else self.username + + def __str__(self): + return self.name + + def __repr__(self): + return f"<{self.__class__.__name__} id={self.id}>" + + @classmethod + async def from_id(cls, bot: Red, user_id: int) -> "PartialUser": + user = bot.get_user(user_id) + if not user: + try: + user = await bot.fetch_user(user_id) + return cls(bot=bot, id=user.id, username=user.name, discriminator=user.discriminator, _obj=user) + except NotFound: + return cls(bot=bot, id=user_id, username="Deleted User", discriminator=0, _obj=None) + return cls(bot=bot, id=user.id, username=user.name, discriminator=user.discriminator, _obj=user) + + +class PartialChannel(AuroraGuildModel): + id: int + name: str + type: ChannelType + _obj: Messageable | None + + @property + def mention(self): + if self.name in ["Deleted Channel", "Forbidden Channel"]: + return self.name + return f"<#{self.id}>" + + def __str__(self): + return self.mention + + def __repr__(self): + return f"<{self.__class__.__name__} id={self.id} guild_id={self.guild_id}>" + + @classmethod + async def from_id(cls, bot: Red, channel_id: int, guild: Guild) -> "PartialChannel": + channel = bot.get_channel(channel_id) + if not channel: + try: + channel = await bot.fetch_channel(channel_id) + return cls(bot=bot, guild_id=channel.guild.id, guild=guild, id=channel.id, name=channel.name, type=channel.type, _obj=channel) + except (NotFound, InvalidData, HTTPException, Forbidden) as e: + if e == Forbidden: + return cls(bot=bot, guild_id=0, id=channel_id, name="Forbidden Channel") + return cls(bot=bot, guild_id=0, id=channel_id, name="Deleted Channel", type=ChannelType.text, _obj=None) + return cls(bot=bot, guild_id=channel.guild.id, guild=guild, id=channel.id, name=channel.name, type=channel.type, _obj=channel) + + +class PartialRole(AuroraGuildModel): + id: int + name: str + _obj: Role | None + + @property + def mention(self): + if self.name in ["Deleted Role", "Forbidden Role"]: + return self.name + return f"<@&{self.id}>" + + def __str__(self): + return self.mention + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} id={self.id} guild_id={self.guild_id}>" + + @classmethod + async def from_id(cls, bot: Red, guild: Guild, role_id: int) -> "PartialRole": + role = guild.get_role(role_id) + if not role: + return cls(bot=bot, guild_id=guild.id, id=role_id, name="Deleted Role", _obj=None) + return cls(bot=bot, guild_id=guild.id, id=role.id, name=role.name, _obj=role) diff --git a/aurora/models/type.py b/aurora/models/type.py new file mode 100644 index 0000000..b510e45 --- /dev/null +++ b/aurora/models/type.py @@ -0,0 +1,98 @@ +from abc import ABC, abstractmethod +from typing import Any, Dict, Tuple + +from class_registry import ClassRegistry +from class_registry.base import AutoRegister +from discord import Interaction, Member, User +from discord.abc import Messageable +from redbot.core import commands + +type_registry: Dict["str", "Type"] = ClassRegistry(attr_name="key", unique=True) + + +class Type(AutoRegister(type_registry), ABC): + """This is a base class for moderation types. + + Attributes: + key (str): The key to use for this type. This should be unique, as this is how the type is registered internally. Changing this key will break existing cases with this type. + string (str): The string to display for this type. + verb (str): The verb to use for this type. + embed_desc (str): The string to use for embed descriptions. + channel (bool): Whether this type targets channels or users. If this is `true` in a subclass, its overridden handler methods should be typed with `discord.abc.Messageable` instead of `discord.Member | discord.User`. + removes_from_guild (bool): Whether this type's handler removes the target from the guild, or if the moderation is expected to occur whenever the user is not in the guild. This does not actually remove the target from the guild, the handler method is responsible for that. + + Properties: + name (str): The string to display for this type. This is the same as the `string` attribute. + """ + + key = "type" + string = "type" + verb = "typed" + embed_desc = "been " + channel = False + removes_from_guild = False + + @abstractmethod + def void(self) -> Any: + """This method should be overridden by any child classes. This is a placeholder to allow for automatic class registration.""" + raise NotImplementedError + + @property + def name(self) -> str: + """Alias for the `string` attribute.""" + return self.string + + def __str__(self) -> str: + return self.string + + def __repr__(self) -> str: + attrs = [ + ("key", self.key), + ("channel", self.channel), + ] + joined = " ".join(f"{key}={value!r}" for key, value in attrs) + return f"<{self.__class__.__name__} {joined}>" + + @classmethod + async def handler(cls, ctx: commands.Context, target: Member | User | Messageable, silent: bool, **kwargs) -> "Type": # pylint: disable=unused-argument + """This method should be overridden by any child classes, but should retain the same starting keyword arguments. + + Arguments: + ctx (commands.Context): The context of the command. + target (discord.Member | discord.User | discord.abc.Messageable): The target of the moderation. + silent (bool): Whether details about the moderation should be DM'ed to the target of the moderation. + """ + raise NotImplementedError + + @classmethod + async def resolve_handler(cls, moderation, reason: str) -> Tuple[bool, str]: # pylint: disable=unused-argument + """This method should be overridden by any resolvable child classes, but should retain the same keyword arguments. + If your moderation type should not be resolvable, do not override this. + + Arguments: + moderation (aurora.models.Moderation): The moderation to resolve. + reason (str): The reason for resolving the moderation. + """ + raise NotImplementedError + + @classmethod + async def expiry_handler(cls, moderation) -> int: # pylint: disable=unused-argument + """This method should be overridden by any expirable child classes, but should retain the same keyword arguments and return an integer. + If your moderation type should not expire, do not override this, but also do not set an `end_timestamp` when you log your moderation. + + Arguments: + moderation (aurora.models.Moderation): The moderation that is expiring. + """ + raise NotImplementedError + + @classmethod + async def duration_edit_handler(cls, interaction: Interaction, old_moderation, new_moderation) -> bool: # pylint: disable=unused-argument + """This method should be overridden by any child classes with editable durations, but should retain the same keyword arguments and should return True if the duration was successfully modified, or False if it was not. + If your moderation type's duration should not be editable, do not override this. + + Arguments: + interaction (discord.Interaction): The interaction that triggered the duration edit. + old_moderation (aurora.models.Moderation): The old moderation, from before the `/edit` command was invoked. + new_moderation (aurora.models.Moderation): The current state of the moderation. + """ + raise NotImplementedError diff --git a/aurora/utilities/config.py b/aurora/utilities/config.py index 0b5e503..14d5e04 100644 --- a/aurora/utilities/config.py +++ b/aurora/utilities/config.py @@ -27,3 +27,13 @@ def register_config(config_obj: Config): history_inline_pagesize=None, auto_evidenceformat=None, ) + + moderation_type = { + "show_in_history": True, + "show_moderator": None, + "use_discord_permissions": None, + "dm_users": None, + } + + config_obj.init_custom("types", 2) + config_obj.register_custom("types", **moderation_type) diff --git a/aurora/utilities/factory.py b/aurora/utilities/factory.py index 0d8a8cd..a7c534a 100644 --- a/aurora/utilities/factory.py +++ b/aurora/utilities/factory.py @@ -2,81 +2,69 @@ 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, Member, Message, Role, User from redbot.core import commands -from redbot.core.utils.chat_formatting import bold, box, error, humanize_timedelta, warning +from redbot.core.bot import Red +from redbot.core.utils.chat_formatting import bold, box, error, humanize_timedelta, inline, warning -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 ..models.moderation import Moderation +from ..models.partials import PartialUser +from ..models.type import Type +from .config import config +from .utils import get_bool_emoji, get_pagesize_str async def message_factory( + bot: Red, color: Color, guild: Guild, reason: str, - moderation_type: str, - moderator: Union[Member, User] = None, - duration: timedelta = None, - response: InteractionMessage = None, - role: Role = None, + moderation_type: Type, + moderator: Union[Member, User] | None = None, + duration: timedelta | None = None, + response: Message | None = None, + case: bool = True, ) -> Embed: """This function creates a message from set parameters, meant for contacting the moderated user. Args: + bot (Red): The bot instance. color (Color): The color of the embed. guild (Guild): The guild the moderation occurred in. reason (str): The reason for the moderation. - moderation_type (str): The type of moderation. + moderation_type (Type): The type of moderation. moderator (Union[Member, User], optional): The moderator who performed the moderation. Defaults to None. duration (timedelta, optional): The duration of the moderation. Defaults to None. - response (InteractionMessage, optional): The response message. Defaults to None. - role (Role, optional): The role that was added or removed. Defaults to None. + response (Message, optional): The response message. Defaults to None. + case (bool, optional): Whether the message is for a moderation case. Defaults to True. Returns: embed: The message embed. """ - if response is not None and moderation_type not in [ - "kicked", - "banned", - "tempbanned", - "unbanned", - ]: + if response is not None and not moderation_type.removes_from_guild: guild_name = f"[{guild.name}]({response.jump_url})" else: guild_name = guild.name - title = moderation_type - - if moderation_type in ["tempbanned", "muted"] and duration: + if duration: embed_duration = f" for {humanize_timedelta(timedelta=duration)}" else: embed_duration = "" - if moderation_type == "note": - embed_desc = "received a" - elif moderation_type == "addrole": - embed_desc = f"received the {role.name} role" - title = "Role Added" - moderation_type = "" - elif moderation_type == "removerole": - embed_desc = f"lost the {role.name} role" - title = "Role Removed" - moderation_type = "" - else: - embed_desc = "been" - embed = Embed( - title=str.title(title), - description=f"You have {embed_desc} {moderation_type}{embed_duration} in {guild_name}.", + title=str.title(moderation_type.verb), + description=f"You have {moderation_type.embed_desc}{moderation_type.verb}{embed_duration} in {guild_name}.", color=color, timestamp=datetime.now(), ) - if await config.guild(guild).show_moderator() and moderator is not None: - embed.add_field( - name="Moderator", value=f"`{moderator.name} ({moderator.id})`", inline=False - ) + show_moderator = await config.custom("types", guild.id, moderation_type.key).show_moderator() + if show_moderator is None: + show_moderator = await config.guild(guild).show_moderator() + + if show_moderator and moderator is not None: + embed.add_field(name="Moderator", value=f"`{moderator.name} ({moderator.id})`", inline=False) embed.add_field(name="Reason", value=f"`{reason}`", inline=False) @@ -85,312 +73,220 @@ async def message_factory( else: embed.set_author(name=guild.name) + if case: + embed.set_footer( + text=f"Case #{await Moderation.get_next_case_number(bot=bot, guild_id=guild.id):,}", + icon_url="attachment://arrow.png", + ) + + return embed + + +async def resolve_factory(moderation: Moderation, reason: str) -> Embed: + """This function creates a resolved embed from set parameters, meant for contacting the moderated user. + + Args: + moderation (aurora.models.Moderation): The moderation object. + reason (str): The reason for resolving the moderation. + Returns: `discord.Embed` + """ + + embed = Embed( + title=str.title(moderation.type.name) + " Resolved", + description=f"Your {moderation.type.name} in {moderation.guild.name} has been resolved.", + color=await moderation.bot.get_embed_color(moderation.guild.channels[0]), + timestamp=datetime.now(), + ) + + embed.add_field(name="Reason", value=f"`{reason}`", inline=False) + + if moderation.guild.icon.url is not None: + embed.set_author(name=moderation.guild.name, icon_url=moderation.guild.icon.url) + else: + embed.set_author(name=moderation.guild.name) embed.set_footer( - text=f"Case #{await get_next_case_number(guild.id):,}", + text=f"Case #{moderation.id:,}", icon_url="attachment://arrow.png", ) return embed -async def log_factory( - interaction: Interaction, case_dict: dict, resolved: bool = False -) -> Embed: +async def log_factory(ctx: commands.Context, moderation: Moderation, resolved: bool = False) -> Embed: """This function creates a log embed from set parameters, meant for moderation logging. Args: - interaction (Interaction): The interaction object. - case_dict (dict): The case dictionary. + ctx (commands.Context): The ctx object. + moderation (aurora.models.Moderation): The moderation object. resolved (bool, optional): Whether the case is resolved or not. Defaults to False. """ + target = await moderation.get_target() + moderator = await moderation.get_moderator() if resolved: - if case_dict["target_type"] == "USER": - target_user = await fetch_user_dict(interaction.client, case_dict["target_id"]) - target_name = ( - f"`{target_user['name']}`" - if target_user["discriminator"] == "0" - else f"`{target_user['name']}#{target_user['discriminator']}`" - ) - elif case_dict["target_type"] == "CHANNEL": - target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"]) - if target_user["mention"]: - target_name = f"{target_user['mention']}" - else: - target_name = f"`{target_user['name']}`" - - moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"]) - moderator_name = ( - f"`{moderator_user['name']}`" - if moderator_user["discriminator"] == "0" - else f"`{moderator_user['name']}#{moderator_user['discriminator']}`" - ) - embed = Embed( - title=f"📕 Case #{case_dict['moderation_id']:,} Resolved", - color=await interaction.client.get_embed_color(interaction.channel), + title=f"📕 Case #{moderation.id:,} Resolved", + color=await ctx.bot.get_embed_color(ctx.channel), ) - embed.description = f"**Type:** {str.title(case_dict['moderation_type'])}\n**Target:** {target_name} ({target_user['id']})\n**Moderator:** {moderator_name} ({moderator_user['id']})\n**Timestamp:** | " + resolved_by = await moderation.get_resolved_by() + embed.description = f"**Type:** {str.title(moderation.type.string)}\n**Target:** {target.name} ({target.id})\n**Moderator:** {moderator.name} ({moderator.id})\n**Timestamp:** | " - if case_dict["duration"] != "NULL": - td = timedelta( - **{ - unit: int(val) - for unit, val in zip( - ["hours", "minutes", "seconds"], - case_dict["duration"].split(":"), - ) - } - ) - duration_embed = ( - f"{humanize_timedelta(timedelta=td)} | " - if case_dict["expired"] == "0" - else str(humanize_timedelta(timedelta=td)) - ) - embed.description = ( - embed.description - + f"\n**Duration:** {duration_embed}\n**Expired:** {bool(case_dict['expired'])}" - ) + if moderation.duration is not None: + duration_embed = f"{humanize_timedelta(timedelta=moderation.duration)} | " if not moderation.expired else str(humanize_timedelta(timedelta=moderation.duration)) + embed.description = embed.description + f"\n**Duration:** {duration_embed}\n**Expired:** {moderation.expired}" - embed.add_field(name="Reason", value=box(case_dict["reason"]), inline=False) + if moderation.metadata.items(): + for key, value in moderation.metadata.items(): + embed.description += f"\n**{key.title()}:** {value}" + + embed.add_field(name="Reason", value=box(moderation.reason), inline=False) - resolved_user = await fetch_user_dict(interaction.client, case_dict["resolved_by"]) - resolved_name = ( - resolved_user["name"] - if resolved_user["discriminator"] == "0" - else f"{resolved_user['name']}#{resolved_user['discriminator']}" - ) embed.add_field( name="Resolve Reason", - value=f"Resolved by `{resolved_name}` ({resolved_user['id']}) for:\n" - + box(case_dict["resolve_reason"]), + value=f"Resolved by `{resolved_by.name}` ({resolved_by.id}) for:\n" + box(moderation.resolve_reason), inline=False, ) else: - if case_dict["target_type"] == "USER": - target_user = await fetch_user_dict(interaction.client, case_dict["target_id"]) - target_name = ( - f"`{target_user['name']}`" - if target_user["discriminator"] == "0" - else f"`{target_user['name']}#{target_user['discriminator']}`" - ) - elif case_dict["target_type"] == "CHANNEL": - target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"]) - if target_user["mention"]: - target_name = target_user["mention"] - else: - target_name = f"`{target_user['name']}`" - - moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"]) - moderator_name = ( - f"`{moderator_user['name']}`" - if moderator_user["discriminator"] == "0" - else f"`{moderator_user['name']}#{moderator_user['discriminator']}`" - ) - embed = Embed( - title=f"📕 Case #{case_dict['moderation_id']:,}", - color=await interaction.client.get_embed_color(interaction.channel), + title=f"📕 Case #{moderation.id:,}", + color=await ctx.bot.get_embed_color(ctx.channel), ) - embed.description = f"**Type:** {str.title(case_dict['moderation_type'])}\n**Target:** {target_name} ({target_user['id']})\n**Moderator:** {moderator_name} ({moderator_user['id']})\n**Timestamp:** | " + embed.description = f"**Type:** {str.title(moderation.type.string)}\n**Target:** {target.name} ({target.id})\n**Moderator:** {moderator.name} ({moderator.id})\n**Timestamp:** | " - if case_dict["duration"] != "NULL": - td = timedelta( - **{ - unit: int(val) - for unit, val in zip( - ["hours", "minutes", "seconds"], - case_dict["duration"].split(":"), - ) - } - ) - embed.description = ( - embed.description - + f"\n**Duration:** {humanize_timedelta(timedelta=td)} | " - ) + if moderation.duration: + embed.description = embed.description + f"\n**Duration:** {humanize_timedelta(timedelta=moderation.duration)} | " - embed.add_field(name="Reason", value=box(case_dict["reason"]), inline=False) + if moderation.metadata.items(): + for key, value in moderation.metadata.items(): + embed.description += f"\n**{key.title()}:** {value}" + + embed.add_field(name="Reason", value=box(moderation.reason), inline=False) return embed -async def case_factory(interaction: Interaction, case_dict: dict) -> Embed: +async def case_factory(interaction: Interaction, moderation: Moderation) -> Embed: """This function creates a case 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. """ - if case_dict["target_type"] == "USER": - target_user = await fetch_user_dict(interaction.client, case_dict["target_id"]) - target_name = ( - f"`{target_user['name']}`" - if target_user["discriminator"] == "0" - else f"`{target_user['name']}#{target_user['discriminator']}`" - ) - elif case_dict["target_type"] == "CHANNEL": - target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"]) - if target_user["mention"]: - target_name = f"{target_user['mention']}" - else: - target_name = f"`{target_user['name']}`" - - moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"]) - moderator_name = ( - f"`{moderator_user['name']}`" - if moderator_user["discriminator"] == "0" - else f"`{moderator_user['name']}#{moderator_user['discriminator']}`" - ) + target = await moderation.get_target() + moderator = await moderation.get_moderator() embed = Embed( - title=f"📕 Case #{case_dict['moderation_id']:,}", + title=f"📕 Case #{moderation.id:,}", color=await interaction.client.get_embed_color(interaction.channel), ) - embed.description = f"**Type:** {str.title(case_dict['moderation_type'])}\n**Target:** {target_name} ({target_user['id']})\n**Moderator:** {moderator_name} ({moderator_user['id']})\n**Resolved:** {bool(case_dict['resolved'])}\n**Timestamp:** | " + embed.description = f"**Type:** {str.title(moderation.type.string)}\n**Target:** `{target.name}` ({target.id})\n**Moderator:** `{moderator.name}` ({moderator.id})\n**Resolved:** {moderation.resolved}\n**Timestamp:** | " - if case_dict["duration"] != "NULL": - td = timedelta( - **{ - unit: int(val) - for unit, val in zip( - ["hours", "minutes", "seconds"], case_dict["duration"].split(":") - ) - } - ) - duration_embed = ( - f"{humanize_timedelta(timedelta=td)} | " - if bool(case_dict["expired"]) is False - else str(humanize_timedelta(timedelta=td)) - ) - embed.description += f"\n**Duration:** {duration_embed}\n**Expired:** {bool(case_dict['expired'])}" + if moderation.duration: + duration_embed = f"{humanize_timedelta(timedelta=moderation.duration)} | " if moderation.expired is False else str(humanize_timedelta(timedelta=moderation.duration)) + embed.description += f"\n**Duration:** {duration_embed}\n**Expired:** {moderation.expired}" - embed.description += ( - f"\n**Changes:** {len(case_dict['changes']) - 1}" - if case_dict["changes"] - else "\n**Changes:** 0" - ) + embed.description += f"\n**Changes:** {len(moderation.changes) - 1}" if moderation.changes else "\n**Changes:** 0" - if case_dict["role_id"]: - embed.description += f"\n**Role:** <@&{case_dict['role_id']}>" + if moderation.role_id: + role = await moderation.get_role() + embed.description += f"\n**Role:** {role.name}" - if case_dict["metadata"]: - if case_dict["metadata"]["imported_from"]: - embed.description += ( - f"\n**Imported From:** {case_dict['metadata']['imported_from']}" - ) + if moderation.metadata: + if moderation.metadata.get("imported_from"): + embed.description += f"\n**Imported From:** {moderation.metadata['imported_from']}" + moderation.metadata.pop("imported_from") + if moderation.metadata.get("imported_timestamp"): + embed.description += f"\n**Imported Timestamp:** | " + moderation.metadata.pop("imported_timestamp") + if moderation.metadata.items(): + for key, value in moderation.metadata.items(): + embed.description += f"\n**{key.title()}:** {value}" - embed.add_field(name="Reason", value=box(case_dict["reason"]), inline=False) + embed.add_field(name="Reason", value=box(moderation.reason), inline=False) - if case_dict["resolved"] == 1: - resolved_user = await fetch_user_dict(interaction.client, case_dict["resolved_by"]) - resolved_name = ( - f"`{resolved_user['name']}`" - if resolved_user["discriminator"] == "0" - else f"`{resolved_user['name']}#{resolved_user['discriminator']}`" - ) + if moderation.resolved: + resolved_user = await moderation.get_resolved_by() + if not resolved_user: + resolved_user = PartialUser(bot=interaction.client, id=0, username="Deleted User", discriminator="0") embed.add_field( name="Resolve Reason", - value=f"Resolved by {resolved_name} ({resolved_user['id']}) for:\n{box(case_dict['resolve_reason'])}", + value=f"Resolved by `{resolved_user.name or 'Deleted User'}` ({resolved_user.id or '0'}) for:\n{box(moderation.resolve_reason)}", inline=False, ) 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 change["user_id"] not in memory_dict: - memory_dict[str(change["user_id"])] = await fetch_user_dict( - interaction.client, change["user_id"] - ) + if moderation.changes: + for change in moderation.changes: + if change.user_id not in memory_dict: + memory_dict[str(change.user_id)] = await change.get_user() - user = memory_dict[str(change["user_id"])] - name = ( - user["name"] - if user["discriminator"] == "0" - else f"{user['name']}#{user['discriminator']}" + user: PartialUser = memory_dict[str(change.user_id)] + + timestamp = f" | " + end_timestamp = f" | " if change.end_timestamp else None + + change_str = [ + f"{bold('User:')} {inline(user.name)} ({user.id})", + f"{bold('Reason:')} {change.reason}" if change.reason else "", + f"{bold('Duration:')} {humanize_timedelta(timedelta=change.duration)}" if change.duration else "", + f"{bold('End Timestamp:')} {end_timestamp}" if end_timestamp else "", + f"{bold('Timestamp')} {timestamp}", + ] + copy = change_str.copy() + for string in change_str: + if string == "": + copy.remove(string) + + embed.add_field( + name=change.type.title(), + value="\n".join(copy), + inline=False, ) - timestamp = f" | " - - if change["type"] == "ORIGINAL": - embed.add_field( - name="Original", - value=f"**User:** `{name}` ({user['id']})\n**Reason:** {change['reason']}\n**Timestamp:** {timestamp}", - inline=False, - ) - - elif change["type"] == "EDIT": - embed.add_field( - name="Edit", - value=f"**User:** `{name}` ({user['id']})\n**Reason:** {change['reason']}\n**Timestamp:** {timestamp}", - inline=False, - ) - - elif change["type"] == "RESOLVE": - embed.add_field( - name="Resolve", - value=f"**User:** `{name}` ({user['id']})\n**Reason:** {change['reason']}\n**Timestamp:** {timestamp}", - inline=False, - ) - else: embed.description = "*No changes have been made to this case.* 🙁" return embed -async def evidenceformat_factory(interaction: Interaction, case_dict: dict) -> str: +async def evidenceformat_factory(moderation: Moderation) -> str: """This function creates a codeblock in evidence format 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. """ - if case_dict["target_type"] == "USER": - target_user = await fetch_user_dict(interaction.client, case_dict["target_id"]) - target_name = ( - target_user["name"] - if target_user["discriminator"] == "0" - else f"{target_user['name']}#{target_user['discriminator']}" - ) + target = await moderation.get_target() + moderator = await moderation.get_moderator() - elif case_dict["target_type"] == "CHANNEL": - target_user = await fetch_channel_dict(interaction.guild, case_dict["target_id"]) - target_name = target_user["name"] + content = f"Case: {moderation.id:,} ({str.title(moderation.type.string)})\nTarget: {target.name} ({target.id})\nModerator: {moderator.name} ({moderator.id})" - moderator_user = await fetch_user_dict(interaction.client, case_dict["moderator_id"]) - moderator_name = ( - moderator_user["name"] - if moderator_user["discriminator"] == "0" - else f"{moderator_user['name']}#{moderator_user['discriminator']}" - ) + if moderation.duration is not None: + content += f"\nDuration: {humanize_timedelta(timedelta=moderation.duration)}" - content = f"Case: {case_dict['moderation_id']:,} ({str.title(case_dict['moderation_type'])})\nTarget: {target_name} ({target_user['id']})\nModerator: {moderator_name} ({moderator_user['id']})" + if moderation.role_id: + role = await moderation.get_role() + content += "\nRole: " + (role.name if role is not None else moderation.role_id) - if case_dict["role_id"] != "0": - role = interaction.guild.get_role(int(case_dict["role_id"])) - content += "\nRole: " + (role.name if role is not None else case_dict["role_id"]) + content += f"\nReason: {moderation.reason}" - if case_dict["duration"] != "NULL": - hours, minutes, seconds = map(int, case_dict["duration"].split(":")) - td = timedelta(hours=hours, minutes=minutes, seconds=seconds) - content += f"\nDuration: {humanize_timedelta(timedelta=td)}" - - content += f"\nReason: {case_dict['reason']}" + for key, value in moderation.metadata.items(): + content += f"\n{key.title()}: {value}" return box(content, "prolog") @@ -419,17 +315,11 @@ async def overrides_embed(ctx: commands.Context) -> Embed: } override_str = [ - "- " - + bold("Auto Evidence Format: ") - + get_bool_emoji(override_settings["auto_evidenceformat"]), + "- " + bold("Auto Evidence Format: ") + get_bool_emoji(override_settings["auto_evidenceformat"]), "- " + bold("Ephemeral: ") + get_bool_emoji(override_settings["ephemeral"]), "- " + bold("History Inline: ") + get_bool_emoji(override_settings["inline"]), - "- " - + bold("History Inline Pagesize: ") - + get_pagesize_str(override_settings["inline_pagesize"]), - "- " - + bold("History Pagesize: ") - + get_pagesize_str(override_settings["pagesize"]), + "- " + bold("History Inline Pagesize: ") + get_pagesize_str(override_settings["inline_pagesize"]), + "- " + bold("History Pagesize: ") + get_pagesize_str(override_settings["pagesize"]), ] override_str = "\n".join(override_str) @@ -450,9 +340,7 @@ async def guild_embed(ctx: commands.Context) -> Embed: guild_settings = { "show_moderator": await config.guild(ctx.guild).show_moderator(), - "use_discord_permissions": await config.guild( - ctx.guild - ).use_discord_permissions(), + "use_discord_permissions": await config.guild(ctx.guild).use_discord_permissions(), "ignore_modlog": await config.guild(ctx.guild).ignore_modlog(), "ignore_other_bots": await config.guild(ctx.guild).ignore_other_bots(), "dm_users": await config.guild(ctx.guild).dm_users(), @@ -460,9 +348,7 @@ async def guild_embed(ctx: commands.Context) -> Embed: "history_ephemeral": await config.guild(ctx.guild).history_ephemeral(), "history_inline": await config.guild(ctx.guild).history_inline(), "history_pagesize": await config.guild(ctx.guild).history_pagesize(), - "history_inline_pagesize": await config.guild( - ctx.guild - ).history_inline_pagesize(), + "history_inline_pagesize": await config.guild(ctx.guild).history_inline_pagesize(), "auto_evidenceformat": await config.guild(ctx.guild).auto_evidenceformat(), "respect_hierarchy": await config.guild(ctx.guild).respect_hierarchy(), } @@ -474,37 +360,17 @@ async def guild_embed(ctx: commands.Context) -> Embed: channel = channel.mention guild_str = [ - "- " - + bold("Show Moderator: ") - + get_bool_emoji(guild_settings["show_moderator"]), - "- " - + bold("Use Discord Permissions: ") - + get_bool_emoji(guild_settings["use_discord_permissions"]), - "- " - + bold("Respect Hierarchy: ") - + get_bool_emoji(guild_settings["respect_hierarchy"]), - "- " - + bold("Ignore Modlog: ") - + get_bool_emoji(guild_settings["ignore_modlog"]), - "- " - + bold("Ignore Other Bots: ") - + get_bool_emoji(guild_settings["ignore_other_bots"]), + "- " + bold("Show Moderator: ") + get_bool_emoji(guild_settings["show_moderator"]), + "- " + bold("Use Discord Permissions: ") + get_bool_emoji(guild_settings["use_discord_permissions"]), + "- " + bold("Respect Hierarchy: ") + get_bool_emoji(guild_settings["respect_hierarchy"]), + "- " + bold("Ignore Modlog: ") + get_bool_emoji(guild_settings["ignore_modlog"]), + "- " + bold("Ignore Other Bots: ") + get_bool_emoji(guild_settings["ignore_other_bots"]), "- " + bold("DM Users: ") + get_bool_emoji(guild_settings["dm_users"]), - "- " - + bold("Auto Evidence Format: ") - + get_bool_emoji(guild_settings["auto_evidenceformat"]), - "- " - + bold("Ephemeral: ") - + get_bool_emoji(guild_settings["history_ephemeral"]), - "- " - + bold("History Inline: ") - + get_bool_emoji(guild_settings["history_inline"]), - "- " - + bold("History Pagesize: ") - + get_pagesize_str(guild_settings["history_pagesize"]), - "- " - + bold("History Inline Pagesize: ") - + get_pagesize_str(guild_settings["history_inline_pagesize"]), + "- " + bold("Auto Evidence Format: ") + get_bool_emoji(guild_settings["auto_evidenceformat"]), + "- " + bold("Ephemeral: ") + get_bool_emoji(guild_settings["history_ephemeral"]), + "- " + bold("History Inline: ") + get_bool_emoji(guild_settings["history_inline"]), + "- " + bold("History Pagesize: ") + get_pagesize_str(guild_settings["history_pagesize"]), + "- " + bold("History Inline Pagesize: ") + get_pagesize_str(guild_settings["history_inline_pagesize"]), "- " + bold("Log Channel: ") + channel, ] guild_str = "\n".join(guild_str) @@ -526,19 +392,11 @@ async def addrole_embed(ctx: commands.Context) -> Embed: roles = [] async with config.guild(ctx.guild).addrole_whitelist() as whitelist: for role in whitelist: - evalulated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)") - if isinstance(evalulated_role, Role): - roles.append({ - "id": evalulated_role.id, - "mention": evalulated_role.mention, - "position": evalulated_role.position - }) + evaluated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)") + if isinstance(evaluated_role, Role): + roles.append({"id": evaluated_role.id, "mention": evaluated_role.mention, "position": evaluated_role.position}) else: - roles.append({ - "id": role, - "mention": error(f"`{role}` (Not Found)"), - "position": 0 - }) + roles.append({"id": role, "mention": error(f"`{role}` (Not Found)"), "position": 0}) if roles: roles = sorted(roles, key=lambda x: x["position"], reverse=True) @@ -549,9 +407,7 @@ async def addrole_embed(ctx: commands.Context) -> Embed: e = await _config(ctx) e.title += ": Addrole Whitelist" - e.description = ( - "Use the select menu below to manage this guild's addrole whitelist." - ) + e.description = "Use the select menu below to manage this guild's addrole whitelist." if len(whitelist_str) > 4000 and len(whitelist_str) < 5000: lines = whitelist_str.split("\n") @@ -579,19 +435,11 @@ async def immune_embed(ctx: commands.Context) -> Embed: roles = [] async with config.guild(ctx.guild).immune_roles() as immune_roles: for role in immune_roles: - evalulated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)") - if isinstance(evalulated_role, Role): - roles.append({ - "id": evalulated_role.id, - "mention": evalulated_role.mention, - "position": evalulated_role.position - }) + evaluated_role = ctx.guild.get_role(role) or error(f"`{role}` (Not Found)") + if isinstance(evaluated_role, Role): + roles.append({"id": evaluated_role.id, "mention": evaluated_role.mention, "position": evaluated_role.position}) else: - roles.append({ - "id": role, - "mention": error(f"`{role}` (Not Found)"), - "position": 0 - }) + roles.append({"id": role, "mention": error(f"`{role}` (Not Found)"), "position": 0}) if roles: roles = sorted(roles, key=lambda x: x["position"], reverse=True) @@ -622,3 +470,34 @@ async def immune_embed(ctx: commands.Context) -> Embed: e.description += "\n\n" + immune_str return e + + +async def type_embed(ctx: commands.Context, moderation_type=Type) -> Embed: + """Generates a configuration menu field value for a guild's settings.""" + + type_settings = { + "show_in_history": await config.custom("types", ctx.guild.id, moderation_type.key).show_in_history(), + "show_moderator": await config.custom("types", ctx.guild.id, moderation_type.key).show_moderator(), + "use_discord_permissions": await config.custom("types", ctx.guild.id, moderation_type.key).use_discord_permissions(), + "dm_users": await config.custom("types", ctx.guild.id, moderation_type.key).dm_users(), + } + + guild_str = [ + "- " + bold("Show in History: ") + get_bool_emoji(type_settings["show_in_history"]), + "- " + bold("Show Moderator: ") + get_bool_emoji(type_settings["show_moderator"]), + "- " + bold("Use Discord Permissions: ") + get_bool_emoji(type_settings["use_discord_permissions"]), + "- " + bold("DM Users: ") + get_bool_emoji(type_settings["dm_users"]), + ] + guild_str = "\n".join(guild_str) + + e = await _config(ctx) + e.title += f": {moderation_type.string.title()} Configuration" + e.description = ( + f""" + Use the buttons below to manage Aurora's configuration for the {bold(moderation_type.string)} moderation type. + If an option has a question mark (\N{BLACK QUESTION MARK ORNAMENT}\N{VARIATION SELECTOR-16}) next to it, Aurora will default to the guild level setting instead. + See `{ctx.prefix}aurora set guild` for more information.\n + """ + + guild_str + ) + return e diff --git a/aurora/utilities/json.py b/aurora/utilities/json.py new file mode 100644 index 0000000..2fe605a --- /dev/null +++ b/aurora/utilities/json.py @@ -0,0 +1,108 @@ +import json +from datetime import datetime, timedelta +from typing import Any + +from redbot.core.bot import Red + +from ..models.base import AuroraBaseModel +from ..models.type import Type + + +class JSONEncoder(json.JSONEncoder): + def default(self, o) -> Any: + match o: + case datetime(): + return int(o.timestamp()) + case timedelta(): + from ..utilities.utils import timedelta_to_string + + return timedelta_to_string(o) + case AuroraBaseModel(): + return o.dump() + case Type(): + return o.key + case Red(): + return None + case _: + return super().default(o) + + +# This is a wrapper around the json module's dumps function that uses our custom JSONEncoder class +def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, default=None, sort_keys=False, **kw) -> str: + """Serialize ``obj`` to a JSON formatted ``str``. + + If ``skipkeys`` is true then ``dict`` keys that are not basic types + (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped + instead of raising a ``TypeError``. + + If ``ensure_ascii`` is false, then the return value can contain non-ASCII + characters if they appear in strings contained in ``obj``. Otherwise, all + such characters are escaped in JSON strings. + + If ``check_circular`` is false, then the circular reference check + for container types will be skipped and a circular reference will + result in an ``RecursionError`` (or worse). + + If ``allow_nan`` is false, then it will be a ``ValueError`` to + serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in + strict compliance of the JSON specification, instead of using the + JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). + + If ``indent`` is a non-negative integer, then JSON array elements and + object members will be pretty-printed with that indent level. An indent + level of 0 will only insert newlines. ``None`` is the most compact + representation. + + If specified, ``separators`` should be an ``(item_separator, key_separator)`` + tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and + ``(',', ': ')`` otherwise. To get the most compact JSON representation, + you should specify ``(',', ':')`` to eliminate whitespace. + + ``default(obj)`` is a function that should return a serializable version + of obj or raise TypeError. The default simply raises TypeError. + + If *sort_keys* is true (default: ``False``), then the output of + dictionaries will be sorted by key. + """ + return json.dumps(obj, cls=JSONEncoder, skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, default=default, sort_keys=sort_keys, **kw) + + +# This is a wrapper around the json module's dump function that uses our custom JSONEncoder class +def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, default=None, sort_keys=False, **kw) -> str: + """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a + ``.write()``-supporting file-like object). + + If ``skipkeys`` is true then ``dict`` keys that are not basic types + (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped + instead of raising a ``TypeError``. + + If ``ensure_ascii`` is false, then the strings written to ``fp`` can + contain non-ASCII characters if they appear in strings contained in + ``obj``. Otherwise, all such characters are escaped in JSON strings. + + If ``check_circular`` is false, then the circular reference check + for container types will be skipped and a circular reference will + result in an ``RecursionError`` (or worse). + + If ``allow_nan`` is false, then it will be a ``ValueError`` to + serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) + in strict compliance of the JSON specification, instead of using the + JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). + + If ``indent`` is a non-negative integer, then JSON array elements and + object members will be pretty-printed with that indent level. An indent + level of 0 will only insert newlines. ``None`` is the most compact + representation. + + If specified, ``separators`` should be an ``(item_separator, key_separator)`` + tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and + ``(',', ': ')`` otherwise. To get the most compact JSON representation, + you should specify ``(',', ':')`` to eliminate whitespace. + + ``default(obj)`` is a function that should return a serializable version + of obj or raise TypeError. The default simply raises TypeError. + + If *sort_keys* is true (default: ``False``), then the output of + dictionaries will be sorted by key. + """ + return json.dump(obj, fp, cls=JSONEncoder, skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, default=default, sort_keys=sort_keys, **kw) diff --git a/aurora/utilities/utils.py b/aurora/utilities/utils.py index 1ff21fa..a366f62 100644 --- a/aurora/utilities/utils.py +++ b/aurora/utilities/utils.py @@ -1,23 +1,25 @@ # pylint: disable=cyclic-import -import json -from datetime import datetime -from datetime import timedelta as td -from typing import Optional, Union +from datetime import datetime, timedelta +from typing import Optional, Tuple, Union +import aiosqlite from dateutil.relativedelta import relativedelta as rd -from discord import File, Guild, Interaction, Member, SelectOption, User -from discord.errors import Forbidden, NotFound +from discord import File, Guild, Interaction, Member, SelectOption, TextChannel, User +from discord.errors import Forbidden from redbot.core import commands, data_manager from redbot.core.utils.chat_formatting import error -from .config import config +from ..models.type import Type +from ..utilities.config import config +from ..utilities.json import dumps +from ..utilities.logger import logger def check_permissions( user: User, - permissions: list, - ctx: Union[commands.Context, Interaction] = None, - guild: Guild = None, + permissions: Tuple[str], + ctx: commands.Context | Interaction | None = None, + guild: Guild | None = None, ) -> Union[bool, str]: """Checks if a user has a specific permission (or a list of permissions) in a channel.""" if ctx: @@ -32,68 +34,63 @@ def check_permissions( raise (KeyError) for permission in permissions: - if ( - not getattr(resolved_permissions, permission, False) - and resolved_permissions.administrator is not True - ): + if not getattr(resolved_permissions, permission, False) and resolved_permissions.administrator is not True: return permission return False async def check_moddable( - target: Union[User, Member], interaction: Interaction, permissions: list + target: Union[User, Member, TextChannel], + ctx: commands.Context, + permissions: Tuple[str], + moderation_type: Type, ) -> bool: """Checks if a moderator can moderate a target.""" - if check_permissions(interaction.client.user, permissions, guild=interaction.guild): - await interaction.response.send_message( - error( - f"I do not have the `{permissions}` permission, required for this action." - ), + is_channel = isinstance(target, TextChannel) + + use_discord_permissions = await config.custom("types", ctx.guild.id, moderation_type.key).use_discord_permissions() + if use_discord_permissions is None: + use_discord_permissions = await config.guild(ctx.guild).use_discord_permissions() + + if check_permissions(ctx.bot.user, permissions, guild=ctx.guild): + await ctx.send( + error(f"I do not have the `{permissions}` permission, required for this action."), ephemeral=True, ) return False - if await config.guild(interaction.guild).use_discord_permissions() is True: - if check_permissions(interaction.user, permissions, guild=interaction.guild): - await interaction.response.send_message( - error( - f"You do not have the `{permissions}` permission, required for this action." - ), + if use_discord_permissions is True: + if check_permissions(ctx.author, permissions, guild=ctx.guild): + await ctx.send( + error(f"You do not have the `{permissions}` permission, required for this action."), ephemeral=True, ) return False - if interaction.user.id == target.id: - await interaction.response.send_message( - content="You cannot moderate yourself!", ephemeral=True - ) + if ctx.author.id == target.id: + await ctx.send(content="You cannot moderate yourself!", ephemeral=True) return False - if target.bot: - await interaction.response.send_message( - content="You cannot moderate bots!", ephemeral=True - ) + if not is_channel and target.bot: + await ctx.send(content="You cannot moderate bots!", ephemeral=True) return False if isinstance(target, Member): - if interaction.user.top_role <= target.top_role and await config.guild(interaction.guild).respect_hierarchy() is True: - await interaction.response.send_message( - content=error( - "You cannot moderate members with a higher role than you!" - ), + if ctx.author.top_role <= target.top_role and await config.guild(ctx.guild).respect_hierarchy() is True: + await ctx.send( + content=error("You cannot moderate members with a higher role than you!"), ephemeral=True, ) return False - if ( - interaction.guild.get_member(interaction.client.user.id).top_role - <= target.top_role - ): - await interaction.response.send_message( - content=error( - "You cannot moderate members with a role higher than the bot!" - ), + if target.guild_permissions.administrator: + await ctx.send(content="You cannot moderate members with the Administrator permission!", ephemeral=True) + return False + + if ctx.guild.get_member(ctx.bot.user.id).top_role <= target.top_role: + await ctx.send( + content=error("You cannot moderate members with a role higher than the bot!"), ephemeral=True, ) return False @@ -102,7 +99,7 @@ async def check_moddable( for role in target.roles: if role.id in immune_roles: - await interaction.response.send_message( + await ctx.send( content=error("You cannot moderate members with an immune role!"), ephemeral=True, ) @@ -111,152 +108,50 @@ async def check_moddable( return True -async def get_next_case_number(guild_id: str, cursor=None) -> int: - """This function returns the next case number from the MySQL table for a specific guild.""" - from .database import connect - - if not cursor: - database = connect() - cursor = database.cursor() - cursor.execute( - f"SELECT moderation_id FROM `moderation_{guild_id}` ORDER BY moderation_id DESC LIMIT 1" - ) - result = cursor.fetchone() - return (result[0] + 1) if result else 1 - - -def generate_dict(result) -> dict: - case = { - "moderation_id": result[0], - "timestamp": result[1], - "moderation_type": result[2], - "target_type": result[3], - "target_id": result[4], - "moderator_id": result[5], - "role_id": result[6], - "duration": result[7], - "end_timestamp": result[8], - "reason": result[9], - "resolved": result[10], - "resolved_by": result[11], - "resolve_reason": result[12], - "expired": result[13], - "changes": json.loads(result[14]), - "metadata": json.loads(result[15]), - } - return case - - -async def fetch_user_dict(client: commands.Bot, user_id: str) -> dict: - """This function returns a dictionary containing either user information or a standard deleted user template.""" - if user_id == "?": - user_dict = {"id": "?", "name": "Unknown User", "discriminator": "0"} - - else: - try: - user = client.get_user(int(user_id)) - if user is None: - user = await client.fetch_user(int(user_id)) - - user_dict = { - "id": user.id, - "name": user.name, - "discriminator": user.discriminator, - } - - except NotFound: - user_dict = { - "id": user_id, - "name": "Deleted User", - "discriminator": "0", - } - - - return user_dict - - -async def fetch_channel_dict(guild: Guild, channel_id: int) -> dict: - """This function returns a dictionary containing either channel information or a standard deleted channel template.""" - try: - channel = guild.get_channel(int(channel_id)) - if not channel: - channel = await guild.fetch_channel(channel_id) - - channel_dict = { - "id": channel.id, - "name": channel.name, - "mention": channel.mention, - } - - except NotFound: - channel_dict = {"id": channel_id, "name": "Deleted Channel", "mention": None} - - return channel_dict - - -async def fetch_role_dict(guild: Guild, role_id: int) -> dict: - """This function returns a dictionary containing either role information or a standard deleted role template.""" - role = guild.get_role(int(role_id)) - if not role: - role_dict = {"id": role_id, "name": "Deleted Role"} - - role_dict = {"id": role.id, "name": role.name} - - return role_dict - - -async def log(interaction: Interaction, moderation_id: int, resolved: bool = False) -> None: +async def log(ctx: commands.Context, moderation_id: int, resolved: bool = False) -> None: """This function sends a message to the guild's configured logging channel when an infraction takes place.""" - from .database import fetch_case + from ..models.moderation import Moderation from .factory import log_factory - logging_channel_id = await config.guild(interaction.guild).log_channel() + logging_channel_id = await config.guild(ctx.guild).log_channel() if logging_channel_id != " ": - logging_channel = interaction.guild.get_channel(logging_channel_id) + logging_channel = ctx.guild.get_channel(logging_channel_id) - case = await fetch_case(moderation_id, interaction.guild.id) - if case: - embed = await log_factory( - interaction=interaction, case_dict=case, resolved=resolved - ) + try: + moderation = await Moderation.find_by_id(ctx.bot, moderation_id, ctx.guild.id) + embed = await log_factory(ctx=ctx, moderation=moderation, resolved=resolved) try: await logging_channel.send(embed=embed) except Forbidden: return + except ValueError: + return -async def send_evidenceformat(interaction: Interaction, case_dict: dict) -> None: +async def send_evidenceformat(ctx: commands.Context, moderation_id: int) -> None: """This function sends an ephemeral message to the moderator who took the moderation action, with a pre-made codeblock for use in the mod-evidence channel.""" + from ..models.moderation import Moderation from .factory import evidenceformat_factory - send_evidence_bool = ( - await config.user(interaction.user).auto_evidenceformat() - or await config.guild(interaction.guild).auto_evidenceformat() - or False - ) - if send_evidence_bool is False: - return - - content = await evidenceformat_factory(interaction=interaction, case_dict=case_dict) - await interaction.followup.send(content=content, ephemeral=True) - - -def convert_timedelta_to_str(timedelta: td) -> str: - """This function converts a timedelta object to a string.""" - total_seconds = int(timedelta.total_seconds()) - hours = total_seconds // 3600 - minutes = (total_seconds % 3600) // 60 - seconds = total_seconds % 60 - return f"{hours}:{minutes}:{seconds}" + send_evidence_bool = await config.user(ctx.author).auto_evidenceformat() or await config.guild(guild=ctx.guild).auto_evidenceformat() or False + if send_evidence_bool is True: + moderation = await Moderation.find_by_id(ctx.bot, moderation_id, ctx.guild.id) + content = await evidenceformat_factory(moderation=moderation) + if not ctx.interaction: + await ctx.author.send(content=content) + else: + await ctx.send(content=content, ephemeral=True) def get_bool_emoji(value: Optional[bool]) -> str: """Returns a unicode emoji based on a boolean value.""" - if value is True: - return "\N{WHITE HEAVY CHECK MARK}" - if value is False: - return "\N{NO ENTRY SIGN}" - return "\N{BLACK QUESTION MARK ORNAMENT}\N{VARIATION SELECTOR-16}" + match value: + case True: + return "\N{WHITE HEAVY CHECK MARK}" + case False: + return "\N{NO ENTRY SIGN}" + case _: + return "\N{BLACK QUESTION MARK ORNAMENT}\N{VARIATION SELECTOR-16}" def get_pagesize_str(value: Union[int, None]) -> str: @@ -286,13 +181,96 @@ def create_pagesize_options() -> list[SelectOption]: ) return options -def timedelta_from_relativedelta(relativedelta: rd) -> td: + +def timedelta_from_relativedelta(relativedelta: rd) -> timedelta: """Converts a relativedelta object to a timedelta object.""" now = datetime.now() then = now - relativedelta return now - then + +def timedelta_from_string(string: str) -> timedelta: + """Converts a string to a timedelta object.""" + hours, minutes, seconds = map(int, string.split(":")) + return timedelta(hours=hours, minutes=minutes, seconds=seconds) + + +def timedelta_to_string(td: timedelta) -> str: + """Converts a timedelta object to a string.""" + days = td.days * 24 + hours, remainder = divmod(td.seconds, 3600) + minutes, seconds = divmod(remainder, 60) + return f"{days + hours}:{minutes:02}:{seconds:02}" + + def get_footer_image(coginstance: commands.Cog) -> File: """Returns the footer image for the embeds.""" image_path = data_manager.bundled_data_path(coginstance) / "arrow.png" return File(image_path, filename="arrow.png", description="arrow") + + +async def create_guild_table(guild: Guild) -> None: + from ..models.moderation import Moderation + + try: + await Moderation.execute(f"SELECT * FROM `moderation_{guild.id}`", return_obj=False) + logger.trace("SQLite Table exists for server %s (%s)", guild.name, guild.id) + + except aiosqlite.OperationalError: + query = f""" + CREATE TABLE `moderation_{guild.id}` ( + moderation_id INTEGER PRIMARY KEY NOT NULL, + timestamp INTEGER NOT NULL, + moderation_type TEXT NOT NULL, + target_type TEXT NOT NULL, + target_id INTEGER NOT NULL, + moderator_id INTEGER NOT NULL, + role_id INTEGER, + duration TEXT, + end_timestamp INTEGER, + reason TEXT, + resolved INTEGER NOT NULL, + resolved_by TEXT, + resolve_reason TEXT, + expired INTEGER NOT NULL, + changes JSON NOT NULL, + metadata JSON NOT NULL + ) + """ + await Moderation.execute(query=query, return_obj=False) + + index_query_1 = f"CREATE INDEX IF NOT EXISTS idx_target_id ON moderation_{guild.id}(target_id);" + await Moderation.execute(query=index_query_1, return_obj=False) + + index_query_2 = f"CREATE INDEX IF NOT EXISTS idx_moderator_id ON moderation_{guild.id}(moderator_id);" + await Moderation.execute(query=index_query_2, return_obj=False) + + index_query_3 = f"CREATE INDEX IF NOT EXISTS idx_moderation_id ON moderation_{guild.id}(moderation_id);" + await Moderation.execute(query=index_query_3, return_obj=False) + + insert_query = f""" + INSERT INTO `moderation_{guild.id}` + (moderation_id, timestamp, moderation_type, target_type, target_id, moderator_id, role_id, duration, end_timestamp, reason, resolved, resolved_by, resolve_reason, expired, changes, metadata) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """ + insert_values = ( + 0, + 0, + "NULL", + "NULL", + 0, + 0, + None, + None, + None, + None, + 0, + None, + None, + 0, + dumps([]), + dumps({}), + ) + await Moderation.execute(query=insert_query, parameters=insert_values, return_obj=False) + + logger.trace("SQLite Table created for server %s (%s)", guild.name, guild.id) -- 2.45.3 From f71a85092bc09b704755bbc8e2a70b763575a4ac Mon Sep 17 00:00:00 2001 From: cswimr Date: Sat, 25 Jan 2025 21:45:36 +0000 Subject: [PATCH 2/6] misc(aurora): transition to rc naming for indev versions --- aurora/aurora.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aurora/aurora.py b/aurora/aurora.py index 2cfd78a..dfe49e7 100644 --- a/aurora/aurora.py +++ b/aurora/aurora.py @@ -46,7 +46,7 @@ class Aurora(commands.Cog): This cog stores all of its data in an SQLite database.""" __author__ = ["[cswimr](https://www.coastalcommits.com/cswimr)"] - __version__ = "3.0.0-indev27" + __version__ = "3.0.0-rc1" __git__ = "https://www.coastalcommits.com/cswimr/SeaCogs" __documentation__ = "https://seacogs.coastalcommits.com/aurora/" -- 2.45.3 From 4bfb92e937f2d50cf1348fcb8cfe151f6c250dac Mon Sep 17 00:00:00 2001 From: cswimr Date: Sat, 25 Jan 2025 21:57:21 +0000 Subject: [PATCH 3/6] chore(deps): update `phx-class-registry` --- pyproject.toml | 2 +- uv.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 2c40dee..623e3a0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,7 +12,7 @@ dependencies = [ "colorthief>=0.2.1", "markdownify>=0.13.1", "numpy>=2.1.2", - "phx-class-registry>=5.0.0", + "phx-class-registry>=5.1.1", "pillow>=10.4.0", "pip>=24.3.1", "py-dactyl", diff --git a/uv.lock b/uv.lock index 9056ced..5f9903a 100644 --- a/uv.lock +++ b/uv.lock @@ -1088,11 +1088,11 @@ sdist = { url = "https://files.pythonhosted.org/packages/bd/be/e9c886b4601a19f4c [[package]] name = "phx-class-registry" -version = "5.0.0" +version = "5.1.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d4/b0/dfe7eee3715a522e0507c5d81daab52d4348ee2672fa77c721617dbb6319/phx_class_registry-5.0.0.tar.gz", hash = "sha256:a57ab8c2eca03e0daf06e0dd840ea26b72e2e51b7b7509015b3df7c0d537ee73", size = 32284 } +sdist = { url = "https://files.pythonhosted.org/packages/ad/e1/4038dc8b09e66b1f850913c05fe1c039f8d9c0ef61347af37c75bbe77e3f/phx_class_registry-5.1.1.tar.gz", hash = "sha256:06c9af198b846a7530406314f63f8d83441daf42d29ee25d8c0b19a9dbc37939", size = 32115 } wheels = [ - { url = "https://files.pythonhosted.org/packages/41/e5/9384dd7f575ade7a14ae4371d6b4eafd997f18577d3e93ccd0e055389b0b/phx_class_registry-5.0.0-py3-none-any.whl", hash = "sha256:6e0644f779c7d793a96090d938fe4c396f3274dd57563dc1c57ea245b5c07f89", size = 14850 }, + { url = "https://files.pythonhosted.org/packages/7d/85/67eb86f25b1857a7669c4ad7a46b439e55c5301cbcb08b9ce8fa9125700d/phx_class_registry-5.1.1-py3-none-any.whl", hash = "sha256:b093ecc1dad34c5dc6eda2530046d956f2303a5cfaa543bf7fba35ce3c7b1672", size = 15732 }, ] [[package]] @@ -1700,7 +1700,7 @@ requires-dist = [ { name = "mkdocs-redirects", marker = "extra == 'documentation'", specifier = ">=1.2.1" }, { name = "mkdocstrings", extras = ["python"], marker = "extra == 'documentation'", specifier = ">=0.26.1" }, { name = "numpy", specifier = ">=2.1.2" }, - { name = "phx-class-registry", specifier = ">=5.0.0" }, + { name = "phx-class-registry", specifier = ">=5.1.1" }, { name = "pillow", specifier = ">=10.4.0" }, { name = "pip", specifier = ">=24.3.1" }, { name = "py-dactyl", git = "https://github.com/cswimr/pydactyl" }, -- 2.45.3 From e79dfd6b9462dfc4d96b31125dd184c810f065a7 Mon Sep 17 00:00:00 2001 From: cswimr Date: Sat, 25 Jan 2025 22:00:54 +0000 Subject: [PATCH 4/6] chore(deps): update `phx-class-registry` --- aurora/info.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aurora/info.json b/aurora/info.json index 8229183..9a1e1a7 100644 --- a/aurora/info.json +++ b/aurora/info.json @@ -9,7 +9,7 @@ "disabled": false, "min_bot_version": "3.5.0", "min_python_version": [3, 10, 0], - "requirements": ["pydantic", "aiosqlite", "phx-class-registry==5.0.0"], + "requirements": ["pydantic", "aiosqlite", "phx-class-registry==5.1.1"], "tags": [ "mod", "moderate", -- 2.45.3 From db125187c9083ae2774acefa52cc74732535cd16 Mon Sep 17 00:00:00 2001 From: cswimr Date: Sat, 25 Jan 2025 22:09:08 +0000 Subject: [PATCH 5/6] fix(aurora): add missing `__init__.py` file --- aurora/models/__init__.py | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 aurora/models/__init__.py diff --git a/aurora/models/__init__.py b/aurora/models/__init__.py new file mode 100644 index 0000000..f15d56d --- /dev/null +++ b/aurora/models/__init__.py @@ -0,0 +1,2 @@ +from .moderation_types import * # noqa: F403 +# This just imports all the built-in moderation types so they can be registered, as they aren't imported anywhere else. -- 2.45.3 From 850ddf15a6bc222a62778ffbcdbb6f9240131b37 Mon Sep 17 00:00:00 2001 From: cswimr Date: Sat, 25 Jan 2025 22:11:37 +0000 Subject: [PATCH 6/6] fix(aurora): improve typehints in the `Type` model --- aurora/models/type.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/aurora/models/type.py b/aurora/models/type.py index b510e45..7bc113a 100644 --- a/aurora/models/type.py +++ b/aurora/models/type.py @@ -1,5 +1,5 @@ from abc import ABC, abstractmethod -from typing import Any, Dict, Tuple +from typing import TYPE_CHECKING, Any, Dict, Tuple from class_registry import ClassRegistry from class_registry.base import AutoRegister @@ -7,10 +7,13 @@ from discord import Interaction, Member, User from discord.abc import Messageable from redbot.core import commands +if TYPE_CHECKING: + from .moderation import Moderation + type_registry: Dict["str", "Type"] = ClassRegistry(attr_name="key", unique=True) -class Type(AutoRegister(type_registry), ABC): +class Type(AutoRegister(registry=type_registry), ABC): """This is a base class for moderation types. Attributes: @@ -65,7 +68,7 @@ class Type(AutoRegister(type_registry), ABC): raise NotImplementedError @classmethod - async def resolve_handler(cls, moderation, reason: str) -> Tuple[bool, str]: # pylint: disable=unused-argument + async def resolve_handler(cls, moderation: "Moderation", reason: str) -> Tuple[bool, str]: # pylint: disable=unused-argument """This method should be overridden by any resolvable child classes, but should retain the same keyword arguments. If your moderation type should not be resolvable, do not override this. @@ -76,7 +79,7 @@ class Type(AutoRegister(type_registry), ABC): raise NotImplementedError @classmethod - async def expiry_handler(cls, moderation) -> int: # pylint: disable=unused-argument + async def expiry_handler(cls, moderation: "Moderation") -> int: # pylint: disable=unused-argument """This method should be overridden by any expirable child classes, but should retain the same keyword arguments and return an integer. If your moderation type should not expire, do not override this, but also do not set an `end_timestamp` when you log your moderation. @@ -86,7 +89,7 @@ class Type(AutoRegister(type_registry), ABC): raise NotImplementedError @classmethod - async def duration_edit_handler(cls, interaction: Interaction, old_moderation, new_moderation) -> bool: # pylint: disable=unused-argument + async def duration_edit_handler(cls, interaction: Interaction, old_moderation: "Moderation", new_moderation: "Moderation") -> bool: # pylint: disable=unused-argument """This method should be overridden by any child classes with editable durations, but should retain the same keyword arguments and should return True if the duration was successfully modified, or False if it was not. If your moderation type's duration should not be editable, do not override this. -- 2.45.3