From 9adfe1461f23ffc0c0025654f37fb433b3601e39 Mon Sep 17 00:00:00 2001 From: SeaswimmerTheFsh Date: Fri, 6 Oct 2023 09:34:30 -0400 Subject: [PATCH] feat(moderation): offloading all embed generation to embed_factory method --- moderation/moderation.py | 119 +++++++++++++++++++++++---------------- 1 file changed, 69 insertions(+), 50 deletions(-) diff --git a/moderation/moderation.py b/moderation/moderation.py index 34d4f3a..acc16a5 100644 --- a/moderation/moderation.py +++ b/moderation/moderation.py @@ -209,13 +209,24 @@ class Moderation(commands.Cog): cursor.execute(f"SELECT moderation_id FROM `moderation_{guild_id}` ORDER BY moderation_id DESC LIMIT 1") return cursor.fetchone()[0] + 1 - async def embed_factory(self, embed_type: str, guild: discord.Guild, reason: str, moderation_type: str, response: discord.InteractionMessage = None, duration: timedelta = None): + async def embed_factory(self, embed_type: str, /, interaction: discord.Interaction = None, case_dict: dict = None, guild: discord.Guild = None, reason: str = None, moderation_type: str = None, response: discord.InteractionMessage = None, duration: timedelta = None): """This method creates an embed from set parameters, meant for either moderation logging or contacting the moderated user. Valid arguments for 'embed_type': - 'message' - 'log' - WIP - - 'case' - WIP""" + - 'case' + + Required arguments for 'message': + - guild + - reason + - moderation_type + - response + - duration (optional) + + Required arguments for 'case': + - interaction + - case_dict""" if embed_type == 'message': if moderation_type in ["kicked", "banned", "tempbanned", "unbanned"]: guild_name = guild.name @@ -234,6 +245,47 @@ class Moderation(commands.Cog): embed.set_author(name=guild.name, icon_url=guild.icon.url) embed.set_footer(text=f"Case #{await self.get_next_case_number(guild.id)}", icon_url="https://cdn.discordapp.com/attachments/1070822161389994054/1159469476773904414/arrow-right-circle-icon-512x512-2p1e2aaw.png?ex=65312319&is=651eae19&hm=3cebdd28e805c13a79ec48ef87c32ca532ffa6b9ede2e48d0cf8e5e81f3a6818&") return embed + if embed_type == 'case': + try: + target = await interaction.client.fetch_user(case_dict["target_id"]) + target_user = { + 'id': target.id, + 'name': target.name, + 'discriminator': target.discriminator + } + except discord.errors.NotFound: + target = discord.User(id=case_dict["target_id"], name="Deleted User", discriminator="0") # pylint: disable=unexpected-keyword-arg, missing-kwoa + target_user = { + 'id': case_dict['target_id'], + 'name': 'Deleted User', + 'discriminator': '0' + } + try: + moderator = await interaction.client.fetch_user(case_dict["moderator_id"]) + moderator_user = { + 'id': moderator.id, + 'name': moderator.name, + 'discriminator': moderator.discriminator + } + except discord.errors.NotFound: + moderator = discord.User(id=case_dict["moderator_id"], name="Deleted User", discriminator="0") # pylint: disable=unexpected-keyword-arg, missing-kwoa + moderator_user = { + 'id': case_dict['moderator_id'], + 'name': 'Deleted User', + 'discriminator': '0' + } + target_name = target_user['name'] if target_user['discriminator'] == "0" else f"{target_user['name']}#{target_user['discriminator']}" + moderator_name = moderator_user['name'] if moderator_user['discriminator'] == "0" else f"{moderator_user['name']}#{moderator_user['discriminator']}" + embed = discord.Embed(title=f"📕 Case #{case_dict['moderation_id']}", color=await self.bot.get_embed_color(None)) + embed.description = f"**Type:** {str.title(case_dict['moderation_type'])}\n**Target:** {target_name} ({target_user['id']})\n**Moderator:** {moderator_name} ({moderator_user['id']})\n**Resolved:** {bool(case_dict['resolved'])}\n**Timestamp:** | " + if case_dict['duration'] != 'NULL': + td = timedelta(**{unit: int(val) for unit, val in zip(["hours", "minutes", "seconds"], case_dict["duration"].split(":"))}) + duration_embed = f"{humanize.precisedelta(td)} | " if case_dict["expired"] == '0' else str(humanize.precisedelta(td)) + embed.description = embed.description + f"\n**Duration:** {duration_embed}\n**Expired:** {bool(case_dict['expired'])}" + embed.add_field(name='Reason', value=f"```{case_dict['reason']}```", inline=False) + if case_dict['resolved'] == 1: + embed.add_field(name='Resolve Reason', value=f"```{case_dict['resolve_reason']}```", inline=False) + return embed raise(TypeError("'type' argument is invalid!")) @app_commands.command(name="note") @@ -244,7 +296,7 @@ class Moderation(commands.Cog): silent = not await self.config.guild(interaction.guild).dm_users() if silent is False: try: - embed = await self.embed_factory('message', interaction.guild, reason, 'note', await interaction.original_response()) + embed = await self.embed_factory('message', guild=interaction.guild, reason=reason, moderation_type='note', response=await interaction.original_response()) await target.send(embed=embed) except discord.errors.HTTPException: pass @@ -258,7 +310,7 @@ class Moderation(commands.Cog): silent = not await self.config.guild(interaction.guild).dm_users() if silent is False: try: - embed = await self.embed_factory('message', interaction.guild, reason, 'warned', await interaction.original_response()) + embed = await self.embed_factory('message', guild=interaction.guild, reason=reason, moderation_type='warned', response=await interaction.original_response()) await target.send(embed=embed) except discord.errors.HTTPException: pass @@ -284,7 +336,7 @@ class Moderation(commands.Cog): silent = not await self.config.guild(interaction.guild).dm_users() if silent is False: try: - embed = await self.embed_factory('message', interaction.guild, reason, 'muted', await interaction.original_response(), parsed_time) + embed = await self.embed_factory('message', guild=interaction.guild, reason=reason, moderation_type='muted', response=await interaction.original_response(), duration=parsed_time) await target.send(embed=embed) except discord.errors.HTTPException: pass @@ -306,7 +358,7 @@ class Moderation(commands.Cog): silent = not await self.config.guild(interaction.guild).dm_users() if silent is False: try: - embed = await self.embed_factory('message', interaction.guild, reason, 'unmuted', await interaction.original_response()) + embed = await self.embed_factory('message', guild=interaction.guild, reason=reason, moderation_type='unmuted', response=await interaction.original_response()) await target.send(embed=embed) except discord.errors.HTTPException: pass @@ -320,7 +372,7 @@ class Moderation(commands.Cog): silent = not await self.config.guild(interaction.guild).dm_users() if silent is False: try: - embed = await self.embed_factory('message', interaction.guild, reason, 'kicked', await interaction.original_response()) + embed = await self.embed_factory('message', guild=interaction.guild, reason=reason, moderation_type='kicked', response=await interaction.original_response()) await target.send(embed=embed) except discord.errors.HTTPException: pass @@ -352,7 +404,7 @@ class Moderation(commands.Cog): return await interaction.response.send_message(content=f"{target.mention} has been banned for {humanize.precisedelta(parsed_time)}!\n**Reason** - `{reason}`") try: - embed = await self.embed_factory('message', interaction.guild, reason, 'tempbanned', await interaction.original_response(), parsed_time) + embed = await self.embed_factory('message', guild=interaction.guild, reason=reason, moderation_type='tempbanned', response=await interaction.original_response(), duration=parsed_time) await target.send(embed=embed) except discord.errors.HTTPException: pass @@ -364,7 +416,7 @@ class Moderation(commands.Cog): silent = not await self.config.guild(interaction.guild).dm_users() if silent is False: try: - embed = await self.embed_factory('message', interaction.guild, reason, 'banned', await interaction.original_response()) + embed = embed = await self.embed_factory('message', guild=interaction.guild, reason=reason, moderation_type='banned', response=await interaction.original_response()) await target.send(embed=embed) except discord.errors.HTTPException: pass @@ -389,7 +441,7 @@ class Moderation(commands.Cog): silent = not await self.config.guild(interaction.guild).dm_users() if silent is False: try: - embed = await self.embed_factory('message', interaction.guild, reason, 'unbanned', await interaction.original_response()) + embed = await self.embed_factory('message', guild=interaction.guild, reason=reason, moderation_type='unbanned', response=await interaction.original_response()) await target.send(embed=embed) except discord.errors.HTTPException: pass @@ -436,7 +488,12 @@ class Moderation(commands.Cog): else: resolve_query = f"UPDATE `{db}`.`moderation_{interaction.guild.id}` SET resolved = 1, resolve_reason = %s WHERE moderation_id = %s" cursor.execute(resolve_query, (reason, case_number)) - await interaction.response.send_message(content=f"✅ Moderation #{case_number} resolved!") + response_query = "SELECT * FROM moderation_%s WHERE moderation_id = %s;" + cursor.execute(response_query, (interaction.guild.id, case_number)) + result = cursor.fetchone() + case_dict = self.generate_dict(result) + embed = self.embed_factory('case', interaction=interaction, case_dict=case_dict) + await interaction.response.send_message(content=f"✅ Moderation #{case_number} resolved!", embed=embed) @app_commands.command(name="case") async def case(self, interaction: discord.Interaction, case_number: int, ephemeral: bool = False): @@ -450,45 +507,7 @@ class Moderation(commands.Cog): database.close() if result: case = self.generate_dict(result) - try: - target = await interaction.client.fetch_user(case["target_id"]) - target_user = { - 'id': target.id, - 'name': target.name, - 'discriminator': target.discriminator - } - except discord.errors.NotFound: - target = discord.User(id=case["target_id"], name="Deleted User", discriminator="0") # pylint: disable=unexpected-keyword-arg, missing-kwoa - target_user = { - 'id': case['target_id'], - 'name': 'Deleted User', - 'discriminator': '0' - } - try: - moderator = await interaction.client.fetch_user(case["moderator_id"]) - moderator_user = { - 'id': moderator.id, - 'name': moderator.name, - 'discriminator': moderator.discriminator - } - except discord.errors.NotFound: - moderator = discord.User(id=case["moderator_id"], name="Deleted User", discriminator="0") # pylint: disable=unexpected-keyword-arg, missing-kwoa - moderator_user = { - 'id': case['moderator_id'], - 'name': 'Deleted User', - 'discriminator': '0' - } - target_name = target_user['name'] if target_user['discriminator'] == "0" else f"{target_user['name']}#{target_user['discriminator']}" - moderator_name = moderator_user['name'] if moderator_user['discriminator'] == "0" else f"{moderator_user['name']}#{moderator_user['discriminator']}" - embed = discord.Embed(title=f"📕 Case #{case['moderation_id']}", color=await self.bot.get_embed_color(None)) - embed.description = f"**Type:** {str.title(case['moderation_type'])}\n**Target:** {target_name} ({target_user['id']})\n**Moderator:** {moderator_name} ({moderator_user['id']})\n**Resolved:** {bool(case['resolved'])}\n**Timestamp:** | " - if case['duration'] != 'NULL': - td = timedelta(**{unit: int(val) for unit, val in zip(["hours", "minutes", "seconds"], case["duration"].split(":"))}) - duration_embed = f"{humanize.precisedelta(td)} | " if case["expired"] == '0' else str(humanize.precisedelta(td)) - embed.description = embed.description + f"\n**Duration:** {duration_embed}\n**Expired:** {bool(case['expired'])}" - embed.add_field(name='Reason', value=f"```{case['reason']}```", inline=False) - if case['resolved'] == 1: - embed.add_field(name='Resolve Reason', value=f"```{case['resolve_reason']}```", inline=False) + embed = self.embed_factory('case', interaction=interaction, case_dict=case) await interaction.response.send_message(embed=embed, ephemeral=ephemeral) else: await interaction.response.send_message(content=f"No case with case number `{case_number}` found.", ephemeral=True)