From 50932750537b7b53fbec6ed076dbdd07b2159a67 Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Sat, 16 Jul 2022 19:47:04 +0200 Subject: [PATCH] Added configuration --- .gitignore | 1 - src/bot/application.py | 38 +++++++++++++++++--- src/bot/bot | 24 +++++++++++++ src/bot/bot.json | 4 +-- src/bot/config/appsettings.development.json | 33 +++++++++++++++++ src/bot/config/appsettings.edrafts-lapi.json | 31 ++++++++++++++++ src/bot/config/appsettings.example.json | 18 ++++++++++ src/bot/{ => config}/appsettings.json | 3 +- src/bot/config/appsettings.production.json | 24 +++++++++++++ src/bot/config/appsettings.staging.json | 33 +++++++++++++++++ src/bot/main.py | 35 ++++++++++++++---- src/bot/startup.py | 24 +++++++++++++ src/bot/translation/de.json | 8 +++++ 13 files changed, 260 insertions(+), 16 deletions(-) create mode 100644 src/bot/bot create mode 100644 src/bot/config/appsettings.development.json create mode 100644 src/bot/config/appsettings.edrafts-lapi.json create mode 100644 src/bot/config/appsettings.example.json rename src/bot/{ => config}/appsettings.json (99%) create mode 100644 src/bot/config/appsettings.production.json create mode 100644 src/bot/config/appsettings.staging.json create mode 100644 src/bot/translation/de.json diff --git a/.gitignore b/.gitignore index 23fa008e..3e0d7a3f 100644 --- a/.gitignore +++ b/.gitignore @@ -140,7 +140,6 @@ cython_debug/ # custom vs code PythonImportHelper-v2-Completion.json -appsettings.*.json # idea .idea/ \ No newline at end of file diff --git a/src/bot/application.py b/src/bot/application.py index b2df0250..7ae51925 100644 --- a/src/bot/application.py +++ b/src/bot/application.py @@ -1,16 +1,44 @@ -from cpl_core.application import ApplicationABC from cpl_core.configuration import ConfigurationABC from cpl_core.console import Console from cpl_core.dependency_injection import ServiceProviderABC +from cpl_core.logging import LoggerABC +from cpl_discord.application import DiscordBotApplicationABC +from cpl_discord.configuration import DiscordBotSettings +from cpl_discord.service import DiscordBotServiceABC, DiscordBotService +from cpl_translation import TranslatePipe, TranslationServiceABC, TranslationSettings -class Application(ApplicationABC): +class Application(DiscordBotApplicationABC): def __init__(self, config: ConfigurationABC, services: ServiceProviderABC): - ApplicationABC.__init__(self, config, services) + DiscordBotApplicationABC.__init__(self, config, services) + + # cpl-core + self._logger: LoggerABC = services.get_service(LoggerABC) + # cpl-discord + self._bot: DiscordBotServiceABC = services.get_service(DiscordBotServiceABC) + self._bot_settings: DiscordBotSettings = config.get_configuration(DiscordBotSettings) + # cpl-translation + self._translation: TranslationServiceABC = services.get_service(TranslationServiceABC) + self._translate: TranslatePipe = services.get_service(TranslatePipe) async def configure(self): - pass + self._translation.load_by_settings(self._configuration.get_configuration(TranslationSettings)) async def main(self): - Console.write_line('Hello World') + try: + self._logger.debug(__name__, f'Starting...\n') + self._logger.trace(__name__, f'Try to start {DiscordBotService.__name__}') + await self._bot.start_async() + except Exception as e: + self._logger.error(__name__, 'Start failed', e) + + async def stop_async(self): + try: + self._logger.trace(__name__, f'Try to stop {DiscordBotService.__name__}') + await self._bot.close() + self._logger.trace(__name__, f'Stopped {DiscordBotService.__name__}') + except Exception as e: + self._logger.error(__name__, 'stop failed', e) + + Console.write_line() diff --git a/src/bot/bot b/src/bot/bot new file mode 100644 index 00000000..ca8225c4 --- /dev/null +++ b/src/bot/bot @@ -0,0 +1,24 @@ +#!/bin/bash + +path="`dirname \"$0\"`" # relative +path="`( cd \"$path\" && pwd)`" # absolutized and normalized + +cd "$path/../" + +if [[ $1 == "-dev" ]]; then + export KDB_ENVIRONMENT=development + export KDB_NAME=KDB-dev +elif [[ $1 == "-stage" ]]; then + export KDB_ENVIRONMENT=staging + export KDB_NAME=KDB-test +elif [[ $1 == "-prod" ]]; then + export KDB_ENVIRONMENT=production + export KDB_NAME=KDB +else + export KDB_ENVIRONMENT=production + export KDB_NAME=KDB-prod +fi + +export PYTHONPATH=./:$PYTHONPATH + +python3.10 bot/main.py diff --git a/src/bot/bot.json b/src/bot/bot.json index 24b55e83..8f360c5b 100644 --- a/src/bot/bot.json +++ b/src/bot/bot.json @@ -17,9 +17,9 @@ "LicenseDescription": "MIT, see LICENSE for more details.", "Dependencies": [ "cpl-core>=2022.7.0.post1", - "cpl-translation==2022.7.0", + "cpl-translation==2022.7.0.post1", "cpl-query==2022.7.0", - "cpl-discord==2022.7.0" + "cpl-discord==2022.7.0.post1" ], "DevDependencies": [ "cpl-cli>=2022.7.0.post1" diff --git a/src/bot/config/appsettings.development.json b/src/bot/config/appsettings.development.json new file mode 100644 index 00000000..234825a9 --- /dev/null +++ b/src/bot/config/appsettings.development.json @@ -0,0 +1,33 @@ +{ + "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_dev.log", + "ConsoleLogLevel": "DEBUG", + "FileLogLevel": "DEBUG" + }, + "Translation": { + "DefaultLanguage": "de", + "Languages": [ + "de" + ] + }, + "DiscordBot": { + "Token": "OTA5ODc4NDcyNzExNzU3ODQ1.YZKsXA.8p-g1c37EBZzYYW09Fvr7egQzhE", + "Prefix": "!kd " + }, + "Bot": { + "Servers": [ + { + "Id": "910199451145076828", + "MessageDeleteTimer": 2, + "BotHasNoPermissionMessage": "Ich habe keine Berechtigungen :(" + } + ] + } +} \ No newline at end of file diff --git a/src/bot/config/appsettings.edrafts-lapi.json b/src/bot/config/appsettings.edrafts-lapi.json new file mode 100644 index 00000000..a1071c7e --- /dev/null +++ b/src/bot/config/appsettings.edrafts-lapi.json @@ -0,0 +1,31 @@ +{ + "LoggingSettings": { + "Path": "logs/", + "Filename": "log_dev.log", + "ConsoleLogLevel": "TRACE", + "FileLogLevel": "TRACE" + }, + "DatabaseSettings": { + "Host": "localhost", + "User": "sh_gismo", + "Password": "c2hfZ2lzbW8=", + "Database": "sh_gismo_dev", + "Charset": "utf8mb4", + "UseUnicode": "true", + "Buffered": "true", + "AuthPlugin": "mysql_native_password" + }, + "DiscordBot": { + "Token": "OTExNTc0NDQyMzMxNzM0MDI2.YZjX2w.k7N2qTkvkDD7j9bT4Nrdl4qBHlI", + "Prefix": "!kde " + }, + "Bot": { + "Servers": [ + { + "Id": "910199451145076828", + "MessageDeleteTimer": 2, + "BotHasNoPermissionMessage": "Ich habe keine Berechtigungen :(" + } + ] + } +} \ No newline at end of file diff --git a/src/bot/config/appsettings.example.json b/src/bot/config/appsettings.example.json new file mode 100644 index 00000000..4242ee40 --- /dev/null +++ b/src/bot/config/appsettings.example.json @@ -0,0 +1,18 @@ +{ + "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" + }, + "DiscordBot": { + "Token": "", + "Prefix": "! " + } +} \ No newline at end of file diff --git a/src/bot/appsettings.json b/src/bot/config/appsettings.json similarity index 99% rename from src/bot/appsettings.json rename to src/bot/config/appsettings.json index 629e6ebd..a02074ce 100644 --- a/src/bot/appsettings.json +++ b/src/bot/config/appsettings.json @@ -5,11 +5,10 @@ "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" } -} +} \ No newline at end of file diff --git a/src/bot/config/appsettings.production.json b/src/bot/config/appsettings.production.json new file mode 100644 index 00000000..a37c918e --- /dev/null +++ b/src/bot/config/appsettings.production.json @@ -0,0 +1,24 @@ +{ + "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" + }, + "Translation": { + "DefaultLanguage": "de", + "Languages": [ + "de" + ] + }, + "Discord": { + "Token": "OTA5ODc3NDg3MjEzODk5ODQ3.YZKrcQ.JLfdP_X0xtpfXKiBqP49HQe6z9Y", + "Prefix": "!kb " + } +} \ No newline at end of file diff --git a/src/bot/config/appsettings.staging.json b/src/bot/config/appsettings.staging.json new file mode 100644 index 00000000..34b75ed5 --- /dev/null +++ b/src/bot/config/appsettings.staging.json @@ -0,0 +1,33 @@ +{ + "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_staging_$start_time.log", + "ConsoleLogLevel": "INFO", + "FileLogLevel": "DEBUG" + }, + "Translation": { + "DefaultLanguage": "de", + "Languages": [ + "de" + ] + }, + "Discord": { + "Token": "OTEwMjAxNjA1NDkwNjEwMjA3.YZPZTQ.lUj2Bs5pQAv4AJ_tb_mHMTpIRls" + }, + "Bot": { + "Prefix": "!kt ", + "Servers": [ + { + "Id": "910199451145076828", + "MessageDeleteTimer": 2, + "BotHasNoPermissionMessage": "Ich habe keine Berechtigungen :(" + } + ] + } +} \ No newline at end of file diff --git a/src/bot/main.py b/src/bot/main.py index ff378e28..e797d225 100644 --- a/src/bot/main.py +++ b/src/bot/main.py @@ -1,4 +1,5 @@ import asyncio +from typing import Optional from cpl_core.application import ApplicationBuilder @@ -6,12 +7,34 @@ from bot.application import Application from bot.startup import Startup -async def main(): - app_builder = ApplicationBuilder(Application) - app_builder.use_startup(Startup) - app: Application = await app_builder.build_async() - await app.run_async() +class Main: + + def __init__(self): + self._bot: Optional[Application] = None + + async def main(self): + app_builder = ApplicationBuilder(Application) + app_builder.use_startup(Startup) + app: Application = await app_builder.build_async() + await app.run_async() + + async def stop(self): + await self._bot.stop_async() if __name__ == '__main__': - asyncio.run(main()) + main = Main() + try: + asyncio.run(main.main()) + except KeyboardInterrupt: + asyncio.run(main.stop()) + +# (( +# ( `) +# ; / , +# / \/ +# / | +# / ~/ +# / ) ) ~ edraft +# ___// | / +# `--' \_~-, diff --git a/src/bot/startup.py b/src/bot/startup.py index 359c03d2..7b4a3da9 100644 --- a/src/bot/startup.py +++ b/src/bot/startup.py @@ -1,16 +1,40 @@ +import os +from datetime import datetime +from typing import Optional + from cpl_core.application import StartupABC from cpl_core.configuration import ConfigurationABC from cpl_core.dependency_injection import ServiceProviderABC, ServiceCollectionABC from cpl_core.environment import ApplicationEnvironment +from cpl_discord import get_discord_collection class Startup(StartupABC): def __init__(self): StartupABC.__init__(self) + self._start_time = datetime.now() + + self._config: Optional[ConfigurationABC] = None def configure_configuration(self, configuration: ConfigurationABC, environment: ApplicationEnvironment) -> ConfigurationABC: + environment.set_working_directory(os.path.dirname(os.path.realpath(__file__))) + configuration.add_environment_variables('KDB_') + configuration.add_environment_variables('DISCORD_') + + 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', str(self._start_time)) + + self._config = configuration return configuration def configure_services(self, services: ServiceCollectionABC, environment: ApplicationEnvironment) -> ServiceProviderABC: + services.add_logging() + services.add_translation() + services.add_discord() + discord_collection = get_discord_collection(services) + return services.build_service_provider() diff --git a/src/bot/translation/de.json b/src/bot/translation/de.json new file mode 100644 index 00000000..ee0fe357 --- /dev/null +++ b/src/bot/translation/de.json @@ -0,0 +1,8 @@ +{ + "common": { + "hello-world": "Hallo Welt" + }, + "commands": { + + } +} \ No newline at end of file