import json import os from typing import Optional CONFIG = 'data/config.json' config: dict = { 'inf19x-insiders-enable': False, 'loeh-enable': False, 'och-timeout': 10, 'och-cooldown': 20, 'och-anyone-enable': False, 'prefix': 'och!', } config_meta: dict = { 'inf19x-insiders-enable': ( True, 'Enables university insider jokes of INF19X' ), 'loeh-enable': ( True, 'Enable time-outing Löh' ), 'och-timeout': ( True, 'The timeout for all och actions in seconds' ), 'och-cooldown': ( True, 'Number of seconds between timeouts' ), 'och-anyone-enable': ( True, 'Enable och-ing anyone' ), 'prefix': ( False, 'Sets the prefix for this bot' ), } def _make_dirs(): os.makedirs(os.path.dirname(CONFIG), exist_ok=True) def config_load() -> dict: try: _make_dirs() config_file = open(CONFIG, 'r') config.update(json.load(config_file)) except (json.JSONDecodeError, FileNotFoundError): pass return config def config_save(): _make_dirs() with open(CONFIG, 'w') as config_file: json.dump(config, config_file) def config_get(key: str, guild: Optional[int] = None): if guild is None: return config[key] guild = _get_guild_config(guild) if key in guild: return guild[key] return config[key] def config_set(key: str, value, guild: Optional[int] = None) -> str: if guild is None: return _config_set_in_scope(config, key, value, type(config[key])) else: if config_meta[key][0]: return _config_set_in_scope(_get_guild_config(guild), key, value, type(config[key])) else: return 'This config can only be changed globally by the bot owner!' def config_set_raw(key: str, value, guild: Optional[int] = None): if guild is None: config[key] = value else: _get_guild_config(guild)[key] = value config_save() def config_get_descriptions() -> iter: return map(lambda entry: (entry[0], entry[1]), config_meta.items()) def _get_guild_config(guild: int) -> dict: config.setdefault('guilds', {}) config['guilds'].setdefault(str(guild), {}) return config['guilds'][str(guild)] def _config_set_in_scope(scope: dict, key: str, value, cfg_type: type) -> str: success = False try: if type(value) == cfg_type: scope[key] = value success = True elif type(value) == str: if cfg_type == int: scope[key] = int(value) success = True elif cfg_type == float: scope[key] = float(value) success = True elif cfg_type == bool: value = value.lower() if value in ('true', '1', 'yes', 'y', 'positive', 'enable', 'en'): value = True elif value in ('false', '0', 'no', 'n', 'negative', 'disable', 'dis'): value = False else: return 'Unable to convert given value to a boolean!' scope[key] = value success = True else: return 'Unknown config type: ' + str(cfg_type) else: return 'Unknown given value type: ' + str(type(value)) except (TypeError, ValueError): success = False if success: config_save() return 'Successfully updated config for `' + key + '`' else: return 'Unable to determine type of given argument'