Implement a better config system
This commit is contained in:
92
lib/config.py
Normal file
92
lib/config.py
Normal file
@@ -0,0 +1,92 @@
|
||||
import json
|
||||
from typing import Optional
|
||||
|
||||
CONFIG = 'config.json'
|
||||
config: dict = {
|
||||
'inf19x-insiders-enable': False,
|
||||
'loeh-cooldown': 20,
|
||||
'loeh-enable': False,
|
||||
'loeh-timeout': 10,
|
||||
'prefix': 'och!',
|
||||
}
|
||||
config_meta: dict = {
|
||||
'inf19x-insiders-enable': (
|
||||
True,
|
||||
'Enables university insider jokes of INF19X'
|
||||
),
|
||||
'loeh-cooldown': (
|
||||
True,
|
||||
'Number of seconds between timeouts'
|
||||
),
|
||||
'loeh-enable': (
|
||||
True,
|
||||
'Enable time-outing Löh'
|
||||
),
|
||||
'loeh-timeout': (
|
||||
True,
|
||||
'The timeout for Löh in seconds'
|
||||
),
|
||||
'prefix': (
|
||||
False,
|
||||
'Sets the prefix for this bot'
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def config_load() -> dict:
|
||||
try:
|
||||
config_file = open(CONFIG, 'r')
|
||||
config.update(json.load(config_file))
|
||||
except (json.JSONDecodeError, FileNotFoundError):
|
||||
pass
|
||||
return config
|
||||
|
||||
|
||||
def config_save():
|
||||
with open(CONFIG, 'w') as config_file:
|
||||
json.dump(config, config_file)
|
||||
|
||||
|
||||
def config_get(key: str, guild: Optional[int] = None):
|
||||
guild = str(guild)
|
||||
if guild in config:
|
||||
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(config[str(guild)], key, value, type(config[key]))
|
||||
else:
|
||||
return 'This config can only be changed globally by the bot owner!'
|
||||
|
||||
|
||||
def config_get_descriptions() -> iter:
|
||||
return map(lambda entry: (entry[0], entry[1]), config_meta.items())
|
||||
|
||||
|
||||
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
|
||||
if type(value) == str:
|
||||
if cfg_type == int:
|
||||
scope[key] = int(value)
|
||||
success = True
|
||||
elif cfg_type == float:
|
||||
scope[key] = float(value)
|
||||
success = True
|
||||
except (TypeError, ValueError):
|
||||
success = False
|
||||
if success:
|
||||
config_save()
|
||||
return 'Successfully updated config for `' + key + '`'
|
||||
else:
|
||||
return 'Unable to determine type of given argument'
|
||||
Reference in New Issue
Block a user