From 7ca17f27f1c7ef7e837f6177983bfcb972d949f3 Mon Sep 17 00:00:00 2001 From: Snaky Date: Tue, 21 Nov 2023 20:04:02 +0200 Subject: [PATCH] [Other]: refactored code --- src/bot.py | 17 ++++--- src/cogs/GiveawaysCog.py | 82 ++++++++++++++++------------------ src/cogs/ModerationCog.py | 8 ++-- src/cogs/VoiceCog.py | 28 ++++++------ src/events/guild.py | 4 +- src/events/message.py | 4 +- src/utils/database/base.py | 10 +++-- src/utils/misc.py | 90 +++++++++++++++++++------------------- 8 files changed, 118 insertions(+), 125 deletions(-) diff --git a/src/bot.py b/src/bot.py index 5eaf989..7654aee 100644 --- a/src/bot.py +++ b/src/bot.py @@ -30,7 +30,6 @@ def __init__(self, debug: bool = False) -> None: self.i18n.load("src/utils/locale") self.debug = debug - async def on_message(self, message: disnake.Message): prefix = await get_prefix(message) prefix_len = len(prefix) @@ -61,10 +60,10 @@ async def on_ready(self) -> None: event_name = extension[:-3] self.load_extension(f"src.cogs.{event_name}") except ( - commands.ExtensionNotFound, - commands.NoEntryPointError, - commands.ExtensionFailed, - commands.ExtensionError, + commands.ExtensionNotFound, + commands.NoEntryPointError, + commands.ExtensionFailed, + commands.ExtensionError, ) as e: logging.error( f"\n\nFailed to load {extension}!\n{traceback.print_exception(e)}" @@ -80,10 +79,10 @@ async def on_ready(self) -> None: try: self.load_extension(f"src.events.{event[:-3]}") except ( - commands.ExtensionNotFound, - commands.NoEntryPointError, - commands.ExtensionFailed, - commands.ExtensionError, + commands.ExtensionNotFound, + commands.NoEntryPointError, + commands.ExtensionFailed, + commands.ExtensionError, ) as e: logging.error( f"\n\nFailed to load {extension}!\n{traceback.print_exception(e)}" diff --git a/src/cogs/GiveawaysCog.py b/src/cogs/GiveawaysCog.py index b6213c5..4f06e6b 100644 --- a/src/cogs/GiveawaysCog.py +++ b/src/cogs/GiveawaysCog.py @@ -50,9 +50,7 @@ async def end_gw(self, i): if len(users) > 0: prize = i.get("prize") - await message.reply( - f"{winners} congratulations, you have won **{prize}**!" - ) + await message.reply(f"{winners} congratulations, you have won **{prize}**!") @commands.slash_command( name=Localized("giveaway", key="GIVEAWAY_COMMAND_NAME"), @@ -66,27 +64,27 @@ async def giveaway(self, interaction): name=Localized("create", key="GIVEAWAY_CREATE_COMMAND_NAME"), ) async def create( - self, - interaction: disnake.ApplicationCommandInteraction, - prize: str = commands.Param( - description=Localized( - "Choice prize", key="GIVEAWAY_CREATE_COMMAND_PRIZE_DESC" - ), - name=Localized("prize", key="GIVEAWAY_CREATE_COMMAND_PRIZE_NAME"), + self, + interaction: disnake.ApplicationCommandInteraction, + prize: str = commands.Param( + description=Localized( + "Choice prize", key="GIVEAWAY_CREATE_COMMAND_PRIZE_DESC" ), - winners: int = commands.Param( - description=Localized( - "Winners", key="GIVEAWAY_CREATE_COMMAND_WINNERS_DESC" - ), - name=Localized("winners", key="GIVEAWAY_CREATE_COMMAND_WINNERS_NAME"), + name=Localized("prize", key="GIVEAWAY_CREATE_COMMAND_PRIZE_NAME"), + ), + winners: int = commands.Param( + description=Localized( + "Winners", key="GIVEAWAY_CREATE_COMMAND_WINNERS_DESC" ), - duration: str = commands.Param( - description=Localized( - "Example: 1d1h1m1s (1 day, 1 hour, 1 minute, 1 second)", - key="GIVEAWAY_CREATE_COMMAND_DURATION_DESC", - ), - name=Localized("duration", key="GIVEAWAY_CREATE_COMMAND_DURATION_NAME"), + name=Localized("winners", key="GIVEAWAY_CREATE_COMMAND_WINNERS_NAME"), + ), + duration: str = commands.Param( + description=Localized( + "Example: 1d1h1m1s (1 day, 1 hour, 1 minute, 1 second)", + key="GIVEAWAY_CREATE_COMMAND_DURATION_DESC", ), + name=Localized("duration", key="GIVEAWAY_CREATE_COMMAND_DURATION_NAME"), + ), ): duration_regex = r"(\d+)([dhms])" @@ -138,22 +136,22 @@ async def create( name=Localized("reroll", key="GIVEAWAY_REROLL_COMMAND_NAME"), ) async def reroll( - self, - interaction, - message_id=commands.Param( - description=Localized( - "Message ID", key="GIVEAWAY_REROLL_COMMAND_MESSAGEID_DESC" - ), - name=Localized("message_id", key="GIVEAWAY_REROLL_COMMAND_MESSAGEID_NAME"), + self, + interaction, + message_id=commands.Param( + description=Localized( + "Message ID", key="GIVEAWAY_REROLL_COMMAND_MESSAGEID_DESC" ), - winners: int = commands.Param( - description=Localized( - "Choice winners (default: 1)", - key="GIVEAWAY_REROLL_COMMAND_WINNERS_DESC", - ), - name=Localized("winners", key="GIVEAWAY_REROLL_COMMAND_WINNERS_NAME"), - default=1, + name=Localized("message_id", key="GIVEAWAY_REROLL_COMMAND_MESSAGEID_NAME"), + ), + winners: int = commands.Param( + description=Localized( + "Choice winners (default: 1)", + key="GIVEAWAY_REROLL_COMMAND_WINNERS_DESC", ), + name=Localized("winners", key="GIVEAWAY_REROLL_COMMAND_WINNERS_NAME"), + default=1, + ), ): try: giveaway_msg = await interaction.channel.fetch_message(message_id) @@ -163,8 +161,8 @@ async def reroll( if giveaway_msg.author == self.bot: if ( - not giveaway_msg.embeds - or not giveaway_msg.embeds[0].title == "Giveaway" + not giveaway_msg.embeds + or not giveaway_msg.embeds[0].title == "Giveaway" ): await interaction.send( "The above message is not a giveaway message.", ephemeral=True @@ -207,13 +205,9 @@ async def check_gw(self): await self.bot.wait_until_ready() async for giveaway_data in self.giveaway_db.collection.find({}): - channel: Optional[disnake.TextChannel] = ( - self.bot.get_channel(giveaway_data["channel_id"]) - or - await self.bot.fetch_channel( - giveaway_data["channel_id"] - ) - ) + channel: Optional[disnake.TextChannel] = self.bot.get_channel( + giveaway_data["channel_id"] + ) or await self.bot.fetch_channel(giveaway_data["channel_id"]) try: await channel.fetch_message(giveaway_data["message_id"]) except (disnake.NotFound, disnake.Forbidden, disnake.HTTPException): diff --git a/src/cogs/ModerationCog.py b/src/cogs/ModerationCog.py index 46761cd..d4e3ba8 100644 --- a/src/cogs/ModerationCog.py +++ b/src/cogs/ModerationCog.py @@ -346,7 +346,7 @@ async def refresh_embed(): ) start = index * per_page - for page in pages[start:(index + 1) * per_page]: + for page in pages[start : (index + 1) * per_page]: mutes_embed.add_field(name="", value=page, inline=False) return mutes_embed @@ -453,7 +453,7 @@ async def refresh_embed(): bans_embed.set_footer(text=f"{ctx.author}", icon_url=ctx.author.avatar) start = index * per_page - for page in pages[start: (index + 1) * per_page]: + for page in pages[start : (index + 1) * per_page]: bans_embed.add_field(name="", value=page, inline=False) return bans_embed @@ -565,9 +565,7 @@ async def refresh_buttons(ind: int, total_p: int): ) return [prev_button, next_button, delete_button] - async def refresh_embed( - context: commands.Context, warns_list: List[Any], i, _ - ): + async def refresh_embed(context: commands.Context, warns_list: List[Any], i, _): warns_embed = Embed( title=f"Warns of {user}", description=f"**Total warns count:** {len(warns_list)}", diff --git a/src/cogs/VoiceCog.py b/src/cogs/VoiceCog.py index adfddcd..694bead 100644 --- a/src/cogs/VoiceCog.py +++ b/src/cogs/VoiceCog.py @@ -13,9 +13,9 @@ class MusicPlayer(mafic.Player[commands.Bot]): def __init__( - self, - client: commands.Bot, - channel: disnake.VoiceChannel, + self, + client: commands.Bot, + channel: disnake.VoiceChannel, ) -> None: super().__init__(client, channel) @@ -31,7 +31,7 @@ def __init__(self, message_id: int, *, timeout: float | None = None) -> None: @disnake.ui.button(label="Skip", style=disnake.ButtonStyle.green) async def skip( - self, _: disnake.ui.Button, interaction: disnake.MessageInteraction + self, _: disnake.ui.Button, interaction: disnake.MessageInteraction ) -> None: player: MusicPlayer @@ -56,7 +56,7 @@ async def skip( @disnake.ui.button(label="Resume/Pause", style=disnake.ButtonStyle.gray) async def resume_and_pause( - self, _: disnake.ui.Button, interaction: disnake.MessageInteraction + self, _: disnake.ui.Button, interaction: disnake.MessageInteraction ): player: MusicPlayer @@ -70,7 +70,7 @@ async def resume_and_pause( @disnake.ui.button(label="Queue", style=disnake.ButtonStyle.blurple) async def queue( - self, _: disnake.ui.Button, interaction: disnake.MessageInteraction + self, _: disnake.ui.Button, interaction: disnake.MessageInteraction ): player: MusicPlayer @@ -298,22 +298,22 @@ async def on_track_start(self, event: mafic.TrackStartEvent) -> None: async def on_message(self, message: disnake.Message): if message.guild: if rooms := await self.private_rooms.get_private_room( - message.guild.id, to_return="channels" + message.guild.id, to_return="channels" ): for room in rooms: if ( - message.channel.id == room - and message.author.id != self.bot.user.id + message.channel.id == room + and message.author.id != self.bot.user.id ): await message.delete() break @commands.Cog.listener() async def on_voice_state_update( - self, - member: disnake.Member, - before: disnake.VoiceState, - after: disnake.VoiceState, + self, + member: disnake.Member, + before: disnake.VoiceState, + after: disnake.VoiceState, ): if after.channel and len(after.channel.members) != 0: is_main_room = await self.private_rooms.get_private_room( @@ -348,7 +348,7 @@ async def on_voice_state_update( return elif before.channel and len(before.channel.members) == 0: if room_channels := await self.private_rooms.get_private_room( - member.guild.id, to_return="channels" + member.guild.id, to_return="channels" ): for room in room_channels: if room_id := room.get("channel_id", None): diff --git a/src/events/guild.py b/src/events/guild.py index 320578d..81f28a6 100644 --- a/src/events/guild.py +++ b/src/events/guild.py @@ -86,7 +86,9 @@ async def on_guild_role_delete(self, role: disnake.Role) -> None: await channel.send(embed=embed) @commands.Cog.listener() - async def on_guild_role_update(self, before: disnake.Role, after: disnake.Role) -> None: + async def on_guild_role_update( + self, before: disnake.Role, after: disnake.Role + ) -> None: embed = disnake.Embed( title="Synth | Updated Role", color=self.settings_db.get_embed_color(before.guild.id), diff --git a/src/events/message.py b/src/events/message.py index 86a97b1..132a3e4 100644 --- a/src/events/message.py +++ b/src/events/message.py @@ -236,9 +236,7 @@ async def on_raw_bulk_message_delete( await channel.send(embeds=embeds) for file in range(0, len(files), 10): - await channel.send( - files=files[file: file + 10] - ) + await channel.send(files=files[file : file + 10]) @commands.Cog.listener() async def on_message_edit( diff --git a/src/utils/database/base.py b/src/utils/database/base.py index e7e3bf7..df720a3 100644 --- a/src/utils/database/base.py +++ b/src/utils/database/base.py @@ -33,9 +33,7 @@ def _add_to_cache(self, param_filter: Dict[str, Any]) -> Any: self.collection_cache[_id] = param_filter if self.debug: - logging.info( - f"[{self.name}]: Added {_id} to cache\nValue: {param_filter}" - ) + logging.info(f"[{self.name}]: Added {_id} to cache\nValue: {param_filter}") return param_filter @@ -107,7 +105,11 @@ async def get_items_in_db( def get_items_in_cache( self, query: Dict[Any, Any], to_return: str = None ) -> Union[ - List[Dict[Union[int, str], Dict[str, Any]]], Dict[str, Any], Dict[str, Any], int, str + List[Dict[Union[int, str], Dict[str, Any]]], + Dict[str, Any], + Dict[str, Any], + int, + str, ]: """ Get items from cache by search query diff --git a/src/utils/misc.py b/src/utils/misc.py index 6425044..fe70048 100644 --- a/src/utils/misc.py +++ b/src/utils/misc.py @@ -59,8 +59,8 @@ async def is_command_disabled(message: Message, command: str) -> bool: async def check_channel( - channel: TextChannel, - interaction: Union[MessageCommandInteraction, commands.Context], + channel: TextChannel, + interaction: Union[MessageCommandInteraction, commands.Context], ) -> bool: await interaction.send( f"Checking access to channel {channel.mention}...", ephemeral=True @@ -218,12 +218,12 @@ async def hms(sec): async def common_checks( - ctx: commands.Context, - member: Union[int, str, disnake.Member, disnake.User], - check_bot=False, - for_unban=False, - for_mute=False, - str_time=None, + ctx: commands.Context, + member: Union[int, str, disnake.Member, disnake.User], + check_bot=False, + for_unban=False, + for_mute=False, + str_time=None, ): error_embed = Embed(color=disnake.Colour.red()) @@ -242,10 +242,10 @@ async def common_checks( return False, error_embed elif ( - not for_unban - and isinstance(member, disnake.Member) - and check_bot - and member.bot + not for_unban + and isinstance(member, disnake.Member) + and check_bot + and member.bot ): error_embed.description = ( f"{emoji('error')} | You can't perform this action on a bot." @@ -253,9 +253,9 @@ async def common_checks( return False, error_embed elif ( - not for_unban - and isinstance(member, disnake.Member) - and member.top_role >= ctx.author.top_role + not for_unban + and isinstance(member, disnake.Member) + and member.top_role >= ctx.author.top_role ): error_embed.description = ( f"{emoji('error')} | Your role is not higher than {member.mention}'s role." @@ -263,9 +263,9 @@ async def common_checks( return False, error_embed elif ( - not for_unban - and isinstance(member, disnake.Member) - and member.id == ctx.bot.user.id + not for_unban + and isinstance(member, disnake.Member) + and member.id == ctx.bot.user.id ): error_embed.description = ( f"{emoji('error')} | You can't perform this action on the bot." @@ -273,11 +273,11 @@ async def common_checks( return False, error_embed elif ( - check_bot - and isinstance(member, disnake.Member) - and member.top_role >= ctx.guild.get_member(ctx.bot.user.id).top_role - and not ctx.author.guild.owner - and not for_unban + check_bot + and isinstance(member, disnake.Member) + and member.top_role >= ctx.guild.get_member(ctx.bot.user.id).top_role + and not ctx.author.guild.owner + and not for_unban ): error_embed.description = ( f"{emoji('error')} | " @@ -302,15 +302,15 @@ async def common_checks( class EmbedPaginator(disnake.ui.View): def __init__( - self, - interaction: Union[ - disnake.MessageCommandInteraction, disnake.MessageInteraction - ], - author: disnake.Member, - embed: disnake.Embed, - data: Optional[Union[Dict, List]], - timeout: Optional[int] = None, - separate: int = 10, + self, + interaction: Union[ + disnake.MessageCommandInteraction, disnake.MessageInteraction + ], + author: disnake.Member, + embed: disnake.Embed, + data: Optional[Union[Dict, List]], + timeout: Optional[int] = None, + separate: int = 10, ) -> None: super().__init__(timeout=timeout) self.current_page = 1 @@ -321,21 +321,21 @@ def __init__( self.data = data async def send_message( - self, - ctx: Union[ - commands.Context, - disnake.MessageCommandInteraction, - disnake.MessageInteraction, - ], + self, + ctx: Union[ + commands.Context, + disnake.MessageCommandInteraction, + disnake.MessageInteraction, + ], ) -> Union[Message, Any]: if isinstance( - ctx, (disnake.MessageCommandInteraction, disnake.MessageInteraction) + ctx, (disnake.MessageCommandInteraction, disnake.MessageInteraction) ): return await ctx.response.send_message(embed=self.embed, view=self) return await ctx.send(embed=self.embed, view=self) async def _create_embed( - self, embed: disnake.Embed, data: Union[Dict, List] + self, embed: disnake.Embed, data: Union[Dict, List] ) -> disnake.Embed: embed: disnake.Embed = disnake.Embed( title=embed.title, @@ -357,15 +357,15 @@ async def _create_embed( return embed async def update( - self, - message: Union[disnake.MessageCommandInteraction, disnake.MessageInteraction], - embed: disnake.Embed, + self, + message: Union[disnake.MessageCommandInteraction, disnake.MessageInteraction], + embed: disnake.Embed, ) -> None: await message.edit_original_response(embed=embed, view=self) @disnake.ui.button(label="️◀️", style=disnake.ButtonStyle.blurple) async def prev_page( - self, _: disnake.ui.Button, interaction: disnake.MessageInteraction + self, _: disnake.ui.Button, interaction: disnake.MessageInteraction ) -> None: await interaction.response.defer() self.current_page -= 1 @@ -376,7 +376,7 @@ async def prev_page( @disnake.ui.button(label="▶️", style=disnake.ButtonStyle.blurple) async def next_page( - self, _: disnake.ui.Button, interaction: disnake.MessageInteraction + self, _: disnake.ui.Button, interaction: disnake.MessageInteraction ) -> None: await interaction.response.defer() self.current_page += 1