0.4 - Befehlsstruktur #37

Merged
edraft merged 10 commits from 0.4 into Alpha 2021-12-31 12:10:05 +01:00
11 changed files with 87 additions and 54 deletions
Showing only changes of commit 4db97248ca - Show all commits

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__))) environment.set_working_directory(os.path.dirname(os.path.realpath(__file__)))
configuration.add_environment_variables('GISMO_') configuration.add_environment_variables('GISMO_')
configuration.add_json_file(f'appsettings.json', optional=False) configuration.add_json_file(f'config/appsettings.json', optional=False)
configuration.add_json_file(f'appsettings.{environment.environment_name}.json', optional=True) configuration.add_json_file(f'config/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.{environment.host_name}.json', optional=True)
configuration.add_configuration('Startup_StartTime', self._start_time) configuration.add_configuration('Startup_StartTime', self._start_time)

View File

@ -19,5 +19,5 @@ class DiscordSettings(ConfigurationModelABC):
try: try:
self._token = settings['Token'] self._token = settings['Token']
except Exception as e: 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()}') 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.bot_service_abc import BotServiceABC
from gismo_core.abc.message_service_abc import MessageServiceABC from gismo_core.abc.message_service_abc import MessageServiceABC
from gismo_core.configuration.server_settings import ServerSettings 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.events.on_ready_abc import OnReadyABC
from modules_core.abc.module_abc import ModuleABC from modules_core.abc.module_abc import ModuleABC
@ -26,11 +27,16 @@ class BootLog(ModuleABC, OnReadyABC):
self._logger = logger self._logger = logger
self._bot = bot self._bot = bot
self._message_service = message_service self._message_service = message_service
ModuleABC.__init__(self) ModuleABC.__init__(
self._priorities[OnReadyABC] = 10 self,
{
OnReadyABC: 10
},
BootLogSettings
)
self._logger.trace(__name__, f'Module {type(self)} loaded') self._logger.trace(__name__, f'Module {type(self)} loaded')
async def on_ready(self): async def on_ready(self):
self._logger.debug(__name__, f'Module {type(self)} started') self._logger.debug(__name__, f'Module {type(self)} started')
try: try:
@ -69,4 +75,4 @@ class BootLog(ModuleABC, OnReadyABC):
server_settings.login_message.format(init_time) 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 abc import ABC, abstractmethod
from typing import Optional
from cpl_core.configuration import ConfigurationModelABC
class ModuleABC(ABC): class ModuleABC(ABC):
@abstractmethod @abstractmethod
def __init__(self): def __init__(self, priorities: dict[type, int], settings_type: type):
self._priorities = {} self._priorities = priorities
self._success = True 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: def get_priority(self, t: type) -> int:
if t not in self._priorities: if t not in self._priorities:
@ -15,7 +26,3 @@ class ModuleABC(ABC):
def stop_propagation(self): def stop_propagation(self):
self._success = False self._success = False
@property
def success(self) -> bool:
return self._success

View File

@ -1,8 +1,10 @@
from abc import ABC, ABCMeta from abc import ABC, ABCMeta
from datetime import datetime from datetime import datetime
import json
from typing import Optional, Sequence, Union from typing import Optional, Sequence, Union
import discord import discord
from cpl_core.configuration import ConfigurationModelABC, ConfigurationABC
from cpl_core.dependency_injection import ServiceProviderABC from cpl_core.dependency_injection import ServiceProviderABC
from cpl_core.environment import ApplicationEnvironmentABC from cpl_core.environment import ApplicationEnvironmentABC
from cpl_core.logging import LoggerABC from cpl_core.logging import LoggerABC
@ -64,8 +66,9 @@ class _MetaCogABC(ABCMeta, commands.CogMeta): pass
class ModuleService(ModuleServiceABC, commands.Cog, metaclass=_MetaCogABC): 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._logger = logger
self._config = config
self._services = services self._services = services
self._env = env self._env = env
self._modules: List[ModuleABC] = List() 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)) module_types = self._modules.where(lambda m: issubclass(m, t))
modules = List(t) modules = List(t)
for module_type in module_types: 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: if module is None:
self._logger.warn(__name__, f'Module {module_type} not found in services!') self._logger.warn(__name__, f'Module {module_type} not found in services!')
break 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) modules.append(module)
return modules.order_by(lambda m: m.get_priority(t)) return modules.order_by(lambda m: m.get_priority(t))
async def _handle_event(self, event: type, *args): 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]) func_name = String.convert_to_snake_case(event.__name__.split('ABC')[0])
for module in modules: for module in modules:
func = getattr(module, func_name) func = getattr(module, func_name)
exit()
await func(*args) await func(*args)
if not module.success: if not module.success:
self._logger.debug(__name__, f'Stopped propagation for {event} from {type(module)}') self._logger.debug(__name__, f'Stopped propagation for {event} from {type(module)}')