107 lines
2.9 KiB
Python
107 lines
2.9 KiB
Python
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
|
|
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'
|