From 3bd6efac2549967c8a1294d3b9a4d65458e564a0 Mon Sep 17 00:00:00 2001 From: Snaky Date: Mon, 6 Nov 2023 17:37:19 +0200 Subject: [PATCH] Make code great again --- README.md | 7 +- src/cogs/backups.py | 133 ---------------------------- src/cogs/basic.py | 52 ++++++----- src/cogs/economy.py | 25 ++++-- src/cogs/fun.py | 90 +++++++++++-------- src/cogs/giveaways.py | 2 +- src/cogs/logger.py | 5 +- src/cogs/private_rooms.py | 12 +-- src/cogs/settings.py | 2 +- src/events/guild.py | 9 +- src/utils/__init__.py | 2 +- src/utils/database/backups.py | 8 +- src/utils/database/base.py | 49 +--------- src/utils/database/forms.py | 2 +- src/utils/database/private_rooms.py | 15 ++-- src/utils/misc.py | 6 +- 16 files changed, 138 insertions(+), 281 deletions(-) diff --git a/README.md b/README.md index 30dd6ac..3870a58 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,14 @@ - [ ] Ticket system - [ ] Economy System - [ ] Giveaways -- [ ] Forms ([read about this on Google Docs](https://docs.google.com/document/d/1LywTG8IN6ACVAJMPqUHMXY8DrSV-DpPOFIEdCt6OEVk/edit)) +- [ ] + Forms ([read about this on Google Docs](https://docs.google.com/document/d/1LywTG8IN6ACVAJMPqUHMXY8DrSV-DpPOFIEdCt6OEVk/edit)) - [ ] ... (Fill this lol) - ## Developers: + #### [/lazy/dev](https://github.com/devbutlazy) + #### [Weever](https://github.com/prunus1337) + #### [Snaky](https://github.com/Snaky1a) diff --git a/src/cogs/backups.py b/src/cogs/backups.py index 20e28fc..b6b36a9 100644 --- a/src/cogs/backups.py +++ b/src/cogs/backups.py @@ -1,6 +1,5 @@ import asyncio import io -import os from typing import Optional import disnake @@ -264,27 +263,6 @@ async def cog_load(self) -> None: @commands.has_permissions(administrator=True) @commands.cooldown(1, 5, commands.BucketType.guild) async def backup(self, ctx: commands.Context) -> None: - # if ctx.invoked_subcommand is None: - # embed = disnake.Embed( - # title="<:backup:1168599276520226826> Backup commands", - # color=0x2F3136, - # description=( - # f"`{ctx.prefix}backup create` – Create/update backup\n" - # f"`{ctx.prefix}backup delete` – Delete backup\n" - # f"`{ctx.prefix}backup load` – Load backup\n" - # f"`{ctx.prefix}backup file` – JSON file of server backup" - # ), - # ) - # - # if backups.check_backup(ctx.guild): - # data = await backups.get(guild_id=ctx.guild.id) - # data = data["backup_data"] - # embed.add_field( - # name="Last Backup:", - # value=f" ()", - # ) - # - # await ctx.send(embed=embed) embed = disnake.Embed(color=0x2F3136) embed.title = "Backup system" embed.add_field( @@ -309,117 +287,6 @@ async def backup(self, ctx: commands.Context) -> None: ) await ctx.send(embed=embed, view=BackupsView(self.bot)) - # @backup.command() - # @commands.cooldown(1, 5, commands.BucketType.guild) - # @is_owner() - # async def create(self, ctx: commands.Context) -> None: - # global msg - # embed = disnake.Embed(color=0x2F3136) - # try: - # embed.title = " Please wait..." - # embed.description = "Creating a server backup..." - # msg = await ctx.send(embed=embed) - # - # backup_data = await BackupGuild(ctx.guild).create() - # - # await self.backups.update_backups_info(ctx.guild.id, backup_data) - # - # embed.colour = 0x2F3136 - # embed.title = "Finished" - # embed.description = "Server backup has been successfully created" - # - # with io.StringIO() as temp_file: - # ujson.dump(backup_data, temp_file, indent=4) - # temp_file.seek(0) - # file_data = temp_file.read().encode() - # await msg.edit( - # embed=embed, file=disnake.File(fp=io.BytesIO(file_data), filename="backup.json") - # ) - # - # except (Exception, ExceptionGroup) as e: - # embed.colour = 0x2F3136 - # embed.title = "An error occurred" - # embed.description = "An error occurred when trying to save the server." - # await msg.edit(embed=embed) - # raise e - # - # @backup.command() - # @commands.cooldown(1, 5, commands.BucketType.guild) - # @is_owner() - # @has_bot_permissions() - # async def load(self, ctx: commands.Context) -> None: - # embed = disnake.Embed(color=0x2F3136) - # if ctx.message.attachments: - # temp_file = await save_file_to_memory(ctx.message.attachments[0]) - # data = ujson.load(temp_file) - # else: - # data = await self.backups.get(ctx.guild.id, to_return="backup_data") - # - # if not data: - # embed.title = "An error occurred" - # embed.description = "There is no backup for this server" - # await ctx.send(embed=embed) - # return - # - # embed.title = " Loading Backup" - # embed.set_footer(text=ctx.author, icon_url=ctx.author.avatar) - # - # msg = await ctx.send(embed=embed) - # - # await BackupGuild(ctx.guild).restore(data=data, message=msg) - # - # @backup.command() - # @commands.cooldown(1, 50, commands.BucketType.guild) - # @commands.has_permissions(administrator=True) - # async def file(self, ctx: commands.Context) -> None: - # if backups.check_backup(ctx.guild): - # backup = { - # "guild": {}, - # "text_channels": {}, - # "voice_channels": {}, - # "categories": {}, - # "roles": {}, - # } - # data = await self.backups.get(ctx.guild.id, to_return="backup_data") - # - # backup["guild"]["name"] = data["guild"]["name"] - # backup["guild"]["afk_timeout"] = data["guild"]["afk_timeout"] - # backup["guild"]["description"] = data["guild"]["description"] - # backup["text_channels"] = data["text"] - # backup["voice_channels"] = data["voice"] - # backup["categories"] = data["category"] - # backup["roles"] = data["roles"] - # - # with open(f"{str(ctx.guild.id)}.json", "w") as f: - # ujson.dump(backup, f, indent=4) - # - # await ctx.send(file=disnake.File(f"{str(ctx.guild.id)}.json")) - # os.remove(f"{str(ctx.guild.id)}.json") - # else: - # embed = disnake.Embed( - # colour=0x2F3136, - # title="An error occurred", - # description="There isn't any backup created for this server", - # ) - # - # await ctx.send(embed=embed) - # - # @backup.command() - # @is_owner() - # async def delete(self, ctx: commands.Context) -> None: - # embed = disnake.Embed(color=0x2F3136) - # - # if backups.check_backup(ctx.guild): - # await self.backups.remove_from_db({"_id": ctx.guild.id}) - # embed.title = "Finished" - # embed.description = "Server backup has been successfully deleted" - # await ctx.send(embed=embed) - # else: - # embed.title = "An error occurred" - # embed.description = "Server backup hasn't been deleted." - # embed.set_footer(text=ctx.author, icon_url=ctx.author.avatar) - # await ctx.send(embed=embed) - def setup(bot: commands.Bot) -> None: bot.add_cog(Backup(bot)) diff --git a/src/cogs/basic.py b/src/cogs/basic.py index 55ef37b..bc39acc 100644 --- a/src/cogs/basic.py +++ b/src/cogs/basic.py @@ -20,7 +20,6 @@ class BasicUtility(commands.Cog): def __init__(self, bot): self.bot = bot self.badges = { - # 0: "No Badge", 1: "<:staff:1168622635228344403>", 2: "<:partner:1168622631705137233>", 4: "<:hypesquad:1168622629901586605>", @@ -38,10 +37,6 @@ def __init__(self, bot): 133172312: "<:synthdev:1169689479452311582>", } - # @commands.command() - # async def test(self, ctx: commands.Context): - # await ctx.send(f"Test emoji: ") - @commands.slash_command( name=Localized("user", key="USER_COMMAND_NAME"), description=Localized( @@ -60,8 +55,14 @@ async def user( if user is None: user = interaction.user + dev_badge = ( + "" + if not check_if_user_is_developer(bot=self.bot, user_id=user.id) + else " <:synthdev:1169689479452311582>" + ) + embed = disnake.Embed( - title=f"@{user.name} / {user.id} {'' if not check_if_user_is_developer(bot=self.bot, user_id=user.id) else ' <:synthdev:1169689479452311582>'}", + title=f"@{user.name} / {user.id} {dev_badge}", color=0x2B2D31, description=f"[Link to DM](discord://discord.com/users/{user.id})", ) @@ -139,16 +140,24 @@ async def server(self, interaction: disnake.MessageCommandInteraction): ) embed.add_field( name="Main Information", - value=f"<:owner:1169684595697004616> **Owner:** {interaction.guild.owner.mention} ({interaction.guild.owner.id})\n" - f"<:created_at:1169684592006017034> **Created at:** {format_dt(interaction.guild.created_at, style='f')}\n" - f"<:boost:1169685353515462697> **Boosts:** {interaction.guild.premium_subscription_count}\n" - f"<:star:1169685347576336385> **Emojis:** {emoji_count}\n" - f"<:link:1169685349409226893> **Icon:** [click]({interaction.guild.icon})\n" - f"<:channels:1169684589640429599> **Channels:** {len(interaction.guild.channels)}\n" - f"<:design:1169686174374301746> <:channels:1169684589640429599> **Text Channels:** {len(interaction.guild.text_channels)}\n" - f"<:design:1169686174374301746> <:voice:1169684588315029534> **Voice Channels:** {len(interaction.guild.voice_channels)}\n" - f"<:design:1169686174374301746> <:category:1169684586666663999> **Categories:** {len(interaction.guild.categories)}\n" - f"<:design:1169688944502378536> <:thread:1169685355423866963> **Threads:** {len(interaction.guild.threads)}\n\n", + value=( + f"<:owner:1169684595697004616> **Owner:** " + f"{interaction.guild.owner.mention} ({interaction.guild.owner.id})\n" + f"<:created_at:1169684592006017034> **Created at:** " + f"{format_dt(interaction.guild.created_at, style='f')}\n" + f"<:boost:1169685353515462697> **Boosts:** {interaction.guild.premium_subscription_count}\n" + f"<:star:1169685347576336385> **Emojis:** {emoji_count}\n" + f"<:link:1169685349409226893> **Icon:** [click]({interaction.guild.icon})\n" + f"<:channels:1169684589640429599> **Channels:** {len(interaction.guild.channels)}\n" + f"<:design:1169686174374301746> <:channels:1169684589640429599> " + f"**Text Channels:** {len(interaction.guild.text_channels)}\n" + f"<:design:1169686174374301746> <:voice:1169684588315029534>" + f" **Voice Channels:** {len(interaction.guild.voice_channels)}\n" + f"<:design:1169686174374301746> <:category:1169684586666663999>" + f" **Categories:** {len(interaction.guild.categories)}\n" + f"<:design:1169688944502378536> <:thread:1169685355423866963>" + f" **Threads:** {len(interaction.guild.threads)}\n\n" + ), inline=False, ) embed.add_field( @@ -245,10 +254,13 @@ async def botinfo(self, interaction: disnake.MessageCommandInteraction): ) embed.add_field( name="Popularity", - value=f"<:info:1169685342077583480> Servers: **{len(self.bot.guilds)}**\n" - f"<:globe:1169690501063123065> Big servers (1000+): **{len([g for g in self.bot.guilds if g.member_count >= 1000])}**\n" - f"<:members:1169684583369949285> Users: **{len(set(self.bot.get_all_members()))}**\n" - f"<:channels:1169684589640429599> Channels: **{len(ch)}**\n", + value=( + f"<:info:1169685342077583480> Servers: **{len(self.bot.guilds)}**\n" + f"<:globe:1169690501063123065> Big servers (1000+): " + f"**{len([g for g in self.bot.guilds if g.member_count >= 1000])}**\n" + f"<:members:1169684583369949285> Users: **{len(set(self.bot.get_all_members()))}**\n" + f"<:channels:1169684589640429599> Channels: **{len(ch)}**\n" + ), inline=False, ) embed.add_field( diff --git a/src/cogs/economy.py b/src/cogs/economy.py index 01efc79..5a4955a 100644 --- a/src/cogs/economy.py +++ b/src/cogs/economy.py @@ -37,11 +37,13 @@ def __init__( @ui.button(emoji="✅", style=ButtonStyle.secondary, custom_id="test") async def yes_callback(self, _: ui.Button, interaction: MessageInteraction) -> None: await interaction.send(content="Please, wait...") + received_balance = await self.economy.get_balance(user_id=self.receiver.id) new_received_balance = received_balance + self.money + old_bal_sender = await self.economy.get_balance(user_id=self.ctx.author.id) new_sender_balance = old_bal_sender - self.money - print(new_received_balance, new_sender_balance) + try: await self.economy.update_db( {"id": self.receiver.id}, {"balance": new_received_balance} @@ -113,7 +115,10 @@ async def balance(self, interaction: CommandInteraction): await interaction.send( embed=Embed( title="Balance", - description=f"{interaction.author.name}, your balance:\n**Cash:** {money} 🪙\n**Bank:** {bank}🪙\n**Total:** {total}🪙", + description=( + f"{interaction.author.name}, your balance:" + f"\n**Cash:** {money} 🪙\n**Bank:** {bank}🪙\n**Total:** {total}🪙" + ), ), ephemeral=True, ) @@ -179,7 +184,10 @@ async def bank( await interaction.send( embed=Embed( title="Balance", - description=f"{interaction.author.name}, your balance now:\n**Cash:** {cash} 🪙\n**Bank:** {bank}🪙\n**Total:** {total}🪙", + description=( + f"{interaction.author.name}, your balance now:" + f"\n**Cash:** {cash} 🪙\n**Bank:** {bank}🪙\n**Total:** {total}🪙" + ), ) ) @@ -218,12 +226,13 @@ async def pay( description="You can't transfer less than 1 🪙", color=Color.red(), ).set_footer(text=f"Command executed by {interaction.author}"), - ) # + ) else: - if isinstance(user, Member): - res = user.id - else: - res = await MemberConverter().convert(interaction, user) + res = ( + user.id + if isinstance(user, Member) + else await MemberConverter().convert(interaction, str(user)) + ) await interaction.send( f"Are you sure you want transfer {money} 🪙 to {res.mention}?", view=Buttons( diff --git a/src/cogs/fun.py b/src/cogs/fun.py index ea43434..ede3639 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -37,14 +37,13 @@ async def roll( description=Localized("Flip a coin", key="COIN_COMMAND_DESC"), ) async def coin(self, interaction: disnake.MessageCommandInteraction): - if random.randint(0, 1) == 0: - embed = disnake.Embed( - title="Flip coin", color=0x2B2D31, description="Heads" - ) - else: - embed = disnake.Embed( - title="Flip coin", color=0x2B2D31, description="Tails" - ) + embed = disnake.Embed(title="Flip coin", color=0x2B2D31) + + match random.randint(0, 1): + case 0: + embed.description = "Heads" + case 1: + embed.description = "Tails" await interaction.send(embed=embed) @commands.slash_command( @@ -87,15 +86,16 @@ async def eight_ball( response_category = random.choice(["good", "medium", "bad"]) - if response_category == "good": - response = random.choice(good_responses) - color = 0x39F007 - elif response_category == "medium": - response = random.choice(medium_responses) - color = 0xF0D707 - else: - response = random.choice(bad_responses) - color = 0xF00707 + match response_category: + case "good": + response = random.choice(good_responses) + color = 0x39F007 + case "medium": + response = random.choice(medium_responses) + color = 0xF0D707 + case "bad": + response = random.choice(bad_responses) + color = 0xF00707 embed = disnake.Embed( title="Magic 8ball", @@ -125,29 +125,41 @@ async def ben( name=Localized("question", key="BEN_COMMAND_QUESTION_NAME"), ), ): + global embed + chance = random.randint(1, 5) - if chance == 1: - embed = disnake.Embed( - title="Yes", description=f"{question}", color=0x2B2D31 - ).set_image(url="https://c.tenor.com/R_itimARcLAAAAAC/talking-ben-yes.gif") - if chance == 2: - embed = disnake.Embed( - title="No", description=f"{question}", color=0x2B2D31 - ).set_image(url="https://c.tenor.com/3ZLujiiPc4YAAAAC/talking-ben-no.gif") - if chance == 3: - embed = disnake.Embed( - title="Hohoho", description=f"{question}", color=0x2B2D31 - ).set_image( - url="https://c.tenor.com/agrQMQjQTzgAAAAd/talking-ben-laugh.gif" - ) - if chance == 4: - embed = disnake.Embed( - title="Ugh...", description=f"{question}", color=0x2B2D31 - ).set_image(url="https://c.tenor.com/fr6i8VzKJuEAAAAd/talking-ben-ugh.gif") - if chance == 5: - embed = disnake.Embed( - title=f"Bye...", description=f"{question}", color=0x2B2D31 - ).set_image(url="https://c.tenor.com/7j3yFGeMMgIAAAAd/talking-ben-ben.gif") + + match chance: + case 1: + embed = disnake.Embed( + title="Yes", description=question, color=0x2B2D31 + ).set_image( + url="https://c.tenor.com/R_itimARcLAAAAAC/talking-ben-yes.gif" + ) + case 2: + embed = disnake.Embed( + title="No", description=question, color=0x2B2D31 + ).set_image( + url="https://c.tenor.com/3ZLujiiPc4YAAAAd/talking-ben-no.gif" + ) + case 3: + embed = disnake.Embed( + title="Hohoho", description=question, color=0x2B2D31 + ).set_image( + url="https://c.tenor.com/agrQMQjQTzgAAAAd/talking-ben-laugh.gif" + ) + case 4: + embed = disnake.Embed( + title="Ugh...", description=question, color=0x2B2D31 + ).set_image( + url="https://c.tenor.com/fr6i8VzKJuEAAAAd/talking-ben-ugh.gif" + ) + case 5: + embed = disnake.Embed( + title="Nope", description=question, color=0x2B2D31 + ).set_image( + url="https://c.tenor.com/7j3yFGeMMgIAAAAd/talking-ben-ben.gif" + ) await interaction.send(embed=embed) diff --git a/src/cogs/giveaways.py b/src/cogs/giveaways.py index ee1d908..090ac8f 100644 --- a/src/cogs/giveaways.py +++ b/src/cogs/giveaways.py @@ -90,7 +90,7 @@ async def create( users = await reaction.users().flatten() users = [user for user in users if not user.bot] - if len(users) == 0: + if not users: await giveaway_msg.edit( content="Not enough participants to choose winners." ) diff --git a/src/cogs/logger.py b/src/cogs/logger.py index 227c79e..87a361b 100644 --- a/src/cogs/logger.py +++ b/src/cogs/logger.py @@ -30,10 +30,9 @@ async def set_log_channel( invite_log_channel: disnake.TextChannel = None, message_log_channel: disnake.TextChannel = None, ): - main_log = await check_channel( + if main_log := await check_channel( channel=main_log_channel, interaction=interaction - ) - if main_log: + ): guild_log = invite_log = message_log = False if guild_log_channel: guild_log = await check_channel( diff --git a/src/cogs/private_rooms.py b/src/cogs/private_rooms.py index 238fcbc..783cee4 100644 --- a/src/cogs/private_rooms.py +++ b/src/cogs/private_rooms.py @@ -39,10 +39,11 @@ async def _users( content="Введите лимит (например: 9)", ephemeral=True ) msg = await self.bot.wait_for( - "message", check=lambda x: x.author == interaction.author, timeout=15 + "message", + check=lambda x: x.author == interaction.author and x.content.isdigit(), + timeout=15, ) - if msg.content.isdigit(): - await self.channel.edit(user_limit=int(msg.content)) + await self.channel.edit(user_limit=int(msg.content)) await msg.delete() @disnake.ui.button(label="🕵️") @@ -277,10 +278,9 @@ async def on_voice_state_update( @commands.Cog.listener() async def on_message(self, message): - rooms = await self.private_rooms.get_private_room( + if rooms := await self.private_rooms.get_private_room( message.guild.id, to_return="channels" - ) - if rooms: + ): for room in rooms: if message.channel.id == room and message.author.id != self.bot.user.id: await message.delete() diff --git a/src/cogs/settings.py b/src/cogs/settings.py index a20290d..a5f7d8a 100644 --- a/src/cogs/settings.py +++ b/src/cogs/settings.py @@ -49,7 +49,7 @@ async def cog_load(self) -> None: @commands.command() async def set_prefix(self, ctx: commands.Context, prefix: str) -> Message: - """Set current prefix to another one""" + """Set the current prefix to another one""" if prefix is None or prefix == "": return await ctx.reply("Please enter a prefix!") elif len(prefix) >= 5: diff --git a/src/events/guild.py b/src/events/guild.py index 26ac571..27cbfcf 100644 --- a/src/events/guild.py +++ b/src/events/guild.py @@ -41,7 +41,8 @@ async def on_guild_join(self, guild: disnake.Guild): join_embed = ( disnake.Embed( title="Synth | New Era", - description=f""" + description=( + f""" Hey :wave_tone1:. Thanks for adding our multi-functional bot, Synth. :rocket: Quick start: @@ -49,8 +50,10 @@ async def on_guild_join(self, guild: disnake.Guild): 2. To get more information about a command, type `{await get_prefix(message=guild)}help ` 3. Join our support server — [click](https://discord.gg/7vT3H3tVYp) -Finally, if you have any issues with the bot, you can take a look at the website. You can also join the [Synth Community](https://discord.gg/7vT3H3tVYp) and ask for help. - """, +Finally, if you have any issues with the bot, you can take a look at the website. You can also join the +[Synth Community](https://discord.gg/7vT3H3tVYp) and ask for help. + """ + ), color=0x2F3136, ) .set_thumbnail(url=self.bot.user.avatar) diff --git a/src/utils/__init__.py b/src/utils/__init__.py index e7ac4b5..1f03605 100644 --- a/src/utils/__init__.py +++ b/src/utils/__init__.py @@ -3,8 +3,8 @@ from .database.forms import FormsDatabase from .database.invite import InviteTrackerDatabase from .database.logger import LoggerDatabase -from .database.tickets import TicketDatabase from .database.private_rooms import PrivateRoomsDatabase +from .database.tickets import TicketDatabase economy = EconomyDatabase("economy") main_db = MainDatabase("bot") diff --git a/src/utils/database/backups.py b/src/utils/database/backups.py index 58d80ba..32da573 100644 --- a/src/utils/database/backups.py +++ b/src/utils/database/backups.py @@ -21,10 +21,10 @@ async def get( if await self.find_one_from_db({"guild_id": guild_id}) is None: return [] - result = await self.find_one_from_db({"guild_id": guild_id}) - if result and to_return: - return result.get(to_return, None) - if result: + + if result := await self.find_one_from_db({"guild_id": guild_id}): + if result and to_return: + return result.get(to_return, None) return result else: return [] diff --git a/src/utils/database/base.py b/src/utils/database/base.py index 44e392b..65ff919 100644 --- a/src/utils/database/base.py +++ b/src/utils/database/base.py @@ -108,51 +108,6 @@ def get_items_in_cache( return result.get(to_return, None) return result - # for key, value in self.collection_cache.items(): - # if isinstance(query, (str, int)): - # if query in value.values() or query in value.keys(): - # result.append({key: value}) - # else: - # if isinstance(query, dict): - # for sub_key, sub_value in value.items(): - # if query in sub_value.values() or query in sub_value.keys(): - # result.append({key: value}) - # break - # else: - # for sub_value in value: - # print(sub_value) - # print(query) - # if isinstance(query, dict): - # print(sub_value.keys(), sub_value) - # if query in sub_value.values() or query in sub_value.keys(): - # result.append({key: value}) - # break - # elif isinstance(query, (str, int, bool)): - # if query == sub_value: - # result.append({key: value}) - # break - # elif isinstance(query, list): - # for sub_sub_value in sub_value: - # if query == sub_sub_value: - # result.append({key: value}) - # break - # if query in sub_value - - # for key, value in self.collection_cache.items(): - # if isinstance(query, (str, int)): - # if query in value.values() or query in value.keys(): - # result.append({key: value}) - # else: - # for inner_query in query.values(): - # if isinstance(inner_query, dict) and all( - # k in value and value[k] == v for k, v in inner_query.items() - # ): - # result.append({key: value}) - # break - # elif inner_query in value.values() or inner_query in value.keys(): - # result.append({key: value}) - # break - async def find_one_from_cache(self, value: Dict[str, Any]) -> Any: results = self.get_items_in_cache(value) return results[0] if results else None @@ -172,7 +127,7 @@ async def find_one( if len(results[0].get(1, [])) >= 1: return results[0].get(1, []) if return_first_result else results - # if not found in cache, search in database + # if not found in cache, search in a database results = await self.get_items_in_db(value, to_list=True) if results: return results[0] if return_first_result else results @@ -198,8 +153,6 @@ async def update_db(self, data: Dict[str, Any], new_value: Dict[str, Any]) -> No await self.collection.update_one(data, {"$set": new_value}, upsert=True) old_data = await self.find_one_from_db(data) self._update_cache(_id=old_data, new_value=new_value) # type: ignore - # if result is None: - # self._add_to_cache(param_filter=new_value) async def remove_from_db(self, data: Dict[str, Any]) -> None: await self.collection.delete_one(data) diff --git a/src/utils/database/forms.py b/src/utils/database/forms.py index 58d3993..78c53ec 100644 --- a/src/utils/database/forms.py +++ b/src/utils/database/forms.py @@ -30,7 +30,7 @@ async def update_form_info( form_description: str, form_channel_id: int, form_type: str, - ) -> int: + ) -> None: if await self.find_one_from_db({"guild_id": guild_id}) is None: await self.add_to_db( { diff --git a/src/utils/database/private_rooms.py b/src/utils/database/private_rooms.py index 4a00c1d..745deb1 100644 --- a/src/utils/database/private_rooms.py +++ b/src/utils/database/private_rooms.py @@ -13,10 +13,9 @@ def __init__(self, database_name: str) -> None: async def get_private_room( self, guild_id: int, to_return: str = None ) -> Union[List[Dict[str, Any]], Mapping[str, Any], None]: - result = await self.find_one_from_db({"guild_id": guild_id}) - if result and to_return: - return result.get(to_return, None) - if result: + if result := await self.find_one_from_db({"guild_id": guild_id}): + if result and to_return: + return result.get(to_return, None) return result else: return None @@ -43,8 +42,7 @@ async def create_private_room( async def delete_private_room( self, member: Member, voice_channel: disnake.VoiceChannel ): - result = await self.get_private_room(member.guild.id, to_return="channels") - if result: + if result := await self.get_private_room(member.guild.id, to_return="channels"): for result_dict in result: if voice_channel.id in result_dict.values(): result_dict.clear() @@ -55,8 +53,9 @@ async def delete_private_room( async def get_owner_id( self, guild_id: int, voice_channel: disnake.VoiceChannel ) -> Optional[int]: - result = await self.get_private_room(guild_id=guild_id, to_return="channels") - if result: + if result := await self.get_private_room( + guild_id=guild_id, to_return="channels" + ): for room in result: if room.get("channel_id") == voice_channel.id: return room.get("owner_id", None) or None diff --git a/src/utils/misc.py b/src/utils/misc.py index 2504f69..54c9f22 100644 --- a/src/utils/misc.py +++ b/src/utils/misc.py @@ -1,4 +1,5 @@ import io +from enum import StrEnum from io import BytesIO from typing import List, Union, Literal @@ -11,13 +12,12 @@ TextChannel, HTTPException, Forbidden, + Guild, ) from disnake.ext import commands from . import main_db -from enum import StrEnum - async def bot_get_guild_prefix(bot: commands.Bot, message: Message) -> List[str]: if not message.guild or await main_db.get_prefix(message.guild.id) is None: @@ -28,7 +28,7 @@ async def bot_get_guild_prefix(bot: commands.Bot, message: Message) -> List[str] # get prefix for commands, events etc.. -async def get_prefix(message: Message) -> Union[List[str], str]: +async def get_prefix(message: Union[Message, Guild]) -> Union[List[str], str]: if not message.guild or await main_db.get_prefix(message.guild.id) is None: return "s."