diff --git a/.gitea/workflows/deploy_dev.yaml b/.gitea/workflows/deploy_dev.yaml index 7d1db445..5b7485a1 100644 --- a/.gitea/workflows/deploy_dev.yaml +++ b/.gitea/workflows/deploy_dev.yaml @@ -24,17 +24,17 @@ jobs: uses: https://github.com/actions/checkout@v3 - name: Shutdown stack - run: docker stack rm kdb_staging + run: docker stack rm sdb_staging - name: Prepare bot build run: | - cd kdb-bot + cd bot pip install --extra-index-url https://pip.sh-edraft.de cpl-cli cpl i - name: Build docker bot run: | - cd kdb-bot + cd bot docker image prune -f cpl docker-build @@ -43,13 +43,13 @@ jobs: - name: Prepare web build run: | - cd kdb-web + cd web npm install -g ts-node npm i - name: Build docker web run: | - cd kdb-web + cd web docker image prune -f npm run docker-build @@ -60,6 +60,6 @@ jobs: portainer-username: "gitea_job" portainer-password: "${{ secrets.docker_job }}" portainer-endpoint: 2 - name: kdb_staging + name: sdb_staging file: ./docker-compose.staging.yml variables: '{}' diff --git a/.gitea/workflows/deploy_prod.yaml b/.gitea/workflows/deploy_prod.yaml index 08273018..bf530ed8 100644 --- a/.gitea/workflows/deploy_prod.yaml +++ b/.gitea/workflows/deploy_prod.yaml @@ -24,17 +24,17 @@ jobs: uses: https://github.com/actions/checkout@v3 - name: Shutdown stack - run: docker stack rm kdb_prod + run: docker stack rm sdb_prod - name: Prepare bot build run: | - cd kdb-bot + cd bot pip install --extra-index-url https://pip.sh-edraft.de cpl-cli cpl i - name: Build docker bot run: | - cd kdb-bot + cd bot docker image prune -f cpl docker-build @@ -43,13 +43,13 @@ jobs: - name: Prepare web build run: | - cd kdb-web + cd web npm install -g ts-node npm i - name: Build docker web run: | - cd kdb-web + cd web docker image prune -f npm run docker-build @@ -60,6 +60,6 @@ jobs: portainer-username: "gitea_job" portainer-password: "${{ secrets.docker_job }}" portainer-endpoint: 2 - name: kdb_prod + name: sdb_prod file: ./docker-compose.yml variables: '{}' diff --git a/bot/cpl-workspace.json b/bot/cpl-workspace.json index 833b19a0..d08ceb87 100644 --- a/bot/cpl-workspace.json +++ b/bot/cpl-workspace.json @@ -32,12 +32,12 @@ "pre-build": "cpl set-version $ARGS; black ./;", "post-build": "cpl run post-build --dev; black ./;", "pre-prod": "cpl build", - "prod": "export KDB_ENVIRONMENT=production; export KDB_NAME=KDB-Prod; cpl start;", + "prod": "export SDB_ENVIRONMENT=production; export SDB_NAME=SDB-Prod; cpl start;", "pre-stage": "cpl build", - "stage": "export KDB_ENVIRONMENT=staging; export KDB_NAME=KDB-Stage; cpl start;", + "stage": "export SDB_ENVIRONMENT=staging; export SDB_NAME=SDB-Stage; cpl start;", "pre-dev": "cpl build", - "dev": "export KDB_ENVIRONMENT=development; export KDB_NAME=KDB-Dev; cpl start;", - "docker-build": "cpl build $ARGS; docker build -t sh-edraft.de/kdb-bot:$(cpl gv) .;", + "dev": "export SDB_ENVIRONMENT=development; export SDB_NAME=SDB-Dev; cpl start;", + "docker-build": "cpl build $ARGS; docker build -t sh-edraft.de/sdb-bot:$(cpl gv) .;", "dc-up": "docker-compose up -d", "dc-down": "docker-compose down", "docker": "cpl dc-down; cpl docker-build; cpl dc-up;" diff --git a/bot/dockerfile b/bot/dockerfile index 478bf7e7..ad507c89 100644 --- a/bot/dockerfile +++ b/bot/dockerfile @@ -2,7 +2,7 @@ FROM python:3.10.4-alpine WORKDIR /app -COPY ./dist/bot/build/kdb-bot/ . +COPY ./dist/bot/build/bot/ . COPY ./dist/bot/build/requirements.txt . RUN python -m pip install --upgrade pip diff --git a/bot/src/bot/application.py b/bot/src/bot/application.py index 4d57ff59..6d1e4dd9 100644 --- a/bot/src/bot/application.py +++ b/bot/src/bot/application.py @@ -23,25 +23,17 @@ class Application(DiscordBotApplicationABC): # cpl-core self._logger: LoggerABC = services.get_service(LoggerABC) - self._data_integrity: DataIntegrityService = services.get_service( - DataIntegrityService - ) + self._data_integrity: DataIntegrityService = services.get_service(DataIntegrityService) # cpl-discord self._bot: DiscordBotServiceABC = services.get_service(DiscordBotServiceABC) - self._bot_settings: DiscordBotSettings = config.get_configuration( - DiscordBotSettings - ) + self._bot_settings: DiscordBotSettings = config.get_configuration(DiscordBotSettings) # cpl-translation - self._translation: TranslationServiceABC = services.get_service( - TranslationServiceABC - ) + self._translation: TranslationServiceABC = services.get_service(TranslationServiceABC) self._t: TranslatePipe = services.get_service(TranslatePipe) # internal stuff self._tasks = services.get_services(TaskABC) - self._feature_flags: FeatureFlagsSettings = config.get_configuration( - FeatureFlagsSettings - ) + self._feature_flags: FeatureFlagsSettings = config.get_configuration(FeatureFlagsSettings) # api if self._feature_flags.get_flag(FeatureFlagsEnum.api_module): @@ -50,9 +42,7 @@ class Application(DiscordBotApplicationABC): self._is_stopping = False async def configure(self): - self._translation.load_by_settings( - self._configuration.get_configuration(TranslationSettings) - ) + self._translation.load_by_settings(self._configuration.get_configuration(TranslationSettings)) async def main(self): try: @@ -95,8 +85,4 @@ class Application(DiscordBotApplicationABC): Console.write_line() def is_restart(self): - return ( - True - if self._configuration.get_configuration("IS_RESTART") == "true" - else False - ) + return True if self._configuration.get_configuration("IS_RESTART") == "true" else False diff --git a/bot/src/bot/extension/init_bot_extension.py b/bot/src/bot/extension/init_bot_extension.py index c0a2feef..04a4fcf0 100644 --- a/bot/src/bot/extension/init_bot_extension.py +++ b/bot/src/bot/extension/init_bot_extension.py @@ -13,6 +13,4 @@ class InitBotExtension(ApplicationExtensionABC): async def run(self, config: ConfigurationABC, services: ServiceProviderABC): settings = config.get_configuration(TechnicianConfig) - bot: DiscordBotServiceABC = services.get_service( - DiscordBotServiceABC, max_messages=settings.cache_max_messages - ) + bot: DiscordBotServiceABC = services.get_service(DiscordBotServiceABC, max_messages=settings.cache_max_messages) diff --git a/bot/src/bot/startup.py b/bot/src/bot/startup.py index 8e52249f..0a5422d2 100644 --- a/bot/src/bot/startup.py +++ b/bot/src/bot/startup.py @@ -50,9 +50,7 @@ class Startup(StartupABC): services.add_singleton(CustomFileLoggerABC, ApiLogger) services.add_translation() - services.add_db_context( - DBContext, self._config.get_configuration(DatabaseSettings) - ) + services.add_db_context(DBContext, self._config.get_configuration(DatabaseSettings)) provider = services.build_service_provider() # instantiate custom logger diff --git a/bot/src/bot/startup_discord_extension.py b/bot/src/bot/startup_discord_extension.py index 73411881..196017dc 100644 --- a/bot/src/bot/startup_discord_extension.py +++ b/bot/src/bot/startup_discord_extension.py @@ -9,13 +9,9 @@ class StartupDiscordExtension(StartupExtensionABC): def __init__(self): pass - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): pass - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): services.add_discord() dcc = get_discord_collection(services) diff --git a/bot/src/bot/startup_migration_extension.py b/bot/src/bot/startup_migration_extension.py index a874e2f4..206262fb 100644 --- a/bot/src/bot/startup_migration_extension.py +++ b/bot/src/bot/startup_migration_extension.py @@ -41,66 +41,30 @@ class StartupMigrationExtension(StartupExtensionABC): def __init__(self): pass - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): pass - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): services.add_transient(MigrationService) services.add_transient(MigrationABC, InitialMigration) - services.add_transient( - MigrationABC, AutoRoleMigration - ) # 03.10.2022 #54 - 0.2.2 + services.add_transient(MigrationABC, AutoRoleMigration) # 03.10.2022 #54 - 0.2.2 services.add_transient(MigrationABC, ApiMigration) # 15.10.2022 #70 - 0.3.0 services.add_transient(MigrationABC, LevelMigration) # 06.11.2022 #25 - 0.3.0 services.add_transient(MigrationABC, StatsMigration) # 09.11.2022 #46 - 0.3.0 - services.add_transient( - MigrationABC, AutoRoleFix1Migration - ) # 30.12.2022 #151 - 0.3.0 - services.add_transient( - MigrationABC, UserMessageCountPerHourMigration - ) # 11.01.2023 #168 - 0.3.1 + services.add_transient(MigrationABC, AutoRoleFix1Migration) # 30.12.2022 #151 - 0.3.0 + 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, UserJoinedGameServerMigration - ) # 12.02.2023 #181 - 1.0.0 - services.add_transient( - MigrationABC, RemoveStatsMigration - ) # 19.02.2023 #190 - 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 - services.add_transient( - MigrationABC, AchievementsMigration - ) # 14.06.2023 #268 - 1.1.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, UserWarningMigration) # 21.02.2023 #35 - 1.0.0 + services.add_transient(MigrationABC, DBHistoryMigration) # 06.03.2023 #246 - 1.0.0 + services.add_transient(MigrationABC, AchievementsMigration) # 14.06.2023 #268 - 1.1.0 services.add_transient(MigrationABC, ConfigMigration) # 19.07.2023 #127 - 1.1.0 - services.add_transient( - MigrationABC, ConfigFeatureFlagsMigration - ) # 15.08.2023 #334 - 1.1.0 - services.add_transient( - MigrationABC, DefaultRoleMigration - ) # 24.09.2023 #360 - 1.1.3 - services.add_transient( - MigrationABC, ShortRoleNameMigration - ) # 28.09.2023 #378 - 1.1.7 - services.add_transient( - MigrationABC, FixUpdatesMigration - ) # 28.09.2023 #378 - 1.1.7 - services.add_transient( - MigrationABC, ShortRoleNameOnlyHighestMigration - ) # 02.10.2023 #391 - 1.1.9 - services.add_transient( - MigrationABC, FixUserHistoryMigration - ) # 10.10.2023 #401 - 1.2.0 - services.add_transient( - MigrationABC, BirthdayMigration - ) # 10.10.2023 #401 - 1.2.0 - services.add_transient( - MigrationABC, SteamSpecialOfferMigration - ) # 10.10.2023 #188 - 1.2.0 + services.add_transient(MigrationABC, ConfigFeatureFlagsMigration) # 15.08.2023 #334 - 1.1.0 + services.add_transient(MigrationABC, DefaultRoleMigration) # 24.09.2023 #360 - 1.1.3 + services.add_transient(MigrationABC, ShortRoleNameMigration) # 28.09.2023 #378 - 1.1.7 + services.add_transient(MigrationABC, FixUpdatesMigration) # 28.09.2023 #378 - 1.1.7 + services.add_transient(MigrationABC, ShortRoleNameOnlyHighestMigration) # 02.10.2023 #391 - 1.1.9 + services.add_transient(MigrationABC, FixUserHistoryMigration) # 10.10.2023 #401 - 1.2.0 + services.add_transient(MigrationABC, BirthdayMigration) # 10.10.2023 #401 - 1.2.0 + services.add_transient(MigrationABC, SteamSpecialOfferMigration) # 10.10.2023 #188 - 1.2.0 diff --git a/bot/src/bot/startup_module_extension.py b/bot/src/bot/startup_module_extension.py index c3f1789e..2d87319d 100644 --- a/bot/src/bot/startup_module_extension.py +++ b/bot/src/bot/startup_module_extension.py @@ -18,15 +18,11 @@ class StartupModuleExtension(StartupExtensionABC): self._modules = ModuleList.get_modules() - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): self._config = config self._feature_flags = config.get_configuration(FeatureFlagsSettings) - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): provider = services.build_service_provider() dc_collection: DiscordCollectionABC = provider.get_service(DiscordCollectionABC) diff --git a/bot/src/bot/startup_settings_extension.py b/bot/src/bot/startup_settings_extension.py index ad45ee9b..caf34f19 100644 --- a/bot/src/bot/startup_settings_extension.py +++ b/bot/src/bot/startup_settings_extension.py @@ -14,38 +14,26 @@ class StartupSettingsExtension(StartupExtensionABC): def __init__(self): self._start_time = datetime.now() - def configure_configuration( - self, configuration: ConfigurationABC, environment: ApplicationEnvironmentABC - ): + def configure_configuration(self, configuration: ConfigurationABC, environment: ApplicationEnvironmentABC): # this shit has to be done here because we need settings in subsequent startup extensions environment.set_working_directory(os.path.dirname(os.path.realpath(__file__))) configuration.add_environment_variables("KDB_") configuration.add_environment_variables("DISCORD_") configuration.add_json_file(f"config/appsettings.json", optional=False) - configuration.add_json_file( - f"config/appsettings.{environment.environment_name}.json", optional=True - ) - configuration.add_json_file( - f"config/appsettings.{environment.host_name}.json", optional=True - ) + configuration.add_json_file(f"config/appsettings.{environment.environment_name}.json", optional=True) + configuration.add_json_file(f"config/appsettings.{environment.host_name}.json", optional=True) # load feature-flags configuration.add_json_file(f"config/feature-flags.json", optional=False) - configuration.add_json_file( - f"config/feature-flags.{environment.environment_name}.json", optional=True - ) - configuration.add_json_file( - f"config/feature-flags.{environment.host_name}.json", optional=True - ) + configuration.add_json_file(f"config/feature-flags.{environment.environment_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)) self._configure_settings_with_sub_settings( 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 @staticmethod @@ -57,6 +45,4 @@ class StartupSettingsExtension(StartupExtensionABC): return for sub_settings in list_atr(settings): - config.add_configuration( - f"{type(sub_settings).__name__}_{atr(sub_settings)}", sub_settings - ) + config.add_configuration(f"{type(sub_settings).__name__}_{atr(sub_settings)}", sub_settings) diff --git a/bot/src/bot_api/abc/auth_service_abc.py b/bot/src/bot_api/abc/auth_service_abc.py index 812b3c30..1ba5fbbb 100644 --- a/bot/src/bot_api/abc/auth_service_abc.py +++ b/bot/src/bot_api/abc/auth_service_abc.py @@ -40,15 +40,11 @@ class AuthServiceABC(ABC): pass @abstractmethod - async def get_filtered_auth_users_async( - self, criteria: AuthUserSelectCriteria - ) -> AuthUserFilteredResultDTO: + async def get_filtered_auth_users_async(self, criteria: AuthUserSelectCriteria) -> AuthUserFilteredResultDTO: pass @abstractmethod - async def get_auth_user_by_email_async( - self, email: str, with_password: bool = False - ) -> AuthUserDTO: + async def get_auth_user_by_email_async(self, email: str, with_password: bool = False) -> AuthUserDTO: pass @abstractmethod diff --git a/bot/src/bot_api/abc/select_criteria_abc.py b/bot/src/bot_api/abc/select_criteria_abc.py index 2c54df69..950b5203 100644 --- a/bot/src/bot_api/abc/select_criteria_abc.py +++ b/bot/src/bot_api/abc/select_criteria_abc.py @@ -3,9 +3,7 @@ from abc import ABC, abstractmethod class SelectCriteriaABC(ABC): @abstractmethod - def __init__( - self, page_index: int, page_size: int, sort_direction: str, sort_column: str - ): + def __init__(self, page_index: int, page_size: int, sort_direction: str, sort_column: str): self.page_index = page_index self.page_size = page_size self.sort_direction = sort_direction diff --git a/bot/src/bot_api/api.py b/bot/src/bot_api/api.py index 587f0503..84184695 100644 --- a/bot/src/bot_api/api.py +++ b/bot/src/bot_api/api.py @@ -57,9 +57,7 @@ class Api(Flask): # Added async_mode see link below # 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 = SocketIO(self, cors_allowed_origins="*", path="/api/socket.io", async_mode="eventlet") self._socketio.on_event("connect", self.on_connect) self._socketio.on_event("disconnect", self.on_disconnect) @@ -145,9 +143,7 @@ class Api(Flask): data = request.get_data() data = "" if len(data) == 0 else str(data.decode(encoding="utf-8")) - text = textwrap.dedent( - f"Request: {request_id}:\n\tHeader:\n\t\t{headers}\n\tResponse: {data}" - ) + text = textwrap.dedent(f"Request: {request_id}:\n\tHeader:\n\t\t{headers}\n\tResponse: {data}") self._logger.trace(__name__, text) return response @@ -162,9 +158,7 @@ class Api(Flask): # from waitress import serve # https://docs.pylonsproject.org/projects/waitress/en/stable/arguments.html # serve(self, host=self._apt_settings.host, port=self._apt_settings.port, threads=10, connection_limit=1000, channel_timeout=10) - self._socket = eventlet.listen( - (self._api_settings.host, self._api_settings.port) - ) + self._socket = eventlet.listen((self._api_settings.host, self._api_settings.port)) wsgi.server(self._socket, self, log_output=False) def stop(self): diff --git a/bot/src/bot_api/api_module.py b/bot/src/bot_api/api_module.py index 13a28547..b2695e12 100644 --- a/bot/src/bot_api/api_module.py +++ b/bot/src/bot_api/api_module.py @@ -26,21 +26,15 @@ class ApiModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.api_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): cwd = env.working_directory env.set_working_directory(os.path.dirname(os.path.realpath(__file__))) config.add_json_file(f"config/apisettings.json", optional=False) - config.add_json_file( - f"config/apisettings.{env.environment_name}.json", optional=True - ) + config.add_json_file(f"config/apisettings.{env.environment_name}.json", optional=True) config.add_json_file(f"config/apisettings.{env.host_name}.json", optional=True) env.set_working_directory(cwd) - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): services.add_singleton(EMailClientABC, EMailClient) services.add_singleton(ApiThread) diff --git a/bot/src/bot_api/app_api_extension.py b/bot/src/bot_api/app_api_extension.py index da1ac033..ea9fda56 100644 --- a/bot/src/bot_api/app_api_extension.py +++ b/bot/src/bot_api/app_api_extension.py @@ -12,9 +12,7 @@ class AppApiExtension(ApplicationExtensionABC): ApplicationExtensionABC.__init__(self) async def run(self, config: ConfigurationABC, services: ServiceProviderABC): - feature_flags: FeatureFlagsSettings = config.get_configuration( - FeatureFlagsSettings - ) + feature_flags: FeatureFlagsSettings = config.get_configuration(FeatureFlagsSettings) if not feature_flags.get_flag(FeatureFlagsEnum.api_module): return diff --git a/bot/src/bot_api/configuration/authentication_settings.py b/bot/src/bot_api/configuration/authentication_settings.py index 3dfb2442..b9c3fff2 100644 --- a/bot/src/bot_api/configuration/authentication_settings.py +++ b/bot/src/bot_api/configuration/authentication_settings.py @@ -16,9 +16,7 @@ class AuthenticationSettings(ConfigurationModelABC): self._issuer = "" if issuer is None else issuer self._audience = "" if audience is None else audience self._token_expire_time = 0 if token_expire_time is None else token_expire_time - self._refresh_token_expire_time = ( - 0 if refresh_token_expire_time is None else refresh_token_expire_time - ) + self._refresh_token_expire_time = 0 if refresh_token_expire_time is None else refresh_token_expire_time @property def secret_key(self) -> str: diff --git a/bot/src/bot_api/controller/auth_controller.py b/bot/src/bot_api/controller/auth_controller.py index b5970ce4..983b5fb9 100644 --- a/bot/src/bot_api/controller/auth_controller.py +++ b/bot/src/bot_api/controller/auth_controller.py @@ -70,9 +70,7 @@ class AuthController: @Route.post(f"{BasePath}/register") 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) return "", 200 @@ -83,9 +81,7 @@ class AuthController: @Route.post(f"{BasePath}/login") async def login(self) -> Response: - dto: AuthUserDTO = JSONProcessor.process( - AuthUserDTO, request.get_json(force=True, silent=True) - ) + dto: AuthUserDTO = JSONProcessor.process(AuthUserDTO, request.get_json(force=True, silent=True)) result = await self._auth_service.login_async(dto) return jsonify(result.to_dict()) @@ -114,52 +110,40 @@ class AuthController: @Route.post(f"{BasePath}/reset-password") async def reset_password(self): - dto: ResetPasswordDTO = JSONProcessor.process( - ResetPasswordDTO, request.get_json(force=True, silent=True) - ) + dto: ResetPasswordDTO = JSONProcessor.process(ResetPasswordDTO, request.get_json(force=True, silent=True)) await self._auth_service.reset_password_async(dto) return "", 200 @Route.post(f"{BasePath}/update-user") @Route.authorize async def update_user(self): - dto: UpdateAuthUserDTO = JSONProcessor.process( - UpdateAuthUserDTO, request.get_json(force=True, silent=True) - ) + dto: UpdateAuthUserDTO = JSONProcessor.process(UpdateAuthUserDTO, request.get_json(force=True, silent=True)) await self._auth_service.update_user_async(dto) return "", 200 @Route.post(f"{BasePath}/update-user-as-admin") @Route.authorize(role=AuthRoleEnum.admin) async def update_user_as_admin(self): - dto: UpdateAuthUserDTO = JSONProcessor.process( - UpdateAuthUserDTO, request.get_json(force=True, silent=True) - ) + dto: UpdateAuthUserDTO = JSONProcessor.process(UpdateAuthUserDTO, request.get_json(force=True, silent=True)) await self._auth_service.update_user_as_admin_async(dto) return "", 200 @Route.post(f"{BasePath}/refresh") 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) return jsonify(result.to_dict()) @Route.post(f"{BasePath}/revoke") async def revoke(self): - dto: TokenDTO = JSONProcessor.process( - TokenDTO, request.get_json(force=True, silent=True) - ) + dto: TokenDTO = JSONProcessor.process(TokenDTO, request.get_json(force=True, silent=True)) await self._auth_service.revoke_async(dto) return "", 200 @Route.post(f"{BasePath}/delete-user") @Route.authorize(role=AuthRoleEnum.admin) async def delete_user(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)) await self._auth_service.delete_auth_user_async(dto) return "", 200 diff --git a/bot/src/bot_api/filter/auth_user_select_criteria.py b/bot/src/bot_api/filter/auth_user_select_criteria.py index b19b8ead..eaa2ee7f 100644 --- a/bot/src/bot_api/filter/auth_user_select_criteria.py +++ b/bot/src/bot_api/filter/auth_user_select_criteria.py @@ -13,9 +13,7 @@ class AuthUserSelectCriteria(SelectCriteriaABC): email: str, auth_role: int, ): - SelectCriteriaABC.__init__( - self, page_index, page_size, sort_direction, sort_column - ) + SelectCriteriaABC.__init__(self, page_index, page_size, sort_direction, sort_column) self.first_name = first_name self.last_name = last_name diff --git a/bot/src/bot_api/filter/discord/server_select_criteria.py b/bot/src/bot_api/filter/discord/server_select_criteria.py index 73196b60..5f194809 100644 --- a/bot/src/bot_api/filter/discord/server_select_criteria.py +++ b/bot/src/bot_api/filter/discord/server_select_criteria.py @@ -10,8 +10,6 @@ class ServerSelectCriteria(SelectCriteriaABC): sort_column: str, name: str, ): - SelectCriteriaABC.__init__( - self, page_index, page_size, sort_direction, sort_column - ) + SelectCriteriaABC.__init__(self, page_index, page_size, sort_direction, sort_column) self.name = name diff --git a/bot/src/bot_api/model/error_dto.py b/bot/src/bot_api/model/error_dto.py index c864dece..867e581c 100644 --- a/bot/src/bot_api/model/error_dto.py +++ b/bot/src/bot_api/model/error_dto.py @@ -11,9 +11,7 @@ class ErrorDTO(DtoABC): def __init__(self, error_code: Optional[ServiceErrorCode], message: str): DtoABC.__init__(self) - self._error_code = ( - ServiceErrorCode.Unknown if error_code is None else error_code - ) + self._error_code = ServiceErrorCode.Unknown if error_code is None else error_code self._message = message @property diff --git a/bot/src/bot_api/model/update_auth_user_dto.py b/bot/src/bot_api/model/update_auth_user_dto.py index d8361171..28e57768 100644 --- a/bot/src/bot_api/model/update_auth_user_dto.py +++ b/bot/src/bot_api/model/update_auth_user_dto.py @@ -34,9 +34,7 @@ class UpdateAuthUserDTO(DtoABC): def from_dict(self, values: dict): self._auth_user = AuthUserDTO().from_dict(values["authUser"]) self._new_auth_user = AuthUserDTO().from_dict(values["newAuthUser"]) - self._change_password = ( - False if "changePassword" not in values else bool(values["changePassword"]) - ) + self._change_password = False if "changePassword" not in values else bool(values["changePassword"]) def to_dict(self) -> dict: return { diff --git a/bot/src/bot_api/route/route.py b/bot/src/bot_api/route/route.py index 3b0fbc96..a72b28e3 100644 --- a/bot/src/bot_api/route/route.py +++ b/bot/src/bot_api/route/route.py @@ -65,9 +65,7 @@ class Route: by_api_key=False, ): if f is None: - return functools.partial( - cls.authorize, role=role, skip_in_dev=skip_in_dev, by_api_key=by_api_key - ) + return functools.partial(cls.authorize, role=role, skip_in_dev=skip_in_dev, by_api_key=by_api_key) @wraps(f) async def decorator(*args, **kwargs): @@ -78,9 +76,7 @@ class Route: api_key = None if "Authorization" in request.headers: if " " not in request.headers.get("Authorization"): - ex = ServiceException( - ServiceErrorCode.Unauthorized, f"Token not set" - ) + ex = ServiceException(ServiceErrorCode.Unauthorized, f"Token not set") error = ErrorDTO(ex.error_code, ex.message) return jsonify(error.to_dict()), 401 @@ -102,9 +98,7 @@ class Route: return jsonify(e), 500 if not valid: - ex = ServiceException( - ServiceErrorCode.Unauthorized, f"API-Key invalid" - ) + ex = ServiceException(ServiceErrorCode.Unauthorized, f"API-Key invalid") error = ErrorDTO(ex.error_code, ex.message) return jsonify(error.to_dict()), 401 @@ -116,9 +110,7 @@ class Route: return jsonify(error.to_dict()), 401 if cls._auth_users is None or cls._auth is None: - ex = ServiceException( - ServiceErrorCode.Unauthorized, f"Authorize is not initialized" - ) + ex = ServiceException(ServiceErrorCode.Unauthorized, f"Authorize is not initialized") error = ErrorDTO(ex.error_code, ex.message) return jsonify(error.to_dict()), 401 @@ -140,9 +132,7 @@ class Route: return jsonify(error.to_dict()), 401 if role is not None and user.auth_role.value < role.value: - ex = ServiceException( - ServiceErrorCode.Unauthorized, f"Role {role} required" - ) + ex = ServiceException(ServiceErrorCode.Unauthorized, f"Role {role} required") error = ErrorDTO(ex.error_code, ex.message) return jsonify(error.to_dict()), 403 diff --git a/bot/src/bot_api/service/auth_service.py b/bot/src/bot_api/service/auth_service.py index ec93775e..94410b52 100644 --- a/bot/src/bot_api/service/auth_service.py +++ b/bot/src/bot_api/service/auth_service.py @@ -90,9 +90,7 @@ class AuthService(AuthServiceABC): def _get_api_key_str(self, api_key: ApiKey) -> str: return hashlib.sha256( - f"{api_key.identifier}:{api_key.key}+{self._auth_settings.secret_key}".encode( - "utf-8" - ) + f"{api_key.identifier}:{api_key.key}+{self._auth_settings.secret_key}".encode("utf-8") ).hexdigest() def generate_token(self, user: AuthUser) -> str: @@ -101,8 +99,7 @@ class AuthService(AuthServiceABC): "user_id": user.id, "email": user.email, "role": user.auth_role.value, - "exp": datetime.now(tz=timezone.utc) - + timedelta(days=self._auth_settings.token_expire_time), + "exp": datetime.now(tz=timezone.utc) + timedelta(days=self._auth_settings.token_expire_time), "iss": self._auth_settings.issuer, "aud": self._auth_settings.audience, }, @@ -158,9 +155,7 @@ class AuthService(AuthServiceABC): def _create_and_save_refresh_token(self, user: AuthUser) -> str: token = str(uuid.uuid4()) user.refresh_token = token - user.refresh_token_expire_time = datetime.now() + timedelta( - days=self._auth_settings.refresh_token_expire_time - ) + user.refresh_token_expire_time = datetime.now() + timedelta(days=self._auth_settings.refresh_token_expire_time) self._auth_users.update_auth_user(user) self._db.save_changes() return token @@ -193,12 +188,8 @@ class AuthService(AuthServiceABC): self._send_link_mail( user.email, - self._t.transform("api.auth.confirmation.subject").format( - user.first_name, user.last_name - ), - self._t.transform("api.auth.confirmation.message").format( - url, user.confirmation_id - ), + self._t.transform("api.auth.confirmation.subject").format(user.first_name, user.last_name), + self._t.transform("api.auth.confirmation.message").format(url, user.confirmation_id), ) def _send_forgot_password_id_to_user(self, user: AuthUser): @@ -208,38 +199,28 @@ class AuthService(AuthServiceABC): self._send_link_mail( user.email, - self._t.transform("api.auth.forgot_password.subject").format( - user.first_name, user.last_name - ), - self._t.transform("api.auth.forgot_password.message").format( - url, user.forgot_password_id - ), + self._t.transform("api.auth.forgot_password.subject").format(user.first_name, user.last_name), + self._t.transform("api.auth.forgot_password.message").format(url, user.forgot_password_id), ) async def get_all_auth_users_async(self) -> List[AuthUserDTO]: result = self._auth_users.get_all_auth_users().select(lambda x: AUT.to_dto(x)) return List(AuthUserDTO, result) - async def get_filtered_auth_users_async( - self, criteria: AuthUserSelectCriteria - ) -> AuthUserFilteredResultDTO: + async def get_filtered_auth_users_async(self, criteria: AuthUserSelectCriteria) -> AuthUserFilteredResultDTO: users = self._auth_users.get_filtered_auth_users(criteria) result = users.result.select(lambda x: AUT.to_dto(x)) return AuthUserFilteredResultDTO(List(AuthUserDTO, result), users.total_count) - async def get_auth_user_by_email_async( - self, email: str, with_password: bool = False - ) -> AuthUserDTO: + async def get_auth_user_by_email_async(self, email: str, with_password: bool = False) -> AuthUserDTO: try: # todo: check if logged in user is admin then send mail user = self._auth_users.get_auth_user_by_email(email) return AUT.to_dto(user, password=user.password if with_password else None) except Exception as e: self._logger.error(__name__, f"AuthUser not found", e) - raise ServiceException( - ServiceErrorCode.InvalidData, f"User not found {email}" - ) + raise ServiceException(ServiceErrorCode.InvalidData, f"User not found {email}") async def find_auth_user_by_email_async(self, email: str) -> Optional[AuthUser]: user = self._auth_users.find_auth_user_by_email(email) @@ -257,22 +238,16 @@ class AuthService(AuthServiceABC): user.password_salt = uuid.uuid4() user.password = self._hash_sha256(user_dto.password, user.password_salt) if not self._is_email_valid(user.email): - raise ServiceException( - ServiceErrorCode.InvalidData, "Invalid E-Mail address" - ) + raise ServiceException(ServiceErrorCode.InvalidData, "Invalid E-Mail address") try: user.confirmation_id = uuid.uuid4() self._auth_users.add_auth_user(user) self._send_confirmation_id_to_user(user) self._db.save_changes() - self._logger.info( - __name__, f"Added auth user with E-Mail: {user_dto.email}" - ) + self._logger.info(__name__, f"Added auth user with E-Mail: {user_dto.email}") except Exception as e: - self._logger.error( - __name__, f"Cannot add user with E-Mail {user_dto.email}", e - ) + self._logger.error(__name__, f"Cannot add user with E-Mail {user_dto.email}", e) raise ServiceException(ServiceErrorCode.UnableToAdd, "Invalid E-Mail") async def add_auth_user_by_oauth_async(self, dto: OAuthDTO): @@ -288,20 +263,14 @@ class AuthService(AuthServiceABC): db_user.first_name = dto.user.first_name db_user.last_name = dto.user.last_name db_user.password_salt = uuid.uuid4() - db_user.password = self._hash_sha256( - dto.user.password, db_user.password_salt - ) + db_user.password = self._hash_sha256(dto.user.password, db_user.password_salt) db_user.oauth_id = None db_user.confirmation_id = uuid.uuid4() self._send_confirmation_id_to_user(db_user) self._auth_users.update_auth_user(db_user) - self._logger.info( - __name__, f"Added auth user with E-Mail: {dto.user.email}" - ) + self._logger.info(__name__, f"Added auth user with E-Mail: {dto.user.email}") except Exception as e: - self._logger.error( - __name__, f"Cannot add user with E-Mail {dto.user.email}", e - ) + self._logger.error(__name__, f"Cannot add user with E-Mail {dto.user.email}", e) raise ServiceException(ServiceErrorCode.UnableToAdd, "Invalid E-Mail") self._db.save_changes() @@ -311,16 +280,14 @@ class AuthService(AuthServiceABC): raise ServiceException(ServiceErrorCode.InvalidData, f"User is empty") if update_user_dto.auth_user is None: - raise ServiceException( - ServiceErrorCode.InvalidData, f"Existing user is empty" - ) + raise ServiceException(ServiceErrorCode.InvalidData, f"Existing user is empty") if update_user_dto.new_auth_user is None: raise ServiceException(ServiceErrorCode.InvalidData, f"New user is empty") - if not self._is_email_valid( - update_user_dto.auth_user.email - ) or not self._is_email_valid(update_user_dto.new_auth_user.email): + if not self._is_email_valid(update_user_dto.auth_user.email) or not self._is_email_valid( + update_user_dto.new_auth_user.email + ): raise ServiceException(ServiceErrorCode.InvalidData, f"Invalid E-Mail") user = self._auth_users.find_auth_user_by_email(update_user_dto.auth_user.email) @@ -333,8 +300,7 @@ class AuthService(AuthServiceABC): # update first name if ( update_user_dto.new_auth_user.first_name is not None - and update_user_dto.auth_user.first_name - != update_user_dto.new_auth_user.first_name + and update_user_dto.auth_user.first_name != update_user_dto.new_auth_user.first_name ): user.first_name = update_user_dto.new_auth_user.first_name @@ -342,8 +308,7 @@ class AuthService(AuthServiceABC): if ( update_user_dto.new_auth_user.last_name is not None and update_user_dto.new_auth_user.last_name != "" - and update_user_dto.auth_user.last_name - != update_user_dto.new_auth_user.last_name + and update_user_dto.auth_user.last_name != update_user_dto.new_auth_user.last_name ): user.last_name = update_user_dto.new_auth_user.last_name @@ -353,33 +318,22 @@ class AuthService(AuthServiceABC): and update_user_dto.new_auth_user.email != "" and update_user_dto.auth_user.email != update_user_dto.new_auth_user.email ): - user_by_new_e_mail = self._auth_users.find_auth_user_by_email( - update_user_dto.new_auth_user.email - ) + user_by_new_e_mail = self._auth_users.find_auth_user_by_email(update_user_dto.new_auth_user.email) if user_by_new_e_mail is not None: - raise ServiceException( - ServiceErrorCode.InvalidUser, "User already exists" - ) + raise ServiceException(ServiceErrorCode.InvalidUser, "User already exists") user.email = update_user_dto.new_auth_user.email - update_user_dto.auth_user.password = self._hash_sha256( - update_user_dto.auth_user.password, user.password_salt - ) + update_user_dto.auth_user.password = self._hash_sha256(update_user_dto.auth_user.password, user.password_salt) if update_user_dto.auth_user.password != user.password: raise ServiceException(ServiceErrorCode.InvalidUser, "Wrong password") # update password if ( update_user_dto.new_auth_user.password is not None - and self._hash_sha256( - update_user_dto.new_auth_user.password, user.password_salt - ) - != user.password + and self._hash_sha256(update_user_dto.new_auth_user.password, user.password_salt) != user.password ): user.password_salt = uuid.uuid4() - user.password = self._hash_sha256( - update_user_dto.new_auth_user.password, user.password_salt - ) + user.password = self._hash_sha256(update_user_dto.new_auth_user.password, user.password_salt) self._auth_users.update_auth_user(user) self._db.save_changes() @@ -389,31 +343,23 @@ class AuthService(AuthServiceABC): raise ServiceException(ServiceErrorCode.InvalidData, f"User is empty") if update_user_dto.auth_user is None: - raise ServiceException( - ServiceErrorCode.InvalidData, f"Existing user is empty" - ) + raise ServiceException(ServiceErrorCode.InvalidData, f"Existing user is empty") if update_user_dto.new_auth_user is None: raise ServiceException(ServiceErrorCode.InvalidData, f"New user is empty") - if not self._is_email_valid( - update_user_dto.auth_user.email - ) or not self._is_email_valid(update_user_dto.new_auth_user.email): + if not self._is_email_valid(update_user_dto.auth_user.email) or not self._is_email_valid( + update_user_dto.new_auth_user.email + ): raise ServiceException(ServiceErrorCode.InvalidData, f"Invalid E-Mail") user = self._auth_users.find_auth_user_by_email(update_user_dto.auth_user.email) if user is None: raise ServiceException(ServiceErrorCode.InvalidUser, "User not found") - if ( - user.confirmation_id is not None - and update_user_dto.new_auth_user.is_confirmed - ): + if user.confirmation_id is not None and update_user_dto.new_auth_user.is_confirmed: user.confirmation_id = None - elif ( - user.confirmation_id is None - and not update_user_dto.new_auth_user.is_confirmed - ): + elif user.confirmation_id is None and not update_user_dto.new_auth_user.is_confirmed: user.confirmation_id = uuid.uuid4() # else # raise ServiceException(ServiceErrorCode.InvalidUser, 'E-Mail not confirmed') @@ -421,8 +367,7 @@ class AuthService(AuthServiceABC): # update first name if ( update_user_dto.new_auth_user.first_name is not None - and update_user_dto.auth_user.first_name - != update_user_dto.new_auth_user.first_name + and update_user_dto.auth_user.first_name != update_user_dto.new_auth_user.first_name ): user.first_name = update_user_dto.new_auth_user.first_name @@ -430,8 +375,7 @@ class AuthService(AuthServiceABC): if ( update_user_dto.new_auth_user.last_name is not None and update_user_dto.new_auth_user.last_name != "" - and update_user_dto.auth_user.last_name - != update_user_dto.new_auth_user.last_name + and update_user_dto.auth_user.last_name != update_user_dto.new_auth_user.last_name ): user.last_name = update_user_dto.new_auth_user.last_name @@ -441,28 +385,19 @@ class AuthService(AuthServiceABC): and update_user_dto.new_auth_user.email != "" and update_user_dto.auth_user.email != update_user_dto.new_auth_user.email ): - user_by_new_e_mail = self._auth_users.find_auth_user_by_email( - update_user_dto.new_auth_user.email - ) + user_by_new_e_mail = self._auth_users.find_auth_user_by_email(update_user_dto.new_auth_user.email) if user_by_new_e_mail is not None: - raise ServiceException( - ServiceErrorCode.InvalidUser, "User already exists" - ) + raise ServiceException(ServiceErrorCode.InvalidUser, "User already exists") user.email = update_user_dto.new_auth_user.email # update password if ( update_user_dto.new_auth_user.password is not None and update_user_dto.change_password - and user.password - != self._hash_sha256( - update_user_dto.new_auth_user.password, user.password_salt - ) + and user.password != self._hash_sha256(update_user_dto.new_auth_user.password, user.password_salt) ): user.password_salt = uuid.uuid4() - user.password = self._hash_sha256( - update_user_dto.new_auth_user.password, user.password_salt - ) + user.password = self._hash_sha256(update_user_dto.new_auth_user.password, user.password_salt) # update role if ( @@ -481,9 +416,7 @@ class AuthService(AuthServiceABC): self._db.save_changes() except Exception as e: self._logger.error(__name__, f"Cannot delete user", e) - raise ServiceException( - ServiceErrorCode.UnableToDelete, f"Cannot delete user by mail {email}" - ) + raise ServiceException(ServiceErrorCode.UnableToDelete, f"Cannot delete user by mail {email}") async def delete_auth_user_async(self, user_dto: AuthUser): try: @@ -567,9 +500,7 @@ class AuthService(AuthServiceABC): if user.id in user_ids: continue - self._auth_users.add_auth_user_user_rel( - AuthUserUsersRelation(db_user, user) - ) + self._auth_users.add_auth_user_user_rel(AuthUserUsersRelation(db_user, user)) if db_user.confirmation_id is not None and not added_user: raise ServiceException(ServiceErrorCode.Forbidden, "E-Mail not verified") @@ -599,19 +530,13 @@ class AuthService(AuthServiceABC): ): raise ServiceException(ServiceErrorCode.InvalidData, "Token expired") - return TokenDTO( - self.generate_token(user), self._create_and_save_refresh_token(user) - ) + return TokenDTO(self.generate_token(user), self._create_and_save_refresh_token(user)) except Exception as e: self._logger.error(__name__, f"Refreshing token failed", e) return TokenDTO("", "") async def revoke_async(self, token_dto: TokenDTO): - if ( - token_dto is None - or token_dto.token is None - or token_dto.refresh_token is None - ): + if token_dto is None or token_dto.token is None or token_dto.refresh_token is None: raise ServiceException(ServiceErrorCode.InvalidData, "Token not set") try: @@ -664,9 +589,7 @@ class AuthService(AuthServiceABC): ) if user.confirmation_id is not None: - raise ServiceException( - ServiceErrorCode.InvalidUser, f"E-Mail not confirmed" - ) + raise ServiceException(ServiceErrorCode.InvalidUser, f"E-Mail not confirmed") if user.password is None or rp_dto.password == "": raise ServiceException(ServiceErrorCode.InvalidData, f"Password not set") diff --git a/bot/src/bot_api/service/discord_service.py b/bot/src/bot_api/service/discord_service.py index 21e0df82..386b3046 100644 --- a/bot/src/bot_api/service/discord_service.py +++ b/bot/src/bot_api/service/discord_service.py @@ -53,17 +53,13 @@ class DiscordService: if role != AuthRoleEnum.admin: auth_user = self._auth_users.find_auth_user_by_email(token["email"]) if auth_user is not None: - user_ids = auth_user.users.select( - lambda x: x.server is not None and x.server.id - ) + user_ids = auth_user.users.select(lambda x: x.server is not None and x.server.id) servers = servers.where(lambda x: x.id in user_ids) servers = List(ServerDTO, servers) return servers.select(self._to_dto).where(lambda x: x.name != "") - async def get_filtered_servers_async( - self, criteria: ServerSelectCriteria - ) -> ServerFilteredResultDTO: + async def get_filtered_servers_async(self, criteria: ServerSelectCriteria) -> ServerFilteredResultDTO: token = self._auth.get_decoded_token_from_request() if token is None or "email" not in token or "role" not in token: raise ServiceException(ServiceErrorCode.InvalidData, "Token invalid") @@ -74,22 +70,15 @@ class DiscordService: if role != AuthRoleEnum.admin: auth_user = self._auth_users.find_auth_user_by_email(token["email"]) if auth_user is not None: - user_ids = auth_user.users.select( - lambda x: x.server is not None and x.server.id - ) - filtered_result.result = filtered_result.result.where( - lambda x: x.id in user_ids - ) + user_ids = auth_user.users.select(lambda x: x.server is not None and x.server.id) + filtered_result.result = filtered_result.result.where(lambda x: x.id in user_ids) - servers: List = filtered_result.result.select(self._to_dto).where( - lambda x: x.name != "" - ) + servers: List = filtered_result.result.select(self._to_dto).where(lambda x: x.name != "") result = List(ServerDTO, servers) if criteria.name is not None and criteria.name != "": result = result.where( - lambda x: criteria.name.lower() in x.name.lower() - or x.name.lower() == criteria.name.lower() + lambda x: criteria.name.lower() in x.name.lower() or x.name.lower() == criteria.name.lower() ) return ServerFilteredResultDTO(List(ServerDTO, result), servers.count()) @@ -98,7 +87,5 @@ class DiscordService: server = self._servers.get_server_by_id(id) guild = self._bot.get_guild(server.discord_id) - server_dto = ServerTransformer.to_dto( - server, guild.name, guild.member_count, guild.icon - ) + server_dto = ServerTransformer.to_dto(server, guild.name, guild.member_count, guild.icon) return server_dto diff --git a/bot/src/bot_api/transformer/auth_user_transformer.py b/bot/src/bot_api/transformer/auth_user_transformer.py index 83633520..9e52fec3 100644 --- a/bot/src/bot_api/transformer/auth_user_transformer.py +++ b/bot/src/bot_api/transformer/auth_user_transformer.py @@ -27,35 +27,27 @@ class AuthUserTransformer(TransformerABC): None, None, datetime.now(), - AuthRoleEnum.normal - if dto.auth_role is None - else AuthRoleEnum(dto.auth_role), + AuthRoleEnum.normal if dto.auth_role is None else AuthRoleEnum(dto.auth_role), auth_user_id=0 if dto.id is None else dto.id, ) @staticmethod @ServiceProviderABC.inject - def _is_technician( - user: User, bot: DiscordBotServiceABC, permissions: PermissionServiceABC - ): + def _is_technician(user: User, bot: DiscordBotServiceABC, permissions: PermissionServiceABC): guild = bot.get_guild(user.server.discord_id) member = guild.get_member(user.discord_id) return permissions.is_member_technician(member) @staticmethod @ServiceProviderABC.inject - 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) member = guild.get_member(user.discord_id) return permissions.is_member_admin(member) @staticmethod @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) member = guild.get_member(user.discord_id) return permissions.is_member_moderator(member) diff --git a/bot/src/bot_api/transformer/server_transformer.py b/bot/src/bot_api/transformer/server_transformer.py index f4ca5d6f..bffba8e1 100644 --- a/bot/src/bot_api/transformer/server_transformer.py +++ b/bot/src/bot_api/transformer/server_transformer.py @@ -13,9 +13,7 @@ class ServerTransformer(TransformerABC): return Server(dto.discord_id) @staticmethod - def to_dto( - db: Server, name: str, member_count: int, icon_url: Optional[discord.Asset] - ) -> ServerDTO: + def to_dto(db: Server, name: str, member_count: int, icon_url: Optional[discord.Asset]) -> ServerDTO: return ServerDTO( db.id, db.discord_id, diff --git a/bot/src/bot_core/abc/client_utils_abc.py b/bot/src/bot_core/abc/client_utils_abc.py index 9dd50401..fdcf5118 100644 --- a/bot/src/bot_core/abc/client_utils_abc.py +++ b/bot/src/bot_core/abc/client_utils_abc.py @@ -45,9 +45,7 @@ class ClientUtilsABC(ABC): pass @abstractmethod - def get_auto_complete_list( - self, _l: List, current: str, select: Callable = None - ) -> List: + def get_auto_complete_list(self, _l: List, current: str, select: Callable = None) -> List: pass @abstractmethod diff --git a/bot/src/bot_core/abc/custom_file_logger_abc.py b/bot/src/bot_core/abc/custom_file_logger_abc.py index 670b90e6..2b2bbe0a 100644 --- a/bot/src/bot_core/abc/custom_file_logger_abc.py +++ b/bot/src/bot_core/abc/custom_file_logger_abc.py @@ -18,9 +18,7 @@ class CustomFileLoggerABC(Logger, ABC): env: ApplicationEnvironmentABC, ): self._key = key - self._settings: LoggingSettings = config.get_configuration( - f"{FileLoggingSettings.__name__}_{key}" - ) + self._settings: LoggingSettings = config.get_configuration(f"{FileLoggingSettings.__name__}_{key}") Logger.__init__(self, self._settings, time_format, env) self._begin_log() @@ -34,9 +32,7 @@ class CustomFileLoggerABC(Logger, ABC): self.info(__name__, f"Starting...") self._console = LoggingLevelEnum(console_level) - def _get_string( - self, name_list_as_str: str, level: LoggingLevelEnum, message: str - ) -> str: + def _get_string(self, name_list_as_str: str, level: LoggingLevelEnum, message: str) -> str: names = name_list_as_str.split(" ") log_level = level.name string = f"<{self._get_datetime_now()}> [ {log_level} ]" diff --git a/bot/src/bot_core/abc/message_service_abc.py b/bot/src/bot_core/abc/message_service_abc.py index 019c8b6a..3dada9a3 100644 --- a/bot/src/bot_core/abc/message_service_abc.py +++ b/bot/src/bot_core/abc/message_service_abc.py @@ -13,9 +13,7 @@ class MessageServiceABC(ABC): pass @abstractmethod - async def delete_messages( - self, messages: List[discord.Message], guild_id: int, without_tracking=False - ): + async def delete_messages(self, messages: List[discord.Message], guild_id: int, without_tracking=False): pass @abstractmethod diff --git a/bot/src/bot_core/abc/task_abc.py b/bot/src/bot_core/abc/task_abc.py index bb684d8e..d068fd37 100644 --- a/bot/src/bot_core/abc/task_abc.py +++ b/bot/src/bot_core/abc/task_abc.py @@ -15,9 +15,7 @@ class TaskABC(commands.Cog): commands.Cog.__init__(self) @ServiceProviderABC.inject - async def _wait_until_ready( - self, config: ConfigurationABC, logger: TaskLogger, bot: DiscordBotServiceABC - ): + async def _wait_until_ready(self, config: ConfigurationABC, logger: TaskLogger, bot: DiscordBotServiceABC): logger.debug(__name__, f"Waiting before {type(self).__name__}") await bot.wait_until_ready() diff --git a/bot/src/bot_core/configuration/file_logging_settings.py b/bot/src/bot_core/configuration/file_logging_settings.py index 1e694363..46028aa5 100644 --- a/bot/src/bot_core/configuration/file_logging_settings.py +++ b/bot/src/bot_core/configuration/file_logging_settings.py @@ -10,9 +10,7 @@ class FileLoggingSettings(LoggingSettings): console_log_level: LoggingLevelEnum = None, file_log_level: LoggingLevelEnum = None, ): - LoggingSettings.__init__( - self, path, filename, console_log_level, file_log_level - ) + LoggingSettings.__init__(self, path, filename, console_log_level, file_log_level) self._key = key diff --git a/bot/src/bot_core/core_extension/core_extension.py b/bot/src/bot_core/core_extension/core_extension.py index ede39c5c..de5a1781 100644 --- a/bot/src/bot_core/core_extension/core_extension.py +++ b/bot/src/bot_core/core_extension/core_extension.py @@ -17,9 +17,7 @@ class CoreExtension(ApplicationExtensionABC): ApplicationExtensionABC.__init__(self) async def run(self, config: ConfigurationABC, services: ServiceProviderABC): - feature_flags: FeatureFlagsSettings = config.get_configuration( - FeatureFlagsSettings - ) + feature_flags: FeatureFlagsSettings = config.get_configuration(FeatureFlagsSettings) if not feature_flags.get_flag(FeatureFlagsEnum.core_module): return diff --git a/bot/src/bot_core/core_extension/core_extension_module.py b/bot/src/bot_core/core_extension/core_extension_module.py index e780a721..ef16529f 100644 --- a/bot/src/bot_core/core_extension/core_extension_module.py +++ b/bot/src/bot_core/core_extension/core_extension_module.py @@ -15,14 +15,8 @@ class CoreExtensionModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.core_extension_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): pass - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): - services.add_transient( - DiscordEventTypesEnum.on_ready.value, CoreExtensionOnReadyEvent - ) + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): + services.add_transient(DiscordEventTypesEnum.on_ready.value, CoreExtensionOnReadyEvent) diff --git a/bot/src/bot_core/core_module.py b/bot/src/bot_core/core_module.py index def17448..02611684 100644 --- a/bot/src/bot_core/core_module.py +++ b/bot/src/bot_core/core_module.py @@ -20,14 +20,10 @@ class CoreModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.core_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): pass - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): services.add_transient(ConfigService) services.add_transient(MessageServiceABC, MessageService) services.add_transient(ClientUtilsABC, ClientUtilsService) diff --git a/bot/src/bot_core/helper/command_checks.py b/bot/src/bot_core/helper/command_checks.py index b6e6672c..e2048409 100644 --- a/bot/src/bot_core/helper/command_checks.py +++ b/bot/src/bot_core/helper/command_checks.py @@ -44,9 +44,7 @@ class CommandChecks: async def check_is_member_admin(ctx: Context): has_permission = cls._permissions.is_member_admin(ctx.author) if not has_permission: - await cls._message_service.send_ctx_msg( - ctx, cls._t.transform("common.no_permission_message") - ) + await cls._message_service.send_ctx_msg(ctx, cls._t.transform("common.no_permission_message")) raise CheckError(f"Member {ctx.author.name} is not admin") return has_permission @@ -58,9 +56,7 @@ class CommandChecks: async def check_is_member_technician(ctx: Context): has_permission = cls._permissions.is_member_technician(ctx.author) if not has_permission: - await cls._message_service.send_ctx_msg( - ctx, cls._t.transform("common.no_permission_message") - ) + await cls._message_service.send_ctx_msg(ctx, cls._t.transform("common.no_permission_message")) raise CheckError(f"Member {ctx.author.name} is not technician") return has_permission @@ -72,9 +68,7 @@ class CommandChecks: async def check_is_member_moderator(ctx: Context): has_permission = cls._permissions.is_member_moderator(ctx.author) if not has_permission: - await cls._message_service.send_ctx_msg( - ctx, cls._t.transform("common.no_permission_message") - ) + await cls._message_service.send_ctx_msg(ctx, cls._t.transform("common.no_permission_message")) raise CheckError(f"Member {ctx.author.name} is not moderator") return has_permission diff --git a/bot/src/bot_core/service/client_utils_service.py b/bot/src/bot_core/service/client_utils_service.py index b215386c..e0272390 100644 --- a/bot/src/bot_core/service/client_utils_service.py +++ b/bot/src/bot_core/service/client_utils_service.py @@ -62,36 +62,28 @@ class ClientUtilsService(ClientUtilsABC): def received_command(self, guild_id: int): server = self._servers.get_server_by_discord_id(guild_id) - client = self._clients.find_client_by_discord_id_and_server_id( - self._bot.user.id, server.id - ) + client = self._clients.find_client_by_discord_id_and_server_id(self._bot.user.id, server.id) client.received_command_count += 1 self._clients.update_client(client) self._db.save_changes() def moved_user(self, guild_id: int): server = self._servers.get_server_by_discord_id(guild_id) - client = self._clients.find_client_by_discord_id_and_server_id( - self._bot.user.id, server.id - ) + client = self._clients.find_client_by_discord_id_and_server_id(self._bot.user.id, server.id) client.moved_users_count += 1 self._clients.update_client(client) self._db.save_changes() def moved_users(self, guild_id: int, count: int): server = self._servers.get_server_by_discord_id(guild_id) - client = self._clients.find_client_by_discord_id_and_server_id( - self._bot.user.id, server.id - ) + client = self._clients.find_client_by_discord_id_and_server_id(self._bot.user.id, server.id) client.moved_users_count += count self._clients.update_client(client) self._db.save_changes() def get_client(self, dc_ic: int, guild_id: int): server = self._servers.get_server_by_discord_id(guild_id) - client = self._clients.find_client_by_discord_id_and_server_id( - self._bot.user.id, server.id - ) + client = self._clients.find_client_by_discord_id_and_server_id(self._bot.user.id, server.id) return client async def check_if_bot_is_ready_yet(self) -> bool: @@ -129,9 +121,7 @@ class ClientUtilsService(ClientUtilsABC): await self._bot.change_presence(activity=discord.Game(name=name)) self._logger.info(__name__, f"Set presence {name}") - def get_auto_complete_list( - self, _l: List, current: str, select: Callable = None - ) -> List: + def get_auto_complete_list(self, _l: List, current: str, select: Callable = None) -> List: if current != "": if select is None: select = lambda x: x @@ -154,9 +144,7 @@ class ClientUtilsService(ClientUtilsABC): ) -> bool: umcph = None try: - umcph = self._umcphs.find_user_message_count_per_hour_by_user_id_and_date( - user.id, created_at - ) + umcph = self._umcphs.find_user_message_count_per_hour_by_user_id_and_date(user.id, created_at) if umcph is None: self._umcphs.add_user_message_count_per_hour( UserMessageCountPerHour( @@ -169,11 +157,7 @@ class ClientUtilsService(ClientUtilsABC): self._db.save_changes() - umcph = ( - self._umcphs.get_user_message_count_per_hour_by_user_id_and_date( - user.id, created_at - ) - ) + umcph = self._umcphs.get_user_message_count_per_hour_by_user_id_and_date(user.id, created_at) except Exception as e: self._logger.error( __name__, @@ -205,9 +189,7 @@ class ClientUtilsService(ClientUtilsABC): def get_ontime_for_user(self, user: User) -> float: return round( - self._user_joined_voice_channel.get_user_joined_voice_channels_by_user_id( - user.id - ) + self._user_joined_voice_channel.get_user_joined_voice_channels_by_user_id(user.id) .where(lambda x: x.leaved_on is not None and x.joined_on is not None) .sum(lambda join: (join.leaved_on - join.joined_on).total_seconds() / 3600), 2, @@ -224,11 +206,7 @@ class ClientUtilsService(ClientUtilsABC): 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() - ) + 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") @@ -248,9 +226,7 @@ class ClientUtilsService(ClientUtilsABC): async def check_default_role(self, member: Union[discord.User, discord.Member]): try: server = self._servers.get_server_by_discord_id(member.guild.id) - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{server.discord_id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{server.discord_id}") if settings.default_role_id is None: return @@ -262,6 +238,4 @@ class ClientUtilsService(ClientUtilsABC): await member.add_roles(default_role) except Exception as e: - self._logger.error( - __name__, f"Cannot check for default role for member {member.id}", e - ) + self._logger.error(__name__, f"Cannot check for default role for member {member.id}", e) diff --git a/bot/src/bot_core/service/data_integrity_service.py b/bot/src/bot_core/service/data_integrity_service.py index f7090636..fc044a9d 100644 --- a/bot/src/bot_core/service/data_integrity_service.py +++ b/bot/src/bot_core/service/data_integrity_service.py @@ -67,16 +67,12 @@ class DataIntegrityService: self._is_for_shutdown = False def _check_known_users(self): - self._logger.debug( - __name__, f"Start checking KnownUsers table, {len(self._bot.users)}" - ) + self._logger.debug(__name__, f"Start checking KnownUsers table, {len(self._bot.users)}") for u in self._bot.users: u: discord.User = u try: if u.bot: - self._logger.trace( - __name__, f"User {u.id} is ignored, because its a bot" - ) + self._logger.trace(__name__, f"User {u.id} is ignored, because its a bot") continue user = self._known_users.find_user_by_discord_id(u.id) @@ -129,9 +125,7 @@ class DataIntegrityService: try: server: Server = self._servers.find_server_by_discord_id(g.id) if server is None: - self._logger.fatal( - __name__, f"Server not found in database: {g.id}" - ) + self._logger.fatal(__name__, f"Server not found in database: {g.id}") client = self._clients.find_client_by_server_id(server.id) if client is not None: @@ -142,9 +136,7 @@ class DataIntegrityService: f"Client for server {g.id} not found in database: {self._bot.user.id}", ) self._logger.debug(__name__, f"Add client: {self._bot.user.id}") - self._clients.add_client( - Client(self._bot.user.id, 0, 0, 0, 0, 0, server) - ) + self._clients.add_client(Client(self._bot.user.id, 0, 0, 0, 0, 0, server)) self._db_context.save_changes() client = self._clients.find_client_by_server_id(server.id) @@ -170,21 +162,15 @@ class DataIntegrityService: try: server = self._servers.find_server_by_discord_id(g.id) if server is None: - self._logger.fatal( - __name__, f"Server not found in database: {g.id}" - ) + self._logger.fatal(__name__, f"Server not found in database: {g.id}") for u in g.members: u: Union[discord.Member, discord.User] = u if u.bot: - self._logger.trace( - __name__, f"User {u.id} is ignored, because its a bot" - ) + self._logger.trace(__name__, f"User {u.id} is ignored, because its a bot") continue - user = self._users.find_user_by_discord_id_and_server_id( - u.id, server.id - ) + user = self._users.find_user_by_discord_id_and_server_id(u.id, server.id) if user is not None: continue @@ -208,30 +194,20 @@ class DataIntegrityService: server = self._servers.find_server_by_discord_id(guild.id) if server is None: - self._logger.fatal( - __name__, f"Server not found in database: {guild.id}" - ) + self._logger.fatal(__name__, f"Server not found in database: {guild.id}") try: for u in guild.members: u: discord.User = u if u.bot: - self._logger.trace( - __name__, f"User {u.id} is ignored, because its a bot" - ) + self._logger.trace(__name__, f"User {u.id} is ignored, because its a bot") continue - user = self._users.find_user_by_discord_id_and_server_id( - u.id, server.id - ) + user = self._users.find_user_by_discord_id_and_server_id(u.id, server.id) if user is None: - self._logger.fatal( - __name__, f"User not found in database: {u.id}" - ) + self._logger.fatal(__name__, f"User not found in database: {u.id}") - join = self._user_joins.find_active_user_joined_server_by_user_id( - user.id - ) + join = self._user_joins.find_active_user_joined_server_by_user_id(user.id) if join is not None: continue @@ -281,36 +257,24 @@ class DataIntegrityService: self._logger.debug(__name__, f"Start checking UserJoinedVoiceChannel table") for guild in self._bot.guilds: guild: discord.Guild = guild - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{guild.id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild.id}") server = self._servers.find_server_by_discord_id(guild.id) if server is None: - self._logger.fatal( - __name__, f"Server not found in database: {guild.id}" - ) + self._logger.fatal(__name__, f"Server not found in database: {guild.id}") try: # close open voice states for member in guild.members: if member.bot: - 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 - 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) if user is None: - self._logger.fatal( - __name__, f"User not found in database: {member.id}" - ) + self._logger.fatal(__name__, f"User not found in database: {member.id}") - joins = self._user_joins_vc.find_active_user_joined_voice_channels_by_user_id( - user.id - ) + joins = self._user_joins_vc.find_active_user_joined_voice_channels_by_user_id(user.id) if joins is None or len(joins) == 0: continue @@ -324,9 +288,7 @@ class DataIntegrityService: if ( (join.leaved_on - join.joined_on).total_seconds() / 60 / 60 ) > settings.max_voice_state_hours: - join.leaved_on = join.joined_on + timedelta( - hours=settings.max_voice_state_hours - ) + join.leaved_on = join.joined_on + timedelta(hours=settings.max_voice_state_hours) self._user_joins_vc.update_user_joined_voice_channel(join) @@ -341,28 +303,17 @@ class DataIntegrityService: # add open voice states for member in guild.members: if member.bot: - 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 - if ( - member.voice is None - or member.voice.channel.id in settings.afk_channel_ids - ): + if member.voice is None or member.voice.channel.id in settings.afk_channel_ids: 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) if user is None: - self._logger.fatal( - __name__, f"User not found in database: {member.id}" - ) + self._logger.fatal(__name__, f"User not found in database: {member.id}") - join = UserJoinedVoiceChannel( - user, member.voice.channel.id, datetime.now() - ) + join = UserJoinedVoiceChannel(user, member.voice.channel.id, datetime.now()) self._user_joins_vc.add_user_joined_voice_channel(join) self._db_context.save_changes() @@ -376,29 +327,19 @@ class DataIntegrityService: server = self._servers.find_server_by_discord_id(guild.id) if server is None: - self._logger.fatal( - __name__, f"Server not found in database: {guild.id}" - ) + self._logger.fatal(__name__, f"Server not found in database: {guild.id}") try: for member in guild.members: if member.bot: - 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 - 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) if user is None: - self._logger.fatal( - __name__, f"User not found in database: {member.id}" - ) + self._logger.fatal(__name__, f"User not found in database: {member.id}") - joins = self._user_joined_gs.find_active_user_joined_game_servers_by_user_id( - user.id - ) + joins = self._user_joined_gs.find_active_user_joined_game_servers_by_user_id(user.id) if joins is None or len(joins) == 0: continue @@ -408,16 +349,12 @@ class DataIntegrityService: f"Active UserJoinedGameServer found in database: {guild.id}:{member.id}@{join.joined_on}", ) join.leaved_on = datetime.now() - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{guild.id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild.id}") if ( (join.leaved_on - join.joined_on).total_seconds() / 60 / 60 ) > settings.max_voice_state_hours: - join.leaved_on = join.joined_on + timedelta( - hours=settings.max_voice_state_hours - ) + join.leaved_on = join.joined_on + timedelta(hours=settings.max_voice_state_hours) self._user_joined_gs.update_user_joined_game_server(join) if self._is_for_shutdown: @@ -434,24 +371,16 @@ class DataIntegrityService: for guild in self._bot.guilds: server = self._servers.find_server_by_discord_id(guild.id) if server is None: - self._logger.fatal( - __name__, f"Server not found in database: {guild.id}" - ) + self._logger.fatal(__name__, f"Server not found in database: {guild.id}") for member in guild.members: if member.bot: - 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 - 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) if user is None: - self._logger.fatal( - __name__, f"User not found in database: {member.id}" - ) + self._logger.fatal(__name__, f"User not found in database: {member.id}") await self._achievements.validate_achievements_for_user(user) diff --git a/bot/src/bot_core/service/message_service.py b/bot/src/bot_core/service/message_service.py index 060d5495..9140742f 100644 --- a/bot/src/bot_core/service/message_service.py +++ b/bot/src/bot_core/service/message_service.py @@ -31,23 +31,15 @@ class MessageService(MessageServiceABC): self._clients = clients self._db = db - async def delete_messages( - self, messages: List[discord.Message], guild_id: int, without_tracking=False - ): + async def delete_messages(self, messages: List[discord.Message], guild_id: int, without_tracking=False): self._logger.debug(__name__, f"Try to delete {messages.count()} messages") - server_st: ServerConfig = self._config.get_configuration( - f"ServerConfig_{guild_id}" - ) + server_st: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild_id}") await asyncio.sleep(server_st.message_delete_timer) for message in messages: - await self.delete_message( - message, mass_delete=True, without_tracking=without_tracking - ) + await self.delete_message(message, mass_delete=True, without_tracking=without_tracking) self._logger.debug(__name__, "Deleting messages finished") - async def delete_message( - self, message: discord.Message, mass_delete=False, without_tracking=False - ): + async def delete_message(self, message: discord.Message, mass_delete=False, without_tracking=False): guild_id = ( message.guild.id if message.guild is not None @@ -58,9 +50,7 @@ class MessageService(MessageServiceABC): else None ) - server_st: ServerConfig = self._config.get_configuration( - f"ServerConfig_{guild_id}" - ) + server_st: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild_id}") if not mass_delete: await asyncio.sleep(server_st.message_delete_timer) self._logger.debug( @@ -74,9 +64,7 @@ class MessageService(MessageServiceABC): self._logger.error(__name__, f"Deleting message failed", e) else: if not without_tracking: - self._clients.append_deleted_message_count( - self._bot.user.id, guild_id, 1 - ) + self._clients.append_deleted_message_count(self._bot.user.id, guild_id, 1) self._db.save_changes() self._logger.info(__name__, f"Deleted message {message}") @@ -88,9 +76,7 @@ class MessageService(MessageServiceABC): wait_before_delete: int = None, without_tracking=False, ): - self._logger.debug( - __name__, f"Try to send message\n\t{message}\n\tto: {channel}" - ) + self._logger.debug(__name__, f"Try to send message\n\t{message}\n\tto: {channel}") msg = None try: if isinstance(message, discord.Embed): @@ -100,15 +86,11 @@ class MessageService(MessageServiceABC): else: msg = await channel.send(message) except Exception as e: - self._logger.error( - __name__, f"Send message to channel {channel.id} failed", e - ) + self._logger.error(__name__, f"Send message to channel {channel.id} failed", e) else: self._logger.info(__name__, f"Sent message to channel {channel.id}") if not without_tracking: - self._clients.append_sent_message_count( - self._bot.user.id, channel.guild.id, 1 - ) + self._clients.append_sent_message_count(self._bot.user.id, channel.guild.id, 1) self._db.save_changes() if wait_before_delete is not None: @@ -125,23 +107,17 @@ class MessageService(MessageServiceABC): receiver: Union[discord.User, discord.Member], without_tracking=False, ): - self._logger.debug( - __name__, f"Try to send message\n\t{message}\n\tto: {receiver}" - ) + self._logger.debug(__name__, f"Try to send message\n\t{message}\n\tto: {receiver}") try: if isinstance(message, discord.Embed): msg = await receiver.send(embed=message) else: msg = await receiver.send(message) except Exception as e: - self._logger.error( - __name__, f"Send message to user {receiver.id} failed", e - ) + self._logger.error(__name__, f"Send message to user {receiver.id} failed", e) else: if not without_tracking: - self._clients.append_sent_message_count( - self._bot.user.id, receiver.guild.id, 1 - ) + self._clients.append_sent_message_count(self._bot.user.id, receiver.guild.id, 1) self._db.save_changes() self._logger.info(__name__, f"Sent message to user {receiver.id}") @@ -160,9 +136,7 @@ class MessageService(MessageServiceABC): self._logger.debug(__name__, f"Message: {message}") return None - self._logger.debug( - __name__, f"Try to send message\t\t{message}\n\tto: {ctx.channel}" - ) + self._logger.debug(__name__, f"Try to send message\t\t{message}\n\tto: {ctx.channel}") msg = None try: if isinstance(message, discord.Embed): @@ -170,15 +144,11 @@ class MessageService(MessageServiceABC): else: msg = await ctx.send(message, file=file, ephemeral=not is_public) except Exception as e: - self._logger.error( - __name__, f"Send message to channel {ctx.channel.id} failed", e - ) + self._logger.error(__name__, f"Send message to channel {ctx.channel.id} failed", e) else: self._logger.info(__name__, f"Sent message to channel {ctx.channel.id}") if not without_tracking and ctx.guild is not None: - self._clients.append_sent_message_count( - self._bot.user.id, ctx.guild.id, 1 - ) + self._clients.append_sent_message_count(self._bot.user.id, ctx.guild.id, 1) self._db.save_changes() if wait_before_delete is not None: @@ -207,30 +177,18 @@ class MessageService(MessageServiceABC): self._logger.debug(__name__, f"Message: {message}") return - self._logger.debug( - __name__, f"Try to send message\t\t{message}\n\tto: {interaction.channel}" - ) + self._logger.debug(__name__, f"Try to send message\t\t{message}\n\tto: {interaction.channel}") try: if isinstance(message, discord.Embed): - await interaction.response.send_message( - embed=message, ephemeral=not is_public, **kwargs - ) + await interaction.response.send_message(embed=message, ephemeral=not is_public, **kwargs) else: - await interaction.response.send_message( - message, ephemeral=not is_public, **kwargs - ) + await interaction.response.send_message(message, ephemeral=not is_public, **kwargs) except Exception as e: - self._logger.error( - __name__, f"Send message to channel {interaction.channel.id} failed", e - ) + self._logger.error(__name__, f"Send message to channel {interaction.channel.id} failed", e) else: - self._logger.info( - __name__, f"Sent message to channel {interaction.channel.id}" - ) + self._logger.info(__name__, f"Sent message to channel {interaction.channel.id}") if not without_tracking and interaction.guild is not None: - self._clients.append_sent_message_count( - self._bot.user.id, interaction.guild.id, 1 - ) + self._clients.append_sent_message_count(self._bot.user.id, interaction.guild.id, 1) self._db.save_changes() if wait_before_delete is not None: @@ -239,6 +197,4 @@ class MessageService(MessageServiceABC): if is_persistent: return - await self.delete_message( - await interaction.original_response(), without_tracking - ) + await self.delete_message(await interaction.original_response(), without_tracking) diff --git a/bot/src/bot_data/abc/achievement_repository_abc.py b/bot/src/bot_data/abc/achievement_repository_abc.py index e1cc6c4e..ff3014fe 100644 --- a/bot/src/bot_data/abc/achievement_repository_abc.py +++ b/bot/src/bot_data/abc/achievement_repository_abc.py @@ -28,9 +28,7 @@ class AchievementRepositoryABC(ABC): pass @abstractmethod - def get_user_got_achievements_by_achievement_id( - self, achievement_id: int - ) -> List[Achievement]: + def get_user_got_achievements_by_achievement_id(self, achievement_id: int) -> List[Achievement]: pass @abstractmethod diff --git a/bot/src/bot_data/abc/auth_user_repository_abc.py b/bot/src/bot_data/abc/auth_user_repository_abc.py index 0dc7eeaf..9d9b06ec 100644 --- a/bot/src/bot_data/abc/auth_user_repository_abc.py +++ b/bot/src/bot_data/abc/auth_user_repository_abc.py @@ -23,9 +23,7 @@ class AuthUserRepositoryABC(ABC): pass @abstractmethod - def get_filtered_auth_users( - self, criteria: AuthUserSelectCriteria - ) -> FilteredResult: + def get_filtered_auth_users(self, criteria: AuthUserSelectCriteria) -> FilteredResult: pass @abstractmethod diff --git a/bot/src/bot_data/abc/client_repository_abc.py b/bot/src/bot_data/abc/client_repository_abc.py index 40cf8033..3b9f9132 100644 --- a/bot/src/bot_data/abc/client_repository_abc.py +++ b/bot/src/bot_data/abc/client_repository_abc.py @@ -36,9 +36,7 @@ class ClientRepositoryABC(ABC): pass @abstractmethod - def find_client_by_discord_id_and_server_id( - self, discord_id: int, server_id: int - ) -> Optional[Client]: + def find_client_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> Optional[Client]: pass @abstractmethod diff --git a/bot/src/bot_data/abc/server_config_repository_abc.py b/bot/src/bot_data/abc/server_config_repository_abc.py index 6a5cd127..f66fdc89 100644 --- a/bot/src/bot_data/abc/server_config_repository_abc.py +++ b/bot/src/bot_data/abc/server_config_repository_abc.py @@ -35,37 +35,25 @@ class ServerConfigRepositoryABC(ABC): pass @abstractmethod - def add_server_team_role_id_config( - self, server_team_role_id: ServerTeamRoleIdsConfig - ): + def add_server_team_role_id_config(self, server_team_role_id: ServerTeamRoleIdsConfig): pass @abstractmethod - def update_server_team_role_id_config( - self, server_team_role_id: ServerTeamRoleIdsConfig - ): + def update_server_team_role_id_config(self, server_team_role_id: ServerTeamRoleIdsConfig): pass @abstractmethod - def delete_server_team_role_id_config( - self, server_team_role_id: ServerTeamRoleIdsConfig - ): + def delete_server_team_role_id_config(self, server_team_role_id: ServerTeamRoleIdsConfig): pass @abstractmethod - def add_server_afk_channel_config( - self, server_afk_channel: ServerAFKChannelIdsConfig - ): + def add_server_afk_channel_config(self, server_afk_channel: ServerAFKChannelIdsConfig): pass @abstractmethod - def update_server_afk_channel_config( - self, server_afk_channel: ServerAFKChannelIdsConfig - ): + def update_server_afk_channel_config(self, server_afk_channel: ServerAFKChannelIdsConfig): pass @abstractmethod - def delete_server_afk_channel_config( - self, server_afk_channel: ServerAFKChannelIdsConfig - ): + def delete_server_afk_channel_config(self, server_afk_channel: ServerAFKChannelIdsConfig): pass diff --git a/bot/src/bot_data/abc/technician_config_repository_abc.py b/bot/src/bot_data/abc/technician_config_repository_abc.py index 364af9b6..25c88d96 100644 --- a/bot/src/bot_data/abc/technician_config_repository_abc.py +++ b/bot/src/bot_data/abc/technician_config_repository_abc.py @@ -43,19 +43,13 @@ class TechnicianConfigRepositoryABC(ABC): pass @abstractmethod - def add_technician_ping_url_config( - self, technician_ping_url: TechnicianPingUrlConfig - ): + def add_technician_ping_url_config(self, technician_ping_url: TechnicianPingUrlConfig): pass @abstractmethod - def update_technician_ping_url_config( - self, technician_ping_url: TechnicianPingUrlConfig - ): + def update_technician_ping_url_config(self, technician_ping_url: TechnicianPingUrlConfig): pass @abstractmethod - def delete_technician_ping_url_config( - self, technician_ping_url: TechnicianPingUrlConfig - ): + def delete_technician_ping_url_config(self, technician_ping_url: TechnicianPingUrlConfig): pass diff --git a/bot/src/bot_data/abc/user_joined_game_server_repository_abc.py b/bot/src/bot_data/abc/user_joined_game_server_repository_abc.py index c6c3cfcf..97a0358b 100644 --- a/bot/src/bot_data/abc/user_joined_game_server_repository_abc.py +++ b/bot/src/bot_data/abc/user_joined_game_server_repository_abc.py @@ -20,45 +20,31 @@ class UserJoinedGameServerRepositoryABC(ABC): pass @abstractmethod - def get_user_joined_game_servers_by_user_id( - self, user_id: int - ) -> List[UserJoinedGameServer]: + def get_user_joined_game_servers_by_user_id(self, user_id: int) -> List[UserJoinedGameServer]: pass @abstractmethod - def get_active_user_joined_game_server_by_user_id( - self, user_id: int - ) -> UserJoinedGameServer: + def get_active_user_joined_game_server_by_user_id(self, user_id: int) -> UserJoinedGameServer: pass @abstractmethod - def find_active_user_joined_game_server_by_user_id( - self, user_id: int - ) -> Optional[UserJoinedGameServer]: + def find_active_user_joined_game_server_by_user_id(self, user_id: int) -> Optional[UserJoinedGameServer]: pass @abstractmethod - def find_active_user_joined_game_servers_by_user_id( - self, user_id: int - ) -> List[Optional[UserJoinedGameServer]]: + def find_active_user_joined_game_servers_by_user_id(self, user_id: int) -> List[Optional[UserJoinedGameServer]]: pass @abstractmethod - def add_user_joined_game_server( - self, user_joined_game_server: UserJoinedGameServer - ): + def add_user_joined_game_server(self, user_joined_game_server: UserJoinedGameServer): pass @abstractmethod - def update_user_joined_game_server( - self, user_joined_game_server: UserJoinedGameServer - ): + def update_user_joined_game_server(self, user_joined_game_server: UserJoinedGameServer): pass @abstractmethod - def delete_user_joined_game_server( - self, user_joined_game_server: UserJoinedGameServer - ): + def delete_user_joined_game_server(self, user_joined_game_server: UserJoinedGameServer): pass @abstractmethod diff --git a/bot/src/bot_data/abc/user_joined_server_repository_abc.py b/bot/src/bot_data/abc/user_joined_server_repository_abc.py index d317b7b2..cbc3a718 100644 --- a/bot/src/bot_data/abc/user_joined_server_repository_abc.py +++ b/bot/src/bot_data/abc/user_joined_server_repository_abc.py @@ -24,21 +24,15 @@ class UserJoinedServerRepositoryABC(ABC): pass @abstractmethod - def get_user_joined_servers_by_user_id( - self, user_id: int - ) -> list[UserJoinedServer]: + def get_user_joined_servers_by_user_id(self, user_id: int) -> list[UserJoinedServer]: pass @abstractmethod - def get_active_user_joined_server_by_user_id( - self, user_id: int - ) -> UserJoinedServer: + def get_active_user_joined_server_by_user_id(self, user_id: int) -> UserJoinedServer: pass @abstractmethod - def find_active_user_joined_server_by_user_id( - self, user_id: int - ) -> Optional[UserJoinedServer]: + def find_active_user_joined_server_by_user_id(self, user_id: int) -> Optional[UserJoinedServer]: pass @abstractmethod diff --git a/bot/src/bot_data/abc/user_joined_voice_channel_repository_abc.py b/bot/src/bot_data/abc/user_joined_voice_channel_repository_abc.py index 793cfe33..7ce7e01a 100644 --- a/bot/src/bot_data/abc/user_joined_voice_channel_repository_abc.py +++ b/bot/src/bot_data/abc/user_joined_voice_channel_repository_abc.py @@ -19,45 +19,31 @@ class UserJoinedVoiceChannelRepositoryABC(ABC): pass @abstractmethod - def get_user_joined_voice_channels_by_user_id( - self, user_id: int - ) -> List[UserJoinedVoiceChannel]: + def get_user_joined_voice_channels_by_user_id(self, user_id: int) -> List[UserJoinedVoiceChannel]: pass @abstractmethod - def get_active_user_joined_voice_channel_by_user_id( - self, user_id: int - ) -> UserJoinedVoiceChannel: + def get_active_user_joined_voice_channel_by_user_id(self, user_id: int) -> UserJoinedVoiceChannel: pass @abstractmethod - def find_active_user_joined_voice_channel_by_user_id( - self, user_id: int - ) -> Optional[UserJoinedVoiceChannel]: + def find_active_user_joined_voice_channel_by_user_id(self, user_id: int) -> Optional[UserJoinedVoiceChannel]: pass @abstractmethod - def find_active_user_joined_voice_channels_by_user_id( - self, user_id: int - ) -> List[Optional[UserJoinedVoiceChannel]]: + def find_active_user_joined_voice_channels_by_user_id(self, user_id: int) -> List[Optional[UserJoinedVoiceChannel]]: pass @abstractmethod - def add_user_joined_voice_channel( - self, user_joined_voice_channel: UserJoinedVoiceChannel - ): + def add_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel): pass @abstractmethod - def update_user_joined_voice_channel( - self, user_joined_voice_channel: UserJoinedVoiceChannel - ): + def update_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel): pass @abstractmethod - def delete_user_joined_voice_channel( - self, user_joined_voice_channel: UserJoinedVoiceChannel - ): + def delete_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel): pass @abstractmethod diff --git a/bot/src/bot_data/abc/user_message_count_per_hour_repository_abc.py b/bot/src/bot_data/abc/user_message_count_per_hour_repository_abc.py index 778177fa..59108387 100644 --- a/bot/src/bot_data/abc/user_message_count_per_hour_repository_abc.py +++ b/bot/src/bot_data/abc/user_message_count_per_hour_repository_abc.py @@ -17,9 +17,7 @@ class UserMessageCountPerHourRepositoryABC(ABC): pass @abstractmethod - def find_user_message_count_per_hour_by_user_id( - self, user_id: int - ) -> Optional[UserMessageCountPerHour]: + def find_user_message_count_per_hour_by_user_id(self, user_id: int) -> Optional[UserMessageCountPerHour]: pass @abstractmethod diff --git a/bot/src/bot_data/abc/user_repository_abc.py b/bot/src/bot_data/abc/user_repository_abc.py index 1605e24d..0e3ced21 100644 --- a/bot/src/bot_data/abc/user_repository_abc.py +++ b/bot/src/bot_data/abc/user_repository_abc.py @@ -32,15 +32,11 @@ class UserRepositoryABC(ABC): pass @abstractmethod - def get_user_by_discord_id_and_server_id( - self, discord_id: int, server_id: int - ) -> User: + def get_user_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> User: pass @abstractmethod - def find_user_by_discord_id_and_server_id( - self, discord_id: int, server_id: int - ) -> Optional[User]: + def find_user_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> Optional[User]: pass @abstractmethod diff --git a/bot/src/bot_data/data_module.py b/bot/src/bot_data/data_module.py index ad38d4f6..cec9cb37 100644 --- a/bot/src/bot_data/data_module.py +++ b/bot/src/bot_data/data_module.py @@ -86,14 +86,10 @@ class DataModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.data_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): 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) @@ -102,15 +98,9 @@ class DataModule(ModuleABC): services.add_transient(UserRepositoryABC, UserRepositoryService) services.add_transient(ClientRepositoryABC, ClientRepositoryService) services.add_transient(KnownUserRepositoryABC, KnownUserRepositoryService) - services.add_transient( - UserJoinedServerRepositoryABC, UserJoinedServerRepositoryService - ) - services.add_transient( - UserJoinedVoiceChannelRepositoryABC, UserJoinedVoiceChannelRepositoryService - ) - services.add_transient( - UserJoinedGameServerRepositoryABC, UserJoinedGameServerRepositoryService - ) + services.add_transient(UserJoinedServerRepositoryABC, UserJoinedServerRepositoryService) + services.add_transient(UserJoinedVoiceChannelRepositoryABC, UserJoinedVoiceChannelRepositoryService) + services.add_transient(UserJoinedGameServerRepositoryABC, UserJoinedGameServerRepositoryService) services.add_transient(AutoRoleRepositoryABC, AutoRoleRepositoryService) services.add_transient(LevelRepositoryABC, LevelRepositoryService) services.add_transient(UserWarningsRepositoryABC, UserWarningsRepositoryService) @@ -119,20 +109,12 @@ class DataModule(ModuleABC): UserMessageCountPerHourRepositoryService, ) services.add_transient(GameServerRepositoryABC, GameServerRepositoryService) - services.add_transient( - UserGameIdentRepositoryABC, UserGameIdentRepositoryService - ) + services.add_transient(UserGameIdentRepositoryABC, UserGameIdentRepositoryService) services.add_transient(AchievementRepositoryABC, AchievementRepositoryService) - services.add_transient( - TechnicianConfigRepositoryABC, TechnicianConfigRepositoryService - ) + services.add_transient(TechnicianConfigRepositoryABC, TechnicianConfigRepositoryService) services.add_transient(ServerConfigRepositoryABC, ServerConfigRepositoryService) - services.add_transient( - ShortRoleNameRepositoryABC, ShortRoleNameRepositoryService - ) - services.add_transient( - SteamSpecialOfferRepositoryABC, SteamSpecialOfferRepositoryService - ) + services.add_transient(ShortRoleNameRepositoryABC, ShortRoleNameRepositoryService) + services.add_transient(SteamSpecialOfferRepositoryABC, SteamSpecialOfferRepositoryService) services.add_transient(SeederService) services.add_transient(DataSeederABC, TechnicianConfigSeeder) diff --git a/bot/src/bot_data/migration/achievements_migration.py b/bot/src/bot_data/migration/achievements_migration.py index b58299c2..f3a454d3 100644 --- a/bot/src/bot_data/migration/achievements_migration.py +++ b/bot/src/bot_data/migration/achievements_migration.py @@ -74,30 +74,12 @@ class AchievementsMigration(MigrationABC): # A join table history between users and achievements is not necessary. - self._cursor.execute( - str( - f"""ALTER TABLE Users ADD MessageCount BIGINT NOT NULL DEFAULT 0 AFTER XP;""" - ) - ) - self._cursor.execute( - str( - f"""ALTER TABLE Users ADD ReactionCount BIGINT NOT NULL DEFAULT 0 AFTER XP;""" - ) - ) - self._cursor.execute( - str( - f"""ALTER TABLE UsersHistory ADD MessageCount BIGINT NOT NULL DEFAULT 0 AFTER XP;""" - ) - ) - self._cursor.execute( - str( - f"""ALTER TABLE UsersHistory ADD ReactionCount BIGINT NOT NULL DEFAULT 0 AFTER XP;""" - ) - ) + self._cursor.execute(str(f"""ALTER TABLE Users ADD MessageCount BIGINT NOT NULL DEFAULT 0 AFTER XP;""")) + self._cursor.execute(str(f"""ALTER TABLE Users ADD ReactionCount BIGINT NOT NULL DEFAULT 0 AFTER XP;""")) + self._cursor.execute(str(f"""ALTER TABLE UsersHistory ADD MessageCount BIGINT NOT NULL DEFAULT 0 AFTER XP;""")) + self._cursor.execute(str(f"""ALTER TABLE UsersHistory ADD ReactionCount BIGINT NOT NULL DEFAULT 0 AFTER XP;""")) - self._cursor.execute( - str(f"""DROP TRIGGER IF EXISTS `TR_AchievementsUpdate`;""") - ) + self._cursor.execute(str(f"""DROP TRIGGER IF EXISTS `TR_AchievementsUpdate`;""")) self._cursor.execute( str( f""" @@ -117,9 +99,7 @@ class AchievementsMigration(MigrationABC): ) ) - self._cursor.execute( - str(f"""DROP TRIGGER IF EXISTS `TR_AchievementsDelete`;""") - ) + self._cursor.execute(str(f"""DROP TRIGGER IF EXISTS `TR_AchievementsDelete`;""")) self._cursor.execute( str( diff --git a/bot/src/bot_data/migration/config_feature_flags_migration.py b/bot/src/bot_data/migration/config_feature_flags_migration.py index a4654bb1..f9046565 100644 --- a/bot/src/bot_data/migration/config_feature_flags_migration.py +++ b/bot/src/bot_data/migration/config_feature_flags_migration.py @@ -16,15 +16,11 @@ class ConfigFeatureFlagsMigration(MigrationABC): self._logger.debug(__name__, "Running upgrade") self._cursor.execute( - str( - """ALTER TABLE CFG_Technician ADD FeatureFlags JSON NULL DEFAULT ('{}') AFTER CacheMaxMessages;""" - ) + str("""ALTER TABLE CFG_Technician ADD FeatureFlags JSON NULL DEFAULT ('{}') AFTER CacheMaxMessages;""") ) self._cursor.execute( - str( - """ALTER TABLE CFG_Server ADD FeatureFlags JSON NULL DEFAULT ('{}') AFTER LoginMessageChannelId;""" - ) + str("""ALTER TABLE CFG_Server ADD FeatureFlags JSON NULL DEFAULT ('{}') AFTER LoginMessageChannelId;""") ) def downgrade(self): diff --git a/bot/src/bot_data/migration/fix_updates_migration.py b/bot/src/bot_data/migration/fix_updates_migration.py index 9f2420e3..f4d5e020 100644 --- a/bot/src/bot_data/migration/fix_updates_migration.py +++ b/bot/src/bot_data/migration/fix_updates_migration.py @@ -47,7 +47,5 @@ class FixUpdatesMigration(MigrationABC): """ ) ) - self._cursor.execute( - "ALTER TABLE CFG_TechnicianHistory DROP COLUMN FeatureFlags;" - ) + self._cursor.execute("ALTER TABLE CFG_TechnicianHistory DROP COLUMN FeatureFlags;") self._cursor.execute("ALTER TABLE CFG_ServerHistory DROP COLUMN FeatureFlags;") diff --git a/bot/src/bot_data/model/achievement.py b/bot/src/bot_data/model/achievement.py index 97a3e059..ebce645d 100644 --- a/bot/src/bot_data/model/achievement.py +++ b/bot/src/bot_data/model/achievement.py @@ -34,9 +34,7 @@ class Achievement(TableABC): TableABC.__init__(self) 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 @ServiceProviderABC.inject def _is_operator_valid(self, operator, service: ServiceProviderABC) -> bool: diff --git a/bot/src/bot_data/model/api_key.py b/bot/src/bot_data/model/api_key.py index 20abc12d..d63c4d1b 100644 --- a/bot/src/bot_data/model/api_key.py +++ b/bot/src/bot_data/model/api_key.py @@ -23,9 +23,7 @@ class ApiKey(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/auth_user.py b/bot/src/bot_data/model/auth_user.py index cdc6d8a2..47bdf41a 100644 --- a/bot/src/bot_data/model/auth_user.py +++ b/bot/src/bot_data/model/auth_user.py @@ -49,9 +49,7 @@ class AuthUser(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/auth_user_users_relation.py b/bot/src/bot_data/model/auth_user_users_relation.py index 25e66301..23b9ceab 100644 --- a/bot/src/bot_data/model/auth_user_users_relation.py +++ b/bot/src/bot_data/model/auth_user_users_relation.py @@ -19,9 +19,7 @@ class AuthUserUsersRelation(TableABC): TableABC.__init__(self) 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 auth_user(self) -> AuthUser: diff --git a/bot/src/bot_data/model/auto_role.py b/bot/src/bot_data/model/auto_role.py index e8b446c7..a1ff7934 100644 --- a/bot/src/bot_data/model/auto_role.py +++ b/bot/src/bot_data/model/auto_role.py @@ -25,9 +25,7 @@ class AutoRole(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/auto_role_rule.py b/bot/src/bot_data/model/auto_role_rule.py index f90fd86f..8729b6ec 100644 --- a/bot/src/bot_data/model/auto_role_rule.py +++ b/bot/src/bot_data/model/auto_role_rule.py @@ -24,9 +24,7 @@ class AutoRoleRule(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/client.py b/bot/src/bot_data/model/client.py index e8c56adf..b6c163c9 100644 --- a/bot/src/bot_data/model/client.py +++ b/bot/src/bot_data/model/client.py @@ -32,9 +32,7 @@ class Client(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/game_server.py b/bot/src/bot_data/model/game_server.py index 8cc510af..eeea20d8 100644 --- a/bot/src/bot_data/model/game_server.py +++ b/bot/src/bot_data/model/game_server.py @@ -23,9 +23,7 @@ class GameServer(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/known_user.py b/bot/src/bot_data/model/known_user.py index e07bcf83..37d375f0 100644 --- a/bot/src/bot_data/model/known_user.py +++ b/bot/src/bot_data/model/known_user.py @@ -16,9 +16,7 @@ class KnownUser(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/level.py b/bot/src/bot_data/model/level.py index bdad1826..a20d268b 100644 --- a/bot/src/bot_data/model/level.py +++ b/bot/src/bot_data/model/level.py @@ -27,9 +27,7 @@ class Level(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/server.py b/bot/src/bot_data/model/server.py index 5ae54ca7..d86c6e97 100644 --- a/bot/src/bot_data/model/server.py +++ b/bot/src/bot_data/model/server.py @@ -18,9 +18,7 @@ class Server(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/server_afk_channel_ids_config.py b/bot/src/bot_data/model/server_afk_channel_ids_config.py index 2c9042d9..9b182426 100644 --- a/bot/src/bot_data/model/server_afk_channel_ids_config.py +++ b/bot/src/bot_data/model/server_afk_channel_ids_config.py @@ -18,9 +18,7 @@ class ServerAFKChannelIdsConfig(TableABC): TableABC.__init__(self) 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 channel_id(self) -> int: diff --git a/bot/src/bot_data/model/server_config.py b/bot/src/bot_data/model/server_config.py index 3453de2f..cf220355 100644 --- a/bot/src/bot_data/model/server_config.py +++ b/bot/src/bot_data/model/server_config.py @@ -56,9 +56,7 @@ class ServerConfig(TableABC, ConfigurationModelABC): self._team_channel_id = team_channel_id self._login_message_channel_id = login_message_channel_id self._default_role_id = default_role_id - self._short_role_name_only_set_highest_role = ( - short_role_name_only_set_highest_role - ) + self._short_role_name_only_set_highest_role = short_role_name_only_set_highest_role self._game_offer_notification_chat_id = game_offer_notification_chat_id self._feature_flags = feature_flags @@ -68,9 +66,7 @@ class ServerConfig(TableABC, ConfigurationModelABC): TableABC.__init__(self) 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 @staticmethod def new(guild: Guild, server: Server) -> "ServerConfig": diff --git a/bot/src/bot_data/model/server_config_history.py b/bot/src/bot_data/model/server_config_history.py index 009491bd..6364f2eb 100644 --- a/bot/src/bot_data/model/server_config_history.py +++ b/bot/src/bot_data/model/server_config_history.py @@ -43,9 +43,7 @@ class ServerConfigHistory(HistoryTableABC): self._team_channel_id = team_channel_id self._login_message_channel_id = login_message_channel_id self._default_role_id = default_role_id - self._short_role_name_only_set_highest_role = ( - short_role_name_only_set_highest_role - ) + self._short_role_name_only_set_highest_role = short_role_name_only_set_highest_role self._feature_flags = feature_flags self._server_id = server_id diff --git a/bot/src/bot_data/model/server_team_role_ids_config.py b/bot/src/bot_data/model/server_team_role_ids_config.py index 7be73531..dfd870dd 100644 --- a/bot/src/bot_data/model/server_team_role_ids_config.py +++ b/bot/src/bot_data/model/server_team_role_ids_config.py @@ -22,9 +22,7 @@ class ServerTeamRoleIdsConfig(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/short_role_name.py b/bot/src/bot_data/model/short_role_name.py index d03b6ddc..4ddef4f1 100644 --- a/bot/src/bot_data/model/short_role_name.py +++ b/bot/src/bot_data/model/short_role_name.py @@ -27,9 +27,7 @@ class ShortRoleName(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/steam_special_offer.py b/bot/src/bot_data/model/steam_special_offer.py index 0b7e6927..76301dc4 100644 --- a/bot/src/bot_data/model/steam_special_offer.py +++ b/bot/src/bot_data/model/steam_special_offer.py @@ -22,9 +22,7 @@ class SteamSpecialOffer(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/technician_config.py b/bot/src/bot_data/model/technician_config.py index 9aab8628..1390f4b8 100644 --- a/bot/src/bot_data/model/technician_config.py +++ b/bot/src/bot_data/model/technician_config.py @@ -33,9 +33,7 @@ class TechnicianConfig(TableABC, ConfigurationModelABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/technician_id_config.py b/bot/src/bot_data/model/technician_id_config.py index 7db76b4b..6ba5f581 100644 --- a/bot/src/bot_data/model/technician_id_config.py +++ b/bot/src/bot_data/model/technician_id_config.py @@ -16,9 +16,7 @@ class TechnicianIdConfig(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/technician_ping_url_config.py b/bot/src/bot_data/model/technician_ping_url_config.py index bcc63b97..31983624 100644 --- a/bot/src/bot_data/model/technician_ping_url_config.py +++ b/bot/src/bot_data/model/technician_ping_url_config.py @@ -16,9 +16,7 @@ class TechnicianPingUrlConfig(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/user.py b/bot/src/bot_data/model/user.py index d1e7d514..ed44c58a 100644 --- a/bot/src/bot_data/model/user.py +++ b/bot/src/bot_data/model/user.py @@ -33,9 +33,7 @@ class User(TableABC): TableABC.__init__(self) 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: @@ -121,9 +119,7 @@ class User(TableABC): UserJoinedServerRepositoryABC, ) - ujs: UserJoinedServerRepositoryABC = services.get_service( - UserJoinedServerRepositoryABC - ) + ujs: UserJoinedServerRepositoryABC = services.get_service(UserJoinedServerRepositoryABC) return ujs.find_active_user_joined_server_by_user_id(self.id) is None @property @@ -136,9 +132,7 @@ class User(TableABC): UserGameIdentRepositoryABC, ) - game_idents_repo: UserGameIdentRepositoryABC = services.get_service( - UserGameIdentRepositoryABC - ) + game_idents_repo: UserGameIdentRepositoryABC = services.get_service(UserGameIdentRepositoryABC) return game_idents_repo.get_user_game_idents_by_user_id(self.id) @staticmethod diff --git a/bot/src/bot_data/model/user_game_ident.py b/bot/src/bot_data/model/user_game_ident.py index 11d88a66..79468d13 100644 --- a/bot/src/bot_data/model/user_game_ident.py +++ b/bot/src/bot_data/model/user_game_ident.py @@ -23,9 +23,7 @@ class UserGameIdent(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/user_got_achievement.py b/bot/src/bot_data/model/user_got_achievement.py index 373bfe05..d2c37cf5 100644 --- a/bot/src/bot_data/model/user_got_achievement.py +++ b/bot/src/bot_data/model/user_got_achievement.py @@ -22,9 +22,7 @@ class UserGotAchievement(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/user_history.py b/bot/src/bot_data/model/user_history.py index 461550fe..357c854a 100644 --- a/bot/src/bot_data/model/user_history.py +++ b/bot/src/bot_data/model/user_history.py @@ -64,9 +64,7 @@ class UserHistory(HistoryTableABC): UserJoinedServerRepositoryABC, ) - ujs: UserJoinedServerRepositoryABC = services.get_service( - UserJoinedServerRepositoryABC - ) + ujs: UserJoinedServerRepositoryABC = services.get_service(UserJoinedServerRepositoryABC) return ujs.find_active_user_joined_server_by_user_id(self.id) is None @property @@ -79,7 +77,5 @@ class UserHistory(HistoryTableABC): UserGameIdentRepositoryABC, ) - game_idents_repo: UserGameIdentRepositoryABC = services.get_service( - UserGameIdentRepositoryABC - ) + game_idents_repo: UserGameIdentRepositoryABC = services.get_service(UserGameIdentRepositoryABC) return game_idents_repo.get_user_game_idents_by_user_id(self.id) diff --git a/bot/src/bot_data/model/user_joined_game_server.py b/bot/src/bot_data/model/user_joined_game_server.py index 8cfaae11..cf60229d 100644 --- a/bot/src/bot_data/model/user_joined_game_server.py +++ b/bot/src/bot_data/model/user_joined_game_server.py @@ -25,9 +25,7 @@ class UserJoinedGameServer(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/user_joined_server.py b/bot/src/bot_data/model/user_joined_server.py index 25cf2b27..e55cb60d 100644 --- a/bot/src/bot_data/model/user_joined_server.py +++ b/bot/src/bot_data/model/user_joined_server.py @@ -22,9 +22,7 @@ class UserJoinedServer(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/user_joined_voice_channel.py b/bot/src/bot_data/model/user_joined_voice_channel.py index 5764b5e8..3b938452 100644 --- a/bot/src/bot_data/model/user_joined_voice_channel.py +++ b/bot/src/bot_data/model/user_joined_voice_channel.py @@ -26,9 +26,7 @@ class UserJoinedVoiceChannel(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/user_message_count_per_hour.py b/bot/src/bot_data/model/user_message_count_per_hour.py index be0fdddc..7815ffa4 100644 --- a/bot/src/bot_data/model/user_message_count_per_hour.py +++ b/bot/src/bot_data/model/user_message_count_per_hour.py @@ -24,9 +24,7 @@ class UserMessageCountPerHour(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/model/user_warnings.py b/bot/src/bot_data/model/user_warnings.py index bd1e290c..99610a5f 100644 --- a/bot/src/bot_data/model/user_warnings.py +++ b/bot/src/bot_data/model/user_warnings.py @@ -24,9 +24,7 @@ class UserWarnings(TableABC): TableABC.__init__(self) 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: diff --git a/bot/src/bot_data/service/achievements_repository_service.py b/bot/src/bot_data/service/achievements_repository_service.py index 004a4a53..d8923db5 100644 --- a/bot/src/bot_data/service/achievements_repository_service.py +++ b/bot/src/bot_data/service/achievements_repository_service.py @@ -49,9 +49,7 @@ class AchievementRepositoryService(AchievementRepositoryABC): def get_achievements(self) -> List[Achievement]: achievements = List(Achievement) - self._logger.trace( - __name__, f"Send SQL command: {Achievement.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {Achievement.get_select_all_string()}") results = self._context.select(Achievement.get_select_all_string()) for result in results: self._logger.trace(__name__, f"Get user with id {result[0]}") @@ -60,9 +58,7 @@ class AchievementRepositoryService(AchievementRepositoryABC): return achievements def get_achievement_by_id(self, id: int) -> Achievement: - self._logger.trace( - __name__, f"Send SQL command: {Achievement.get_select_by_id_string(id)}" - ) + self._logger.trace(__name__, f"Send SQL command: {Achievement.get_select_by_id_string(id)}") result = self._context.select(Achievement.get_select_by_id_string(id))[0] return self._from_result(result) @@ -73,9 +69,7 @@ class AchievementRepositoryService(AchievementRepositoryABC): __name__, f"Send SQL command: {Achievement.get_select_by_server_id_string(server_id)}", ) - results = self._context.select( - Achievement.get_select_by_server_id_string(server_id) - ) + results = self._context.select(Achievement.get_select_by_server_id_string(server_id)) for result in results: self._logger.trace(__name__, f"Get user with id {result[0]}") achievements.append(self._from_result(result)) @@ -89,34 +83,26 @@ class AchievementRepositoryService(AchievementRepositoryABC): __name__, f"Send SQL command: {UserGotAchievement.get_select_by_user_id_string(user_id)}", ) - results = self._context.select( - UserGotAchievement.get_select_by_user_id_string(user_id) - ) + results = self._context.select(UserGotAchievement.get_select_by_user_id_string(user_id)) for result in results: self._logger.trace(__name__, f"Got UserGotAchievement with id {result[0]}") achievements_joins.append(self._join_from_result(result)) for achievements_join in achievements_joins: - results = self._context.select( - Achievement.get_select_by_id_string(achievements_join.achievement.id) - ) + results = self._context.select(Achievement.get_select_by_id_string(achievements_join.achievement.id)) for result in results: self._logger.trace(__name__, f"Got Achievement with id {result[0]}") achievements.append(self._from_result(result)) return achievements - def get_user_got_achievements_by_achievement_id( - self, achievement_id: int - ) -> List[Achievement]: + def get_user_got_achievements_by_achievement_id(self, achievement_id: int) -> List[Achievement]: achievements_joins = List(UserGotAchievement) self._logger.trace( __name__, f"Send SQL command: {UserGotAchievement.get_select_by_achievement_id_string(achievement_id)}", ) - results = self._context.select( - UserGotAchievement.get_select_by_achievement_id_string(achievement_id) - ) + results = self._context.select(UserGotAchievement.get_select_by_achievement_id_string(achievement_id)) for result in results: self._logger.trace(__name__, f"Got UserGotAchievement with id {result[0]}") achievements_joins.append(self._join_from_result(result)) diff --git a/bot/src/bot_data/service/api_key_repository_service.py b/bot/src/bot_data/service/api_key_repository_service.py index dfa6f72e..d4f57dfc 100644 --- a/bot/src/bot_data/service/api_key_repository_service.py +++ b/bot/src/bot_data/service/api_key_repository_service.py @@ -45,9 +45,7 @@ class ApiKeyRepositoryService(ApiKeyRepositoryABC): def get_api_keys(self) -> List[ApiKey]: api_keys = List(ApiKey) - self._logger.trace( - __name__, f"Send SQL command: {ApiKey.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {ApiKey.get_select_all_string()}") results = self._context.select(ApiKey.get_select_all_string()) for result in results: api_keys.append(self._api_key_from_result(result)) @@ -55,26 +53,16 @@ class ApiKeyRepositoryService(ApiKeyRepositoryABC): return api_keys def get_api_key(self, identifier: str, key: str) -> ApiKey: - self._logger.trace( - __name__, f"Send SQL command: {ApiKey.get_select_string(identifier, key)}" - ) - return self._api_key_from_result( - self._context.select(ApiKey.get_select_string(identifier, key))[0] - ) + self._logger.trace(__name__, f"Send SQL command: {ApiKey.get_select_string(identifier, key)}") + return self._api_key_from_result(self._context.select(ApiKey.get_select_string(identifier, key))[0]) def get_api_key_by_id(self, id: int) -> ApiKey: self._logger.trace(__name__, f"Send SQL command: {ApiKey.get_select_by_id(id)}") - return self._api_key_from_result( - self._context.select(ApiKey.get_select_by_id(id))[0] - ) + return self._api_key_from_result(self._context.select(ApiKey.get_select_by_id(id))[0]) def get_api_key_by_key(self, key: str) -> ApiKey: - self._logger.trace( - __name__, f"Send SQL command: {ApiKey.get_select_by_key(key)}" - ) - return self._api_key_from_result( - self._context.select(ApiKey.get_select_by_key(key))[0] - ) + self._logger.trace(__name__, f"Send SQL command: {ApiKey.get_select_by_key(key)}") + return self._api_key_from_result(self._context.select(ApiKey.get_select_by_key(key))[0]) def add_api_key(self, api_key: ApiKey): self._logger.trace(__name__, f"Send SQL command: {api_key.insert_string}") diff --git a/bot/src/bot_data/service/auth_user_repository_service.py b/bot/src/bot_data/service/auth_user_repository_service.py index 1b959068..00afe7ae 100644 --- a/bot/src/bot_data/service/auth_user_repository_service.py +++ b/bot/src/bot_data/service/auth_user_repository_service.py @@ -74,9 +74,7 @@ class AuthUserRepositoryService(AuthUserRepositoryABC): def get_all_auth_users(self) -> List[AuthUser]: users = List(AuthUser) - self._logger.trace( - __name__, f"Send SQL command: {AuthUser.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {AuthUser.get_select_all_string()}") results = self._context.select(AuthUser.get_select_all_string()) for result in results: self._logger.trace(__name__, f"Get auth user with id {result[0]}") @@ -84,36 +82,22 @@ class AuthUserRepositoryService(AuthUserRepositoryABC): return users - def get_filtered_auth_users( - self, criteria: AuthUserSelectCriteria - ) -> FilteredResult: + def get_filtered_auth_users(self, criteria: AuthUserSelectCriteria) -> FilteredResult: users = self.get_all_auth_users() - self._logger.trace( - __name__, f"Send SQL command: {AuthUser.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {AuthUser.get_select_all_string()}") query = users if criteria.first_name is not None and criteria.first_name != "": - query = query.where( - lambda x: criteria.first_name in x.first_name - or x.first_name == criteria.first_name - ) + query = query.where(lambda x: criteria.first_name in x.first_name or x.first_name == criteria.first_name) if criteria.last_name is not None and criteria.last_name != "": - query = query.where( - lambda x: criteria.last_name in x.last_name - or x.last_name == criteria.last_name - ) + query = query.where(lambda x: criteria.last_name in x.last_name or x.last_name == criteria.last_name) if criteria.email is not None and criteria.email != "": - query = query.where( - lambda x: criteria.email in x.email or x.email == criteria.email - ) + query = query.where(lambda x: criteria.email in x.email or x.email == criteria.email) if criteria.auth_role is not None: - query = query.where( - lambda x: x.auth_role == AuthRoleEnum(criteria.auth_role) - ) + query = query.where(lambda x: x.auth_role == AuthRoleEnum(criteria.auth_role)) # sort if ( @@ -144,16 +128,12 @@ class AuthUserRepositoryService(AuthUserRepositoryABC): return result def get_auth_user_by_email(self, email: str) -> AuthUser: - self._logger.trace( - __name__, f"Send SQL command: {AuthUser.get_select_by_email_string(email)}" - ) + self._logger.trace(__name__, f"Send SQL command: {AuthUser.get_select_by_email_string(email)}") result = self._context.select(AuthUser.get_select_by_email_string(email))[0] return self._user_from_result(result) def find_auth_user_by_email(self, email: str) -> Optional[AuthUser]: - self._logger.trace( - __name__, f"Send SQL command: {AuthUser.get_select_by_email_string(email)}" - ) + self._logger.trace(__name__, f"Send SQL command: {AuthUser.get_select_by_email_string(email)}") result = self._context.select(AuthUser.get_select_by_email_string(email)) if result is None or len(result) == 0: return None @@ -180,9 +160,7 @@ class AuthUserRepositoryService(AuthUserRepositoryABC): __name__, f"Send SQL command: {AuthUser.get_select_by_forgot_password_id_string(id)}", ) - result = self._context.select( - AuthUser.get_select_by_forgot_password_id_string(id) - ) + result = self._context.select(AuthUser.get_select_by_forgot_password_id_string(id)) if result is None or len(result) == 0: return None diff --git a/bot/src/bot_data/service/auto_role_repository_service.py b/bot/src/bot_data/service/auto_role_repository_service.py index e739962a..bf0d781a 100644 --- a/bot/src/bot_data/service/auto_role_repository_service.py +++ b/bot/src/bot_data/service/auto_role_repository_service.py @@ -25,9 +25,7 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC): def get_auto_roles(self) -> List[AutoRole]: auto_roles = List(AutoRole) - self._logger.trace( - __name__, f"Send SQL command: {AutoRole.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {AutoRole.get_select_all_string()}") results = self._context.select(AutoRole.get_select_all_string()) for result in results: auto_roles.append( @@ -44,9 +42,7 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC): return auto_roles def get_auto_role_by_id(self, id: int) -> AutoRole: - self._logger.trace( - __name__, f"Send SQL command: {AutoRole.get_select_by_id_string(id)}" - ) + self._logger.trace(__name__, f"Send SQL command: {AutoRole.get_select_by_id_string(id)}") result = self._context.select(AutoRole.get_select_by_id_string(id))[0] return AutoRole( self._servers.get_server_by_id(result[1]), @@ -58,9 +54,7 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC): ) def find_auto_role_by_id(self, id: int) -> Optional[AutoRole]: - self._logger.trace( - __name__, f"Send SQL command: {AutoRole.get_select_by_id_string(id)}" - ) + self._logger.trace(__name__, f"Send SQL command: {AutoRole.get_select_by_id_string(id)}") result = self._context.select(AutoRole.get_select_by_id_string(id)) if result is None or len(result) == 0: return None @@ -77,9 +71,7 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC): ) def get_auto_roles_by_server_id(self, id: int) -> List[AutoRole]: - self._logger.trace( - __name__, f"Send SQL command: {AutoRole.get_select_by_server_id_string(id)}" - ) + self._logger.trace(__name__, f"Send SQL command: {AutoRole.get_select_by_server_id_string(id)}") auto_roles = List(AutoRole) results = self._context.select(AutoRole.get_select_by_server_id_string(id)) for result in results: @@ -145,9 +137,7 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC): def get_auto_role_rules(self) -> List[AutoRoleRule]: auto_role_rules = List(AutoRoleRule) - self._logger.trace( - __name__, f"Send SQL command: {AutoRoleRule.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {AutoRoleRule.get_select_all_string()}") results = self._context.select(AutoRoleRule.get_select_all_string()) for result in results: auto_role_rules.append( @@ -164,9 +154,7 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC): return auto_role_rules def get_auto_role_rule_by_id(self, id: int) -> AutoRoleRule: - self._logger.trace( - __name__, f"Send SQL command: {AutoRoleRule.get_select_by_id_string(id)}" - ) + self._logger.trace(__name__, f"Send SQL command: {AutoRoleRule.get_select_by_id_string(id)}") result = self._context.select(AutoRoleRule.get_select_by_id_string(id))[0] return AutoRoleRule( self.get_auto_role_by_id(result[1]), @@ -183,9 +171,7 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC): __name__, f"Send SQL command: {AutoRoleRule.get_select_by_auto_role_id_string(id)}", ) - results = self._context.select( - AutoRoleRule.get_select_by_auto_role_id_string(id) - ) + results = self._context.select(AutoRoleRule.get_select_by_auto_role_id_string(id)) for result in results: auto_role_rules.append( AutoRoleRule( @@ -201,19 +187,13 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC): return auto_role_rules def add_auto_role_rule(self, auto_role_rule: AutoRoleRule): - self._logger.trace( - __name__, f"Send SQL command: {auto_role_rule.insert_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {auto_role_rule.insert_string}") self._context.cursor.execute(auto_role_rule.insert_string) def update_auto_role_rule(self, auto_role_rule: AutoRoleRule): - self._logger.trace( - __name__, f"Send SQL command: {auto_role_rule.udpate_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {auto_role_rule.udpate_string}") self._context.cursor.execute(auto_role_rule.udpate_string) def delete_auto_role_rule(self, auto_role_rule: AutoRoleRule): - self._logger.trace( - __name__, f"Send SQL command: {auto_role_rule.delete_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {auto_role_rule.delete_string}") self._context.cursor.execute(auto_role_rule.delete_string) diff --git a/bot/src/bot_data/service/client_repository_service.py b/bot/src/bot_data/service/client_repository_service.py index ce92d9ad..e3d08ad3 100644 --- a/bot/src/bot_data/service/client_repository_service.py +++ b/bot/src/bot_data/service/client_repository_service.py @@ -25,9 +25,7 @@ class ClientRepositoryService(ClientRepositoryABC): def get_clients(self) -> List[Client]: clients = List(Client) - self._logger.trace( - __name__, f"Send SQL command: {Client.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {Client.get_select_all_string()}") results = self._context.select(Client.get_select_all_string()) for result in results: self._logger.trace(__name__, f"Get client with id {result[0]}") @@ -49,9 +47,7 @@ class ClientRepositoryService(ClientRepositoryABC): return clients def get_client_by_id(self, client_id: int) -> Client: - self._logger.trace( - __name__, f"Send SQL command: {Client.get_select_by_id_string(client_id)}" - ) + self._logger.trace(__name__, f"Send SQL command: {Client.get_select_by_id_string(client_id)}") result = self._context.select(Client.get_select_by_id_string(client_id)) return Client( result[1], @@ -96,9 +92,7 @@ class ClientRepositoryService(ClientRepositoryABC): __name__, f"Send SQL command: {Client.get_select_by_discord_id_string(discord_id)}", ) - result = self._context.select( - Client.get_select_by_discord_id_string(discord_id) - )[0] + result = self._context.select(Client.get_select_by_discord_id_string(discord_id))[0] return Client( result[1], result[2], @@ -117,9 +111,7 @@ class ClientRepositoryService(ClientRepositoryABC): __name__, f"Send SQL command: {Client.get_select_by_discord_id_string(discord_id)}", ) - result = self._context.select( - Client.get_select_by_discord_id_string(discord_id) - ) + result = self._context.select(Client.get_select_by_discord_id_string(discord_id)) if result is None or len(result) == 0: return None @@ -162,16 +154,12 @@ class ClientRepositoryService(ClientRepositoryABC): id=result[0], ) - def find_client_by_discord_id_and_server_id( - self, discord_id: int, server_id: int - ) -> Optional[Client]: + def find_client_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> Optional[Client]: self._logger.trace( __name__, f"Send SQL command: {Client.get_select_by_discord_id_and_server_id_string(discord_id, server_id)}", ) - result = self._context.select( - Client.get_select_by_discord_id_and_server_id_string(discord_id, server_id) - ) + result = self._context.select(Client.get_select_by_discord_id_and_server_id_string(discord_id, server_id)) if result is None or len(result) == 0: return None diff --git a/bot/src/bot_data/service/game_server_repository_service.py b/bot/src/bot_data/service/game_server_repository_service.py index 0a87b95e..1bdd0aeb 100644 --- a/bot/src/bot_data/service/game_server_repository_service.py +++ b/bot/src/bot_data/service/game_server_repository_service.py @@ -42,9 +42,7 @@ class GameServerRepositoryService(GameServerRepositoryABC): ) results = self._context.select(GameServer.get_select_all_string()) for result in results: - self._logger.trace( - __name__, f"Get user-joined-game-server with id {result[0]}" - ) + self._logger.trace(__name__, f"Get user-joined-game-server with id {result[0]}") game_servers.append(self._from_result(result)) return game_servers @@ -57,9 +55,7 @@ class GameServerRepositoryService(GameServerRepositoryABC): ) results = self._context.select(GameServer.get_select_by_server_id_string(id)) for result in results: - self._logger.trace( - __name__, f"Get user-joined-game-server with id {result[0]}" - ) + self._logger.trace(__name__, f"Get user-joined-game-server with id {result[0]}") game_servers.append(self._from_result(result)) return game_servers diff --git a/bot/src/bot_data/service/known_user_repository_service.py b/bot/src/bot_data/service/known_user_repository_service.py index 5ef2d7c5..b7dc57e2 100644 --- a/bot/src/bot_data/service/known_user_repository_service.py +++ b/bot/src/bot_data/service/known_user_repository_service.py @@ -25,9 +25,7 @@ class KnownUserRepositoryService(KnownUserRepositoryABC): def get_users(self) -> List[KnownUser]: users = List(KnownUser) - self._logger.trace( - __name__, f"Send SQL command: {KnownUser.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {KnownUser.get_select_all_string()}") results = self._context.select(KnownUser.get_select_all_string()) for result in results: self._logger.trace(__name__, f"Get known_user with id {result[0]}") @@ -36,9 +34,7 @@ class KnownUserRepositoryService(KnownUserRepositoryABC): return users def get_user_by_id(self, id: int) -> KnownUser: - self._logger.trace( - __name__, f"Send SQL command: {KnownUser.get_select_by_id_string(id)}" - ) + self._logger.trace(__name__, f"Send SQL command: {KnownUser.get_select_by_id_string(id)}") result = self._context.select(KnownUser.get_select_by_id_string(id)) return KnownUser(result[1], result[2], result[3], id=result[0]) @@ -47,9 +43,7 @@ class KnownUserRepositoryService(KnownUserRepositoryABC): __name__, f"Send SQL command: {KnownUser.get_select_by_discord_id_string(discord_id)}", ) - result = self._context.select( - KnownUser.get_select_by_discord_id_string(discord_id) - )[0] + result = self._context.select(KnownUser.get_select_by_discord_id_string(discord_id))[0] return KnownUser(result[1], result[2], result[3], id=result[0]) def find_user_by_discord_id(self, discord_id: int) -> Optional[KnownUser]: @@ -57,9 +51,7 @@ class KnownUserRepositoryService(KnownUserRepositoryABC): __name__, f"Send SQL command: {KnownUser.get_select_by_discord_id_string(discord_id)}", ) - result = self._context.select( - KnownUser.get_select_by_discord_id_string(discord_id) - ) + result = self._context.select(KnownUser.get_select_by_discord_id_string(discord_id)) if result is None or len(result) == 0: return None diff --git a/bot/src/bot_data/service/level_repository_service.py b/bot/src/bot_data/service/level_repository_service.py index e7828104..c713c0da 100644 --- a/bot/src/bot_data/service/level_repository_service.py +++ b/bot/src/bot_data/service/level_repository_service.py @@ -42,9 +42,7 @@ class LevelRepositoryService(LevelRepositoryABC): def get_levels(self) -> List[Level]: levels = List(Level) - self._logger.trace( - __name__, f"Send SQL command: {Level.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {Level.get_select_all_string()}") results = self._context.select(Level.get_select_all_string()) for result in results: self._logger.trace(__name__, f"Get level with id {result[0]}") @@ -53,17 +51,13 @@ class LevelRepositoryService(LevelRepositoryABC): return levels def get_level_by_id(self, id: int) -> Level: - self._logger.trace( - __name__, f"Send SQL command: {Level.get_select_by_id_string(id)}" - ) + self._logger.trace(__name__, f"Send SQL command: {Level.get_select_by_id_string(id)}") result = self._context.select(Level.get_select_by_id_string(id))[0] return self._level_from_result(result) def find_level_by_id(self, id: int) -> Optional[Level]: - self._logger.trace( - __name__, f"Send SQL command: {Level.get_select_by_id_string(id)}" - ) + self._logger.trace(__name__, f"Send SQL command: {Level.get_select_by_id_string(id)}") result = self._context.select(Level.get_select_by_id_string(id)) if result is None or len(result) == 0: return None diff --git a/bot/src/bot_data/service/migration_service.py b/bot/src/bot_data/service/migration_service.py index cf6303e9..dc6436a7 100644 --- a/bot/src/bot_data/service/migration_service.py +++ b/bot/src/bot_data/service/migration_service.py @@ -21,9 +21,7 @@ class MigrationService: self._cursor = db.cursor self._migrations: List[MigrationABC] = ( - List(type, MigrationABC.__subclasses__()) - .order_by(lambda x: x.name) - .order_by(lambda x: x.prio) + List(type, MigrationABC.__subclasses__()).order_by(lambda x: x.name).order_by(lambda x: x.prio) ) def migrate(self): @@ -40,21 +38,15 @@ class MigrationService: __name__, f"Running SQL Command: {MigrationHistory.get_select_by_id_string(migration_id)}", ) - migration_from_db = self._db.select( - MigrationHistory.get_select_by_id_string(migration_id) - ) + migration_from_db = self._db.select(MigrationHistory.get_select_by_id_string(migration_id)) if migration_from_db is not None and len(migration_from_db) > 0: continue self._logger.debug(__name__, f"Running Migration {migration_id}") - migration_as_service: MigrationABC = self._services.get_service( - migration - ) + migration_as_service: MigrationABC = self._services.get_service(migration) migration_as_service.upgrade() self._cursor.execute(MigrationHistory(migration_id).insert_string) self._db.save_changes() except Exception as e: - self._logger.error( - __name__, f"Cannot get migration with id {migration}", e - ) + self._logger.error(__name__, f"Cannot get migration with id {migration}", e) diff --git a/bot/src/bot_data/service/server_config_repository_service.py b/bot/src/bot_data/service/server_config_repository_service.py index 9ff8bf10..45d1aeaa 100644 --- a/bot/src/bot_data/service/server_config_repository_service.py +++ b/bot/src/bot_data/service/server_config_repository_service.py @@ -31,13 +31,9 @@ class ServerConfigRepositoryService(ServerConfigRepositoryABC): __name__, f"Send SQL command: {ServerTeamRoleIdsConfig.get_select_by_server_id_string(server_id)}", ) - results = self._context.select( - ServerTeamRoleIdsConfig.get_select_by_server_id_string(server_id) - ) + results = self._context.select(ServerTeamRoleIdsConfig.get_select_by_server_id_string(server_id)) for result in results: - self._logger.trace( - __name__, f"Got ServerTeamRoleIdsConfig with id {result[0]}" - ) + self._logger.trace(__name__, f"Got ServerTeamRoleIdsConfig with id {result[0]}") ids.append( ServerTeamRoleIdsConfig( result[1], @@ -57,13 +53,9 @@ class ServerConfigRepositoryService(ServerConfigRepositoryABC): __name__, f"Send SQL command: {ServerAFKChannelIdsConfig.get_select_by_server_id_string(server_id)}", ) - results = self._context.select( - ServerAFKChannelIdsConfig.get_select_by_server_id_string(server_id) - ) + results = self._context.select(ServerAFKChannelIdsConfig.get_select_by_server_id_string(server_id)) for result in results: - self._logger.trace( - __name__, f"Got ServerAFKChannelIdsConfig with id {result[0]}" - ) + self._logger.trace(__name__, f"Got ServerAFKChannelIdsConfig with id {result[0]}") urls.append(result[1]) return urls @@ -101,9 +93,7 @@ class ServerConfigRepositoryService(ServerConfigRepositoryABC): __name__, f"Send SQL command: {ServerConfig.get_select_by_server_id_string(server_id)}", ) - result = self._context.select( - ServerConfig.get_select_by_server_id_string(server_id) - ) + result = self._context.select(ServerConfig.get_select_by_server_id_string(server_id)) return len(result) > 0 @@ -112,9 +102,7 @@ class ServerConfigRepositoryService(ServerConfigRepositoryABC): __name__, f"Send SQL command: {ServerConfig.get_select_by_server_id_string(server_id)}", ) - result = self._context.select( - ServerConfig.get_select_by_server_id_string(server_id) - )[0] + result = self._context.select(ServerConfig.get_select_by_server_id_string(server_id))[0] return self._from_result(result) @@ -123,9 +111,7 @@ class ServerConfigRepositoryService(ServerConfigRepositoryABC): __name__, f"Send SQL command: {ServerConfig.get_select_by_id_string(config_id)}", ) - result = self._context.select(ServerConfig.get_select_by_id_string(config_id))[ - 0 - ] + result = self._context.select(ServerConfig.get_select_by_id_string(config_id))[0] return self._from_result(result) @@ -141,50 +127,26 @@ class ServerConfigRepositoryService(ServerConfigRepositoryABC): self._logger.trace(__name__, f"Send SQL command: {server_config.delete_string}") self._context.cursor.execute(server_config.delete_string) - def add_server_team_role_id_config( - self, server_team_role_id: ServerTeamRoleIdsConfig - ): - self._logger.trace( - __name__, f"Send SQL command: {server_team_role_id.insert_string}" - ) + def add_server_team_role_id_config(self, server_team_role_id: ServerTeamRoleIdsConfig): + self._logger.trace(__name__, f"Send SQL command: {server_team_role_id.insert_string}") self._context.cursor.execute(server_team_role_id.insert_string) - def update_server_team_role_id_config( - self, server_team_role_id: ServerTeamRoleIdsConfig - ): - self._logger.trace( - __name__, f"Send SQL command: {server_team_role_id.udpate_string}" - ) + def update_server_team_role_id_config(self, server_team_role_id: ServerTeamRoleIdsConfig): + self._logger.trace(__name__, f"Send SQL command: {server_team_role_id.udpate_string}") self._context.cursor.execute(server_team_role_id.udpate_string) - def delete_server_team_role_id_config( - self, server_team_role_id: ServerTeamRoleIdsConfig - ): - self._logger.trace( - __name__, f"Send SQL command: {server_team_role_id.delete_string}" - ) + def delete_server_team_role_id_config(self, server_team_role_id: ServerTeamRoleIdsConfig): + self._logger.trace(__name__, f"Send SQL command: {server_team_role_id.delete_string}") self._context.cursor.execute(server_team_role_id.delete_string) - def add_server_afk_channel_config( - self, server_afk_channel: ServerAFKChannelIdsConfig - ): - self._logger.trace( - __name__, f"Send SQL command: {server_afk_channel.insert_string}" - ) + def add_server_afk_channel_config(self, server_afk_channel: ServerAFKChannelIdsConfig): + self._logger.trace(__name__, f"Send SQL command: {server_afk_channel.insert_string}") self._context.cursor.execute(server_afk_channel.insert_string) - def update_server_afk_channel_config( - self, server_afk_channel: ServerAFKChannelIdsConfig - ): - self._logger.trace( - __name__, f"Send SQL command: {server_afk_channel.udpate_string}" - ) + def update_server_afk_channel_config(self, server_afk_channel: ServerAFKChannelIdsConfig): + self._logger.trace(__name__, f"Send SQL command: {server_afk_channel.udpate_string}") self._context.cursor.execute(server_afk_channel.udpate_string) - def delete_server_afk_channel_config( - self, server_afk_channel: ServerAFKChannelIdsConfig - ): - self._logger.trace( - __name__, f"Send SQL command: {server_afk_channel.delete_string}" - ) + def delete_server_afk_channel_config(self, server_afk_channel: ServerAFKChannelIdsConfig): + self._logger.trace(__name__, f"Send SQL command: {server_afk_channel.delete_string}") self._context.cursor.execute(server_afk_channel.delete_string) diff --git a/bot/src/bot_data/service/server_repository_service.py b/bot/src/bot_data/service/server_repository_service.py index 43f54c3d..5817d7dc 100644 --- a/bot/src/bot_data/service/server_repository_service.py +++ b/bot/src/bot_data/service/server_repository_service.py @@ -26,9 +26,7 @@ class ServerRepositoryService(ServerRepositoryABC): def get_servers(self) -> List[Server]: servers = List(Server) - self._logger.trace( - __name__, f"Send SQL command: {Server.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {Server.get_select_all_string()}") results = self._context.select(Server.get_select_all_string()) for result in results: servers.append(Server(result[1], result[2], result[3], id=result[0])) @@ -38,9 +36,7 @@ class ServerRepositoryService(ServerRepositoryABC): def get_filtered_servers(self, criteria: ServerSelectCriteria) -> FilteredResult: servers = self.get_servers() - self._logger.trace( - __name__, f"Send SQL command: {Server.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {Server.get_select_all_string()}") query = servers # sort @@ -52,9 +48,7 @@ class ServerRepositoryService(ServerRepositoryABC): ): crit_sort_direction = criteria.sort_direction.lower() if crit_sort_direction == "desc" or crit_sort_direction == "descending": - query = query.order_by_descending( - lambda x: getattr(x, criteria.sort_column) - ) + query = query.order_by_descending(lambda x: getattr(x, criteria.sort_column)) else: query = query.order_by(lambda x: getattr(x, criteria.sort_column)) @@ -66,25 +60,19 @@ class ServerRepositoryService(ServerRepositoryABC): return result def get_server_by_id(self, server_id: int) -> Server: - cs = self._cache.cached_server.where( - lambda x: x.id == server_id - ).single_or_default() + cs = self._cache.cached_server.where(lambda x: x.id == server_id).single_or_default() if cs is not None: return cs - self._logger.trace( - __name__, f"Send SQL command: {Server.get_select_by_id_string(server_id)}" - ) + self._logger.trace(__name__, f"Send SQL command: {Server.get_select_by_id_string(server_id)}") result = self._context.select(Server.get_select_by_id_string(server_id))[0] server = Server(result[1], result[2], result[3], id=result[0]) self._cache.add_server(server) return server def get_server_by_discord_id(self, discord_id: int) -> Server: - cs = self._cache.cached_server.where( - lambda x: x.discord_id == discord_id - ).single_or_default() + cs = self._cache.cached_server.where(lambda x: x.discord_id == discord_id).single_or_default() if cs is not None: return cs @@ -92,15 +80,11 @@ class ServerRepositoryService(ServerRepositoryABC): __name__, f"Send SQL command: {Server.get_select_by_discord_id_string(discord_id)}", ) - result = self._context.select( - Server.get_select_by_discord_id_string(discord_id) - )[0] + result = self._context.select(Server.get_select_by_discord_id_string(discord_id))[0] return Server(result[1], result[2], result[3], id=result[0]) def find_server_by_discord_id(self, discord_id: int) -> Optional[Server]: - cs = self._cache.cached_server.where( - lambda x: x.discord_id == discord_id - ).single_or_default() + cs = self._cache.cached_server.where(lambda x: x.discord_id == discord_id).single_or_default() if cs is not None: return cs @@ -108,9 +92,7 @@ class ServerRepositoryService(ServerRepositoryABC): __name__, f"Send SQL command: {Server.get_select_by_discord_id_string(discord_id)}", ) - result = self._context.select( - Server.get_select_by_discord_id_string(discord_id) - ) + result = self._context.select(Server.get_select_by_discord_id_string(discord_id)) if result is None or len(result) == 0: return None diff --git a/bot/src/bot_data/service/short_role_name_repository_service.py b/bot/src/bot_data/service/short_role_name_repository_service.py index 5b6a929e..3c4bed64 100644 --- a/bot/src/bot_data/service/short_role_name_repository_service.py +++ b/bot/src/bot_data/service/short_role_name_repository_service.py @@ -35,9 +35,7 @@ class ShortRoleNameRepositoryService(ShortRoleNameRepositoryABC): return ShortRoleName( self._get_value_from_result(sql_result[1]), # name int(self._get_value_from_result(sql_result[2])), # role_id - ShortRoleNamePositionEnum( - self._get_value_from_result(sql_result[3]) - ), # position + ShortRoleNamePositionEnum(self._get_value_from_result(sql_result[3])), # position self._servers.get_server_by_id(sql_result[4]), # server self._get_value_from_result(sql_result[5]), # created_at self._get_value_from_result(sql_result[6]), # modified_at @@ -46,9 +44,7 @@ class ShortRoleNameRepositoryService(ShortRoleNameRepositoryABC): def get_short_role_names(self) -> List[ShortRoleName]: short_role_names = List(ShortRoleName) - self._logger.trace( - __name__, f"Send SQL command: {ShortRoleName.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {ShortRoleName.get_select_all_string()}") results = self._context.select(ShortRoleName.get_select_all_string()) for result in results: self._logger.trace(__name__, f"Get short_role_name with id {result[0]}") @@ -57,9 +53,7 @@ class ShortRoleNameRepositoryService(ShortRoleNameRepositoryABC): return short_role_names def get_short_role_name_by_id(self, id: int) -> ShortRoleName: - self._logger.trace( - __name__, f"Send SQL command: {ShortRoleName.get_select_by_id_string(id)}" - ) + self._logger.trace(__name__, f"Send SQL command: {ShortRoleName.get_select_by_id_string(id)}") result = self._context.select(ShortRoleName.get_select_by_id_string(id))[0] return self._short_role_name_from_result(result) @@ -70,9 +64,7 @@ class ShortRoleNameRepositoryService(ShortRoleNameRepositoryABC): __name__, f"Send SQL command: {ShortRoleName.get_select_by_role_id_string(role_id)}", ) - results = self._context.select( - ShortRoleName.get_select_by_role_id_string(role_id) - ) + results = self._context.select(ShortRoleName.get_select_by_role_id_string(role_id)) for result in results: self._logger.trace(__name__, f"Get short_role_name with id {result[0]}") short_role_names.append(self._short_role_name_from_result(result)) @@ -85,9 +77,7 @@ class ShortRoleNameRepositoryService(ShortRoleNameRepositoryABC): __name__, f"Send SQL command: {ShortRoleName.get_select_by_server_id_string(server_id)}", ) - results = self._context.select( - ShortRoleName.get_select_by_server_id_string(server_id) - ) + results = self._context.select(ShortRoleName.get_select_by_server_id_string(server_id)) for result in results: self._logger.trace(__name__, f"Get short_role_name with id {result[0]}") @@ -96,19 +86,13 @@ class ShortRoleNameRepositoryService(ShortRoleNameRepositoryABC): return short_role_names def add_short_role_name(self, short_role_name: ShortRoleName): - self._logger.trace( - __name__, f"Send SQL command: {short_role_name.insert_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {short_role_name.insert_string}") self._context.cursor.execute(short_role_name.insert_string) def update_short_role_name(self, short_role_name: ShortRoleName): - self._logger.trace( - __name__, f"Send SQL command: {short_role_name.udpate_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {short_role_name.udpate_string}") self._context.cursor.execute(short_role_name.udpate_string) def delete_short_role_name(self, short_role_name: ShortRoleName): - self._logger.trace( - __name__, f"Send SQL command: {short_role_name.delete_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {short_role_name.delete_string}") self._context.cursor.execute(short_role_name.delete_string) diff --git a/bot/src/bot_data/service/steam_special_offer_repository_service.py b/bot/src/bot_data/service/steam_special_offer_repository_service.py index 256f01b2..dfd0e7ee 100644 --- a/bot/src/bot_data/service/steam_special_offer_repository_service.py +++ b/bot/src/bot_data/service/steam_special_offer_repository_service.py @@ -43,9 +43,7 @@ class SteamSpecialOfferRepositoryService(SteamSpecialOfferRepositoryABC): def get_steam_special_offers(self) -> List[SteamSpecialOffer]: steam_special_offers = List(SteamSpecialOffer) - self._logger.trace( - __name__, f"Send SQL command: {SteamSpecialOffer.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {SteamSpecialOffer.get_select_all_string()}") results = self._context.select(SteamSpecialOffer.get_select_all_string()) for result in results: self._logger.trace(__name__, f"Get steam_special_offer with id {result[0]}") @@ -58,26 +56,18 @@ class SteamSpecialOfferRepositoryService(SteamSpecialOfferRepositoryABC): __name__, f"Send SQL command: {SteamSpecialOffer.get_select_by_name_string(name)}", ) - result = self._context.select( - SteamSpecialOffer.get_select_by_name_string(name) - )[0] + result = self._context.select(SteamSpecialOffer.get_select_by_name_string(name))[0] return self._steam_special_offer_from_result(result) def add_steam_special_offer(self, steam_special_offer: SteamSpecialOffer): - self._logger.trace( - __name__, f"Send SQL command: {steam_special_offer.insert_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {steam_special_offer.insert_string}") self._context.cursor.execute(steam_special_offer.insert_string) def update_steam_special_offer(self, steam_special_offer: SteamSpecialOffer): - self._logger.trace( - __name__, f"Send SQL command: {steam_special_offer.udpate_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {steam_special_offer.udpate_string}") self._context.cursor.execute(steam_special_offer.udpate_string) def delete_steam_special_offer(self, steam_special_offer: SteamSpecialOffer): - self._logger.trace( - __name__, f"Send SQL command: {steam_special_offer.delete_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {steam_special_offer.delete_string}") self._context.cursor.execute(steam_special_offer.delete_string) diff --git a/bot/src/bot_data/service/technician_config_repository_service.py b/bot/src/bot_data/service/technician_config_repository_service.py index 3d31b415..3500bbde 100644 --- a/bot/src/bot_data/service/technician_config_repository_service.py +++ b/bot/src/bot_data/service/technician_config_repository_service.py @@ -19,9 +19,7 @@ class TechnicianConfigRepositoryService(TechnicianConfigRepositoryABC): def _get_technician_ids(self) -> List[int]: ids = List(int) - self._logger.trace( - __name__, f"Send SQL command: {TechnicianIdConfig.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {TechnicianIdConfig.get_select_all_string()}") results = self._context.select(TechnicianIdConfig.get_select_all_string()) for result in results: self._logger.trace(__name__, f"Got TechnicianId with id {result[0]}") @@ -57,37 +55,27 @@ class TechnicianConfigRepositoryService(TechnicianConfigRepositoryABC): ) def does_technician_config_exists(self) -> bool: - self._logger.trace( - __name__, f"Send SQL command: {TechnicianConfig.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {TechnicianConfig.get_select_all_string()}") result = self._context.select(TechnicianConfig.get_select_all_string()) return len(result) > 0 def get_technician_config(self) -> TechnicianConfig: - self._logger.trace( - __name__, f"Send SQL command: {TechnicianConfig.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {TechnicianConfig.get_select_all_string()}") result = self._context.select(TechnicianConfig.get_select_all_string())[0] return self._from_result(result) def add_technician_config(self, technician_config: TechnicianConfig): - self._logger.trace( - __name__, f"Send SQL command: {technician_config.insert_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {technician_config.insert_string}") self._context.cursor.execute(technician_config.insert_string) def update_technician_config(self, technician_config: TechnicianConfig): - self._logger.trace( - __name__, f"Send SQL command: {technician_config.udpate_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {technician_config.udpate_string}") self._context.cursor.execute(technician_config.udpate_string) def delete_technician_config(self, technician_config: TechnicianConfig): - self._logger.trace( - __name__, f"Send SQL command: {technician_config.delete_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {technician_config.delete_string}") self._context.cursor.execute(technician_config.delete_string) def add_technician_id_config(self, technician_id: TechnicianIdConfig): @@ -102,26 +90,14 @@ class TechnicianConfigRepositoryService(TechnicianConfigRepositoryABC): self._logger.trace(__name__, f"Send SQL command: {technician_id.delete_string}") self._context.cursor.execute(technician_id.delete_string) - def add_technician_ping_url_config( - self, technician_ping_url: TechnicianPingUrlConfig - ): - self._logger.trace( - __name__, f"Send SQL command: {technician_ping_url.insert_string}" - ) + def add_technician_ping_url_config(self, technician_ping_url: TechnicianPingUrlConfig): + self._logger.trace(__name__, f"Send SQL command: {technician_ping_url.insert_string}") self._context.cursor.execute(technician_ping_url.insert_string) - def update_technician_ping_url_config( - self, technician_ping_url: TechnicianPingUrlConfig - ): - self._logger.trace( - __name__, f"Send SQL command: {technician_ping_url.udpate_string}" - ) + def update_technician_ping_url_config(self, technician_ping_url: TechnicianPingUrlConfig): + self._logger.trace(__name__, f"Send SQL command: {technician_ping_url.udpate_string}") self._context.cursor.execute(technician_ping_url.udpate_string) - def delete_technician_ping_url_config( - self, technician_ping_url: TechnicianPingUrlConfig - ): - self._logger.trace( - __name__, f"Send SQL command: {technician_ping_url.delete_string}" - ) + def delete_technician_ping_url_config(self, technician_ping_url: TechnicianPingUrlConfig): + self._logger.trace(__name__, f"Send SQL command: {technician_ping_url.delete_string}") self._context.cursor.execute(technician_ping_url.delete_string) diff --git a/bot/src/bot_data/service/technician_config_seeder.py b/bot/src/bot_data/service/technician_config_seeder.py index 09dfd3bc..3107db0a 100644 --- a/bot/src/bot_data/service/technician_config_seeder.py +++ b/bot/src/bot_data/service/technician_config_seeder.py @@ -42,14 +42,10 @@ class TechnicianConfigSeeder(DataSeederABC): self._technician_config.add_technician_config(config) for technician in config.technician_ids: - self._technician_config.add_technician_id_config( - TechnicianIdConfig(technician) - ) + self._technician_config.add_technician_id_config(TechnicianIdConfig(technician)) for url in config.ping_urls: - self._technician_config.add_technician_ping_url_config( - TechnicianPingUrlConfig(url) - ) + self._technician_config.add_technician_ping_url_config(TechnicianPingUrlConfig(url)) self._db.save_changes() self._logger.debug(__name__, "Seeded technician config") diff --git a/bot/src/bot_data/service/user_game_ident_repository_service.py b/bot/src/bot_data/service/user_game_ident_repository_service.py index 0039d85e..d0dfc38b 100644 --- a/bot/src/bot_data/service/user_game_ident_repository_service.py +++ b/bot/src/bot_data/service/user_game_ident_repository_service.py @@ -51,17 +51,13 @@ class UserGameIdentRepositoryService(UserGameIdentRepositoryABC): return joins - def get_user_game_idents_by_game_server_id( - self, game_server_id: int - ) -> List[UserGameIdent]: + def get_user_game_idents_by_game_server_id(self, game_server_id: int) -> List[UserGameIdent]: joins = List(UserGameIdent) self._logger.trace( __name__, f"Send SQL command: {UserGameIdent.get_select_by_game_server_id_string(game_server_id)}", ) - results = self._context.select( - UserGameIdent.get_select_by_game_server_id_string(game_server_id) - ) + results = self._context.select(UserGameIdent.get_select_by_game_server_id_string(game_server_id)) for result in results: self._logger.trace(__name__, f"Get UserGameIdent with id {result[0]}") joins.append(self._from_result(result)) @@ -81,9 +77,7 @@ class UserGameIdentRepositoryService(UserGameIdentRepositoryABC): __name__, f"Send SQL command: {UserGameIdent.get_select_by_ident_string(ident)}", ) - result = self._context.select(UserGameIdent.get_select_by_ident_string(ident))[ - 0 - ] + result = self._context.select(UserGameIdent.get_select_by_ident_string(ident))[0] return self._from_result(result) def find_user_game_ident_by_ident(self, ident: str) -> Optional[UserGameIdent]: @@ -104,30 +98,22 @@ class UserGameIdentRepositoryService(UserGameIdentRepositoryABC): __name__, f"Send SQL command: {UserGameIdent.get_select_by_user_id_string(user_id)}", ) - results = self._context.select( - UserGameIdent.get_select_by_user_id_string(user_id) - ) + results = self._context.select(UserGameIdent.get_select_by_user_id_string(user_id)) for result in results: joins.append(self._from_result(result)) return joins def add_user_game_ident(self, user_game_ident: UserGameIdent): - self._logger.trace( - __name__, f"Send SQL command: {user_game_ident.insert_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {user_game_ident.insert_string}") self._context.cursor.execute(user_game_ident.insert_string) def update_user_game_ident(self, user_game_ident: UserGameIdent): - self._logger.trace( - __name__, f"Send SQL command: {user_game_ident.udpate_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {user_game_ident.udpate_string}") self._context.cursor.execute(user_game_ident.udpate_string) def delete_user_game_ident(self, user_game_ident: UserGameIdent): - self._logger.trace( - __name__, f"Send SQL command: {user_game_ident.delete_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {user_game_ident.delete_string}") self._context.cursor.execute(user_game_ident.delete_string) def delete_user_game_ident_by_user_id(self, user_id: int): diff --git a/bot/src/bot_data/service/user_joined_game_server_repository_service.py b/bot/src/bot_data/service/user_joined_game_server_repository_service.py index 5f1a3627..e9ded8ba 100644 --- a/bot/src/bot_data/service/user_joined_game_server_repository_service.py +++ b/bot/src/bot_data/service/user_joined_game_server_repository_service.py @@ -46,9 +46,7 @@ class UserJoinedGameServerRepositoryService(UserJoinedGameServerRepositoryABC): ) results = self._context.select(UserJoinedGameServer.get_select_all_string()) for result in results: - self._logger.trace( - __name__, f"Get user-joined-game-server with id {result[0]}" - ) + self._logger.trace(__name__, f"Get user-joined-game-server with id {result[0]}") joins.append(self._from_result(result)) return joins @@ -58,49 +56,35 @@ class UserJoinedGameServerRepositoryService(UserJoinedGameServerRepositoryABC): __name__, f"Send SQL command: {UserJoinedGameServer.get_select_by_id_string(id)}", ) - result = self._context.select(UserJoinedGameServer.get_select_by_id_string(id))[ - 0 - ] + result = self._context.select(UserJoinedGameServer.get_select_by_id_string(id))[0] return self._from_result(result) - def get_user_joined_game_servers_by_user_id( - self, user_id: int - ) -> List[UserJoinedGameServer]: + def get_user_joined_game_servers_by_user_id(self, user_id: int) -> List[UserJoinedGameServer]: joins = List(UserJoinedGameServer) self._logger.trace( __name__, f"Send SQL command: {UserJoinedGameServer.get_select_by_user_id_string(user_id)}", ) - results = self._context.select( - UserJoinedGameServer.get_select_by_user_id_string(user_id) - ) + results = self._context.select(UserJoinedGameServer.get_select_by_user_id_string(user_id)) for result in results: joins.append(self._from_result(result)) return joins - def get_active_user_joined_game_server_by_user_id( - self, user_id: int - ) -> UserJoinedGameServer: + def get_active_user_joined_game_server_by_user_id(self, user_id: int) -> UserJoinedGameServer: self._logger.trace( __name__, f"Send SQL command: {UserJoinedGameServer.get_select_by_user_id_string(user_id)}", ) - result = self._context.select( - UserJoinedGameServer.get_select_active_by_user_id_string(user_id) - )[0] + result = self._context.select(UserJoinedGameServer.get_select_active_by_user_id_string(user_id))[0] return self._from_result(result) - def find_active_user_joined_game_server_by_user_id( - self, user_id: int - ) -> Optional[UserJoinedGameServer]: + def find_active_user_joined_game_server_by_user_id(self, user_id: int) -> Optional[UserJoinedGameServer]: self._logger.trace( __name__, f"Send SQL command: {UserJoinedGameServer.get_select_by_user_id_string(user_id)}", ) - result = self._context.select( - UserJoinedGameServer.get_select_active_by_user_id_string(user_id) - ) + result = self._context.select(UserJoinedGameServer.get_select_active_by_user_id_string(user_id)) if result is None or len(result) == 0: return None @@ -108,45 +92,29 @@ class UserJoinedGameServerRepositoryService(UserJoinedGameServerRepositoryABC): return self._from_result(result) - def find_active_user_joined_game_servers_by_user_id( - self, user_id: int - ) -> List[Optional[UserJoinedGameServer]]: + def find_active_user_joined_game_servers_by_user_id(self, user_id: int) -> List[Optional[UserJoinedGameServer]]: self._logger.trace( __name__, f"Send SQL command: {UserJoinedGameServer.get_select_active_by_user_id_string(user_id)}", ) result = List(UserJoinedGameServer) - db_results = self._context.select( - UserJoinedGameServer.get_select_active_by_user_id_string(user_id) - ) + db_results = self._context.select(UserJoinedGameServer.get_select_active_by_user_id_string(user_id)) for db_result in db_results: result.append(self._from_result(db_result)) return result - def add_user_joined_game_server( - self, user_joined_game_server: UserJoinedGameServer - ): - self._logger.trace( - __name__, f"Send SQL command: {user_joined_game_server.insert_string}" - ) + def add_user_joined_game_server(self, user_joined_game_server: UserJoinedGameServer): + self._logger.trace(__name__, f"Send SQL command: {user_joined_game_server.insert_string}") self._context.cursor.execute(user_joined_game_server.insert_string) - def update_user_joined_game_server( - self, user_joined_game_server: UserJoinedGameServer - ): - self._logger.trace( - __name__, f"Send SQL command: {user_joined_game_server.udpate_string}" - ) + def update_user_joined_game_server(self, user_joined_game_server: UserJoinedGameServer): + self._logger.trace(__name__, f"Send SQL command: {user_joined_game_server.udpate_string}") self._context.cursor.execute(user_joined_game_server.udpate_string) - def delete_user_joined_game_server( - self, user_joined_game_server: UserJoinedGameServer - ): - self._logger.trace( - __name__, f"Send SQL command: {user_joined_game_server.delete_string}" - ) + def delete_user_joined_game_server(self, user_joined_game_server: UserJoinedGameServer): + self._logger.trace(__name__, f"Send SQL command: {user_joined_game_server.delete_string}") self._context.cursor.execute(user_joined_game_server.delete_string) def delete_user_joined_game_server_by_user_id(self, user_id: int): @@ -154,6 +122,4 @@ class UserJoinedGameServerRepositoryService(UserJoinedGameServerRepositoryABC): __name__, f"Send SQL command: {UserJoinedGameServer.delete_by_user_id_string}", ) - self._context.cursor.execute( - UserJoinedGameServer.delete_by_user_id_string(user_id) - ) + self._context.cursor.execute(UserJoinedGameServer.delete_by_user_id_string(user_id)) diff --git a/bot/src/bot_data/service/user_joined_server_repository_service.py b/bot/src/bot_data/service/user_joined_server_repository_service.py index 02d8f948..abd0a17b 100644 --- a/bot/src/bot_data/service/user_joined_server_repository_service.py +++ b/bot/src/bot_data/service/user_joined_server_repository_service.py @@ -25,9 +25,7 @@ class UserJoinedServerRepositoryService(UserJoinedServerRepositoryABC): def get_user_joined_servers(self) -> List[UserJoinedServer]: joins = List(UserJoinedServer) - self._logger.trace( - __name__, f"Send SQL command: {UserJoinedServer.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {UserJoinedServer.get_select_all_string()}") results = self._context.select(UserJoinedServer.get_select_all_string()) for result in results: self._logger.trace(__name__, f"Get user-joined-server with id {result[0]}") @@ -74,17 +72,13 @@ class UserJoinedServerRepositoryService(UserJoinedServerRepositoryABC): id=result[0], ) - def get_user_joined_servers_by_user_id( - self, user_id: int - ) -> List[UserJoinedServer]: + def get_user_joined_servers_by_user_id(self, user_id: int) -> List[UserJoinedServer]: joins = List(UserJoinedServer) self._logger.trace( __name__, f"Send SQL command: {UserJoinedServer.get_select_by_user_id_string(user_id)}", ) - results = self._context.select( - UserJoinedServer.get_select_by_user_id_string(user_id) - ) + results = self._context.select(UserJoinedServer.get_select_by_user_id_string(user_id)) for result in results: joins.append( UserJoinedServer( @@ -99,16 +93,12 @@ class UserJoinedServerRepositoryService(UserJoinedServerRepositoryABC): return joins - def get_active_user_joined_server_by_user_id( - self, user_id: int - ) -> UserJoinedServer: + def get_active_user_joined_server_by_user_id(self, user_id: int) -> UserJoinedServer: self._logger.trace( __name__, f"Send SQL command: {UserJoinedServer.get_select_by_user_id_string(user_id)}", ) - result = self._context.select( - UserJoinedServer.get_select_active_by_user_id_string(user_id) - )[0] + result = self._context.select(UserJoinedServer.get_select_active_by_user_id_string(user_id))[0] return UserJoinedServer( self._users.get_user_by_id(result[1]), result[2], @@ -118,16 +108,12 @@ class UserJoinedServerRepositoryService(UserJoinedServerRepositoryABC): id=result[0], ) - def find_active_user_joined_server_by_user_id( - self, user_id: int - ) -> Optional[UserJoinedServer]: + def find_active_user_joined_server_by_user_id(self, user_id: int) -> Optional[UserJoinedServer]: self._logger.trace( __name__, f"Send SQL command: {UserJoinedServer.get_select_by_user_id_string(user_id)}", ) - result = self._context.select( - UserJoinedServer.get_select_active_by_user_id_string(user_id) - ) + result = self._context.select(UserJoinedServer.get_select_active_by_user_id_string(user_id)) if result is None or len(result) == 0: return None @@ -143,19 +129,13 @@ class UserJoinedServerRepositoryService(UserJoinedServerRepositoryABC): ) def add_user_joined_server(self, user_joined_server: UserJoinedServer): - self._logger.trace( - __name__, f"Send SQL command: {user_joined_server.insert_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {user_joined_server.insert_string}") self._context.cursor.execute(user_joined_server.insert_string) def update_user_joined_server(self, user_joined_server: UserJoinedServer): - self._logger.trace( - __name__, f"Send SQL command: {user_joined_server.udpate_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {user_joined_server.udpate_string}") self._context.cursor.execute(user_joined_server.udpate_string) def delete_user_joined_server(self, user_joined_server: UserJoinedServer): - self._logger.trace( - __name__, f"Send SQL command: {user_joined_server.delete_string}" - ) + self._logger.trace(__name__, f"Send SQL command: {user_joined_server.delete_string}") self._context.cursor.execute(user_joined_server.delete_string) diff --git a/bot/src/bot_data/service/user_joined_voice_channel_repository_service.py b/bot/src/bot_data/service/user_joined_voice_channel_repository_service.py index f01216ac..c441d26a 100644 --- a/bot/src/bot_data/service/user_joined_voice_channel_repository_service.py +++ b/bot/src/bot_data/service/user_joined_voice_channel_repository_service.py @@ -33,9 +33,7 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB ) results = self._context.select(UserJoinedVoiceChannel.get_select_all_string()) for result in results: - self._logger.trace( - __name__, f"Get user-joined-voice-channel with id {result[0]}" - ) + self._logger.trace(__name__, f"Get user-joined-voice-channel with id {result[0]}") joins.append( UserJoinedVoiceChannel( self._users.get_user_by_id(result[1]), @@ -54,9 +52,7 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB __name__, f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_id_string(id)}", ) - result = self._context.select( - UserJoinedVoiceChannel.get_select_by_id_string(id) - )[0] + result = self._context.select(UserJoinedVoiceChannel.get_select_by_id_string(id))[0] return UserJoinedVoiceChannel( self._users.get_user_by_id(result[1]), result[2], @@ -66,17 +62,13 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB id=result[0], ) - def get_user_joined_voice_channels_by_user_id( - self, user_id: int - ) -> List[UserJoinedVoiceChannel]: + def get_user_joined_voice_channels_by_user_id(self, user_id: int) -> List[UserJoinedVoiceChannel]: joins = List(UserJoinedVoiceChannel) self._logger.trace( __name__, f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_user_id_string(user_id)}", ) - results = self._context.select( - UserJoinedVoiceChannel.get_select_by_user_id_string(user_id) - ) + results = self._context.select(UserJoinedVoiceChannel.get_select_by_user_id_string(user_id)) for result in results: joins.append( UserJoinedVoiceChannel( @@ -91,16 +83,12 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB return joins - def get_active_user_joined_voice_channel_by_user_id( - self, user_id: int - ) -> UserJoinedVoiceChannel: + def get_active_user_joined_voice_channel_by_user_id(self, user_id: int) -> UserJoinedVoiceChannel: self._logger.trace( __name__, f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_user_id_string(user_id)}", ) - result = self._context.select( - UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id) - )[0] + result = self._context.select(UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id))[0] return UserJoinedVoiceChannel( self._users.get_user_by_id(result[1]), result[2], @@ -110,16 +98,12 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB id=result[0], ) - def find_active_user_joined_voice_channel_by_user_id( - self, user_id: int - ) -> Optional[UserJoinedVoiceChannel]: + def find_active_user_joined_voice_channel_by_user_id(self, user_id: int) -> Optional[UserJoinedVoiceChannel]: self._logger.trace( __name__, f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_user_id_string(user_id)}", ) - result = self._context.select( - UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id) - ) + result = self._context.select(UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id)) if result is None or len(result) == 0: return None @@ -134,17 +118,13 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB id=result[0], ) - def find_active_user_joined_voice_channels_by_user_id( - self, user_id: int - ) -> List[Optional[UserJoinedVoiceChannel]]: + def find_active_user_joined_voice_channels_by_user_id(self, user_id: int) -> List[Optional[UserJoinedVoiceChannel]]: self._logger.trace( __name__, f"Send SQL command: {UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id)}", ) result = List(UserJoinedVoiceChannel) - db_results = self._context.select( - UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id) - ) + db_results = self._context.select(UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id)) for db_result in db_results: result.append( @@ -160,28 +140,16 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB return result - def add_user_joined_voice_channel( - self, user_joined_voice_channel: UserJoinedVoiceChannel - ): - self._logger.trace( - __name__, f"Send SQL command: {user_joined_voice_channel.insert_string}" - ) + def add_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel): + self._logger.trace(__name__, f"Send SQL command: {user_joined_voice_channel.insert_string}") self._context.cursor.execute(user_joined_voice_channel.insert_string) - def update_user_joined_voice_channel( - self, user_joined_voice_channel: UserJoinedVoiceChannel - ): - self._logger.trace( - __name__, f"Send SQL command: {user_joined_voice_channel.udpate_string}" - ) + def update_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel): + self._logger.trace(__name__, f"Send SQL command: {user_joined_voice_channel.udpate_string}") self._context.cursor.execute(user_joined_voice_channel.udpate_string) - def delete_user_joined_voice_channel( - self, user_joined_voice_channel: UserJoinedVoiceChannel - ): - self._logger.trace( - __name__, f"Send SQL command: {user_joined_voice_channel.delete_string}" - ) + def delete_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel): + self._logger.trace(__name__, f"Send SQL command: {user_joined_voice_channel.delete_string}") self._context.cursor.execute(user_joined_voice_channel.delete_string) def delete_user_joined_voice_channel_by_user_id(self, user_id: int): @@ -189,6 +157,4 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB __name__, f"Send SQL command: {UserJoinedVoiceChannel.delete_by_user_id_string}", ) - self._context.cursor.execute( - UserJoinedVoiceChannel.delete_by_user_id_string(user_id) - ) + self._context.cursor.execute(UserJoinedVoiceChannel.delete_by_user_id_string(user_id)) diff --git a/bot/src/bot_data/service/user_message_count_per_hour_repository_service.py b/bot/src/bot_data/service/user_message_count_per_hour_repository_service.py index 2ccb57e6..e63db818 100644 --- a/bot/src/bot_data/service/user_message_count_per_hour_repository_service.py +++ b/bot/src/bot_data/service/user_message_count_per_hour_repository_service.py @@ -51,16 +51,12 @@ class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepository ) results = self._context.select(UserMessageCountPerHour.get_select_all_string()) for result in results: - self._logger.trace( - __name__, f"Get user message count per hour with id {result[0]}" - ) + self._logger.trace(__name__, f"Get user message count per hour with id {result[0]}") umcphs.append(self._from_result(result)) return umcphs - def find_user_message_count_per_hour_by_user_id( - self, user_id: int - ) -> List[Optional[UserMessageCountPerHour]]: + def find_user_message_count_per_hour_by_user_id(self, user_id: int) -> List[Optional[UserMessageCountPerHour]]: umcphs = List(UserMessageCountPerHour) sql = UserMessageCountPerHour.get_select_by_user_id_string(user_id) self._logger.trace(__name__, f"Send SQL command: {sql}") @@ -69,9 +65,7 @@ class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepository return umcphs for result in results: - self._logger.trace( - __name__, f"Get user message count per hour with id {result[0]}" - ) + self._logger.trace(__name__, f"Get user message count per hour with id {result[0]}") umcphs.append(self._from_result(result)) return umcphs @@ -79,9 +73,7 @@ class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepository def get_user_message_count_per_hour_by_user_id_and_date( self, user_id: int, date: datetime ) -> UserMessageCountPerHour: - sql = UserMessageCountPerHour.get_select_by_user_id_and_date_string( - user_id, date - ) + sql = UserMessageCountPerHour.get_select_by_user_id_and_date_string(user_id, date) self._logger.trace(__name__, f"Send SQL command: {sql}") result = self._context.select(sql)[0] return self._from_result(result) @@ -89,9 +81,7 @@ class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepository def find_user_message_count_per_hour_by_user_id_and_date( self, user_id: int, date: datetime ) -> Optional[UserMessageCountPerHour]: - sql = UserMessageCountPerHour.get_select_by_user_id_and_date_string( - user_id, date - ) + sql = UserMessageCountPerHour.get_select_by_user_id_and_date_string(user_id, date) self._logger.trace(__name__, f"Send SQL command: {sql}") result = self._context.select(sql) if result is None or len(result) == 0: diff --git a/bot/src/bot_data/service/user_repository_service.py b/bot/src/bot_data/service/user_repository_service.py index b39cd560..940156a8 100644 --- a/bot/src/bot_data/service/user_repository_service.py +++ b/bot/src/bot_data/service/user_repository_service.py @@ -39,9 +39,7 @@ class UserRepositoryService(UserRepositoryABC): def get_users(self) -> List[User]: users = List(User) - self._logger.trace( - __name__, f"Send SQL command: {User.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {User.get_select_all_string()}") results = self._context.select(User.get_select_all_string()) for result in results: self._logger.trace(__name__, f"Get user with id {result[0]}") @@ -50,17 +48,13 @@ class UserRepositoryService(UserRepositoryABC): return users def get_user_by_id(self, id: int) -> User: - self._logger.trace( - __name__, f"Send SQL command: {User.get_select_by_id_string(id)}" - ) + self._logger.trace(__name__, f"Send SQL command: {User.get_select_by_id_string(id)}") result = self._context.select(User.get_select_by_id_string(id))[0] return self._from_result(result) def find_user_by_id(self, id: int) -> Optional[User]: - self._logger.trace( - __name__, f"Send SQL command: {User.get_select_by_id_string(id)}" - ) + self._logger.trace(__name__, f"Send SQL command: {User.get_select_by_id_string(id)}") result = self._context.select(User.get_select_by_id_string(id)) if result is None or len(result) == 0: return None @@ -93,29 +87,21 @@ class UserRepositoryService(UserRepositoryABC): return users - def get_user_by_discord_id_and_server_id( - self, discord_id: int, server_id: int - ) -> User: + def get_user_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> User: self._logger.trace( __name__, f"Send SQL command: {User.get_select_by_discord_id_and_server_id_string(discord_id, server_id)}", ) - result = self._context.select( - User.get_select_by_discord_id_and_server_id_string(discord_id, server_id) - )[0] + result = self._context.select(User.get_select_by_discord_id_and_server_id_string(discord_id, server_id))[0] return self._from_result(result) - def find_user_by_discord_id_and_server_id( - self, discord_id: int, server_id: int - ) -> Optional[User]: + def find_user_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> Optional[User]: self._logger.trace( __name__, f"Send SQL command: {User.get_select_by_discord_id_and_server_id_string(discord_id, server_id)}", ) - result = self._context.select( - User.get_select_by_discord_id_and_server_id_string(discord_id, server_id) - ) + result = self._context.select(User.get_select_by_discord_id_and_server_id_string(discord_id, server_id)) if result is None or len(result) == 0: return None diff --git a/bot/src/bot_data/service/user_warnings_repository_service.py b/bot/src/bot_data/service/user_warnings_repository_service.py index fade2db6..fbf7c4ee 100644 --- a/bot/src/bot_data/service/user_warnings_repository_service.py +++ b/bot/src/bot_data/service/user_warnings_repository_service.py @@ -47,9 +47,7 @@ class UserWarningsRepositoryService(UserWarningsRepositoryABC): def get_user_warnings(self) -> List[UserWarnings]: warnings = List(UserWarnings) - self._logger.trace( - __name__, f"Send SQL command: {UserWarnings.get_select_all_string()}" - ) + self._logger.trace(__name__, f"Send SQL command: {UserWarnings.get_select_all_string()}") results = self._context.select(UserWarnings.get_select_all_string()) for result in results: warnings.append(self._from_result(result)) @@ -57,9 +55,7 @@ class UserWarningsRepositoryService(UserWarningsRepositoryABC): return warnings def get_user_warnings_by_id(self, id: int) -> UserWarnings: - self._logger.trace( - __name__, f"Send SQL command: {UserWarnings.get_select_by_id_string(id)}" - ) + self._logger.trace(__name__, f"Send SQL command: {UserWarnings.get_select_by_id_string(id)}") result = self._context.select(UserWarnings.get_select_by_id_string(id))[0] return self._from_result(result) @@ -69,9 +65,7 @@ class UserWarningsRepositoryService(UserWarningsRepositoryABC): __name__, f"Send SQL command: {UserWarnings.get_select_by_user_id_string(user_id)}", ) - results = self._context.select( - UserWarnings.get_select_by_user_id_string(user_id) - ) + results = self._context.select(UserWarnings.get_select_by_user_id_string(user_id)) for result in results: warnings.append(self._from_result(result)) diff --git a/bot/src/bot_graphql/abc/filter_abc.py b/bot/src/bot_graphql/abc/filter_abc.py index aec7b1a9..e0d5ff8d 100644 --- a/bot/src/bot_graphql/abc/filter_abc.py +++ b/bot/src/bot_graphql/abc/filter_abc.py @@ -24,11 +24,7 @@ class FilterABC(ABC): sig = signature(f) for param in sig.parameters.items(): parameter = param[1] - if ( - parameter.name == "self" - or parameter.name == "cls" - or parameter.annotation == Parameter.empty - ): + if parameter.name == "self" or parameter.name == "cls" or parameter.annotation == Parameter.empty: continue if issubclass(parameter.annotation, FilterABC): @@ -38,9 +34,7 @@ class FilterABC(ABC): @staticmethod @ServiceProviderABC.inject - def get_collection_filter( - filter_type: type, values: dict, services: ServiceProviderABC - ): + def get_collection_filter(filter_type: type, values: dict, services: ServiceProviderABC): filter: FilterABC = services.get_service(filter_type) filter.from_dict(values) return filter diff --git a/bot/src/bot_graphql/abc/query_abc.py b/bot/src/bot_graphql/abc/query_abc.py index 535bbc59..850fb22b 100644 --- a/bot/src/bot_graphql/abc/query_abc.py +++ b/bot/src/bot_graphql/abc/query_abc.py @@ -38,14 +38,10 @@ class QueryABC(ObjectType): def __init__(self, name: str): ObjectType.__init__(self, name) - def add_collection( - self, name: str, get_collection: Callable, filter_type: type = None - ): + def add_collection(self, name: str, get_collection: Callable, filter_type: type = None): def wrapper(*args, **kwargs): if filter_type is not None and "filter" in kwargs: - kwargs["filter"] = FilterABC.get_collection_filter( - filter_type, kwargs["filter"] - ) + kwargs["filter"] = FilterABC.get_collection_filter(filter_type, kwargs["filter"]) else: kwargs["filter"] = None @@ -98,10 +94,7 @@ class QueryABC(ObjectType): u: User = u guild = bot.get_guild(u.server.discord_id) member = guild.get_member(u.discord_id) - if ( - permissions.is_member_moderator(member) - and u.server.id == element.server.id - ): + if permissions.is_member_moderator(member) and u.server.id == element.server.id: access = True break @@ -111,10 +104,7 @@ class QueryABC(ObjectType): u: User = u guild = bot.get_guild(u.server.discord_id) member = guild.get_member(u.discord_id) - if ( - permissions.is_member_moderator(member) - and u.server.id == element.server.id - ): + if permissions.is_member_moderator(member) and u.server.id == element.server.id: access = True break @@ -124,10 +114,7 @@ class QueryABC(ObjectType): u: User = u guild = bot.get_guild(u.server.discord_id) member = guild.get_member(u.discord_id) - if ( - permissions.is_member_moderator(member) - and u.server.id == element.auto_role.server.id - ): + if permissions.is_member_moderator(member) and u.server.id == element.auto_role.server.id: access = True break @@ -212,18 +199,11 @@ class QueryABC(ObjectType): u: User = u guild = bot.get_guild(u.server.discord_id) member = guild.get_member(u.discord_id) - if ( - permissions.is_member_moderator(member) - and u.server.id == element.server.id - ): + if permissions.is_member_moderator(member) and u.server.id == element.server.id: access = True break - elif ( - type(element) == dict - and "key" in element - and element["key"] in [e.value for e in FeatureFlagsEnum] - ): + elif type(element) == dict and "key" in element and element["key"] in [e.value for e in FeatureFlagsEnum]: for u in user.users: u: User = u guild = bot.get_guild(u.server.discord_id) @@ -235,9 +215,7 @@ class QueryABC(ObjectType): return access @ServiceProviderABC.inject - def _can_user_mutate_data( - self, server: Server, permission: UserRoleEnum, services: ServiceProviderABC - ): + def _can_user_mutate_data(self, server: Server, permission: UserRoleEnum, services: ServiceProviderABC): permissions: PermissionService = services.get_service(PermissionService) bot: DiscordBotServiceABC = services.get_service(DiscordBotServiceABC) @@ -246,9 +224,7 @@ class QueryABC(ObjectType): return member = bot.get_guild(server.discord_id).get_member( - auth_user.users.where(lambda x: x.server.id == server.id) - .single() - .discord_id + auth_user.users.where(lambda x: x.server.id == server.id).single().discord_id ) check_perm = lambda x: True @@ -261,9 +237,7 @@ class QueryABC(ObjectType): check_perm = lambda x: permissions.is_member_technician(x) if not check_perm(member): - ex = ServiceException( - ServiceErrorCode.Forbidden, f"User not allowed to mutate data" - ) + ex = ServiceException(ServiceErrorCode.Forbidden, f"User not allowed to mutate data") raise ex # @FilterABC.resolve_filter_annotation diff --git a/bot/src/bot_graphql/filter/achievement_filter.py b/bot/src/bot_graphql/filter/achievement_filter.py index 1e1afd11..b95e00c0 100644 --- a/bot/src/bot_graphql/filter/achievement_filter.py +++ b/bot/src/bot_graphql/filter/achievement_filter.py @@ -55,16 +55,10 @@ class AchievementFilter(FilterABC): query = query.where(lambda x: x.name == self._name or self._name in x.name) if self._description is not None: - query = query.where( - lambda x: x.description == self._description - or self._description in x.description - ) + query = query.where(lambda x: x.description == self._description or self._description in x.description) if self._attribute is not None: - query = query.where( - lambda x: x.attribute == self._attribute - or self._attribute in x.attribute - ) + query = query.where(lambda x: x.attribute == self._attribute or self._attribute in x.attribute) if self._operator is not None: query = query.where(lambda x: x.operator == self._operator) @@ -73,9 +67,7 @@ class AchievementFilter(FilterABC): query = query.where(lambda x: x.value == self._value) if self._server is not None: - servers = self._server.filter(query.select(lambda x: x.server)).select( - lambda x: x.id - ) + servers = self._server.filter(query.select(lambda x: x.server)).select(lambda x: x.id) query = query.where(lambda x: x.server.id in servers) return query diff --git a/bot/src/bot_graphql/filter/auto_role_filter.py b/bot/src/bot_graphql/filter/auto_role_filter.py index caa976d5..6f17dd59 100644 --- a/bot/src/bot_graphql/filter/auto_role_filter.py +++ b/bot/src/bot_graphql/filter/auto_role_filter.py @@ -46,26 +46,21 @@ class AutoRoleFilter(FilterABC): if self._channel_id is not None: query = query.where( - lambda x: x.discord_channel_id == self._channel_id - or str(self._channel_id) in str(x.discord_channel_id) + lambda x: x.discord_channel_id == self._channel_id or str(self._channel_id) in str(x.discord_channel_id) ) if self._channel_name is not None: query = query.where( - lambda x: x.discord_channel_name == self._channel_name - or self._channel_name in x.discord_channel_name + lambda x: x.discord_channel_name == self._channel_name or self._channel_name in x.discord_channel_name ) if self._message_id is not None: query = query.where( - lambda x: x.discord_message_id == self._message_id - or str(self._message_id) in str(x.discord_message_id) + lambda x: x.discord_message_id == self._message_id or str(self._message_id) in str(x.discord_message_id) ) if self._server is not None: - servers = self._server.filter(query.select(lambda x: x.server)).select( - lambda x: x.id - ) + servers = self._server.filter(query.select(lambda x: x.server)).select(lambda x: x.id) query = query.where(lambda x: x.server.id in servers) return query diff --git a/bot/src/bot_graphql/filter/auto_role_rule_filter.py b/bot/src/bot_graphql/filter/auto_role_rule_filter.py index 6d661147..b9571d8f 100644 --- a/bot/src/bot_graphql/filter/auto_role_rule_filter.py +++ b/bot/src/bot_graphql/filter/auto_role_rule_filter.py @@ -57,9 +57,7 @@ class AutoRoleRuleFilter(FilterABC): query = query.where(get_role_name) if self._auto_role is not None: - auto_roles = self._auto_role.filter( - query.select(lambda x: x.game_server) - ).select(lambda x: x.id) + auto_roles = self._auto_role.filter(query.select(lambda x: x.game_server)).select(lambda x: x.id) query = query.where(lambda x: x.game_server.id in auto_roles) return query diff --git a/bot/src/bot_graphql/filter/client_filter.py b/bot/src/bot_graphql/filter/client_filter.py index 8f46fca2..29563600 100644 --- a/bot/src/bot_graphql/filter/client_filter.py +++ b/bot/src/bot_graphql/filter/client_filter.py @@ -38,15 +38,10 @@ class ClientFilter(FilterABC): query = query.where(lambda x: x.id == self._discord_id) if self._name is not None: - query = query.where( - lambda x: self._name.lower() == x.name.lower() - or self._name.lower() in x.name.lower() - ) + query = query.where(lambda x: self._name.lower() == x.name.lower() or self._name.lower() in x.name.lower()) if self._server is not None: - servers = self._server.filter(query.select(lambda x: x.server)).select( - lambda x: x.id - ) + servers = self._server.filter(query.select(lambda x: x.server)).select(lambda x: x.id) query = query.where(lambda x: x.server.id in servers) return query diff --git a/bot/src/bot_graphql/filter/level_filter.py b/bot/src/bot_graphql/filter/level_filter.py index ebd8de39..2ded4ad8 100644 --- a/bot/src/bot_graphql/filter/level_filter.py +++ b/bot/src/bot_graphql/filter/level_filter.py @@ -33,15 +33,10 @@ class LevelFilter(FilterABC): query = query.where(lambda x: x.id == self._id) if self._name is not None: - query = query.where( - lambda x: self._name.lower() == x.name.lower() - or self._name.lower() in x.name.lower() - ) + query = query.where(lambda x: self._name.lower() == x.name.lower() or self._name.lower() in x.name.lower()) if self._server is not None: - servers = self._server.filter(query.select(lambda x: x.server)).select( - lambda x: x.id - ) + servers = self._server.filter(query.select(lambda x: x.server)).select(lambda x: x.id) query = query.where(lambda x: x.server.id in servers) return query diff --git a/bot/src/bot_graphql/filter/server_filter.py b/bot/src/bot_graphql/filter/server_filter.py index f6384146..e090323e 100644 --- a/bot/src/bot_graphql/filter/server_filter.py +++ b/bot/src/bot_graphql/filter/server_filter.py @@ -32,8 +32,7 @@ class ServerFilter(FilterABC): if self._discord_id is not None: query = query.where( - lambda x: x.discord_id == self._discord_id - or str(self._discord_id) in str(x.discord_id) + lambda x: x.discord_id == self._discord_id or str(self._discord_id) in str(x.discord_id) ) if self._name is not None: @@ -41,8 +40,7 @@ class ServerFilter(FilterABC): def where_guild(x: Guild): guild = bot.get_guild(x.discord_id) return guild is not None and ( - self._name.lower() == guild.name.lower() - or self._name.lower() in guild.name.lower() + self._name.lower() == guild.name.lower() or self._name.lower() in guild.name.lower() ) query = query.where(where_guild) diff --git a/bot/src/bot_graphql/filter/short_role_name_filter.py b/bot/src/bot_graphql/filter/short_role_name_filter.py index 2fb3b2be..426e3630 100644 --- a/bot/src/bot_graphql/filter/short_role_name_filter.py +++ b/bot/src/bot_graphql/filter/short_role_name_filter.py @@ -46,10 +46,7 @@ class ShortRoleNameFilter(FilterABC): query = query.where(lambda x: x.id == self._id) if self._short_name is not None: - query = query.where( - lambda x: x.short_name == self._short_name - or self._short_name in x.short_name - ) + query = query.where(lambda x: x.short_name == self._short_name or self._short_name in x.short_name) if self._role_id is not None: query = query.where(lambda x: x.role_id == self._role_id) @@ -67,9 +64,7 @@ class ShortRoleNameFilter(FilterABC): query = query.where(lambda x: x.position.value == self._position.value) if self._server is not None: - servers = self._server.filter(query.select(lambda x: x.server)).select( - lambda x: x.id - ) + servers = self._server.filter(query.select(lambda x: x.server)).select(lambda x: x.id) query = query.where(lambda x: x.server.id in servers) return query diff --git a/bot/src/bot_graphql/filter/user_filter.py b/bot/src/bot_graphql/filter/user_filter.py index 7a50f6d2..53c130d5 100644 --- a/bot/src/bot_graphql/filter/user_filter.py +++ b/bot/src/bot_graphql/filter/user_filter.py @@ -73,8 +73,7 @@ class UserFilter(FilterABC): if self._discord_id is not None: query = query.where( - lambda x: x.discord_id == self._discord_id - or str(self._discord_id) in str(x.discord_id) + lambda x: x.discord_id == self._discord_id or str(self._discord_id) in str(x.discord_id) ) if self._name is not None: @@ -82,9 +81,7 @@ class UserFilter(FilterABC): def _get_member(user: User): guild = self._bot.get_guild(user.server.discord_id) member = guild.get_member(user.discord_id) - return member is not None and ( - member.name == self._name or self._name in member.name - ) + return member is not None and (member.name == self._name or self._name in member.name) query = query.where(_get_member) @@ -92,30 +89,20 @@ class UserFilter(FilterABC): query = query.where(lambda x: x.xp == self._xp) if self._ontime is not None: - query = query.where( - lambda x: self._client_utils.get_ontime_for_user(x) == self._ontime - ) + query = query.where(lambda x: self._client_utils.get_ontime_for_user(x) == self._ontime) if self._level is not None: - levels = self._level.filter( - query.select(lambda x: self._levels.get_level(x)) - ).select(lambda x: x.id) + levels = self._level.filter(query.select(lambda x: self._levels.get_level(x))).select(lambda x: x.id) query = query.where(lambda x: self._levels.get_level(x).id in levels) if self._server is not None: - servers = self._server.filter(query.select(lambda x: x.server)).select( - lambda x: x.id - ) + servers = self._server.filter(query.select(lambda x: x.server)).select(lambda x: x.id) query = query.where(lambda x: x.server.id in servers) if self._left_server is not None: def _has_user_left_server(user: User): - active_join = ( - self._user_joined_servers.find_active_user_joined_server_by_user_id( - user.id - ) - ) + active_join = self._user_joined_servers.find_active_user_joined_server_by_user_id(user.id) return (active_join is None) == self._left_server query = query.where(_has_user_left_server) diff --git a/bot/src/bot_graphql/filter/user_joined_game_server_filter.py b/bot/src/bot_graphql/filter/user_joined_game_server_filter.py index 84297e50..1d266a70 100644 --- a/bot/src/bot_graphql/filter/user_joined_game_server_filter.py +++ b/bot/src/bot_graphql/filter/user_joined_game_server_filter.py @@ -42,9 +42,7 @@ class UserJoinedGameServerFilter(FilterABC): query = query.where(lambda x: x.game_server == self._game_server) if self._user is not None: - users = self._user.filter(query.select(lambda x: x.user)).select( - lambda x: x.id - ) + users = self._user.filter(query.select(lambda x: x.user)).select(lambda x: x.id) query = query.where(lambda x: x.user.id in users) return query diff --git a/bot/src/bot_graphql/filter/user_joined_server_filter.py b/bot/src/bot_graphql/filter/user_joined_server_filter.py index dd760752..3aac7e25 100644 --- a/bot/src/bot_graphql/filter/user_joined_server_filter.py +++ b/bot/src/bot_graphql/filter/user_joined_server_filter.py @@ -43,21 +43,13 @@ class UserJoinedServerFilter(FilterABC): query = query.where(lambda x: x.id == self._id) if self._user is not None: - users = self._user.filter(query.select(lambda x: x.user)).select( - lambda x: x.id - ) + users = self._user.filter(query.select(lambda x: x.user)).select(lambda x: x.id) query = query.where(lambda x: x.user.id in users) if self._joined_on is not None: - query = query.where( - lambda x: x.joined_on == self._joined_on - or self._joined_on in x.joined_on - ) + query = query.where(lambda x: x.joined_on == self._joined_on or self._joined_on in x.joined_on) if self._leaved_on is not None: - query = query.where( - lambda x: x.leaved_on == self._leaved_on - or self._leaved_on in x.leaved_on - ) + query = query.where(lambda x: x.leaved_on == self._leaved_on or self._leaved_on in x.leaved_on) return query diff --git a/bot/src/bot_graphql/filter/user_joined_voice_channel_filter.py b/bot/src/bot_graphql/filter/user_joined_voice_channel_filter.py index 681cf038..51ba446a 100644 --- a/bot/src/bot_graphql/filter/user_joined_voice_channel_filter.py +++ b/bot/src/bot_graphql/filter/user_joined_voice_channel_filter.py @@ -46,9 +46,7 @@ class UserJoinedVoiceChannelFilter(FilterABC): if "leavedOn" in values: self._leaved_on = values["leavedOn"] - def filter( - self, query: List[UserJoinedVoiceChannel] - ) -> List[UserJoinedVoiceChannel]: + def filter(self, query: List[UserJoinedVoiceChannel]) -> List[UserJoinedVoiceChannel]: if self._id is not None: query = query.where(lambda x: x.id == self._id) @@ -64,21 +62,13 @@ class UserJoinedVoiceChannelFilter(FilterABC): query = query.where(get_channel_name) if self._user is not None: - users = self._user.filter(query.select(lambda x: x.user)).select( - lambda x: x.id - ) + users = self._user.filter(query.select(lambda x: x.user)).select(lambda x: x.id) query = query.where(lambda x: x.user.id in users) if self._joined_on is not None: - query = query.where( - lambda x: x.joined_on == self._joined_on - or self._joined_on in x.joined_on - ) + query = query.where(lambda x: x.joined_on == self._joined_on or self._joined_on in x.joined_on) if self._leaved_on is not None: - query = query.where( - lambda x: x.leaved_on == self._leaved_on - or self._leaved_on in x.leaved_on - ) + query = query.where(lambda x: x.leaved_on == self._leaved_on or self._leaved_on in x.leaved_on) return query diff --git a/bot/src/bot_graphql/filter/user_warning_filter.py b/bot/src/bot_graphql/filter/user_warning_filter.py index c2d70df1..2c716c9e 100644 --- a/bot/src/bot_graphql/filter/user_warning_filter.py +++ b/bot/src/bot_graphql/filter/user_warning_filter.py @@ -43,21 +43,14 @@ class UserWarningFilter(FilterABC): query = query.where(lambda x: x.id == self._id) if self._user is not None: - users = self._user.filter(query.select(lambda x: x.user)).select( - lambda x: x.id - ) + users = self._user.filter(query.select(lambda x: x.user)).select(lambda x: x.id) query = query.where(lambda x: x.id in users) if self._description is not None: - query = query.where( - lambda x: x.description == self._description - or self._description in x.description - ) + query = query.where(lambda x: x.description == self._description or self._description in x.description) if self._author is not None: - users = self._author.filter(query.select(lambda x: x.author)).select( - lambda x: x.id - ) + users = self._author.filter(query.select(lambda x: x.author)).select(lambda x: x.id) query = query.where(lambda x: x.id in users) return query diff --git a/bot/src/bot_graphql/graphql_module.py b/bot/src/bot_graphql/graphql_module.py index 822556a4..e15e0c35 100644 --- a/bot/src/bot_graphql/graphql_module.py +++ b/bot/src/bot_graphql/graphql_module.py @@ -95,14 +95,10 @@ class GraphQLModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.data_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): pass - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): services.add_singleton(Schema) services.add_singleton(GraphQLService) services.add_singleton(Query) diff --git a/bot/src/bot_graphql/mutations/achievement_mutation.py b/bot/src/bot_graphql/mutations/achievement_mutation.py index 2731df20..40975a38 100644 --- a/bot/src/bot_graphql/mutations/achievement_mutation.py +++ b/bot/src/bot_graphql/mutations/achievement_mutation.py @@ -55,26 +55,16 @@ class AchievementMutation(QueryABC): and a.server.id == server.id ) - return ( - self._achievements.get_achievements_by_server_id(achievement.server.id) - .where(get_new_achievement) - .last() - ) + return self._achievements.get_achievements_by_server_id(achievement.server.id).where(get_new_achievement).last() def resolve_update_achievement(self, *_, input: dict): achievement = self._achievements.get_achievement_by_id(input["id"]) self._can_user_mutate_data(achievement.server, UserRoleEnum.moderator) achievement.name = input["name"] if "name" in input else achievement.name - achievement.description = ( - input["description"] if "description" in input else achievement.description - ) - achievement.attribute = ( - input["attribute"] if "attribute" in input else achievement.attribute - ) - achievement.operator = ( - input["operator"] if "operator" in input else achievement.operator - ) + achievement.description = input["description"] if "description" in input else achievement.description + achievement.attribute = input["attribute"] if "attribute" in input else achievement.attribute + achievement.operator = input["operator"] if "operator" in input else achievement.operator achievement.value = input["value"] if "value" in input else achievement.value self._achievements.update_achievement(achievement) diff --git a/bot/src/bot_graphql/mutations/auto_role_mutation.py b/bot/src/bot_graphql/mutations/auto_role_mutation.py index e4dec683..72ac1cf9 100644 --- a/bot/src/bot_graphql/mutations/auto_role_mutation.py +++ b/bot/src/bot_graphql/mutations/auto_role_mutation.py @@ -42,22 +42,14 @@ class AutoRoleMutation(QueryABC): and x.discord_message_id == int(input["messageId"]) ) - return ( - self._auto_roles.get_auto_roles_by_server_id(auto_role.server.id) - .where(get_new) - .last() - ) + return self._auto_roles.get_auto_roles_by_server_id(auto_role.server.id).where(get_new).last() def resolve_update_auto_role(self, *_, input: dict): auto_role = self._auto_roles.get_auto_role_by_id(input["id"]) self._can_user_mutate_data(auto_role.server, UserRoleEnum.moderator) - auto_role.discord_channel_id = ( - input["channelId"] if "channelId" in input else auto_role.discord_channel_id - ) - auto_role.discord_message_id = ( - input["messageId"] if "messageId" in input else auto_role.discord_message_id - ) + auto_role.discord_channel_id = input["channelId"] if "channelId" in input else auto_role.discord_channel_id + auto_role.discord_message_id = input["messageId"] if "messageId" in input else auto_role.discord_message_id self._auto_roles.update_auto_role(auto_role) self._db.save_changes() diff --git a/bot/src/bot_graphql/mutations/auto_role_rule_mutation.py b/bot/src/bot_graphql/mutations/auto_role_rule_mutation.py index 0b880c0b..ceafdd2d 100644 --- a/bot/src/bot_graphql/mutations/auto_role_rule_mutation.py +++ b/bot/src/bot_graphql/mutations/auto_role_rule_mutation.py @@ -36,9 +36,7 @@ class AutoRoleRuleMutation(QueryABC): input["emojiName"], input["roleId"], ) - self._can_user_mutate_data( - auto_role_rule.auto_role.server, UserRoleEnum.moderator - ) + self._can_user_mutate_data(auto_role_rule.auto_role.server, UserRoleEnum.moderator) self._auto_roles.add_auto_role_rule(auto_role_rule) self._db.save_changes() @@ -58,26 +56,14 @@ class AutoRoleRuleMutation(QueryABC): self._bot.get_guild(auto_role_rule.auto_role.server.discord_id), ) ) - return ( - self._auto_roles.get_auto_role_rules_by_auto_role_id( - auto_role_rule.auto_role.id - ) - .where(get_new) - .last() - ) + return self._auto_roles.get_auto_role_rules_by_auto_role_id(auto_role_rule.auto_role.id).where(get_new).last() def resolve_update_auto_role_rule(self, *_, input: dict): auto_role_rule = self._auto_roles.get_auto_role_rule_by_id(input["id"]) - self._can_user_mutate_data( - auto_role_rule.auto_role.server, UserRoleEnum.moderator - ) + self._can_user_mutate_data(auto_role_rule.auto_role.server, UserRoleEnum.moderator) - auto_role_rule.emoji_name = ( - input["emojiName"] if "emojiName" in input else auto_role_rule.emoji_name - ) - auto_role_rule.role_id = ( - input["roleId"] if "roleId" in input else auto_role_rule.role_id - ) + auto_role_rule.emoji_name = input["emojiName"] if "emojiName" in input else auto_role_rule.emoji_name + auto_role_rule.role_id = input["roleId"] if "roleId" in input else auto_role_rule.role_id self._auto_roles.update_auto_role_rule(auto_role_rule) self._db.save_changes() @@ -95,9 +81,7 @@ class AutoRoleRuleMutation(QueryABC): def resolve_delete_auto_role_rule(self, *_, id: int): auto_role_rule = self._auto_roles.get_auto_role_rule_by_id(id) - self._can_user_mutate_data( - auto_role_rule.auto_role.server, UserRoleEnum.moderator - ) + self._can_user_mutate_data(auto_role_rule.auto_role.server, UserRoleEnum.moderator) self._auto_roles.delete_auto_role_rule(auto_role_rule) self._db.save_changes() diff --git a/bot/src/bot_graphql/mutations/level_mutation.py b/bot/src/bot_graphql/mutations/level_mutation.py index 179cc786..215538b7 100644 --- a/bot/src/bot_graphql/mutations/level_mutation.py +++ b/bot/src/bot_graphql/mutations/level_mutation.py @@ -54,11 +54,7 @@ class LevelMutation(QueryABC): ) self._bot.loop.create_task(self._level_seeder.seed()) - return ( - self._levels.get_levels_by_server_id(level.server.id) - .where(get_new_level) - .last() - ) + return self._levels.get_levels_by_server_id(level.server.id).where(get_new_level).last() def resolve_update_level(self, *_, input: dict): level = self._levels.get_level_by_id(input["id"]) @@ -67,9 +63,7 @@ class LevelMutation(QueryABC): level.name = input["name"] if "name" in input else level.name level.color = input["color"] if "color" in input else level.color level.min_xp = input["minXp"] if "minXp" in input else level.min_xp - level.permissions = ( - input["permissions"] if "permissions" in input else level.permissions - ) + level.permissions = input["permissions"] if "permissions" in input else level.permissions self._levels.update_level(level) self._db.save_changes() diff --git a/bot/src/bot_graphql/mutations/server_config_mutation.py b/bot/src/bot_graphql/mutations/server_config_mutation.py index 0f7df29b..6b2ff5eb 100644 --- a/bot/src/bot_graphql/mutations/server_config_mutation.py +++ b/bot/src/bot_graphql/mutations/server_config_mutation.py @@ -41,44 +41,28 @@ class ServerConfigMutation(QueryABC): raise ValueError("Id not set") server_config = self._server_configs.get_server_config_by_id(int(input["id"])) - self._can_user_mutate_data( - Route.get_user().users[0].server, UserRoleEnum.technician - ) + self._can_user_mutate_data(Route.get_user().users[0].server, UserRoleEnum.technician) server_config.message_delete_timer = ( - input["messageDeleteTimer"] - if "messageDeleteTimer" in input - else server_config.message_delete_timer + input["messageDeleteTimer"] if "messageDeleteTimer" in input else server_config.message_delete_timer ) server_config.notification_chat_id = ( - input["notificationChatId"] - if "notificationChatId" in input - else server_config.notification_chat_id + input["notificationChatId"] if "notificationChatId" in input else server_config.notification_chat_id ) server_config.max_voice_state_hours = ( - input["maxVoiceStateHours"] - if "maxVoiceStateHours" in input - else server_config.max_voice_state_hours + input["maxVoiceStateHours"] if "maxVoiceStateHours" in input else server_config.max_voice_state_hours ) server_config.xp_per_message = ( - input["xpPerMessage"] - if "xpPerMessage" in input - else server_config.xp_per_message + input["xpPerMessage"] if "xpPerMessage" in input else server_config.xp_per_message ) server_config.xp_per_reaction = ( - input["xpPerReaction"] - if "xpPerReaction" in input - else server_config.xp_per_reaction + input["xpPerReaction"] if "xpPerReaction" in input else server_config.xp_per_reaction ) server_config.max_message_xp_per_hour = ( - input["maxMessageXpPerHour"] - if "maxMessageXpPerHour" in input - else server_config.max_message_xp_per_hour + input["maxMessageXpPerHour"] if "maxMessageXpPerHour" in input else server_config.max_message_xp_per_hour ) server_config.xp_per_ontime_hour = ( - input["xpPerOntimeHour"] - if "xpPerOntimeHour" in input - else server_config.xp_per_ontime_hour + input["xpPerOntimeHour"] if "xpPerOntimeHour" in input else server_config.xp_per_ontime_hour ) server_config.xp_per_event_participation = ( input["xpPerEventParticipation"] @@ -86,29 +70,19 @@ class ServerConfigMutation(QueryABC): else server_config.xp_per_event_participation ) server_config.xp_per_achievement = ( - input["xpPerAchievement"] - if "xpPerAchievement" in input - else server_config.xp_per_achievement + input["xpPerAchievement"] if "xpPerAchievement" in input else server_config.xp_per_achievement ) server_config.xp_for_birthday = ( - input["xpForBirthday"] - if "xpForBirthday" in input - else server_config.xp_for_birthday + input["xpForBirthday"] if "xpForBirthday" in input else server_config.xp_for_birthday ) server_config.afk_command_channel_id = ( - input["afkCommandChannelId"] - if "afkCommandChannelId" in input - else server_config.afk_command_channel_id + input["afkCommandChannelId"] if "afkCommandChannelId" in input else server_config.afk_command_channel_id ) server_config.help_voice_channel_id = ( - input["helpVoiceChannelId"] - if "helpVoiceChannelId" in input - else server_config.help_voice_channel_id + input["helpVoiceChannelId"] if "helpVoiceChannelId" in input else server_config.help_voice_channel_id ) server_config.team_channel_id = ( - input["teamChannelId"] - if "teamChannelId" in input - else server_config.team_channel_id + input["teamChannelId"] if "teamChannelId" in input else server_config.team_channel_id ) server_config.login_message_channel_id = ( input["loginMessageChannelId"] @@ -116,9 +90,7 @@ class ServerConfigMutation(QueryABC): else server_config.login_message_channel_id ) server_config.default_role_id = ( - input["defaultRoleId"] - if "defaultRoleId" in input - else server_config.default_role_id + input["defaultRoleId"] if "defaultRoleId" in input else server_config.default_role_id ) server_config.short_role_name_only_set_highest_role = ( input["shortRoleNameOnlySetHighestRole"] @@ -150,33 +122,25 @@ class ServerConfigMutation(QueryABC): if "moderatorRoleIds" in input: team_role_ids.extend( [ - ServerTeamRoleIdsConfig( - x, TeamMemberTypeEnum.moderator, server_config.server.id - ) + ServerTeamRoleIdsConfig(x, TeamMemberTypeEnum.moderator, server_config.server.id) for x in input["moderatorRoleIds"] ] ) else: team_role_ids.extend( - server_config.team_role_ids.where( - lambda x: x.team_member_type == TeamMemberTypeEnum.moderator - ) + server_config.team_role_ids.where(lambda x: x.team_member_type == TeamMemberTypeEnum.moderator) ) if "adminRoleIds" in input: team_role_ids.extend( [ - ServerTeamRoleIdsConfig( - x, TeamMemberTypeEnum.admin, server_config.server.id - ) + ServerTeamRoleIdsConfig(x, TeamMemberTypeEnum.admin, server_config.server.id) for x in input["adminRoleIds"] ] ) else: team_role_ids.extend( - server_config.team_role_ids.where( - lambda x: x.team_member_type == TeamMemberTypeEnum.admin - ) + server_config.team_role_ids.where(lambda x: x.team_member_type == TeamMemberTypeEnum.admin) ) self._server_configs.update_server_config(server_config) @@ -188,15 +152,11 @@ class ServerConfigMutation(QueryABC): self._update_team_role_ids(server_config) self._db.save_changes() - self._bot.loop.create_task( - self._config_service.reload_server_config(server_config.server) - ) + self._bot.loop.create_task(self._config_service.reload_server_config(server_config.server)) return server_config def _update_afk_channel_ids(self, new_config: ServerConfig): - old_config = self._server_configs.get_server_config_by_server( - new_config.server.id - ) + old_config = self._server_configs.get_server_config_by_server(new_config.server.id) for channel_id in old_config.afk_channel_ids: if channel_id in new_config.afk_channel_ids: continue @@ -214,13 +174,9 @@ class ServerConfigMutation(QueryABC): ) def _update_team_role_ids(self, new_config: ServerConfig): - old_config = self._server_configs.get_server_config_by_server( - new_config.server.id - ) + old_config = self._server_configs.get_server_config_by_server(new_config.server.id) for role_id in old_config.team_role_ids: - if role_id.role_id in new_config.team_role_ids.select( - lambda x: int(x.role_id) - ): + if role_id.role_id in new_config.team_role_ids.select(lambda x: int(x.role_id)): continue self._server_configs.delete_server_team_role_id_config(role_id) @@ -232,9 +188,7 @@ class ServerConfigMutation(QueryABC): raise ValueError(f"Invalid roleId") for role_id in new_config.team_role_ids: - if role_id.role_id in old_config.team_role_ids.select( - lambda x: str(x.role_id) - ): + if role_id.role_id in old_config.team_role_ids.select(lambda x: str(x.role_id)): continue self._server_configs.add_server_team_role_id_config(role_id) diff --git a/bot/src/bot_graphql/mutations/short_role_name_mutation.py b/bot/src/bot_graphql/mutations/short_role_name_mutation.py index d3b8c910..3044af99 100644 --- a/bot/src/bot_graphql/mutations/short_role_name_mutation.py +++ b/bot/src/bot_graphql/mutations/short_role_name_mutation.py @@ -41,9 +41,7 @@ class ShortRoleNameMutation(QueryABC): server, ) - result = self._short_role_names.find_short_role_names_by_role_id( - short_role_name.role_id - ) + result = self._short_role_names.find_short_role_names_by_role_id(short_role_name.role_id) if result.count() > 0: raise ValueError("Short name for role already exists") @@ -58,9 +56,7 @@ class ShortRoleNameMutation(QueryABC): ) return ( - self._short_role_names.get_short_role_names_by_server_id( - short_role_name.server.id - ) + self._short_role_names.get_short_role_names_by_server_id(short_role_name.server.id) .where(get_new_short_role_name) .last() ) @@ -69,15 +65,9 @@ class ShortRoleNameMutation(QueryABC): short_role_name = self._short_role_names.get_short_role_name_by_id(input["id"]) self._can_user_mutate_data(short_role_name.server, UserRoleEnum.moderator) - short_role_name.short_name = ( - input["shortName"] if "shortName" in input else short_role_name.short_name - ) - short_role_name.role_id = ( - input["roleId"] if "roleId" in input else short_role_name.role_id - ) - short_role_name.position = ( - input["position"] if "position" in input else short_role_name.position - ) + short_role_name.short_name = input["shortName"] if "shortName" in input else short_role_name.short_name + short_role_name.role_id = input["roleId"] if "roleId" in input else short_role_name.role_id + short_role_name.position = input["position"] if "position" in input else short_role_name.position self._short_role_names.update_short_role_name(short_role_name) self._db.save_changes() diff --git a/bot/src/bot_graphql/mutations/technician_config_mutation.py b/bot/src/bot_graphql/mutations/technician_config_mutation.py index 09ba300b..f5dbbaa2 100644 --- a/bot/src/bot_graphql/mutations/technician_config_mutation.py +++ b/bot/src/bot_graphql/mutations/technician_config_mutation.py @@ -43,9 +43,7 @@ class TechnicianConfigMutation(QueryABC): self._bot.loop.create_task(self._tech_seeder.seed()) technician_config = self._technician_configs.get_technician_config() - self._can_user_mutate_data( - Route.get_user().users[0].server, UserRoleEnum.technician - ) + self._can_user_mutate_data(Route.get_user().users[0].server, UserRoleEnum.technician) technician_config.help_command_reference_url = ( input["helpCommandReferenceUrl"] @@ -53,19 +51,13 @@ class TechnicianConfigMutation(QueryABC): else technician_config.help_command_reference_url ) technician_config.wait_for_restart = ( - input["waitForRestart"] - if "waitForRestart" in input - else technician_config.wait_for_restart + input["waitForRestart"] if "waitForRestart" in input else technician_config.wait_for_restart ) technician_config.wait_for_shutdown = ( - input["waitForShutdown"] - if "waitForShutdown" in input - else technician_config.wait_for_shutdown + input["waitForShutdown"] if "waitForShutdown" in input else technician_config.wait_for_shutdown ) technician_config.cache_max_messages = ( - input["cacheMaxMessages"] - if "cacheMaxMessages" in input - else technician_config.cache_max_messages + input["cacheMaxMessages"] if "cacheMaxMessages" in input else technician_config.cache_max_messages ) old_feature_flags = technician_config.feature_flags technician_config.feature_flags = ( @@ -83,9 +75,7 @@ class TechnicianConfigMutation(QueryABC): technician_config.feature_flags[old_flag] = False technician_config.ping_urls = ( - List(str, input["pingURLs"]) - if "pingURLs" in input - else technician_config.ping_urls + List(str, input["pingURLs"]) if "pingURLs" in input else technician_config.ping_urls ) technician_config.technician_ids = ( List(int).extend([int(x) for x in input["technicianIds"]]) @@ -110,17 +100,13 @@ class TechnicianConfigMutation(QueryABC): if url in new_config.ping_urls: continue - self._technician_configs.delete_technician_ping_url_config( - TechnicianPingUrlConfig(url) - ) + self._technician_configs.delete_technician_ping_url_config(TechnicianPingUrlConfig(url)) for url in new_config.ping_urls: if url in old_config.ping_urls: continue - self._technician_configs.add_technician_ping_url_config( - TechnicianPingUrlConfig(url) - ) + self._technician_configs.add_technician_ping_url_config(TechnicianPingUrlConfig(url)) def _update_technician_ids(self, new_config: TechnicianConfig): old_config = self._technician_configs.get_technician_config() @@ -128,9 +114,7 @@ class TechnicianConfigMutation(QueryABC): if technician_id in new_config.technician_ids: continue - self._technician_configs.delete_technician_id_config( - TechnicianIdConfig(technician_id) - ) + self._technician_configs.delete_technician_id_config(TechnicianIdConfig(technician_id)) for technician_id in new_config.technician_ids: user = self._bot.get_user(technician_id) @@ -141,6 +125,4 @@ class TechnicianConfigMutation(QueryABC): if technician_id in old_config.technician_ids: continue - self._technician_configs.add_technician_id_config( - TechnicianIdConfig(technician_id) - ) + self._technician_configs.add_technician_id_config(TechnicianIdConfig(technician_id)) diff --git a/bot/src/bot_graphql/mutations/user_joined_game_server_mutation.py b/bot/src/bot_graphql/mutations/user_joined_game_server_mutation.py index d5885fd6..4f53a741 100644 --- a/bot/src/bot_graphql/mutations/user_joined_game_server_mutation.py +++ b/bot/src/bot_graphql/mutations/user_joined_game_server_mutation.py @@ -63,9 +63,7 @@ class UserJoinedGameServerMutation(QueryABC): def _get_api_key_str(self, api_key: ApiKey) -> str: return hashlib.sha256( - f"{api_key.identifier}:{api_key.key}+{self._auth_settings.secret_key}".encode( - "utf-8" - ) + f"{api_key.identifier}:{api_key.key}+{self._auth_settings.secret_key}".encode("utf-8") ).hexdigest() def _get_api_key(self) -> Optional[ApiKey]: @@ -84,19 +82,13 @@ class UserJoinedGameServerMutation(QueryABC): game_ident = self._user_game_idents.get_user_game_ident_by_ident(input["ident"]) user = game_ident.user - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{user.server.discord_id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - settings.feature_flags, FeatureFlagsEnum.game_server - ): + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{user.server.discord_id}") + if not FeatureFlagsSettings.get_flag_from_dict(settings.feature_flags, FeatureFlagsEnum.game_server): raise Exception("Feature not activated") self._can_user_mutate_data(user.server, UserRoleEnum.admin) - active = self._user_joined_game_servers.find_active_user_joined_game_server_by_user_id( - user.id - ) + active = self._user_joined_game_servers.find_active_user_joined_game_server_by_user_id(user.id) if active is not None: self._logger.debug( __name__, @@ -108,38 +100,26 @@ class UserJoinedGameServerMutation(QueryABC): self._user_joined_game_servers.add_user_joined_game_server(new) self._db.save_changes() - return self._user_joined_game_servers.get_active_user_joined_game_server_by_user_id( - user.id - ) + return self._user_joined_game_servers.get_active_user_joined_game_server_by_user_id(user.id) def resolve_user_left(self, *_, input: dict): - game_ident = self._user_game_idents.find_user_game_ident_by_ident( - input["ident"] - ) + game_ident = self._user_game_idents.find_user_game_ident_by_ident(input["ident"]) if game_ident is None: return user = game_ident.user - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{user.server.discord_id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - settings.feature_flags, FeatureFlagsEnum.game_server - ): + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{user.server.discord_id}") + if not FeatureFlagsSettings.get_flag_from_dict(settings.feature_flags, FeatureFlagsEnum.game_server): raise Exception("Feature not activated") self._can_user_mutate_data(user.server, UserRoleEnum.admin) - active = self._user_joined_game_servers.find_active_user_joined_game_server_by_user_id( - user.id - ) + active = self._user_joined_game_servers.find_active_user_joined_game_server_by_user_id(user.id) if active is None: return active.leaved_on = datetime.now() - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{user.server.discord_id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{user.server.discord_id}") ontime = round((active.leaved_on - active.joined_on).total_seconds() / 3600, 2) old_xp = user.xp diff --git a/bot/src/bot_graphql/mutations/user_mutation.py b/bot/src/bot_graphql/mutations/user_mutation.py index 778db4f4..9ec5f4cc 100644 --- a/bot/src/bot_graphql/mutations/user_mutation.py +++ b/bot/src/bot_graphql/mutations/user_mutation.py @@ -48,9 +48,7 @@ class UserMutation(QueryABC): auth_user = Route.get_user() member = self._bot.get_guild(user.server.discord_id).get_member( - auth_user.users.where(lambda x: x.server.id == user.server.id) - .single() - .discord_id + auth_user.users.where(lambda x: x.server.id == user.server.id).single().discord_id ) if member.id != user.discord_id: self._can_user_mutate_data(user.server, UserRoleEnum.moderator) @@ -64,19 +62,9 @@ class UserMutation(QueryABC): if "userWarnings" in input: self._update_user_warning(user, input["userWarnings"]) - user.xp = ( - new_xp - if new_xp is not None - else input["xp"] - if "xp" in input - else user.xp - ) + user.xp = new_xp if new_xp is not None else input["xp"] if "xp" in input else user.xp - user.birthday = ( - datetime.strptime(input["birthday"], "%d.%m.%Y") - if "birthday" in input - else user.birthday - ) + user.birthday = datetime.strptime(input["birthday"], "%d.%m.%Y") if "birthday" in input else user.birthday self._users.update_user(user) self._db.save_changes() @@ -88,23 +76,15 @@ class UserMutation(QueryABC): def _update_user_warning(self, user: User, new_warnings: dict): old_warnings = self._user_warnings.get_user_warnings_by_user_id(user.id) for warning in old_warnings: - if warning.id in [ - int(x["id"]) if "id" in x else None for x in new_warnings - ]: + if warning.id in [int(x["id"]) if "id" in x else None for x in new_warnings]: continue self._user_warning_service.remove_warnings(warning.id) for warning in new_warnings: - if "id" in warning and int(warning["id"]) in old_warnings.select( - lambda x: x.id - ): + if "id" in warning and int(warning["id"]) in old_warnings.select(lambda x: x.id): continue - member = self._bot.get_guild(user.server.discord_id).get_member( - user.discord_id - ) + member = self._bot.get_guild(user.server.discord_id).get_member(user.discord_id) author = self._users.get_user_by_id(int(warning["author"])) - self._user_warning_service.add_warnings( - member, warning["description"], author.discord_id - ) + self._user_warning_service.add_warnings(member, warning["description"], author.discord_id) diff --git a/bot/src/bot_graphql/queries/achievement_query.py b/bot/src/bot_graphql/queries/achievement_query.py index f12e8657..ab72fde0 100644 --- a/bot/src/bot_graphql/queries/achievement_query.py +++ b/bot/src/bot_graphql/queries/achievement_query.py @@ -9,9 +9,7 @@ class AchievementQuery(DataQueryWithHistoryABC): self, db: DatabaseContextABC, ): - DataQueryWithHistoryABC.__init__( - self, "Achievement", "AchievementsHistory", AchievementHistory, db - ) + DataQueryWithHistoryABC.__init__(self, "Achievement", "AchievementsHistory", AchievementHistory, db) self.set_field("id", lambda x, *_: x.id) self.set_field("name", lambda x, *_: x.name) diff --git a/bot/src/bot_graphql/queries/auto_role_query.py b/bot/src/bot_graphql/queries/auto_role_query.py index ea6b9d7c..aaf694b7 100644 --- a/bot/src/bot_graphql/queries/auto_role_query.py +++ b/bot/src/bot_graphql/queries/auto_role_query.py @@ -18,9 +18,7 @@ class AutoRoleQuery(DataQueryWithHistoryABC): servers: ServerRepositoryABC, db: DatabaseContextABC, ): - DataQueryWithHistoryABC.__init__( - self, "AutoRole", "AutoRolesHistory", AutoRoleHistory, db - ) + DataQueryWithHistoryABC.__init__(self, "AutoRole", "AutoRolesHistory", AutoRoleHistory, db) self._bot = bot self._auto_role_rules = auto_role_rules @@ -33,9 +31,7 @@ class AutoRoleQuery(DataQueryWithHistoryABC): self.set_field("server", self.resolve_server) self.add_collection( "autoRoleRule", - lambda x, *_: self._auto_role_rules.get_auto_role_rules_by_auto_role_id( - x.id - ), + lambda x, *_: self._auto_role_rules.get_auto_role_rules_by_auto_role_id(x.id), AutoRoleFilter, ) diff --git a/bot/src/bot_graphql/queries/auto_role_rule_query.py b/bot/src/bot_graphql/queries/auto_role_rule_query.py index e08dc4f1..0b6373dd 100644 --- a/bot/src/bot_graphql/queries/auto_role_rule_query.py +++ b/bot/src/bot_graphql/queries/auto_role_rule_query.py @@ -14,9 +14,7 @@ class AutoRoleRuleQuery(DataQueryWithHistoryABC): auto_roles: AutoRoleRepositoryABC, db: DatabaseContextABC, ): - DataQueryWithHistoryABC.__init__( - self, "AutoRoleRule", "AutoRoleRulesHistory", AutoRoleRuleHistory, db - ) + DataQueryWithHistoryABC.__init__(self, "AutoRoleRule", "AutoRoleRulesHistory", AutoRoleRuleHistory, db) self._bot = bot self._auto_roles = auto_roles diff --git a/bot/src/bot_graphql/queries/client_query.py b/bot/src/bot_graphql/queries/client_query.py index af462202..6e69a369 100644 --- a/bot/src/bot_graphql/queries/client_query.py +++ b/bot/src/bot_graphql/queries/client_query.py @@ -8,9 +8,7 @@ from bot_graphql.abc.data_query_with_history_abc import DataQueryWithHistoryABC class ClientQuery(DataQueryWithHistoryABC): def __init__(self, bot: DiscordBotServiceABC, db: DatabaseContextABC): - DataQueryWithHistoryABC.__init__( - self, "Client", "ClientsHistory", ClientHistory, db - ) + DataQueryWithHistoryABC.__init__(self, "Client", "ClientsHistory", ClientHistory, db) self._bot = bot diff --git a/bot/src/bot_graphql/queries/discord/guild_query.py b/bot/src/bot_graphql/queries/discord/guild_query.py index 5393c530..cf32e8d7 100644 --- a/bot/src/bot_graphql/queries/discord/guild_query.py +++ b/bot/src/bot_graphql/queries/discord/guild_query.py @@ -21,9 +21,7 @@ class GuildQuery(QueryABC): self.set_field("roles", lambda g, *_: g.roles.order_by(lambda x: x.position)) self.set_field( "emojis", - lambda g, *_: List(discord.Emoji, g.emojis).order_by_descending( - lambda x: x.created_at - ), + lambda g, *_: List(discord.Emoji, g.emojis).order_by_descending(lambda x: x.created_at), ) def _resolve_channels(self, g: Guild, *_, filter=None): diff --git a/bot/src/bot_graphql/queries/known_user_query.py b/bot/src/bot_graphql/queries/known_user_query.py index c6079b56..d3435735 100644 --- a/bot/src/bot_graphql/queries/known_user_query.py +++ b/bot/src/bot_graphql/queries/known_user_query.py @@ -7,9 +7,7 @@ from bot_graphql.abc.data_query_with_history_abc import DataQueryWithHistoryABC class KnownUserQuery(DataQueryWithHistoryABC): def __init__(self, db: DatabaseContextABC): - DataQueryWithHistoryABC.__init__( - self, "KnownUser", "KnownUsersHistory", KnownUserHistory, db - ) + DataQueryWithHistoryABC.__init__(self, "KnownUser", "KnownUsersHistory", KnownUserHistory, db) self.set_field("id", self.resolve_id) self.set_field("discordId", self.resolve_discord_id) diff --git a/bot/src/bot_graphql/queries/level_query.py b/bot/src/bot_graphql/queries/level_query.py index 7eef1b3f..5f726c5b 100644 --- a/bot/src/bot_graphql/queries/level_query.py +++ b/bot/src/bot_graphql/queries/level_query.py @@ -7,9 +7,7 @@ from bot_graphql.abc.data_query_with_history_abc import DataQueryWithHistoryABC class LevelQuery(DataQueryWithHistoryABC): def __init__(self, db: DatabaseContextABC): - DataQueryWithHistoryABC.__init__( - self, "Level", "LevelsHistory", LevelHistory, db - ) + DataQueryWithHistoryABC.__init__(self, "Level", "LevelsHistory", LevelHistory, db) self.set_field("id", self.resolve_id) self.set_field("name", self.resolve_name) diff --git a/bot/src/bot_graphql/queries/server_config_query.py b/bot/src/bot_graphql/queries/server_config_query.py index 9c28b560..3f45fdbf 100644 --- a/bot/src/bot_graphql/queries/server_config_query.py +++ b/bot/src/bot_graphql/queries/server_config_query.py @@ -8,25 +8,15 @@ from bot_graphql.abc.data_query_with_history_abc import DataQueryWithHistoryABC class ServerConfigQuery(DataQueryWithHistoryABC): def __init__(self, db: DatabaseContextABC): - DataQueryWithHistoryABC.__init__( - self, "ServerConfig", "CFG_ServerHistory", ServerConfigHistory, db - ) + DataQueryWithHistoryABC.__init__(self, "ServerConfig", "CFG_ServerHistory", ServerConfigHistory, db) self.set_field("id", lambda config, *_: config.id) - self.set_field( - "messageDeleteTimer", lambda config, *_: config.message_delete_timer - ) - self.set_field( - "notificationChatId", lambda config, *_: config.notification_chat_id - ) - self.set_field( - "maxVoiceStateHours", lambda config, *_: config.max_voice_state_hours - ) + self.set_field("messageDeleteTimer", lambda config, *_: config.message_delete_timer) + self.set_field("notificationChatId", lambda config, *_: config.notification_chat_id) + self.set_field("maxVoiceStateHours", lambda config, *_: config.max_voice_state_hours) self.set_field("xpPerMessage", lambda config, *_: config.xp_per_message) self.set_field("xpPerReaction", lambda config, *_: config.xp_per_reaction) - self.set_field( - "maxMessageXpPerHour", lambda config, *_: config.max_message_xp_per_hour - ) + self.set_field("maxMessageXpPerHour", lambda config, *_: config.max_message_xp_per_hour) self.set_field("xpPerOntimeHour", lambda config, *_: config.xp_per_ontime_hour) self.set_field( "xpPerEventParticipation", @@ -34,16 +24,10 @@ class ServerConfigQuery(DataQueryWithHistoryABC): ) self.set_field("xpPerAchievement", lambda config, *_: config.xp_per_achievement) self.set_field("xpForBirthday", lambda config, *_: config.xp_for_birthday) - self.set_field( - "afkCommandChannelId", lambda config, *_: config.afk_command_channel_id - ) - self.set_field( - "helpVoiceChannelId", lambda config, *_: config.help_voice_channel_id - ) + self.set_field("afkCommandChannelId", lambda config, *_: config.afk_command_channel_id) + self.set_field("helpVoiceChannelId", lambda config, *_: config.help_voice_channel_id) self.set_field("teamChannelId", lambda config, *_: config.team_channel_id) - self.set_field( - "loginMessageChannelId", lambda config, *_: config.login_message_channel_id - ) + self.set_field("loginMessageChannelId", lambda config, *_: config.login_message_channel_id) self.set_field("defaultRoleId", lambda config, *_: config.default_role_id) self.set_field( "shortRoleNameOnlySetHighestRole", @@ -57,10 +41,7 @@ class ServerConfigQuery(DataQueryWithHistoryABC): "featureFlag", lambda config, *_: List( any, - [ - {"key": x, "value": config.feature_flags[x]} - for x in config.feature_flags - ], + [{"key": x, "value": config.feature_flags[x]} for x in config.feature_flags], ), ) self.set_field("afkChannelIds", lambda config, *_: config.afk_channel_ids) diff --git a/bot/src/bot_graphql/queries/server_query.py b/bot/src/bot_graphql/queries/server_query.py index 67879229..edd647cd 100644 --- a/bot/src/bot_graphql/queries/server_query.py +++ b/bot/src/bot_graphql/queries/server_query.py @@ -45,9 +45,7 @@ class ServerQuery(DataQueryWithHistoryABC): short_role_names: ShortRoleNameRepositoryABC, server_configs: ServerConfigRepositoryABC, ): - DataQueryWithHistoryABC.__init__( - self, "Server", "ServersHistory", ServerHistory, db - ) + DataQueryWithHistoryABC.__init__(self, "Server", "ServersHistory", ServerHistory, db) self._config = config self._bot = bot @@ -94,9 +92,7 @@ class ServerQuery(DataQueryWithHistoryABC): ) self.add_collection( "shortRoleName", - lambda server, *_: short_role_names.get_short_role_names_by_server_id( - server.id - ), + lambda server, *_: short_role_names.get_short_role_names_by_server_id(server.id), ShortRoleNameFilter, ) self.set_field( @@ -105,9 +101,7 @@ class ServerQuery(DataQueryWithHistoryABC): ) self.set_field( "hasFeatureFlag", - lambda server, *_, **kwargs: self._resolve_has_feature_flag( - server, *_, **kwargs - ), + lambda server, *_, **kwargs: self._resolve_has_feature_flag(server, *_, **kwargs), ) @staticmethod @@ -127,14 +121,10 @@ class ServerQuery(DataQueryWithHistoryABC): return server.icon_url def _resolve_has_feature_flag(self, server: Server, *_, **kwargs): - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{server.discord_id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{server.discord_id}") if "flag" not in kwargs: return False return { "key": kwargs["flag"], - "value": FeatureFlagsSettings.get_flag_from_dict( - settings.feature_flags, FeatureFlagsEnum(kwargs["flag"]) - ), + "value": FeatureFlagsSettings.get_flag_from_dict(settings.feature_flags, FeatureFlagsEnum(kwargs["flag"])), } diff --git a/bot/src/bot_graphql/queries/short_role_name_query.py b/bot/src/bot_graphql/queries/short_role_name_query.py index 6191aadd..75d07ac6 100644 --- a/bot/src/bot_graphql/queries/short_role_name_query.py +++ b/bot/src/bot_graphql/queries/short_role_name_query.py @@ -9,9 +9,7 @@ class ShortRoleNameQuery(DataQueryWithHistoryABC): self, db: DatabaseContextABC, ): - DataQueryWithHistoryABC.__init__( - self, "ShortRoleName", "ShortRoleNamesHistory", ShortRoleNameHistory, db - ) + DataQueryWithHistoryABC.__init__(self, "ShortRoleName", "ShortRoleNamesHistory", ShortRoleNameHistory, db) self.set_field("id", lambda x, *_: x.id) self.set_field("shortName", lambda x, *_: x.short_name) diff --git a/bot/src/bot_graphql/queries/technician_config_history_query.py b/bot/src/bot_graphql/queries/technician_config_history_query.py index 41ebbb54..fb35ff2f 100644 --- a/bot/src/bot_graphql/queries/technician_config_history_query.py +++ b/bot/src/bot_graphql/queries/technician_config_history_query.py @@ -18,9 +18,6 @@ class TechnicianConfigHistoryQuery(HistoryQueryABC): "featureFlag", lambda config, *_: List( any, - [ - {"key": x, "value": config.feature_flags[x]} - for x in config.feature_flags - ], + [{"key": x, "value": config.feature_flags[x]} for x in config.feature_flags], ), ) diff --git a/bot/src/bot_graphql/queries/technician_config_query.py b/bot/src/bot_graphql/queries/technician_config_query.py index a6363d9b..d44d66ad 100644 --- a/bot/src/bot_graphql/queries/technician_config_query.py +++ b/bot/src/bot_graphql/queries/technician_config_query.py @@ -31,10 +31,7 @@ class TechnicianConfigQuery(DataQueryWithHistoryABC): "featureFlag", lambda config, *_: List( any, - [ - {"key": x, "value": config.feature_flags[x]} - for x in config.feature_flags - ], + [{"key": x, "value": config.feature_flags[x]} for x in config.feature_flags], ), ) self.set_field("pingURLs", lambda config, *_: config.ping_urls) diff --git a/bot/src/bot_graphql/queries/user_query.py b/bot/src/bot_graphql/queries/user_query.py index d91d5043..ceeab6d4 100644 --- a/bot/src/bot_graphql/queries/user_query.py +++ b/bot/src/bot_graphql/queries/user_query.py @@ -66,16 +66,12 @@ class UserQuery(DataQueryWithHistoryABC): ) self.add_collection( "joinedVoiceChannel", - lambda user, *_: self._ujvs.get_user_joined_voice_channels_by_user_id( - user.id - ), + lambda user, *_: self._ujvs.get_user_joined_voice_channels_by_user_id(user.id), UserJoinedVoiceChannelFilter, ) self.add_collection( "userJoinedGameServer", - lambda user, *_: self._user_joined_game_server.get_user_joined_game_servers_by_user_id( - user.id - ), + lambda user, *_: self._user_joined_game_server.get_user_joined_game_servers_by_user_id(user.id), UserJoinedGameServerFilter, ) self.add_collection( diff --git a/bot/src/bot_graphql/queries/user_warning_query.py b/bot/src/bot_graphql/queries/user_warning_query.py index c738e0d7..f6243d5e 100644 --- a/bot/src/bot_graphql/queries/user_warning_query.py +++ b/bot/src/bot_graphql/queries/user_warning_query.py @@ -9,9 +9,7 @@ class UserWarningQuery(DataQueryWithHistoryABC): self, db: DatabaseContextABC, ): - DataQueryWithHistoryABC.__init__( - self, "UserWarning", "UserWarningsHistory", UserWarningsHistory, db - ) + DataQueryWithHistoryABC.__init__(self, "UserWarning", "UserWarningsHistory", UserWarningsHistory, db) self.set_field("id", lambda x, *_: x.id) self.set_field("user", lambda x, *_: x.user) diff --git a/bot/src/bot_graphql/query.py b/bot/src/bot_graphql/query.py index 602fe555..41dafdf0 100644 --- a/bot/src/bot_graphql/query.py +++ b/bot/src/bot_graphql/query.py @@ -62,9 +62,7 @@ class Query(QueryABC): ): QueryABC.__init__(self, "Query") - self.add_collection( - "autoRole", lambda *_: auto_roles.get_auto_roles(), AutoRoleFilter - ) + self.add_collection("autoRole", lambda *_: auto_roles.get_auto_roles(), AutoRoleFilter) self.add_collection( "autoRoleRule", lambda *_: auto_roles.get_auto_role_rules(), @@ -91,9 +89,7 @@ class Query(QueryABC): UserJoinedGameServerFilter, ) self.add_collection("user", lambda *_: users.get_users(), UserFilter) - self.add_collection( - "achievement", lambda *_: achievements.get_achievements(), AchievementFilter - ) + self.add_collection("achievement", lambda *_: achievements.get_achievements(), AchievementFilter) self.add_collection( "shortRoleName", lambda *_: short_role_names.get_short_role_names(), @@ -105,24 +101,14 @@ class Query(QueryABC): UserWarningFilter, ) - self.set_field( - "technicianConfig", lambda *_: technician_config.get_technician_config() - ) + self.set_field("technicianConfig", lambda *_: technician_config.get_technician_config()) - self.set_field( - "achievementAttributes", lambda *_: achievement_service.get_attributes() - ) - self.set_field( - "achievementOperators", lambda *_: achievement_service.get_operators() - ) + self.set_field("achievementAttributes", lambda *_: achievement_service.get_attributes()) + self.set_field("achievementOperators", lambda *_: achievement_service.get_operators()) self.set_field( "shortRoleNamePositions", lambda *_: [x.value for x in ShortRoleNamePositionEnum], ) - self.set_field( - "possibleFeatureFlags", lambda *_: [e.value for e in FeatureFlagsEnum] - ) - self.set_field( - "discord", lambda *_: Discord(bot.guilds, List(any).extend(bot.users)) - ) + self.set_field("possibleFeatureFlags", lambda *_: [e.value for e in FeatureFlagsEnum]) + self.set_field("discord", lambda *_: Discord(bot.guilds, List(any).extend(bot.users))) diff --git a/bot/src/bot_graphql/schema.py b/bot/src/bot_graphql/schema.py index 5e09a19c..020efbc8 100644 --- a/bot/src/bot_graphql/schema.py +++ b/bot/src/bot_graphql/schema.py @@ -10,9 +10,7 @@ from bot_graphql.query import Query class Schema: def __init__(self, query: Query, mutation: Mutation, queries: list[QueryABC]): - type_defs = load_schema_from_path( - os.path.join(os.path.dirname(os.path.realpath(__file__)), "graphql/") - ) + type_defs = load_schema_from_path(os.path.join(os.path.dirname(os.path.realpath(__file__)), "graphql/")) self._schema = make_executable_schema(type_defs, query, mutation, *queries) @property diff --git a/bot/src/modules/achievements/achievement_attribute_resolver.py b/bot/src/modules/achievements/achievement_attribute_resolver.py index 7de2ee0b..66f478f8 100644 --- a/bot/src/modules/achievements/achievement_attribute_resolver.py +++ b/bot/src/modules/achievements/achievement_attribute_resolver.py @@ -46,22 +46,9 @@ class AchievementAttributeResolver: self._achievements = achievements def get_played_on_game_server(self, user: User) -> List[str]: - joins = self._user_joined_game_server.get_user_joined_game_servers_by_user_id( - user.id - ) + joins = self._user_joined_game_server.get_user_joined_game_servers_by_user_id(user.id) return joins.select(lambda x: x.game_server.name) def get_last_ontime_hours(self, user: User) -> int: - ujvs = ( - self._user_joined_voice_channels.get_user_joined_voice_channels_by_user_id( - user.id - ) - ) - return int( - str( - ujvs.max( - lambda join: (join.leaved_on - join.joined_on).total_seconds() - / 3600 - ) - ) - ) + ujvs = self._user_joined_voice_channels.get_user_joined_voice_channels_by_user_id(user.id) + return int(str(ujvs.max(lambda join: (join.leaved_on - join.joined_on).total_seconds() / 3600))) diff --git a/bot/src/modules/achievements/achievement_service.py b/bot/src/modules/achievements/achievement_service.py index 9d3bbac5..39b6cd47 100644 --- a/bot/src/modules/achievements/achievement_service.py +++ b/bot/src/modules/achievements/achievement_service.py @@ -45,12 +45,8 @@ class AchievementService: self._attributes.extend( [ AchievementAttribute("xp", lambda user: user.xp, "number"), - AchievementAttribute( - "message_count", lambda user: user.message_count, "number" - ), - AchievementAttribute( - "reaction_count", lambda user: user.reaction_count, "number" - ), + AchievementAttribute("message_count", lambda user: user.message_count, "number"), + AchievementAttribute("reaction_count", lambda user: user.reaction_count, "number"), AchievementAttribute("ontime", lambda user: user.ontime, "number"), AchievementAttribute("level", lambda user: user.level, "Level"), # special cases @@ -70,14 +66,10 @@ class AchievementService: self._operators = { "==": lambda value, expected_value: value == expected_value, "!=": lambda value, expected_value: value != expected_value, - "<=": lambda value, expected_value: self._num(value) - <= self._num(expected_value), - ">=": lambda value, expected_value: self._num(value) - >= self._num(expected_value), - "<": lambda value, expected_value: self._num(value) - < self._num(expected_value), - ">": lambda value, expected_value: self._num(value) - > self._num(expected_value), + "<=": lambda value, expected_value: self._num(value) <= self._num(expected_value), + ">=": lambda value, expected_value: self._num(value) >= self._num(expected_value), + "<": lambda value, expected_value: self._num(value) < self._num(expected_value), + ">": lambda value, expected_value: self._num(value) > self._num(expected_value), "contains": lambda value, expected_value: expected_value in value, } @@ -100,57 +92,37 @@ class AchievementService: def _match(self, value: any, operator: str, expected_value: str) -> bool: return self._operators[operator](str(value), expected_value) - def has_user_achievement_already( - self, user: User, achievement: Achievement - ) -> bool: + def has_user_achievement_already(self, user: User, achievement: Achievement) -> bool: user_achievements = self._achievements.get_achievements_by_user_id(user.id) return user_achievements.where(lambda x: x.name == achievement.name).count() > 0 def has_user_achievement(self, user: User, achievement: Achievement) -> bool: - attribute: AchievementAttribute = self._attributes.where( - lambda x: x.name == achievement.attribute - ).single() - return self._match( - attribute.resolve(user), achievement.operator, achievement.value - ) + attribute: AchievementAttribute = self._attributes.where(lambda x: x.name == achievement.attribute).single() + return self._match(attribute.resolve(user), achievement.operator, achievement.value) async def validate_achievements_for_user(self, user: User): achievements = self._achievements.get_achievements_by_server_id(user.server.id) for achievement in achievements: - if self.has_user_achievement_already( - user, achievement - ) or not self.has_user_achievement(user, achievement): + if self.has_user_achievement_already(user, achievement) or not self.has_user_achievement(user, achievement): continue - self._achievements.add_user_got_achievement( - UserGotAchievement(user, achievement, user.server) - ) + self._achievements.add_user_got_achievement(UserGotAchievement(user, achievement, user.server)) self._db.save_changes() self._give_user_xp(user) - await self._send_achievement_notification( - user.server.discord_id, user.discord_id, achievement.name - ) + await self._send_achievement_notification(user.server.discord_id, user.discord_id, achievement.name) def _give_user_xp(self, user: User): - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{user.server.discord_id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{user.server.discord_id}") user.xp += settings.xp_per_achievement self._users.update_user(user) self._db.save_changes() - async def _send_achievement_notification( - self, guild_id: int, member_id: int, achievement_name: str - ): + async def _send_achievement_notification(self, guild_id: int, member_id: int, achievement_name: str): member = self._bot.get_guild(guild_id).get_member(member_id) - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{guild_id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild_id}") await self._message_service.send_channel_message( self._bot.get_channel(settings.notification_chat_id), - self._t.transform("modules.achievements.got_new_achievement").format( - member.mention, achievement_name - ), + self._t.transform("modules.achievements.got_new_achievement").format(member.mention, achievement_name), is_persistent=True, ) diff --git a/bot/src/modules/achievements/achievements_module.py b/bot/src/modules/achievements/achievements_module.py index cc7c5ec6..4e1a53f4 100644 --- a/bot/src/modules/achievements/achievements_module.py +++ b/bot/src/modules/achievements/achievements_module.py @@ -29,25 +29,17 @@ class AchievementsModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.achievements_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): pass - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): services.add_transient(AchievementAttributeResolver) services.add_transient(AchievementService) services.add_transient(AchievementGroup) - services.add_transient( - DiscordEventTypesEnum.on_message.value, AchievementOnMessageEvent - ) - services.add_transient( - DiscordEventTypesEnum.on_reaction_add.value, AchievementOnReactionAddEvent - ) + services.add_transient(DiscordEventTypesEnum.on_message.value, AchievementOnMessageEvent) + services.add_transient(DiscordEventTypesEnum.on_reaction_add.value, AchievementOnReactionAddEvent) services.add_transient( DiscordEventTypesEnum.on_reaction_remove.value, AchievementOnReactionRemoveEvent, diff --git a/bot/src/modules/achievements/commands/achievements_group.py b/bot/src/modules/achievements/commands/achievements_group.py index 497dfe4c..a0c73ccb 100644 --- a/bot/src/modules/achievements/commands/achievements_group.py +++ b/bot/src/modules/achievements/commands/achievements_group.py @@ -54,9 +54,7 @@ class AchievementGroup(DiscordCommandABC): if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") if not FeatureFlagsSettings.get_flag_from_dict( server_config.feature_flags, FeatureFlagsEnum.achievements_module ): diff --git a/bot/src/modules/achievements/events/achievement_on_message_event.py b/bot/src/modules/achievements/events/achievement_on_message_event.py index 1cb6a9ee..b3564ccf 100644 --- a/bot/src/modules/achievements/events/achievement_on_message_event.py +++ b/bot/src/modules/achievements/events/achievement_on_message_event.py @@ -43,18 +43,14 @@ class AchievementOnMessageEvent(OnMessageABC): if message.author.bot: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{message.guild.id}" - ) + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{message.guild.id}") if not FeatureFlagsSettings.get_flag_from_dict( server_config.feature_flags, FeatureFlagsEnum.achievements_module ): return server = self._servers.get_server_by_discord_id(message.guild.id) - user = self._users.get_user_by_discord_id_and_server_id( - message.author.id, server.id - ) + user = self._users.get_user_by_discord_id_and_server_id(message.author.id, server.id) user.message_count += 1 self._users.update_user(user) diff --git a/bot/src/modules/achievements/events/achievement_on_reaction_add_event.py b/bot/src/modules/achievements/events/achievement_on_reaction_add_event.py index cb4fcec9..37959385 100644 --- a/bot/src/modules/achievements/events/achievement_on_reaction_add_event.py +++ b/bot/src/modules/achievements/events/achievement_on_reaction_add_event.py @@ -50,9 +50,7 @@ class AchievementOnReactionAddEvent(OnReactionAddABC): if user.bot: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{user.guild.id}" - ) + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{user.guild.id}") if not FeatureFlagsSettings.get_flag_from_dict( server_config.feature_flags, FeatureFlagsEnum.achievements_module ): diff --git a/bot/src/modules/achievements/events/achievement_on_reaction_remove_event.py b/bot/src/modules/achievements/events/achievement_on_reaction_remove_event.py index 63aacffc..a25e1868 100644 --- a/bot/src/modules/achievements/events/achievement_on_reaction_remove_event.py +++ b/bot/src/modules/achievements/events/achievement_on_reaction_remove_event.py @@ -50,9 +50,7 @@ class AchievementOnReactionRemoveEvent(OnReactionRemoveABC): if user.bot: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{user.guild.id}" - ) + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{user.guild.id}") if not FeatureFlagsSettings.get_flag_from_dict( server_config.feature_flags, FeatureFlagsEnum.achievements_module ): diff --git a/bot/src/modules/achievements/events/achievement_on_voice_state_update_event.py b/bot/src/modules/achievements/events/achievement_on_voice_state_update_event.py index d7c5aeb7..b28d5f64 100644 --- a/bot/src/modules/achievements/events/achievement_on_voice_state_update_event.py +++ b/bot/src/modules/achievements/events/achievement_on_voice_state_update_event.py @@ -46,9 +46,7 @@ class AchievementOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC): if member.bot: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{member.guild.id}" - ) + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{member.guild.id}") if not FeatureFlagsSettings.get_flag_from_dict( server_config.feature_flags, FeatureFlagsEnum.achievements_module ): diff --git a/bot/src/modules/auto_role/auto_role_module.py b/bot/src/modules/auto_role/auto_role_module.py index 4fee55e8..07eba97e 100644 --- a/bot/src/modules/auto_role/auto_role_module.py +++ b/bot/src/modules/auto_role/auto_role_module.py @@ -20,14 +20,10 @@ class AutoRoleModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.auto_role_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): pass - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): services.add_transient(AutoRoleReactionHandler) # commands services.add_transient(AutoRoleGroup) diff --git a/bot/src/modules/auto_role/command/auto_role_group.py b/bot/src/modules/auto_role/command/auto_role_group.py index 6e5ae53c..f8d48d4e 100644 --- a/bot/src/modules/auto_role/command/auto_role_group.py +++ b/bot/src/modules/auto_role/command/auto_role_group.py @@ -58,14 +58,10 @@ class AutoRoleGroup(DiscordCommandABC): self, interaction: discord.Interaction, current: str ) -> TList[app_commands.Choice[str]]: server = self._servers.get_server_by_discord_id(interaction.guild.id) - auto_roles = self._auto_roles.get_auto_roles_by_server_id(server.id).select( - lambda x: x.id - ) + auto_roles = self._auto_roles.get_auto_roles_by_server_id(server.id).select(lambda x: x.id) return [ app_commands.Choice(name=auto_role, value=auto_role) - for auto_role in self._client_utils.get_auto_complete_list( - auto_roles, current, lambda x: x.name - ) + for auto_role in self._client_utils.get_auto_complete_list(auto_roles, current, lambda x: x.name) ] @commands.hybrid_group(name="auto-role") @@ -82,12 +78,8 @@ class AutoRoleGroup(DiscordCommandABC): if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.auto_role_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.auto_role_module): return embed = discord.Embed( @@ -98,9 +90,7 @@ class AutoRoleGroup(DiscordCommandABC): server = self._servers.get_server_by_discord_id(ctx.guild.id) auto_roles = self._auto_roles.get_auto_roles_by_server_id(server.id) if auto_roles.count() < 1: - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.auto_role.error.nothing_found") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.auto_role.error.nothing_found")) self._logger.trace(__name__, f"Finished command auto-role list") return @@ -128,18 +118,12 @@ class AutoRoleGroup(DiscordCommandABC): @CommandChecks.check_is_ready() @CommandChecks.check_is_member_moderator() async def add(self, ctx: Context, channel: discord.TextChannel, message_id: str): - self._logger.debug( - __name__, f"Received command auto-role add {ctx} {message_id}" - ) + self._logger.debug(__name__, f"Received command auto-role add {ctx} {message_id}") if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.auto_role_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.auto_role_module): return message = ( @@ -151,56 +135,38 @@ class AutoRoleGroup(DiscordCommandABC): .single_or_default() ) if message is None: - self._logger.debug( - __name__, f"Message with id {message_id} not found in {channel.name}" - ) + self._logger.debug(__name__, f"Message with id {message_id} not found in {channel.name}") await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.auto_role.add.error.not_found").format( - message_id, channel.mention - ), + self._t.transform("modules.auto_role.add.error.not_found").format(message_id, channel.mention), ) self._logger.trace(__name__, f"Finished command auto-role add") return if self._auto_roles.find_auto_role_by_message_id(int(message_id)) is not None: - self._logger.debug( - __name__, f"auto-role for message {message_id} already exists" - ) + self._logger.debug(__name__, f"auto-role for message {message_id} already exists") await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.auto_role.add.error.already_exists").format( - message_id - ), + self._t.transform("modules.auto_role.add.error.already_exists").format(message_id), ) self._logger.trace(__name__, f"Finished command auto-role add") return server = self._servers.get_server_by_discord_id(ctx.guild.id) - self._auto_roles.add_auto_role( - AutoRole(server, int(channel.id), int(message_id)) - ) + self._auto_roles.add_auto_role(AutoRole(server, int(channel.id), int(message_id))) self._db_context.save_changes() - self._logger.info( - __name__, f"Saved auto-role for message {message_id} at server {server}" - ) + self._logger.info(__name__, f"Saved auto-role for message {message_id} at server {server}") await self._message_service.send_ctx_msg( ctx, self._t.transform("modules.auto_role.add.success").format(message_id) ) self._logger.trace(__name__, f"Finished command auto-role add") @add.autocomplete("message_id") - async def add_autocomplete( - self, interaction: discord.Interaction, current: str - ) -> TList[app_commands.Choice[str]]: - channel = discord.utils.get( - interaction.guild.text_channels, id=interaction.channel_id - ) + async def add_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: + channel = discord.utils.get(interaction.guild.text_channels, id=interaction.channel_id) try: channel_from_data = interaction.data["options"][0]["options"][0]["value"] - found_channel = discord.utils.get( - interaction.guild.text_channels, id=int(channel_from_data) - ) + found_channel = discord.utils.get(interaction.guild.text_channels, id=int(channel_from_data)) if found_channel is not None: channel = found_channel finally: @@ -208,9 +174,7 @@ class AutoRoleGroup(DiscordCommandABC): messages = [message async for message in channel.history(limit=10)] return [ - app_commands.Choice( - name=f"{message.author}@{message.created_at}", value=str(message.id) - ) + app_commands.Choice(name=f"{message.author}@{message.created_at}", value=str(message.id)) for message in messages if current in str(message.id) ] @@ -220,18 +184,12 @@ class AutoRoleGroup(DiscordCommandABC): @CommandChecks.check_is_ready() @CommandChecks.check_is_member_moderator() async def remove(self, ctx: Context, auto_role: int): - self._logger.debug( - __name__, f"Received command auto-role remove {ctx} {auto_role}" - ) + self._logger.debug(__name__, f"Received command auto-role remove {ctx} {auto_role}") if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.auto_role_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.auto_role_module): return auto_role_from_db = self._auto_roles.find_auto_role_by_id(auto_role) @@ -239,16 +197,12 @@ class AutoRoleGroup(DiscordCommandABC): self._logger.debug(__name__, f"auto-role {auto_role} not found") await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.auto_role.remove.error.not_found").format( - auto_role - ), + self._t.transform("modules.auto_role.remove.error.not_found").format(auto_role), ) self._logger.trace(__name__, f"Finished command auto-role remove") return - for rule in self._auto_roles.get_auto_role_rules_by_auto_role_id( - auto_role_from_db.id - ): + for rule in self._auto_roles.get_auto_role_rules_by_auto_role_id(auto_role_from_db.id): self._auto_roles.delete_auto_role_rule(rule) self._logger.info(__name__, f"Removed auto-role rule {rule.role_id}") @@ -271,18 +225,12 @@ class AutoRoleGroup(DiscordCommandABC): @CommandChecks.check_is_ready() @CommandChecks.check_is_member_moderator() async def react(self, ctx: Context, auto_role: int): - self._logger.debug( - __name__, f"Received command auto-role react {ctx} {auto_role}" - ) + self._logger.debug(__name__, f"Received command auto-role react {ctx} {auto_role}") if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.auto_role_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.auto_role_module): return auto_role_from_db = self._auto_roles.find_auto_role_by_id(auto_role) @@ -290,16 +238,12 @@ class AutoRoleGroup(DiscordCommandABC): self._logger.debug(__name__, f"auto-role {auto_role} not found") await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.auto_role.remove.error.not_found").format( - auto_role - ), + self._t.transform("modules.auto_role.remove.error.not_found").format(auto_role), ) self._logger.trace(__name__, f"Finished command auto-role react") return - for rule in self._auto_roles.get_auto_role_rules_by_auto_role_id( - auto_role_from_db.id - ): + for rule in self._auto_roles.get_auto_role_rules_by_auto_role_id(auto_role_from_db.id): await self._client_utils.react_to_message_by_auto_role_rule( auto_role_from_db.discord_channel_id, auto_role_from_db.discord_message_id, @@ -333,12 +277,8 @@ class AutoRoleGroup(DiscordCommandABC): if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.auto_role_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.auto_role_module): return embed = discord.Embed( @@ -391,30 +331,20 @@ class AutoRoleGroup(DiscordCommandABC): @CommandChecks.check_is_ready() @CommandChecks.check_is_member_moderator() async def add(self, ctx: Context, auto_role: int, emoji_name: str, role_id: str): - self._logger.debug( - __name__, f"Received command auto-role add {ctx} {auto_role}" - ) + self._logger.debug(__name__, f"Received command auto-role add {ctx} {auto_role}") if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.auto_role_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.auto_role_module): return emoji = discord.utils.get(self._bot.emojis, name=emoji_name) if emoji is None: - self._logger.debug( - __name__, f"auto-role rule add emoji {emoji_name} not found" - ) + self._logger.debug(__name__, f"auto-role rule add emoji {emoji_name} not found") await self._message_service.send_ctx_msg( ctx, - self._t.transform( - "modules.auto_role.rule.add.error.emoji_not_found" - ).format(emoji_name, auto_role), + self._t.transform("modules.auto_role.rule.add.error.emoji_not_found").format(emoji_name, auto_role), ) self._logger.trace(__name__, f"Finished command auto-role add") return @@ -424,9 +354,7 @@ class AutoRoleGroup(DiscordCommandABC): self._logger.debug(__name__, f"auto-role rule add role {role_id} not found") await self._message_service.send_ctx_msg( ctx, - self._t.transform( - "modules.auto_role.rule.add.error.role_not_found" - ).format(role_id, auto_role), + self._t.transform("modules.auto_role.rule.add.error.role_not_found").format(role_id, auto_role), ) self._logger.trace(__name__, f"Finished command auto-role add") return @@ -435,9 +363,7 @@ class AutoRoleGroup(DiscordCommandABC): if auto_role_from_db is None: await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.auto_role.remove.error.not_found").format( - auto_role - ), + self._t.transform("modules.auto_role.remove.error.not_found").format(auto_role), ) self._logger.trace(__name__, f"Finished command auto-role rule add") return @@ -450,16 +376,12 @@ class AutoRoleGroup(DiscordCommandABC): ): await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.auto_role.add.error.already_exists").format( - auto_role - ), + self._t.transform("modules.auto_role.add.error.already_exists").format(auto_role), ) self._logger.trace(__name__, f"Finished command auto-role rule add") return - self._auto_roles.add_auto_role_rule( - AutoRoleRule(auto_role_from_db, emoji_name, int(role_id)) - ) + self._auto_roles.add_auto_role_rule(AutoRoleRule(auto_role_from_db, emoji_name, int(role_id))) self._db_context.save_changes() rule = ( self._auto_roles.get_auto_role_rules_by_auto_role_id(auto_role) @@ -479,28 +401,20 @@ class AutoRoleGroup(DiscordCommandABC): await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.auto_role.rule.add.success").format( - emoji, role.mention, auto_role - ), + self._t.transform("modules.auto_role.rule.add.success").format(emoji, role.mention, auto_role), ) self._logger.trace(__name__, f"Finished command auto-role rule add") @add.autocomplete("auto_role") - async def add_autocomplete( - self, interaction: discord.Interaction, current: str - ) -> TList[app_commands.Choice[str]]: + async def add_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: return await self._auto_role_auto_complete(interaction, current) @add.autocomplete("emoji_name") - async def add_autocomplete( - self, interaction: discord.Interaction, current: str - ) -> TList[app_commands.Choice[str]]: + async def add_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: emojis = List(discord.Emoji, interaction.guild.emojis) return [ app_commands.Choice(name=emoji.name, value=emoji.name) - for emoji in self._client_utils.get_auto_complete_list( - emojis, current, lambda e: e.name - ) + for emoji in self._client_utils.get_auto_complete_list(emojis, current, lambda e: e.name) ] @add.autocomplete("role_id") @@ -510,9 +424,7 @@ class AutoRoleGroup(DiscordCommandABC): roles = List(discord.Role, interaction.guild.roles) return [ app_commands.Choice(name=role.name, value=str(role.id)) - for role in self._client_utils.get_auto_complete_list( - roles, current, lambda r: r.name - ) + for role in self._client_utils.get_auto_complete_list(roles, current, lambda r: r.name) ] @rule.command() @@ -520,18 +432,12 @@ class AutoRoleGroup(DiscordCommandABC): @CommandChecks.check_is_ready() @CommandChecks.check_is_member_moderator() async def remove(self, ctx: Context, auto_role_rule: int): - self._logger.debug( - __name__, f"Received command auto-role remove {ctx} {auto_role_rule}" - ) + self._logger.debug(__name__, f"Received command auto-role remove {ctx} {auto_role_rule}") if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.auto_role_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.auto_role_module): return auto_role_from_db = self._auto_roles.get_auto_role_rule_by_id(auto_role_rule) @@ -539,9 +445,7 @@ class AutoRoleGroup(DiscordCommandABC): self._logger.debug(__name__, f"auto-role rule {auto_role_rule} not found") await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.auto_role.remove.error.not_found").format( - auto_role_rule - ), + self._t.transform("modules.auto_role.remove.error.not_found").format(auto_role_rule), ) self._logger.trace(__name__, f"Finished command auto-role rule remove") return @@ -551,9 +455,7 @@ class AutoRoleGroup(DiscordCommandABC): self._logger.info(__name__, f"Removed auto-role rule {auto_role_rule}") await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.auto_role.rule.remove.success").format( - auto_role_rule - ), + self._t.transform("modules.auto_role.rule.remove.success").format(auto_role_rule), ) self._logger.trace(__name__, f"Finished command auto-role remove") @@ -562,18 +464,12 @@ class AutoRoleGroup(DiscordCommandABC): self, interaction: discord.Interaction, current: str ) -> TList[app_commands.Choice[str]]: server = self._servers.get_server_by_discord_id(interaction.guild.id) - auto_roles = self._auto_roles.get_auto_roles_by_server_id(server.id).select( - lambda x: x.id - ) - rules = auto_roles.select_many( - lambda ar: self._auto_roles.get_auto_role_rules_by_auto_role_id(ar) - ) + auto_roles = self._auto_roles.get_auto_roles_by_server_id(server.id).select(lambda x: x.id) + rules = auto_roles.select_many(lambda ar: self._auto_roles.get_auto_role_rules_by_auto_role_id(ar)) return [ app_commands.Choice( name=f"{rule.id} {rule.emoji_name} {interaction.guild.get_role(int(rule.role_id))}", value=rule.id, ) - for rule in self._client_utils.get_auto_complete_list( - rules, current, lambda r: r.id - ) + for rule in self._client_utils.get_auto_complete_list(rules, current, lambda r: r.id) ] diff --git a/bot/src/modules/auto_role/events/auto_role_on_raw_reaction_add.py b/bot/src/modules/auto_role/events/auto_role_on_raw_reaction_add.py index a85fadd2..f5d14804 100644 --- a/bot/src/modules/auto_role/events/auto_role_on_raw_reaction_add.py +++ b/bot/src/modules/auto_role/events/auto_role_on_raw_reaction_add.py @@ -35,12 +35,8 @@ class AutoRoleOnRawReactionAddEvent(OnRawReactionAddABC): @EventChecks.check_is_ready() async def on_raw_reaction_add(self, payload: RawReactionActionEvent): self._logger.debug(__name__, f"Module {type(self)} started") - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{payload.guild_id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.auto_role_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{payload.guild_id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.auto_role_module): return await self._reaction_handler.handle(payload, "add") diff --git a/bot/src/modules/auto_role/events/auto_role_on_raw_reaction_remove.py b/bot/src/modules/auto_role/events/auto_role_on_raw_reaction_remove.py index 0defd312..a174c8f5 100644 --- a/bot/src/modules/auto_role/events/auto_role_on_raw_reaction_remove.py +++ b/bot/src/modules/auto_role/events/auto_role_on_raw_reaction_remove.py @@ -35,12 +35,8 @@ class AutoRoleOnRawReactionRemoveEvent(OnRawReactionRemoveABC): @EventChecks.check_is_ready() async def on_raw_reaction_remove(self, payload: RawReactionActionEvent): self._logger.debug(__name__, f"Module {type(self)} started") - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{payload.guild_id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.auto_role_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{payload.guild_id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.auto_role_module): return await self._reaction_handler.handle(payload, "remove") diff --git a/bot/src/modules/auto_role/helper/auto_role_reaction_handler.py b/bot/src/modules/auto_role/helper/auto_role_reaction_handler.py index b0b59aee..47ab3778 100644 --- a/bot/src/modules/auto_role/helper/auto_role_reaction_handler.py +++ b/bot/src/modules/auto_role/helper/auto_role_reaction_handler.py @@ -22,9 +22,7 @@ class AutoRoleReactionHandler: self._servers = servers self._auto_roles = auto_roles - self._message_ids = self._auto_roles.get_auto_roles().select( - lambda x: x.discord_message_id - ) + self._message_ids = self._auto_roles.get_auto_roles().select(lambda x: x.discord_message_id) self._roles = self._auto_roles.get_auto_roles() async def handle(self, payload: RawReactionActionEvent, r_type=None) -> None: @@ -36,9 +34,7 @@ class AutoRoleReactionHandler: guild = self._bot.get_guild(payload.guild_id) user = guild.get_member(payload.user_id) if user is None: - self._logger.warn( - __name__, f"User {payload.user_id} in {guild.name} not found - skipping" - ) + self._logger.warn(__name__, f"User {payload.user_id} in {guild.name} not found - skipping") return if user.bot: @@ -53,9 +49,7 @@ class AutoRoleReactionHandler: self._logger.debug(__name__, f"auto-role for message not found - skipping") return - rules: List[ - AutoRoleRule - ] = self._auto_roles.get_auto_role_rules_by_auto_role_id(auto_role.id) + rules: List[AutoRoleRule] = self._auto_roles.get_auto_role_rules_by_auto_role_id(auto_role.id) if rules.count() == 0: self._logger.debug(__name__, f"auto-role rules not found - skipping") return diff --git a/bot/src/modules/base/base_module.py b/bot/src/modules/base/base_module.py index 60f17173..fc04e55e 100644 --- a/bot/src/modules/base/base_module.py +++ b/bot/src/modules/base/base_module.py @@ -53,14 +53,10 @@ class BaseModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.base_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): pass - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): services.add_transient(BaseReactionHandler) services.add_singleton(EventService) services.add_transient(UserWarningsService) @@ -86,27 +82,13 @@ class BaseModule(ModuleABC): services.add_transient(UnregisterGroup) services.add_transient(GameServerGroup) # events - services.add_transient( - DiscordEventTypesEnum.on_command.value, BaseOnCommandEvent - ) - services.add_transient( - DiscordEventTypesEnum.on_command_error.value, BaseOnCommandErrorEvent - ) - services.add_transient( - DiscordEventTypesEnum.on_member_join.value, BaseOnMemberJoinEvent - ) - services.add_transient( - DiscordEventTypesEnum.on_member_remove.value, BaseOnMemberRemoveEvent - ) - services.add_transient( - DiscordEventTypesEnum.on_message.value, BaseOnMessageEvent - ) - services.add_transient( - DiscordEventTypesEnum.on_message_delete.value, BaseOnMessageDeleteEvent - ) - services.add_transient( - DiscordEventTypesEnum.on_raw_reaction_add.value, BaseOnRawReactionAddEvent - ) + services.add_transient(DiscordEventTypesEnum.on_command.value, BaseOnCommandEvent) + services.add_transient(DiscordEventTypesEnum.on_command_error.value, BaseOnCommandErrorEvent) + services.add_transient(DiscordEventTypesEnum.on_member_join.value, BaseOnMemberJoinEvent) + services.add_transient(DiscordEventTypesEnum.on_member_remove.value, BaseOnMemberRemoveEvent) + services.add_transient(DiscordEventTypesEnum.on_message.value, BaseOnMessageEvent) + services.add_transient(DiscordEventTypesEnum.on_message_delete.value, BaseOnMessageDeleteEvent) + services.add_transient(DiscordEventTypesEnum.on_raw_reaction_add.value, BaseOnRawReactionAddEvent) services.add_transient( DiscordEventTypesEnum.on_raw_reaction_remove.value, BaseOnRawReactionRemoveEvent, diff --git a/bot/src/modules/base/birthday_watcher.py b/bot/src/modules/base/birthday_watcher.py index 2b01095f..7b19638a 100644 --- a/bot/src/modules/base/birthday_watcher.py +++ b/bot/src/modules/base/birthday_watcher.py @@ -46,9 +46,7 @@ class BirthdayWatcher(TaskABC): if user.birthday.day != today.day or user.birthday.month != today.month: continue - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{user.server.discord_id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{user.server.discord_id}") user.xp += settings.xp_for_birthday self._users.update_user(user) @@ -58,9 +56,7 @@ class BirthdayWatcher(TaskABC): member = guild.get_member(user.discord_id) await self._message_service.send_channel_message( self._bot.get_channel(settings.notification_chat_id), - self._t.transform("modules.base.user.birthday.has_birthday").format( - member.mention - ), + self._t.transform("modules.base.user.birthday.has_birthday").format(member.mention), is_persistent=True, ) except Exception as e: diff --git a/bot/src/modules/base/command/afk_command.py b/bot/src/modules/base/command/afk_command.py index 924c012d..092c9788 100644 --- a/bot/src/modules/base/command/afk_command.py +++ b/bot/src/modules/base/command/afk_command.py @@ -39,9 +39,7 @@ class AFKCommand(DiscordCommandABC): @CommandChecks.check_is_ready() async def afk(self, ctx: Context): self._logger.debug(__name__, f"Received command afk {ctx}") - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") if ctx.author.voice is None or ctx.author.voice.channel is None: await self._message_service.send_ctx_msg( @@ -52,9 +50,7 @@ class AFKCommand(DiscordCommandABC): return self._bot.loop.create_task( - self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.base.afk_command_move_message") - ) + self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.afk_command_move_message")) ) channel: VoiceChannel = ctx.guild.get_channel(settings.afk_command_channel_id) try: @@ -66,8 +62,6 @@ class AFKCommand(DiscordCommandABC): f"Cannot move user {ctx.author.id} to channel {ctx.channel.id}", e, ) - await self._message_service.send_ctx_msg( - ctx, self._t.transform("common.no_permission_message") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("common.no_permission_message")) self._logger.trace(__name__, f"Finished afk command") diff --git a/bot/src/modules/base/command/game_server_group.py b/bot/src/modules/base/command/game_server_group.py index 051db38e..55d235e3 100644 --- a/bot/src/modules/base/command/game_server_group.py +++ b/bot/src/modules/base/command/game_server_group.py @@ -76,15 +76,9 @@ class GameServerGroup(DiscordCommandABC): if ctx.guild is None: return - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - settings.feature_flags, FeatureFlagsEnum.game_server - ): - await self._message_service.send_ctx_msg( - ctx, self._t.transform("common.feature_not_activated") - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(settings.feature_flags, FeatureFlagsEnum.game_server): + await self._message_service.send_ctx_msg(ctx, self._t.transform("common.feature_not_activated")) return server = self._servers.get_server_by_discord_id(ctx.guild.id) @@ -127,22 +121,14 @@ class GameServerGroup(DiscordCommandABC): @CommandChecks.check_is_ready() @CommandChecks.check_is_member_admin() async def add(self, ctx: Context, name: str, api_key_id: int): - self._logger.debug( - __name__, f"Received command game-server add {ctx}: {name} {api_key_id}" - ) + self._logger.debug(__name__, f"Received command game-server add {ctx}: {name} {api_key_id}") if ctx.guild is None: return - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - settings.feature_flags, FeatureFlagsEnum.game_server - ): - await self._message_service.send_ctx_msg( - ctx, self._t.transform("common.feature_not_activated") - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(settings.feature_flags, FeatureFlagsEnum.game_server): + await self._message_service.send_ctx_msg(ctx, self._t.transform("common.feature_not_activated")) return server = self._servers.get_server_by_discord_id(ctx.guild.id) @@ -166,9 +152,7 @@ class GameServerGroup(DiscordCommandABC): return [ app_commands.Choice(name=f"{key.identifier}: {key.key}", value=key.id) - for key in self._client_utils.get_auto_complete_list( - keys, current, lambda x: x.key - ) + for key in self._client_utils.get_auto_complete_list(keys, current, lambda x: x.key) ] @game_server.command() @@ -181,38 +165,26 @@ class GameServerGroup(DiscordCommandABC): if ctx.guild is None: return - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - settings.feature_flags, FeatureFlagsEnum.game_server - ): - await self._message_service.send_ctx_msg( - ctx, self._t.transform("common.feature_not_activated") - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(settings.feature_flags, FeatureFlagsEnum.game_server): + await self._message_service.send_ctx_msg(ctx, self._t.transform("common.feature_not_activated")) return game_server = self._game_servers.get_game_server_by_id(id) self._game_servers.delete_game_server(game_server) self._db.save_changes() - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.base.game_server.remove.success") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.game_server.remove.success")) self._logger.trace(__name__, f"Finished command game-server remove") @remove.autocomplete("id") - async def id_autocomplete( - self, interaction: discord.Interaction, current: str - ) -> TList[app_commands.Choice[str]]: + async def id_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: server = self._servers.get_server_by_discord_id(interaction.guild.id) game_servers = self._game_servers.get_game_servers_by_server_id(server.id) return [ app_commands.Choice(name=gs.name, value=gs.id) - for gs in self._client_utils.get_auto_complete_list( - game_servers, current, lambda x: x.name - ) + for gs in self._client_utils.get_auto_complete_list(game_servers, current, lambda x: x.name) ] @game_server.command(name="list-members") @@ -225,30 +197,20 @@ class GameServerGroup(DiscordCommandABC): if ctx.guild is None: return - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - settings.feature_flags, FeatureFlagsEnum.game_server - ): - await self._message_service.send_ctx_msg( - ctx, self._t.transform("common.feature_not_activated") - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(settings.feature_flags, FeatureFlagsEnum.game_server): + await self._message_service.send_ctx_msg(ctx, self._t.transform("common.feature_not_activated")) return game_server = self._game_servers.get_game_server_by_id(id) - game_idents = self._user_game_idents.get_user_game_idents_by_game_server_id( - game_server.id - ) + game_idents = self._user_game_idents.get_user_game_idents_by_game_server_id(game_server.id) users = "" for game_ident in game_idents: users += f"\n{game_ident.user.name}" embed = discord.Embed( title=self._t.transform("modules.base.game_server.list_members.title"), - description=self._t.transform( - "modules.base.game_server.list_members.description" - ), + description=self._t.transform("modules.base.game_server.list_members.description"), color=int("ef9d0d", 16), ) embed.add_field( @@ -261,15 +223,11 @@ class GameServerGroup(DiscordCommandABC): self._logger.trace(__name__, f"Finished command game-server remove") @list_members.autocomplete("id") - async def id_autocomplete( - self, interaction: discord.Interaction, current: str - ) -> TList[app_commands.Choice[str]]: + async def id_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: server = self._servers.get_server_by_discord_id(interaction.guild.id) game_servers = self._game_servers.get_game_servers_by_server_id(server.id) return [ app_commands.Choice(name=gs.name, value=gs.id) - for gs in self._client_utils.get_auto_complete_list( - game_servers, current, lambda x: x.name - ) + for gs in self._client_utils.get_auto_complete_list(game_servers, current, lambda x: x.name) ] diff --git a/bot/src/modules/base/command/help_command.py b/bot/src/modules/base/command/help_command.py index e97dc198..beb63e77 100644 --- a/bot/src/modules/base/command/help_command.py +++ b/bot/src/modules/base/command/help_command.py @@ -50,8 +50,6 @@ class HelpCommand(DiscordCommandABC): self._logger.trace(__name__, f"Finished help command") @help.autocomplete("persistent_flag") - async def help_autocomplete( - self, interaction: discord.Interaction, current: str - ) -> List[app_commands.Choice[str]]: + async def help_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]: flags = ["--stay"] return [app_commands.Choice(name=key, value=key) for key in flags] diff --git a/bot/src/modules/base/command/info_command.py b/bot/src/modules/base/command/info_command.py index 11290c05..e228be84 100644 --- a/bot/src/modules/base/command/info_command.py +++ b/bot/src/modules/base/command/info_command.py @@ -55,10 +55,7 @@ class InfoCommand(DiscordCommandABC): ) start_time = self._config.get_configuration("Bot_StartTime") ontime = round( - ( - datetime.now() - datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S.%f") - ).total_seconds() - / 3600, + (datetime.now() - datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S.%f")).total_seconds() / 3600, 2, ) embed.add_field( diff --git a/bot/src/modules/base/command/mass_move_command.py b/bot/src/modules/base/command/mass_move_command.py index cedbaa03..4dd835d2 100644 --- a/bot/src/modules/base/command/mass_move_command.py +++ b/bot/src/modules/base/command/mass_move_command.py @@ -58,9 +58,7 @@ class MassMoveCommand(DiscordCommandABC): await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.base.mass_move.moved").format( - channel_from.mention, channel_to.mention - ), + self._t.transform("modules.base.mass_move.moved").format(channel_from.mention, channel_to.mention), ) self._logger.trace(__name__, f"Finished mass-move command") diff --git a/bot/src/modules/base/command/ping_command.py b/bot/src/modules/base/command/ping_command.py index 69aff5cf..ca0a14ac 100644 --- a/bot/src/modules/base/command/ping_command.py +++ b/bot/src/modules/base/command/ping_command.py @@ -58,12 +58,8 @@ class PingCommand(DiscordCommandABC): color=int("ef9d0d", 16), ) for server in self._settings.ping_urls: - embed.add_field( - name=server, value=f"{self._get_ping(server)} ms", inline=False - ) + embed.add_field(name=server, value=f"{self._get_ping(server)} ms", inline=False) await self._message_service.send_ctx_msg(ctx, embed) else: - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.base.pong") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.pong")) self._logger.trace(__name__, f"Finished ping command") diff --git a/bot/src/modules/base/command/presence_command.py b/bot/src/modules/base/command/presence_command.py index 688e3d20..a314b4aa 100644 --- a/bot/src/modules/base/command/presence_command.py +++ b/bot/src/modules/base/command/presence_command.py @@ -34,9 +34,7 @@ class PresenceCommand(DiscordCommandABC): if text == "": await self._bot.change_presence(activity=None) - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.base.presence.removed") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.presence.removed")) return if len(text) > 128: @@ -46,8 +44,6 @@ class PresenceCommand(DiscordCommandABC): return await self._bot.change_presence(activity=discord.Game(name=text)) - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.base.presence.changed") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.presence.changed")) self._logger.trace(__name__, f"Finished presence command") diff --git a/bot/src/modules/base/command/purge_command.py b/bot/src/modules/base/command/purge_command.py index ff40f718..9816e29f 100644 --- a/bot/src/modules/base/command/purge_command.py +++ b/bot/src/modules/base/command/purge_command.py @@ -41,20 +41,14 @@ class PurgeCommand(DiscordCommandABC): @CommandChecks.check_is_member_moderator() async def purge(self, ctx: Context): self._logger.debug(__name__, f"Received command purge {ctx}") - server_settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) + server_settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.moderator.purge_message") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.moderator.purge_message")) await asyncio.sleep(server_settings.message_delete_timer) try: await ctx.channel.purge() except Exception as e: self._logger.error(__name__, f"Cannot purge channel {ctx.channel.id}", e) - await self._message_service.send_ctx_msg( - ctx, self._t.transform("common.bot_has_no_permission_message") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("common.bot_has_no_permission_message")) self._logger.trace(__name__, f"Finished purge command") diff --git a/bot/src/modules/base/command/register_group.py b/bot/src/modules/base/command/register_group.py index 4fc94ac3..a598b31e 100644 --- a/bot/src/modules/base/command/register_group.py +++ b/bot/src/modules/base/command/register_group.py @@ -59,17 +59,13 @@ class RegisterGroup(DiscordCommandABC): @commands.guild_only() @CommandChecks.check_is_ready() @CommandChecks.check_is_member_moderator() - async def minecraft( - self, ctx: Context, member: discord.Member, game_server: int, name: str - ): + async def minecraft(self, ctx: Context, member: discord.Member, game_server: int, name: str): self._logger.debug(__name__, f"Received command register minecraft {ctx}") minecraft_id = None try: self._logger.debug(__name__, f"Try to get minecraft id for {name}") - response = requests.get( - url=f"https://api.mojang.com/users/profiles/minecraft/{name}" - ) + response = requests.get(url=f"https://api.mojang.com/users/profiles/minecraft/{name}") if len(response.content) == 0: await self._message_service.send_interaction_msg( ctx.interaction, @@ -110,7 +106,5 @@ class RegisterGroup(DiscordCommandABC): return [ app_commands.Choice(name=gs.name, value=gs.id) - for gs in self._client_utils.get_auto_complete_list( - game_servers, current, lambda x: x.name - ) + for gs in self._client_utils.get_auto_complete_list(game_servers, current, lambda x: x.name) ] diff --git a/bot/src/modules/base/command/submit_group.py b/bot/src/modules/base/command/submit_group.py index b832b7c2..ad1570e3 100644 --- a/bot/src/modules/base/command/submit_group.py +++ b/bot/src/modules/base/command/submit_group.py @@ -11,9 +11,7 @@ from modules.base.forms.complaint_form import ComplaintForm class SubmitGroup(DiscordCommandABC): - def __init__( - self, services: ServiceProviderABC, logger: LoggerABC, bot: DiscordBotServiceABC - ): + def __init__(self, services: ServiceProviderABC, logger: LoggerABC, bot: DiscordBotServiceABC): DiscordCommandABC.__init__(self) self._services = services diff --git a/bot/src/modules/base/command/unregister_group.py b/bot/src/modules/base/command/unregister_group.py index 3f4e2c1d..4d5f796a 100644 --- a/bot/src/modules/base/command/unregister_group.py +++ b/bot/src/modules/base/command/unregister_group.py @@ -62,9 +62,7 @@ class UnregisterGroup(DiscordCommandABC): server = self._servers.get_server_by_discord_id(ctx.guild.id) user = self._users.get_user_by_discord_id_and_server_id(member.id, server.id) - ident = user.game_idents.where( - lambda x: x.game_server.id == game_server - ).single() + ident = user.game_idents.where(lambda x: x.game_server.id == game_server).single() self._user_game_idents.delete_user_game_ident(ident) self._users.update_user(user) self._db.save_changes() @@ -84,7 +82,5 @@ class UnregisterGroup(DiscordCommandABC): return [ app_commands.Choice(name=gs.name, value=gs.id) - for gs in self._client_utils.get_auto_complete_list( - game_servers, current, lambda x: x.name - ) + for gs in self._client_utils.get_auto_complete_list(game_servers, current, lambda x: x.name) ] diff --git a/bot/src/modules/base/command/user_group.py b/bot/src/modules/base/command/user_group.py index 5ed217e7..4f1df692 100644 --- a/bot/src/modules/base/command/user_group.py +++ b/bot/src/modules/base/command/user_group.py @@ -111,9 +111,7 @@ class UserGroup(DiscordCommandABC): type = "add" if not is_remove else "remove" await self._message_service.send_interaction_msg( ctx.interaction, - self._t.transform(f"modules.base.user.{type}.{atr.lower()}").format( - atr, value, member.mention - ), + self._t.transform(f"modules.base.user.{type}.{atr.lower()}").format(atr, value, member.mention), ) @commands.hybrid_group() @@ -131,9 +129,7 @@ class UserGroup(DiscordCommandABC): ) date = datetime.date(year, month, day) server = self._servers.get_server_by_discord_id(ctx.guild.id) - user = self._users.get_user_by_discord_id_and_server_id( - ctx.author.id, server.id - ) + user = self._users.get_user_by_discord_id_and_server_id(ctx.author.id, server.id) user.birthday = date self._users.update_user(user) self._db.save_changes() @@ -141,15 +137,11 @@ class UserGroup(DiscordCommandABC): ctx.interaction, self._t.transform("modules.base.user.birthday.success") ) # notify team to prevent multiple entries every day - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") channel = ctx.guild.get_channel(settings.team_channel_id) await self._message_service.send_channel_message( channel, - self._t.transform("modules.base.user.birthday.success_team").format( - ctx.author.mention, date - ), + self._t.transform("modules.base.user.birthday.success_team").format(ctx.author.mention, date), is_persistent=True, ) self._logger.trace(__name__, f"Finished user-info command") @@ -188,18 +180,12 @@ class UserGroup(DiscordCommandABC): @user.command() @commands.guild_only() @CommandChecks.check_is_ready() - async def info( - self, ctx: Context, member: Optional[discord.Member] = None, *, wait: int = None - ): - self._logger.debug( - __name__, f"Received command user-info {ctx}:{member},{wait}" - ) + async def info(self, ctx: Context, member: Optional[discord.Member] = None, *, wait: int = None): + self._logger.debug(__name__, f"Received command user-info {ctx}:{member},{wait}") is_mod = self._permissions.is_member_moderator(ctx.author) if member is not None and not is_mod: - await self._message_service.send_ctx_msg( - ctx, self._t.transform("common.no_permission_message") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("common.no_permission_message")) return if member is None or not isinstance(member, discord.Member): @@ -209,16 +195,10 @@ class UserGroup(DiscordCommandABC): user = self._users.find_user_by_discord_id_and_server_id(member.id, server.id) joins = self._user_joined_servers.get_user_joined_servers_by_user_id(user.id) - embed = discord.Embed( - title=member.name, description=member.name, color=int("ef9d0d", 16) - ) + embed = discord.Embed(title=member.name, description=member.name, color=int("ef9d0d", 16)) - embed.add_field( - name=self._t.transform("modules.base.user.atr.id"), value=member.id - ) - embed.add_field( - name=self._t.transform("modules.base.user.atr.name"), value=member.name - ) + embed.add_field(name=self._t.transform("modules.base.user.atr.id"), value=member.id) + embed.add_field(name=self._t.transform("modules.base.user.atr.name"), value=member.name) embed.add_field( name=self._t.transform("modules.base.user.atr.discord_join"), value=self._date.transform(member.created_at), @@ -229,9 +209,7 @@ class UserGroup(DiscordCommandABC): value=self._date.transform(member.joined_at), inline=False, ) - embed.add_field( - name=self._t.transform("modules.base.user.atr.xp"), value=str(user.xp) - ) + embed.add_field(name=self._t.transform("modules.base.user.atr.xp"), value=str(user.xp)) embed.add_field( name=self._t.transform("modules.base.user.atr.ontime"), value=str(self._client_utils.get_ontime_for_user(user)), @@ -281,9 +259,7 @@ class UserGroup(DiscordCommandABC): ) # send to interaction because of sensitive data - await self._message_service.send_interaction_msg( - ctx.interaction, embed, wait_before_delete=wait - ) + await self._message_service.send_interaction_msg(ctx.interaction, embed, wait_before_delete=wait) self._logger.trace(__name__, f"Finished user-info command") @user.command() @@ -294,9 +270,7 @@ class UserGroup(DiscordCommandABC): is_mod = self._permissions.is_member_moderator(ctx.author) if member is not None and not is_mod: - await self._message_service.send_ctx_msg( - ctx, self._t.transform("common.no_permission_message") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("common.no_permission_message")) return if member is None or not isinstance(member, discord.Member): @@ -320,26 +294,18 @@ class UserGroup(DiscordCommandABC): await self._message_service.send_interaction_msg( ctx.interaction, - self._t.transform(f"modules.base.user.get.{atr.lower()}").format( - member.mention, value - ), + self._t.transform(f"modules.base.user.get.{atr.lower()}").format(member.mention, value), ) @get.autocomplete("atr") - async def get_autocomplete( - self, interaction: discord.Interaction, current: str - ) -> TList[app_commands.Choice[str]]: - return [ - app_commands.Choice(name=value, value=key) for key, value in self._atr_TList - ] + async def get_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: + return [app_commands.Choice(name=value, value=key) for key, value in self._atr_TList] @user.command() @commands.guild_only() @CommandChecks.check_is_ready() @CommandChecks.check_is_member_moderator() - async def set( - self, ctx: Context, atr: str, value: int, member: discord.Member = None - ): + async def set(self, ctx: Context, atr: str, value: int, member: discord.Member = None): self._logger.debug(__name__, f"Received command user-set {atr} {ctx}:{member}") if member is None or not isinstance(member, discord.Member): @@ -352,9 +318,7 @@ class UserGroup(DiscordCommandABC): try: user.xp = value except TypeError as te: - self._logger.error( - __name__, f"String value couldn't be converted to int", te - ) + self._logger.error(__name__, f"String value couldn't be converted to int", te) await self._message_service.send_interaction_msg( ctx.interaction, self._t.transform("modules.base.user.set.error.type_error"), @@ -374,15 +338,11 @@ class UserGroup(DiscordCommandABC): await self._message_service.send_interaction_msg( ctx.interaction, - self._t.transform(f"modules.base.user.set.{atr.lower()}").format( - member.mention, value - ), + self._t.transform(f"modules.base.user.set.{atr.lower()}").format(member.mention, value), ) @set.autocomplete("atr") - async def set_autocomplete( - self, interaction: discord.Interaction, current: str - ) -> TList[app_commands.Choice[str]]: + async def set_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: atr_TList = [("xp", self._atr_dict["xp"])] return [app_commands.Choice(name=value, value=key) for key, value in atr_TList] @@ -390,18 +350,12 @@ class UserGroup(DiscordCommandABC): @commands.guild_only() @CommandChecks.check_is_ready() @CommandChecks.check_is_member_moderator() - async def add( - self, ctx: Context, atr: str, value: int, member: discord.Member = None - ): - self._logger.debug( - __name__, f"Received command user-add {atr}-={value} {ctx}:{member}" - ) + async def add(self, ctx: Context, atr: str, value: int, member: discord.Member = None): + self._logger.debug(__name__, f"Received command user-add {atr}-={value} {ctx}:{member}") await self._handle_atr_calc(ctx, atr, value, member) @add.autocomplete("atr") - async def set_autocomplete( - self, interaction: discord.Interaction, current: str - ) -> TList[app_commands.Choice[str]]: + async def set_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: atr_TList = [("xp", self._atr_dict["xp"])] return [app_commands.Choice(name=value, value=key) for key, value in atr_TList] @@ -409,18 +363,12 @@ class UserGroup(DiscordCommandABC): @commands.guild_only() @CommandChecks.check_is_ready() @CommandChecks.check_is_member_moderator() - async def remove( - self, ctx: Context, atr: str, value: int, member: discord.Member = None - ): - self._logger.debug( - __name__, f"Received command user-remove {atr}-={value} {ctx}:{member}" - ) + async def remove(self, ctx: Context, atr: str, value: int, member: discord.Member = None): + self._logger.debug(__name__, f"Received command user-remove {atr}-={value} {ctx}:{member}") await self._handle_atr_calc(ctx, atr, value, member, is_remove=True) @remove.autocomplete("atr") - async def set_autocomplete( - self, interaction: discord.Interaction, current: str - ) -> TList[app_commands.Choice[str]]: + async def set_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: atr_TList = [("xp", self._atr_dict["xp"])] return [app_commands.Choice(name=value, value=key) for key, value in atr_TList] @@ -429,9 +377,7 @@ class UserGroup(DiscordCommandABC): @CommandChecks.check_is_ready() @CommandChecks.check_is_member_moderator() async def reset(self, ctx: Context, atr: str, member: discord.Member = None): - self._logger.debug( - __name__, f"Received command user-reset {atr} {ctx}:{member}" - ) + self._logger.debug(__name__, f"Received command user-reset {atr} {ctx}:{member}") if member is None or not isinstance(member, discord.Member): member = ctx.author @@ -446,9 +392,7 @@ class UserGroup(DiscordCommandABC): await self._level.check_level(member) elif atr == "ontime": - self._user_joined_voice_channel.delete_user_joined_voice_channel_by_user_id( - user.id - ) + self._user_joined_voice_channel.delete_user_joined_voice_channel_by_user_id(user.id) self._db.save_changes() else: @@ -460,18 +404,14 @@ class UserGroup(DiscordCommandABC): await self._message_service.send_interaction_msg( ctx.interaction, - self._t.transform(f"modules.base.user.reset.{atr.lower()}").format( - atr, member.mention - ), + self._t.transform(f"modules.base.user.reset.{atr.lower()}").format(atr, member.mention), ) @reset.autocomplete("atr") async def reset_autocomplete( self, interaction: discord.Interaction, current: str ) -> TList[app_commands.Choice[str]]: - return [ - app_commands.Choice(name=value, value=key) for key, value in self._atr_TList - ] + return [app_commands.Choice(name=value, value=key) for key, value in self._atr_TList] @user.group() @commands.guild_only() @@ -483,9 +423,7 @@ class UserGroup(DiscordCommandABC): @CommandChecks.check_is_ready() @CommandChecks.check_is_member_moderator() async def show(self, ctx: Context, member: discord.Member, wait: int = None): - self._logger.debug( - __name__, f"Received command user warning show {ctx}:{member}" - ) + self._logger.debug(__name__, f"Received command user warning show {ctx}:{member}") server = self._servers.find_server_by_discord_id(ctx.guild.id) user = self._users.find_user_by_discord_id_and_server_id(member.id, server.id) @@ -515,9 +453,7 @@ class UserGroup(DiscordCommandABC): value=warnings_description_string, inline=True, ) - await self._message_service.send_interaction_msg( - ctx.interaction, embed, wait_before_delete=wait - ) + await self._message_service.send_interaction_msg(ctx.interaction, embed, wait_before_delete=wait) self._logger.trace(__name__, f"Finished user warning show command") @warning.command() @@ -525,21 +461,13 @@ class UserGroup(DiscordCommandABC): @CommandChecks.check_is_ready() @CommandChecks.check_is_member_moderator() async def add(self, ctx: Context, member: discord.Member, description: str): - self._logger.debug( - __name__, f"Received command user warning add {ctx}:{member},{description}" - ) + self._logger.debug(__name__, f"Received command user warning add {ctx}:{member},{description}") try: - await self._user_warnings_service.add_warnings_async( - member, description, ctx.author.id - ) - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.base.warnings.add.success") - ) + await self._user_warnings_service.add_warnings_async(member, description, ctx.author.id) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.warnings.add.success")) except Exception as e: self._logger.error(__name__, f"Adding user warning failed", e) - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.base.warnings.add.failed") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.warnings.add.failed")) self._logger.trace(__name__, f"Finished user warning add command") @warning.command() @@ -547,17 +475,11 @@ class UserGroup(DiscordCommandABC): @CommandChecks.check_is_ready() @CommandChecks.check_is_member_moderator() async def remove(self, ctx: Context, warning_id: int): - self._logger.debug( - __name__, f"Received command user warning remove {ctx}:{warning_id}" - ) + self._logger.debug(__name__, f"Received command user warning remove {ctx}:{warning_id}") try: await self._user_warnings_service.remove_warnings_async(warning_id) - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.base.warnings.remove.success") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.warnings.remove.success")) except Exception as e: self._logger.error(__name__, f"Removing user warning failed", e) - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.base.warnings.remove.failed") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.warnings.remove.failed")) self._logger.trace(__name__, f"Finished user warning remove command") diff --git a/bot/src/modules/base/events/base_on_command_error_event.py b/bot/src/modules/base/events/base_on_command_error_event.py index 5a4628f6..d5aab492 100644 --- a/bot/src/modules/base/events/base_on_command_error_event.py +++ b/bot/src/modules/base/events/base_on_command_error_event.py @@ -167,9 +167,7 @@ class BaseOnCommandErrorEvent(OnCommandErrorABC): ) elif isinstance(error, commands.NotOwner): - await self._messenger.send_ctx_msg( - ctx, self._t.transform("common.errors.not_owner"), without_tracking=True - ) + await self._messenger.send_ctx_msg(ctx, self._t.transform("common.errors.not_owner"), without_tracking=True) elif isinstance(error, commands.MissingPermissions): await self._messenger.send_ctx_msg( @@ -261,19 +259,13 @@ class BaseOnCommandErrorEvent(OnCommandErrorABC): self._t.transform("common.errors.command_error"), without_tracking=True, ) - message = self._t.transform( - "modules.base.technician_command_error_message" - ).format( + message = self._t.transform("modules.base.technician_command_error_message").format( ctx.command, ctx.author, error, - datetime.datetime.now().strftime( - self._time_format_settings.date_time_format - ), + datetime.datetime.now().strftime(self._time_format_settings.date_time_format), uid, ) for t in self._tech_settings.technician_ids: member = self._bot.get_user(t) - await self._messenger.send_dm_message( - message, member, without_tracking=True - ) + await self._messenger.send_dm_message(message, member, without_tracking=True) diff --git a/bot/src/modules/base/events/base_on_command_event.py b/bot/src/modules/base/events/base_on_command_event.py index 149426d5..407a875f 100644 --- a/bot/src/modules/base/events/base_on_command_event.py +++ b/bot/src/modules/base/events/base_on_command_event.py @@ -49,9 +49,7 @@ class BaseOnCommandEvent(OnCommandABC): self._clients.append_received_command_count(self._bot.user.id, g_id, 1) self._db.save_changes() except Exception as e: - self._logger.error( - __name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e - ) + self._logger.error(__name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e) def _handle_message_for_xp(self, message: discord.Message): dc_user_id = message.author.id @@ -63,9 +61,7 @@ class BaseOnCommandEvent(OnCommandABC): user: Optional[User] = None try: - user = self._users.get_user_by_discord_id_and_server_id( - dc_user_id, server.id - ) + user = self._users.get_user_by_discord_id_and_server_id(dc_user_id, server.id) except Exception as e: self._logger.error(__name__, f"Cannot get user {dc_user_id}", e) return @@ -74,23 +70,17 @@ class BaseOnCommandEvent(OnCommandABC): self._logger.error(__name__, f"User not found {dc_user_id}") return - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{message.guild.id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{message.guild.id}") old_xp = user.xp user.xp += settings.xp_per_message self._users.update_user(user) self._db.save_changes() - self._logger.debug( - __name__, f"User {user} sent message. xp: from {old_xp} to {user.xp}" - ) + self._logger.debug(__name__, f"User {user} sent message. xp: from {old_xp} to {user.xp}") async def on_command(self, ctx: Context): self._logger.debug(__name__, f"Module {type(self)} started") - self._logger.info( - __name__, f"Received command: {ctx.command} from {ctx.channel}" - ) + self._logger.info(__name__, f"Received command: {ctx.command} from {ctx.channel}") if ctx is None or ctx.guild is None: return self._append_received_command_count(ctx.guild.id) diff --git a/bot/src/modules/base/events/base_on_member_join_event.py b/bot/src/modules/base/events/base_on_member_join_event.py index 99939a27..a09772d6 100644 --- a/bot/src/modules/base/events/base_on_member_join_event.py +++ b/bot/src/modules/base/events/base_on_member_join_event.py @@ -66,9 +66,7 @@ class BaseOnMemberJoinEvent(OnMemberJoinABC): except Exception as e: self._logger.error(__name__, f"Cannot get user {member.id}", e) - async def _add_if_not_exists_user_async( - self, member: Union[discord.User, discord.Member] - ): + async def _add_if_not_exists_user_async(self, member: Union[discord.User, discord.Member]): self._logger.debug(__name__, f"Check if user exists {member}") await self._messenger.send_dm_message( self._t.transform("modules.base.welcome_message").format(member.guild.name), @@ -77,40 +75,28 @@ class BaseOnMemberJoinEvent(OnMemberJoinABC): try: server = self._servers.get_server_by_discord_id(member.guild.id) - 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) if user is not None: - self._user_joins.add_user_joined_server( - UserJoinedServer(user, datetime.now()) - ) + self._user_joins.add_user_joined_server(UserJoinedServer(user, datetime.now())) self._db.save_changes() return self._logger.debug(__name__, f"Add user: {member.id}") self._users.add_user(User(member.id, 0, 0, 0, server)) self._db.save_changes() - user = self._users.get_user_by_discord_id_and_server_id( - member.id, server.id - ) - self._user_joins.add_user_joined_server( - UserJoinedServer(user, datetime.now()) - ) + user = self._users.get_user_by_discord_id_and_server_id(member.id, server.id) + self._user_joins.add_user_joined_server(UserJoinedServer(user, datetime.now())) self._db.save_changes() except Exception as e: self._logger.error(__name__, f"Cannot get user {member.id}", e) async def _notify_team(self, member: discord.Member): self._logger.debug(__name__, f"Notify team that a member left") - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{member.guild.id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{member.guild.id}") channel = member.guild.get_channel(settings.team_channel_id) await self._messenger.send_channel_message( channel, - self._t.transform("modules.base.welcome_message_for_team").format( - member.mention - ), + self._t.transform("modules.base.welcome_message_for_team").format(member.mention), is_persistent=True, ) self._logger.trace(__name__, f"Notified team that a member left") diff --git a/bot/src/modules/base/events/base_on_member_remove_event.py b/bot/src/modules/base/events/base_on_member_remove_event.py index ed6a02df..adfe7e87 100644 --- a/bot/src/modules/base/events/base_on_member_remove_event.py +++ b/bot/src/modules/base/events/base_on_member_remove_event.py @@ -41,16 +41,12 @@ class BaseOnMemberRemoveEvent(OnMemberRemoveABC): async def _remove_user(self, member: Union[discord.User, discord.Member]): self._logger.debug(__name__, f"Remove user {member}") - await self._message_service.send_dm_message( - self._t.transform("modules.base.goodbye_message"), member - ) + await self._message_service.send_dm_message(self._t.transform("modules.base.goodbye_message"), member) try: server = self._servers.get_server_by_discord_id(member.guild.id) - 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) if user is None: self._logger.error(__name__, f"Cannot find user {member}") return @@ -64,15 +60,11 @@ class BaseOnMemberRemoveEvent(OnMemberRemoveABC): async def _notify_team(self, member: discord.Member): self._logger.debug(__name__, f"Notify team that a member left") - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{member.guild.id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{member.guild.id}") channel = member.guild.get_channel(settings.team_channel_id) await self._message_service.send_channel_message( channel, - self._t.transform("modules.base.member_left_message").format( - member.mention - ), + self._t.transform("modules.base.member_left_message").format(member.mention), is_persistent=True, ) self._logger.trace(__name__, f"Notified team that a member left") diff --git a/bot/src/modules/base/events/base_on_message_delete_event.py b/bot/src/modules/base/events/base_on_message_delete_event.py index c3bcd022..3d3aad1c 100644 --- a/bot/src/modules/base/events/base_on_message_delete_event.py +++ b/bot/src/modules/base/events/base_on_message_delete_event.py @@ -40,9 +40,7 @@ class BaseOnMessageDeleteEvent(OnMessageDeleteABC): self._clients.append_deleted_message_count(self._bot.user.id, g_id, 1) self._db.save_changes() except Exception as e: - self._logger.error( - __name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e - ) + self._logger.error(__name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e) def _handle_message_delete(self, message: discord.Message): dc_user_id = message.author.id @@ -54,9 +52,7 @@ class BaseOnMessageDeleteEvent(OnMessageDeleteABC): user: Optional[User] = None try: - user = self._users.find_user_by_discord_id_and_server_id( - dc_user_id, server.id - ) + user = self._users.find_user_by_discord_id_and_server_id(dc_user_id, server.id) except Exception as e: self._logger.error(__name__, f"Cannot get user {dc_user_id}", e) return @@ -65,9 +61,7 @@ class BaseOnMessageDeleteEvent(OnMessageDeleteABC): self._logger.error(__name__, f"User not found {dc_user_id}") return - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{message.guild.id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{message.guild.id}") old_xp = user.xp user.xp -= settings.xp_per_message self._users.update_user(user) @@ -83,9 +77,7 @@ class BaseOnMessageDeleteEvent(OnMessageDeleteABC): if message is None or message.guild is None: return - self._logger.info( - __name__, f"Received message: {LogMessageHelper.get_log_string(message)}" - ) + self._logger.info(__name__, f"Received message: {LogMessageHelper.get_log_string(message)}") self._append_deleted_message_count(message.guild.id) if not message.author.bot: diff --git a/bot/src/modules/base/events/base_on_message_event.py b/bot/src/modules/base/events/base_on_message_event.py index 438b10b8..e6531385 100644 --- a/bot/src/modules/base/events/base_on_message_event.py +++ b/bot/src/modules/base/events/base_on_message_event.py @@ -45,9 +45,7 @@ class BaseOnMessageEvent(OnMessageABC): self._clients.append_received_message_count(self._bot.user.id, g_id, 1) self._db.save_changes() except Exception as e: - self._logger.error( - __name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e - ) + self._logger.error(__name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e) def _handle_message_for_xp(self, message: discord.Message): dc_user_id = message.author.id @@ -59,9 +57,7 @@ class BaseOnMessageEvent(OnMessageABC): user: Optional[User] = None try: - user = self._users.find_user_by_discord_id_and_server_id( - dc_user_id, server.id - ) + user = self._users.find_user_by_discord_id_and_server_id(dc_user_id, server.id) except Exception as e: self._logger.error(__name__, f"Cannot get user {dc_user_id}", e) return @@ -70,9 +66,7 @@ class BaseOnMessageEvent(OnMessageABC): self._logger.error(__name__, f"User not found {dc_user_id}") return - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{server.discord_id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{server.discord_id}") if self._client_utils.is_message_xp_count_by_hour_higher_that_max_message_count_per_hour( message.created_at, user, settings ): @@ -83,9 +77,7 @@ class BaseOnMessageEvent(OnMessageABC): self._users.update_user(user) self._db.save_changes() - self._logger.debug( - __name__, f"User {user} sent message. xp: from {old_xp} to {user.xp}" - ) + self._logger.debug(__name__, f"User {user} sent message. xp: from {old_xp} to {user.xp}") @EventChecks.check_is_ready() async def on_message(self, message: discord.Message): @@ -93,9 +85,7 @@ class BaseOnMessageEvent(OnMessageABC): if message is None or message.guild is None: return - self._logger.info( - __name__, f"Received message: {LogMessageHelper.get_log_string(message)}" - ) + self._logger.info(__name__, f"Received message: {LogMessageHelper.get_log_string(message)}") self._append_received_message_count(message.guild.id) if not message.author.bot: diff --git a/bot/src/modules/base/events/base_on_scheduled_event_update_event.py b/bot/src/modules/base/events/base_on_scheduled_event_update_event.py index f3dfda00..640a9a80 100644 --- a/bot/src/modules/base/events/base_on_scheduled_event_update_event.py +++ b/bot/src/modules/base/events/base_on_scheduled_event_update_event.py @@ -21,9 +21,7 @@ class BaseOnScheduledEventUpdateEvent(OnScheduledEventUpdateABC): self._bot = bot self._events = events - async def on_scheduled_event_update( - self, before: discord.ScheduledEvent, after: discord.ScheduledEvent - ): + async def on_scheduled_event_update(self, before: discord.ScheduledEvent, after: discord.ScheduledEvent): self._logger.debug(__name__, f"Module {type(self)} started") # save started event @@ -35,8 +33,7 @@ class BaseOnScheduledEventUpdateEvent(OnScheduledEventUpdateABC): self._events.give_xp_for_event_participation(member, active_event) # delete stopped event if before.status != after.status and ( - after.status.value == EventStatus.cancelled.value - or after.status.value == EventStatus.completed.value + after.status.value == EventStatus.cancelled.value or after.status.value == EventStatus.completed.value ): event = self._events.get_active_event(after) if event is None: diff --git a/bot/src/modules/base/events/base_on_voice_state_update_event.py b/bot/src/modules/base/events/base_on_voice_state_update_event.py index 5a5e25ab..6fb0c113 100644 --- a/bot/src/modules/base/events/base_on_voice_state_update_event.py +++ b/bot/src/modules/base/events/base_on_voice_state_update_event.py @@ -45,14 +45,10 @@ class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC): self._logger.info(__name__, f"Module {type(self)} loaded") - def _update_voice_state( - self, joined: bool, dc_user_id: int, channel_id: int, server: Server - ): + def _update_voice_state(self, joined: bool, dc_user_id: int, channel_id: int, server: Server): user: Optional[User] = None try: - user = self._users.get_user_by_discord_id_and_server_id( - dc_user_id, server.id - ) + user = self._users.get_user_by_discord_id_and_server_id(dc_user_id, server.id) except Exception as e: self._logger.error(__name__, f"Cannot get user {dc_user_id}", e) return @@ -68,13 +64,9 @@ class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC): self._db.save_changes() return - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{server.discord_id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{server.discord_id}") - join = self._user_joins_vc.get_active_user_joined_voice_channel_by_user_id( - user.id - ) + join = self._user_joins_vc.get_active_user_joined_voice_channel_by_user_id(user.id) join.leaved_on = datetime.now() old_xp = user.xp @@ -103,9 +95,7 @@ class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC): __name__, f"Detected on_voice_state_update {member.id} from {before} to {after}", ) - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{member.guild.id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{member.guild.id}") server = self._servers.get_server_by_discord_id(member.guild.id) try: @@ -133,36 +123,18 @@ class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC): # channel to channel elif before.channel is not None and after.channel is not None: # joined - if ( - before.channel.id in settings.afk_channel_ids - and after.channel.id not in settings.afk_channel_ids - ): - self._logger.trace( - __name__, f"User {member.id} joined {after.channel}" - ) + if before.channel.id in settings.afk_channel_ids and after.channel.id not in settings.afk_channel_ids: + self._logger.trace(__name__, f"User {member.id} joined {after.channel}") self._update_voice_state(True, member.id, after.channel.id, server) # left - elif ( - after.channel.id in settings.afk_channel_ids - and before.channel.id not in settings.afk_channel_ids - ): - self._logger.trace( - __name__, f"User {member.id} left {before.channel}" - ) - self._update_voice_state( - False, member.id, before.channel.id, server - ) + elif after.channel.id in settings.afk_channel_ids and before.channel.id not in settings.afk_channel_ids: + self._logger.trace(__name__, f"User {member.id} left {before.channel}") + self._update_voice_state(False, member.id, before.channel.id, server) else: - self._logger.trace( - __name__, f"User {member.id} switched to {after.channel}" - ) - self._update_voice_state( - False, member.id, before.channel.id, server - ) + self._logger.trace(__name__, f"User {member.id} switched to {after.channel}") + self._update_voice_state(False, member.id, before.channel.id, server) self._update_voice_state(True, member.id, after.channel.id, server) except Exception as e: - self._logger.error( - __name__, f"Cannot handle voice state for user {member.id}", e - ) + self._logger.error(__name__, f"Cannot handle voice state for user {member.id}", e) diff --git a/bot/src/modules/base/events/base_on_voice_state_update_event_help_channel.py b/bot/src/modules/base/events/base_on_voice_state_update_event_help_channel.py index d1d24e07..3e1b3da0 100644 --- a/bot/src/modules/base/events/base_on_voice_state_update_event_help_channel.py +++ b/bot/src/modules/base/events/base_on_voice_state_update_event_help_channel.py @@ -33,15 +33,11 @@ class BaseOnVoiceStateUpdateEventHelpChannel(OnVoiceStateUpdateABC): async def _notify_team(self, member: discord.Member): self._logger.debug(__name__, f"Notify team that a member needs help") - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{member.guild.id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{member.guild.id}") channel = member.guild.get_channel(settings.team_channel_id) await self._message_service.send_channel_message( channel, - self._t.transform("modules.base.member_joined_help_voice_channel").format( - member.mention - ), + self._t.transform("modules.base.member_joined_help_voice_channel").format(member.mention), is_persistent=True, ) self._logger.trace(__name__, f"Notified team that a member need help") @@ -55,9 +51,7 @@ class BaseOnVoiceStateUpdateEventHelpChannel(OnVoiceStateUpdateABC): ): self._logger.debug(__name__, f"Module {type(self)} started") server = self._servers.get_server_by_discord_id(member.guild.id) - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{server.discord_id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{server.discord_id}") if after.channel is None or after.channel.id != settings.help_voice_channel_id: return diff --git a/bot/src/modules/base/forms/bug_report_form.py b/bot/src/modules/base/forms/bug_report_form.py index 88fc6cab..185fd51f 100644 --- a/bot/src/modules/base/forms/bug_report_form.py +++ b/bot/src/modules/base/forms/bug_report_form.py @@ -10,9 +10,7 @@ from bot_data.model.technician_config import TechnicianConfig class BugReportForm(ui.Modal): - description = ui.TextInput( - label="Report a bug", required=True, style=TextStyle.long - ) + description = ui.TextInput(label="Report a bug", required=True, style=TextStyle.long) def __init__( self, @@ -40,14 +38,10 @@ class BugReportForm(ui.Modal): for t in self._technician_config.technician_ids: member = self._bot.get_user(t) await self._message_service.send_dm_message( - self._t.transform("modules.base.bug.message").format( - interaction.user.mention, self.description.value - ), + self._t.transform("modules.base.bug.message").format(interaction.user.mention, self.description.value), member, without_tracking=True, ) - await self._message_service.send_interaction_msg( - interaction, self._t.transform("modules.base.bug.response") - ) + await self._message_service.send_interaction_msg(interaction, self._t.transform("modules.base.bug.response")) self._logger.trace(__name__, f"Finished bug report form") diff --git a/bot/src/modules/base/forms/complaint_form.py b/bot/src/modules/base/forms/complaint_form.py index cb39e23c..b0d77813 100644 --- a/bot/src/modules/base/forms/complaint_form.py +++ b/bot/src/modules/base/forms/complaint_form.py @@ -10,9 +10,7 @@ from bot_data.model.server_config import ServerConfig class ComplaintForm(ui.Modal): - description = ui.TextInput( - label="Complain about something", required=True, style=TextStyle.long - ) + description = ui.TextInput(label="Complain about something", required=True, style=TextStyle.long) def __init__( self, @@ -34,9 +32,7 @@ class ComplaintForm(ui.Modal): async def on_submit(self, interaction: discord.Interaction): self._logger.debug(__name__, f"Started complaint command form") - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{interaction.guild.id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{interaction.guild.id}") channel = interaction.guild.get_channel(settings.team_channel_id) await self._message_service.send_channel_message( channel, diff --git a/bot/src/modules/base/helper/base_reaction_handler.py b/bot/src/modules/base/helper/base_reaction_handler.py index e63f4412..d2cb1581 100644 --- a/bot/src/modules/base/helper/base_reaction_handler.py +++ b/bot/src/modules/base/helper/base_reaction_handler.py @@ -38,9 +38,7 @@ class BaseReactionHandler: guild = self._bot.get_guild(payload.guild_id) member = guild.get_member(payload.user_id) if member is None: - self._logger.warn( - __name__, f"User {payload.user_id} in {guild.name} not found - skipping" - ) + self._logger.warn(__name__, f"User {payload.user_id} in {guild.name} not found - skipping") return try: @@ -62,12 +60,8 @@ class BaseReactionHandler: self._logger.debug(__name__, f"Skipping reaction handling") return except Exception as e: - self._logger.error( - __name__, f"Getting message for reaction logging failed", e - ) - self._logger.info( - __name__, f"{log_msg} to message {payload.message_id}" - ) + self._logger.error(__name__, f"Getting message for reaction logging failed", e) + self._logger.info(__name__, f"{log_msg} to message {payload.message_id}") except Exception as e: self._logger.error(__name__, f"Reaction logging failed", e) @@ -76,9 +70,7 @@ class BaseReactionHandler: server = self._servers.get_server_by_discord_id(guild.id) user = self._users.get_user_by_discord_id_and_server_id(member.id, server.id) - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{guild.id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild.id}") if r_type == "add": if self._client_utils.is_message_xp_count_by_hour_higher_that_max_message_count_per_hour( diff --git a/bot/src/modules/base/helper/voice_channel_transformer.py b/bot/src/modules/base/helper/voice_channel_transformer.py index f7fa205f..a6056e58 100644 --- a/bot/src/modules/base/helper/voice_channel_transformer.py +++ b/bot/src/modules/base/helper/voice_channel_transformer.py @@ -8,9 +8,7 @@ from bot_core.abc.client_utils_abc import ClientUtilsABC class VoiceChannelTransformer(Transformer): - async def transform( - self, interaction: Interaction, value: str, / - ) -> discord.VoiceChannel: + async def transform(self, interaction: Interaction, value: str, /) -> discord.VoiceChannel: voice_channel = ( List(discord.VoiceChannel, interaction.guild.voice_channels) .where(lambda x: str(x.id) == value) @@ -18,24 +16,16 @@ class VoiceChannelTransformer(Transformer): ) return voice_channel - async def autocomplete( - self, interaction: Interaction, current: str, / - ) -> list[Choice[str]]: + async def autocomplete(self, interaction: Interaction, current: str, /) -> list[Choice[str]]: @ServiceProviderABC.inject def get_client_utils(client_utils: ClientUtilsABC) -> ClientUtilsABC: return client_utils - voice_channels = List(discord.Role, interaction.guild.voice_channels).where( - lambda x: len(x.members) > 0 - ) + voice_channels = List(discord.Role, interaction.guild.voice_channels).where(lambda x: len(x.members) > 0) return [ app_commands.Choice( - name=f"{vc.name}" - if vc.category is None - else f"{vc.name}: {vc.category.name}", + name=f"{vc.name}" if vc.category is None else f"{vc.name}: {vc.category.name}", value=vc.name, ) - for vc in get_client_utils().get_auto_complete_list( - voice_channels, current, lambda x: x.name - ) + for vc in get_client_utils().get_auto_complete_list(voice_channels, current, lambda x: x.name) ] diff --git a/bot/src/modules/base/service/event_service.py b/bot/src/modules/base/service/event_service.py index 51cf211c..30b19d96 100644 --- a/bot/src/modules/base/service/event_service.py +++ b/bot/src/modules/base/service/event_service.py @@ -36,9 +36,7 @@ class EventService: self._active_events.add(event) def get_active_event(self, event: discord.ScheduledEvent) -> Optional[ActiveEvent]: - return self._active_events.where( - lambda x: x.event.id == event.id - ).single_or_default() + return self._active_events.where(lambda x: x.event.id == event.id).single_or_default() def get_active_event_by_channel_id(self, channel_id: int) -> Optional[ActiveEvent]: return self._active_events.where( @@ -51,18 +49,14 @@ class EventService: self._active_events.remove(event) - def give_xp_for_event_participation( - self, member: discord.Member, active_event: ActiveEvent - ): + def give_xp_for_event_participation(self, member: discord.Member, active_event: ActiveEvent): server = self._servers.get_server_by_discord_id(member.guild.id) user = self._users.get_user_by_discord_id_and_server_id(member.id, server.id) if active_event.participants.any(lambda x: x.id == user.id): self._logger.debug(__name__, f"Module {type(self)} stopped") return - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{server.discord_id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{server.discord_id}") user.xp += settings.xp_per_event_participation self._users.update_user(user) self._db.save_changes() diff --git a/bot/src/modules/base/service/user_warnings_service.py b/bot/src/modules/base/service/user_warnings_service.py index 54c394c7..eea9129a 100644 --- a/bot/src/modules/base/service/user_warnings_service.py +++ b/bot/src/modules/base/service/user_warnings_service.py @@ -46,92 +46,60 @@ class UserWarningsService: self._t = t self._permissions = permissions - async def notify_team( - self, member: discord.Member, description: str, removed=False - ): + async def notify_team(self, member: discord.Member, description: str, removed=False): try: - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{member.guild.id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{member.guild.id}") channel = member.guild.get_channel(settings.team_channel_id) if removed: - translation = self._t.transform( - "modules.base.warnings.team_removed" - ).format(description, member.mention) + translation = self._t.transform("modules.base.warnings.team_removed").format( + description, member.mention + ) else: - translation = self._t.transform( - "modules.base.warnings.team_warned" - ).format(member.mention, description) + translation = self._t.transform("modules.base.warnings.team_warned").format(member.mention, description) self._bot.loop.create_task( - self._message_service.send_channel_message( - channel, translation, is_persistent=True - ) + self._message_service.send_channel_message(channel, translation, is_persistent=True) ) except Exception as e: - self._logger.error( - __name__, f"Team notification for user warning failed!", e - ) + self._logger.error(__name__, f"Team notification for user warning failed!", e) async def notify_user(self, member: discord.Member, message: str): try: # run as task to keep the interaction alive - self._bot.loop.create_task( - self._message_service.send_dm_message(message, member) - ) + self._bot.loop.create_task(self._message_service.send_dm_message(message, member)) except Exception as e: - self._logger.error( - __name__, f"User notification for user warning failed!", e - ) + self._logger.error(__name__, f"User notification for user warning failed!", e) async def check_for_warnings(self, member: discord.Member, user: User): existing_warnings = self._warnings.get_user_warnings_by_user_id(user.id) if existing_warnings.count() == 1: - await self.notify_user( - member, self._t.transform("modules.base.warnings.first") - ) + await self.notify_user(member, self._t.transform("modules.base.warnings.first")) elif existing_warnings.count() == 2: server = self._servers.get_server_by_discord_id(member.guild.id) - user = self._users.get_user_by_discord_id_and_server_id( - member.id, server.id - ) + user = self._users.get_user_by_discord_id_and_server_id(member.id, server.id) level = self._level_service.get_level(user) - levels = self._levels.get_levels_by_server_id(server.id).order_by( - lambda l: l.min_xp - ) + levels = self._levels.get_levels_by_server_id(server.id).order_by(lambda l: l.min_xp) - new_level = levels.where( - lambda l: l.min_xp < level.min_xp - ).last_or_default() + new_level = levels.where(lambda l: l.min_xp < level.min_xp).last_or_default() if new_level is not None: user.xp = new_level.min_xp self._users.update_user(user) self._db.save_changes() - await self.notify_user( - member, self._t.transform("modules.base.warnings.second") - ) + await self.notify_user(member, self._t.transform("modules.base.warnings.second")) elif existing_warnings.count() == 3: server = self._servers.get_server_by_discord_id(member.guild.id) - user = self._users.get_user_by_discord_id_and_server_id( - member.id, server.id - ) + user = self._users.get_user_by_discord_id_and_server_id(member.id, server.id) levels = self._levels.get_levels_by_server_id(server.id) - new_level = ( - levels.where(lambda l: l.min_xp > 0) - .order_by(lambda l: l.min_xp) - .last_or_default() - ) + new_level = levels.where(lambda l: l.min_xp > 0).order_by(lambda l: l.min_xp).last_or_default() if new_level is not None: user.xp = new_level.min_xp self._users.update_user(user) self._db.save_changes() - await self.notify_user( - member, self._t.transform("modules.base.warnings.third") - ) + await self.notify_user(member, self._t.transform("modules.base.warnings.third")) elif existing_warnings.count() >= 4: user.xp = 0 @@ -149,39 +117,29 @@ class UserWarningsService: await self.notify_user( member, - self._t.transform("modules.base.warnings.warned").format( - warning.description - ), + self._t.transform("modules.base.warnings.warned").format(warning.description), ) await self.notify_team(member, warning.description) await self.check_for_warnings(member, user) - def _add_warnings( - self, member: discord.Member, description: str, author_id: int = None - ): + def _add_warnings(self, member: discord.Member, description: str, author_id: int = None): server = self._servers.get_server_by_discord_id(member.guild.id) user = self._users.get_user_by_discord_id_and_server_id(member.id, server.id) author = None if author_id is not None: - author = self._users.get_user_by_discord_id_and_server_id( - author_id, server.id - ) + author = self._users.get_user_by_discord_id_and_server_id(author_id, server.id) warning = UserWarnings(description, user, author) self._warnings.add_user_warnings(warning) self._db.save_changes() return warning - def add_warnings( - self, member: discord.Member, description: str, author_id: int = None - ): + def add_warnings(self, member: discord.Member, description: str, author_id: int = None): warning = self._add_warnings(member, description, author_id) self._bot.loop.create_task(self._notify_after_add(member, warning)) - async def add_warnings_async( - self, member: discord.Member, description: str, author_id: int = None - ): + async def add_warnings_async(self, member: discord.Member, description: str, author_id: int = None): warning = self._add_warnings(member, description, author_id) await self._notify_after_add(member, warning) @@ -190,9 +148,7 @@ class UserWarningsService: member = guild.get_member(warning.user.discord_id) await self.notify_user( member, - self._t.transform("modules.base.warnings.removed").format( - warning.description - ), + self._t.transform("modules.base.warnings.removed").format(warning.description), ) await self.notify_team(member, warning.description, removed=True) diff --git a/bot/src/modules/boot_log/boot_log_extension.py b/bot/src/modules/boot_log/boot_log_extension.py index e0f59082..62b7c6c7 100644 --- a/bot/src/modules/boot_log/boot_log_extension.py +++ b/bot/src/modules/boot_log/boot_log_extension.py @@ -14,9 +14,7 @@ class BootLogExtension(ApplicationExtensionABC): pass async def run(self, config: ConfigurationABC, services: ServiceProviderABC): - feature_flags: FeatureFlagsSettings = config.get_configuration( - FeatureFlagsSettings - ) + feature_flags: FeatureFlagsSettings = config.get_configuration(FeatureFlagsSettings) if not feature_flags.get_flag(FeatureFlagsEnum.boot_log_module): return logger: LoggerABC = services.get_service(LoggerABC) diff --git a/bot/src/modules/boot_log/boot_log_module.py b/bot/src/modules/boot_log/boot_log_module.py index 0701876f..dde842f0 100644 --- a/bot/src/modules/boot_log/boot_log_module.py +++ b/bot/src/modules/boot_log/boot_log_module.py @@ -13,16 +13,10 @@ class BootLogModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.boot_log_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): pass - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): # commands # events - services.add_transient( - DiscordEventTypesEnum.on_ready.value, BootLogOnReadyEvent - ) + services.add_transient(DiscordEventTypesEnum.on_ready.value, BootLogOnReadyEvent) diff --git a/bot/src/modules/boot_log/boot_log_on_ready_event.py b/bot/src/modules/boot_log/boot_log_on_ready_event.py index f0962bae..4c8aeec7 100644 --- a/bot/src/modules/boot_log/boot_log_on_ready_event.py +++ b/bot/src/modules/boot_log/boot_log_on_ready_event.py @@ -45,10 +45,7 @@ class BootLogOnReadyEvent(OnReadyABC): try: start_time = self._config.get_configuration("Bot_StartTime") init_time = round( - ( - datetime.now() - - datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S.%f") - ).total_seconds(), + (datetime.now() - datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S.%f")).total_seconds(), 2, ) self._config.add_configuration("InitTime", str(init_time)) @@ -59,9 +56,7 @@ class BootLogOnReadyEvent(OnReadyABC): # print error if initialisation took way too long elif init_time >= 90: - self._logger.error( - __name__, "It takes far too long to start the bot!!!" - ) + self._logger.error(__name__, "It takes far too long to start the bot!!!") except Exception as e: self._logger.error(__name__, "Init time calculation failed", e) return @@ -70,9 +65,7 @@ class BootLogOnReadyEvent(OnReadyABC): g: guild = g self._logger.debug(__name__, f"Server detected: {g.id}") - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{g.id}" - ) + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{g.id}") if server_config is None: self._logger.error(__name__, f"Config ServerConfig_{g.id} not found!") return @@ -85,9 +78,7 @@ class BootLogOnReadyEvent(OnReadyABC): self._bot.loop.create_task( self._message_service.send_channel_message( self._bot.get_channel(server_config.login_message_channel_id), - self._t.transform("modules.boot_log.login_message").format( - init_time - ), + self._t.transform("modules.boot_log.login_message").format(init_time), ) ) diff --git a/bot/src/modules/config/config_extension.py b/bot/src/modules/config/config_extension.py index f11ba6ad..ce164180 100644 --- a/bot/src/modules/config/config_extension.py +++ b/bot/src/modules/config/config_extension.py @@ -13,9 +13,7 @@ class ConfigExtension(ApplicationExtensionABC): pass async def run(self, config: ConfigurationABC, services: ServiceProviderABC): - feature_flags: FeatureFlagsSettings = config.get_configuration( - FeatureFlagsSettings - ) + feature_flags: FeatureFlagsSettings = config.get_configuration(FeatureFlagsSettings) if not feature_flags.get_flag(FeatureFlagsEnum.config_module): return logger: LoggerABC = services.get_service(LoggerABC) diff --git a/bot/src/modules/config/config_module.py b/bot/src/modules/config/config_module.py index a8180637..14c16263 100644 --- a/bot/src/modules/config/config_module.py +++ b/bot/src/modules/config/config_module.py @@ -13,12 +13,8 @@ class ConfigModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.config_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): pass - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): services.add_transient(DiscordEventTypesEnum.on_ready.value, ConfigOnReadyEvent) diff --git a/bot/src/modules/config/events/config_on_ready_event.py b/bot/src/modules/config/events/config_on_ready_event.py index ddec8ccf..14ad229a 100644 --- a/bot/src/modules/config/events/config_on_ready_event.py +++ b/bot/src/modules/config/events/config_on_ready_event.py @@ -26,6 +26,4 @@ class ConfigOnReadyEvent(OnReadyABC): async def on_ready(self): for guild in self._bot.guilds: - await self._config_service.reload_server_config( - self._servers.get_server_by_discord_id(guild.id) - ) + await self._config_service.reload_server_config(self._servers.get_server_by_discord_id(guild.id)) diff --git a/bot/src/modules/database/database_extension.py b/bot/src/modules/database/database_extension.py index de874826..1c26e70b 100644 --- a/bot/src/modules/database/database_extension.py +++ b/bot/src/modules/database/database_extension.py @@ -17,9 +17,7 @@ class DatabaseExtension(ApplicationExtensionABC): pass async def run(self, config: ConfigurationABC, services: ServiceProviderABC): - feature_flags: FeatureFlagsSettings = config.get_configuration( - FeatureFlagsSettings - ) + feature_flags: FeatureFlagsSettings = config.get_configuration(FeatureFlagsSettings) if not feature_flags.get_flag(FeatureFlagsEnum.data_module): return logger: LoggerABC = services.get_service(DatabaseLogger) diff --git a/bot/src/modules/database/database_module.py b/bot/src/modules/database/database_module.py index 65b98988..bd7c6c6f 100644 --- a/bot/src/modules/database/database_module.py +++ b/bot/src/modules/database/database_module.py @@ -13,16 +13,10 @@ class DatabaseModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.database_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): pass - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): # commands # events - services.add_transient( - DiscordEventTypesEnum.on_ready.value, DatabaseOnReadyEvent - ) + services.add_transient(DiscordEventTypesEnum.on_ready.value, DatabaseOnReadyEvent) diff --git a/bot/src/modules/database/database_on_ready_event.py b/bot/src/modules/database/database_on_ready_event.py index 9b76de38..5c3bd775 100644 --- a/bot/src/modules/database/database_on_ready_event.py +++ b/bot/src/modules/database/database_on_ready_event.py @@ -29,25 +29,18 @@ class DatabaseOnReadyEvent(OnReadyABC): try: start_time = self._config.get_configuration("Database_StartTime") init_time = round( - ( - datetime.now() - - datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S.%f") - ).total_seconds(), + (datetime.now() - datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S.%f")).total_seconds(), 2, ) self._config.add_configuration("Database_InitTime", str(init_time)) self._logger.debug(__name__, f"Database Init time: {init_time}s") # print warning if initialisation took too long if init_time >= 30: - self._logger.warn( - __name__, "It takes too long to prepare the database!" - ) + self._logger.warn(__name__, "It takes too long to prepare the database!") # print error if initialisation took way too long elif init_time >= 90: - self._logger.error( - __name__, "It takes far too long to prepare the database!!!" - ) + self._logger.error(__name__, "It takes far too long to prepare the database!!!") except Exception as e: # self._logger.error(__name__, "Database init time calculation failed", e) return diff --git a/bot/src/modules/level/command/level_group.py b/bot/src/modules/level/command/level_group.py index e5dca679..50e03692 100644 --- a/bot/src/modules/level/command/level_group.py +++ b/bot/src/modules/level/command/level_group.py @@ -108,17 +108,13 @@ class LevelGroup(DiscordCommandABC): except Exception as e: self._logger.error(__name__, f"Level seeding failed", e) - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.level.seeding_failed") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.level.seeding_failed")) async def _level_auto_complete( self, interaction: discord.Interaction, current: str ) -> TList[app_commands.Choice[str]]: server = self._servers.get_server_by_discord_id(interaction.guild.id) - levels = self._levels.get_levels_by_server_id(server.id).select( - lambda l: l.name - ) + levels = self._levels.get_levels_by_server_id(server.id).select(lambda l: l.name) return [ app_commands.Choice(name=level, value=level) for level in self._client_utils.get_auto_complete_list(levels, current) @@ -138,20 +134,14 @@ class LevelGroup(DiscordCommandABC): if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.level_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.level_module): return server = self._servers.get_server_by_discord_id(ctx.guild.id) levels = self._levels.get_levels_by_server_id(server.id) if levels.count() < 1: - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.level.error.nothing_found") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.level.error.nothing_found")) self._logger.trace(__name__, f"Finished command level list") return @@ -173,9 +163,7 @@ class LevelGroup(DiscordCommandABC): value=level_name, inline=True, ) - embed.add_field( - name=self._t.transform("modules.level.list.min_xp"), value=xp, inline=True - ) + embed.add_field(name=self._t.transform("modules.level.list.min_xp"), value=xp, inline=True) embed.add_field( name=self._t.transform("modules.level.list.permission_int"), value=permissions, @@ -188,19 +176,13 @@ class LevelGroup(DiscordCommandABC): @commands.guild_only() @CommandChecks.check_is_ready() @CommandChecks.check_is_member_admin() - async def create( - self, ctx: Context, name: str, color: str, min_xp: int, permissions: int - ): + async def create(self, ctx: Context, name: str, color: str, min_xp: int, permissions: int): self._logger.debug(__name__, f"Received command level create {ctx}") if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.level_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.level_module): return try: @@ -226,26 +208,19 @@ class LevelGroup(DiscordCommandABC): self._logger.debug(__name__, f"Level with name {level.name} already exists") await self._message_service.send_ctx_msg( ctx, - self._t.transform( - "modules.level.error.level_with_name_already_exists" - ).format(level.name), + self._t.transform("modules.level.error.level_with_name_already_exists").format(level.name), ) - elif ( - levels.where(lambda l: l.min_xp == level.min_xp).first_or_default() - is not None - ): + elif levels.where(lambda l: l.min_xp == level.min_xp).first_or_default() is not None: self._logger.debug( __name__, f"Level with min_xp {level.min_xp} already exists {level.name}", ) - found_level = levels.where( - lambda l: l.min_xp == level.min_xp - ).first_or_default() + found_level = levels.where(lambda l: l.min_xp == level.min_xp).first_or_default() await self._message_service.send_ctx_msg( ctx, - self._t.transform( - "modules.level.error.level_with_xp_already_exists" - ).format(found_level.name, found_level.min_xp), + self._t.transform("modules.level.error.level_with_xp_already_exists").format( + found_level.name, found_level.min_xp + ), ) else: try: @@ -264,9 +239,7 @@ class LevelGroup(DiscordCommandABC): else: await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.level.create.created").format( - name, permissions - ), + self._t.transform("modules.level.create.created").format(name, permissions), ) await self._seed_levels(ctx) @@ -303,19 +276,13 @@ class LevelGroup(DiscordCommandABC): if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.level_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.level_module): return server = self._servers.get_server_by_discord_id(ctx.guild.id) level_from_db = ( - self._levels.get_levels_by_server_id(server.id) - .where(lambda l: l.name == level) - .single_or_default() + self._levels.get_levels_by_server_id(server.id).where(lambda l: l.name == level).single_or_default() ) if level_from_db is None: await self._message_service.send_ctx_msg( @@ -349,13 +316,9 @@ class LevelGroup(DiscordCommandABC): except Exception as e: await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.level.edit.permission_invalid").format( - permissions - ), - ) - self._logger.error( - __name__, f"Error parsing permissions {permissions}", e + self._t.transform("modules.level.edit.permission_invalid").format(permissions), ) + self._logger.error(__name__, f"Error parsing permissions {permissions}", e) return try: @@ -377,9 +340,7 @@ class LevelGroup(DiscordCommandABC): e, ) else: - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.level.edit.edited").format(level) - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.level.edit.edited").format(level)) await self._seed_levels(ctx) self._logger.trace(__name__, f"Finished command level edit") @@ -413,19 +374,13 @@ class LevelGroup(DiscordCommandABC): if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.level_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.level_module): return server = self._servers.get_server_by_discord_id(ctx.guild.id) level_from_db = ( - self._levels.get_levels_by_server_id(server.id) - .where(lambda l: l.name == level) - .first_or_default() + self._levels.get_levels_by_server_id(server.id).where(lambda l: l.name == level).first_or_default() ) if level_from_db is None: self._logger.debug(__name__, f"level {level} not found") @@ -440,9 +395,7 @@ class LevelGroup(DiscordCommandABC): self._levels.delete_level(level_from_db) self._db.save_changes() guild: Guild = self._bot.guilds.where(lambda g: g == ctx.guild).single() - role: Role = guild.roles.where( - lambda r: r.name == level - ).single_or_default() + role: Role = guild.roles.where(lambda r: r.name == level).single_or_default() if role is not None: await role.delete() self._logger.info(__name__, f"Removed level {level}") @@ -471,12 +424,8 @@ class LevelGroup(DiscordCommandABC): if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.level_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.level_module): return if member.bot: @@ -485,16 +434,12 @@ class LevelGroup(DiscordCommandABC): server = self._servers.get_server_by_discord_id(ctx.guild.id) user = self._users.get_user_by_discord_id_and_server_id(member.id, server.id) level = self._level_service.get_level(user) - levels = self._levels.get_levels_by_server_id(server.id).order_by( - lambda l: l.min_xp - ) + levels = self._levels.get_levels_by_server_id(server.id).order_by(lambda l: l.min_xp) if level == levels.first(): await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.level.down.already_first").format( - member.mention - ), + self._t.transform("modules.level.down.already_first").format(member.mention), ) self._logger.trace(__name__, f"Finished command level down") return @@ -506,15 +451,11 @@ class LevelGroup(DiscordCommandABC): self._db.save_changes() await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.level.down.success").format( - member.mention, new_level.name - ), + self._t.transform("modules.level.down.success").format(member.mention, new_level.name), ) await self._level_service.set_level(user) except Exception as e: - self._logger.error( - __name__, f"Cannot level down {member.name} with level {level.name}", e - ) + self._logger.error(__name__, f"Cannot level down {member.name} with level {level.name}", e) await self._message_service.send_ctx_msg( ctx, self._t.transform("modules.level.down.failed").format(member.mention), @@ -531,12 +472,8 @@ class LevelGroup(DiscordCommandABC): if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.level_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.level_module): return if member.bot: @@ -545,16 +482,12 @@ class LevelGroup(DiscordCommandABC): server = self._servers.get_server_by_discord_id(ctx.guild.id) user = self._users.get_user_by_discord_id_and_server_id(member.id, server.id) level = self._level_service.get_level(user) - levels = self._levels.get_levels_by_server_id(server.id).order_by( - lambda l: l.min_xp - ) + levels = self._levels.get_levels_by_server_id(server.id).order_by(lambda l: l.min_xp) if level.name == levels.last().name: await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.level.up.already_last").format( - member.mention - ), + self._t.transform("modules.level.up.already_last").format(member.mention), ) self._logger.trace(__name__, f"Finished command level up") return @@ -566,15 +499,11 @@ class LevelGroup(DiscordCommandABC): self._db.save_changes() await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.level.up.success").format( - member.mention, new_level.name - ), + self._t.transform("modules.level.up.success").format(member.mention, new_level.name), ) await self._level_service.set_level(user) except Exception as e: - self._logger.error( - __name__, f"Cannot level up {member.name} with level {level.name}", e - ) + self._logger.error(__name__, f"Cannot level up {member.name} with level {level.name}", e) await self._message_service.send_ctx_msg( ctx, self._t.transform("modules.level.up.failed").format(member.mention) ) @@ -590,12 +519,8 @@ class LevelGroup(DiscordCommandABC): if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.level_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.level_module): return if member.bot: @@ -604,11 +529,7 @@ class LevelGroup(DiscordCommandABC): server = self._servers.get_server_by_discord_id(ctx.guild.id) user = self._users.get_user_by_discord_id_and_server_id(member.id, server.id) current_level = self._level_service.get_level(user) - new_level = ( - self._levels.get_levels_by_server_id(server.id) - .where(lambda l: l.name == level) - .single_or_default() - ) + new_level = self._levels.get_levels_by_server_id(server.id).where(lambda l: l.name == level).single_or_default() if new_level is None: await self._message_service.send_ctx_msg( @@ -620,9 +541,7 @@ class LevelGroup(DiscordCommandABC): if current_level.name == level: await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.level.set.already_level").format( - member.mention, level - ), + self._t.transform("modules.level.set.already_level").format(member.mention, level), ) self._logger.trace(__name__, f"Finished command level set") return @@ -633,15 +552,11 @@ class LevelGroup(DiscordCommandABC): self._db.save_changes() await self._message_service.send_ctx_msg( ctx, - self._t.transform("modules.level.set.success").format( - member.mention, new_level.name - ), + self._t.transform("modules.level.set.success").format(member.mention, new_level.name), ) await self._level_service.set_level(user) except Exception as e: - self._logger.error( - __name__, f"Cannot set level {level} for {member.name}", e - ) + self._logger.error(__name__, f"Cannot set level {level} for {member.name}", e) await self._message_service.send_ctx_msg( ctx, self._t.transform("modules.level.set.failed").format(member.mention), @@ -650,9 +565,7 @@ class LevelGroup(DiscordCommandABC): self._logger.trace(__name__, f"Finished command level set") @set.autocomplete("level") - async def set_autocomplete( - self, interaction: discord.Interaction, current: str - ) -> TList[app_commands.Choice[str]]: + async def set_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: return await self._level_auto_complete(interaction, current) @level.command() @@ -664,12 +577,8 @@ class LevelGroup(DiscordCommandABC): if ctx.guild is None: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.level_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.level_module): return await self._seed_levels(ctx) diff --git a/bot/src/modules/level/events/level_on_member_join_event.py b/bot/src/modules/level/events/level_on_member_join_event.py index 94f74841..7113f761 100644 --- a/bot/src/modules/level/events/level_on_member_join_event.py +++ b/bot/src/modules/level/events/level_on_member_join_event.py @@ -11,9 +11,7 @@ from modules.level.service.level_service import LevelService class LevelOnMemberJoinEvent(OnMemberJoinABC): - def __init__( - self, config: ConfigurationABC, logger: MessageLogger, level: LevelService - ): + def __init__(self, config: ConfigurationABC, logger: MessageLogger, level: LevelService): OnMemberJoinABC.__init__(self) self._config = config self._logger = logger @@ -22,12 +20,8 @@ class LevelOnMemberJoinEvent(OnMemberJoinABC): @EventChecks.check_is_ready() async def on_member_join(self, member: discord.Member): self._logger.debug(__name__, f"Module {type(self)} started") - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{member.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.level_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{member.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.level_module): return await self._level.check_level(member) diff --git a/bot/src/modules/level/events/level_on_message_event.py b/bot/src/modules/level/events/level_on_message_event.py index 94141f78..4c98706f 100644 --- a/bot/src/modules/level/events/level_on_message_event.py +++ b/bot/src/modules/level/events/level_on_message_event.py @@ -11,9 +11,7 @@ from modules.level.service.level_service import LevelService class LevelOnMessageEvent(OnMessageABC): - def __init__( - self, config: ConfigurationABC, logger: MessageLogger, level: LevelService - ): + def __init__(self, config: ConfigurationABC, logger: MessageLogger, level: LevelService): OnMessageABC.__init__(self) self._config = config self._logger = logger @@ -28,12 +26,8 @@ class LevelOnMessageEvent(OnMessageABC): if message.author.bot: return - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{message.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.level_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{message.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.level_module): return try: diff --git a/bot/src/modules/level/events/level_on_raw_reaction_add_event.py b/bot/src/modules/level/events/level_on_raw_reaction_add_event.py index b59ce939..bffc56ef 100644 --- a/bot/src/modules/level/events/level_on_raw_reaction_add_event.py +++ b/bot/src/modules/level/events/level_on_raw_reaction_add_event.py @@ -29,12 +29,8 @@ class LevelOnRawReactionAddEvent(OnRawReactionAddABC): @EventChecks.check_is_ready() async def on_raw_reaction_add(self, payload: RawReactionActionEvent): self._logger.debug(__name__, f"Module {type(self)} started") - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{payload.guild_id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.level_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{payload.guild_id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.level_module): return try: diff --git a/bot/src/modules/level/events/level_on_raw_reaction_remove_event.py b/bot/src/modules/level/events/level_on_raw_reaction_remove_event.py index fceccd0b..fa94e334 100644 --- a/bot/src/modules/level/events/level_on_raw_reaction_remove_event.py +++ b/bot/src/modules/level/events/level_on_raw_reaction_remove_event.py @@ -29,12 +29,8 @@ class LevelOnRawReactionRemoveEvent(OnRawReactionRemoveABC): @EventChecks.check_is_ready() async def on_raw_reaction_remove(self, payload: RawReactionActionEvent): self._logger.debug(__name__, f"Module {type(self)} started") - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{payload.guild_id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.level_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{payload.guild_id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.level_module): return try: diff --git a/bot/src/modules/level/events/level_on_voice_state_update_event.py b/bot/src/modules/level/events/level_on_voice_state_update_event.py index c529311c..9a0b5978 100644 --- a/bot/src/modules/level/events/level_on_voice_state_update_event.py +++ b/bot/src/modules/level/events/level_on_voice_state_update_event.py @@ -11,9 +11,7 @@ from modules.level.service.level_service import LevelService class LevelOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC): - def __init__( - self, config: ConfigurationABC, logger: LoggerABC, level: LevelService - ): + def __init__(self, config: ConfigurationABC, logger: LoggerABC, level: LevelService): OnVoiceStateUpdateABC.__init__(self) self._config = config self._logger = logger @@ -29,12 +27,8 @@ class LevelOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC): after: discord.VoiceState, ): self._logger.debug(__name__, f"Module {type(self)} started") - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{member.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.level_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{member.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.level_module): return await self._level.check_level(member) diff --git a/bot/src/modules/level/level_module.py b/bot/src/modules/level/level_module.py index 19e04459..500e4a01 100644 --- a/bot/src/modules/level/level_module.py +++ b/bot/src/modules/level/level_module.py @@ -29,17 +29,13 @@ class LevelModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.level_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): cwd = env.working_directory env.set_working_directory(os.path.dirname(os.path.realpath(__file__))) config.add_json_file(f"default-level.json", optional=False) env.set_working_directory(cwd) - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): services.add_transient(DataSeederABC, LevelSeeder) services.add_transient(LevelService) @@ -47,19 +43,13 @@ class LevelModule(ModuleABC): services.add_transient(LevelGroup) # events - services.add_transient( - DiscordEventTypesEnum.on_message.value, LevelOnMessageEvent - ) + services.add_transient(DiscordEventTypesEnum.on_message.value, LevelOnMessageEvent) services.add_transient( DiscordEventTypesEnum.on_voice_state_update.value, LevelOnVoiceStateUpdateEvent, ) - services.add_transient( - DiscordEventTypesEnum.on_member_join.value, LevelOnMemberJoinEvent - ) - services.add_transient( - DiscordEventTypesEnum.on_raw_reaction_add.value, LevelOnRawReactionAddEvent - ) + services.add_transient(DiscordEventTypesEnum.on_member_join.value, LevelOnMemberJoinEvent) + services.add_transient(DiscordEventTypesEnum.on_raw_reaction_add.value, LevelOnRawReactionAddEvent) services.add_transient( DiscordEventTypesEnum.on_raw_reaction_remove.value, LevelOnRawReactionRemoveEvent, diff --git a/bot/src/modules/level/level_seeder.py b/bot/src/modules/level/level_seeder.py index e0f81148..19c7b773 100644 --- a/bot/src/modules/level/level_seeder.py +++ b/bot/src/modules/level/level_seeder.py @@ -46,10 +46,7 @@ class LevelSeeder(DataSeederABC): async def _create_level(self, level: Level, guild: Guild, server: Server): level.server = server try: - if ( - guild.roles.where(lambda r: r.name == level.name).first_or_default() - is None - ): + if guild.roles.where(lambda r: r.name == level.name).first_or_default() is None: await guild.create_role( name=level.name, colour=Colour(int(level.color, 16)), @@ -60,11 +57,7 @@ class LevelSeeder(DataSeederABC): self._logger.debug(__name__, f"Created role {level.name}") levels = self._levels.find_levels_by_server_id(server.id) - if ( - levels is None - or levels.where(lambda l: l.name == level.name).first_or_default() - is None - ): + if levels is None or levels.where(lambda l: l.name == level.name).first_or_default() is None: self._levels.add_level(level) self._logger.debug(__name__, f"Saved level {level.name}") self._db.save_changes() @@ -78,21 +71,12 @@ class LevelSeeder(DataSeederABC): async def seed(self): # create levels for guild in self._bot.guilds: - server_config: ServerConfig = self._config.get_configuration( - f"ServerConfig_{guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - server_config.feature_flags, FeatureFlagsEnum.level_module - ): + server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(server_config.feature_flags, FeatureFlagsEnum.level_module): continue created_default = False - if ( - guild.roles.where( - lambda r: r.name == self._level_header - ).first_or_default() - is None - ): + if guild.roles.where(lambda r: r.name == self._level_header).first_or_default() is None: await guild.create_role(name=self._level_header) server = self._servers.find_server_by_discord_id(guild.id) @@ -118,20 +102,13 @@ class LevelSeeder(DataSeederABC): continue levels = levels.order_by_descending(lambda l: l.min_xp) - position_above_levels = ( - guild.roles.where(lambda r: r.name == self._level_header) - .single() - .position - ) + position_above_levels = guild.roles.where(lambda r: r.name == self._level_header).single().position for role in guild.roles.order_by_descending(lambda r: r.position): if levels.where(lambda l: l.name == role.name).count() == 0: continue new_position = position_above_levels - ( - levels.index_of( - levels.where(lambda l: l.name == role.name).single() - ) - + 1 + levels.index_of(levels.where(lambda l: l.name == role.name).single()) + 1 ) if new_position <= 0: new_position = 1 @@ -142,9 +119,7 @@ class LevelSeeder(DataSeederABC): ) await role.edit(position=new_position) except Exception as e: - self._logger.error( - __name__, f"Cannot change position of {role.name}", e - ) + self._logger.error(__name__, f"Cannot change position of {role.name}", e) for m in guild.members: await self._level.check_level(m) diff --git a/bot/src/modules/level/service/level_service.py b/bot/src/modules/level/service/level_service.py index 258bec27..e85c1719 100644 --- a/bot/src/modules/level/service/level_service.py +++ b/bot/src/modules/level/service/level_service.py @@ -43,9 +43,7 @@ class LevelService: if user.xp < 0: return levels_by_server.order_by(lambda l: l.min_xp).first() - levels = levels_by_server.order_by(lambda l: l.min_xp).where( - lambda l: user.xp >= l.min_xp - ) + levels = levels_by_server.order_by(lambda l: l.min_xp).where(lambda l: user.xp >= l.min_xp) if levels.count() == 0: return levels_by_server.order_by(lambda l: l.min_xp).last() @@ -53,12 +51,8 @@ class LevelService: return levels.last() async def set_level(self, user: User): - level_names = self._levels.get_levels_by_server_id(user.server.id).select( - lambda l: l.name - ) - guild: Guild = self._bot.guilds.where( - lambda g: g.id == user.server.discord_id - ).single() + level_names = self._levels.get_levels_by_server_id(user.server.id).select(lambda l: l.name) + guild: Guild = self._bot.guilds.where(lambda g: g.id == user.server.discord_id).single() member: Member = guild.members.where(lambda m: m.id == user.discord_id).single() level = self.get_level(user) @@ -69,39 +63,25 @@ class LevelService: notification_needed = False for role in member.roles.where(lambda r: r.name in level_names.to_list()): try: - self._logger.debug( - __name__, f"Try to remove role {role.name} from {member.name}" - ) + self._logger.debug(__name__, f"Try to remove role {role.name} from {member.name}") await member.remove_roles(role) notification_needed = True - self._logger.info( - __name__, f"Removed role {role.name} from {member.name}" - ) + self._logger.info(__name__, f"Removed role {role.name} from {member.name}") except Exception as e: - self._logger.error( - __name__, f"Removing role {role.name} from {member.name} failed!", e - ) + self._logger.error(__name__, f"Removing role {role.name} from {member.name} failed!", e) try: - self._logger.debug( - __name__, f"Try to add role {level_role.name} to {member.name}" - ) + self._logger.debug(__name__, f"Try to add role {level_role.name} to {member.name}") await member.add_roles(level_role) self._logger.info(__name__, f"Add role {level_role.name} to {member.name}") except Exception as e: - self._logger.error( - __name__, f"Adding role {level_role.name} to {member.name} failed!", e - ) + self._logger.error(__name__, f"Adding role {level_role.name} to {member.name} failed!", e) if notification_needed: - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{guild.id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild.id}") await self._message_service.send_channel_message( self._bot.get_channel(settings.notification_chat_id), - self._t.transform("modules.level.new_level_message").format( - member.mention, level.name - ), + self._t.transform("modules.level.new_level_message").format(member.mention, level.name), is_persistent=True, ) @@ -112,9 +92,7 @@ class LevelService: server = self._servers.get_server_by_discord_id(member.guild.id) user = self._users.find_user_by_discord_id_and_server_id(member.id, server.id) if user is None: - self._logger.warn( - __name__, f"User not found {member.guild.name}@{member.name}" - ) + self._logger.warn(__name__, f"User not found {member.guild.name}@{member.name}") return await self.set_level(user) diff --git a/bot/src/modules/permission/permission_module.py b/bot/src/modules/permission/permission_module.py index fb6c509d..75da783e 100644 --- a/bot/src/modules/permission/permission_module.py +++ b/bot/src/modules/permission/permission_module.py @@ -13,14 +13,10 @@ class PermissionModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.permission_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): pass - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): services.add_transient(PermissionServiceABC, PermissionService) # commands # events diff --git a/bot/src/modules/permission/service/permission_service.py b/bot/src/modules/permission/service/permission_service.py index c75175e7..9ac28c55 100644 --- a/bot/src/modules/permission/service/permission_service.py +++ b/bot/src/modules/permission/service/permission_service.py @@ -28,22 +28,18 @@ class PermissionService(PermissionServiceABC): self._server_configs = server_configs self._technician_configs = technician_configs - def _has_member_role( - self, member: discord.Member, team_member_type: TeamMemberTypeEnum - ) -> bool: + def _has_member_role(self, member: discord.Member, team_member_type: TeamMemberTypeEnum) -> bool: if member is None or member.guild is None: return False - self._logger.debug( - __name__, f"Checking is member {member.name} {team_member_type.value}" - ) + self._logger.debug(__name__, f"Checking is member {member.name} {team_member_type.value}") try: server = self._servers.get_server_by_discord_id(member.guild.id) config = self._server_configs.get_server_config_by_server(server.id) - roles = config.team_role_ids.where( - lambda x: x.team_member_type == team_member_type - ).select(lambda x: member.guild.get_role(x.role_id)) + roles = config.team_role_ids.where(lambda x: x.team_member_type == team_member_type).select( + lambda x: member.guild.get_role(x.role_id) + ) for role in roles: if role not in member.roles: continue @@ -58,9 +54,9 @@ class PermissionService(PermissionServiceABC): return self._has_member_role(member, TeamMemberTypeEnum.admin) def is_member_moderator(self, member: discord.Member) -> bool: - return self._has_member_role( - member, TeamMemberTypeEnum.moderator - ) or self._has_member_role(member, TeamMemberTypeEnum.admin) + return self._has_member_role(member, TeamMemberTypeEnum.moderator) or self._has_member_role( + member, TeamMemberTypeEnum.admin + ) def is_member_technician(self, member: discord.Member) -> bool: if member is None or member.guild is None: diff --git a/bot/src/modules/short_role_name/events/short_role_name_on_member_update_event.py b/bot/src/modules/short_role_name/events/short_role_name_on_member_update_event.py index 574b3379..6b942ed1 100644 --- a/bot/src/modules/short_role_name/events/short_role_name_on_member_update_event.py +++ b/bot/src/modules/short_role_name/events/short_role_name_on_member_update_event.py @@ -9,8 +9,6 @@ class ShortRoleNameOnMemberUpdateEvent(OnMemberUpdateABC): OnMemberUpdateABC.__init__(self) self._service = service - async def on_member_update( - self, before: discord.member.Member, after: discord.member.Member - ): + async def on_member_update(self, before: discord.member.Member, after: discord.member.Member): if before.roles != after.roles or before.name != after.name: await self._service.check_short_role_names(after) diff --git a/bot/src/modules/short_role_name/service/short_role_name_service.py b/bot/src/modules/short_role_name/service/short_role_name_service.py index f85f2d01..5a2e8af8 100644 --- a/bot/src/modules/short_role_name/service/short_role_name_service.py +++ b/bot/src/modules/short_role_name/service/short_role_name_service.py @@ -32,12 +32,8 @@ class ShortRoleNameService: async def check_short_role_names(self, member: discord.Member): self._logger.debug(__name__, f"Started short role name check for {member.id}") - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{member.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - settings.feature_flags, FeatureFlagsEnum.short_role_name - ): + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{member.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(settings.feature_flags, FeatureFlagsEnum.short_role_name): self._logger.debug(__name__, f"Feature not active") return @@ -49,16 +45,12 @@ class ShortRoleNameService: new_nick = member.nick if member.nick is not None else member.name member_roles = List(discord.Role, member.roles) highest_role: Optional[discord.Role] = ( - member_roles.last_or_default() - if settings.short_role_name_only_set_highest_role - else None + member_roles.last_or_default() if settings.short_role_name_only_set_highest_role else None ) member_role_ids = member_roles.select(lambda x: x.id) server = self._server.get_server_by_discord_id(member.guild.id) - for short_role_name in self._short_role_names.get_short_role_names_by_server_id( - server.id - ): + for short_role_name in self._short_role_names.get_short_role_names_by_server_id(server.id): short_role_name: ShortRoleName = short_role_name new_nick = new_nick.replace(f" [{short_role_name.short_name}]", "") diff --git a/bot/src/modules/short_role_name/short_role_name_check_command.py b/bot/src/modules/short_role_name/short_role_name_check_command.py index feb35a99..663be0f1 100644 --- a/bot/src/modules/short_role_name/short_role_name_check_command.py +++ b/bot/src/modules/short_role_name/short_role_name_check_command.py @@ -47,22 +47,14 @@ class ShortRoleNameCheckCommand(DiscordCommandABC): if ctx.guild is None: return - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - settings.feature_flags, FeatureFlagsEnum.short_role_name - ): - await self._message_service.send_ctx_msg( - ctx, self._t.transform("common.feature_not_activated") - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(settings.feature_flags, FeatureFlagsEnum.short_role_name): + await self._message_service.send_ctx_msg(ctx, self._t.transform("common.feature_not_activated")) return for member in ctx.guild.members: await self._service.check_short_role_names(member) - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.short_role_name.checked_message") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.short_role_name.checked_message")) self._logger.trace(__name__, f"Finished purge command") diff --git a/bot/src/modules/short_role_name/short_role_name_module.py b/bot/src/modules/short_role_name/short_role_name_module.py index 224e52d9..19b732fe 100644 --- a/bot/src/modules/short_role_name/short_role_name_module.py +++ b/bot/src/modules/short_role_name/short_role_name_module.py @@ -21,14 +21,10 @@ class ShortRoleNameModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.short_role_name_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): pass - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): services.add_transient(DataSeederABC, ShortRoleNameSeeder) services.add_transient(ShortRoleNameService) diff --git a/bot/src/modules/special_offers/special_offers_module.py b/bot/src/modules/special_offers/special_offers_module.py index 4a35120d..e64108b5 100644 --- a/bot/src/modules/special_offers/special_offers_module.py +++ b/bot/src/modules/special_offers/special_offers_module.py @@ -13,14 +13,10 @@ class SteamSpecialOffersModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.steam_special_offers_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): pass - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): services.add_singleton(TaskABC, SteamOfferWatcher) # commands # events diff --git a/bot/src/modules/special_offers/steam_offer_watcher.py b/bot/src/modules/special_offers/steam_offer_watcher.py index b31e6a6a..d2cd2317 100644 --- a/bot/src/modules/special_offers/steam_offer_watcher.py +++ b/bot/src/modules/special_offers/steam_offer_watcher.py @@ -53,9 +53,7 @@ class SteamOfferWatcher(TaskABC): @staticmethod def _get_max_count() -> int: count = 0 - result = requests.get( - f"https://store.steampowered.com/search/results?specials=1" - ) + result = requests.get(f"https://store.steampowered.com/search/results?specials=1") soup = bs4.BeautifulSoup(result.text, "lxml") element = soup.find_all("div", {"class": "search_results_count"}) if len(element) < 1: @@ -77,13 +75,9 @@ class SteamOfferWatcher(TaskABC): for element in elements: name_element = element.find("span", {"class": "title"}) - original_price_element = element.find( - "div", {"class": "discount_original_price"} - ) + original_price_element = element.find("div", {"class": "discount_original_price"}) discount_element = element.find("div", {"class": "discount_pct"}) - discount_price_element = element.find( - "div", {"class": "discount_final_price"} - ) + discount_price_element = element.find("div", {"class": "discount_final_price"}) if ( name_element is None @@ -99,25 +93,15 @@ class SteamOfferWatcher(TaskABC): name = name_element.contents[0].replace("'", "`").replace('"', "`") original_price = float( - original_price_element.contents[0] - .replace(" ", "") - .replace("€", "") - .replace(",", ".") + original_price_element.contents[0].replace(" ", "").replace("€", "").replace(",", ".") ) discount = int(discount_element.contents[0].replace("%", "")) discount_price = float( - discount_price_element.contents[0] - .replace(" ", "") - .replace("€", "") - .replace(",", ".") + discount_price_element.contents[0].replace(" ", "").replace("€", "").replace(",", ".") ) games.add(SteamSpecialOffer(name, original_price, discount_price, discount)) self._urls[name] = element.attrs["href"] - self._image_urls[name] = ( - element.find("div", {"class": "search_capsule"}) - .find("img") - .attrs["src"] - ) + self._image_urls[name] = element.find("div", {"class": "search_capsule"}).find("img").attrs["src"] return games @@ -134,9 +118,7 @@ class SteamOfferWatcher(TaskABC): return new_offers - async def _send_embed_for_offer( - self, offer: SteamSpecialOffer, channel_id: int - ) -> discord.Embed: + async def _send_embed_for_offer(self, offer: SteamSpecialOffer, channel_id: int) -> discord.Embed: embed = discord.Embed( title=offer.name, url=self._urls[offer.name], @@ -211,9 +193,7 @@ class SteamOfferWatcher(TaskABC): if self._is_new: return for guild in self._bot.guilds: - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{guild.id}" - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild.id}") if ( not FeatureFlagsSettings.get_flag_from_dict( settings.feature_flags, FeatureFlagsEnum.steam_special_offers @@ -224,9 +204,7 @@ class SteamOfferWatcher(TaskABC): for offer in offers_for_notifications: self._bot.loop.create_task( - self._send_embed_for_offer( - offer, settings.game_offer_notification_chat_id - ) + self._send_embed_for_offer(offer, settings.game_offer_notification_chat_id) ) except Exception as e: self._logger.error(__name__, f"Steam offer watcher failed", e) diff --git a/bot/src/modules/technician/api_key_seeder.py b/bot/src/modules/technician/api_key_seeder.py index 70792942..f8f1305c 100644 --- a/bot/src/modules/technician/api_key_seeder.py +++ b/bot/src/modules/technician/api_key_seeder.py @@ -36,9 +36,7 @@ class ApiKeySeeder(DataSeederABC): return try: - frontend_key = ApiKey( - "frontend", "87f529fd-a32e-40b3-a1d1-7a1583cf3ff5", None - ) + frontend_key = ApiKey("frontend", "87f529fd-a32e-40b3-a1d1-7a1583cf3ff5", None) self._api_keys.add_api_key(frontend_key) self._db.save_changes() self._logger.info(__name__, f"Created frontend API-Key") diff --git a/bot/src/modules/technician/command/api_key_group.py b/bot/src/modules/technician/command/api_key_group.py index f0171553..11912385 100644 --- a/bot/src/modules/technician/command/api_key_group.py +++ b/bot/src/modules/technician/command/api_key_group.py @@ -54,9 +54,7 @@ class ApiKeyGroup(DiscordCommandABC): def _get_api_key_str(self, api_key: ApiKey) -> str: return hashlib.sha256( - f"{api_key.identifier}:{api_key.key}+{self._auth_settings.secret_key}".encode( - "utf-8" - ) + f"{api_key.identifier}:{api_key.key}+{self._auth_settings.secret_key}".encode("utf-8") ).hexdigest() @commands.hybrid_group(name="api-key") @@ -69,9 +67,7 @@ class ApiKeyGroup(DiscordCommandABC): @CommandChecks.check_is_ready() @CommandChecks.check_is_member_technician() async def get(self, ctx: Context, key: str, wait: int = None): - self._logger.debug( - __name__, f"Received command api-key get {ctx}: {key},{wait}" - ) + self._logger.debug(__name__, f"Received command api-key get {ctx}: {key},{wait}") api_key = self._api_keys.get_api_key_by_key(key) await self._message_service.send_ctx_msg( @@ -83,16 +79,12 @@ class ApiKeyGroup(DiscordCommandABC): self._logger.trace(__name__, f"Finished command api-key get") @get.autocomplete("key") - async def get_autocomplete( - self, interaction: discord.Interaction, current: str - ) -> TList[app_commands.Choice[str]]: + async def get_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: keys = self._api_keys.get_api_keys() return [ app_commands.Choice(name=f"{key.identifier}: {key.key}", value=key.key) - for key in self._client_utils.get_auto_complete_list( - keys, current, lambda x: x.key - ) + for key in self._client_utils.get_auto_complete_list(keys, current, lambda x: x.key) ] @api_key.command() @@ -100,14 +92,10 @@ class ApiKeyGroup(DiscordCommandABC): @CommandChecks.check_is_ready() @CommandChecks.check_is_member_moderator() async def add(self, ctx: Context, identifier: str): - self._logger.debug( - __name__, f"Received command api-key add {ctx}: {identifier}" - ) + self._logger.debug(__name__, f"Received command api-key add {ctx}: {identifier}") server = self._servers.get_server_by_discord_id(ctx.guild.id) - user = self._users.get_user_by_discord_id_and_server_id( - ctx.author.id, server.id - ) + user = self._users.get_user_by_discord_id_and_server_id(ctx.author.id, server.id) api_key = ApiKey(identifier, str(uuid.uuid4()), user) self._api_keys.add_api_key(api_key) self._db.save_changes() @@ -137,21 +125,15 @@ class ApiKeyGroup(DiscordCommandABC): api_key = keys.single() self._api_keys.delete_api_key(api_key) self._db.save_changes() - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.technician.api_key.remove.success") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.technician.api_key.remove.success")) self._logger.trace(__name__, f"Finished command api-key remove") @remove.autocomplete("key") - async def set_autocomplete( - self, interaction: discord.Interaction, current: str - ) -> TList[app_commands.Choice[str]]: + async def set_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: keys = self._api_keys.get_api_keys() return [ app_commands.Choice(name=f"{key.identifier}: {key.key}", value=key.key) - for key in self._client_utils.get_auto_complete_list( - keys, current, lambda x: x.key - ) + for key in self._client_utils.get_auto_complete_list(keys, current, lambda x: x.key) ] diff --git a/bot/src/modules/technician/command/log_command.py b/bot/src/modules/technician/command/log_command.py index 27e8c557..2f799d61 100644 --- a/bot/src/modules/technician/command/log_command.py +++ b/bot/src/modules/technician/command/log_command.py @@ -98,10 +98,7 @@ class LogCommand(DiscordCommandABC): continue split_filename = file.split(".") - if ( - f".{split_filename[len(split_filename) - 1]}" - not in file_extensions - ): + if f".{split_filename[len(split_filename) - 1]}" not in file_extensions: continue files.append(os.path.join(r, file)) diff --git a/bot/src/modules/technician/command/restart_command.py b/bot/src/modules/technician/command/restart_command.py index 102519fd..76fda82c 100644 --- a/bot/src/modules/technician/command/restart_command.py +++ b/bot/src/modules/technician/command/restart_command.py @@ -52,9 +52,7 @@ class RestartCommand(DiscordCommandABC): self._config.add_configuration("IS_RESTART", "true") await self._client_utils.presence_game("common.presence.restart") - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.technician.restart_message") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.technician.restart_message")) await asyncio.sleep(self._settings.wait_for_restart) await self._data_integrity.check_data_integrity(is_for_shutdown=True) await self._bot.stop_async() diff --git a/bot/src/modules/technician/command/shutdown_command.py b/bot/src/modules/technician/command/shutdown_command.py index 5ddf9603..db2f807a 100644 --- a/bot/src/modules/technician/command/shutdown_command.py +++ b/bot/src/modules/technician/command/shutdown_command.py @@ -51,9 +51,7 @@ class ShutdownCommand(DiscordCommandABC): self._logger.debug(__name__, f"Received command shutdown {ctx}") await self._client_utils.presence_game("common.presence.shutdown") - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.technician.shutdown_message") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.technician.shutdown_message")) await asyncio.sleep(self._settings.wait_for_shutdown) await self._data_integrity.check_data_integrity(is_for_shutdown=True) await self._bot.stop_async() diff --git a/bot/src/modules/technician/command/sync_xp_command.py b/bot/src/modules/technician/command/sync_xp_command.py index 90e97554..e54a770f 100644 --- a/bot/src/modules/technician/command/sync_xp_command.py +++ b/bot/src/modules/technician/command/sync_xp_command.py @@ -71,28 +71,18 @@ class SyncXpGroup(DiscordCommandABC): if ctx.guild is None: return - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - settings.feature_flags, FeatureFlagsEnum.sync_xp - ): - await self._message_service.send_ctx_msg( - ctx, self._t.transform("common.feature_not_activated") - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(settings.feature_flags, FeatureFlagsEnum.sync_xp): + await self._message_service.send_ctx_msg(ctx, self._t.transform("common.feature_not_activated")) return other_server = self._servers.get_server_by_id(server_id) - users_on_other_server = self._users.get_users_by_server_id( - other_server.id - ).where(lambda x: not x.left_server) - discord_ids_on_other_server = users_on_other_server.select( - lambda x: x.discord_id - ) + users_on_other_server = self._users.get_users_by_server_id(other_server.id).where(lambda x: not x.left_server) + discord_ids_on_other_server = users_on_other_server.select(lambda x: x.discord_id) - for user in self._users.get_users_by_server_id( - self._servers.get_server_by_discord_id(ctx.guild.id).id - ).where(lambda x: not x.left_server): + for user in self._users.get_users_by_server_id(self._servers.get_server_by_discord_id(ctx.guild.id).id).where( + lambda x: not x.left_server + ): try: if user.discord_id not in discord_ids_on_other_server: continue @@ -106,21 +96,15 @@ class SyncXpGroup(DiscordCommandABC): user.xp = user_on_other_server.xp self._users.update_user(user) self._db.save_changes() - await self._level_service.check_level( - ctx.guild.get_member(user.discord_id) - ) + await self._level_service.check_level(ctx.guild.get_member(user.discord_id)) except Exception as e: self._logger.error(__name__, f"Cannot sync user {user.name}", e) - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.technician.synced_message") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.technician.synced_message")) self._logger.trace(__name__, f"Finished sync xp command") @all_members.autocomplete("server_id") - async def list_autocomplete( - self, interaction: discord.Interaction, current: str - ) -> list[app_commands.Choice]: + async def list_autocomplete(self, interaction: discord.Interaction, current: str) -> list[app_commands.Choice]: return [ app_commands.Choice(name=server.name, value=server.id) for server in self._client_utils.get_auto_complete_list( @@ -138,15 +122,9 @@ class SyncXpGroup(DiscordCommandABC): if ctx.guild is None: return - settings: ServerConfig = self._config.get_configuration( - f"ServerConfig_{ctx.guild.id}" - ) - if not FeatureFlagsSettings.get_flag_from_dict( - settings.feature_flags, FeatureFlagsEnum.sync_xp - ): - await self._message_service.send_ctx_msg( - ctx, self._t.transform("common.feature_not_activated") - ) + settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}") + if not FeatureFlagsSettings.get_flag_from_dict(settings.feature_flags, FeatureFlagsEnum.sync_xp): + await self._message_service.send_ctx_msg(ctx, self._t.transform("common.feature_not_activated")) return other_server = self._servers.get_server_by_id(server_id) @@ -169,16 +147,12 @@ class SyncXpGroup(DiscordCommandABC): except Exception as e: self._logger.error(__name__, f"Cannot sync user {user.name}", e) - await self._message_service.send_ctx_msg( - ctx, self._t.transform("modules.technician.synced_message") - ) + await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.technician.synced_message")) await self._level_service.check_level(member) self._logger.trace(__name__, f"Finished sync xp command") @by_member.autocomplete("server_id") - async def list_autocomplete( - self, interaction: discord.Interaction, current: str - ) -> list[app_commands.Choice]: + async def list_autocomplete(self, interaction: discord.Interaction, current: str) -> list[app_commands.Choice]: return [ app_commands.Choice(name=server.name, value=server.id) for server in self._client_utils.get_auto_complete_list( diff --git a/bot/src/modules/technician/technician_module.py b/bot/src/modules/technician/technician_module.py index 77677cc9..8550b7d6 100644 --- a/bot/src/modules/technician/technician_module.py +++ b/bot/src/modules/technician/technician_module.py @@ -18,14 +18,10 @@ class TechnicianModule(ModuleABC): def __init__(self, dc: DiscordCollectionABC): ModuleABC.__init__(self, dc, FeatureFlagsEnum.base_module) - def configure_configuration( - self, config: ConfigurationABC, env: ApplicationEnvironmentABC - ): + def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): pass - def configure_services( - self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC - ): + def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): services.add_transient(DataSeederABC, ApiKeySeeder) # commands services.add_transient(RestartCommand) diff --git a/bot/tools/get_version/startup.py b/bot/tools/get_version/startup.py index eaa731d7..8cb6680f 100644 --- a/bot/tools/get_version/startup.py +++ b/bot/tools/get_version/startup.py @@ -14,14 +14,10 @@ class Startup(StartupABC): def configure_configuration( self, configuration: ConfigurationABC, environment: ApplicationEnvironment ) -> ConfigurationABC: - environment.set_working_directory( - os.path.abspath(os.path.join(environment.working_directory, "../../")) - ) + environment.set_working_directory(os.path.abspath(os.path.join(environment.working_directory, "../../"))) configuration.add_json_file(f"cpl-workspace.json", optional=False, output=False) ws: WorkspaceSettings = configuration.get_configuration(WorkspaceSettings) - configuration.add_json_file( - ws.projects[ws.default_project], optional=False, output=False - ) + configuration.add_json_file(ws.projects[ws.default_project], optional=False, output=False) return configuration diff --git a/bot/tools/post_build/post_build_settings.py b/bot/tools/post_build/post_build_settings.py index b1d815da..3c8a789e 100644 --- a/bot/tools/post_build/post_build_settings.py +++ b/bot/tools/post_build/post_build_settings.py @@ -24,9 +24,5 @@ class PostBuildSettings(ConfigurationModelABC): self._keep_config = settings["KeepConfigs"] self._config_paths = settings["ConfigPaths"] 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()}" - ) + Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings") + Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}") diff --git a/bot/tools/post_build/service/dependencies.py b/bot/tools/post_build/service/dependencies.py index b0362257..060adae4 100644 --- a/bot/tools/post_build/service/dependencies.py +++ b/bot/tools/post_build/service/dependencies.py @@ -54,9 +54,7 @@ class Dependencies: ) for project in self._workspace.projects: - project_file = os.path.join( - self._env.working_directory, self._workspace.projects[project] - ) + project_file = os.path.join(self._env.working_directory, self._workspace.projects[project]) self._config.add_json_file(project_file, output=False, optional=False) project: ProjectSettings = self._config.get_configuration(ProjectSettings) self._add_dependencies(project.dependencies) diff --git a/bot/tools/post_build/startup.py b/bot/tools/post_build/startup.py index 6d5e484d..537f3f2a 100644 --- a/bot/tools/post_build/startup.py +++ b/bot/tools/post_build/startup.py @@ -18,14 +18,10 @@ class Startup(StartupABC): self, configuration: ConfigurationABC, environment: ApplicationEnvironment ) -> ConfigurationABC: configuration.add_json_file(f"appsettings.json", optional=False, output=False) - environment.set_working_directory( - os.path.abspath(os.path.join(environment.working_directory, "../../")) - ) + environment.set_working_directory(os.path.abspath(os.path.join(environment.working_directory, "../../"))) configuration.add_json_file(f"cpl-workspace.json", optional=False, output=False) ws: WorkspaceSettings = configuration.get_configuration(WorkspaceSettings) - configuration.add_json_file( - ws.projects[ws.default_project], optional=False, output=False - ) + configuration.add_json_file(ws.projects[ws.default_project], optional=False, output=False) return configuration diff --git a/bot/tools/set_version/application.py b/bot/tools/set_version/application.py index f773982c..882d819a 100644 --- a/bot/tools/set_version/application.py +++ b/bot/tools/set_version/application.py @@ -22,9 +22,7 @@ class Application(ApplicationABC): self._workspace: WorkspaceSettings = config.get_configuration(WorkspaceSettings) self._git_service: GitService = self._services.get_service(GitService) - self._version_setter: VersionSetterService = self._services.get_service( - VersionSetterService - ) + self._version_setter: VersionSetterService = self._services.get_service(VersionSetterService) self._version_pipe: VersionPipe = self._services.get_service(VersionPipe) def configure(self): @@ -63,15 +61,11 @@ class Application(ApplicationABC): optional=False, output=False, ) - ps: ProjectSettings = self._configuration.get_configuration( - ProjectSettings - ) + ps: ProjectSettings = self._configuration.get_configuration(ProjectSettings) version[VersionSettingsNameEnum.major.value] = ps.version.major version[VersionSettingsNameEnum.minor.value] = ps.version.minor - version[ - VersionSettingsNameEnum.micro.value - ] = f'dev{branch.split("#")[1]}' + version[VersionSettingsNameEnum.micro.value] = f'dev{branch.split("#")[1]}' else: if "." not in branch and "." in suffix: branch = suffix @@ -86,9 +80,7 @@ class Application(ApplicationABC): else: if not suffix.startswith(".") and suffix != "": suffix = f".{suffix}" - version[ - VersionSettingsNameEnum.micro.value - ] = f'{branch.split(".")[2]}{suffix}' + version[VersionSettingsNameEnum.micro.value] = f'{branch.split(".")[2]}{suffix}' except Exception as e: Console.error(f"Branch {branch} does not contain valid version") return @@ -114,18 +106,12 @@ class Application(ApplicationABC): try: skipped = [] for project in self._workspace.projects: - if ( - project not in diff_paths - and String.convert_to_snake_case(project) not in diff_paths - and not force - ): + if project not in diff_paths and String.convert_to_snake_case(project) not in diff_paths and not force: # Console.write_line(f'Skipping {project} due to missing changes') skipped.append(project) continue - Console.write_line( - f"Set dependencies {self._version_pipe.transform(version)} for {project}" - ) + Console.write_line(f"Set dependencies {self._version_pipe.transform(version)} for {project}") self._version_setter.set_dependencies( self._workspace.projects[project], version, @@ -139,12 +125,8 @@ class Application(ApplicationABC): skipped=skipped, ) - Console.write_line( - f"Set version {self._version_pipe.transform(version)} for {project}" - ) - self._version_setter.set_version( - self._workspace.projects[project], version - ) + Console.write_line(f"Set version {self._version_pipe.transform(version)} for {project}") + self._version_setter.set_version(self._workspace.projects[project], version) except Exception as e: Console.error("Version could not be set", traceback.format_exc()) return diff --git a/bot/tools/set_version/startup.py b/bot/tools/set_version/startup.py index 47898325..ce7fb47f 100644 --- a/bot/tools/set_version/startup.py +++ b/bot/tools/set_version/startup.py @@ -19,12 +19,8 @@ class Startup(StartupABC): ) -> ConfigurationABC: configuration.add_json_file("cpl-workspace.json", optional=True, output=False) if configuration.get_configuration(WorkspaceSettings) is None: - environment.set_working_directory( - os.path.join(environment.working_directory, "../../") - ) - configuration.add_json_file( - "cpl-workspace.json", optional=False, output=False - ) + environment.set_working_directory(os.path.join(environment.working_directory, "../../")) + configuration.add_json_file("cpl-workspace.json", optional=False, output=False) return configuration diff --git a/bot/tools/set_version/version_setter_service.py b/bot/tools/set_version/version_setter_service.py index e4b0545d..af019658 100644 --- a/bot/tools/set_version/version_setter_service.py +++ b/bot/tools/set_version/version_setter_service.py @@ -12,9 +12,7 @@ class VersionSetterService: def _read_file(self, file: str) -> dict: project_json = {} - with open( - os.path.join(self._env.working_directory, file), "r", encoding="utf-8" - ) as f: + with open(os.path.join(self._env.working_directory, file), "r", encoding="utf-8") as f: # load json project_json = json.load(f) f.close() @@ -22,9 +20,7 @@ class VersionSetterService: return project_json def _write_file(self, file: str, project_json: dict): - with open( - os.path.join(self._env.working_directory, file), "w", encoding="utf-8" - ) as f: + with open(os.path.join(self._env.working_directory, file), "w", encoding="utf-8") as f: f.write(json.dumps(project_json, indent=2)) f.close() @@ -52,10 +48,7 @@ class VersionSetterService: if ( skipped is not None - and ( - dep_name in skipped - or String.convert_to_snake_case(dep_name) in skipped - ) + and (dep_name in skipped or String.convert_to_snake_case(dep_name) in skipped) or dep_version == "" ): new_deps.append(dependency)