Improved bot startup logic

This commit is contained in:
Sven Heidemann 2021-11-16 18:34:41 +01:00
parent 2176037d08
commit d2c233a855
12 changed files with 80 additions and 24 deletions

View File

@ -20,8 +20,6 @@ __version__ = '0.1.0'
from collections import namedtuple
# imports:
import nest_asyncio
nest_asyncio.apply()
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='0', minor='1', micro='0')

View File

@ -5,7 +5,6 @@ from cpl_core.logging import LoggerABC
from gismo_core.abc.bot_service_abc import BotServiceABC
from gismo_core.service.bot_service import BotService
from modules_core.abc.module_service_abc import ModuleServiceABC
class Application(ApplicationABC):
@ -23,5 +22,6 @@ class Application(ApplicationABC):
try:
self._logger.trace(__name__, f'Try to start {BotService}')
await self._bot.start_async()
self._logger.trace(__name__, f'Stopped {BotService}')
except Exception as e:
self._logger.error(__name__, 'Start failed', e)

View File

@ -18,6 +18,14 @@
},
"Bot": {
"Prefix": "!dev-g"
"Prefix": "!dev-g",
"Servers": [
{
"Id": "511824600884051979"
},
{
"Id": "910199451145076828"
}
]
}
}

View File

@ -1,6 +1,6 @@
import asyncio
from cpl_core.application import ApplicationBuilder, ApplicationABC
from cpl_core.application import ApplicationABC, ApplicationBuilder
from gismo.application import Application
from gismo.startup import Startup
@ -14,7 +14,6 @@ async def main():
app: ApplicationABC = await app_builder.build_async()
await app.run_async()
if __name__ == '__main__':
ml = asyncio.get_event_loop()
ml.run_until_complete(main())

View File

@ -6,7 +6,7 @@ from cpl_core.configuration import ConfigurationABC
from cpl_core.dependency_injection import (ServiceCollectionABC,
ServiceProviderABC)
from cpl_core.environment import ApplicationEnvironment
from cpl_core.logging.logger_abc import LoggerABC
from cpl_core.logging import LoggerABC
from gismo_core.abc.bot_service_abc import BotServiceABC
from gismo_core.service.bot_service import BotService

View File

@ -1,7 +1,9 @@
import traceback
from cpl_core.configuration.configuration_model_abc import ConfigurationModelABC
from cpl_core.configuration import ConfigurationModelABC
from cpl_core.console import Console
from cpl_query.extension import List
from gismo_core.configuration.server_settings import ServerSettings
class BotSettings(ConfigurationModelABC):
@ -10,14 +12,25 @@ class BotSettings(ConfigurationModelABC):
ConfigurationModelABC.__init__(self)
self._prefix: str = ''
self._servers: List[ServerSettings] = List()
@property
def prefix(self) -> str:
return self._prefix
@property
def servers(self) -> List[ServerSettings]:
return self._servers
def from_dict(self, settings: dict):
try:
self._prefix = settings['Prefix']
servers = List(ServerSettings)
for s in settings['Servers']:
st = ServerSettings()
st.from_dict(s)
servers.append(st)
self._servers = servers
except Exception as e:
Console.error(f'[ ERROR ] [ {__name__} ]: Reading error in {self.__name__} settings')
Console.error(f'[ ERROR ] [ {__name__} ]: Reading error in settings')
Console.error(f'[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}')

View File

@ -1,6 +1,6 @@
import traceback
from cpl_core.configuration.configuration_model_abc import ConfigurationModelABC
from cpl_core.configuration import ConfigurationModelABC
from cpl_core.console import Console

View File

@ -0,0 +1,23 @@
import traceback
from cpl_core.configuration.configuration_model_abc import ConfigurationModelABC
from cpl_core.console import Console
class ServerSettings(ConfigurationModelABC):
def __init__(self):
ConfigurationModelABC.__init__(self)
self._id: int = ''
@property
def id(self) -> str:
return self._id
def from_dict(self, settings: dict):
try:
self._id = settings['Id']
except Exception as e:
Console.error(f'[ ERROR ] [ {__name__} ]: Reading error in settings')
Console.error(f'[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}')

View File

@ -1,16 +1,18 @@
from cpl_core.configuration import ConfigurationABC
from cpl_core.logging import LoggerABC
from discord.ext import commands
from gismo_core.abc.bot_service_abc import BotServiceABC
from gismo_core.configuration.bot_settings import BotSettings
from gismo_core.configuration.discord_settings import DiscordSettings
from gismo_core.configuration.server_settings import ServerSettings
from modules_core.abc.module_service_abc import ModuleServiceABC
class BotService(BotServiceABC, commands.Bot):
def __init__(self, logger: LoggerABC, modules: ModuleServiceABC, discord_settings: DiscordSettings, bot_settings: BotSettings):
def __init__(self, config: ConfigurationABC, logger: LoggerABC, modules: ModuleServiceABC, discord_settings: DiscordSettings, bot_settings: BotSettings):
# services
self._config = config
self._logger = logger
self._modules = modules
@ -23,12 +25,21 @@ class BotService(BotServiceABC, commands.Bot):
async def start_async(self):
self._logger.trace(__name__, 'Try to connect to discord')
self.run(self._discord_settings.token)
await self.start(self._discord_settings.token)
# continue at on_ready
async def on_ready(self):
self._logger.info(__name__, 'Connected to discord')
await self._modules.start_modules()
self._logger.debug(__name__, 'Try to load discord server configs')
for server in self._bot_settings.servers:
server: ServerSettings = server
self._logger.trace(__name__, f'Try to load config for server: {server.id}')
self._config.add_configuration(f'DSERVER_{server.id}', server)
self._logger.trace(__name__, f'Loaded config for server: {server.id}')
await self._modules.on_ready()
async def stop_async(self):
self._logger.debug(__name__, f'Try to stop {BotService}')
@ -37,4 +48,3 @@ class BotService(BotServiceABC, commands.Bot):
# save data
except Exception as e:
self._logger.error(__name__, 'Stop failed', e)

View File

@ -3,7 +3,7 @@ from datetime import datetime
from cpl_core.configuration import ConfigurationABC
from cpl_core.console import Console
from cpl_core.logging import LoggerABC, LoggingLevelEnum, LoggingSettings
from discord import guild
from gismo_core.abc.bot_service_abc import BotServiceABC
from modules_core.abc.module_abc import ModuleABC
@ -40,4 +40,13 @@ class BootLog(ModuleABC):
if self._logging_st.console.value >= LoggingLevelEnum.INFO.value:
Console.banner(self._bot.user.name)
for g in self._bot.guilds:
g: guild = g
self._logger.debug(__name__, f'Server detected: {g.id}')
server_config = self._config.get_configuration(f'DSERVER_{g.id}')
if server_config is None:
self._logger.error(__name__, f'Config for server {g.id} not found!')
await self._bot.close()
self._logger.trace(__name__, f'Module {type(self)} stopped')

View File

@ -8,4 +8,4 @@ class ModuleServiceABC(ABC):
def __init__(self): pass
@abstractmethod
async def start_modules(self): pass
async def on_ready(self): pass

View File

@ -1,11 +1,7 @@
from os import path
import discord
from cpl_core.dependency_injection import ServiceProviderABC
from cpl_core.environment import ApplicationEnvironmentABC
from cpl_core.logging import LoggerABC
from cpl_query.extension import List
from discord.ext import commands
from modules_core.abc.module_abc import ModuleABC
from modules_core.abc.module_service_abc import ModuleServiceABC
@ -19,8 +15,8 @@ class ModuleService(ModuleServiceABC):
self._modules: List[ModuleABC] = List()
self._modules.extend(ModuleABC.__subclasses__())
async def start_modules(self):
self._logger.trace(__name__, 'Start loading modules')
async def on_ready(self):
self._logger.debug(__name__, 'Start on_ready modules')
modules = self._modules.where(lambda m: hasattr(m, 'on_ready') and callable(m.on_ready))
for module_type in modules:
module = self._services.get_service(module_type)