From a9928597e3671bbe880e8b929bb212d7da90dac7 Mon Sep 17 00:00:00 2001 From: oscarvsp Date: Tue, 5 Dec 2023 12:27:27 +0100 Subject: [PATCH] added check and error msg for database loading --- classes/database.py | 56 ++++++++++++++++++++++++--------------------- cogs/Admin.py | 35 +++++++--------------------- cogs/Ulb.py | 14 +++++------- 3 files changed, 44 insertions(+), 61 deletions(-) diff --git a/classes/database.py b/classes/database.py index 61d0c39..9313d65 100644 --- a/classes/database.py +++ b/classes/database.py @@ -94,7 +94,7 @@ def loaded(cls) -> bool: return cls._loaded @classmethod - def load(cls, bot: Bot) -> None: + async def load(cls, bot: Bot) -> bool: """Load the data from the google sheet. Returns @@ -104,31 +104,35 @@ def load(cls, bot: Bot) -> None: - Guild: `Dict[disnake.Guild, disnake.Role]` - Users: `Dict[disnake.User, UlbUser]]` """ - # First time this is call, we need to load the credentials and the sheet - if not cls._sheet: - cred_dict = {} - cred_dict["type"] = os.getenv("GS_TYPE") - cred_dict["project_id"] = os.getenv("GS_PROJECT_ID") - cred_dict["auth_uri"] = os.getenv("GS_AUTHOR_URI") - cred_dict["token_uri"] = os.getenv("GS_TOKEN_URI") - cred_dict["auth_provider_x509_cert_url"] = os.getenv("GS_AUTH_PROV") - cred_dict["client_x509_cert_url"] = os.getenv("GS_CLIENT_CERT_URL") - cred_dict["private_key"] = os.getenv("GS_PRIVATE_KEY").replace( - "\\n", "\n" - ) # Python add a '\' before any '\n' when loading a str - cred_dict["private_key_id"] = os.getenv("GS_PRIVATE_KEY_ID") - cred_dict["client_email"] = os.getenv("GS_CLIENT_EMAIL") - cred_dict["client_id"] = int(os.getenv("GS_CLIENT_ID")) - creds = ServiceAccountCredentials.from_json_keyfile_dict(cred_dict, cls._scope) - cls._client = gspread.authorize(creds) - logging.info("[Database] Google sheet credentials loaded.") - - # Open google sheet - cls._sheet = cls._client.open_by_url(os.getenv("GOOGLE_SHEET_URL")) - cls._users_ws = cls._sheet.worksheet("users") - cls._guilds_ws = cls._sheet.worksheet("guilds") - - logging.info("[Database] Spreadsheed loaded") + try: + # First time this is call, we need to load the credentials and the sheet + if not cls._sheet: + cred_dict = {} + cred_dict["type"] = os.getenv("GS_TYPE") + cred_dict["project_id"] = os.getenv("GS_PROJECT_ID") + cred_dict["auth_uri"] = os.getenv("GS_AUTHOR_URI") + cred_dict["token_uri"] = os.getenv("GS_TOKEN_URI") + cred_dict["auth_provider_x509_cert_url"] = os.getenv("GS_AUTH_PROV") + cred_dict["client_x509_cert_url"] = os.getenv("GS_CLIENT_CERT_URL") + cred_dict["private_key"] = os.getenv("GS_PRIVATE_KEY").replace( + "\\n", "\n" + ) # Python add a '\' before any '\n' when loading a str + cred_dict["private_key_id"] = os.getenv("GS_PRIVATE_KEY_ID") + cred_dict["client_email"] = os.getenv("GS_CLIENT_EMAIL") + cred_dict["client_id"] = int(os.getenv("GS_CLIENT_ID")) + creds = ServiceAccountCredentials.from_json_keyfile_dict(cred_dict, cls._scope) + cls._client = gspread.authorize(creds) + logging.info("[Database] Google sheet credentials loaded.") + + # Open google sheet + cls._sheet = cls._client.open_by_url(os.getenv("GOOGLE_SHEET_URL")) + cls._users_ws = cls._sheet.worksheet("users") + cls._guilds_ws = cls._sheet.worksheet("guilds") + + logging.info("[Database] Spreadsheed loaded") + except (ValueError, gspread.exceptions.SpreadsheetNotFound, gspread.exceptions.WorksheetNotFound) as err: + await bot.send_error_log(bot.tracebackEx(err)) + return logging.info("[Database] Loading data...") diff --git a/cogs/Admin.py b/cogs/Admin.py index 10990fc..3ca1882 100644 --- a/cogs/Admin.py +++ b/cogs/Admin.py @@ -28,11 +28,12 @@ def __init__(self, bot: Bot): ) async def update(self, inter: disnake.ApplicationCommandInteraction): await inter.response.defer(ephemeral=True) - Database.load(self.bot) - await utils.update_all_guilds() - await inter.edit_original_response( - embed=disnake.Embed(description="All servers updated !", color=disnake.Color.green()) - ) + await Database.load(self.bot) + if (Database.loaded): + await utils.update_all_guilds() + await inter.edit_original_response( + embed=disnake.Embed(description="All servers updated !", color=disnake.Color.green()) + ) @commands.slash_command( name="yearly-update", @@ -401,32 +402,12 @@ async def server_info( number_registered_user = len( [1 for _, member in enumerate(guild.members) if member in Database.ulb_users.keys()] ) - - n_registered = len(Database.ulb_guilds.get(guild).role.members) - percent = int(n_registered / guild.member_count * 100) - guild_data = Database.ulb_guilds.get(guild) await inter.edit_original_response( embed=disnake.Embed( title="Info du server", - description=f"**Nom :** {guild.name}\n**ID :** `{guild.id}`\n**Role :** @{guild_data.role.name}\n**Role ID :** `{guild_data.role.id}`\n**Rename :** `{'Oui' if guild_data.rename else 'Non'}`\n**Nombre de membre vérifié :** `{n_registered} ({percent}%)`", - color=disnake.Color.blue(), - ) - ) - - @commands.slash_command( - name="stats", - default_member_permissions=disnake.Permissions.all(), - description="Voir les statistiques d'utilisation du bot.", - ) - async def stats(self, inter: disnake.ApplicationCommandInteraction): - await inter.response.defer(ephemeral=True) - - await inter.edit_original_response( - embed=disnake.Embed( - title="Statistique du bot", - description=f"**Servers configurés : **`{len(Database.ulb_guilds)}`\n**Membres vérifiés : **`{len(Database.ulb_users)}`", - color=disnake.Colour.blue(), + description=f"**Nom :** {guild.name}\n**ID :** `{guild.id}`\n**Role :** @{guild_data.role.name}\n**Role ID :** `{guild_data.role.id}`\n**Rename :** `{'Oui' if guild_data.rename else 'Non'}`\n**Nombre de membre vérifié :** `{number_registered_user}`", + color=disnake.Color.green(), ) ) diff --git a/cogs/Ulb.py b/cogs/Ulb.py index 05a9e1c..7e42f46 100644 --- a/cogs/Ulb.py +++ b/cogs/Ulb.py @@ -19,10 +19,11 @@ def __init__(self, bot: Bot): @commands.Cog.listener("on_ready") async def on_ready(self): - Database.load(self.bot) - Registration.setup(self) - logging.info("[Cog:Ulb] Ready !") - await utils.update_all_guilds() + await Database.load(self.bot) + if (Database.loaded): + Registration.setup(self) + logging.info("[Cog:Ulb] Ready !") + await utils.update_all_guilds() async def wait_setup(self, inter: disnake.ApplicationCommandInteraction) -> None: """Async sleep until GoogleSheet is loaded and RegistrationForm is set""" @@ -162,12 +163,9 @@ async def info(self, inter: disnake.ApplicationCommandInteraction): ) return - n_registered = len(guilddata.role.members) - percent = int(n_registered / inter.guild.member_count * 100) - embed = disnake.Embed( title="Info du serveur", - description=f"ULB role : {guilddata.role.mention}\nNombre de membre vérifié : **{n_registered}** *({percent}%)*\nRenommer les membres : **{'oui' if guilddata.rename else 'non'}**", + description=f"ULB role : {guilddata.role.mention}\nRenommer les membres : **{'oui' if guilddata.rename else 'non'}**", color=disnake.Color.green(), )