From 9abbe12270c42644849c07701fc0b979f03dd5e4 Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 04:23:30 -0500 Subject: [PATCH 01/16] repo: added repository info.json --- info.json | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 info.json diff --git a/info.json b/info.json new file mode 100644 index 0000000..04f29ab --- /dev/null +++ b/info.json @@ -0,0 +1,9 @@ +{ + "author": [ + "SeaswimmerTheFsh (seasw.)" + ], + "install_msg": "Thanks for installing my repo!\n\nIf you have any issues with any of the cogs, please create an issue [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs/issues) or join my [Discord Server](https://discord.gg/eMUMe77Yb8 ).", + "name": "SeaCogs", + "short": "Various cogs for Red, by SeaswimmerTheFsh (seasw.)", + "description": "Various cogs for Red, by SeaswimmerTheFsh (seasw.)" +} -- 2.45.2 From ca50deedd566bcbe583ff4d09802745a79108ca1 Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 04:23:55 -0500 Subject: [PATCH 02/16] feat(aurora): renamed moderation cog to aurora, converted to sqlite3 --- aurora/__init__.py | 5 + moderation/moderation.py => aurora/aurora.py | 141 +++--------------- {moderation => aurora}/importers/__init__.py | 0 .../importers/aurora.py | 11 +- .../importers/galacticbot.py | 2 +- aurora/info.json | 11 ++ {moderation => aurora}/utilities/__init__.py | 0 {moderation => aurora}/utilities/config.py | 6 - {moderation => aurora}/utilities/database.py | 52 +++---- .../utilities/embed_factory.py | 0 {moderation => aurora}/utilities/logger.py | 0 {moderation => aurora}/utilities/utils.py | 2 +- moderation/__init__.py | 5 - moderation/info.json | 11 -- 14 files changed, 63 insertions(+), 183 deletions(-) create mode 100644 aurora/__init__.py rename moderation/moderation.py => aurora/aurora.py (92%) rename {moderation => aurora}/importers/__init__.py (100%) rename moderation/importers/moderation.py => aurora/importers/aurora.py (94%) rename {moderation => aurora}/importers/galacticbot.py (99%) create mode 100644 aurora/info.json rename {moderation => aurora}/utilities/__init__.py (100%) rename {moderation => aurora}/utilities/config.py (83%) rename {moderation => aurora}/utilities/database.py (79%) rename {moderation => aurora}/utilities/embed_factory.py (100%) rename {moderation => aurora}/utilities/logger.py (100%) rename {moderation => aurora}/utilities/utils.py (99%) delete mode 100644 moderation/__init__.py delete mode 100644 moderation/info.json diff --git a/aurora/__init__.py b/aurora/__init__.py new file mode 100644 index 0000000..49ef5ec --- /dev/null +++ b/aurora/__init__.py @@ -0,0 +1,5 @@ +from .aurora import Aurora + + +async def setup(bot): + await bot.add_cog(Aurora(bot)) diff --git a/moderation/moderation.py b/aurora/aurora.py similarity index 92% rename from moderation/moderation.py rename to aurora/aurora.py index 31da9b1..3b4ddd5 100644 --- a/moderation/moderation.py +++ b/aurora/aurora.py @@ -8,19 +8,19 @@ import json import os import time +import sqlite3 from datetime import datetime, timedelta, timezone from math import ceil import discord import humanize -import mysql.connector from discord.ext import tasks from pytimeparse2 import disable_dateutil, parse from redbot.core import app_commands, checks, commands, data_manager from redbot.core.app_commands import Choice from .importers.galacticbot import ImportGalacticBotView -from .importers.moderation import ImportModerationView +from .importers.aurora import ImportAuroraView from .utilities.config import config, register_config from .utilities.database import connect, create_guild_table, fetch_case, mysql_log from .utilities.embed_factory import embed_factory @@ -28,7 +28,7 @@ from .utilities.logger import logger from .utilities.utils import check_conf, check_moddable, check_permissions, fetch_channel_dict, fetch_user_dict, generate_dict, log, send_evidenceformat -class Moderation(commands.Cog): +class Aurora(commands.Cog): """Custom moderation cog. Developed by SeaswimmerTheFsh.""" @@ -36,7 +36,7 @@ class Moderation(commands.Cog): if requester == "discord_deleted_user": await config.user_from_id(user_id).clear() - database = await connect() + database = connect() cursor = database.cursor() cursor.execute("SHOW TABLES;") @@ -68,17 +68,6 @@ class Moderation(commands.Cog): async def cog_load(self): """This method prepares the database schema for all of the guilds the bot is currently in.""" - conf = await check_conf([ - 'mysql_address', - 'mysql_database', - 'mysql_username', - 'mysql_password' - ]) - - if conf: - logger.error("Failed to create tables, due to MySQL connection configuration being unset.") - return - guilds: list[discord.Guild] = self.bot.guilds try: @@ -96,20 +85,8 @@ class Moderation(commands.Cog): async def db_generate_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): - conf = await check_conf([ - 'mysql_address', - 'mysql_database', - 'mysql_username', - 'mysql_password' - - ]) - if conf: - logger.error("Failed to create a table for %s, due to MySQL connection configuration being unset.", guild.id) - return - try: await create_guild_table(guild) - except ConnectionRefusedError: return @@ -592,7 +569,7 @@ class Moderation(commands.Cog): await interaction.followup.send(f"I do not have the `{permissions}` permission, required for this action.", ephemeral=True) return - database = await connect() + database = connect() if export: cursor = database.cursor(dictionary=True) @@ -714,13 +691,8 @@ class Moderation(commands.Cog): await interaction.response.send_message(f"I do not have the `{permissions}` permission, required for this action.", ephemeral=True) return - conf = await check_conf(['mysql_database']) - if conf: - raise(LookupError) - - database = await connect() + database = connect() cursor = database.cursor() - db = await config.mysql_database() query_1 = "SELECT * FROM moderation_%s WHERE moderation_id = %s;" cursor.execute(query_1, (interaction.guild.id, case)) @@ -782,9 +754,9 @@ class Moderation(commands.Cog): except discord.NotFound: pass - resolve_query = f"UPDATE `{db}`.`moderation_{interaction.guild.id}` SET resolved = 1, changes = %s, resolved_by = %s, resolve_reason = %s WHERE moderation_id = %s" + resolve_query = f"UPDATE `moderation_{interaction.guild.id}` SET resolved = 1, changes = %s, resolved_by = %s, resolve_reason = %s WHERE moderation_id = %s" else: - resolve_query = f"UPDATE `{db}`.`moderation_{interaction.guild.id}` SET resolved = 1, changes = %s, resolved_by = %s, resolve_reason = %s WHERE moderation_id = %s" + resolve_query = f"UPDATE `moderation_{interaction.guild.id}` SET resolved = 1, changes = %s, resolved_by = %s, resolve_reason = %s WHERE moderation_id = %s" cursor.execute(resolve_query, (json.dumps(changes), interaction.user.id, reason, case_dict['moderation_id'])) database.commit() @@ -941,7 +913,7 @@ class Moderation(commands.Cog): } ) - database = await connect() + database = connect() cursor = database.cursor() db = await config.mysql_database() @@ -970,7 +942,7 @@ class Moderation(commands.Cog): if conf: raise(LookupError) - database = await connect() + database = connect() cursor = database.cursor() db = await config.mysql_database() @@ -983,7 +955,7 @@ class Moderation(commands.Cog): try: cursor.execute(tempban_query, (time.time(),)) result = cursor.fetchall() - except mysql.connector.errors.ProgrammingError: + except sqlite3.ProgrammingError: continue target_ids = [row[0] for row in result] @@ -1010,8 +982,7 @@ class Moderation(commands.Cog): try: cursor.execute(blacklist_query, (time.time(),)) result = cursor.fetchall() - except mysql.connector.errors.ProgrammingError: - + except sqlite3.ProgrammingError: continue target_ids = [row[0] for row in result] moderation_ids = [row[1] for row in result] @@ -1047,7 +1018,7 @@ class Moderation(commands.Cog): guild_settings_string = "" for setting in guild_settings: - if 'mysql' in setting or 'roles' in setting: + if 'roles' in setting: continue if setting == 'log_channel': channel = ctx.guild.get_channel(guild_settings[setting]) @@ -1323,96 +1294,20 @@ class Moderation(commands.Cog): await config.guild(ctx.guild).log_channel.set(" ") await ctx.send("Logging channel disabled.") - @moderationset.command(name="mysql") - @checks.is_owner() - async def moderationset_mysql(self, ctx: commands.Context): - """Configure MySQL connection details.""" - await ctx.message.add_reaction("✅") - await ctx.author.send(content="Click the button below to configure your MySQL connection details.", view=self.ConfigButtons(60)) - - class ConfigButtons(discord.ui.View): - def __init__(self, timeout): - super().__init__() - - @discord.ui.button(label="Edit", style=discord.ButtonStyle.success) - async def config_button(self, interaction: discord.Interaction, button: discord.ui.Button): # pylint: disable=unused-argument - await interaction.response.send_modal(Moderation.MySQLConfigModal) - - class MySQLConfigModal(discord.ui.Modal, title="MySQL Database Configuration"): - def __init__(self): - super().__init__() - address = discord.ui.TextInput( - label="Address", - placeholder="Input your MySQL address here.", - style=discord.TextStyle.short, - required=False, - max_length=300 - ) - database = discord.ui.TextInput( - label="Database", - placeholder="Input the name of your database here.", - style=discord.TextStyle.short, - required=False, - max_length=300 - ) - username = discord.ui.TextInput( - label="Username", - placeholder="Input your MySQL username here.", - style=discord.TextStyle.short, - required=False, - max_length=300 - ) - password = discord.ui.TextInput( - label="Password", - placeholder="Input your MySQL password here.", - style=discord.TextStyle.short, - required=False, - max_length=300 - ) - - async def on_submit(self, interaction: discord.Interaction): - message = "" - - if self.address.value != "": - await config.mysql_address.set(self.address.value) - message += f"- Address set to\n - `{self.address.value}`\n" - - if self.database.value != "": - await config.mysql_database.set(self.database.value) - message += f"- Database set to\n - `{self.database.value}`\n" - - if self.username.value != "": - await config.mysql_username.set(self.username.value) - message += f"- Username set to\n - `{self.username.value}`\n" - - if self.password.value != "": - await config.mysql_password.set(self.password.value) - trimmed_password = self.password.value[:8] - message += f"- Password set to\n - `{trimmed_password}` - Trimmed for security\n" - - if message == "": - trimmed_password = str(await config.mysql_password())[:8] - send = f"No changes were made.\nCurrent configuration:\n- Address:\n - `{await config.mysql_address()}`\n- Database:\n - `{await config.mysql_database()}`\n- Username:\n - `{await config.mysql_username()}`\n- Password:\n - `{trimmed_password}` - Trimmed for security" - - else: - send = f"Configuration changed:\n{message}" - - await interaction.response.send_message(send, ephemeral=True) - @moderationset.group(autohelp=True, name='import') @checks.admin() async def moderationset_import(self, ctx: commands.Context): """Import moderations from other bots.""" - @moderationset_import.command(name="moderation") + @moderationset_import.command(name="aurora") @checks.admin() - async def moderationset_import_moderation(self, ctx: commands.Context): - """Import moderations from another bot using this cog.""" + async def moderationset_import_aurora(self, ctx: commands.Context): + """Import moderations 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("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=ImportModerationView(60, ctx, message)) + await message.edit(view=ImportAuroraView(60, ctx, message)) else: - await ctx.send("Please provide a valid moderation export file.") + await ctx.send("Please provide a valid Aurora export file.") @moderationset_import.command(name="galacticbot") @checks.admin() diff --git a/moderation/importers/__init__.py b/aurora/importers/__init__.py similarity index 100% rename from moderation/importers/__init__.py rename to aurora/importers/__init__.py diff --git a/moderation/importers/moderation.py b/aurora/importers/aurora.py similarity index 94% rename from moderation/importers/moderation.py rename to aurora/importers/aurora.py index aaf2c9b..f608dc5 100644 --- a/moderation/importers/moderation.py +++ b/aurora/importers/aurora.py @@ -8,7 +8,7 @@ from redbot.core import commands from ..utilities.database import connect, create_guild_table, mysql_log -class ImportModerationView(ui.View): +class ImportAuroraView(ui.View): def __init__(self, timeout, ctx, message): super().__init__() self.ctx: commands.Context = ctx @@ -23,7 +23,7 @@ class ImportModerationView(ui.View): "Deleting original table...", ephemeral=True ) - database = await connect() + database = connect() cursor = database.cursor() query = f"DROP TABLE IF EXISTS moderation_{self.ctx.guild.id};" @@ -67,9 +67,10 @@ class ImportModerationView(ui.View): metadata = {} else: metadata: Dict[str, any] = case["metadata"] - metadata.update({ - 'imported_from': 'SeaCogs/Moderation' - }) + if not metadata['imported_from']: + metadata.update({ + 'imported_from': 'Aurora' + }) if case["duration"] != "NULL": hours, minutes, seconds = map(int, case["duration"].split(":")) diff --git a/moderation/importers/galacticbot.py b/aurora/importers/galacticbot.py similarity index 99% rename from moderation/importers/galacticbot.py rename to aurora/importers/galacticbot.py index e72b0b5..a4d0e9f 100644 --- a/moderation/importers/galacticbot.py +++ b/aurora/importers/galacticbot.py @@ -18,7 +18,7 @@ class ImportGalacticBotView(ui.View): await self.message.delete() await interaction.response.send_message("Deleting original table...", ephemeral=True) - database = await connect() + database = connect() cursor = database.cursor() query = f"DROP TABLE IF EXISTS moderation_{self.ctx.guild.id};" diff --git a/aurora/info.json b/aurora/info.json new file mode 100644 index 0000000..ccd8b0b --- /dev/null +++ b/aurora/info.json @@ -0,0 +1,11 @@ +{ + "author" : ["SeaswimmerTheFsh"], + "install_msg" : "Thank you for installing Aurora!\nYou can find the source code of this cog [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs).", + "name" : "Aurora", + "short" : "A full replacement for Red's core Mod cogs.", + "description" : "Aurora is designed to be a full replacement for Red's core Mod cogs. 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.", + "end_user_data_statement" : "This cog stores the following information:\n- User IDs of accounts who moderate users or are moderated\n- Guild IDs of guilds with the cog enabled\n- Timestamps of moderations\n- Other information relating to moderations", + "requirements": ["humanize", "pytimeparse2"], + "hidden": false, + "disabled": false +} diff --git a/moderation/utilities/__init__.py b/aurora/utilities/__init__.py similarity index 100% rename from moderation/utilities/__init__.py rename to aurora/utilities/__init__.py diff --git a/moderation/utilities/config.py b/aurora/utilities/config.py similarity index 83% rename from moderation/utilities/config.py rename to aurora/utilities/config.py index 02d7c73..27e666b 100644 --- a/moderation/utilities/config.py +++ b/aurora/utilities/config.py @@ -3,12 +3,6 @@ from redbot.core import Config config: Config = Config.get_conf(None, identifier=481923957134912, cog_name="Moderation") def register_config(config_obj: Config): - config_obj.register_global( - mysql_address= " ", - mysql_database = " ", - mysql_username = " ", - mysql_password = " " - ) config_obj.register_guild( use_discord_permissions = True, ignore_other_bots = True, diff --git a/moderation/utilities/database.py b/aurora/utilities/database.py similarity index 79% rename from moderation/utilities/database.py rename to aurora/utilities/database.py index 53e319f..5ec1883 100644 --- a/moderation/utilities/database.py +++ b/aurora/utilities/database.py @@ -2,51 +2,39 @@ import json import time +import sqlite3 +from os import sep from datetime import datetime -import mysql.connector from discord import Guild +from redbot.core import data_manager -from .config import config from .logger import logger from .utils import check_conf, generate_dict, get_next_case_number -async def connect(): - """Connects to the MySQL database, and returns a connection object.""" - conf = await check_conf( - ["mysql_address", "mysql_database", "mysql_username", "mysql_password"] - ) - - if conf: - raise LookupError("MySQL connection details not set properly!") - +def connect() -> sqlite3.Connection: + """Connects to the SQLite database, and returns a connection object.""" try: - connection = mysql.connector.connect( - host=await config.mysql_address(), - user=await config.mysql_username(), - password=await config.mysql_password(), - database=await config.mysql_database(), - ) - + connection = sqlite3.connect(database=data_manager.cog_data_path(raw_name='Moderation') + sep + 'moderation.db') return connection - except mysql.connector.ProgrammingError as e: - logger.error("Unable to access the MySQL database!\nError:\n%s", e.msg) + except sqlite3.ProgrammingError as e: + logger.error("Unable to access the SQLite database!\nError:\n%s", e.msg) raise ConnectionRefusedError( - f"Unable to access the MySQL Database!\n{e.msg}" + f"Unable to access the SQLite Database!\n{e.msg}" ) from e async def create_guild_table(guild: Guild): - database = await connect() + database = connect() cursor = database.cursor() try: cursor.execute(f"SELECT * FROM `moderation_{guild.id}`") - logger.debug("MySQL Table exists for server %s (%s)", guild.name, guild.id) + logger.debug("SQLite Table exists for server %s (%s)", guild.name, guild.id) - except mysql.connector.errors.ProgrammingError: + except sqlite3.ProgrammingError: query = f""" CREATE TABLE `moderation_{guild.id}` ( moderation_id INT UNIQUE PRIMARY KEY NOT NULL, @@ -71,10 +59,12 @@ async def create_guild_table(guild: Guild): index_query_1 = "CREATE INDEX idx_target_id ON moderation_%s(target_id(25));" cursor.execute(index_query_1, (guild.id,)) + index_query_2 = ( "CREATE INDEX idx_moderator_id ON moderation_%s(moderator_id(25));" ) cursor.execute(index_query_2, (guild.id,)) + index_query_3 = ( "CREATE INDEX idx_moderation_id ON moderation_%s(moderation_id);" ) @@ -108,7 +98,7 @@ async def create_guild_table(guild: Guild): database.commit() logger.debug( - "MySQL Table (moderation_%s) created for %s (%s)", + "SQLite Table (moderation_%s) created for %s (%s)", guild.id, guild.name, guild.id, @@ -126,7 +116,7 @@ async def mysql_log( role_id: int, duration, reason: str, - database: mysql.connector.MySQLConnection = None, + database: sqlite3.Connection = None, timestamp: int = None, resolved: bool = False, resolved_by: str = None, @@ -134,7 +124,7 @@ async def mysql_log( expired: bool = None, changes: list = [], metadata: dict = {}, -): # pylint: disable=dangerous-default-value +) -> int: # pylint: disable=dangerous-default-value if not timestamp: timestamp = int(time.time()) @@ -157,7 +147,7 @@ async def mysql_log( resolved_reason = "NULL" if not database: - database = await connect() + database = connect() close_db = True else: close_db = False @@ -192,7 +182,7 @@ async def mysql_log( database.close() logger.debug( - "MySQL row inserted into moderation_%s!\n%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s", + "Row inserted into moderation_%s!\n%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s", guild_id, moderation_id, timestamp, @@ -215,9 +205,9 @@ async def mysql_log( return moderation_id -async def fetch_case(moderation_id: int, guild_id: str): +async def fetch_case(moderation_id: int, guild_id: str) -> dict: """This method fetches a case from the database and returns the case's dictionary.""" - database = await connect() + database = connect() cursor = database.cursor() query = "SELECT * FROM moderation_%s WHERE moderation_id = %s;" diff --git a/moderation/utilities/embed_factory.py b/aurora/utilities/embed_factory.py similarity index 100% rename from moderation/utilities/embed_factory.py rename to aurora/utilities/embed_factory.py diff --git a/moderation/utilities/logger.py b/aurora/utilities/logger.py similarity index 100% rename from moderation/utilities/logger.py rename to aurora/utilities/logger.py diff --git a/moderation/utilities/utils.py b/aurora/utilities/utils.py similarity index 99% rename from moderation/utilities/utils.py rename to aurora/utilities/utils.py index 49f4106..2c5c970 100644 --- a/moderation/utilities/utils.py +++ b/aurora/utilities/utils.py @@ -116,7 +116,7 @@ async def get_next_case_number(guild_id: str, cursor=None): from .database import connect if not cursor: - database = await connect() + database = connect() cursor = database.cursor() cursor.execute( f"SELECT moderation_id FROM `moderation_{guild_id}` ORDER BY moderation_id DESC LIMIT 1" diff --git a/moderation/__init__.py b/moderation/__init__.py deleted file mode 100644 index f639c18..0000000 --- a/moderation/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -from .moderation import Moderation - - -async def setup(bot): - await bot.add_cog(Moderation(bot)) diff --git a/moderation/info.json b/moderation/info.json deleted file mode 100644 index 4c79a21..0000000 --- a/moderation/info.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "author" : ["SeaswimmerTheFsh"], - "install_msg" : "Thank you for installing Moderation!\nYou can find the source code of this cog [here](https://coastalcommits.com/SeaswimmerTheFsh/SeaCogs).\nThis cog currently requires a MySQL database to function, instructions on how to set this up can be found [here]()", - "name" : "Moderation", - "short" : "Implements a variety of moderation commands", - "description" : "Implements a variety of moderation commands, including a warning system, a mute system, and a ban system.", - "end_user_data_statement" : "This cog stores the following information:\n- User IDs of accounts who moderate users or are moderated\n- Guild IDs of guilds with the cog enabled\n- Timestamps of moderations\n- Other information relating to moderations", - "requirements": ["mysql-connector-python", "humanize", "pytimeparse2"], - "hidden": false, - "disabled": false - } -- 2.45.2 From a402f230014f85d31f5e7539cf256e85f9da1c20 Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 04:39:57 -0500 Subject: [PATCH 03/16] fix(aurora): fixing sqlite queries and pylint errors --- aurora/aurora.py | 65 +++++++++++++++-------------------- aurora/utilities/database.py | 66 +++++++++++++++++------------------- aurora/utilities/utils.py | 11 ------ 3 files changed, 59 insertions(+), 83 deletions(-) diff --git a/aurora/aurora.py b/aurora/aurora.py index 3b4ddd5..cdf6406 100644 --- a/aurora/aurora.py +++ b/aurora/aurora.py @@ -25,7 +25,7 @@ from .utilities.config import config, register_config from .utilities.database import connect, create_guild_table, fetch_case, mysql_log from .utilities.embed_factory import embed_factory from .utilities.logger import logger -from .utilities.utils import check_conf, check_moddable, check_permissions, fetch_channel_dict, fetch_user_dict, generate_dict, log, send_evidenceformat +from .utilities.utils import check_moddable, check_permissions, fetch_channel_dict, fetch_user_dict, generate_dict, log, send_evidenceformat class Aurora(commands.Cog): @@ -572,12 +572,13 @@ class Aurora(commands.Cog): database = connect() if export: - cursor = database.cursor(dictionary=True) + database.row_factory = sqlite3.Row + cursor = database.cursor() - query = """SELECT * - FROM moderation_%s + query = f"""SELECT * + FROM moderation_{interaction.guild.id} ORDER BY moderation_id DESC;""" - cursor.execute(query, (interaction.guild.id,)) + cursor.execute(query) results = cursor.fetchall() @@ -599,22 +600,22 @@ class Aurora(commands.Cog): cursor = database.cursor() if target: - query = """SELECT * - FROM moderation_%s - WHERE target_id = %s + query = f"""SELECT * + FROM moderation_{interaction.guild.id} + WHERE target_id = ? ORDER BY moderation_id DESC;""" - cursor.execute(query, (interaction.guild.id, target.id)) + cursor.execute(query, (target.id,)) elif moderator: - query = """SELECT * - FROM moderation_%s - WHERE moderator_id = %s + query = f"""SELECT * + FROM moderation_{interaction.guild.id} + WHERE moderator_id = ? ORDER BY moderation_id DESC;""" - cursor.execute(query, (interaction.guild.id, moderator.id)) + cursor.execute(query, (moderator.id,)) else: - query = """SELECT * - FROM moderation_%s + query = f"""SELECT * + FROM moderation_{interaction.guild.id} ORDER BY moderation_id DESC;""" - cursor.execute(query, (interaction.guild.id,)) + cursor.execute(query) results = cursor.fetchall() result_dict_list = [] @@ -694,15 +695,15 @@ class Aurora(commands.Cog): database = connect() cursor = database.cursor() - query_1 = "SELECT * FROM moderation_%s WHERE moderation_id = %s;" - cursor.execute(query_1, (interaction.guild.id, case)) + 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: await interaction.response.send_message(content=f"There is no moderation with a case number of {case}.", ephemeral=True) return - query_2 = "SELECT * FROM moderation_%s WHERE moderation_id = %s AND resolved = 0;" - cursor.execute(query_2, (interaction.guild.id, case)) + 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=f"This moderation has already been resolved!\nUse `/case {case}` for more information.", ephemeral=True) @@ -754,9 +755,9 @@ class Aurora(commands.Cog): except discord.NotFound: pass - resolve_query = f"UPDATE `moderation_{interaction.guild.id}` SET resolved = 1, changes = %s, resolved_by = %s, resolve_reason = %s WHERE moderation_id = %s" + 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 = %s, resolved_by = %s, resolve_reason = %s WHERE moderation_id = %s" + 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() @@ -850,10 +851,6 @@ class Aurora(commands.Cog): parsed_time = None case_dict = await fetch_case(case, interaction.guild.id) if case_dict: - conf = await check_conf(['mysql_database']) - if conf: - raise(LookupError) - if duration: try: parsed_time = parse(sval=duration, as_timedelta=True, raise_exception=True) @@ -915,13 +912,12 @@ class Aurora(commands.Cog): database = connect() cursor = database.cursor() - db = await config.mysql_database() if parsed_time: - update_query = f"UPDATE `{db}`.`moderation_{interaction.guild.id}` SET changes = %s, reason = %s, duration = %s, end_timestamp = %s WHERE moderation_id = %s" + update_query = f"UPDATE `moderation_{interaction.guild.id}` SET changes = %s, reason = %s, duration = %s, end_timestamp = %s WHERE moderation_id = %s" cursor.execute(update_query, (json.dumps(changes), reason, parsed_time, end_timestamp, case)) else: - update_query = f"UPDATE `{db}`.`moderation_{interaction.guild.id}` SET changes = %s, reason = %s WHERE moderation_id = %s" + update_query = f"UPDATE `moderation_{interaction.guild.id}` SET changes = %s, reason = %s WHERE moderation_id = %s" cursor.execute(update_query, (json.dumps(changes), reason, case)) database.commit() @@ -938,19 +934,14 @@ class Aurora(commands.Cog): @tasks.loop(minutes=1) async def handle_expiry(self): - conf = await check_conf(['mysql_database']) - if conf: - raise(LookupError) - database = connect() cursor = database.cursor() - db = await config.mysql_database() guilds: list[discord.Guild] = self.bot.guilds for guild in guilds: if not await self.bot.cog_disabled_in_guild(self, guild): - tempban_query = f"SELECT target_id, moderation_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= %s AND moderation_type = 'TEMPBAN' AND expired = 0" + 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(),)) @@ -975,10 +966,10 @@ class Aurora(commands.Cog): except [discord.errors.NotFound, discord.errors.Forbidden, discord.errors.HTTPException] as e: print(f"Failed to unban {user.name}#{user.discriminator} ({user.id}) from {guild.name} ({guild.id})\n{e}") - expiry_query = f"UPDATE `{db}`.`moderation_{guild.id}` SET expired = 1 WHERE (end_timestamp != 0 AND end_timestamp <= %s AND expired = 0 AND moderation_type != 'BLACKLIST') OR (expired = 0 AND resolved = 1 AND moderation_type != 'BLACKLIST')" + expiry_query = f"UPDATE `moderation_{guild.id}` SET expired = 1 WHERE (end_timestamp != 0 AND end_timestamp <= ? AND expired = 0 AND moderation_type != 'BLACKLIST') OR (expired = 0 AND resolved = 1 AND moderation_type != 'BLACKLIST')" cursor.execute(expiry_query, (time.time(),)) - blacklist_query = f"SELECT target_id, moderation_id, role_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= %s AND moderation_type = 'BLACKLIST' AND expired = 0" + blacklist_query = f"SELECT target_id, moderation_id, role_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'BLACKLIST' AND expired = 0" try: cursor.execute(blacklist_query, (time.time(),)) result = cursor.fetchall() diff --git a/aurora/utilities/database.py b/aurora/utilities/database.py index 5ec1883..d5e963a 100644 --- a/aurora/utilities/database.py +++ b/aurora/utilities/database.py @@ -10,7 +10,7 @@ from discord import Guild from redbot.core import data_manager from .logger import logger -from .utils import check_conf, generate_dict, get_next_case_number +from .utils import generate_dict, get_next_case_number def connect() -> sqlite3.Connection: @@ -37,43 +37,39 @@ async def create_guild_table(guild: Guild): except sqlite3.ProgrammingError: query = f""" CREATE TABLE `moderation_{guild.id}` ( - moderation_id INT UNIQUE PRIMARY KEY NOT NULL, - timestamp INT NOT NULL, - moderation_type LONGTEXT NOT NULL, - target_type LONGTEXT NOT NULL, - target_id LONGTEXT NOT NULL, - moderator_id LONGTEXT NOT NULL, - role_id LONGTEXT, - duration LONGTEXT, - end_timestamp INT, - reason LONGTEXT, - resolved BOOL NOT NULL, - resolved_by LONGTEXT, - resolve_reason LONGTEXT, - expired BOOL NOT NULL, - changes JSON NOT NULL, - metadata JSON NOT NULL + moderation_id INTEGER PRIMARY KEY, + timestamp INTEGER NOT NULL, + moderation_type TEXT NOT NULL, + target_type TEXT NOT NULL, + target_id TEXT NOT NULL, + moderator_id TEXT NOT NULL, + role_id TEXT, + duration TEXT, + end_timestamp INTEGER, + reason TEXT, + resolved INTEGER NOT NULL, + resolved_by TEXT, + resolve_reason TEXT, + expired INTEGER NOT NULL, + changes TEXT NOT NULL, + metadata TEXT NOT NULL ) """ cursor.execute(query) - index_query_1 = "CREATE INDEX idx_target_id ON moderation_%s(target_id(25));" - cursor.execute(index_query_1, (guild.id,)) + index_query_1 = "CREATE INDEX idx_target_id ON moderation_{}(target_id);" + cursor.execute(index_query_1.format(guild.id)) - index_query_2 = ( - "CREATE INDEX idx_moderator_id ON moderation_%s(moderator_id(25));" - ) - cursor.execute(index_query_2, (guild.id,)) + index_query_2 = "CREATE INDEX idx_moderator_id ON moderation_{}(moderator_id);" + cursor.execute(index_query_2.format(guild.id)) - index_query_3 = ( - "CREATE INDEX idx_moderation_id ON moderation_%s(moderation_id);" - ) - cursor.execute(index_query_3, (guild.id,)) + index_query_3 = "CREATE INDEX idx_moderation_id ON moderation_{}(moderation_id);" + cursor.execute(index_query_3.format(guild.id)) 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 (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """ insert_values = ( 0, @@ -98,7 +94,7 @@ async def create_guild_table(guild: Guild): database.commit() logger.debug( - "SQLite Table (moderation_%s) created for %s (%s)", + "SQLite Table (moderation_?) created for ? (?)", guild.id, guild.name, guild.id, @@ -122,9 +118,9 @@ async def mysql_log( resolved_by: str = None, resolved_reason: str = None, expired: bool = None, - changes: list = [], - metadata: dict = {}, -) -> int: # pylint: disable=dangerous-default-value + changes: list = [], # pylint: disable=dangerous-default-value + metadata: dict = {}, # pylint: disable=dangerous-default-value +) -> int: if not timestamp: timestamp = int(time.time()) @@ -155,7 +151,7 @@ async def mysql_log( moderation_id = await get_next_case_number(guild_id=guild_id, cursor=cursor) - 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 (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" + 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" val = ( moderation_id, timestamp, @@ -210,8 +206,8 @@ async def fetch_case(moderation_id: int, guild_id: str) -> dict: database = connect() cursor = database.cursor() - query = "SELECT * FROM moderation_%s WHERE moderation_id = %s;" - cursor.execute(query, (guild_id, moderation_id)) + query = f"SELECT * FROM moderation_{guild_id} WHERE moderation_id = ?;" + cursor.execute(query, (moderation_id,)) result = cursor.fetchone() cursor.close() diff --git a/aurora/utilities/utils.py b/aurora/utilities/utils.py index 2c5c970..3a52f91 100644 --- a/aurora/utilities/utils.py +++ b/aurora/utilities/utils.py @@ -10,17 +10,6 @@ from redbot.core import commands from .config import config -async def check_conf(config_list: list): - """Checks if any required config options are not set.""" - not_found_list = [] - - for item in config_list: - if await config.item() == " ": - not_found_list.append(item) - - return not_found_list - - def check_permissions( user: User, permissions: list, -- 2.45.2 From 4226d0b6feccea6301a2338547c1aae76dc1f6c1 Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 04:45:50 -0500 Subject: [PATCH 04/16] fix(aurora): pylint fix + sqlite connection fix --- aurora/utilities/database.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/aurora/utilities/database.py b/aurora/utilities/database.py index d5e963a..11129f8 100644 --- a/aurora/utilities/database.py +++ b/aurora/utilities/database.py @@ -3,7 +3,6 @@ import json import time import sqlite3 -from os import sep from datetime import datetime from discord import Guild @@ -16,7 +15,7 @@ from .utils import generate_dict, get_next_case_number 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='Moderation') + sep + 'moderation.db') + connection = sqlite3.connect(database=data_manager.cog_data_path(raw_name='Aurora') / 'aurora.db') return connection except sqlite3.ProgrammingError as e: @@ -103,6 +102,7 @@ async def create_guild_table(guild: Guild): database.close() +# pylint: disable=dangerous-default-value async def mysql_log( guild_id: str, author_id: str, @@ -118,8 +118,8 @@ async def mysql_log( resolved_by: str = None, resolved_reason: str = None, expired: bool = None, - changes: list = [], # pylint: disable=dangerous-default-value - metadata: dict = {}, # pylint: disable=dangerous-default-value + changes: list = [], + metadata: dict = {}, ) -> int: if not timestamp: timestamp = int(time.time()) -- 2.45.2 From 3087afa1d2b6d3e4a36a18b57fb989d69129be68 Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 04:47:16 -0500 Subject: [PATCH 05/16] fix(aurora): sqlite3 uses OperationalErrors, not ProgrammingErrors --- aurora/aurora.py | 4 ++-- aurora/utilities/database.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/aurora/aurora.py b/aurora/aurora.py index cdf6406..da45a0b 100644 --- a/aurora/aurora.py +++ b/aurora/aurora.py @@ -946,7 +946,7 @@ class Aurora(commands.Cog): try: cursor.execute(tempban_query, (time.time(),)) result = cursor.fetchall() - except sqlite3.ProgrammingError: + except sqlite3.OperationalError: continue target_ids = [row[0] for row in result] @@ -973,7 +973,7 @@ class Aurora(commands.Cog): try: cursor.execute(blacklist_query, (time.time(),)) result = cursor.fetchall() - except sqlite3.ProgrammingError: + except sqlite3.OperationalError: continue target_ids = [row[0] for row in result] moderation_ids = [row[1] for row in result] diff --git a/aurora/utilities/database.py b/aurora/utilities/database.py index 11129f8..1875023 100644 --- a/aurora/utilities/database.py +++ b/aurora/utilities/database.py @@ -18,7 +18,7 @@ def connect() -> sqlite3.Connection: connection = sqlite3.connect(database=data_manager.cog_data_path(raw_name='Aurora') / 'aurora.db') return connection - except sqlite3.ProgrammingError as e: + 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}" @@ -33,7 +33,7 @@ async def create_guild_table(guild: Guild): cursor.execute(f"SELECT * FROM `moderation_{guild.id}`") logger.debug("SQLite Table exists for server %s (%s)", guild.name, guild.id) - except sqlite3.ProgrammingError: + except sqlite3.OperationalError: query = f""" CREATE TABLE `moderation_{guild.id}` ( moderation_id INTEGER PRIMARY KEY, -- 2.45.2 From 9cc0cae53b8b659ff9d9026354fb675550420325 Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 04:51:16 -0500 Subject: [PATCH 06/16] fix(aurora): fixed aurora importer --- aurora/importers/aurora.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aurora/importers/aurora.py b/aurora/importers/aurora.py index f608dc5..2f06d98 100644 --- a/aurora/importers/aurora.py +++ b/aurora/importers/aurora.py @@ -66,7 +66,7 @@ class ImportAuroraView(ui.View): if "metadata" not in case: metadata = {} else: - metadata: Dict[str, any] = case["metadata"] + metadata: Dict[str, any] = json.loads(case["metadata"]) if not metadata['imported_from']: metadata.update({ 'imported_from': 'Aurora' -- 2.45.2 From 12f14984a27c40c82f6ee2886f547253f2f13c62 Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 04:52:04 -0500 Subject: [PATCH 07/16] fix(aurora): fixed cancel button in importers --- aurora/importers/aurora.py | 2 +- aurora/importers/galacticbot.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/aurora/importers/aurora.py b/aurora/importers/aurora.py index 2f06d98..8270676 100644 --- a/aurora/importers/aurora.py +++ b/aurora/importers/aurora.py @@ -107,6 +107,6 @@ class ImportAuroraView(ui.View): async def import_button_n( self, interaction: Interaction, button: ui.Button ): # pylint: disable=unused-argument - await self.message.edit("Import cancelled.", view=None) + 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 a4d0e9f..1c7ae76 100644 --- a/aurora/importers/galacticbot.py +++ b/aurora/importers/galacticbot.py @@ -140,6 +140,6 @@ class ImportGalacticBotView(ui.View): @ui.button(label="No", style=ButtonStyle.danger) async def import_button_n(self, interaction: Interaction, button: ui.Button): # pylint: disable=unused-argument - await self.message.edit("Import cancelled.", view=None) + await self.message.edit(content="Import cancelled.", view=None) await self.message.delete(10) await self.ctx.message.delete(10) -- 2.45.2 From 036333e909eb66c99508cfc5fba26d896e80c593 Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 04:54:30 -0500 Subject: [PATCH 08/16] fix(aurora): fixed importers trying to import durations and breaking --- aurora/importers/aurora.py | 2 +- aurora/importers/galacticbot.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/aurora/importers/aurora.py b/aurora/importers/aurora.py index 8270676..21041e9 100644 --- a/aurora/importers/aurora.py +++ b/aurora/importers/aurora.py @@ -85,7 +85,7 @@ class ImportAuroraView(ui.View): case["target_type"], case["target_id"], case["role_id"], - duration, + str(duration), case["reason"], timestamp=case["timestamp"], resolved=case["resolved"], diff --git a/aurora/importers/galacticbot.py b/aurora/importers/galacticbot.py index 1c7ae76..646a05e 100644 --- a/aurora/importers/galacticbot.py +++ b/aurora/importers/galacticbot.py @@ -123,7 +123,7 @@ class ImportGalacticBotView(ui.View): case['targetType'], case['target'], 0, - duration, + str(duration), reason, timestamp=timestamp, resolved=resolved, -- 2.45.2 From 673e8b41d1845b89e96cdec9a2818342005cea6b Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 04:55:21 -0500 Subject: [PATCH 09/16] misc(aurora): changed logger name from moderation to aurora --- aurora/utilities/logger.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aurora/utilities/logger.py b/aurora/utilities/logger.py index 0357c60..84a7836 100644 --- a/aurora/utilities/logger.py +++ b/aurora/utilities/logger.py @@ -1,3 +1,3 @@ import logging -logger = logging.getLogger("red.sea.moderation") +logger = logging.getLogger("red.sea.aurora") -- 2.45.2 From e62bd62e294bd17caae6496cf10abe009002afa5 Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 04:56:58 -0500 Subject: [PATCH 10/16] fix(aurora): actually fixed duration error --- aurora/importers/aurora.py | 2 +- aurora/importers/galacticbot.py | 2 +- aurora/utilities/database.py | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/aurora/importers/aurora.py b/aurora/importers/aurora.py index 21041e9..8270676 100644 --- a/aurora/importers/aurora.py +++ b/aurora/importers/aurora.py @@ -85,7 +85,7 @@ class ImportAuroraView(ui.View): case["target_type"], case["target_id"], case["role_id"], - str(duration), + duration, case["reason"], timestamp=case["timestamp"], resolved=case["resolved"], diff --git a/aurora/importers/galacticbot.py b/aurora/importers/galacticbot.py index 646a05e..1c7ae76 100644 --- a/aurora/importers/galacticbot.py +++ b/aurora/importers/galacticbot.py @@ -123,7 +123,7 @@ class ImportGalacticBotView(ui.View): case['targetType'], case['target'], 0, - str(duration), + duration, reason, timestamp=timestamp, resolved=resolved, diff --git a/aurora/utilities/database.py b/aurora/utilities/database.py index 1875023..762214b 100644 --- a/aurora/utilities/database.py +++ b/aurora/utilities/database.py @@ -127,6 +127,7 @@ async def mysql_log( if duration != "NULL": end_timedelta = datetime.fromtimestamp(timestamp) + duration end_timestamp = int(end_timedelta.timestamp()) + duration = str(duration) else: end_timestamp = 0 -- 2.45.2 From 5a53e3327be56e092e3c4774483fa7e299eb7b43 Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 05:01:08 -0500 Subject: [PATCH 11/16] fix(aurora): fixed durations, again --- aurora/utilities/database.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/aurora/utilities/database.py b/aurora/utilities/database.py index 762214b..88189dc 100644 --- a/aurora/utilities/database.py +++ b/aurora/utilities/database.py @@ -3,7 +3,7 @@ import json import time import sqlite3 -from datetime import datetime +from datetime import datetime, timedelta from discord import Guild from redbot.core import data_manager @@ -110,7 +110,7 @@ async def mysql_log( target_type: str, target_id: int, role_id: int, - duration, + duration: timedelta, reason: str, database: sqlite3.Connection = None, timestamp: int = None, @@ -127,7 +127,12 @@ async def mysql_log( if duration != "NULL": end_timedelta = datetime.fromtimestamp(timestamp) + duration end_timestamp = int(end_timedelta.timestamp()) - duration = str(duration) + + total_seconds = int(duration.total_seconds()) + hours = total_seconds // 3600 + minutes = (total_seconds % 3600) // 60 + seconds = total_seconds % 60 + duration = f"{hours}:{minutes}:{seconds}" else: end_timestamp = 0 -- 2.45.2 From 9cbe87bd66f0d99deaf807e740fae3b723465f7e Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 05:02:46 -0500 Subject: [PATCH 12/16] fix(moderation): logger fix --- aurora/utilities/database.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aurora/utilities/database.py b/aurora/utilities/database.py index 88189dc..32bd116 100644 --- a/aurora/utilities/database.py +++ b/aurora/utilities/database.py @@ -93,7 +93,7 @@ async def create_guild_table(guild: Guild): database.commit() logger.debug( - "SQLite Table (moderation_?) created for ? (?)", + "SQLite Table (moderation_%s) created for %s (%s)", guild.id, guild.name, guild.id, -- 2.45.2 From b1edf79409b011f95fbdc599f211090555964a93 Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 05:09:12 -0500 Subject: [PATCH 13/16] misc(aurora): some whitelabel changes --- aurora/aurora.py | 34 +++++++++++++++++----------------- aurora/utilities/database.py | 20 ++++++++++---------- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/aurora/aurora.py b/aurora/aurora.py index da45a0b..5690f2e 100644 --- a/aurora/aurora.py +++ b/aurora/aurora.py @@ -576,19 +576,19 @@ class Aurora(commands.Cog): cursor = database.cursor() query = f"""SELECT * - FROM moderation_{interaction.guild.id} + FROM {interaction.guild.id} ORDER BY moderation_id DESC;""" cursor.execute(query) results = cursor.fetchall() try: - filename = str(data_manager.cog_data_path(cog_instance=self)) + str(os.sep) + f"moderation_{interaction.guild.id}.json" + filename = str(data_manager.cog_data_path(cog_instance=self)) + str(os.sep) + f"{interaction.guild.id}.json" with open(filename, "w", encoding="utf-8") as f: json.dump(results, f, indent=2) - await interaction.followup.send(file=discord.File(filename, f"moderation_{interaction.guild.id}.json"), ephemeral=ephemeral) + await interaction.followup.send(file=discord.File(filename, f"{interaction.guild.id}.json"), ephemeral=ephemeral) os.remove(filename) except json.JSONDecodeError as e: @@ -601,19 +601,19 @@ class Aurora(commands.Cog): if target: query = f"""SELECT * - FROM moderation_{interaction.guild.id} + FROM {interaction.guild.id} WHERE target_id = ? ORDER BY moderation_id DESC;""" cursor.execute(query, (target.id,)) elif moderator: query = f"""SELECT * - FROM moderation_{interaction.guild.id} + FROM {interaction.guild.id} WHERE moderator_id = ? ORDER BY moderation_id DESC;""" cursor.execute(query, (moderator.id,)) else: query = f"""SELECT * - FROM moderation_{interaction.guild.id} + FROM {interaction.guild.id} ORDER BY moderation_id DESC;""" cursor.execute(query) @@ -695,14 +695,14 @@ class Aurora(commands.Cog): database = connect() cursor = database.cursor() - query_1 = f"SELECT * FROM moderation_{interaction.guild.id} WHERE moderation_id = ?;" + query_1 = f"SELECT * FROM {interaction.guild.id} WHERE moderation_id = ?;" cursor.execute(query_1, (case,)) result_1 = cursor.fetchone() if result_1 is None or case == 0: await interaction.response.send_message(content=f"There is no moderation with a case number of {case}.", ephemeral=True) return - query_2 = f"SELECT * FROM moderation_{interaction.guild.id} WHERE moderation_id = ? AND resolved = 0;" + query_2 = f"SELECT * FROM {interaction.guild.id} WHERE moderation_id = ? AND resolved = 0;" cursor.execute(query_2, (case,)) result_2 = cursor.fetchone() if result_2 is None: @@ -755,9 +755,9 @@ class Aurora(commands.Cog): except discord.NotFound: pass - resolve_query = f"UPDATE `moderation_{interaction.guild.id}` SET resolved = 1, changes = ?, resolved_by = ?, resolve_reason = ? WHERE moderation_id = ?" + resolve_query = f"UPDATE `{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 = ?" + resolve_query = f"UPDATE `{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() @@ -802,7 +802,7 @@ class Aurora(commands.Cog): 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" + filename = str(data_manager.cog_data_path(cog_instance=self)) + str(os.sep) + f"{interaction.guild.id}_case_{case}.json" with open(filename, "w", encoding="utf-8") as f: json.dump(case_dict, f, indent=2) @@ -812,7 +812,7 @@ class Aurora(commands.Cog): 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) + await interaction.response.send_message(content=content, file=discord.File(filename, f"{interaction.guild.id}_case_{case}.json"), ephemeral=ephemeral) os.remove(filename) return @@ -914,10 +914,10 @@ class Aurora(commands.Cog): cursor = database.cursor() if parsed_time: - update_query = f"UPDATE `moderation_{interaction.guild.id}` SET changes = %s, reason = %s, duration = %s, end_timestamp = %s WHERE moderation_id = %s" + update_query = f"UPDATE `{interaction.guild.id}` SET changes = %s, reason = %s, duration = %s, end_timestamp = %s WHERE moderation_id = %s" cursor.execute(update_query, (json.dumps(changes), reason, parsed_time, end_timestamp, case)) else: - update_query = f"UPDATE `moderation_{interaction.guild.id}` SET changes = %s, reason = %s WHERE moderation_id = %s" + update_query = f"UPDATE `{interaction.guild.id}` SET changes = %s, reason = %s WHERE moderation_id = %s" cursor.execute(update_query, (json.dumps(changes), reason, case)) database.commit() @@ -941,7 +941,7 @@ class Aurora(commands.Cog): for guild in guilds: if not await self.bot.cog_disabled_in_guild(self, guild): - 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" + tempban_query = f"SELECT target_id, moderation_id FROM {guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'TEMPBAN' AND expired = 0" try: cursor.execute(tempban_query, (time.time(),)) @@ -966,10 +966,10 @@ class Aurora(commands.Cog): except [discord.errors.NotFound, discord.errors.Forbidden, discord.errors.HTTPException] as e: print(f"Failed to unban {user.name}#{user.discriminator} ({user.id}) from {guild.name} ({guild.id})\n{e}") - expiry_query = f"UPDATE `moderation_{guild.id}` SET expired = 1 WHERE (end_timestamp != 0 AND end_timestamp <= ? AND expired = 0 AND moderation_type != 'BLACKLIST') OR (expired = 0 AND resolved = 1 AND moderation_type != 'BLACKLIST')" + expiry_query = f"UPDATE `{guild.id}` SET expired = 1 WHERE (end_timestamp != 0 AND end_timestamp <= ? AND expired = 0 AND moderation_type != 'BLACKLIST') OR (expired = 0 AND resolved = 1 AND moderation_type != 'BLACKLIST')" cursor.execute(expiry_query, (time.time(),)) - blacklist_query = f"SELECT target_id, moderation_id, role_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'BLACKLIST' AND expired = 0" + blacklist_query = f"SELECT target_id, moderation_id, role_id FROM {guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'BLACKLIST' AND expired = 0" try: cursor.execute(blacklist_query, (time.time(),)) result = cursor.fetchall() diff --git a/aurora/utilities/database.py b/aurora/utilities/database.py index 32bd116..4a6ef14 100644 --- a/aurora/utilities/database.py +++ b/aurora/utilities/database.py @@ -30,12 +30,12 @@ async def create_guild_table(guild: Guild): cursor = database.cursor() try: - cursor.execute(f"SELECT * FROM `moderation_{guild.id}`") + cursor.execute(f"SELECT * FROM `{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}` ( + CREATE TABLE `{guild.id}` ( moderation_id INTEGER PRIMARY KEY, timestamp INTEGER NOT NULL, moderation_type TEXT NOT NULL, @@ -56,17 +56,17 @@ async def create_guild_table(guild: Guild): """ cursor.execute(query) - index_query_1 = "CREATE INDEX idx_target_id ON moderation_{}(target_id);" + index_query_1 = "CREATE INDEX idx_target_id ON {}(target_id);" cursor.execute(index_query_1.format(guild.id)) - index_query_2 = "CREATE INDEX idx_moderator_id ON moderation_{}(moderator_id);" + index_query_2 = "CREATE INDEX idx_moderator_id ON {}(moderator_id);" cursor.execute(index_query_2.format(guild.id)) - index_query_3 = "CREATE INDEX idx_moderation_id ON moderation_{}(moderation_id);" + index_query_3 = "CREATE INDEX idx_moderation_id ON {}(moderation_id);" cursor.execute(index_query_3.format(guild.id)) insert_query = f""" - INSERT INTO `moderation_{guild.id}` + INSERT INTO `{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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """ @@ -93,7 +93,7 @@ async def create_guild_table(guild: Guild): database.commit() logger.debug( - "SQLite Table (moderation_%s) created for %s (%s)", + "SQLite Table (%s) created for %s (%s)", guild.id, guild.name, guild.id, @@ -157,7 +157,7 @@ async def mysql_log( moderation_id = await get_next_case_number(guild_id=guild_id, cursor=cursor) - 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + sql = f"INSERT INTO `{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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" val = ( moderation_id, timestamp, @@ -184,7 +184,7 @@ async def mysql_log( database.close() logger.debug( - "Row inserted into moderation_%s!\n%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s", + "Row inserted into %s!\n%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s", guild_id, moderation_id, timestamp, @@ -212,7 +212,7 @@ async def fetch_case(moderation_id: int, guild_id: str) -> dict: database = connect() cursor = database.cursor() - query = f"SELECT * FROM moderation_{guild_id} WHERE moderation_id = ?;" + query = f"SELECT * FROM {guild_id} WHERE moderation_id = ?;" cursor.execute(query, (moderation_id,)) result = cursor.fetchone() -- 2.45.2 From beb4e3909b9a5f0359f49ef5ea33bbf0c8676a37 Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 05:11:32 -0500 Subject: [PATCH 14/16] fix(aurora): fixed index creation --- aurora/utilities/database.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/aurora/utilities/database.py b/aurora/utilities/database.py index 4a6ef14..4af7c79 100644 --- a/aurora/utilities/database.py +++ b/aurora/utilities/database.py @@ -56,14 +56,14 @@ async def create_guild_table(guild: Guild): """ cursor.execute(query) - index_query_1 = "CREATE INDEX idx_target_id ON {}(target_id);" - cursor.execute(index_query_1.format(guild.id)) + index_query_1 = f"CREATE INDEX idx_target_id ON {guild.id}(target_id);" + cursor.execute(index_query_1) - index_query_2 = "CREATE INDEX idx_moderator_id ON {}(moderator_id);" - cursor.execute(index_query_2.format(guild.id)) + index_query_2 = f"CREATE INDEX idx_moderator_id ON {guild.id}(moderator_id);" + cursor.execute(index_query_2) - index_query_3 = "CREATE INDEX idx_moderation_id ON {}(moderation_id);" - cursor.execute(index_query_3.format(guild.id)) + index_query_3 = f"CREATE INDEX idx_moderation_id ON {guild.id}(moderation_id);" + cursor.execute(index_query_3) insert_query = f""" INSERT INTO `{guild.id}` -- 2.45.2 From 84fed6f17e88bf019c5620cca3d7b7d7f97fd56a Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 05:12:58 -0500 Subject: [PATCH 15/16] Revert "fix(aurora): fixed index creation" This reverts commit beb4e3909b9a5f0359f49ef5ea33bbf0c8676a37. --- aurora/utilities/database.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/aurora/utilities/database.py b/aurora/utilities/database.py index 4af7c79..4a6ef14 100644 --- a/aurora/utilities/database.py +++ b/aurora/utilities/database.py @@ -56,14 +56,14 @@ async def create_guild_table(guild: Guild): """ cursor.execute(query) - index_query_1 = f"CREATE INDEX idx_target_id ON {guild.id}(target_id);" - cursor.execute(index_query_1) + index_query_1 = "CREATE INDEX idx_target_id ON {}(target_id);" + cursor.execute(index_query_1.format(guild.id)) - index_query_2 = f"CREATE INDEX idx_moderator_id ON {guild.id}(moderator_id);" - cursor.execute(index_query_2) + index_query_2 = "CREATE INDEX idx_moderator_id ON {}(moderator_id);" + cursor.execute(index_query_2.format(guild.id)) - index_query_3 = f"CREATE INDEX idx_moderation_id ON {guild.id}(moderation_id);" - cursor.execute(index_query_3) + index_query_3 = "CREATE INDEX idx_moderation_id ON {}(moderation_id);" + cursor.execute(index_query_3.format(guild.id)) insert_query = f""" INSERT INTO `{guild.id}` -- 2.45.2 From 910601a2695f22dde21326b12d77d114895d4660 Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Thu, 28 Dec 2023 05:13:13 -0500 Subject: [PATCH 16/16] Revert "misc(aurora): some whitelabel changes" This reverts commit b1edf79409b011f95fbdc599f211090555964a93. --- aurora/aurora.py | 34 +++++++++++++++++----------------- aurora/utilities/database.py | 20 ++++++++++---------- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/aurora/aurora.py b/aurora/aurora.py index 5690f2e..da45a0b 100644 --- a/aurora/aurora.py +++ b/aurora/aurora.py @@ -576,19 +576,19 @@ class Aurora(commands.Cog): cursor = database.cursor() query = f"""SELECT * - FROM {interaction.guild.id} + FROM moderation_{interaction.guild.id} ORDER BY moderation_id DESC;""" cursor.execute(query) results = cursor.fetchall() try: - filename = str(data_manager.cog_data_path(cog_instance=self)) + str(os.sep) + f"{interaction.guild.id}.json" + 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(results, f, indent=2) - await interaction.followup.send(file=discord.File(filename, f"{interaction.guild.id}.json"), ephemeral=ephemeral) + await interaction.followup.send(file=discord.File(filename, f"moderation_{interaction.guild.id}.json"), ephemeral=ephemeral) os.remove(filename) except json.JSONDecodeError as e: @@ -601,19 +601,19 @@ class Aurora(commands.Cog): if target: query = f"""SELECT * - FROM {interaction.guild.id} + FROM moderation_{interaction.guild.id} WHERE target_id = ? ORDER BY moderation_id DESC;""" cursor.execute(query, (target.id,)) elif moderator: query = f"""SELECT * - FROM {interaction.guild.id} + FROM moderation_{interaction.guild.id} WHERE moderator_id = ? ORDER BY moderation_id DESC;""" cursor.execute(query, (moderator.id,)) else: query = f"""SELECT * - FROM {interaction.guild.id} + FROM moderation_{interaction.guild.id} ORDER BY moderation_id DESC;""" cursor.execute(query) @@ -695,14 +695,14 @@ class Aurora(commands.Cog): database = connect() cursor = database.cursor() - query_1 = f"SELECT * FROM {interaction.guild.id} WHERE moderation_id = ?;" + 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: await interaction.response.send_message(content=f"There is no moderation with a case number of {case}.", ephemeral=True) return - query_2 = f"SELECT * FROM {interaction.guild.id} WHERE moderation_id = ? AND resolved = 0;" + 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: @@ -755,9 +755,9 @@ class Aurora(commands.Cog): except discord.NotFound: pass - resolve_query = f"UPDATE `{interaction.guild.id}` SET resolved = 1, changes = ?, resolved_by = ?, resolve_reason = ? WHERE moderation_id = ?" + resolve_query = f"UPDATE `moderation_{interaction.guild.id}` SET resolved = 1, changes = ?, resolved_by = ?, resolve_reason = ? WHERE moderation_id = ?" else: - resolve_query = f"UPDATE `{interaction.guild.id}` SET resolved = 1, changes = ?, resolved_by = ?, resolve_reason = ? WHERE moderation_id = ?" + 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() @@ -802,7 +802,7 @@ class Aurora(commands.Cog): 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"{interaction.guild.id}_case_{case}.json" + filename = str(data_manager.cog_data_path(cog_instance=self)) + str(os.sep) + f"moderation_{interaction.guild.id}_case_{case}.json" with open(filename, "w", encoding="utf-8") as f: json.dump(case_dict, f, indent=2) @@ -812,7 +812,7 @@ class Aurora(commands.Cog): else: content = f"Case #{case:,} exported." - await interaction.response.send_message(content=content, file=discord.File(filename, f"{interaction.guild.id}_case_{case}.json"), ephemeral=ephemeral) + 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 @@ -914,10 +914,10 @@ class Aurora(commands.Cog): cursor = database.cursor() if parsed_time: - update_query = f"UPDATE `{interaction.guild.id}` SET changes = %s, reason = %s, duration = %s, end_timestamp = %s WHERE moderation_id = %s" + update_query = f"UPDATE `moderation_{interaction.guild.id}` SET changes = %s, reason = %s, duration = %s, end_timestamp = %s WHERE moderation_id = %s" cursor.execute(update_query, (json.dumps(changes), reason, parsed_time, end_timestamp, case)) else: - update_query = f"UPDATE `{interaction.guild.id}` SET changes = %s, reason = %s WHERE moderation_id = %s" + update_query = f"UPDATE `moderation_{interaction.guild.id}` SET changes = %s, reason = %s WHERE moderation_id = %s" cursor.execute(update_query, (json.dumps(changes), reason, case)) database.commit() @@ -941,7 +941,7 @@ class Aurora(commands.Cog): for guild in guilds: if not await self.bot.cog_disabled_in_guild(self, guild): - tempban_query = f"SELECT target_id, moderation_id FROM {guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'TEMPBAN' AND expired = 0" + 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(),)) @@ -966,10 +966,10 @@ class Aurora(commands.Cog): except [discord.errors.NotFound, discord.errors.Forbidden, discord.errors.HTTPException] as e: print(f"Failed to unban {user.name}#{user.discriminator} ({user.id}) from {guild.name} ({guild.id})\n{e}") - expiry_query = f"UPDATE `{guild.id}` SET expired = 1 WHERE (end_timestamp != 0 AND end_timestamp <= ? AND expired = 0 AND moderation_type != 'BLACKLIST') OR (expired = 0 AND resolved = 1 AND moderation_type != 'BLACKLIST')" + expiry_query = f"UPDATE `moderation_{guild.id}` SET expired = 1 WHERE (end_timestamp != 0 AND end_timestamp <= ? AND expired = 0 AND moderation_type != 'BLACKLIST') OR (expired = 0 AND resolved = 1 AND moderation_type != 'BLACKLIST')" cursor.execute(expiry_query, (time.time(),)) - blacklist_query = f"SELECT target_id, moderation_id, role_id FROM {guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'BLACKLIST' AND expired = 0" + blacklist_query = f"SELECT target_id, moderation_id, role_id FROM moderation_{guild.id} WHERE end_timestamp != 0 AND end_timestamp <= ? AND moderation_type = 'BLACKLIST' AND expired = 0" try: cursor.execute(blacklist_query, (time.time(),)) result = cursor.fetchall() diff --git a/aurora/utilities/database.py b/aurora/utilities/database.py index 4a6ef14..32bd116 100644 --- a/aurora/utilities/database.py +++ b/aurora/utilities/database.py @@ -30,12 +30,12 @@ async def create_guild_table(guild: Guild): cursor = database.cursor() try: - cursor.execute(f"SELECT * FROM `{guild.id}`") + 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 `{guild.id}` ( + CREATE TABLE `moderation_{guild.id}` ( moderation_id INTEGER PRIMARY KEY, timestamp INTEGER NOT NULL, moderation_type TEXT NOT NULL, @@ -56,17 +56,17 @@ async def create_guild_table(guild: Guild): """ cursor.execute(query) - index_query_1 = "CREATE INDEX idx_target_id ON {}(target_id);" + index_query_1 = "CREATE INDEX idx_target_id ON moderation_{}(target_id);" cursor.execute(index_query_1.format(guild.id)) - index_query_2 = "CREATE INDEX idx_moderator_id ON {}(moderator_id);" + index_query_2 = "CREATE INDEX idx_moderator_id ON moderation_{}(moderator_id);" cursor.execute(index_query_2.format(guild.id)) - index_query_3 = "CREATE INDEX idx_moderation_id ON {}(moderation_id);" + index_query_3 = "CREATE INDEX idx_moderation_id ON moderation_{}(moderation_id);" cursor.execute(index_query_3.format(guild.id)) insert_query = f""" - INSERT INTO `{guild.id}` + 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """ @@ -93,7 +93,7 @@ async def create_guild_table(guild: Guild): database.commit() logger.debug( - "SQLite Table (%s) created for %s (%s)", + "SQLite Table (moderation_%s) created for %s (%s)", guild.id, guild.name, guild.id, @@ -157,7 +157,7 @@ async def mysql_log( moderation_id = await get_next_case_number(guild_id=guild_id, cursor=cursor) - sql = f"INSERT INTO `{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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" val = ( moderation_id, timestamp, @@ -184,7 +184,7 @@ async def mysql_log( database.close() logger.debug( - "Row inserted into %s!\n%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s", + "Row inserted into moderation_%s!\n%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s", guild_id, moderation_id, timestamp, @@ -212,7 +212,7 @@ async def fetch_case(moderation_id: int, guild_id: str) -> dict: database = connect() cursor = database.cursor() - query = f"SELECT * FROM {guild_id} WHERE moderation_id = ?;" + query = f"SELECT * FROM moderation_{guild_id} WHERE moderation_id = ?;" cursor.execute(query, (moderation_id,)) result = cursor.fetchone() -- 2.45.2