Skip to content

Commit

Permalink
added check and error msg for database loading
Browse files Browse the repository at this point in the history
  • Loading branch information
OscarVsp committed Dec 5, 2023
1 parent 14e3413 commit a992859
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 61 deletions.
56 changes: 30 additions & 26 deletions classes/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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...")

Expand Down
35 changes: 8 additions & 27 deletions cogs/Admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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(),
)
)

Expand Down
14 changes: 6 additions & 8 deletions cogs/Ulb.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"""
Expand Down Expand Up @@ -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(),
)

Expand Down

0 comments on commit a992859

Please sign in to comment.