Improved config loading

This commit is contained in:
Sven Heidemann 2021-12-27 19:32:12 +01:00
parent 40419c9a0b
commit 4db97248ca
11 changed files with 87 additions and 54 deletions

View File

@ -1,36 +0,0 @@
{
"TimeFormatSettings": {
"DateFormat": "%Y-%m-%d",
"TimeFormat": "%H:%M:%S",
"DateTimeFormat": "%Y-%m-%d %H:%M:%S.%f",
"DateTimeLogFormat": "%Y-%m-%d_%H-%M-%S"
},
"LoggingSettings": {
"Path": "logs/",
"Filename": "log_$start_time.log",
"ConsoleLogLevel": "ERROR",
"FileLogLevel": "WARN"
},
"Discord": {
"Token": ""
},
"Bot": {
"Prefix": "!g",
"Servers": [
{
"Id": "",
"LoginMessageChannelId": "",
"LoginMessage": "",
"MessageDeleteTimer": 0,
"WelcomeMessage": "",
"GoodbyeMessage": "",
"MaxVoiceStateHours": 0,
"XpPerMessage": 0,
"XpPerOntimeHour": 0,
"AFKChannelIds": [],
"AdminRoleIds": [],
"ModeratorRoleIds": []
}
]
}
}

View File

@ -0,0 +1,2 @@
{
}

View File

@ -0,0 +1,10 @@
{
"910199451145076828": {
"LoginMessageChannelId": "910199452915093588",
"LoginMessage": "Ich bin on the line :D\nDer Start hat {} Sekunden gedauert"
},
"511824600884051979": {
"LoginMessageChannelId": "521260270757347328",
"LoginMessage": "Ich bin on the line :D\nDer Start hat {} Sekunden gedauert"
}
}

View File

@ -0,0 +1,2 @@
{
}

View File

@ -54,9 +54,9 @@ class Startup(StartupABC):
environment.set_working_directory(os.path.dirname(os.path.realpath(__file__)))
configuration.add_environment_variables('GISMO_')
configuration.add_json_file(f'appsettings.json', optional=False)
configuration.add_json_file(f'appsettings.{environment.environment_name}.json', optional=True)
configuration.add_json_file(f'appsettings.{environment.host_name}.json', optional=True)
configuration.add_json_file(f'config/appsettings.json', optional=False)
configuration.add_json_file(f'config/appsettings.{environment.environment_name}.json', optional=True)
configuration.add_json_file(f'config/appsettings.{environment.host_name}.json', optional=True)
configuration.add_configuration('Startup_StartTime', self._start_time)

View File

@ -19,5 +19,5 @@ class DiscordSettings(ConfigurationModelABC):
try:
self._token = settings['Token']
except Exception as e:
Console.error(f'[ ERROR ] [ {__name__} ]: Reading error in {self.__name__} settings')
Console.error(f'[ ERROR ] [ {__name__} ]: Reading error in {__name__} settings')
Console.error(f'[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}')

View File

@ -8,6 +8,7 @@ from discord import guild
from gismo_core.abc.bot_service_abc import BotServiceABC
from gismo_core.abc.message_service_abc import MessageServiceABC
from gismo_core.configuration.server_settings import ServerSettings
from modules.boot_log.boot_log_settings import BootLogSettings
from modules_core.abc.events.on_ready_abc import OnReadyABC
from modules_core.abc.module_abc import ModuleABC
@ -26,11 +27,16 @@ class BootLog(ModuleABC, OnReadyABC):
self._logger = logger
self._bot = bot
self._message_service = message_service
ModuleABC.__init__(self)
self._priorities[OnReadyABC] = 10
ModuleABC.__init__(
self,
{
OnReadyABC: 10
},
BootLogSettings
)
self._logger.trace(__name__, f'Module {type(self)} loaded')
async def on_ready(self):
self._logger.debug(__name__, f'Module {type(self)} started')
try:
@ -69,4 +75,4 @@ class BootLog(ModuleABC, OnReadyABC):
server_settings.login_message.format(init_time)
)
self._logger.trace(__name__, f'Module {type(self)} stopped')
self._logger.trace(__name__, f'Module {type(self)} stopped')

View File

@ -0,0 +1,29 @@
import traceback
from cpl_core.configuration.configuration_model_abc import ConfigurationModelABC
from cpl_core.console import Console
class BootLogSettings(ConfigurationModelABC):
def __init__(self):
ConfigurationModelABC.__init__(self)
self._login_message_channel_id: int = 0
self._login_message: str = ''
@property
def login_message_channel_id(self) -> int:
return self._login_message_channel_id
@property
def login_message(self) -> str:
return self._login_message
def from_dict(self, settings: dict):
try:
self._login_message_channel_id = int(settings['LoginMessageChannelId'])
self._login_message = settings['LoginMessage']
except Exception as e:
Console.error(f'[ ERROR ] [ {__name__} ]: Reading error in {__name__} settings')
Console.error(f'[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}')

View File

@ -1,12 +1,23 @@
from abc import ABC, abstractmethod
from typing import Optional
from cpl_core.configuration import ConfigurationModelABC
class ModuleABC(ABC):
@abstractmethod
def __init__(self):
self._priorities = {}
def __init__(self, priorities: dict[type, int], settings_type: type):
self._priorities = priorities
self._success = True
self._settings_type = settings_type
@property
def success(self) -> bool:
return self._success
@property
def settings_type(self) -> type:
return self._settings_type
def get_priority(self, t: type) -> int:
if t not in self._priorities:
@ -15,7 +26,3 @@ class ModuleABC(ABC):
def stop_propagation(self):
self._success = False
@property
def success(self) -> bool:
return self._success

View File

@ -1,8 +1,10 @@
from abc import ABC, ABCMeta
from datetime import datetime
import json
from typing import Optional, Sequence, Union
import discord
from cpl_core.configuration import ConfigurationModelABC, ConfigurationABC
from cpl_core.dependency_injection import ServiceProviderABC
from cpl_core.environment import ApplicationEnvironmentABC
from cpl_core.logging import LoggerABC
@ -64,8 +66,9 @@ class _MetaCogABC(ABCMeta, commands.CogMeta): pass
class ModuleService(ModuleServiceABC, commands.Cog, metaclass=_MetaCogABC):
def __init__(self, logger: LoggerABC, services: ServiceProviderABC, env: ApplicationEnvironmentABC):
def __init__(self, logger: LoggerABC, config: ConfigurationABC, services: ServiceProviderABC, env: ApplicationEnvironmentABC):
self._logger = logger
self._config = config
self._services = services
self._env = env
self._modules: List[ModuleABC] = List()
@ -75,12 +78,21 @@ class ModuleService(ModuleServiceABC, commands.Cog, metaclass=_MetaCogABC):
module_types = self._modules.where(lambda m: issubclass(m, t))
modules = List(t)
for module_type in module_types:
module = self._services.get_service(module_type)
module: ModuleABC = self._services.get_service(module_type)
if module is None:
self._logger.warn(__name__, f'Module {module_type} not found in services!')
break
with open(f'config/{String.convert_to_snake_case(type(module).__name__).lower()}.json', encoding='utf-8') as cfg:
json_cfg = json.load(cfg)
for id in json_cfg:
settings: ConfigurationModelABC = module.settings_type()
settings.from_dict(json_cfg[id])
self._config.add_configuration(f'{type(module).__name__}_{id}', settings)
self._logger.debug(__name__, f'Added config: {type(module).__name__}_{id}')
modules.append(module)
return modules.order_by(lambda m: m.get_priority(t))
async def _handle_event(self, event: type, *args):
@ -94,6 +106,7 @@ class ModuleService(ModuleServiceABC, commands.Cog, metaclass=_MetaCogABC):
func_name = String.convert_to_snake_case(event.__name__.split('ABC')[0])
for module in modules:
func = getattr(module, func_name)
exit()
await func(*args)
if not module.success:
self._logger.debug(__name__, f'Stopped propagation for {event} from {type(module)}')