"""Class and functions for storing and retrieving highscores data.""" import os import json HIGHSCORES_CONFIG_FILE = "highscores_config.json" HIGHSCORES_DATA_FILE = "highscores_data.json" class HighscoresData: """Class for storing and retrieving highscores data.""" def __init__(self) -> None: self._config = open_highscores_config() self._data = open_highscores_data() def add_new_server(self, guild_id: int): """ Creates new skeleton data dict and adds to self for new guild. @param guild_id: guild_id to add. """ # create the dict skeleton = { "highscore_channel_id": -1, "verification_channel_id": -1, "username_length": 12, } config: dict = open_highscores_config() skeleton["tables"] = {} for boss, categories in config["tables"].items(): skeleton["tables"][boss] = {"message_id": 0} boss_categories = {} for category in categories: rank_list = [] boss_categories[category] = rank_list skeleton["tables"][boss]["categories"] = boss_categories self._data[str(guild_id)] = skeleton def get_guild_data(self, guild_id: int) -> dict: """ Gets guild data from the guild id. @param guild_id: guild id to retrieve data for @returns: dict of guild's highscore data """ return self._data[str(guild_id)] def set_guild_data(self, guild_id: int, data: dict) -> None: """ Sets guild data for given guild id, saves data. @param guild_id: guild id to save data for @param data: data to set and save """ self._data[str(guild_id)] = data save_highscores_data(self._data) def open_highscores_config(): """ Opens the highscores config file and returns. @return: dict of highscores config. """ # Load bot config with open(HIGHSCORES_CONFIG_FILE, encoding="utf-8", mode="r") as file: return json.load(file) def open_highscores_data(): """ Opens a highscores_data.json file if one exists, otherwise returns empty dict. @return: dict of highscores data. """ if os.path.exists(HIGHSCORES_DATA_FILE): with open(HIGHSCORES_DATA_FILE, encoding="utf-8", mode="r") as file: data = json.load(file) else: data = {} return data def save_highscores_data(data: dict): """ Saves the highscores data dict into a json file. @param data: dict of highscores data. """ with open(HIGHSCORES_DATA_FILE, encoding="utf-8", mode="w") as file: file.write(json.dumps(data, indent=4))