Compare commits

..

No commits in common. "2aadf5134d5a73987f463726c2e8244e3c621a8e" and "027144f35d3d4e6571ed3c16a2e0464e634124b6" have entirely different histories.

12 changed files with 326 additions and 318 deletions

View file

@ -6,8 +6,8 @@
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
import json
import logging as py_logging
import os
import sqlite3
import time
from datetime import datetime, timedelta, timezone
from math import ceil
@ -19,7 +19,7 @@ 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 bold, box, error, humanize_list, humanize_timedelta, warning
from redbot.core.utils.chat_formatting import box, error, humanize_list, humanize_timedelta, warning
from .importers.aurora import ImportAuroraView
from .importers.galacticbot import ImportGalacticBotView
@ -30,10 +30,11 @@ from .menus.overrides import Overrides
from .models.change import Change
from .models.moderation import Moderation
from .utilities.config import config, register_config
from .utilities.database import connect, create_guild_table
from .utilities.factory import addrole_embed, case_factory, changes_factory, evidenceformat_factory, guild_embed, immune_embed, message_factory, overrides_embed
from .utilities.json import dump
from .utilities.logger import logger
from .utilities.utils import check_moddable, check_permissions, create_guild_table, get_footer_image, log, send_evidenceformat, timedelta_from_relativedelta
from .utilities.utils import check_moddable, check_permissions, get_footer_image, log, send_evidenceformat, timedelta_from_relativedelta
class Aurora(commands.Cog):
@ -42,22 +43,28 @@ class Aurora(commands.Cog):
This cog stores all of its data in an SQLite database."""
__author__ = ["SeaswimmerTheFsh"]
__version__ = "2.3.0"
__version__ = "2.2.0"
__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()
results = await Moderation.execute(query="SHOW TABLES;", return_obj=False)
tables = [table[0] for table in results]
database = connect()
cursor = database.cursor()
cursor.execute("SHOW TABLES;")
tables = [table[0] for table in cursor.fetchall()]
condition = "target_id = %s OR moderator_id = %s;"
for table in tables:
delete_query = f"DELETE FROM {table[0]} WHERE {condition}"
await Moderation.execute(query=delete_query, parameters=(user_id, user_id), return_obj=False)
cursor.execute(delete_query, (user_id, user_id))
database.commit()
cursor.close()
database.close()
if requester == "owner":
await config.user_from_id(user_id).clear()
if requester == "user":
@ -69,26 +76,20 @@ class Aurora(commands.Cog):
"Invalid requester passed to red_delete_data_for_user: %s", requester
)
def __init__(self, bot: Red) -> None:
def __init__(self, bot: Red):
super().__init__()
self.bot = bot
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"{bold('Cog Version:')} {self.__version__}",
f"{bold('Author:')} {humanize_list(self.__author__)}",
f"{bold('Documentation:')} {self.__documentation__}",
f"Cog Version: **{self.__version__}**",
f"Author: {humanize_list(self.__author__)}",
f"Documentation: {self.__documentation__}",
]
return "\n".join(text)
@ -121,11 +122,14 @@ 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;"""
results = 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]:,})")
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]:,})")
@commands.Cog.listener("on_audit_log_entry_create")
async def autologger(self, entry: discord.AuditLogEntry):
@ -171,7 +175,7 @@ class Aurora(commands.Cog):
else:
return
await Moderation.log(
Moderation.log(
self.bot,
entry.guild.id,
entry.user.id,
@ -229,7 +233,7 @@ class Aurora(commands.Cog):
except discord.errors.HTTPException:
pass
moderation = await Moderation.log(
moderation = Moderation.log(
interaction.client,
interaction.guild.id,
interaction.user.id,
@ -288,7 +292,7 @@ class Aurora(commands.Cog):
except discord.errors.HTTPException:
pass
moderation = await Moderation.log(
moderation = Moderation.log(
interaction.client,
interaction.guild.id,
interaction.user.id,
@ -394,7 +398,7 @@ class Aurora(commands.Cog):
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 = await Moderation.log(
moderation = Moderation.log(
interaction.client,
interaction.guild.id,
interaction.user.id,
@ -500,7 +504,7 @@ class Aurora(commands.Cog):
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 = await Moderation.log(
moderation = Moderation.log(
interaction.client,
interaction.guild.id,
interaction.user.id,
@ -588,7 +592,7 @@ class Aurora(commands.Cog):
except discord.errors.HTTPException:
pass
moderation = await Moderation.log(
moderation = Moderation.log(
interaction.client,
interaction.guild.id,
interaction.user.id,
@ -724,7 +728,7 @@ class Aurora(commands.Cog):
await target.kick(reason=f"Kicked by {interaction.user.id} for: {reason}")
moderation = await Moderation.log(
moderation = Moderation.log(
interaction.client,
interaction.guild.id,
interaction.user.id,
@ -832,7 +836,7 @@ class Aurora(commands.Cog):
delete_message_seconds=delete_messages_seconds,
)
moderation = await Moderation.log(
moderation = Moderation.log(
interaction.client,
interaction.guild.id,
interaction.user.id,
@ -876,7 +880,7 @@ class Aurora(commands.Cog):
delete_message_seconds=delete_messages_seconds,
)
moderation = await Moderation.log(
moderation = Moderation.log(
interaction.client,
interaction.guild.id,
interaction.user.id,
@ -953,7 +957,7 @@ class Aurora(commands.Cog):
except discord.errors.HTTPException:
pass
moderation = await Moderation.log(
moderation = Moderation.log(
interaction.client,
interaction.guild.id,
interaction.user.id,
@ -997,7 +1001,7 @@ class Aurora(commands.Cog):
await channel.edit(slowmode_delay=interval)
await interaction.response.send_message(f"Slowmode in {channel.mention} has been set to {interval} seconds!\n**Reason** - `{reason}`")
moderation = await Moderation.log(
moderation = Moderation.log(
interaction.client,
interaction.guild.id,
interaction.user.id,
@ -1042,7 +1046,7 @@ class Aurora(commands.Cog):
inline: bool
Display infractions in a grid arrangement (does not look very good)
export: bool
Exports the server's moderation history to a JSON file"""
Exports the server's entire moderation history to a JSON file"""
if ephemeral is None:
ephemeral = (
await config.user(interaction.user).history_ephemeral()
@ -1085,45 +1089,47 @@ class Aurora(commands.Cog):
)
return
if target:
filename = f"moderation_target_{str(target.id)}_{str(interaction.guild.id)}.json"
moderations = await Moderation.find_by_target(interaction.client, interaction.guild.id, target.id)
elif moderator:
filename = f"moderation_moderator_{str(moderator.id)}_{str(interaction.guild.id)}.json"
moderations = await Moderation.find_by_moderator(interaction.client, interaction.guild.id, moderator.id)
else:
filename = f"moderation_{str(interaction.guild.id)}.json"
moderations = await Moderation.get_latest(interaction.client, interaction.guild.id)
database = connect()
if export:
try:
filepath = (
filename = (
str(data_manager.cog_data_path(cog_instance=self))
+ str(os.sep)
+ filename
+ f"moderation_{interaction.guild.id}.json"
)
with open(filepath, "w", encoding="utf-8") as f:
dump(obj=moderations, fp=f, indent=2)
cases = Moderation.get_latest(bot=interaction.client, guild_id=interaction.guild.id)
with open(filename, "w", encoding="utf-8") as f:
dump(obj=cases, fp=f, indent=2)
await interaction.followup.send(
file=discord.File(
fp=filepath, filename=filename
filename, f"moderation_{interaction.guild.id}.json"
),
ephemeral=ephemeral,
)
os.remove(filepath)
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(text=e, lang="py"),
+ box(e, "py"),
ephemeral=ephemeral,
)
database.close()
return
if target:
moderations = Moderation.find_by_target(interaction.client, interaction.guild.id, target.id)
elif moderator:
moderations = Moderation.find_by_moderator(interaction.client, interaction.guild.id, moderator.id)
else:
moderations = Moderation.get_latest(interaction.client, interaction.guild.id)
case_quantity = len(moderations)
page_quantity = ceil(case_quantity / pagesize)
start_index = (page - 1) * pagesize
@ -1208,7 +1214,7 @@ class Aurora(commands.Cog):
return
try:
moderation = await Moderation.find_by_id(interaction.client, case, interaction.guild.id)
moderation = 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
@ -1246,9 +1252,9 @@ class Aurora(commands.Cog):
@app_commands.command(name="case")
@app_commands.choices(
raw=[
Choice(name="Export as Codeblock", value="codeblock"),
export=[
Choice(name="Export as File", value="file"),
Choice(name="Export as Codeblock", value="codeblock"),
]
)
async def case(
@ -1258,7 +1264,7 @@ class Aurora(commands.Cog):
ephemeral: bool | None = None,
evidenceformat: bool = False,
changes: bool = False,
raw: Choice[str] | None = None,
export: Choice[str] | None = None,
):
"""Check the details of a specific case.
@ -1268,11 +1274,9 @@ 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
raw: bool
export: bool
Export the case to a JSON file or codeblock"""
permissions = check_permissions(
interaction.client.user, ["embed_links"], interaction
@ -1294,15 +1298,15 @@ class Aurora(commands.Cog):
)
try:
mod = await Moderation.find_by_id(interaction.client, case, interaction.guild.id)
mod = 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 raw:
if raw.value == "file" or len(mod.to_json(2)) > 1800:
if export:
if export.value == "file" or len(mod.to_json(2)) > 1800:
filename = (
str(data_manager.cog_data_path(cog_instance=self))
+ str(os.sep)
@ -1311,7 +1315,7 @@ class Aurora(commands.Cog):
with open(filename, "w", encoding="utf-8") as f:
mod.to_json(2, f)
if raw.value == "codeblock":
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."
)
@ -1387,7 +1391,7 @@ class Aurora(commands.Cog):
return
try:
moderation = await Moderation.find_by_id(interaction.client, case, interaction.guild.id)
moderation = Moderation.find_by_id(interaction.client, case, interaction.guild.id)
old_moderation = moderation
except ValueError:
await interaction.response.send_message(
@ -1465,7 +1469,7 @@ class Aurora(commands.Cog):
"end_timestamp": moderation.end_timestamp,
}))
await moderation.update()
moderation.update()
embed = await case_factory(interaction=interaction, moderation=moderation)
await interaction.response.send_message(
@ -1481,6 +1485,8 @@ class Aurora(commands.Cog):
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
@ -1490,17 +1496,20 @@ class Aurora(commands.Cog):
if not await self.bot.cog_disabled_in_guild(self, guild):
time_per_guild = time.time()
tempban_query = f"SELECT * FROM moderation_{guild.id} WHERE end_timestamp IS NOT NULL AND end_timestamp <= ? AND moderation_type = 'TEMPBAN' AND expired = 0"
tempbans = await Moderation.execute(bot=self.bot, guild_id=guild.id, query=tempban_query, parameters=(time.time(),))
tempban_query = f"SELECT target_id, moderation_id FROM moderation_{guild.id} WHERE end_timestamp IS NOT NULL 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]
unban_num = 0
for moderation in tempbans:
user = self.bot.get_user(moderation.target_id)
if user is None:
try:
user = await self.bot.fetch_user(moderation.target_id)
except discord.errors.NotFound:
continue
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"
@ -1508,14 +1517,14 @@ class Aurora(commands.Cog):
)
try:
await guild.unban(
user, reason=f"Automatic unban from case #{moderation.id}"
user, reason=f"Automatic unban from case #{moderation_id}"
)
embed = await message_factory(
bot=self.bot,
color=await self.bot.get_embed_color(guild.channels[0]),
guild=guild,
reason=f"Automatic unban from case #{moderation.id}",
reason=f"Automatic unban from case #{moderation_id}",
moderation_type="unbanned",
)
@ -1524,14 +1533,14 @@ class Aurora(commands.Cog):
except discord.errors.HTTPException:
pass
logger.trace(
logger.debug(
"Unbanned %s (%s) from %s (%s)",
name,
user.id,
guild.name,
guild.id,
)
unban_num += 1
unban_num = unban_num + 1
except (
discord.errors.NotFound,
discord.errors.Forbidden,
@ -1547,23 +1556,26 @@ class Aurora(commands.Cog):
)
removerole_num = 0
addrole_query = f"SELECT * FROM moderation_{guild.id} WHERE end_timestamp IS NOT NULL AND end_timestamp <= ? AND moderation_type = 'ADDROLE' AND expired = 0"
addroles = await Moderation.execute(bot=self.bot, guild_id=guild.id, query=addrole_query, parameters=(time.time(),))
addrole_query = f"SELECT target_id, moderation_id, role_id FROM moderation_{guild.id} WHERE end_timestamp IS NOT NULL 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 moderation in addroles:
for target_id, moderation_id, role_id in zip(
target_ids, moderation_ids, role_ids
):
try:
member = await guild.fetch_member(moderation.target_id)
member = await guild.fetch_member(target_id)
await member.remove_roles(
Object(moderation.role_id), reason=f"Automatic role removal from case #{moderation.id}"
Object(role_id), reason=f"Automatic role removal from case #{moderation_id}"
)
logger.trace(
"Removed role %s from %s (%s)",
moderation.role_id,
member.name,
member.id,
)
removerole_num = removerole_num + 1
except (
discord.errors.NotFound,
@ -1572,36 +1584,44 @@ class Aurora(commands.Cog):
) as e:
logger.error(
"Removing the role %s from user %s failed due to: \n%s",
moderation.role_id,
moderation.target_id,
role_id,
target_id,
e,
)
continue
addrole_num = 0
removerole_query = f"SELECT * FROM moderation_{guild.id} WHERE end_timestamp IS NOT NULL AND end_timestamp <= ? AND moderation_type = 'REMOVEROLE' AND expired = 0"
removeroles = await Moderation.execute(bot=self.bot, guild_id=guild.id, query=removerole_query, parameters=(time.time(),))
removerole_query = f"SELECT target_id, moderation_id, role_id FROM moderation_{guild.id} WHERE end_timestamp IS NOT NULL 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 moderation in removeroles:
for target_id, moderation_id, role_id in zip(
target_ids, moderation_ids, role_ids
):
try:
member = await guild.fetch_member(moderation.target_id)
member = await guild.fetch_member(target_id)
await member.add_roles(
Object(moderation.role_id), reason=f"Automatic role addition from case #{moderation.id}"
Object(role_id), reason=f"Automatic role addition from case #{moderation_id}"
)
logger.trace("Added role %s to %s (%s)", moderation.role_id, member.name, member.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", moderation.role_id, moderation.target_id, e)
logger.error("Adding the role %s to user %s failed due to: \n%s", role_id, target_id, e)
continue
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)
cursor.execute(expiry_query, (time.time(),))
per_guild_completion_time = (time.time() - time_per_guild) * 1000
logger.debug(
@ -1617,6 +1637,9 @@ class Aurora(commands.Cog):
global_addrole_num = global_addrole_num + addrole_num
global_removerole_num = global_removerole_num + removerole_num
database.commit()
cursor.close()
database.close()
completion_time = (time.time() - current_time) * 1000
logger.debug(

View file

@ -1,16 +1,15 @@
# pylint: disable=duplicate-code
import json
import os
from time import time
from typing import Dict
from discord import ButtonStyle, File, Interaction, Message, ui
from redbot.core import commands, data_manager
from redbot.core.utils.chat_formatting import warning
from discord import ButtonStyle, Interaction, Message, ui
from redbot.core import commands
from redbot.core.utils.chat_formatting import box, warning
from ..models.moderation import Moderation
from ..utilities.json import dump
from ..utilities.utils import create_guild_table, timedelta_from_string
from ..utilities.database import connect, create_guild_table
from ..utilities.utils import timedelta_from_string
class ImportAuroraView(ui.View):
@ -28,8 +27,14 @@ class ImportAuroraView(ui.View):
"Deleting original table...", ephemeral=True
)
database = connect()
cursor = database.cursor()
query = f"DROP TABLE IF EXISTS moderation_{self.ctx.guild.id};"
await Moderation.execute(query=query, return_obj=False)
cursor.execute(query)
cursor.close()
database.commit()
await interaction.edit_original_response(content="Creating new table...")
@ -91,7 +96,7 @@ class ImportAuroraView(ui.View):
duration = None
try:
await Moderation.log(
Moderation.log(
bot=interaction.client,
guild_id=self.ctx.guild.id,
moderator_id=case["moderator_id"],
@ -108,6 +113,7 @@ class ImportAuroraView(ui.View):
expired=case["expired"],
changes=changes,
metadata=metadata,
database=database,
return_obj=False
)
except Exception as e: # pylint: disable=broad-exception-caught
@ -115,25 +121,12 @@ class ImportAuroraView(ui.View):
await interaction.edit_original_response(content="Import complete.")
if 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(
await interaction.edit_original_response(
content="Import complete.\n"
+ warning("Failed to import the following cases:\n"),
file=File(
filename, f"failed_cases_{interaction.guild.id}.json"
)
+ warning("Failed to import the following cases:\n")
+ box(failed_cases)
)
os.remove(filename)
@ui.button(label="No", style=ButtonStyle.danger)
async def import_button_n(
self, interaction: Interaction, button: ui.Button

View file

@ -8,14 +8,13 @@ from redbot.core import commands
from redbot.core.utils.chat_formatting import box, warning
from ..models.moderation import Change, Moderation
from ..utilities.database import create_guild_table
from ..utilities.database import connect, 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)
@ -27,14 +26,14 @@ class ImportGalacticBotView(ui.View):
"Deleting original table...", ephemeral=True
)
database = await Moderation.connect()
cursor = await database.cursor()
database = connect()
cursor = database.cursor()
query = f"DROP TABLE IF EXISTS moderation_{self.ctx.guild.id};"
await cursor.execute(query)
cursor.execute(query)
await cursor.close()
await database.commit()
cursor.close()
database.commit()
await interaction.edit_original_response(content="Creating new table...")
@ -125,7 +124,7 @@ class ImportGalacticBotView(ui.View):
else:
reason = None
await Moderation.log(
Moderation.log(
self.ctx.guild.id,
case["executor"],
case["type"],

View file

@ -9,7 +9,7 @@
"disabled": false,
"min_bot_version": "3.5.0",
"min_python_version": [3, 10, 0],
"requirements": ["pydantic", "aiosqlite"],
"requirements": ["pydantic"],
"tags": [
"mod",
"moderate",

View file

@ -1,6 +1,5 @@
from typing import Any, Optional
from typing import Any
from discord import Guild
from pydantic import BaseModel, ConfigDict
from redbot.core.bot import Red
@ -13,19 +12,17 @@ class AuroraBaseModel(BaseModel):
def dump(self) -> dict:
return self.model_dump(exclude={"bot"})
def to_json(self, indent: int | None = None, file: Any | None = None, **kwargs) -> str:
def to_json(self, indent: int | None = None, file: Any | None = None, **kwargs):
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)
return dump(self.dump(), file, indent=indent, **kwargs) if file else dumps(self.model_dump(exclude={"bot"}), indent=indent, **kwargs)
class AuroraGuildModel(AuroraBaseModel):
"""Subclass of AuroraBaseModel that includes a guild_id attribute and a guild attribute, and a modified to_json() method to match."""
model_config = ConfigDict(ignored_types=(Red, Guild), arbitrary_types_allowed=True)
"""Subclass of AuroraBaseModel that includes a guild_id attribute, and a modified to_json() method to match."""
guild_id: int
guild: Optional[Guild] = None
def dump(self) -> dict:
return self.model_dump(exclude={"bot", "guild_id", "guild"})
return self.model_dump(exclude={"bot", "guild_id"})
def to_json(self, indent: int | None = None, file: Any | None = None, **kwargs) -> str:
def to_json(self, indent: int | None = None, file: Any | None = None, **kwargs):
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)
return dump(self.dump(), file, indent=indent, **kwargs) if file else dumps(self.model_dump(exclude={"bot", "guild_id"}), indent=indent, **kwargs)

View file

@ -1,14 +1,12 @@
import json
import sqlite3
from datetime import datetime, timedelta
from sqlite3 import Cursor
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 discord import NotFound
from redbot.core import data_manager
from redbot.core.bot import Red
from ..utilities.logger import logger
@ -54,7 +52,7 @@ class Moderation(AuroraGuildModel):
async def get_target(self) -> Union["PartialUser", "PartialChannel"]:
if self.target_type == "USER":
return await PartialUser.from_id(self.bot, self.target_id)
return await PartialChannel.from_id(self.bot, self.target_id, self.guild)
return await PartialChannel.from_id(self.bot, self.target_id)
async def get_resolved_by(self) -> Optional["PartialUser"]:
if self.resolved_by:
@ -63,7 +61,7 @@ class Moderation(AuroraGuildModel):
async def get_role(self) -> Optional["PartialRole"]:
if self.role_id:
return await PartialRole.from_id(self.bot, self.guild, self.role_id)
return await PartialRole.from_id(self.bot, self.guild_id, self.role_id)
return None
def __str__(self) -> str:
@ -117,31 +115,33 @@ class Moderation(AuroraGuildModel):
"user_id": resolved_by,
}))
await self.update()
self.update()
async def update(self) -> None:
def update(self) -> None:
from ..utilities.database import connect
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,
self.target_type,
self.moderator_id,
self.role_id,
str(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,
))
with connect() as database:
database.execute(query, (
self.timestamp.timestamp(),
self.moderation_type,
self.target_type,
self.moderator_id,
self.role_id,
str(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",
logger.debug("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(),
@ -162,14 +162,6 @@ class Moderation(AuroraGuildModel):
@classmethod
def from_dict(cls, bot: Red, data: dict) -> "Moderation":
if data.get("guild_id"):
try:
guild: discord.Guild = bot.get_guild(data["guild_id"])
if not guild:
guild = bot.fetch_guild(data["guild_id"])
except (discord.Forbidden, discord.HTTPException):
guild = None
data.update({"guild": guild})
return cls(bot=bot, **data)
@classmethod
@ -213,51 +205,37 @@ class Moderation(AuroraGuildModel):
}
return 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]]:
logger.trace("Executing query: \"%s\" with parameters \"%s\"", query, parameters)
def execute(cls, bot: Red, guild_id: int, query: str, parameters: tuple | None = None, cursor: Cursor | None = None) -> Tuple["Moderation"]:
from ..utilities.database import connect
logger.trace("Executing query: %s", query)
logger.trace("With parameters: %s", parameters)
if not parameters:
parameters = ()
if not cursor:
no_cursor = True
database = await cls.connect()
cursor = await database.cursor()
database = connect()
cursor = database.cursor()
else:
no_cursor = False
await cursor.execute(query, parameters)
results = await cursor.fetchall()
await database.commit()
cursor.execute(query, parameters)
results = cursor.fetchall()
if no_cursor:
await cursor.close()
await database.close()
cursor.close()
database.close()
if results and return_obj and bot and guild_id:
if results:
cases = []
for result in results:
case = cls.from_result(bot=bot, result=result, guild_id=guild_id)
if case.moderation_id != 0:
cases.append(case)
return tuple(cases)
return results
return ()
@classmethod
async def get_latest(cls, bot: Red, guild_id: int, limit: int | None = None, offset: int = 0, types: Iterable | None = None, cursor: Cursor | None = None) -> Tuple["Moderation"]:
def get_latest(cls, bot: Red, guild_id: int, limit: int | None = None, offset: int = 0, types: Iterable | None = None, cursor: Cursor | None = None) -> Tuple["Moderation"]:
params = []
query = f"SELECT * FROM moderation_{guild_id} ORDER BY moderation_id DESC"
if types:
@ -267,41 +245,41 @@ class Moderation(AuroraGuildModel):
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)
return 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)
def get_next_case_number(cls, bot: Red, guild_id: int, cursor: Cursor | None = None) -> int:
result = 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":
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)
case = 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, types: Iterable | None = None, cursor: Cursor | None = None) -> Tuple["Moderation"]:
def find_by_target(cls, bot: Red, guild_id: int, target: int, types: Iterable | None = None, cursor: Cursor | None = None) -> Tuple["Moderation"]:
query = f"SELECT * FROM moderation_{guild_id} WHERE target_id = ?"
if types:
query += f" AND moderation_type IN ({', '.join(['?' for _ in types])})"
query += " ORDER BY moderation_id DESC;"
return await cls.execute(bot=bot, guild_id=guild_id, query=query, parameters=(target, *types) if types else (target,), cursor=cursor)
return cls.execute(bot=bot, guild_id=guild_id, query=query, parameters=(target, *types) if types else (target,), cursor=cursor)
@classmethod
async def find_by_moderator(cls, bot: Red, guild_id: int, moderator: int, types: Iterable | None = None, cursor: Cursor | None = None) -> Tuple["Moderation"]:
def find_by_moderator(cls, bot: Red, guild_id: int, moderator: int, types: Iterable | None = None, cursor: Cursor | None = None) -> Tuple["Moderation"]:
query = f"SELECT * FROM moderation_{guild_id} WHERE moderator_id = ?"
if types:
query += f" AND moderation_type IN ({', '.join(['?' for _ in types])})"
query += " ORDER BY moderation_id DESC;"
return await cls.execute(bot=bot, guild_id=guild_id, query=query, parameters=(moderator, *types) if types else (moderator,), cursor=cursor)
return cls.execute(bot=bot, guild_id=guild_id, query=query, parameters=(moderator, *types) if types else (moderator,), cursor=cursor)
@classmethod
async def log(
def log(
cls,
bot: Red,
guild_id: int,
@ -322,6 +300,7 @@ class Moderation(AuroraGuildModel):
metadata: dict | None = None,
return_obj: bool = True,
) -> Union["Moderation", int]:
from ..utilities.database import connect
from ..utilities.json import dumps
if not timestamp:
timestamp = datetime.fromtimestamp(time())
@ -356,12 +335,13 @@ class Moderation(AuroraGuildModel):
role_id = None
if not database:
database = await cls.connect()
database = connect()
close_db = True
else:
close_db = False
cursor = database.cursor()
moderation_id = await cls.get_next_case_number(bot=bot, guild_id=guild_id)
moderation_id = cls.get_next_case_number(bot=bot, guild_id=guild_id, cursor=cursor)
case = {
"moderation_id": moderation_id,
@ -383,13 +363,14 @@ class Moderation(AuroraGuildModel):
}
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()))
cursor.execute(sql, tuple(case.values()))
await database.commit()
cursor.close()
database.commit()
if close_db:
await database.close()
database.close()
logger.verbose(
logger.debug(
"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"],
@ -411,5 +392,5 @@ class Moderation(AuroraGuildModel):
)
if return_obj:
return await cls.find_by_id(bot=bot, moderation_id=moderation_id, guild_id=guild_id)
return cls.find_by_id(bot=bot, moderation_id=moderation_id, guild_id=guild_id)
return moderation_id

View file

@ -1,4 +1,4 @@
from discord import ChannelType, Forbidden, Guild, HTTPException, InvalidData, NotFound
from discord import Forbidden, HTTPException, InvalidData, NotFound
from redbot.core.bot import Red
from .base import AuroraBaseModel, AuroraGuildModel
@ -31,7 +31,6 @@ class PartialUser(AuroraBaseModel):
class PartialChannel(AuroraGuildModel):
id: int
name: str
type: ChannelType
@property
def mention(self):
@ -43,17 +42,17 @@ class PartialChannel(AuroraGuildModel):
return self.mention
@classmethod
async def from_id(cls, bot: Red, channel_id: int, guild: Guild) -> "PartialChannel":
async def from_id(cls, bot: Red, channel_id: int) -> "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)
return cls(bot=bot, guild_id=channel.guild.id, id=channel.id, name=channel.name)
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)
return cls(bot=bot, guild_id=channel.guild.id, guild=guild, id=channel.id, name=channel.name, type=channel.type)
return cls(bot=bot, guild_id=0, id=channel_id, name="Deleted Channel")
return cls(bot=bot, guild_id=channel.guild.id, id=channel.id, name=channel.name)
class PartialRole(AuroraGuildModel):
id: int
@ -69,8 +68,12 @@ class PartialRole(AuroraGuildModel):
return self.mention
@classmethod
async def from_id(cls, bot: Red, guild: Guild, role_id: int) -> "PartialRole":
async def from_id(cls, bot: Red, guild_id: int, role_id: int) -> "PartialRole":
try:
guild = await bot.fetch_guild(guild_id, with_counts=False)
except (Forbidden, HTTPException):
return cls(bot=bot, guild_id=guild_id, id=role_id, name="Forbidden Role")
role = guild.get_role(role_id)
if not role:
return cls(bot=bot, guild_id=guild.id, id=role_id, name="Deleted Role")
return cls(bot=bot, guild_id=guild.id, id=role.id, name=role.name)
return cls(bot=bot, guild_id=guild_id, id=role_id, name="Deleted Role")
return cls(bot=bot, guild_id=guild_id, id=role.id, name=role.name)

View file

@ -0,0 +1,100 @@
# pylint: disable=cyclic-import
import json
import sqlite3
from discord import Guild
from redbot.core import data_manager
from .logger import logger
def connect() -> sqlite3.Connection:
"""Connects to the SQLite database, and returns a connection object."""
try:
connection = sqlite3.connect(
database=data_manager.cog_data_path(raw_name="Aurora") / "aurora.db"
)
return connection
except sqlite3.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
async def create_guild_table(guild: Guild):
database = connect()
cursor = database.cursor()
try:
cursor.execute(f"SELECT * FROM `moderation_{guild.id}`")
logger.debug("SQLite Table exists for server %s (%s)", guild.name, guild.id)
except sqlite3.OperationalError:
query = f"""
CREATE TABLE `moderation_{guild.id}` (
moderation_id INTEGER PRIMARY KEY,
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
)
"""
cursor.execute(query)
index_query_1 = f"CREATE INDEX IF NOT EXISTS idx_target_id ON moderation_{guild.id}(target_id);"
cursor.execute(index_query_1)
index_query_2 = f"CREATE INDEX IF NOT EXISTS idx_moderator_id ON moderation_{guild.id}(moderator_id);"
cursor.execute(index_query_2)
index_query_3 = f"CREATE INDEX IF NOT EXISTS idx_moderation_id ON moderation_{guild.id}(moderation_id);"
cursor.execute(index_query_3)
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,
json.dumps([]),
json.dumps({}),
)
cursor.execute(insert_query, insert_values)
database.commit()
logger.debug(
"SQLite Table (moderation_%s) created for %s (%s)",
guild.id,
guild.name,
guild.id,
)
database.close()

View file

@ -91,7 +91,7 @@ async def message_factory(
embed.set_author(name=guild.name)
embed.set_footer(
text=f"Case #{await Moderation.get_next_case_number(bot=bot, guild_id=guild.id):,}",
text=f"Case #{Moderation.get_next_case_number(bot=bot, guild_id=guild.id):,}",
icon_url="attachment://arrow.png",
)

View file

@ -2,7 +2,6 @@
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, TextChannel, User
from discord.errors import Forbidden
@ -10,8 +9,6 @@ from redbot.core import commands, data_manager
from redbot.core.utils.chat_formatting import error
from ..utilities.config import config
from ..utilities.json import dumps
from ..utilities.logger import logger
def check_permissions(
@ -123,7 +120,7 @@ async def log(interaction: Interaction, moderation_id: int, resolved: bool = Fal
logging_channel = interaction.guild.get_channel(logging_channel_id)
try:
moderation = await Moderation.find_by_id(interaction.client, moderation_id, interaction.guild_id)
moderation = Moderation.find_by_id(interaction.client, moderation_id, interaction.guild_id)
embed = await log_factory(
interaction=interaction, moderation=moderation, resolved=resolved
)
@ -148,7 +145,7 @@ async def send_evidenceformat(interaction: Interaction, moderation_id: int) -> N
if send_evidence_bool is False:
return
moderation = await Moderation.find_by_id(interaction.client, moderation_id, interaction.guild.id)
moderation = Moderation.find_by_id(interaction.client, moderation_id, interaction.guild.id)
content = await evidenceformat_factory(moderation=moderation)
await interaction.followup.send(content=content, ephemeral=True)
@ -213,69 +210,3 @@ 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,
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)

20
poetry.lock generated
View file

@ -123,24 +123,6 @@ files = [
[package.dependencies]
frozenlist = ">=1.1.0"
[[package]]
name = "aiosqlite"
version = "0.20.0"
description = "asyncio bridge to the standard sqlite3 module"
optional = false
python-versions = ">=3.8"
files = [
{file = "aiosqlite-0.20.0-py3-none-any.whl", hash = "sha256:36a1deaca0cac40ebe32aac9977a6e2bbc7f5189f23f4a54d5908986729e5bd6"},
{file = "aiosqlite-0.20.0.tar.gz", hash = "sha256:6d35c8c256637f4672f843c31021464090805bf925385ac39473fb16eaaca3d7"},
]
[package.dependencies]
typing_extensions = ">=4.0"
[package.extras]
dev = ["attribution (==1.7.0)", "black (==24.2.0)", "coverage[toml] (==7.4.1)", "flake8 (==7.0.0)", "flake8-bugbear (==24.2.6)", "flit (==3.9.0)", "mypy (==1.8.0)", "ufmt (==2.3.0)", "usort (==1.0.8.post1)"]
docs = ["sphinx (==7.2.6)", "sphinx-mdinclude (==0.5.3)"]
[[package]]
name = "annotated-types"
version = "0.7.0"
@ -2673,4 +2655,4 @@ multidict = ">=4.0"
[metadata]
lock-version = "2.0"
python-versions = ">=3.11,<3.12"
content-hash = "22b824824f73dc3dc1a9a0a01060371ee1f6414e5bef39cb7455d21121988b47"
content-hash = "3f732c0b0b0eb2a31fb9484c7cf699cd3c26474d6779528102af4c509a48351e"

View file

@ -18,7 +18,6 @@ pydantic = "^2.7.1"
colorthief = "^0.2.1"
beautifulsoup4 = "^4.12.3"
markdownify = "^0.12.1"
aiosqlite = "^0.20.0"
[tool.poetry.group.dev]
optional = true