2 Commits

Author SHA1 Message Date
59f1183a50 [WIP] improved data loading #127 2023-02-18 19:30:10 +01:00
527d28ae39 Load config from db #127 2023-02-18 18:28:59 +01:00
363 changed files with 12480 additions and 13875 deletions

View File

@@ -10,11 +10,10 @@
"auto-role": "src/modules/auto_role/auto-role.json", "auto-role": "src/modules/auto_role/auto-role.json",
"base": "src/modules/base/base.json", "base": "src/modules/base/base.json",
"boot-log": "src/modules/boot_log/boot-log.json", "boot-log": "src/modules/boot_log/boot-log.json",
"database": "src/modules/database/database.json",
"level": "src/modules/level/level.json", "level": "src/modules/level/level.json",
"permission": "src/modules/permission/permission.json", "permission": "src/modules/permission/permission.json",
"stats": "src/modules/stats/stats.json",
"technician": "src/modules/technician/technician.json", "technician": "src/modules/technician/technician.json",
"checks": "tools/checks/checks.json",
"get-version": "tools/get_version/get-version.json", "get-version": "tools/get_version/get-version.json",
"post-build": "tools/post_build/post-build.json", "post-build": "tools/post_build/post-build.json",
"set-version": "tools/set_version/set-version.json" "set-version": "tools/set_version/set-version.json"

View File

@@ -15,7 +15,4 @@ RUN apk add nano
RUN pip install -r requirements.txt --extra-index-url https://pip.sh-edraft.de RUN pip install -r requirements.txt --extra-index-url https://pip.sh-edraft.de
RUN pip install flask[async] RUN pip install flask[async]
# RUN pip install dnspython==2.2.1 # https://stackoverflow.com/questions/75137717/eventlet-dns-python-attribute-error-module-dns-rdtypes-has-no-attribute-any
# ^ probably fixed py package updates
CMD [ "bash", "/app/bot/bot"] CMD [ "bash", "/app/bot/bot"]

View File

@@ -15,7 +15,7 @@ __title__ = "bot"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -52,7 +52,7 @@ class Application(DiscordBotApplicationABC):
self._api.join() self._api.join()
return return
self._logger.info(__name__, f"Try to start {DiscordBotService.__name__}") self._logger.trace(__name__, f"Try to start {DiscordBotService.__name__}")
await self._bot.start_async() await self._bot.start_async()
await self._bot.stop_async() await self._bot.stop_async()
except Exception as e: except Exception as e:
@@ -64,9 +64,9 @@ class Application(DiscordBotApplicationABC):
self._is_stopping = True self._is_stopping = True
try: try:
self._logger.info(__name__, f"Try to stop {DiscordBotService.__name__}") self._logger.trace(__name__, f"Try to stop {DiscordBotService.__name__}")
await self._bot.close() await self._bot.close()
self._logger.info(__name__, f"Stopped {DiscordBotService.__name__}") self._logger.trace(__name__, f"Stopped {DiscordBotService.__name__}")
except Exception as e: except Exception as e:
self._logger.error(__name__, "stop failed", e) self._logger.error(__name__, "stop failed", e)

View File

@@ -2,9 +2,9 @@
"ProjectSettings": { "ProjectSettings": {
"Name": "bot", "Name": "bot",
"Version": { "Version": {
"Major": "1", "Major": "0",
"Minor": "0", "Minor": "3",
"Micro": "5" "Micro": "dev127"
}, },
"Author": "Sven Heidemann", "Author": "Sven Heidemann",
"AuthorEmail": "sven.heidemann@sh-edraft.de", "AuthorEmail": "sven.heidemann@sh-edraft.de",
@@ -18,8 +18,7 @@
"Dependencies": [ "Dependencies": [
"cpl-core==2022.12.1.post3", "cpl-core==2022.12.1.post3",
"cpl-translation==2022.12.1", "cpl-translation==2022.12.1",
"cpl-query==2022.12.2.post2", "cpl-query==2022.12.2.post1",
"cpl-discord==2022.12.2.post1",
"Flask==2.2.2", "Flask==2.2.2",
"Flask-Classful==0.14.2", "Flask-Classful==0.14.2",
"Flask-Cors==3.0.10", "Flask-Cors==3.0.10",
@@ -29,7 +28,8 @@
"eventlet==0.33.3", "eventlet==0.33.3",
"requests-oauthlib==1.3.1", "requests-oauthlib==1.3.1",
"icmplib==3.0.3", "icmplib==3.0.3",
"ariadne==0.17.1" "ariadne==0.17.1",
"cpl-discord==2022.12.2"
], ],
"DevDependencies": [ "DevDependencies": [
"cpl-cli==2022.12.1.post3", "cpl-cli==2022.12.1.post3",
@@ -61,9 +61,9 @@
"../modules/auto_role/auto-role.json", "../modules/auto_role/auto-role.json",
"../modules/base/base.json", "../modules/base/base.json",
"../modules/boot_log/boot-log.json", "../modules/boot_log/boot-log.json",
"../modules/database/database.json",
"../modules/level/level.json", "../modules/level/level.json",
"../modules/permission/permission.json", "../modules/permission/permission.json",
"../modules/stats/stats.json",
"../modules/technician/technician.json" "../modules/technician/technician.json"
] ]
} }

View File

@@ -15,7 +15,7 @@ __title__ = "bot.extension"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -3,7 +3,7 @@ from cpl_core.configuration import ConfigurationABC
from cpl_core.dependency_injection import ServiceProviderABC from cpl_core.dependency_injection import ServiceProviderABC
from cpl_discord.service import DiscordBotServiceABC from cpl_discord.service import DiscordBotServiceABC
from bot_core.configuration.bot_settings import BotSettings from bot_core.configuration.bot_startup_settings import BotStartupSettings
class InitBotExtension(ApplicationExtensionABC): class InitBotExtension(ApplicationExtensionABC):
@@ -11,6 +11,6 @@ class InitBotExtension(ApplicationExtensionABC):
ApplicationExtensionABC.__init__(self) ApplicationExtensionABC.__init__(self)
async def run(self, config: ConfigurationABC, services: ServiceProviderABC): async def run(self, config: ConfigurationABC, services: ServiceProviderABC):
settings = config.get_configuration(BotSettings) settings: BotStartupSettings = config.get_configuration(BotStartupSettings)
bot: DiscordBotServiceABC = services.get_service(DiscordBotServiceABC, max_messages=settings.cache_max_messages) bot: DiscordBotServiceABC = services.get_service(DiscordBotServiceABC, max_messages=settings.cache_max_messages)

View File

@@ -14,8 +14,8 @@ from bot.startup_module_extension import StartupModuleExtension
from bot.startup_settings_extension import StartupSettingsExtension from bot.startup_settings_extension import StartupSettingsExtension
from bot_api.app_api_extension import AppApiExtension from bot_api.app_api_extension import AppApiExtension
from bot_core.core_extension.core_extension import CoreExtension from bot_core.core_extension.core_extension import CoreExtension
from bot_data.data_extension.database_extension import DatabaseExtension
from modules.boot_log.boot_log_extension import BootLogExtension from modules.boot_log.boot_log_extension import BootLogExtension
from modules.database.database_extension import DatabaseExtension
class Program: class Program:
@@ -39,7 +39,6 @@ class Program:
) )
self.app: Application = await app_builder.build_async() self.app: Application = await app_builder.build_async()
await self.app.run_async() await self.app.run_async()
Console.write_line(f"[ INFO ] [ {__name__} ]: Finished app.run_async")
async def stop(self): async def stop(self):
if self.app is None: if self.app is None:

View File

@@ -8,9 +8,9 @@ from bot_graphql.graphql_module import GraphQLModule
from modules.auto_role.auto_role_module import AutoRoleModule from modules.auto_role.auto_role_module import AutoRoleModule
from modules.base.base_module import BaseModule from modules.base.base_module import BaseModule
from modules.boot_log.boot_log_module import BootLogModule from modules.boot_log.boot_log_module import BootLogModule
from modules.database.database_module import DatabaseModule
from modules.level.level_module import LevelModule from modules.level.level_module import LevelModule
from modules.permission.permission_module import PermissionModule from modules.permission.permission_module import PermissionModule
from modules.stats.stats_module import StatsModule
from modules.technician.technician_module import TechnicianModule from modules.technician.technician_module import TechnicianModule
@@ -25,11 +25,11 @@ class ModuleList:
DataModule, DataModule,
GraphQLModule, GraphQLModule,
PermissionModule, PermissionModule,
LevelModule,
DatabaseModule,
AutoRoleModule, AutoRoleModule,
BaseModule, BaseModule,
LevelModule,
ApiModule, ApiModule,
StatsModule,
TechnicianModule, TechnicianModule,
# has to be last! # has to be last!
BootLogModule, BootLogModule,

View File

@@ -8,16 +8,14 @@ from bot_data.migration.api_key_migration import ApiKeyMigration
from bot_data.migration.api_migration import ApiMigration from bot_data.migration.api_migration import ApiMigration
from bot_data.migration.auto_role_fix1_migration import AutoRoleFix1Migration from bot_data.migration.auto_role_fix1_migration import AutoRoleFix1Migration
from bot_data.migration.auto_role_migration import AutoRoleMigration from bot_data.migration.auto_role_migration import AutoRoleMigration
from bot_data.migration.db_history_migration import DBHistoryMigration from bot_data.migration.config_migration import ConfigMigration
from bot_data.migration.initial_migration import InitialMigration from bot_data.migration.initial_migration import InitialMigration
from bot_data.migration.level_migration import LevelMigration from bot_data.migration.level_migration import LevelMigration
from bot_data.migration.remove_stats_migration import RemoveStatsMigration
from bot_data.migration.stats_migration import StatsMigration from bot_data.migration.stats_migration import StatsMigration
from bot_data.migration.user_joined_game_server_migration import UserJoinedGameServerMigration from bot_data.migration.user_joined_game_server_migration import UserJoinedGameServerMigration
from bot_data.migration.user_message_count_per_hour_migration import ( from bot_data.migration.user_message_count_per_hour_migration import (
UserMessageCountPerHourMigration, UserMessageCountPerHourMigration,
) )
from bot_data.migration.user_warning_migration import UserWarningMigration
from bot_data.service.migration_service import MigrationService from bot_data.service.migration_service import MigrationService
@@ -39,6 +37,4 @@ class StartupMigrationExtension(StartupExtensionABC):
services.add_transient(MigrationABC, UserMessageCountPerHourMigration) # 11.01.2023 #168 - 0.3.1 services.add_transient(MigrationABC, UserMessageCountPerHourMigration) # 11.01.2023 #168 - 0.3.1
services.add_transient(MigrationABC, ApiKeyMigration) # 09.02.2023 #162 - 1.0.0 services.add_transient(MigrationABC, ApiKeyMigration) # 09.02.2023 #162 - 1.0.0
services.add_transient(MigrationABC, UserJoinedGameServerMigration) # 12.02.2023 #181 - 1.0.0 services.add_transient(MigrationABC, UserJoinedGameServerMigration) # 12.02.2023 #181 - 1.0.0
services.add_transient(MigrationABC, RemoveStatsMigration) # 19.02.2023 #190 - 1.0.0 services.add_transient(MigrationABC, ConfigMigration) # 18.02.2023 #127 - 1.0.0
services.add_transient(MigrationABC, UserWarningMigration) # 21.02.2023 #35 - 1.0.0
services.add_transient(MigrationABC, DBHistoryMigration) # 06.03.2023 #246 - 1.0.0

View File

@@ -1,6 +1,5 @@
import os import os
from datetime import datetime from datetime import datetime
from typing import Callable, Type, Optional
from cpl_core.application import StartupExtensionABC from cpl_core.application import StartupExtensionABC
from cpl_core.configuration import ConfigurationABC from cpl_core.configuration import ConfigurationABC
@@ -8,11 +7,7 @@ from cpl_core.dependency_injection import ServiceCollectionABC
from cpl_core.environment import ApplicationEnvironmentABC from cpl_core.environment import ApplicationEnvironmentABC
from bot_core.configuration.bot_logging_settings import BotLoggingSettings from bot_core.configuration.bot_logging_settings import BotLoggingSettings
from bot_core.configuration.bot_settings import BotSettings from bot_core.helper.settings_helper import SettingsHelper
from modules.base.configuration.base_settings import BaseSettings
from modules.boot_log.configuration.boot_log_settings import BootLogSettings
from modules.level.configuration.level_settings import LevelSettings
from modules.permission.configuration.permission_settings import PermissionSettings
class StartupSettingsExtension(StartupExtensionABC): class StartupSettingsExtension(StartupExtensionABC):
@@ -34,27 +29,9 @@ class StartupSettingsExtension(StartupExtensionABC):
configuration.add_json_file(f"config/feature-flags.{environment.host_name}.json", optional=True) configuration.add_json_file(f"config/feature-flags.{environment.host_name}.json", optional=True)
configuration.add_configuration("Startup_StartTime", str(self._start_time)) configuration.add_configuration("Startup_StartTime", str(self._start_time))
self._configure_settings_with_sub_settings(configuration, BotSettings, lambda x: x.servers, lambda x: x.id) SettingsHelper.configure_settings_with_sub_settings(
self._configure_settings_with_sub_settings(configuration, BaseSettings, lambda x: x.servers, lambda x: x.id)
self._configure_settings_with_sub_settings(configuration, BootLogSettings, lambda x: x.servers, lambda x: x.id)
self._configure_settings_with_sub_settings(configuration, LevelSettings, lambda x: x.servers, lambda x: x.id)
self._configure_settings_with_sub_settings(
configuration, PermissionSettings, lambda x: x.servers, lambda x: x.id
)
self._configure_settings_with_sub_settings(
configuration, BotLoggingSettings, lambda x: x.files, lambda x: x.key configuration, BotLoggingSettings, lambda x: x.files, lambda x: x.key
) )
def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
pass pass
@staticmethod
def _configure_settings_with_sub_settings(
config: ConfigurationABC, settings: Type, list_atr: Callable, atr: Callable
):
settings: Optional[settings] = config.get_configuration(settings)
if settings is None:
return
for sub_settings in list_atr(settings):
config.add_configuration(f"{type(sub_settings).__name__}_{atr(sub_settings)}", sub_settings)

View File

@@ -1,27 +1,51 @@
{ {
"api": {
"api": {
"test_mail": {
"message": "Dies ist eine Test-Mail vom Krümelmonster Web Interface\nGesendet von {}-{}",
"subject": "Krümelmonster Web Interface Test-Mail"
}
},
"auth": {
"confirmation": {
"message": "Öffne den Link, um die E-Mail zu bestätigen:\n{}auth/register/{}",
"subject": "E-Mail für {} {} bestätigen"
},
"forgot_password": {
"message": "Öffne den Link, um das Passwort zu ändern:\n{}auth/forgot-password/{}",
"subject": "Passwort für {} {} zurücksetzen"
}
},
"mail": {
"automatic_mail": "\n\nDies ist eine automatische E-Mail.\nGesendet von {}-{}@{}"
}
},
"common": { "common": {
"hello_world": "Hallo Welt",
"bot_has_no_permission_message": "Ey!!!\nWas soll das?\nIch habe keine Berechtigungen :(\nScheiß System...", "bot_has_no_permission_message": "Ey!!!\nWas soll das?\nIch habe keine Berechtigungen :(\nScheiß System...",
"no_permission_message": "Nein!\nIch höre nicht auf dich ¯\\_(ツ)_/¯",
"not_implemented_yet": "Ey Alter, das kann ich noch nicht...",
"presence": {
"booting": "{} Ich fahre gerade hoch...",
"running": "{} Ich esse Kekse :D",
"restart": "{} Muss neue Kekse holen...",
"shutdown": "{} Ich werde bestimmt wieder kommen..."
},
"errors": {
"error": "Es gab einen Fehler. Meld dich bitte bei einem Admin.",
"command_error": "Es gab einen Fehler beim bearbeiten des Befehls. Meld dich bitte bei einem Admin.",
"missing_required_argument": "Fehler: Ein benötigter Parameter fehlt!",
"argument_parsing_error": "Fehler: Parameter konnte nicht gelesen werden!",
"unexpected_quote_error": "Fehler: Unerwarteter Zitat Fehler!",
"invalid_end_of_quoted_string_error": "Fehler: Ungültiges Zitatende!",
"expected_closing_quote_error": "Fehler: Erwarte Zitatende!",
"bad_argument": "Fehler: Ungültiger Parameter!",
"bad_union_argument": "Fehler: Ungültiger Union Parameter!",
"private_message_only": "Fehler: Nur private Nachrichten sind erlaubt!",
"no_private_message": "Fehler: Private Nachrichten sind nicht erlaubt!",
"check_failure": "Fehler: Du hast nicht die benötigte Berechtigung!",
"check_any_failure": "Fehler: Alle checks sind Fehlgeschlagen!",
"command_not_found": "Fehler: Befehl konnte nicht gefunden werden!",
"disabled_command": "Fehler: Befehl wurde deaktiviert!",
"command_invoke_error": "Fehler: Befehl konnte nicht aufgerufen werden!",
"too_many_arguments": "Fehler: Zu viele Parameter!",
"user_input_error": "Fehler: Eingabefehler!",
"command_on_cooldown": "Fehler: Befehl befindet sich im cooldown!",
"max_concurrency_reached": "Fehler: Maximale Parallelität erreicht!",
"not_owner": "Fehler: Du bist nicht mein besitzer!",
"missing_permissions": "Fehler: Berechtigungen fehlen!",
"bot_missing_permissions": "Fehler: Mir fehlen Berechtigungen!",
"missing_role": "Fehler: Benötigte Rolle fehlt!",
"bot_missing_role": "Fehler: Mir fehlt eine benötigte Rolle!",
"missing_any_role": "Fehler: Alle benötigten Rollen fehlen!",
"bot_missing_any_role": "Fehler: Mir fehlen alle benötigten Rollen!",
"nsfw_channel_required": "Fehler: NSFW Kanal benötigt!",
"extension_error": "Fehler: Erweiterungsfehler!",
"extension_already_loaded": "Fehler: Erweiterung wurde bereits geladen!",
"extension_not_loaded": "Fehler: Erweiterung wurde nicht geladen!",
"no_entry_point_error": "Fehler: Kein Eintrittspunkt!",
"extension_failed": "Fehler: Erweiterung ist fehlgeschlagen!",
"bot_not_ready_yet": "Ey Alter! Gedulde dich doch mal! ..."
},
"colors": { "colors": {
"blue": "Blau", "blue": "Blau",
"dark_blue": "Dunkelblau", "dark_blue": "Dunkelblau",
@@ -45,296 +69,259 @@
"red": "Rot", "red": "Rot",
"teal": "Blaugrün", "teal": "Blaugrün",
"yellow": "Gelb" "yellow": "Gelb"
},
"errors": {
"argument_parsing_error": "Fehler: Parameter konnte nicht gelesen werden!",
"bad_argument": "Fehler: Ungültiger Parameter!",
"bad_union_argument": "Fehler: Ungültiger Union Parameter!",
"bot_missing_any_role": "Fehler: Mir fehlen alle benötigten Rollen!",
"bot_missing_permissions": "Fehler: Mir fehlen Berechtigungen!",
"bot_missing_role": "Fehler: Mir fehlt eine benötigte Rolle!",
"bot_not_ready_yet": "Ey Alter! Gedulde dich doch mal! ...",
"check_any_failure": "Fehler: Alle Checks sind Fehlgeschlagen!",
"check_failure": "Fehler: Du hast nicht die benötigte Berechtigung!",
"command_error": "Es gab einen Fehler beim Bearbeiten des Befehls. Melde dich bitte bei einem Admin.",
"command_invoke_error": "Fehler: Befehl konnte nicht aufgerufen werden!",
"command_not_found": "Fehler: Befehl konnte nicht gefunden werden!",
"command_on_cooldown": "Fehler: Befehl befindet sich im Cooldown!",
"disabled_command": "Fehler: Befehl wurde deaktiviert!",
"error": "Es gab einen Fehler. Melde dich bitte bei einem Admin.",
"expected_closing_quote_error": "Fehler: Erwarte Zitatende!",
"extension_already_loaded": "Fehler: Erweiterung wurde bereits geladen!",
"extension_error": "Fehler: Erweiterungsfehler!",
"extension_failed": "Fehler: Erweiterung ist fehlgeschlagen!",
"extension_not_loaded": "Fehler: Erweiterung wurde nicht geladen!",
"invalid_end_of_quoted_string_error": "Fehler: Ungültiges Zitatende!",
"max_concurrency_reached": "Fehler: Maximale Parallelität erreicht!",
"missing_any_role": "Fehler: Alle benötigten Rollen fehlen!",
"missing_permissions": "Fehler: Berechtigungen fehlen!",
"missing_required_argument": "Fehler: Ein benötigter Parameter fehlt!",
"missing_role": "Fehler: Benötigte Rolle fehlt!",
"no_entry_point_error": "Fehler: Kein Eintrittspunkt!",
"no_private_message": "Fehler: Private Nachrichten sind nicht erlaubt!",
"not_owner": "Fehler: Du bist nicht mein besitzer!",
"nsfw_channel_required": "Fehler: NSFW Kanal benötigt!",
"private_message_only": "Fehler: Nur private Nachrichten sind erlaubt!",
"too_many_arguments": "Fehler: Zu viele Parameter!",
"unexpected_quote_error": "Fehler: Unerwarteter Fehler beim Anführungszeichen!",
"user_input_error": "Fehler: Eingabefehler!"
},
"hello_world": "Hallo Welt",
"no_permission_message": "Nein!\nIch höre nicht auf dich ¯\\_(ツ)_/¯",
"not_implemented_yet": "Ey Alter, das kann ich noch nicht...",
"presence": {
"booting": "Ich fahre gerade hoch...",
"restart": "Muss neue Kekse holen...",
"running": "Ich esse Kekse :D",
"shutdown": "Ich werde bestimmt wieder kommen..."
} }
}, },
"modules": { "modules": {
"auto_role": { "auto_role": {
"list": {
"title": "Beobachtete Nachrichten:",
"description": "Von auto-role beobachtete Nachrichten:",
"auto_role_id": "auto-role Id",
"message_id": "Nachricht-Id"
},
"add": { "add": {
"success": "auto-role für die Nachricht {} wurde hinzugefügt :D",
"error": { "error": {
"already_exists": "auto-role für die Nachricht {} existiert bereits!", "not_found": "Nachricht {} in {} nicht gefunden!",
"not_found": "Nachricht {} in {} nicht gefunden!" "already_exists": "auto-role für die Nachricht {} existiert bereits!"
}, }
"success": "auto-role für die Nachricht {} wurde hinzugefügt :D" },
"remove": {
"success": "auto-role {} wurde entfernt :D",
"error": {
"not_found": "auto-role {} nicht gefunden!"
}
}, },
"error": { "error": {
"nothing_found": "Keine auto-role Einträge gefunden." "nothing_found": "Keine auto-role Einträge gefunden."
}, },
"list": {
"auto_role_id": "auto-role Id",
"description": "Von auto-role beobachtete Nachrichten:",
"message_id": "Nachricht-Id",
"title": "Beobachtete Nachrichten:"
},
"remove": {
"error": {
"not_found": "auto-role {} nicht gefunden!"
},
"success": "auto-role {} wurde entfernt :D"
},
"rule": { "rule": {
"list": {
"title": "auto-role Regeln:",
"description": "Von auto-role angewendete Regeln:",
"auto_role_rule_id": "auto-role Regel Id",
"emoji": "Emoji",
"role": "Rolle"
},
"add": { "add": {
"success": "Regel {} -> {} für auto-role {} wurde hinzugefügt :D",
"error": { "error": {
"already_exists": "Regel für auto-role {} existiert bereits!",
"emoji_not_found": "Emoji {} für auto-role Regel {} nicht gefunden!",
"not_found": "Regel für auto-role {} nicht gefunden!", "not_found": "Regel für auto-role {} nicht gefunden!",
"role_not_found": "Rolle {} für auto-role Regel {} nicht gefunden!" "emoji_not_found": "Emoji {} für auto-role Regel {} nicht gefunden!",
}, "role_not_found": "Rolle {} für auto-role Regel {} nicht gefunden!",
"success": "Regel {} -> {} für auto-role {} wurde hinzugefügt :D" "already_exists": "Regel für auto-role {} existiert bereits!"
}
},
"remove": {
"success": "Regel für auto-role {} wurde entfernt :D",
"error": {
"not_found": "Regel für auto-role {} nicht gefunden!"
}
}, },
"error": { "error": {
"id_not_found": "Kein auto-role Eintrag mit der Id gefunden!" "id_not_found": "Kein auto-role Eintrag mit der Id gefunden!"
},
"list": {
"auto_role_rule_id": "auto-role Regel Id",
"description": "Von auto-role angewendete Regeln:",
"emoji": "Emoji",
"role": "Rolle",
"title": "auto-role Regeln:"
},
"remove": {
"error": {
"not_found": "Regel für auto-role {} nicht gefunden!"
},
"success": "Regel für auto-role {} wurde entfernt :D"
} }
} }
}, },
"base": {
"afk_command_channel_missing_message": "Zu unfähig einem Sprachkanal beizutreten?",
"afk_command_move_message": "Ich verschiebe dich ja schon... (◔_◔)",
"game_server": {
"error": {
"nothing_found": "Keine Gameserver gefunden."
},
"list": {
"title": "Gameserver",
"description": "Konfigurierte Gameserver:",
"name": "Name",
"api_key": "API Key"
},
"add": {
"success": "Gameserver {} wurde hinzugefügt :)"
},
"remove": {
"success": "Gameserver wurde entfernt :D"
}
},
"goodbye_message": "Schade, dass du uns so schnell verlässt :(",
"info": {
"description": "Informationen über mich",
"fields": {
"deleted_message_count": "Gelöschte Nachrichten",
"modules": "Module",
"moved_users_count": "Verschobene Benutzer",
"ontime": "Ontime",
"received_command_count": "Empfangene Befehle",
"received_message_count": "Empfangene Nachrichten",
"sent_message_count": "Gesendete Nachrichten",
"version": "Version"
},
"footer": "",
"title": "Krümelmonster"
},
"mass_move": {
"channel_from_error": "Du musst dich in einem Voicechannel befinden oder die Option \"channel_from\" mit angeben.",
"moved": "Alle Personen aus {} wurden nach {} verschoben."
},
"member_joined_help_voice_channel": "{} braucht Hilfe, bitte kümmere dich drum :D",
"pong": "Pong",
"presence": {
"changed": "Presence wurde geändert.",
"max_char_count_exceeded": "Der Text darf nicht mehr als 128 Zeichen lang sein!",
"removed": "Presence wurde entfernt."
},
"register": {
"not_found": "Benutzer konnte nicht gefunden werden!",
"success": "Spieler wurde mit dem Mitglied verlinkt :D"
},
"technician_command_error_message": "Es gab ein Fehler mit dem Befehl: {} ausgelöst von {} -> {}\nDatum und Zeit: {}\nSchau bitte ins Log für Details.\nUUID: {}",
"technician_error_message": "Es gab ein Fehler mit dem Event: {}\nDatum und Zeit: {}\nSchau bitte ins Log für Details.\nUUID: {}",
"unregister": {
"success": "Verlinkung wurde entfernt :D"
},
"user": {
"add": {
"xp": "Die {} von {} wurden um {} erhöht"
},
"atr": {
"discord_join": "Discord beigetreten am",
"id": "Id",
"joins": "Beitritte",
"last_join": "Server beigetreten am",
"lefts": "Abgänge",
"name": "Name",
"ontime": "Ontime",
"roles": "Rollen",
"warnings": "Verwarnungen",
"xp": "XP"
},
"error": {
"atr_not_found": "Das Attribut {} konnte nicht gefunden werden :("
},
"get": {
"ontime": "{} war insgesamt {} Stunden aktiv in einem Sprachkanal",
"xp": "{} hat {} xp"
},
"info": {
"footer": ""
},
"remove": {
"xp": "Die {} von {} wurden um {} verringert"
},
"reset": {
"ontime": "Die {} von {} wurden entfernt",
"xp": "Die {} von {} wurden entfernt"
},
"set": {
"error": {
"type_error": "Der angegebene Wert ist keine Zahl! :(",
"value_type_not_numeric": "Der angegebende Wert ist keine Ganzzahl! :("
},
"xp": "{} hat nun {} xp"
}
},
"warnings": {
"add": {
"failed": "Verwarnung konnte nicht hinzugefügt werden :(",
"success": "Verwarnung wurde hinzugefügt :)"
},
"first": "Bei der nächsten Verwarnung wirst du auf das vorherige Level zurückgesetzt!",
"kick": "Ich musste {} aufgrund zu vieler Verwarnungen kicken",
"remove": {
"failed": "Verwarnung konnte nicht entfernt werden :(",
"success": "Verwarnung wurde entfernt :)"
},
"removed": "Die Verwarnung '{}' wurde entfernt.",
"second": "Bei der nächsten verwarnung wirst du auf das erste Level zurückgesetzt!",
"show": {
"description": "Beschreibung",
"id": "Id"
},
"team_removed": "Die Verwarnung '{}' an {} wurde entfernt.",
"team_warned": "{} wurde verwarnt. Der Grund ist: {}",
"third": "Bei der nächsten verwarnung wirst du gekickt und zurückgesetzt!",
"warned": "Du wurdest verwarnt. Der Grund ist: {}"
},
"welcome_message": "Hello There!\nIch heiße dich bei {} herzlichst Willkommen!",
"welcome_message_for_team": "{} hat gerade das Irrenhaus betreten."
},
"boot_log": {
"login_message": "Ich bin on the line :D\nDer Scheiß hat {} Sekunden gedauert"
},
"level": {
"create": {
"created": "Level {} mit Berechtigungen {} wurde erstellt :D"
},
"down": {
"already_first": "{} hat bereits das erste Level.",
"failed": "{} konnte nicht runtergesetzt werden :(",
"success": "{} wurde auf Level {} runtergesetzt :)"
},
"edit": {
"color_invalid": "Die Farbe {} ist ungültig!",
"edited": "Level {} wurde bearbeitet :D",
"not_found": "Level {} nicht gefunden!",
"permission_invalid": "Der Berechtigungswert {} ist ungültig!"
},
"error": {
"level_with_name_already_exists": "Ein Level mit dem Namen {} existiert bereits!",
"level_with_xp_already_exists": "Das Level {} hat bereits die Mindest-XP {}!",
"nothing_found": "Keine Einträge gefunden."
},
"list": {
"description": "Konfigurierte Level:",
"min_xp": "Mindest-XP",
"name": "Name",
"permission_int": "Berechtigungen",
"title": "Level:"
},
"new_level_message": "{} ist nun Level {}",
"remove": {
"error": {
"not_found": "Level {} nicht gefunden!"
},
"success": "Level {} wurde entfernt :D"
},
"seeding_failed": "Levelsystem konnte nicht neu geladen werden :(",
"seeding_finished": "Levelsystem wurde erfolgreich neu geladen :)",
"seeding_started": "Levelsystem wird neu geladen...",
"set": {
"already_level": "{} hat bereits das Level {} :/",
"failed": "Das Level von {} konnte nicht auf {} gesetzt werden :(",
"not_found": "Das Level {} konnte nicht gefunden werden :(",
"success": "{} ist nun Level {} :)"
},
"up": {
"already_last": "{} hat bereits das höchste Level.",
"failed": "{} konnte nicht hochgesetzt werden :(",
"success": "{} wurde auf Level {} hochgesetzt :)"
}
},
"moderator": { "moderator": {
"purge_message": "Na gut..., ich lösche alle Nachrichten wenns sein muss." "purge_message": "Na gut..., ich lösche alle Nachrichten wenns sein muss."
}, },
"base": {
"technician_error_message": "Es gab ein Fehler mit dem Event: {}\nDatum und Zeit: {}\nSchau bitte ins log für Details.\nUUID: {}",
"technician_command_error_message": "Es gab ein Fehler mit dem Befehl: {} ausgelöst von {} -> {}\nDatum und Zeit: {}\nSchau bitte ins log für Details.\nUUID: {}",
"welcome_message": "Hello There!\nIch heiße dich bei {} herzlichst Willkommen!",
"welcome_message_for_team": "{} hat gerade das Irrenhaus betreten.",
"goodbye_message": "Schade, dass du uns so schnell verlässt :(",
"afk_command_channel_missing_message": "Zu unfähig einem Sprachkanal beizutreten?",
"afk_command_move_message": "Ich verschiebe dich ja schon... (◔_◔)",
"member_joined_help_voice_channel": "{} braucht hilfe, bitte kümmer dich drum :D",
"pong": "Pong",
"info": {
"title": "Krümmelmonster",
"description": "Informationen über mich",
"fields": {
"version": "Version",
"ontime": "Ontime",
"sent_message_count": "Gesendete Nachrichten",
"received_message_count": "Empfangene Nachrichten",
"deleted_message_count": "Gelöschte Nachrichten",
"received_command_count": "Empfangene Befehle",
"moved_users_count": "Verschobene Benutzer",
"modules": "Module"
},
"footer": ""
},
"mass_move": {
"moved": "Alle Personen aus {} wurden nach {} verschoben.",
"channel_from_error": "Du musst dich in einem Voicechannel befinden oder die Option \"channel_from\" mit angeben."
},
"presence": {
"changed": "Presence wurde geändert.",
"removed": "Presence wurde entfernt.",
"max_char_count_exceeded": "Der Text darf nicht mehr als 128 Zeichen lang sein!"
},
"user": {
"atr": {
"id": "Id",
"name": "Name",
"discord_join": "Discord beigetreten am",
"last_join": "Server beigetreten am",
"xp": "XP",
"ontime": "Ontime",
"roles": "Rollen",
"joins": "Beitritte",
"lefts": "Abgänge",
"warnings": "Verwarnungen"
},
"info": {
"footer": ""
},
"get": {
"xp": "{} hat {} xp",
"ontime": "{} war insgesamt {} Stunden aktiv in einem Sprachkanal"
},
"set": {
"xp": "{} hat nun {} xp",
"error": {
"value_type_not_numeric": "Der angegebende Wert ist keine Ganzzahl! :(",
"type_error": "Der angegebene Wert ist keine Zahl! :("
}
},
"add": {
"xp": "Die {} von {} wurden um {} erhöht"
},
"remove": {
"xp": "Die {} von {} wurden um {} verringert"
},
"reset": {
"xp": "Die {} von {} wurden entfernt",
"ontime": "Die {} von {} wurden entfernt"
},
"error": {
"atr_not_found": "Das Attribut {} konnte nicht gefunden werden :("
}
},
"register": {
"success": "Spieler wurde mit dem Mitglied verlinkt :D",
"not_found": "Benutzer nicht gefunden!"
},
"unregister": {
"success": "Verlinkung wurde entfernt :D"
}
},
"boot_log": {
"login_message": "Ich bin on the line :D\nDer Scheiß hat {} Sekunden gedauert"
},
"level": {
"new_level_message": "{} ist nun Level {}",
"seeding_started": "Levelsystem wird neu geladen...",
"seeding_failed": "Levelsystem konnte nicht neu geladen werden :(",
"seeding_finished": "Levelsystem wurde Erfolgreich neu geladen :)",
"error": {
"nothing_found": "Keine Level Einträge gefunden.",
"level_with_name_already_exists": "Ein Level mit dem Namen {} existiert bereits!",
"level_with_xp_already_exists": "Das Level {} hat bereits die Mindest-XP {}!"
},
"list": {
"title": "Level:",
"description": "Konfigurierte Level:",
"name": "Name",
"min_xp": "Mindest-XP",
"permission_int": "Berechtigungen"
},
"create": {
"created": "Level {} mit Berechtigungen {} wurde erstellt :D"
},
"edit": {
"edited": "Level {} wurde bearbeitet :D",
"color_invalid": "Die Farbe {} ist ungültig!",
"permission_invalid": "Der Berechtigungswert {} ist ungültig!",
"not_found": "Level {} nicht gefunden!"
},
"remove": {
"success": "Level {} wurde entfernt :D",
"error": {
"not_found": "Level {} nicht gefunden!"
}
},
"down": {
"already_first": "{} hat bereits das erste Level.",
"success": "{} wurde auf Level {} runtergesetzt :)",
"failed": "{} konnte nicht runtergesetzt werden :("
},
"up": {
"already_last": "{} hat bereits das höchste Level.",
"success": "{} wurde auf Level {} hochgesetzt :)",
"failed": "{} konnte nicht hochgesetzt werden :("
},
"set": {
"already_level": "{} hat bereits das Level {} :/",
"success": "{} ist nun Level {} :)",
"failed": "Das Level von {} konnte nicht auf {} gesetzt werden :(",
"not_found": "Das Level {} konnte nicht gefunden werden :("
}
},
"database": {},
"permission": {},
"stats": {
"list": {
"statistic": "Statistik",
"description": "Beschreibung",
"nothing_found": "Keine Statistiken gefunden."
},
"view": {
"statistic": "Statistik",
"description": "Beschreibung",
"failed": "Statistik kann nicht gezeigt werden :("
},
"add": {
"failed": "Statistik kann nicht hinzugefügt werden :(",
"success": "Statistik wurde hinzugefügt :D"
},
"edit": {
"failed": "Statistik kann nicht bearbeitet werden :(",
"success": "Statistik wurde gespeichert :D"
},
"remove": {
"failed": "Statistik kann nicht gelöscht werden :(",
"success": "Statistik wurde gelöscht :D"
}
},
"technician": { "technician": {
"restart_message": "Bin gleich wieder da :D",
"shutdown_message": "Trauert nicht um mich, es war eine logische Entscheidung. Das Wohl von Vielen, es wiegt schwerer als das Wohl von Wenigen oder eines Einzelnen. Ich war es und ich werde es immer sein, Euer Freund. Lebt lange und in Frieden :)",
"log_message": "Hier sind deine Logdateien! :)",
"api_key": { "api_key": {
"get": "API-Schlüssel für {}: {}",
"add": { "add": {
"success": "API-Schlüssel für {} wurde erstellt: {}" "success": "API-Schlüssel für {} wurde erstellt: {}"
}, },
"get": "API-Schlüssel für {}: {}",
"remove": { "remove": {
"not_found": "API-Schlüssel konnte nicht gefunden werden!", "not_found": "API-Schlüssel konnte nicht gefunden werden!",
"success": "API-Schlüssel wurde entfernt :D" "success": "API-Schlüssel wurde entfernt :D"
} }
}
}
},
"api": {
"mail": {
"automatic_mail": "\n\nDies ist eine automatische E-Mail.\nGesendet von {}-{}@{}"
},
"api": {
"test_mail": {
"subject": "Krümmelmonster Web Interface Test-Mail",
"message": "Dies ist eine Test-Mail vom Krümmelmonster Web Interface\nGesendet von {}-{}"
}
},
"auth": {
"confirmation": {
"subject": "E-Mail für {} {} bestätigen",
"message": "Öffne den Link um die E-Mail zu bestätigen:\n{}auth/register/{}"
}, },
"log_message": "Hier sind deine Logdateien! :)", "forgot_password": {
"restart_message": "Bin gleich wieder da :D", "subject": "Passwort für {} {} zurücksetzen",
"shutdown_message": "Trauert nicht um mich, es war eine logische Entscheidung. Das Wohl von Vielen, es wiegt schwerer als das Wohl von Wenigen oder eines Einzelnen. Ich war es und ich werde es immer sein, euer Freund. Lebt lange und in Frieden :)" "message": "Öffne den Link um das Passwort zu ändern:\n{}auth/forgot-password/{}"
}
} }
} }
} }

View File

@@ -15,7 +15,7 @@ __title__ = "bot_api"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_api.abc"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -53,10 +53,7 @@ class Api(Flask):
self.register_error_handler(exc_class, self.handle_exception) self.register_error_handler(exc_class, self.handle_exception)
# websockets # websockets
# Added async_mode see link below self._socketio = SocketIO(self, cors_allowed_origins="*", path="/api/socket.io")
# https://github.com/miguelgrinberg/Flask-SocketIO/discussions/1849
# https://stackoverflow.com/questions/39370848/flask-socket-io-sometimes-client-calls-freeze-the-server
self._socketio = SocketIO(self, cors_allowed_origins="*", path="/api/socket.io", async_mode="eventlet")
self._socketio.on_event("connect", self.on_connect) self._socketio.on_event("connect", self.on_connect)
self._socketio.on_event("disconnect", self.on_disconnect) self._socketio.on_event("disconnect", self.on_disconnect)

View File

@@ -2,9 +2,9 @@
"ProjectSettings": { "ProjectSettings": {
"Name": "bot-api", "Name": "bot-api",
"Version": { "Version": {
"Major": "1", "Major": "0",
"Minor": "0", "Minor": "3",
"Micro": "5" "Micro": "1"
}, },
"Author": "", "Author": "",
"AuthorEmail": "", "AuthorEmail": "",

View File

@@ -15,7 +15,7 @@ __title__ = "bot_api.configuration"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports # imports
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_api.controller"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -71,7 +71,7 @@ class AuthController:
@Route.post(f"{BasePath}/register") @Route.post(f"{BasePath}/register")
async def register(self): async def register(self):
dto: AuthUserDTO = JSONProcessor.process(AuthUserDTO, request.get_json(force=True, silent=True)) dto: AuthUserDTO = JSONProcessor.process(AuthUserDTO, request.get_json(force=True, silent=True))
self._auth_service.add_auth_user(dto) await self._auth_service.add_auth_user(dto)
return "", 200 return "", 200
@Route.post(f"{BasePath}/register-by-id/<id>") @Route.post(f"{BasePath}/register-by-id/<id>")
@@ -129,6 +129,7 @@ class AuthController:
return "", 200 return "", 200
@Route.post(f"{BasePath}/refresh") @Route.post(f"{BasePath}/refresh")
@Route.authorize
async def refresh(self) -> Response: async def refresh(self) -> Response:
dto: TokenDTO = JSONProcessor.process(TokenDTO, request.get_json(force=True, silent=True)) dto: TokenDTO = JSONProcessor.process(TokenDTO, request.get_json(force=True, silent=True))
result = await self._auth_service.refresh_async(dto) result = await self._auth_service.refresh_async(dto)

View File

@@ -15,7 +15,7 @@ __title__ = "bot_api.event"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_api.exception"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_api.filter"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_api.filter.discord"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_api.logging"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_api.model"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_api.model.discord"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -1,13 +1,16 @@
import traceback
from cpl_core.console import Console
from bot_api.abc.dto_abc import DtoABC from bot_api.abc.dto_abc import DtoABC
class TokenDTO(DtoABC): class TokenDTO(DtoABC):
def __init__(self, token: str, refresh_token: str, first_login: bool = False): def __init__(self, token: str, refresh_token: str):
DtoABC.__init__(self) DtoABC.__init__(self)
self._token = token self._token = token
self._refresh_token = refresh_token self._refresh_token = refresh_token
self._first_login = first_login
@property @property
def token(self) -> str: def token(self) -> str:
@@ -17,14 +20,9 @@ class TokenDTO(DtoABC):
def refresh_token(self) -> str: def refresh_token(self) -> str:
return self._refresh_token return self._refresh_token
@property
def first_login(self) -> bool:
return self._first_login
def from_dict(self, values: dict): def from_dict(self, values: dict):
self._token = values["token"] self._token = values["token"]
self._refresh_token = values["refreshToken"] self._refresh_token = values["refreshToken"]
self._first_login = values["firstLogin"]
def to_dict(self) -> dict: def to_dict(self) -> dict:
return {"token": self._token, "refreshToken": self._refresh_token, "firstLogin": self._first_login} return {"token": self._token, "refreshToken": self._refresh_token}

View File

@@ -10,6 +10,7 @@ class UserDTO(DtoABC):
id: int = None, id: int = None,
dc_id: int = None, dc_id: int = None,
xp: int = None, xp: int = None,
minecraft_id: Optional[str] = None,
server: Optional[Server] = None, server: Optional[Server] = None,
is_technician: Optional[bool] = None, is_technician: Optional[bool] = None,
is_admin: Optional[bool] = None, is_admin: Optional[bool] = None,
@@ -20,6 +21,7 @@ class UserDTO(DtoABC):
self._user_id = id self._user_id = id
self._discord_id = dc_id self._discord_id = dc_id
self._xp = xp self._xp = xp
self._minecraft_id = minecraft_id
self._server = server self._server = server
self._is_technician = is_technician self._is_technician = is_technician
@@ -42,6 +44,14 @@ class UserDTO(DtoABC):
def xp(self, value: int): def xp(self, value: int):
self._xp = value self._xp = value
@property
def minecraft_id(self) -> Optional[str]:
return self._minecraft_id
@minecraft_id.setter
def minecraft_id(self, value: str):
self._minecraft_id = value
@property @property
def server(self) -> Optional[Server]: def server(self) -> Optional[Server]:
return self._server return self._server
@@ -62,6 +72,7 @@ class UserDTO(DtoABC):
self._user_id = values["id"] self._user_id = values["id"]
self._discord_id = values["dcId"] self._discord_id = values["dcId"]
self._xp = values["xp"] self._xp = values["xp"]
self._minecraft_id = values["minecraftId"]
self._server = values["server"] self._server = values["server"]
def to_dict(self) -> dict: def to_dict(self) -> dict:
@@ -69,6 +80,7 @@ class UserDTO(DtoABC):
"id": self._user_id, "id": self._user_id,
"dcId": self._discord_id, "dcId": self._discord_id,
"xp": self._xp, "xp": self._xp,
"minecraftId": self._minecraft_id,
"server": self._server.id, "server": self._server.id,
"isTechnician": self.is_technician, "isTechnician": self.is_technician,
"isAdmin": self.is_admin, "isAdmin": self.is_admin,

View File

@@ -15,7 +15,7 @@ __title__ = "bot_api.route"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_api.service"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports # imports
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -80,9 +80,6 @@ class AuthService(AuthServiceABC):
@staticmethod @staticmethod
def _is_email_valid(email: str) -> bool: def _is_email_valid(email: str) -> bool:
if email is None:
raise False
if re.fullmatch(_email_regex, email) is not None: if re.fullmatch(_email_regex, email) is not None:
return True return True
@@ -483,21 +480,18 @@ class AuthService(AuthServiceABC):
if user_dto is None: if user_dto is None:
raise ServiceException(ServiceErrorCode.InvalidData, "User not set") raise ServiceException(ServiceErrorCode.InvalidData, "User not set")
members = self._users.get_users_by_discord_id(dc_id)
if members.count() == 0:
raise ServiceException(ServiceErrorCode.InvalidUser, f"Member not found")
added_user = False
db_user = self._auth_users.find_auth_user_by_email(user_dto.email) db_user = self._auth_users.find_auth_user_by_email(user_dto.email)
if db_user is None: if db_user is None:
self.add_auth_user(user_dto) self.add_auth_user(user_dto)
added_user = True # raise ServiceException(ServiceErrorCode.InvalidUser, f'User not found')
db_user = self._auth_users.get_auth_user_by_email(user_dto.email) db_user = self._auth_users.get_auth_user_by_email(user_dto.email)
if db_user.users.count() == 0: if db_user.users.count() == 0:
members.for_each(lambda x: self._auth_users.add_auth_user_user_rel(AuthUserUsersRelation(db_user, x))) self._users.get_users_by_discord_id(dc_id).for_each(
lambda x: self._auth_users.add_auth_user_user_rel(AuthUserUsersRelation(db_user, x))
)
if db_user.confirmation_id is not None and not added_user: if db_user.confirmation_id is not None:
raise ServiceException(ServiceErrorCode.Forbidden, "E-Mail not verified") raise ServiceException(ServiceErrorCode.Forbidden, "E-Mail not verified")
token = self.generate_token(db_user) token = self.generate_token(db_user)
@@ -506,7 +500,7 @@ class AuthService(AuthServiceABC):
db_user.forgot_password_id = None db_user.forgot_password_id = None
self._db.save_changes() self._db.save_changes()
return TokenDTO(token, refresh_token, first_login=added_user) return TokenDTO(token, refresh_token)
async def refresh_async(self, token_dto: TokenDTO) -> TokenDTO: async def refresh_async(self, token_dto: TokenDTO) -> TokenDTO:
if token_dto is None: if token_dto is None:

View File

@@ -15,7 +15,7 @@ __title__ = "bot_api.transformer"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -43,14 +43,14 @@ class AuthUserTransformer(TransformerABC):
def _is_admin(user: User, bot: DiscordBotServiceABC, permissions: PermissionServiceABC): def _is_admin(user: User, bot: DiscordBotServiceABC, permissions: PermissionServiceABC):
guild = bot.get_guild(user.server.discord_id) guild = bot.get_guild(user.server.discord_id)
member = guild.get_member(user.discord_id) member = guild.get_member(user.discord_id)
return permissions.is_member_admin(member) return permissions.is_member_technician(member)
@staticmethod @staticmethod
@ServiceProviderABC.inject @ServiceProviderABC.inject
def _is_moderator(user: User, bot: DiscordBotServiceABC, permissions: PermissionServiceABC): def _is_moderator(user: User, bot: DiscordBotServiceABC, permissions: PermissionServiceABC):
guild = bot.get_guild(user.server.discord_id) guild = bot.get_guild(user.server.discord_id)
member = guild.get_member(user.discord_id) member = guild.get_member(user.discord_id)
return permissions.is_member_moderator(member) return permissions.is_member_technician(member)
@classmethod @classmethod
def to_dto(cls, db: AuthUser, password: str = None) -> AuthUserDTO: def to_dto(cls, db: AuthUser, password: str = None) -> AuthUserDTO:
@@ -69,6 +69,7 @@ class AuthUserTransformer(TransformerABC):
u.id, u.id,
u.discord_id, u.discord_id,
u.xp, u.xp,
u.minecraft_id,
u.server, u.server,
cls._is_technician(u), cls._is_technician(u),
cls._is_admin(u), cls._is_admin(u),

View File

@@ -15,7 +15,7 @@ __title__ = "bot_core"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports # imports
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_core.abc"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -2,11 +2,9 @@ from abc import ABC, abstractmethod
from datetime import datetime from datetime import datetime
from typing import Callable from typing import Callable
import discord
from cpl_query.extension import List from cpl_query.extension import List
from discord.ext.commands import Context from discord.ext.commands import Context
from bot_data.model.auto_role_rule import AutoRoleRule
from bot_data.model.user import User from bot_data.model.user import User
from modules.base.configuration.base_server_settings import BaseServerSettings from modules.base.configuration.base_server_settings import BaseServerSettings
@@ -61,9 +59,3 @@ class ClientUtilsABC(ABC):
@abstractmethod @abstractmethod
def get_ontime_for_user(self, user: User) -> float: def get_ontime_for_user(self, user: User) -> float:
pass pass
@abstractmethod
async def react_to_message_by_auto_role_rule(
self, discord_channel_id: int, discord_message_id: int, rule: AutoRoleRule, guild: discord.Guild
):
pass

View File

@@ -25,9 +25,7 @@ class MessageServiceABC(ABC):
self, self,
channel: discord.TextChannel, channel: discord.TextChannel,
message: Union[str, discord.Embed], message: Union[str, discord.Embed],
is_persistent: bool = False, without_tracking=True,
wait_before_delete: int = None,
without_tracking=False,
): ):
pass pass

View File

@@ -2,9 +2,9 @@
"ProjectSettings": { "ProjectSettings": {
"Name": "bot-core", "Name": "bot-core",
"Version": { "Version": {
"Major": "1", "Major": "0",
"Minor": "0", "Minor": "3",
"Micro": "5" "Micro": "1"
}, },
"Author": "Sven Heidemann", "Author": "Sven Heidemann",
"AuthorEmail": "sven.heidemann@sh-edraft.de", "AuthorEmail": "sven.heidemann@sh-edraft.de",

View File

@@ -15,7 +15,7 @@ __title__ = "bot_core.configuration"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -12,19 +12,13 @@ class BotSettings(ConfigurationModelABC):
ConfigurationModelABC.__init__(self) ConfigurationModelABC.__init__(self)
self._servers: List[ServerSettings] = List(ServerSettings) self._servers: List[ServerSettings] = List(ServerSettings)
self._technicians: List[int] = List(int)
self._wait_for_restart = 2 self._wait_for_restart = 2
self._wait_for_shutdown = 2 self._wait_for_shutdown = 2
self._cache_max_messages = 1000
@property @property
def servers(self) -> List[ServerSettings]: def servers(self) -> List[ServerSettings]:
return self._servers return self._servers
@property
def technicians(self) -> List[int]:
return self._technicians
@property @property
def wait_for_restart(self) -> int: def wait_for_restart(self) -> int:
return self._wait_for_restart return self._wait_for_restart
@@ -33,23 +27,13 @@ class BotSettings(ConfigurationModelABC):
def wait_for_shutdown(self) -> int: def wait_for_shutdown(self) -> int:
return self._wait_for_shutdown return self._wait_for_shutdown
@property
def cache_max_messages(self) -> int:
return self._cache_max_messages
def from_dict(self, settings: dict): def from_dict(self, settings: dict):
try: try:
self._technicians = settings["Technicians"]
self._wait_for_restart = settings["WaitForRestart"] self._wait_for_restart = settings["WaitForRestart"]
self._wait_for_shutdown = settings["WaitForShutdown"] self._wait_for_shutdown = settings["WaitForShutdown"]
settings.pop("Technicians")
settings.pop("WaitForRestart") settings.pop("WaitForRestart")
settings.pop("WaitForShutdown") settings.pop("WaitForShutdown")
if "CacheMaxMessages" in settings:
self._cache_max_messages = settings["CacheMaxMessages"]
settings.pop("CacheMaxMessages")
servers = List(ServerSettings) servers = List(ServerSettings)
for s in settings: for s in settings:
st = ServerSettings() st = ServerSettings()

View File

@@ -0,0 +1,29 @@
import traceback
from cpl_core.configuration import ConfigurationModelABC
from cpl_core.console import Console
from cpl_query.extension import List
class BotStartupSettings(ConfigurationModelABC):
def __init__(self):
ConfigurationModelABC.__init__(self)
self._cache_max_messages = 1000
self._technicians: List[int] = List(int)
@property
def cache_max_messages(self) -> int:
return self._cache_max_messages
@property
def technicians(self) -> List[int]:
return self._technicians
def from_dict(self, settings: dict):
try:
self._cache_max_messages = int(settings["CacheMaxMessages"])
self._technicians = settings["Technicians"]
except Exception as e:
Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")

View File

@@ -10,12 +10,12 @@ class FeatureFlagsEnum(Enum):
boot_log_module = "BootLogModule" boot_log_module = "BootLogModule"
core_module = "CoreModule" core_module = "CoreModule"
core_extension_module = "CoreExtensionModule" core_extension_module = "CoreExtensionModule"
data_module = "DataModule" data_module = ("DataModule",)
database_module = "DatabaseModule" database_module = ("DatabaseModule",)
level_module = "LevelModule" level_module = "LevelModule"
moderator_module = "ModeratorModule" moderator_module = "ModeratorModule"
permission_module = "PermissionModule" permission_module = "PermissionModule"
stats_module = "StatsModule"
# features # features
api_only = "ApiOnly" api_only = "ApiOnly"
presence = "Presence" presence = "Presence"
version_in_presence = "VersionInPresence"

View File

@@ -1,4 +1,5 @@
import traceback import traceback
from typing import Optional, Callable
from cpl_core.configuration.configuration_model_abc import ConfigurationModelABC from cpl_core.configuration.configuration_model_abc import ConfigurationModelABC
from cpl_core.console import Console from cpl_core.console import Console
@@ -23,10 +24,10 @@ class FeatureFlagsSettings(ConfigurationModelABC):
FeatureFlagsEnum.database_module.value: True, # 02.10.2022 #48 FeatureFlagsEnum.database_module.value: True, # 02.10.2022 #48
FeatureFlagsEnum.moderator_module.value: False, # 02.10.2022 #48 FeatureFlagsEnum.moderator_module.value: False, # 02.10.2022 #48
FeatureFlagsEnum.permission_module.value: True, # 02.10.2022 #48 FeatureFlagsEnum.permission_module.value: True, # 02.10.2022 #48
FeatureFlagsEnum.stats_module.value: True, # 08.11.2022 #46
# features # features
FeatureFlagsEnum.api_only.value: False, # 13.10.2022 #70 FeatureFlagsEnum.api_only.value: False, # 13.10.2022 #70
FeatureFlagsEnum.presence.value: True, # 03.10.2022 #56 FeatureFlagsEnum.presence.value: True, # 03.10.2022 #56
FeatureFlagsEnum.version_in_presence.value: False, # 21.03.2023 #253
} }
def get_flag(self, key: FeatureFlagsEnum) -> bool: def get_flag(self, key: FeatureFlagsEnum) -> bool:

View File

@@ -15,7 +15,7 @@ __title__ = "bot_core.core_extension"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_core.events"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_core.exception"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_core.helper"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -0,0 +1,17 @@
from typing import Type, Callable, Optional
from cpl_core.configuration import ConfigurationABC
from cpl_core.type import T
class SettingsHelper:
@staticmethod
def configure_settings_with_sub_settings(
config: ConfigurationABC, settings: Type[T], list_atr: Callable, atr: Callable
):
settings: Optional[settings] = config.get_configuration(settings)
if settings is None:
return
for sub_settings in list_atr(settings):
config.add_configuration(f"{type(sub_settings).__name__}_{atr(sub_settings)}", sub_settings)

View File

@@ -15,7 +15,7 @@ __title__ = "bot_core.logging"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports # imports
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_core.pipes"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports # imports
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_core.service"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -9,7 +9,6 @@ from cpl_core.time import TimeFormatSettings
from cpl_discord.service import DiscordBotServiceABC from cpl_discord.service import DiscordBotServiceABC
from cpl_query.extension import List from cpl_query.extension import List
from cpl_translation import TranslatePipe from cpl_translation import TranslatePipe
from discord import Guild
from discord.ext.commands import Context from discord.ext.commands import Context
from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.client_utils_abc import ClientUtilsABC
@@ -24,7 +23,6 @@ from bot_data.abc.user_joined_voice_channel_repository_abc import (
from bot_data.abc.user_message_count_per_hour_repository_abc import ( from bot_data.abc.user_message_count_per_hour_repository_abc import (
UserMessageCountPerHourRepositoryABC, UserMessageCountPerHourRepositoryABC,
) )
from bot_data.model.auto_role_rule import AutoRoleRule
from bot_data.model.user import User from bot_data.model.user import User
from bot_data.model.user_message_count_per_hour import UserMessageCountPerHour from bot_data.model.user_message_count_per_hour import UserMessageCountPerHour
from modules.base.configuration.base_server_settings import BaseServerSettings from modules.base.configuration.base_server_settings import BaseServerSettings
@@ -113,11 +111,7 @@ class ClientUtilsService(ClientUtilsABC):
import bot import bot
if self._feature_flags.get_flag(FeatureFlagsEnum.version_in_presence): name = self._t.transform(t_key).format(bot.__version__)
name = f"{bot.__version__} {self._t.transform(t_key)}"
else:
name = self._t.transform(t_key)
await self._bot.change_presence(activity=discord.Game(name=name)) await self._bot.change_presence(activity=discord.Game(name=name))
self._logger.info(__name__, f"Set presence {name}") self._logger.info(__name__, f"Set presence {name}")
@@ -194,27 +188,3 @@ class ClientUtilsService(ClientUtilsABC):
.sum(lambda join: (join.leaved_on - join.joined_on).total_seconds() / 3600), .sum(lambda join: (join.leaved_on - join.joined_on).total_seconds() / 3600),
2, 2,
) )
async def react_to_message_by_auto_role_rule(
self, discord_channel_id: int, discord_message_id: int, rule: AutoRoleRule, guild: discord.Guild
):
try:
guild: Guild = self._bot.guilds.where(lambda g: g == guild).single()
channel = guild.get_channel(discord_channel_id)
message = await channel.fetch_message(discord_message_id)
emoji = List(discord.Emoji, guild.emojis).where(lambda x: x.name == rule.emoji_name).single()
if emoji is None:
self._logger.debug(__name__, f"Emoji {rule.emoji_name} not found")
return
await message.add_reaction(emoji)
self._logger.debug(
__name__,
f"Added reaction {rule.emoji_name} to message: {discord_message_id}",
)
except Exception as e:
self._logger.error(
__name__,
f"Cannot add reaction {rule.emoji_name} to message: {discord_message_id}",
e,
)

View File

@@ -15,7 +15,7 @@ __title__ = "bot_data"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports # imports
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_data.abc"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports # imports
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -18,10 +18,6 @@ class ApiKeyRepositoryABC(ABC):
def get_api_key(self, identifier: str, key: str) -> ApiKey: def get_api_key(self, identifier: str, key: str) -> ApiKey:
pass pass
@abstractmethod
def get_api_key_by_id(self, id: int) -> ApiKey:
pass
@abstractmethod @abstractmethod
def get_api_key_by_key(self, key: str) -> ApiKey: def get_api_key_by_key(self, key: str) -> ApiKey:
pass pass

View File

@@ -1,39 +0,0 @@
from abc import ABC, abstractmethod
from cpl_query.extension import List
from bot_data.model.game_server import GameServer
class GameServerRepositoryABC(ABC):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def get_game_servers(self) -> List[GameServer]:
pass
@abstractmethod
def get_game_server_by_id(self, id: int) -> GameServer:
pass
@abstractmethod
def get_game_servers_by_server_id(self, id: int) -> List[GameServer]:
pass
@abstractmethod
def get_game_server_by_api_key_id(self, id: int) -> GameServer:
pass
@abstractmethod
def add_game_server(self, game_server: GameServer):
pass
@abstractmethod
def update_game_server(self, game_server: GameServer):
pass
@abstractmethod
def delete_game_server(self, game_server: GameServer):
pass

View File

@@ -1,27 +0,0 @@
from abc import ABC, abstractmethod
from datetime import datetime
class HistoryTableABC(ABC):
@abstractmethod
def __init__(self):
self._id = 0
self._deleted = False
self._date_from = datetime.now().isoformat()
self._date_to = datetime.now().isoformat()
@property
def id(self) -> int:
return self._id
@property
def deleted(self) -> bool:
return self._deleted
@property
def date_from(self) -> str:
return self._date_from
@property
def date_to(self) -> str:
return self._date_to

View File

@@ -3,7 +3,6 @@ from abc import ABC, abstractmethod
class MigrationABC(ABC): class MigrationABC(ABC):
name = None name = None
prio = 0
@abstractmethod @abstractmethod
def __init__(self): def __init__(self):

View File

@@ -0,0 +1,44 @@
from abc import ABC, abstractmethod
from typing import Optional
from cpl_query.extension import List
from bot_data.model.statistic import Statistic
class StatisticRepositoryABC(ABC):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def get_statistics(self) -> List[Statistic]:
pass
@abstractmethod
def get_statistics_by_server_id(self, server_id: int) -> List[Statistic]:
pass
@abstractmethod
def get_statistic_by_id(self, id: int) -> Statistic:
pass
@abstractmethod
def get_statistic_by_name(self, name: str, server_id: int) -> Statistic:
pass
@abstractmethod
def find_statistic_by_name(self, name: str, server_id: int) -> Optional[Statistic]:
pass
@abstractmethod
def add_statistic(self, statistic: Statistic):
pass
@abstractmethod
def update_statistic(self, statistic: Statistic):
pass
@abstractmethod
def delete_statistic(self, statistic: Statistic):
pass

View File

@@ -1,15 +0,0 @@
from abc import abstractmethod
from cpl_core.database import TableABC
class TableWithIdABC(TableABC):
@abstractmethod
def __init__(self):
self.__init__()
self._id = 0
@property
def id(self) -> int:
return self._id

View File

@@ -1,47 +0,0 @@
from abc import ABC, abstractmethod
from cpl_query.extension import List
from bot_data.model.user_game_ident import UserGameIdent
class UserGameIdentRepositoryABC(ABC):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def get_user_game_idents(self) -> List[UserGameIdent]:
pass
@abstractmethod
def get_user_game_ident_by_id(self, id: int) -> UserGameIdent:
pass
@abstractmethod
def get_user_game_ident_by_ident(self, ident: str) -> UserGameIdent:
pass
@abstractmethod
def find_user_game_ident_by_ident(self, ident: str) -> UserGameIdent:
pass
@abstractmethod
def get_user_game_idents_by_user_id(self, user_id: int) -> List[UserGameIdent]:
pass
@abstractmethod
def add_user_game_ident(self, user_game_ident: UserGameIdent):
pass
@abstractmethod
def update_user_game_ident(self, user_game_ident: UserGameIdent):
pass
@abstractmethod
def delete_user_game_ident(self, user_game_ident: UserGameIdent):
pass
@abstractmethod
def delete_user_game_ident_by_user_id(self, user_id: int):
pass

View File

@@ -1,35 +0,0 @@
from abc import ABC, abstractmethod
from cpl_query.extension import List
from bot_data.model.user_warnings import UserWarnings
class UserWarningsRepositoryABC(ABC):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def get_user_warnings(self) -> List[UserWarnings]:
pass
@abstractmethod
def get_user_warnings_by_id(self, id: int) -> UserWarnings:
pass
@abstractmethod
def get_user_warnings_by_user_id(self, user_id: int) -> List[UserWarnings]:
pass
@abstractmethod
def add_user_warnings(self, user_warnings: UserWarnings):
pass
@abstractmethod
def update_user_warnings(self, user_warnings: UserWarnings):
pass
@abstractmethod
def delete_user_warnings(self, user_warnings: UserWarnings):
pass

View File

@@ -2,9 +2,9 @@
"ProjectSettings": { "ProjectSettings": {
"Name": "bot-data", "Name": "bot-data",
"Version": { "Version": {
"Major": "1", "Major": "0",
"Minor": "0", "Minor": "3",
"Micro": "5" "Micro": "dev127"
}, },
"Author": "Sven Heidemann", "Author": "Sven Heidemann",
"AuthorEmail": "sven.heidemann@sh-edraft.de", "AuthorEmail": "sven.heidemann@sh-edraft.de",

View File

@@ -0,0 +1,86 @@
from cpl_core.configuration import ConfigurationABC
from cpl_core.database.context import DatabaseContextABC
from cpl_discord.service import DiscordBotServiceABC
from bot_core.configuration.bot_settings import BotSettings
from bot_core.helper.settings_helper import SettingsHelper
from bot_core.logging.database_logger import DatabaseLogger
from bot_data.abc.data_seeder_abc import DataSeederABC
from bot_data.service.db_config import DBConfigService
from bot_data.service.seeder_service import SeederService
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.configuration.base_server_settings import BaseServerSettings
from modules.base.configuration.base_settings import BaseSettings
from modules.boot_log.configuration.boot_log_settings import BootLogSettings
from modules.level.configuration.level_settings import LevelSettings
from modules.permission.configuration.permission_settings import PermissionSettings
class ConfigSeeder(DataSeederABC):
def __init__(
self,
config: ConfigurationABC,
logger: DatabaseLogger,
seeder: SeederService,
bot: DiscordBotServiceABC,
db_context: DatabaseContextABC,
db_config: DBConfigService,
base_helper: BaseHelperABC,
):
DataSeederABC.__init__(self)
self._config = config
self._logger = logger
self._seeder = seeder
self._bot = bot
self._db_context = db_context
self._db_config = db_config
self._base_helper = base_helper
async def seed(self):
self._logger.debug(__name__, f"Load config from database")
try:
cfg = self._db_config.get_st_bot()
bot_settings = BotSettings()
bot_settings.from_dict(cfg)
base_settings = BaseSettings()
base_settings.from_dict(cfg)
boot_log_settings = BootLogSettings()
boot_log_settings.from_dict(cfg)
level_settings = LevelSettings()
level_settings.from_dict(cfg)
permission_settings = PermissionSettings()
permission_settings.from_dict(cfg)
SettingsHelper.configure_settings_with_sub_settings(
self._config, BotSettings, lambda x: x.servers, lambda x: x.id
)
SettingsHelper.configure_settings_with_sub_settings(
self._config, BaseSettings, lambda x: x.servers, lambda x: x.id
)
SettingsHelper.configure_settings_with_sub_settings(
self._config, BootLogSettings, lambda x: x.servers, lambda x: x.id
)
SettingsHelper.configure_settings_with_sub_settings(
self._config, LevelSettings, lambda x: x.servers, lambda x: x.id
)
SettingsHelper.configure_settings_with_sub_settings(
self._config, PermissionSettings, lambda x: x.servers, lambda x: x.id
)
except Exception as e:
self._logger.fatal(__name__, "Cannot load config from db", e)
try:
for guild in self._bot.guilds:
settings: BaseServerSettings = self._base_helper.get_config(guild.id)
if settings is None:
self._db_config.create_config_for_guild(guild.id)
except Exception as e:
self._logger.fatal(__name__, "Cannot load or create guild config from db", e)
self._logger.info(__name__, f"Loaded config from database")

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-
"""
bot Keksdose bot
~~~~~~~~~~~~~~~~~~~
Discord bot for the Keksdose discord Server
:copyright: (c) 2022 - 2023 sh-edraft.de
:license: MIT, see LICENSE for more details.
"""
__title__ = "bot_data.data_extension"
__author__ = "Sven Heidemann"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "0.3.dev127"
from collections import namedtuple
# imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="0", minor="3", micro="dev127")

View File

@@ -1,4 +1,3 @@
import sys
from datetime import datetime from datetime import datetime
from cpl_core.application.application_extension_abc import ApplicationExtensionABC from cpl_core.application.application_extension_abc import ApplicationExtensionABC
@@ -10,6 +9,7 @@ from bot_core.configuration.feature_flags_enum import FeatureFlagsEnum
from bot_core.configuration.feature_flags_settings import FeatureFlagsSettings from bot_core.configuration.feature_flags_settings import FeatureFlagsSettings
from bot_core.logging.database_logger import DatabaseLogger from bot_core.logging.database_logger import DatabaseLogger
from bot_data.service.migration_service import MigrationService from bot_data.service.migration_service import MigrationService
from bot_data.service.seeder_service import SeederService
class DatabaseExtension(ApplicationExtensionABC): class DatabaseExtension(ApplicationExtensionABC):
@@ -25,6 +25,3 @@ class DatabaseExtension(ApplicationExtensionABC):
config.add_configuration("Database_StartTime", str(datetime.now())) config.add_configuration("Database_StartTime", str(datetime.now()))
migrations: MigrationService = services.get_service(MigrationService) migrations: MigrationService = services.get_service(MigrationService)
migrations.migrate() migrations.migrate()
if config.get_configuration("MIGRATION_ONLY"):
logger.warn(__name__, "Migrations finished. Stopping application...")
sys.exit()

View File

@@ -1,6 +1,7 @@
from cpl_core.configuration import ConfigurationABC from cpl_core.configuration import ConfigurationABC
from cpl_core.dependency_injection import ServiceCollectionABC from cpl_core.dependency_injection import ServiceCollectionABC
from cpl_core.environment import ApplicationEnvironmentABC from cpl_core.environment import ApplicationEnvironmentABC
from cpl_discord.discord_event_types_enum import DiscordEventTypesEnum
from cpl_discord.service.discord_collection_abc import DiscordCollectionABC from cpl_discord.service.discord_collection_abc import DiscordCollectionABC
from bot_core.abc.module_abc import ModuleABC from bot_core.abc.module_abc import ModuleABC
@@ -9,11 +10,11 @@ from bot_data.abc.api_key_repository_abc import ApiKeyRepositoryABC
from bot_data.abc.auth_user_repository_abc import AuthUserRepositoryABC from bot_data.abc.auth_user_repository_abc import AuthUserRepositoryABC
from bot_data.abc.auto_role_repository_abc import AutoRoleRepositoryABC from bot_data.abc.auto_role_repository_abc import AutoRoleRepositoryABC
from bot_data.abc.client_repository_abc import ClientRepositoryABC from bot_data.abc.client_repository_abc import ClientRepositoryABC
from bot_data.abc.game_server_repository_abc import GameServerRepositoryABC from bot_data.abc.data_seeder_abc import DataSeederABC
from bot_data.abc.known_user_repository_abc import KnownUserRepositoryABC from bot_data.abc.known_user_repository_abc import KnownUserRepositoryABC
from bot_data.abc.level_repository_abc import LevelRepositoryABC from bot_data.abc.level_repository_abc import LevelRepositoryABC
from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.server_repository_abc import ServerRepositoryABC
from bot_data.abc.user_game_ident_repository_abc import UserGameIdentRepositoryABC from bot_data.abc.statistic_repository_abc import StatisticRepositoryABC
from bot_data.abc.user_joined_game_server_repository_abc import UserJoinedGameServerRepositoryABC from bot_data.abc.user_joined_game_server_repository_abc import UserJoinedGameServerRepositoryABC
from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC
from bot_data.abc.user_joined_voice_channel_repository_abc import ( from bot_data.abc.user_joined_voice_channel_repository_abc import (
@@ -23,18 +24,18 @@ from bot_data.abc.user_message_count_per_hour_repository_abc import (
UserMessageCountPerHourRepositoryABC, UserMessageCountPerHourRepositoryABC,
) )
from bot_data.abc.user_repository_abc import UserRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC
from bot_data.abc.user_warnings_repository_abc import UserWarningsRepositoryABC from bot_data.config_seeder import ConfigSeeder
from bot_data.events.database_on_ready_event import DatabaseOnReadyEvent
from bot_data.service.api_key_repository_service import ApiKeyRepositoryService from bot_data.service.api_key_repository_service import ApiKeyRepositoryService
from bot_data.service.auth_user_repository_service import AuthUserRepositoryService from bot_data.service.auth_user_repository_service import AuthUserRepositoryService
from bot_data.service.auto_role_repository_service import AutoRoleRepositoryService from bot_data.service.auto_role_repository_service import AutoRoleRepositoryService
from bot_data.service.cache_service import CacheService
from bot_data.service.client_repository_service import ClientRepositoryService from bot_data.service.client_repository_service import ClientRepositoryService
from bot_data.service.game_server_repository_service import GameServerRepositoryService from bot_data.service.db_config import DBConfigService
from bot_data.service.known_user_repository_service import KnownUserRepositoryService from bot_data.service.known_user_repository_service import KnownUserRepositoryService
from bot_data.service.level_repository_service import LevelRepositoryService from bot_data.service.level_repository_service import LevelRepositoryService
from bot_data.service.seeder_service import SeederService from bot_data.service.seeder_service import SeederService
from bot_data.service.server_repository_service import ServerRepositoryService from bot_data.service.server_repository_service import ServerRepositoryService
from bot_data.service.user_game_ident_repository_service import UserGameIdentRepositoryService from bot_data.service.statistic_repository_service import StatisticRepositoryService
from bot_data.service.user_joined_game_server_repository_service import UserJoinedGameServerRepositoryService from bot_data.service.user_joined_game_server_repository_service import UserJoinedGameServerRepositoryService
from bot_data.service.user_joined_server_repository_service import ( from bot_data.service.user_joined_server_repository_service import (
UserJoinedServerRepositoryService, UserJoinedServerRepositoryService,
@@ -46,7 +47,6 @@ from bot_data.service.user_message_count_per_hour_repository_service import (
UserMessageCountPerHourRepositoryService, UserMessageCountPerHourRepositoryService,
) )
from bot_data.service.user_repository_service import UserRepositoryService from bot_data.service.user_repository_service import UserRepositoryService
from bot_data.service.user_warnings_repository_service import UserWarningsRepositoryService
class DataModule(ModuleABC): class DataModule(ModuleABC):
@@ -57,8 +57,6 @@ class DataModule(ModuleABC):
pass pass
def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
services.add_singleton(CacheService)
services.add_transient(ApiKeyRepositoryABC, ApiKeyRepositoryService) services.add_transient(ApiKeyRepositoryABC, ApiKeyRepositoryService)
services.add_transient(AuthUserRepositoryABC, AuthUserRepositoryService) services.add_transient(AuthUserRepositoryABC, AuthUserRepositoryService)
services.add_transient(ServerRepositoryABC, ServerRepositoryService) services.add_transient(ServerRepositoryABC, ServerRepositoryService)
@@ -70,12 +68,14 @@ class DataModule(ModuleABC):
services.add_transient(UserJoinedGameServerRepositoryABC, UserJoinedGameServerRepositoryService) services.add_transient(UserJoinedGameServerRepositoryABC, UserJoinedGameServerRepositoryService)
services.add_transient(AutoRoleRepositoryABC, AutoRoleRepositoryService) services.add_transient(AutoRoleRepositoryABC, AutoRoleRepositoryService)
services.add_transient(LevelRepositoryABC, LevelRepositoryService) services.add_transient(LevelRepositoryABC, LevelRepositoryService)
services.add_transient(UserWarningsRepositoryABC, UserWarningsRepositoryService) services.add_transient(StatisticRepositoryABC, StatisticRepositoryService)
services.add_transient( services.add_transient(
UserMessageCountPerHourRepositoryABC, UserMessageCountPerHourRepositoryABC,
UserMessageCountPerHourRepositoryService, UserMessageCountPerHourRepositoryService,
) )
services.add_transient(GameServerRepositoryABC, GameServerRepositoryService)
services.add_transient(UserGameIdentRepositoryABC, UserGameIdentRepositoryService)
services.add_transient(DBConfigService)
services.add_transient(DataSeederABC, ConfigSeeder)
services.add_transient(SeederService) services.add_transient(SeederService)
self._dc.add_event(DiscordEventTypesEnum.on_ready.value, DatabaseOnReadyEvent)

View File

@@ -1,5 +1,3 @@
import time
from cpl_core.database import DatabaseSettings from cpl_core.database import DatabaseSettings
from cpl_core.database.context import DatabaseContext from cpl_core.database.context import DatabaseContext
@@ -33,9 +31,4 @@ class DBContext(DatabaseContext):
return super(DBContext, self).select(statement) return super(DBContext, self).select(statement)
except Exception as e: except Exception as e:
self._logger.error(__name__, f"Database error caused by {statement}", e) self._logger.error(__name__, f"Database error caused by {statement}", e)
try:
time.sleep(0.5)
return self.select(statement)
except Exception as e:
pass
return [] return []

View File

@@ -11,11 +11,11 @@ Discord bot for the Keksdose discord Server
""" """
__title__ = "bot_graphql.queries.discord" __title__ = "bot_data.events"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.dev127"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports: # imports:
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="dev127")

View File

@@ -274,7 +274,6 @@ class DatabaseOnReadyEvent(OnReadyABC):
self._logger.debug(__name__, f"Start checking UserJoinedVoiceChannel table") self._logger.debug(__name__, f"Start checking UserJoinedVoiceChannel table")
for guild in self._bot.guilds: for guild in self._bot.guilds:
guild: discord.Guild = guild guild: discord.Guild = guild
settings: BaseServerSettings = self._config.get_configuration(f"BaseServerSettings_{guild.id}")
server = self._servers.find_server_by_discord_id(guild.id) server = self._servers.find_server_by_discord_id(guild.id)
if server is None: if server is None:
@@ -300,6 +299,10 @@ class DatabaseOnReadyEvent(OnReadyABC):
f"Active UserJoinedVoiceChannel found in database: {guild.id}:{member.id}@{join.joined_on}", f"Active UserJoinedVoiceChannel found in database: {guild.id}:{member.id}@{join.joined_on}",
) )
join.leaved_on = datetime.now() join.leaved_on = datetime.now()
settings: BaseServerSettings = self._config.get_configuration(f"BaseServerSettings_{guild.id}")
if settings is None:
self._logger.error(__name__, f"BaseServer settings for server {guild.id} not found!")
return
if ( if (
(join.leaved_on - join.joined_on).total_seconds() / 60 / 60 (join.leaved_on - join.joined_on).total_seconds() / 60 / 60
@@ -315,7 +318,7 @@ class DatabaseOnReadyEvent(OnReadyABC):
self._logger.trace(__name__, f"User {member.id} is ignored, because its a bot") self._logger.trace(__name__, f"User {member.id} is ignored, because its a bot")
continue continue
if member.voice is None or member.voice.channel.id in settings.afk_channel_ids: if member.voice is None:
continue continue
user = self._users.find_user_by_discord_id_and_server_id(member.id, server.id) user = self._users.find_user_by_discord_id_and_server_id(member.id, server.id)
@@ -375,6 +378,8 @@ class DatabaseOnReadyEvent(OnReadyABC):
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")
await self._seeder.seed()
self._check_known_users() self._check_known_users()
self._check_servers() self._check_servers()
self._check_clients() self._check_clients()
@@ -383,7 +388,5 @@ class DatabaseOnReadyEvent(OnReadyABC):
self._check_user_joins_vc() self._check_user_joins_vc()
self._check_user_joined_gs() self._check_user_joined_gs()
await self._seeder.seed()
self._validate_init_time() self._validate_init_time()
self._logger.trace(__name__, f"Module {type(self)} stopped") self._logger.trace(__name__, f"Module {type(self)} stopped")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_data.migration"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports # imports
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -4,7 +4,7 @@ from bot_data.db_context import DBContext
class ApiKeyMigration(MigrationABC): class ApiKeyMigration(MigrationABC):
name = "1.0.0_ApiKeyMigration" name = "1.0_ApiKeyMigration"
def __init__(self, logger: DatabaseLogger, db: DBContext): def __init__(self, logger: DatabaseLogger, db: DBContext):
MigrationABC.__init__(self) MigrationABC.__init__(self)

View File

@@ -0,0 +1,119 @@
from bot_core.logging.database_logger import DatabaseLogger
from bot_data.abc.migration_abc import MigrationABC
from bot_data.db_context import DBContext
class ConfigMigration(MigrationABC):
name = "1.0_ConfigMigration"
def __init__(self, logger: DatabaseLogger, db: DBContext):
MigrationABC.__init__(self)
self._logger = logger
self._db = db
self._cursor = db.cursor
def upgrade(self):
self._logger.debug(__name__, "Running upgrade")
self._cursor.execute(
f"""
CREATE TABLE IF NOT EXISTS `ST_Bot` (
`Id` BIGINT NOT NULL AUTO_INCREMENT,
`WaitForRestart` BIGINT NOT NULL DEFAULT 8,
`WaitForShutdown` BIGINT NOT NULL DEFAULT 8,
PRIMARY KEY(`Id`)
);
"""
)
self._cursor.execute(
f"""
CREATE TABLE IF NOT EXISTS `ST_Servers` (
`Id` BIGINT NOT NULL AUTO_INCREMENT,
`ServerId` BIGINT NOT NULL,
`MessageDeleteTimer` BIGINT NOT NULL DEFAULT 4,
-- base
`MaxVoiceStateHours` BIGINT NOT NULL DEFAULT 6,
`XpPerMessage` BIGINT NOT NULL DEFAULT 1,
`XpPerReaction` BIGINT NOT NULL DEFAULT 1,
`MaxMessageXpPerHour` BIGINT NOT NULL DEFAULT 40,
`XpPerOntimeHour` BIGINT NOT NULL DEFAULT 20,
`XpPerEventParticipation` BIGINT NOT NULL DEFAULT 20,
`AFKCommandChannelId` BIGINT NOT NULL DEFAULT 1,
`HelpCommandReferenceUrl` VARCHAR(512) NOT NULL DEFAULT 'https://git.sh-edraft.de/sh-edraft.de/kd_discord_bot/wiki/Befehle',
`HelpVoiceChannelId` BIGINT NOT NULL DEFAULT 1,
-- boot log
`LoginMessageChannelId` BIGINT NOT NULL,
-- level
`ChangedLevelNotificationChannelId` BIGINT NOT NULL,
PRIMARY KEY(`Id`),
FOREIGN KEY (`ServerId`) REFERENCES `Servers`(`ServerId`)
);
"""
)
self._cursor.execute(
f"""
CREATE TABLE IF NOT EXISTS `ST_Servers_AFKChannelIds` (
`Id` BIGINT NOT NULL AUTO_INCREMENT,
`ST_Server` BIGINT NOT NULL,
`ChannelId` BIGINT NOT NULL,
PRIMARY KEY(`Id`),
FOREIGN KEY (`ST_Server`) REFERENCES `ST_Servers`(`Id`)
);
"""
)
self._cursor.execute(
f"""
CREATE TABLE IF NOT EXISTS `ST_Servers_PingURLs` (
`Id` BIGINT NOT NULL AUTO_INCREMENT,
`ST_Server` BIGINT NOT NULL,
`URL` VARCHAR(512) NOT NULL,
PRIMARY KEY(`Id`),
FOREIGN KEY (`ST_Server`) REFERENCES `ST_Servers`(`Id`)
);
"""
)
self._cursor.execute(
f"""
CREATE TABLE IF NOT EXISTS `ST_Servers_Permissions` (
`Id` BIGINT NOT NULL AUTO_INCREMENT,
`ST_Server` BIGINT NOT NULL,
`RoleId` BIGINT NOT NULL,
`RoleType` BIGINT NOT NULL DEFAULT 1,
PRIMARY KEY(`Id`),
FOREIGN KEY (`ST_Server`) REFERENCES `ST_Servers`(`Id`)
);
"""
)
self._cursor.execute(
f"""
CREATE TABLE IF NOT EXISTS `ST_RoleTypes` (
`Id` BIGINT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(10) NOT NULL,
PRIMARY KEY(`Id`)
);
"""
)
self._cursor.execute(
f"""
INSERT INTO `ST_RoleTypes`
(`Id`, `Name`)
VALUES
(1, 'Moderator'),
(2, 'Admin');
"""
)
def downgrade(self):
self._logger.debug(__name__, "Running downgrade")
self._cursor.execute("DROP TABLE `ST_Bot`;")
self._cursor.execute("DROP TABLE `ST_Servers`;")
self._cursor.execute("DROP TABLE `ST_Servers_AFKChannelIds`;")
self._cursor.execute("DROP TABLE `ST_Servers_PingURLs`;")
self._cursor.execute("DROP TABLE `ST_Servers_Permissions`;")
self._cursor.execute("DROP TABLE `ST_RoleTypes`;")

View File

@@ -1,65 +0,0 @@
import os
from bot_core.logging.database_logger import DatabaseLogger
from bot_data.abc.migration_abc import MigrationABC
from bot_data.db_context import DBContext
class DBHistoryMigration(MigrationABC):
name = "1.0.0_DBHistoryMigration"
prio = 1
def __init__(self, logger: DatabaseLogger, db: DBContext):
MigrationABC.__init__(self)
self._logger = logger
self._db = db
self._cursor = db.cursor
def _exec(self, file: str):
path = f"{os.path.dirname(os.path.realpath(__file__))}/db_history_scripts"
sql = open(f"{path}/{file}").read()
for statement in sql.split("\n\n"):
self._cursor.execute(statement + ";")
def upgrade(self):
self._logger.debug(__name__, "Running upgrade")
self._exec("api_keys.sql")
self._exec("auth_users.sql")
self._exec("auth_user_users_relation.sql")
self._exec("auto_role_rules.sql")
self._exec("auto_roles.sql")
self._exec("clients.sql")
self._exec("game_servers.sql")
self._exec("known_users.sql")
self._exec("levels.sql")
self._exec("servers.sql")
self._exec("user_game_idents.sql")
self._exec("user_joined_game_servers.sql")
self._exec("user_joined_servers.sql")
self._exec("user_joined_voice_channel.sql")
self._exec("user_message_count_per_hour.sql")
self._exec("users.sql")
self._exec("user_warnings.sql")
self._logger.debug(__name__, "Finished history upgrade")
def downgrade(self):
self._cursor.execute("DROP TABLE `ApiKeysHistory`;")
self._cursor.execute("DROP TABLE `AuthUsersHistory`;")
self._cursor.execute("DROP TABLE `AuthUserUsersRelationsHistory`;")
self._cursor.execute("DROP TABLE `AutoRoleRulesHistory`;")
self._cursor.execute("DROP TABLE `AutoRolesHistory`;")
self._cursor.execute("DROP TABLE `ClientsHistory`;")
self._cursor.execute("DROP TABLE `GameServersHistory`;")
self._cursor.execute("DROP TABLE `KnownUsersHistory`;")
self._cursor.execute("DROP TABLE `LevelsHistory`;")
self._cursor.execute("DROP TABLE `ServersHistory`;")
self._cursor.execute("DROP TABLE `UserGameIdentsHistory`;")
self._cursor.execute("DROP TABLE `UserJoinedGameServerHistory`;")
self._cursor.execute("DROP TABLE `UserJoinedServersHistory`;")
self._cursor.execute("DROP TABLE `UserJoinedVoiceChannelHistory`;")
self._cursor.execute("DROP TABLE `UserMessageCountPerHourHistory`;")
self._cursor.execute("DROP TABLE `UsersHistory`;")
self._cursor.execute("DROP TABLE `UserWarningsHistory`;")

View File

@@ -1,46 +0,0 @@
ALTER TABLE `ApiKeys`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `ApiKeys`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `ApiKeysHistory`
(
`Id` BIGINT(20) NOT NULL,
`Identifier` VARCHAR(255) NOT NULL,
`Key` VARCHAR(255) NOT NULL,
`CreatorId` BIGINT(20) DEFAULT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_ApiKeysUpdate`;
CREATE TRIGGER `TR_ApiKeysUpdate`
AFTER UPDATE
ON `ApiKeys`
FOR EACH ROW
BEGIN
INSERT INTO `ApiKeysHistory` (
`Id`, `Identifier`, `Key`, `CreatorId`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.Identifier, OLD.Key, OLD.CreatorId, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_ApiKeysDelete`;
CREATE TRIGGER `TR_ApiKeysDelete`
AFTER DELETE
ON `ApiKeys`
FOR EACH ROW
BEGIN
INSERT INTO `ApiKeysHistory` (
`Id`, `Identifier`, `Key`, `CreatorId`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.Identifier, OLD.Key, OLD.CreatorId, TRUE, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,46 +0,0 @@
ALTER TABLE `AuthUserUsersRelations`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `AuthUserUsersRelations`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `AuthUserUsersRelationsHistory`
(
`Id` BIGINT(20) NOT NULL,
`AuthUserId` BIGINT(20) DEFAULT NULL,
`UserId` BIGINT(20) DEFAULT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_AuthUserUsersRelationsUpdate`;
CREATE TRIGGER `TR_AuthUserUsersRelationsUpdate`
AFTER UPDATE
ON `AuthUserUsersRelations`
FOR EACH ROW
BEGIN
INSERT INTO `AuthUserUsersRelationsHistory` (
`Id`, `AuthUserId`, `UserId`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.AuthUserId, OLD.UserId, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_AuthUserUsersRelationsDelete`;
CREATE TRIGGER `TR_AuthUserUsersRelationsDelete`
AFTER DELETE
ON `AuthUserUsersRelations`
FOR EACH ROW
BEGIN
INSERT INTO `AuthUserUsersRelationsHistory` (
`Id`, `AuthUserId`, `UserId`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.AuthUserId, OLD.UserId, TRUE, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,62 +0,0 @@
ALTER TABLE `AuthUsers`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `AuthUsers`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `AuthUsersHistory`
(
`Id` BIGINT(20) NOT NULL,
`FirstName` VARCHAR(255) DEFAULT NULL,
`LastName` VARCHAR(255) DEFAULT NULL,
`EMail` VARCHAR(255) DEFAULT NULL,
`Password` VARCHAR(255) DEFAULT NULL,
`PasswordSalt` VARCHAR(255) DEFAULT NULL,
`RefreshToken` VARCHAR(255) DEFAULT NULL,
`ConfirmationId` VARCHAR(255) DEFAULT NULL,
`ForgotPasswordId` VARCHAR(255) DEFAULT NULL,
`OAuthId` VARCHAR(255) DEFAULT NULL,
`RefreshTokenExpiryTime` DATETIME(6) NOT NULL,
`AuthRole` BIGINT(11) NOT NULL DEFAULT 0,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_AuthUsersUpdate`;
CREATE TRIGGER `TR_AuthUsersUpdate`
AFTER UPDATE
ON `AuthUsers`
FOR EACH ROW
BEGIN
INSERT INTO `AuthUsersHistory` (
`Id`, `FirstName`, `LastName`, `EMail`, `Password`, `PasswordSalt`,
`RefreshToken`, `ConfirmationId`, `ForgotPasswordId`, `OAuthId`,
`RefreshTokenExpiryTime`, `AuthRole`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.FirstName, OLD.LastName, OLD.EMail, OLD.Password, OLD.PasswordSalt, OLD.RefreshToken,
OLD.ConfirmationId, OLD.ForgotPasswordId, OLD.OAuthId, OLD.RefreshTokenExpiryTime, OLD.AuthRole,
OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_AuthUsersDelete`;
CREATE TRIGGER `TR_AuthUsersDelete`
AFTER DELETE
ON `AuthUsers`
FOR EACH ROW
BEGIN
INSERT INTO `AuthUsersHistory` (
`Id`, `FirstName`, `LastName`, `EMail`, `Password`, `PasswordSalt`, `RefreshToken`,
`ConfirmationId`, `ForgotPasswordId`, `OAuthId`, `RefreshTokenExpiryTime`,
`AuthRole`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.FirstName, OLD.LastName, OLD.EMail, OLD.Password, OLD.PasswordSalt, OLD.RefreshToken,
OLD.ConfirmationId, OLD.ForgotPasswordId, OLD.OAuthId, OLD.RefreshTokenExpiryTime, OLD.AuthRole, TRUE,
OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,46 +0,0 @@
ALTER TABLE `AutoRoleRules`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `AutoRoleRules`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `AutoRoleRulesHistory`
(
`Id` BIGINT(20) NOT NULL,
`AutoRoleId` BIGINT(20) DEFAULT NULL,
`DiscordEmojiName` VARCHAR(64) DEFAULT NULL,
`DiscordRoleId` BIGINT(20) NOT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_AutoRoleRulesUpdate`;
CREATE TRIGGER `TR_AutoRoleRulesUpdate`
AFTER UPDATE
ON `AutoRoleRules`
FOR EACH ROW
BEGIN
INSERT INTO `AutoRoleRulesHistory` (
`Id`, `AutoRoleId`, `DiscordEmojiName`, `DiscordRoleId`, `DateFrom`, `DateTo`
)
VALUES (
OLD.AutoRoleRuleId, OLD.AutoRoleId, OLD.DiscordEmojiName, OLD.DiscordRoleId, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_AutoRoleRulesDelete`;
CREATE TRIGGER `TR_AutoRoleRulesDelete`
AFTER DELETE
ON `AutoRoleRules`
FOR EACH ROW
BEGIN
INSERT INTO `AutoRoleRulesHistory` (
`Id`, `AutoRoleId`, `DiscordEmojiName`, `DiscordRoleId`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.AutoRoleRuleId, OLD.AutoRoleId, OLD.DiscordEmojiName, OLD.DiscordRoleId, TRUE, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,48 +0,0 @@
ALTER TABLE `AutoRoles`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `AutoRoles`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `AutoRolesHistory`
(
`Id` BIGINT(20) NOT NULL,
`ServerId` BIGINT(20) DEFAULT NULL,
`DiscordChannelId` BIGINT(20) NOT NULL,
`DiscordMessageId` BIGINT(20) NOT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_AutoRolesUpdate`;
CREATE TRIGGER `TR_AutoRolesUpdate`
AFTER UPDATE
ON `AutoRoles`
FOR EACH ROW
BEGIN
INSERT INTO `AutoRolesHistory` (
`Id`, `ServerId`, `DiscordChannelId`, `DiscordMessageId`, `DateFrom`, `DateTo`
)
VALUES (
OLD.AutoRoleId, OLD.ServerId, OLD.DiscordChannelId, OLD.DiscordMessageId, OLD.LastModifiedAt,
CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_AutoRolesDelete`;
CREATE TRIGGER `TR_AutoRolesDelete`
AFTER DELETE
ON `AutoRoles`
FOR EACH ROW
BEGIN
INSERT INTO `AutoRolesHistory` (
`Id`, `ServerId`, `DiscordChannelId`, `DiscordMessageId`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.AutoRoleId, OLD.ServerId, OLD.DiscordChannelId, OLD.DiscordMessageId, TRUE, OLD.LastModifiedAt,
CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,54 +0,0 @@
ALTER TABLE `Clients`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `Clients`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `ClientsHistory`
(
`Id` BIGINT(20) NOT NULL,
`DiscordId` BIGINT(20) NOT NULL,
`SentMessageCount` BIGINT(20) NOT NULL DEFAULT 0,
`ReceivedMessageCount` BIGINT(20) NOT NULL DEFAULT 0,
`DeletedMessageCount` BIGINT(20) NOT NULL DEFAULT 0,
`ReceivedCommandsCount` BIGINT(20) NOT NULL DEFAULT 0,
`MovedUsersCount` BIGINT(20) NOT NULL DEFAULT 0,
`ServerId` BIGINT(20) DEFAULT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_ClientsUpdate`;
CREATE TRIGGER `TR_ClientsUpdate`
AFTER UPDATE
ON `Clients`
FOR EACH ROW
BEGIN
INSERT INTO `ClientsHistory` (
`Id`, `DiscordId`, `SentMessageCount`, `ReceivedMessageCount`, `DeletedMessageCount`,
`ReceivedCommandsCount`, `MovedUsersCount`, `ServerId`, `DateFrom`, `DateTo`
)
VALUES (
OLD.ClientId, OLD.DiscordClientId, OLD.SentMessageCount, OLD.ReceivedMessageCount, OLD.DeletedMessageCount,
OLD.ReceivedCommandsCount, OLD.MovedUsersCount, OLD.ServerId, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_ClientsDelete`;
CREATE TRIGGER `TR_ClientsDelete`
AFTER DELETE
ON `Clients`
FOR EACH ROW
BEGIN
INSERT INTO `ClientsHistory` (
`Id`, `DiscordId`, `SentMessageCount`, `ReceivedMessageCount`, `DeletedMessageCount`,
`ReceivedCommandsCount`, `MovedUsersCount`, `ServerId`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.ClientId, OLD.DiscordClientId, OLD.SentMessageCount, OLD.ReceivedMessageCount, OLD.DeletedMessageCount,
OLD.ReceivedCommandsCount, OLD.MovedUsersCount, OLD.ServerId, TRUE, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,46 +0,0 @@
ALTER TABLE `GameServers`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `GameServers`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `GameServersHistory`
(
`Id` BIGINT(20) NOT NULL,
`Name` VARCHAR(255) NOT NULL,
`ServerId` BIGINT(20) NOT NULL,
`ApiKeyId` BIGINT(20) NOT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_GameServersUpdate`;
CREATE TRIGGER `TR_GameServersUpdate`
AFTER UPDATE
ON `GameServers`
FOR EACH ROW
BEGIN
INSERT INTO `GameServersHistory` (
`Id`, `Name`, `ServerId`, `ApiKeyId`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.Name, OLD.ServerId, OLD.ApiKeyId, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_GameServersDelete`;
CREATE TRIGGER `TR_GameServersDelete`
AFTER DELETE
ON `GameServers`
FOR EACH ROW
BEGIN
INSERT INTO `GameServersHistory` (
`Id`, `Name`, `ServerId`, `ApiKeyId`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.Name, OLD.ServerId, OLD.ApiKeyId, TRUE, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,44 +0,0 @@
ALTER TABLE `KnownUsers`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `KnownUsers`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `KnownUsersHistory`
(
`Id` BIGINT(20) NOT NULL,
`DiscordId` BIGINT(20) NOT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_KnownUsersUpdate`;
CREATE TRIGGER `TR_KnownUsersUpdate`
AFTER UPDATE
ON `KnownUsers`
FOR EACH ROW
BEGIN
INSERT INTO `KnownUsersHistory` (
`Id`, `DiscordId`, `DateFrom`, `DateTo`
)
VALUES (
OLD.KnownUserId, OLD.DiscordId, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_KnownUsersDelete`;
CREATE TRIGGER `TR_KnownUsersDelete`
AFTER DELETE
ON `KnownUsers`
FOR EACH ROW
BEGIN
INSERT INTO `KnownUsersHistory` (
`Id`, `DiscordId`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.KnownUserId, OLD.DiscordId, TRUE, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,50 +0,0 @@
ALTER TABLE `Levels`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `Levels`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `LevelsHistory`
(
`Id` BIGINT(20) NOT NULL,
`Name` VARCHAR(255) NOT NULL,
`Color` VARCHAR(8) NOT NULL,
`MinXp` BIGINT(20) NOT NULL,
`PermissionInt` BIGINT(20) NOT NULL,
`ServerId` BIGINT(20) DEFAULT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_LevelsUpdate`;
CREATE TRIGGER `TR_LevelsUpdate`
AFTER UPDATE
ON `Levels`
FOR EACH ROW
BEGIN
INSERT INTO `LevelsHistory` (
`Id`, `Name`, `Color`, `MinXp`, `PermissionInt`, `ServerId`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.Name, OLD.Color, OLD.MinXp, OLD.PermissionInt, OLD.ServerId, OLD.LastModifiedAt,
CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_LevelsDelete`;
CREATE TRIGGER `TR_LevelsDelete`
AFTER DELETE
ON `Levels`
FOR EACH ROW
BEGIN
INSERT INTO `LevelsHistory` (
`Id`, `Name`, `Color`, `MinXp`, `PermissionInt`, `ServerId`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.Name, OLD.Color, OLD.MinXp, OLD.PermissionInt, OLD.ServerId, TRUE, OLD.LastModifiedAt,
CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,44 +0,0 @@
ALTER TABLE `Servers`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `Servers`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `ServersHistory`
(
`Id` BIGINT(20) NOT NULL,
`DiscordId` BIGINT(20) NOT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_ServersUpdate`;
CREATE TRIGGER `TR_ServersUpdate`
AFTER UPDATE
ON `Servers`
FOR EACH ROW
BEGIN
INSERT INTO `ServersHistory` (
`Id`, `DiscordId`, `DateFrom`, `DateTo`
)
VALUES (
OLD.ServerId, OLD.DiscordServerId, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_ServersDelete`;
CREATE TRIGGER `TR_ServersDelete`
AFTER DELETE
ON `Servers`
FOR EACH ROW
BEGIN
INSERT INTO `ServersHistory` (
`Id`, `DiscordId`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.ServerId, OLD.DiscordServerId, TRUE, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,46 +0,0 @@
ALTER TABLE `UserGameIdents`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `UserGameIdents`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `UserGameIdentsHistory`
(
`Id` BIGINT(20) NOT NULL,
`UserId` BIGINT(20) NOT NULL,
`GameServerId` BIGINT(20) NOT NULL,
`Ident` VARCHAR(255) NOT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_UserGameIdentsUpdate`;
CREATE TRIGGER `TR_UserGameIdentsUpdate`
AFTER UPDATE
ON `UserGameIdents`
FOR EACH ROW
BEGIN
INSERT INTO `UserGameIdentsHistory` (
`Id`, `UserId`, `GameServerId`, `Ident`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.UserId, OLD.GameServerId, OLD.Ident, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_UserGameIdentsDelete`;
CREATE TRIGGER `TR_UserGameIdentsDelete`
AFTER DELETE
ON `UserGameIdents`
FOR EACH ROW
BEGIN
INSERT INTO `UserGameIdentsHistory` (
`Id`, `UserId`, `GameServerId`, `Ident`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.UserId, OLD.GameServerId, OLD.Ident, TRUE, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,47 +0,0 @@
ALTER TABLE `UserJoinedGameServer`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `UserJoinedGameServer`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `UserJoinedGameServerHistory`
(
`Id` BIGINT(20) NOT NULL,
`UserId` BIGINT(20) NOT NULL,
`GameServerId` BIGINT(20) NOT NULL,
`JoinedOn` DATETIME(6) NOT NULL,
`LeavedOn` DATETIME(6) DEFAULT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_UserJoinedGameServerUpdate`;
CREATE TRIGGER `TR_UserJoinedGameServerUpdate`
AFTER UPDATE
ON `UserJoinedGameServer`
FOR EACH ROW
BEGIN
INSERT INTO `UserJoinedGameServerHistory` (
`Id`, `UserId`, `GameServerId`, `JoinedOn`, `LeavedOn`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.UserId, OLD.GameServerId, OLD.JoinedOn, OLD.LeavedOn, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_UserJoinedGameServerDelete`;
CREATE TRIGGER `TR_UserJoinedGameServerDelete`
AFTER DELETE
ON `UserJoinedGameServer`
FOR EACH ROW
BEGIN
INSERT INTO `UserJoinedGameServerHistory` (
`Id`, `UserId`, `GameServerId`, `JoinedOn`, `LeavedOn`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.UserId, OLD.GameServerId, OLD.JoinedOn, OLD.LeavedOn, TRUE, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,46 +0,0 @@
ALTER TABLE `UserJoinedServers`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `UserJoinedServers`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `UserJoinedServersHistory`
(
`Id` BIGINT(20) NOT NULL,
`UserId` BIGINT(20) NOT NULL,
`JoinedOn` DATETIME(6) NOT NULL,
`LeavedOn` DATETIME(6) DEFAULT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_UserJoinedServersUpdate`;
CREATE TRIGGER `TR_UserJoinedServersUpdate`
AFTER UPDATE
ON `UserJoinedServers`
FOR EACH ROW
BEGIN
INSERT INTO `UserJoinedServersHistory` (
`Id`, `UserId`, `JoinedOn`, `LeavedOn`, `DateFrom`, `DateTo`
)
VALUES (
OLD.JoinId, OLD.UserId, OLD.JoinedOn, OLD.LeavedOn, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_UserJoinedServersDelete`;
CREATE TRIGGER `TR_UserJoinedServersDelete`
AFTER DELETE
ON `UserJoinedServers`
FOR EACH ROW
BEGIN
INSERT INTO `UserJoinedServersHistory` (
`Id`, `UserId`, `JoinedOn`, `LeavedOn`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.JoinId, OLD.UserId, OLD.JoinedOn, OLD.LeavedOn, TRUE, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,49 +0,0 @@
ALTER TABLE `UserJoinedVoiceChannel`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `UserJoinedVoiceChannel`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `UserJoinedVoiceChannelHistory`
(
`Id` BIGINT(20) NOT NULL,
`UserId` BIGINT(20) NOT NULL,
`DiscordChannelId` BIGINT(20) NOT NULL,
`JoinedOn` DATETIME(6) NOT NULL,
`LeavedOn` DATETIME(6) DEFAULT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_UserJoinedVoiceChannelUpdate`;
CREATE TRIGGER `TR_UserJoinedVoiceChannelUpdate`
AFTER UPDATE
ON `UserJoinedVoiceChannel`
FOR EACH ROW
BEGIN
INSERT INTO `UserJoinedVoiceChannelHistory` (
`Id`, `UserId`, `DiscordChannelId`, `JoinedOn`, `LeavedOn`, `DateFrom`, `DateTo`
)
VALUES (
OLD.JoinId, OLD.UserId, OLD.DiscordChannelId, OLD.JoinedOn, OLD.LeavedOn, OLD.LastModifiedAt,
CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_UserJoinedVoiceChannelDelete`;
CREATE TRIGGER `TR_UserJoinedVoiceChannelDelete`
AFTER DELETE
ON `UserJoinedVoiceChannel`
FOR EACH ROW
BEGIN
INSERT INTO `UserJoinedVoiceChannelHistory` (
`Id`, `UserId`, `DiscordChannelId`, `JoinedOn`, `LeavedOn`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.JoinId, OLD.UserId, OLD.DiscordChannelId, OLD.JoinedOn, OLD.LeavedOn, TRUE, OLD.LastModifiedAt,
CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,47 +0,0 @@
ALTER TABLE `UserMessageCountPerHour`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `UserMessageCountPerHour`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `UserMessageCountPerHourHistory`
(
`Id` BIGINT(20) NOT NULL,
`Date` DATETIME(6) NOT NULL,
`Hour` BIGINT(20) DEFAULT NULL,
`XPCount` BIGINT(20) DEFAULT NULL,
`UserId` BIGINT(20) DEFAULT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_UserMessageCountPerHourUpdate`;
CREATE TRIGGER `TR_UserMessageCountPerHourUpdate`
AFTER UPDATE
ON `UserMessageCountPerHour`
FOR EACH ROW
BEGIN
INSERT INTO `UserMessageCountPerHourHistory` (
`Id`, `UserId`, `Date`, `Hour`, `XPCount`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.UserId, OLD.Date, OLD.Hour, OLD.XPCount, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_UserMessageCountPerHourDelete`;
CREATE TRIGGER `TR_UserMessageCountPerHourDelete`
AFTER DELETE
ON `UserMessageCountPerHour`
FOR EACH ROW
BEGIN
INSERT INTO `UserMessageCountPerHourHistory` (
`Id`, `UserId`, `Date`, `Hour`, `XPCount`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.UserId, OLD.Date, OLD.Hour, OLD.XPCount, TRUE, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,46 +0,0 @@
ALTER TABLE `UserWarnings`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `UserWarnings`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `UserWarningsHistory`
(
`Id` BIGINT(20) NOT NULL,
`Description` VARCHAR(255) NOT NULL,
`UserId` BIGINT(20) NOT NULL,
`Author` BIGINT(20) DEFAULT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_UserWarningsUpdate`;
CREATE TRIGGER `TR_UserWarningsUpdate`
AFTER UPDATE
ON `UserWarnings`
FOR EACH ROW
BEGIN
INSERT INTO `UserWarningsHistory` (
`Id`, `Description`, `UserId`, `Author`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.Description, OLD.UserId, OLD.Author, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_UserWarningsDelete`;
CREATE TRIGGER `TR_UserWarningsDelete`
AFTER DELETE
ON `UserWarnings`
FOR EACH ROW
BEGIN
INSERT INTO `UserWarningsHistory` (
`Id`, `Description`, `UserId`, `Author`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.Id, OLD.Description, OLD.UserId, OLD.Author, TRUE, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,46 +0,0 @@
ALTER TABLE `Users`
CHANGE `CreatedAt` `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6);
ALTER TABLE `Users`
CHANGE `LastModifiedAt` `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6);
CREATE TABLE IF NOT EXISTS `UsersHistory`
(
`Id` BIGINT(20) NOT NULL,
`DiscordId` BIGINT(20) NOT NULL,
`XP` BIGINT(20) NOT NULL DEFAULT 0,
`ServerId` BIGINT(20) DEFAULT NULL,
`Deleted` BOOL DEFAULT FALSE,
`DateFrom` DATETIME(6) NOT NULL,
`DateTo` DATETIME(6) NOT NULL
);
DROP TRIGGER IF EXISTS `TR_UsersUpdate`;
CREATE TRIGGER `TR_UsersUpdate`
AFTER UPDATE
ON `Users`
FOR EACH ROW
BEGIN
INSERT INTO `UsersHistory` (
`Id`, `DiscordId`, `XP`, `ServerId`, `DateFrom`, `DateTo`
)
VALUES (
OLD.UserId, OLD.DiscordId, OLD.XP, OLD.ServerId, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;
DROP TRIGGER IF EXISTS `TR_UsersDelete`;
CREATE TRIGGER `TR_UsersDelete`
AFTER DELETE
ON `Users`
FOR EACH ROW
BEGIN
INSERT INTO `UsersHistory` (
`Id`, `DiscordId`, `XP`, `ServerId`, `Deleted`, `DateFrom`, `DateTo`
)
VALUES (
OLD.UserId, OLD.DiscordId, OLD.XP, OLD.ServerId, TRUE, OLD.LastModifiedAt, CURRENT_TIMESTAMP(6)
);
END;

View File

@@ -1,43 +0,0 @@
from bot_core.logging.database_logger import DatabaseLogger
from bot_data.abc.migration_abc import MigrationABC
from bot_data.db_context import DBContext
class RemoveStatsMigration(MigrationABC):
name = "1.0.0_RemoveStatsMigration"
def __init__(self, logger: DatabaseLogger, db: DBContext):
MigrationABC.__init__(self)
self._logger = logger
self._db = db
self._cursor = db.cursor
def upgrade(self):
self._logger.debug(__name__, "Running upgrade")
self._cursor.execute(
str(
f"""
DROP TABLE IF EXISTS `Statistics`;
"""
)
)
def downgrade(self):
self._cursor.execute(
str(
f"""
CREATE TABLE IF NOT EXISTS `Statistics` (
`Id` BIGINT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(255) NOT NULL,
`Description` VARCHAR(255) NOT NULL,
`Code` LONGTEXT NOT NULL,
`ServerId` BIGINT,
`CreatedAt` DATETIME(6),
`LastModifiedAt` DATETIME(6),
PRIMARY KEY(`Id`),
FOREIGN KEY (`ServerId`) REFERENCES `Servers`(`ServerId`)
);
"""
)
)

View File

@@ -4,7 +4,7 @@ from bot_data.db_context import DBContext
class UserJoinedGameServerMigration(MigrationABC): class UserJoinedGameServerMigration(MigrationABC):
name = "1.0.0_UserJoinedGameServerMigration" name = "1.0_UserJoinedGameServerMigration"
def __init__(self, logger: DatabaseLogger, db: DBContext): def __init__(self, logger: DatabaseLogger, db: DBContext):
MigrationABC.__init__(self) MigrationABC.__init__(self)
@@ -18,34 +18,15 @@ class UserJoinedGameServerMigration(MigrationABC):
self._cursor.execute( self._cursor.execute(
str( str(
f""" f"""
CREATE TABLE IF NOT EXISTS `GameServers` ( CREATE TABLE IF NOT EXISTS `UserJoinedGameServer` (
`Id` BIGINT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(255) NOT NULL,
`ServerId` BIGINT NOT NULL,
`ApiKeyId` BIGINT NOT NULL,
`CreatedAt` DATETIME(6),
`LastModifiedAt` DATETIME(6),
FOREIGN KEY (`ServerId`) REFERENCES Servers(`ServerId`),
FOREIGN KEY (`ApiKeyId`) REFERENCES ApiKeys(`Id`),
PRIMARY KEY(`Id`)
);
"""
)
)
self._cursor.execute(
str(
f"""
CREATE TABLE IF NOT EXISTS `UserJoinedGameServer` (
`Id` BIGINT NOT NULL AUTO_INCREMENT, `Id` BIGINT NOT NULL AUTO_INCREMENT,
`UserId` BIGINT NOT NULL, `UserId` BIGINT NOT NULL,
`GameServerId` BIGINT NOT NULL, `GameServer` VARCHAR(255) NOT NULL,
`JoinedOn` DATETIME(6) NOT NULL, `JoinedOn` DATETIME(6) NOT NULL,
`LeavedOn` DATETIME(6), `LeavedOn` DATETIME(6),
`CreatedAt` DATETIME(6), `CreatedAt` DATETIME(6),
`LastModifiedAt` DATETIME(6), `LastModifiedAt` DATETIME(6),
FOREIGN KEY (`UserId`) REFERENCES Users(`UserId`), FOREIGN KEY (`UserId`) REFERENCES Users(`UserId`),
FOREIGN KEY (`GameServerId`) REFERENCES GameServers(`Id`),
PRIMARY KEY(`Id`) PRIMARY KEY(`Id`)
); );
""" """
@@ -55,23 +36,17 @@ class UserJoinedGameServerMigration(MigrationABC):
self._cursor.execute( self._cursor.execute(
str( str(
f""" f"""
CREATE TABLE IF NOT EXISTS `UserGameIdents` ( ALTER TABLE Users ADD MinecraftId VARCHAR(255) NULL AFTER XP;
`Id` BIGINT NOT NULL AUTO_INCREMENT,
`UserId` BIGINT NOT NULL,
`GameServerId` BIGINT NOT NULL,
`Ident` VARCHAR(255) NOT NULL,
`CreatedAt` DATETIME(6),
`LastModifiedAt` DATETIME(6),
FOREIGN KEY (`UserId`) REFERENCES Users(`UserId`),
FOREIGN KEY (`GameServerId`) REFERENCES GameServers(`Id`),
CONSTRAINT UC_UserGameIdent UNIQUE (`GameServerId`,`Ident`),
PRIMARY KEY(`Id`)
);
""" """
) )
) )
def downgrade(self): def downgrade(self):
self._cursor.execute("DROP TABLE `GameServers`;")
self._cursor.execute("DROP TABLE `UserJoinedGameServer`;") self._cursor.execute("DROP TABLE `UserJoinedGameServer`;")
self._cursor.execute("DROP TABLE `UserGameIdents`;") self._cursor.execute(
str(
f"""
ALTER TABLE Users DROP COLUMN MinecraftId;
"""
)
)

View File

@@ -1,37 +0,0 @@
from bot_core.logging.database_logger import DatabaseLogger
from bot_data.abc.migration_abc import MigrationABC
from bot_data.db_context import DBContext
class UserWarningMigration(MigrationABC):
name = "1.0.0_UserWarningMigration"
def __init__(self, logger: DatabaseLogger, db: DBContext):
MigrationABC.__init__(self)
self._logger = logger
self._db = db
self._cursor = db.cursor
def upgrade(self):
self._logger.debug(__name__, "Running upgrade")
self._cursor.execute(
str(
f"""
CREATE TABLE IF NOT EXISTS `UserWarnings` (
`Id` BIGINT NOT NULL AUTO_INCREMENT,
`Description` VARCHAR(255) NOT NULL,
`UserId` BIGINT NOT NULL,
`Author` BIGINT NULL,
`CreatedAt` DATETIME(6),
`LastModifiedAt` DATETIME(6),
PRIMARY KEY(`Id`),
FOREIGN KEY (`UserId`) REFERENCES `Users`(`UserId`),
FOREIGN KEY (`Author`) REFERENCES `Users`(`UserId`)
);
"""
)
)
def downgrade(self):
self._cursor.execute("DROP TABLE `UserWarnings`;")

View File

@@ -15,7 +15,7 @@ __title__ = "bot_data.model"
__author__ = "Sven Heidemann" __author__ = "Sven Heidemann"
__license__ = "MIT" __license__ = "MIT"
__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" __copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de"
__version__ = "1.0.5" __version__ = "0.3.1"
from collections import namedtuple from collections import namedtuple
@@ -23,4 +23,4 @@ from collections import namedtuple
# imports # imports
VersionInfo = namedtuple("VersionInfo", "major minor micro") VersionInfo = namedtuple("VersionInfo", "major minor micro")
version_info = VersionInfo(major="1", minor="0", micro="5") version_info = VersionInfo(major="0", minor="3", micro="1")

View File

@@ -25,10 +25,6 @@ class ApiKey(TableABC):
self._created_at = created_at if created_at is not None else self._created_at self._created_at = created_at if created_at is not None else self._created_at
self._modified_at = modified_at if modified_at is not None else self._modified_at self._modified_at = modified_at if modified_at is not None else self._modified_at
@property
def id(self) -> int:
return self._id
@property @property
def identifier(self) -> str: def identifier(self) -> str:
return self._identifier return self._identifier
@@ -59,15 +55,6 @@ class ApiKey(TableABC):
""" """
) )
@staticmethod
def get_select_by_id(id: int) -> str:
return str(
f"""
SELECT * FROM `ApiKeys`
WHERE `Id` = {id};
"""
)
@staticmethod @staticmethod
def get_select_by_key(key: str) -> str: def get_select_by_key(key: str) -> str:
return str( return str(
@@ -82,11 +69,13 @@ class ApiKey(TableABC):
return str( return str(
f""" f"""
INSERT INTO `ApiKeys` ( INSERT INTO `ApiKeys` (
`Identifier`, `Key`, `CreatorId` `Identifier`, `Key`, `CreatorId`, `CreatedAt`, `LastModifiedAt`
) VALUES ( ) VALUES (
'{self._identifier}', '{self._identifier}',
'{self._key}', '{self._key}',
{"NULL" if self._creator is None else f"'{self._creator.id}'"} {"NULL" if self._creator is None else self._creator.id},
'{self._created_at}',
'{self._modified_at}'
); );
""" """
) )
@@ -98,7 +87,7 @@ class ApiKey(TableABC):
UPDATE `ApiKeys` UPDATE `ApiKeys`
SET `Identifier` = '{self._identifier}', SET `Identifier` = '{self._identifier}',
`Key` = '{self._key}', `Key` = '{self._key}',
`CreatorId` = {"NULL" if self._creator is None else f"'{self._creator.id}'"} `LastModifiedAt` = '{self._modified_at}'
WHERE `Id` = {self._id}; WHERE `Id` = {self._id};
""" """
) )

View File

@@ -220,21 +220,25 @@ class AuthUser(TableABC):
`ForgotPasswordId`, `ForgotPasswordId`,
`OAuthId`, `OAuthId`,
`RefreshTokenExpiryTime`, `RefreshTokenExpiryTime`,
`AuthRole` `AuthRole`,
) VALUES ( `CreatedAt`,
{self._auth_user_id}, `LastModifiedAt`
'{self._first_name}', ) VALUES (
'{self._last_name}', {self._auth_user_id},
'{self._email}', '{self._first_name}',
'{self._password}', '{self._last_name}',
'{self._password_salt}', '{self._email}',
{"NULL" if self._refresh_token is None else f"'{self._refresh_token}'"}, '{self._password}',
{"NULL" if self._confirmation_id is None else f"'{self._confirmation_id}'"}, '{self._password_salt}',
{"NULL" if self._forgot_password_id is None else f"'{self._forgot_password_id}'"}, '{"NULL" if self._refresh_token is None else self._refresh_token}',
{"NULL" if self._oauth_id is None else f"'{self._oauth_id}'"}, '{"NULL" if self._confirmation_id is None else self._confirmation_id}',
'{self._refresh_token_expire_time.isoformat()}', '{"NULL" if self._forgot_password_id is None else self._forgot_password_id}',
{self._auth_role_id.value} '{"NULL" if self._oauth_id is None else self._oauth_id}',
) '{self._refresh_token_expire_time.isoformat()}',
{self._auth_role_id.value},
'{self._created_at}',
'{self._modified_at}'
)
""" """
) )
@@ -248,12 +252,13 @@ class AuthUser(TableABC):
`EMail` = '{self._email}', `EMail` = '{self._email}',
`Password` = '{self._password}', `Password` = '{self._password}',
`PasswordSalt` = '{self._password_salt}', `PasswordSalt` = '{self._password_salt}',
`RefreshToken` = {"NULL" if self._refresh_token is None else f"'{self._refresh_token}'"}, {f"`RefreshToken` = ''," if self._refresh_token is not None else ''}
`ConfirmationId` = {"NULL" if self._confirmation_id is None else f"'{self._confirmation_id}'"}, {f"`ConfirmationId` = ''," if self._confirmation_id is not None else ''}
`ForgotPasswordId` = {"NULL" if self._forgot_password_id is None else f"'{self._forgot_password_id}'"}, {f"`ForgotPasswordId` = ''," if self._forgot_password_id is not None else ''}
`OAuthId` = {"NULL" if self._oauth_id is None else f"'{self._oauth_id}'"}, {f"`OAuthId` = ''," if self._oauth_id is not None else ''}
`RefreshTokenExpiryTime` = '{self._refresh_token_expire_time.isoformat()}', `RefreshTokenExpiryTime` = '{self._refresh_token_expire_time.isoformat()}',
`AuthRole` = {self._auth_role_id.value} `AuthRole` = {self._auth_role_id.value},
`LastModifiedAt` = '{self._modified_at}'
WHERE `AuthUsers`.`Id` = {self._auth_user_id}; WHERE `AuthUsers`.`Id` = {self._auth_user_id};
""" """
) )

Some files were not shown because too many files have changed in this diff Show More