Formatted files with black

This commit is contained in:
Sven Heidemann 2023-01-13 23:54:06 +01:00
parent e2b2fb5abb
commit ea266cc5be
141 changed files with 741 additions and 1886 deletions

View File

@ -25,8 +25,8 @@
"gv": "cpl get-version", "gv": "cpl get-version",
"get-version": "export VERSION=$(cpl run get-version --dev); echo $VERSION;", "get-version": "export VERSION=$(cpl run get-version --dev); echo $VERSION;",
"pre-build": "cpl set-version $ARGS; black src;", "pre-build": "cpl set-version $ARGS; black ./;",
"post-build": "cpl run post-build --dev; black src;", "post-build": "cpl run post-build --dev; black ./;",
"pre-prod": "cpl build", "pre-prod": "cpl build",
"prod": "export KDB_ENVIRONMENT=production; export KDB_NAME=KDB-Prod; cpl start;", "prod": "export KDB_ENVIRONMENT=production; export KDB_NAME=KDB-Prod; cpl start;",

2
kdb-bot/pyproject.toml Normal file
View File

@ -0,0 +1,2 @@
[tool.black]
line-length = 120

View File

@ -23,18 +23,12 @@ class Application(DiscordBotApplicationABC):
self._logger: LoggerABC = services.get_service(LoggerABC) self._logger: LoggerABC = services.get_service(LoggerABC)
# cpl-discord # cpl-discord
self._bot: DiscordBotServiceABC = services.get_service(DiscordBotServiceABC) self._bot: DiscordBotServiceABC = services.get_service(DiscordBotServiceABC)
self._bot_settings: DiscordBotSettings = config.get_configuration( self._bot_settings: DiscordBotSettings = config.get_configuration(DiscordBotSettings)
DiscordBotSettings
)
# cpl-translation # cpl-translation
self._translation: TranslationServiceABC = services.get_service( self._translation: TranslationServiceABC = services.get_service(TranslationServiceABC)
TranslationServiceABC
)
self._t: TranslatePipe = services.get_service(TranslatePipe) self._t: TranslatePipe = services.get_service(TranslatePipe)
self._feature_flags: FeatureFlagsSettings = config.get_configuration( self._feature_flags: FeatureFlagsSettings = config.get_configuration(FeatureFlagsSettings)
FeatureFlagsSettings
)
# api # api
if self._feature_flags.get_flag(FeatureFlagsEnum.api_module): if self._feature_flags.get_flag(FeatureFlagsEnum.api_module):
@ -43,9 +37,7 @@ class Application(DiscordBotApplicationABC):
self._is_stopping = False self._is_stopping = False
async def configure(self): async def configure(self):
self._translation.load_by_settings( self._translation.load_by_settings(self._configuration.get_configuration(TranslationSettings))
self._configuration.get_configuration(TranslationSettings)
)
async def main(self): async def main(self):
try: try:
@ -81,8 +73,4 @@ class Application(DiscordBotApplicationABC):
Console.write_line() Console.write_line()
def is_restart(self): def is_restart(self):
return ( return True if self._configuration.get_configuration("IS_RESTART") == "true" else False #
True
if self._configuration.get_configuration("IS_RESTART") == "true"
else False
) #

View File

@ -13,6 +13,4 @@ class InitBotExtension(ApplicationExtensionABC):
async def run(self, config: ConfigurationABC, services: ServiceProviderABC): async def run(self, config: ConfigurationABC, services: ServiceProviderABC):
settings = config.get_configuration(BotSettings) settings = config.get_configuration(BotSettings)
bot: DiscordBotServiceABC = services.get_service( bot: DiscordBotServiceABC = services.get_service(DiscordBotServiceABC, max_messages=settings.cache_max_messages)
DiscordBotServiceABC, max_messages=settings.cache_max_messages
)

View File

@ -48,9 +48,7 @@ class Startup(StartupABC):
services.add_singleton(CustomFileLoggerABC, ApiLogger) services.add_singleton(CustomFileLoggerABC, ApiLogger)
services.add_translation() services.add_translation()
services.add_db_context( services.add_db_context(DBContext, self._config.get_configuration(DatabaseSettings))
DBContext, self._config.get_configuration(DatabaseSettings)
)
provider = services.build_service_provider() provider = services.build_service_provider()
# instantiate custom logger # instantiate custom logger

View File

@ -9,13 +9,9 @@ class StartupDiscordExtension(StartupExtensionABC):
def __init__(self): def __init__(self):
pass pass
def configure_configuration( def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
):
pass pass
def configure_services( def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
):
services.add_discord() services.add_discord()
dcc = get_discord_collection(services) dcc = get_discord_collection(services)

View File

@ -20,25 +20,15 @@ class StartupMigrationExtension(StartupExtensionABC):
def __init__(self): def __init__(self):
pass pass
def configure_configuration( def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
):
pass pass
def configure_services( def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
):
services.add_transient(MigrationService) services.add_transient(MigrationService)
services.add_transient(MigrationABC, InitialMigration) services.add_transient(MigrationABC, InitialMigration)
services.add_transient( services.add_transient(MigrationABC, AutoRoleMigration) # 03.10.2022 #54 - 0.2.2
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, ApiMigration) # 15.10.2022 #70 - 0.3.0
services.add_transient(MigrationABC, LevelMigration) # 06.11.2022 #25 - 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, StatsMigration) # 09.11.2022 #46 - 0.3.0
services.add_transient( services.add_transient(MigrationABC, AutoRoleFix1Migration) # 30.12.2022 #151 - 0.3.0
MigrationABC, AutoRoleFix1Migration services.add_transient(MigrationABC, UserMessageCountPerHourMigration) # 11.01.2023 #168 - 0.3.1
) # 30.12.2022 #151 - 0.3.0
services.add_transient(
MigrationABC, UserMessageCountPerHourMigration
) # 11.01.2023 #168 - 0.3.1

View File

@ -18,15 +18,11 @@ class StartupModuleExtension(StartupExtensionABC):
self._modules = ModuleList.get_modules() self._modules = ModuleList.get_modules()
def configure_configuration( def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
):
self._config = config self._config = config
self._feature_flags = config.get_configuration(FeatureFlagsSettings) self._feature_flags = config.get_configuration(FeatureFlagsSettings)
def configure_services( def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
):
provider = services.build_service_provider() provider = services.build_service_provider()
dc_collection: DiscordCollectionABC = provider.get_service(DiscordCollectionABC) dc_collection: DiscordCollectionABC = provider.get_service(DiscordCollectionABC)

View File

@ -19,43 +19,25 @@ class StartupSettingsExtension(StartupExtensionABC):
def __init__(self): def __init__(self):
self._start_time = datetime.now() self._start_time = datetime.now()
def configure_configuration( def configure_configuration(self, configuration: ConfigurationABC, environment: ApplicationEnvironmentABC):
self, configuration: ConfigurationABC, environment: ApplicationEnvironmentABC
):
# this shit has to be done here because we need settings in subsequent startup extensions # 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__))) environment.set_working_directory(os.path.dirname(os.path.realpath(__file__)))
configuration.add_environment_variables("KDB_") configuration.add_environment_variables("KDB_")
configuration.add_environment_variables("DISCORD_") configuration.add_environment_variables("DISCORD_")
configuration.add_json_file(f"config/appsettings.json", optional=False) configuration.add_json_file(f"config/appsettings.json", optional=False)
configuration.add_json_file( configuration.add_json_file(f"config/appsettings.{environment.environment_name}.json", optional=True)
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.host_name}.json", optional=True
)
# load feature-flags # load feature-flags
configuration.add_json_file(f"config/feature-flags.json", optional=False) configuration.add_json_file(f"config/feature-flags.json", optional=False)
configuration.add_json_file( configuration.add_json_file(f"config/feature-flags.{environment.environment_name}.json", optional=True)
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.host_name}.json", optional=True
)
configuration.add_configuration("Startup_StartTime", str(self._start_time)) configuration.add_configuration("Startup_StartTime", str(self._start_time))
self._configure_settings_with_sub_settings( self._configure_settings_with_sub_settings(configuration, BotSettings, lambda x: x.servers, lambda x: x.id)
configuration, BotSettings, lambda x: x.servers, lambda x: x.id self._configure_settings_with_sub_settings(configuration, BaseSettings, lambda x: x.servers, lambda x: x.id)
) self._configure_settings_with_sub_settings(configuration, BootLogSettings, lambda x: x.servers, lambda x: x.id)
self._configure_settings_with_sub_settings( self._configure_settings_with_sub_settings(configuration, LevelSettings, lambda x: x.servers, lambda x: x.id)
configuration, BaseSettings, lambda x: x.servers, lambda x: x.id
)
self._configure_settings_with_sub_settings(
configuration, BootLogSettings, lambda x: x.servers, lambda x: x.id
)
self._configure_settings_with_sub_settings(
configuration, LevelSettings, lambda x: x.servers, lambda x: x.id
)
self._configure_settings_with_sub_settings( self._configure_settings_with_sub_settings(
configuration, PermissionSettings, lambda x: x.servers, lambda x: x.id configuration, PermissionSettings, lambda x: x.servers, lambda x: x.id
) )
@ -63,9 +45,7 @@ class StartupSettingsExtension(StartupExtensionABC):
configuration, BotLoggingSettings, lambda x: x.files, lambda x: x.key configuration, BotLoggingSettings, lambda x: x.files, lambda x: x.key
) )
def configure_services( def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
):
pass pass
@staticmethod @staticmethod
@ -77,6 +57,4 @@ class StartupSettingsExtension(StartupExtensionABC):
return return
for sub_settings in list_atr(settings): for sub_settings in list_atr(settings):
config.add_configuration( config.add_configuration(f"{type(sub_settings).__name__}_{atr(sub_settings)}", sub_settings)
f"{type(sub_settings).__name__}_{atr(sub_settings)}", sub_settings
)

View File

@ -40,15 +40,11 @@ class AuthServiceABC(ABC):
pass pass
@abstractmethod @abstractmethod
async def get_filtered_auth_users_async( async def get_filtered_auth_users_async(self, criteria: AuthUserSelectCriteria) -> AuthUserFilteredResultDTO:
self, criteria: AuthUserSelectCriteria
) -> AuthUserFilteredResultDTO:
pass pass
@abstractmethod @abstractmethod
async def get_auth_user_by_email_async( async def get_auth_user_by_email_async(self, email: str, with_password: bool = False) -> AuthUserDTO:
self, email: str, with_password: bool = False
) -> AuthUserDTO:
pass pass
@abstractmethod @abstractmethod
@ -64,9 +60,7 @@ class AuthServiceABC(ABC):
pass pass
@abstractmethod @abstractmethod
async def add_auth_user_by_discord_async( async def add_auth_user_by_discord_async(self, user_dto: AuthUserDTO, dc_id: int) -> OAuthDTO:
self, user_dto: AuthUserDTO, dc_id: int
) -> OAuthDTO:
pass pass
@abstractmethod @abstractmethod

View File

@ -3,9 +3,7 @@ from abc import ABC, abstractmethod
class SelectCriteriaABC(ABC): class SelectCriteriaABC(ABC):
@abstractmethod @abstractmethod
def __init__( def __init__(self, page_index: int, page_size: int, sort_direction: str, sort_column: str):
self, page_index: int, page_size: int, sort_direction: str, sort_column: str
):
self.page_index = page_index self.page_index = page_index
self.page_size = page_size self.page_size = page_size
self.sort_direction = sort_direction self.sort_direction = sort_direction

View File

@ -140,9 +140,7 @@ class Api(Flask):
data = request.get_data() data = request.get_data()
data = "" if len(data) == 0 else str(data.decode(encoding="utf-8")) data = "" if len(data) == 0 else str(data.decode(encoding="utf-8"))
text = textwrap.dedent( text = textwrap.dedent(f"Request: {request_id}:\n\tHeader:\n\t\t{headers}\n\tResponse: {data}")
f"Request: {request_id}:\n\tHeader:\n\t\t{headers}\n\tResponse: {data}"
)
self._logger.trace(__name__, text) self._logger.trace(__name__, text)
return response return response

View File

@ -26,21 +26,15 @@ class ApiModule(ModuleABC):
def __init__(self, dc: DiscordCollectionABC): def __init__(self, dc: DiscordCollectionABC):
ModuleABC.__init__(self, dc, FeatureFlagsEnum.api_module) ModuleABC.__init__(self, dc, FeatureFlagsEnum.api_module)
def configure_configuration( def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
):
cwd = env.working_directory cwd = env.working_directory
env.set_working_directory(os.path.dirname(os.path.realpath(__file__))) 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.json", optional=False)
config.add_json_file( config.add_json_file(f"config/apisettings.{env.environment_name}.json", optional=True)
f"config/apisettings.{env.environment_name}.json", optional=True
)
config.add_json_file(f"config/apisettings.{env.host_name}.json", optional=True) config.add_json_file(f"config/apisettings.{env.host_name}.json", optional=True)
env.set_working_directory(cwd) env.set_working_directory(cwd)
def configure_services( def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
):
services.add_singleton(EMailClientABC, EMailClient) services.add_singleton(EMailClientABC, EMailClient)
services.add_singleton(ApiThread) services.add_singleton(ApiThread)

View File

@ -15,15 +15,11 @@ class AppApiExtension(ApplicationExtensionABC):
ApplicationExtensionABC.__init__(self) ApplicationExtensionABC.__init__(self)
async def run(self, config: ConfigurationABC, services: ServiceProviderABC): async def run(self, config: ConfigurationABC, services: ServiceProviderABC):
feature_flags: FeatureFlagsSettings = config.get_configuration( feature_flags: FeatureFlagsSettings = config.get_configuration(FeatureFlagsSettings)
FeatureFlagsSettings
)
if not feature_flags.get_flag(FeatureFlagsEnum.api_module): if not feature_flags.get_flag(FeatureFlagsEnum.api_module):
return return
auth_settings: AuthenticationSettings = config.get_configuration( auth_settings: AuthenticationSettings = config.get_configuration(AuthenticationSettings)
AuthenticationSettings
)
auth_users: AuthUserRepositoryABC = services.get_service(AuthUserRepositoryABC) auth_users: AuthUserRepositoryABC = services.get_service(AuthUserRepositoryABC)
auth: AuthServiceABC = services.get_service(AuthServiceABC) auth: AuthServiceABC = services.get_service(AuthServiceABC)
Route.init_authorize(auth_users, auth) Route.init_authorize(auth_users, auth)

View File

@ -30,9 +30,5 @@ class ApiSettings(ConfigurationModelABC):
self._host = settings["Host"] self._host = settings["Host"]
self._redirect_to_https = bool(settings["RedirectToHTTPS"]) self._redirect_to_https = bool(settings["RedirectToHTTPS"])
except Exception as e: except Exception as e:
Console.error( Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings" Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
)
Console.error(
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
)

View File

@ -43,9 +43,5 @@ class AuthenticationSettings(ConfigurationModelABC):
self._token_expire_time = int(settings["TokenExpireTime"]) self._token_expire_time = int(settings["TokenExpireTime"])
self._refresh_token_expire_time = int(settings["RefreshTokenExpireTime"]) self._refresh_token_expire_time = int(settings["RefreshTokenExpireTime"])
except Exception as e: except Exception as e:
Console.error( Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings" Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
)
Console.error(
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
)

View File

@ -43,9 +43,5 @@ class DiscordAuthenticationSettings(ConfigurationModelABC):
self._token_url = settings["TokenURL"] self._token_url = settings["TokenURL"]
self._auth_url = settings["AuthURL"] self._auth_url = settings["AuthURL"]
except Exception as e: except Exception as e:
Console.error( Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings" Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
)
Console.error(
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
)

View File

@ -18,9 +18,5 @@ class FrontendSettings(ConfigurationModelABC):
try: try:
self._url = settings["URL"] self._url = settings["URL"]
except Exception as e: except Exception as e:
Console.error( Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings" Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
)
Console.error(
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
)

View File

@ -72,9 +72,7 @@ class AuthController:
@Route.post(f"{BasePath}/register") @Route.post(f"{BasePath}/register")
async def register(self): async def register(self):
dto: AuthUserDTO = JSONProcessor.process( dto: AuthUserDTO = JSONProcessor.process(AuthUserDTO, request.get_json(force=True, silent=True))
AuthUserDTO, request.get_json(force=True, silent=True)
)
await self._auth_service.add_auth_user_async(dto) await self._auth_service.add_auth_user_async(dto)
return "", 200 return "", 200
@ -85,9 +83,7 @@ class AuthController:
@Route.post(f"{BasePath}/login") @Route.post(f"{BasePath}/login")
async def login(self) -> Response: async def login(self) -> Response:
dto: AuthUserDTO = JSONProcessor.process( dto: AuthUserDTO = JSONProcessor.process(AuthUserDTO, request.get_json(force=True, silent=True))
AuthUserDTO, request.get_json(force=True, silent=True)
)
result = await self._auth_service.login_async(dto) result = await self._auth_service.login_async(dto)
return jsonify(result.to_dict()) return jsonify(result.to_dict())
@ -116,53 +112,41 @@ class AuthController:
@Route.post(f"{BasePath}/reset-password") @Route.post(f"{BasePath}/reset-password")
async def reset_password(self): async def reset_password(self):
dto: ResetPasswordDTO = JSONProcessor.process( dto: ResetPasswordDTO = JSONProcessor.process(ResetPasswordDTO, request.get_json(force=True, silent=True))
ResetPasswordDTO, request.get_json(force=True, silent=True)
)
await self._auth_service.reset_password_async(dto) await self._auth_service.reset_password_async(dto)
return "", 200 return "", 200
@Route.post(f"{BasePath}/update-user") @Route.post(f"{BasePath}/update-user")
@Route.authorize @Route.authorize
async def update_user(self): async def update_user(self):
dto: UpdateAuthUserDTO = JSONProcessor.process( dto: UpdateAuthUserDTO = JSONProcessor.process(UpdateAuthUserDTO, request.get_json(force=True, silent=True))
UpdateAuthUserDTO, request.get_json(force=True, silent=True)
)
await self._auth_service.update_user_async(dto) await self._auth_service.update_user_async(dto)
return "", 200 return "", 200
@Route.post(f"{BasePath}/update-user-as-admin") @Route.post(f"{BasePath}/update-user-as-admin")
@Route.authorize(role=AuthRoleEnum.admin) @Route.authorize(role=AuthRoleEnum.admin)
async def update_user_as_admin(self): async def update_user_as_admin(self):
dto: UpdateAuthUserDTO = JSONProcessor.process( dto: UpdateAuthUserDTO = JSONProcessor.process(UpdateAuthUserDTO, request.get_json(force=True, silent=True))
UpdateAuthUserDTO, request.get_json(force=True, silent=True)
)
await self._auth_service.update_user_as_admin_async(dto) await self._auth_service.update_user_as_admin_async(dto)
return "", 200 return "", 200
@Route.post(f"{BasePath}/refresh") @Route.post(f"{BasePath}/refresh")
@Route.authorize @Route.authorize
async def refresh(self) -> Response: async def refresh(self) -> Response:
dto: TokenDTO = JSONProcessor.process( dto: TokenDTO = JSONProcessor.process(TokenDTO, request.get_json(force=True, silent=True))
TokenDTO, request.get_json(force=True, silent=True)
)
result = await self._auth_service.refresh_async(dto) result = await self._auth_service.refresh_async(dto)
return jsonify(result.to_dict()) return jsonify(result.to_dict())
@Route.post(f"{BasePath}/revoke") @Route.post(f"{BasePath}/revoke")
async def revoke(self): async def revoke(self):
dto: TokenDTO = JSONProcessor.process( dto: TokenDTO = JSONProcessor.process(TokenDTO, request.get_json(force=True, silent=True))
TokenDTO, request.get_json(force=True, silent=True)
)
await self._auth_service.revoke_async(dto) await self._auth_service.revoke_async(dto)
return "", 200 return "", 200
@Route.post(f"{BasePath}/delete-user") @Route.post(f"{BasePath}/delete-user")
@Route.authorize(role=AuthRoleEnum.admin) @Route.authorize(role=AuthRoleEnum.admin)
async def delete_user(self): async def delete_user(self):
dto: AuthUserDTO = JSONProcessor.process( dto: AuthUserDTO = JSONProcessor.process(AuthUserDTO, request.get_json(force=True, silent=True))
AuthUserDTO, request.get_json(force=True, silent=True)
)
await self._auth_service.delete_auth_user_async(dto) await self._auth_service.delete_auth_user_async(dto)
return "", 200 return "", 200

View File

@ -13,9 +13,7 @@ class AuthUserSelectCriteria(SelectCriteriaABC):
email: str, email: str,
auth_role: int, auth_role: int,
): ):
SelectCriteriaABC.__init__( SelectCriteriaABC.__init__(self, page_index, page_size, sort_direction, sort_column)
self, page_index, page_size, sort_direction, sort_column
)
self.first_name = first_name self.first_name = first_name
self.last_name = last_name self.last_name = last_name

View File

@ -10,8 +10,6 @@ class ServerSelectCriteria(SelectCriteriaABC):
sort_column: str, sort_column: str,
name: str, name: str,
): ):
SelectCriteriaABC.__init__( SelectCriteriaABC.__init__(self, page_index, page_size, sort_direction, sort_column)
self, page_index, page_size, sort_direction, sort_column
)
self.name = name self.name = name

View File

@ -11,9 +11,7 @@ class ErrorDTO(DtoABC):
def __init__(self, error_code: Optional[ServiceErrorCode], message: str): def __init__(self, error_code: Optional[ServiceErrorCode], message: str):
DtoABC.__init__(self) DtoABC.__init__(self)
self._error_code = ( self._error_code = ServiceErrorCode.Unknown if error_code is None else error_code
ServiceErrorCode.Unknown if error_code is None else error_code
)
self._message = message self._message = message
@property @property

View File

@ -34,9 +34,7 @@ class UpdateAuthUserDTO(DtoABC):
def from_dict(self, values: dict): def from_dict(self, values: dict):
self._auth_user = AuthUserDTO().from_dict(values["authUser"]) self._auth_user = AuthUserDTO().from_dict(values["authUser"])
self._new_auth_user = AuthUserDTO().from_dict(values["newAuthUser"]) self._new_auth_user = AuthUserDTO().from_dict(values["newAuthUser"])
self._change_password = ( self._change_password = False if "changePassword" not in values else bool(values["changePassword"])
False if "changePassword" not in values else bool(values["changePassword"])
)
def to_dict(self) -> dict: def to_dict(self) -> dict:
return { return {

View File

@ -42,9 +42,7 @@ class Route:
return jsonify(error.to_dict()), 401 return jsonify(error.to_dict()), 401
if cls._auth_users is None or cls._auth is None: if cls._auth_users is None or cls._auth is None:
ex = ServiceException( ex = ServiceException(ServiceErrorCode.Unauthorized, f"Authorize is not initialized")
ServiceErrorCode.Unauthorized, f"Authorize is not initialized"
)
error = ErrorDTO(ex.error_code, ex.message) error = ErrorDTO(ex.error_code, ex.message)
return jsonify(error.to_dict()), 401 return jsonify(error.to_dict()), 401
@ -66,9 +64,7 @@ class Route:
return jsonify(error.to_dict()), 401 return jsonify(error.to_dict()), 401
if role is not None and user.auth_role.value < role.value: if role is not None and user.auth_role.value < role.value:
ex = ServiceException( ex = ServiceException(ServiceErrorCode.Unauthorized, f"Role {role} required")
ServiceErrorCode.Unauthorized, f"Role {role} required"
)
error = ErrorDTO(ex.error_code, ex.message) error = ErrorDTO(ex.error_code, ex.message)
return jsonify(error.to_dict()), 403 return jsonify(error.to_dict()), 403

View File

@ -88,8 +88,7 @@ class AuthService(AuthServiceABC):
"user_id": user.id, "user_id": user.id,
"email": user.email, "email": user.email,
"role": user.auth_role.value, "role": user.auth_role.value,
"exp": datetime.now(tz=timezone.utc) "exp": datetime.now(tz=timezone.utc) + timedelta(days=self._auth_settings.token_expire_time),
+ timedelta(days=self._auth_settings.token_expire_time),
"iss": self._auth_settings.issuer, "iss": self._auth_settings.issuer,
"aud": self._auth_settings.audience, "aud": self._auth_settings.audience,
}, },
@ -145,9 +144,7 @@ class AuthService(AuthServiceABC):
def _create_and_save_refresh_token(self, user: AuthUser) -> str: def _create_and_save_refresh_token(self, user: AuthUser) -> str:
token = str(uuid.uuid4()) token = str(uuid.uuid4())
user.refresh_token = token user.refresh_token = token
user.refresh_token_expire_time = datetime.now() + timedelta( user.refresh_token_expire_time = datetime.now() + timedelta(days=self._auth_settings.refresh_token_expire_time)
days=self._auth_settings.refresh_token_expire_time
)
self._auth_users.update_auth_user(user) self._auth_users.update_auth_user(user)
self._db.save_changes() self._db.save_changes()
return token return token
@ -180,12 +177,8 @@ class AuthService(AuthServiceABC):
self._send_link_mail( self._send_link_mail(
user.email, user.email,
self._t.transform("api.auth.confirmation.subject").format( self._t.transform("api.auth.confirmation.subject").format(user.first_name, user.last_name),
user.first_name, user.last_name self._t.transform("api.auth.confirmation.message").format(url, user.confirmation_id),
),
self._t.transform("api.auth.confirmation.message").format(
url, user.confirmation_id
),
) )
def _send_forgot_password_id_to_user(self, user: AuthUser): def _send_forgot_password_id_to_user(self, user: AuthUser):
@ -195,38 +188,28 @@ class AuthService(AuthServiceABC):
self._send_link_mail( self._send_link_mail(
user.email, user.email,
self._t.transform("api.auth.forgot_password.subject").format( self._t.transform("api.auth.forgot_password.subject").format(user.first_name, user.last_name),
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.message").format(
url, user.forgot_password_id
),
) )
async def get_all_auth_users_async(self) -> List[AuthUserDTO]: 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)) result = self._auth_users.get_all_auth_users().select(lambda x: AUT.to_dto(x))
return List(AuthUserDTO, result) return List(AuthUserDTO, result)
async def get_filtered_auth_users_async( async def get_filtered_auth_users_async(self, criteria: AuthUserSelectCriteria) -> AuthUserFilteredResultDTO:
self, criteria: AuthUserSelectCriteria
) -> AuthUserFilteredResultDTO:
users = self._auth_users.get_filtered_auth_users(criteria) users = self._auth_users.get_filtered_auth_users(criteria)
result = users.result.select(lambda x: AUT.to_dto(x)) result = users.result.select(lambda x: AUT.to_dto(x))
return AuthUserFilteredResultDTO(List(AuthUserDTO, result), users.total_count) return AuthUserFilteredResultDTO(List(AuthUserDTO, result), users.total_count)
async def get_auth_user_by_email_async( async def get_auth_user_by_email_async(self, email: str, with_password: bool = False) -> AuthUserDTO:
self, email: str, with_password: bool = False
) -> AuthUserDTO:
try: try:
# todo: check if logged in user is admin then send mail # todo: check if logged in user is admin then send mail
user = self._auth_users.get_auth_user_by_email(email) user = self._auth_users.get_auth_user_by_email(email)
return AUT.to_dto(user, password=user.password if with_password else None) return AUT.to_dto(user, password=user.password if with_password else None)
except Exception as e: except Exception as e:
self._logger.error(__name__, f"AuthUser not found", e) self._logger.error(__name__, f"AuthUser not found", e)
raise ServiceException( raise ServiceException(ServiceErrorCode.InvalidData, f"User not found {email}")
ServiceErrorCode.InvalidData, f"User not found {email}"
)
async def find_auth_user_by_email_async(self, email: str) -> Optional[AuthUser]: async def find_auth_user_by_email_async(self, email: str) -> Optional[AuthUser]:
user = self._auth_users.find_auth_user_by_email(email) user = self._auth_users.find_auth_user_by_email(email)
@ -244,22 +227,16 @@ class AuthService(AuthServiceABC):
user.password_salt = uuid.uuid4() user.password_salt = uuid.uuid4()
user.password = self._hash_sha256(user_dto.password, user.password_salt) user.password = self._hash_sha256(user_dto.password, user.password_salt)
if not self._is_email_valid(user.email): if not self._is_email_valid(user.email):
raise ServiceException( raise ServiceException(ServiceErrorCode.InvalidData, "Invalid E-Mail address")
ServiceErrorCode.InvalidData, "Invalid E-Mail address"
)
try: try:
user.confirmation_id = uuid.uuid4() user.confirmation_id = uuid.uuid4()
self._auth_users.add_auth_user(user) self._auth_users.add_auth_user(user)
self._send_confirmation_id_to_user(user) self._send_confirmation_id_to_user(user)
self._db.save_changes() self._db.save_changes()
self._logger.info( self._logger.info(__name__, f"Added auth user with E-Mail: {user_dto.email}")
__name__, f"Added auth user with E-Mail: {user_dto.email}"
)
except Exception as e: except Exception as e:
self._logger.error( self._logger.error(__name__, f"Cannot add user with E-Mail {user_dto.email}", e)
__name__, f"Cannot add user with E-Mail {user_dto.email}", e
)
raise ServiceException(ServiceErrorCode.UnableToAdd, "Invalid E-Mail") raise ServiceException(ServiceErrorCode.UnableToAdd, "Invalid E-Mail")
async def add_auth_user_by_oauth_async(self, dto: OAuthDTO): async def add_auth_user_by_oauth_async(self, dto: OAuthDTO):
@ -275,27 +252,19 @@ class AuthService(AuthServiceABC):
db_user.first_name = dto.user.first_name db_user.first_name = dto.user.first_name
db_user.last_name = dto.user.last_name db_user.last_name = dto.user.last_name
db_user.password_salt = uuid.uuid4() db_user.password_salt = uuid.uuid4()
db_user.password = self._hash_sha256( db_user.password = self._hash_sha256(dto.user.password, db_user.password_salt)
dto.user.password, db_user.password_salt
)
db_user.oauth_id = None db_user.oauth_id = None
db_user.confirmation_id = uuid.uuid4() db_user.confirmation_id = uuid.uuid4()
self._send_confirmation_id_to_user(db_user) self._send_confirmation_id_to_user(db_user)
self._auth_users.update_auth_user(db_user) self._auth_users.update_auth_user(db_user)
self._logger.info( self._logger.info(__name__, f"Added auth user with E-Mail: {dto.user.email}")
__name__, f"Added auth user with E-Mail: {dto.user.email}"
)
except Exception as e: except Exception as e:
self._logger.error( self._logger.error(__name__, f"Cannot add user with E-Mail {dto.user.email}", e)
__name__, f"Cannot add user with E-Mail {dto.user.email}", e
)
raise ServiceException(ServiceErrorCode.UnableToAdd, "Invalid E-Mail") raise ServiceException(ServiceErrorCode.UnableToAdd, "Invalid E-Mail")
self._db.save_changes() self._db.save_changes()
async def add_auth_user_by_discord_async( async def add_auth_user_by_discord_async(self, user_dto: AuthUserDTO, dc_id: int) -> OAuthDTO:
self, user_dto: AuthUserDTO, dc_id: int
) -> OAuthDTO:
db_auth_user = self._auth_users.find_auth_user_by_email(user_dto.email) db_auth_user = self._auth_users.find_auth_user_by_email(user_dto.email)
# user exists # user exists
@ -306,9 +275,7 @@ class AuthService(AuthServiceABC):
# user exists but discord user id not set # user exists but discord user id not set
elif db_auth_user is not None and db_auth_user.users.count() == 0: elif db_auth_user is not None and db_auth_user.users.count() == 0:
self._logger.debug( self._logger.debug(__name__, f"Auth user exists but not linked with discord")
__name__, f"Auth user exists but not linked with discord"
)
# users = self._users.get_users_by_discord_id(user_dto.user_id) # users = self._users.get_users_by_discord_id(user_dto.user_id)
# add auth_user to user refs # add auth_user to user refs
db_auth_user.oauth_id = None db_auth_user.oauth_id = None
@ -317,11 +284,7 @@ class AuthService(AuthServiceABC):
# user does not exists # user does not exists
self._logger.debug(__name__, f"Auth user does not exist") self._logger.debug(__name__, f"Auth user does not exist")
try: try:
user_dto.user_id = ( user_dto.user_id = self._users.get_users_by_discord_id(user_dto.user_id).single().user_id
self._users.get_users_by_discord_id(user_dto.user_id)
.single()
.user_id
)
except Exception as e: except Exception as e:
self._logger.error(__name__, f"User not found") self._logger.error(__name__, f"User not found")
user_dto.user_id = None user_dto.user_id = None
@ -340,9 +303,7 @@ class AuthService(AuthServiceABC):
for user in users: for user in users:
if user.server.server_id != server.server_id: if user.server.server_id != server.server_id:
continue continue
self._auth_users.add_auth_user_user_rel( self._auth_users.add_auth_user_user_rel(AuthUserUsersRelation(db_auth_user, user))
AuthUserUsersRelation(db_auth_user, user)
)
self._auth_users.update_auth_user(db_auth_user) self._auth_users.update_auth_user(db_auth_user)
self._db.save_changes() self._db.save_changes()
@ -353,16 +314,14 @@ class AuthService(AuthServiceABC):
raise ServiceException(ServiceErrorCode.InvalidData, f"User is empty") raise ServiceException(ServiceErrorCode.InvalidData, f"User is empty")
if update_user_dto.auth_user is None: if update_user_dto.auth_user is None:
raise ServiceException( raise ServiceException(ServiceErrorCode.InvalidData, f"Existing user is empty")
ServiceErrorCode.InvalidData, f"Existing user is empty"
)
if update_user_dto.new_auth_user is None: if update_user_dto.new_auth_user is None:
raise ServiceException(ServiceErrorCode.InvalidData, f"New user is empty") raise ServiceException(ServiceErrorCode.InvalidData, f"New user is empty")
if not self._is_email_valid( if not self._is_email_valid(update_user_dto.auth_user.email) or not self._is_email_valid(
update_user_dto.auth_user.email update_user_dto.new_auth_user.email
) or not self._is_email_valid(update_user_dto.new_auth_user.email): ):
raise ServiceException(ServiceErrorCode.InvalidData, f"Invalid E-Mail") raise ServiceException(ServiceErrorCode.InvalidData, f"Invalid E-Mail")
user = self._auth_users.find_auth_user_by_email(update_user_dto.auth_user.email) user = self._auth_users.find_auth_user_by_email(update_user_dto.auth_user.email)
@ -375,8 +334,7 @@ class AuthService(AuthServiceABC):
# update first name # update first name
if ( if (
update_user_dto.new_auth_user.first_name is not None update_user_dto.new_auth_user.first_name is not None
and update_user_dto.auth_user.first_name and update_user_dto.auth_user.first_name != update_user_dto.new_auth_user.first_name
!= update_user_dto.new_auth_user.first_name
): ):
user.first_name = update_user_dto.new_auth_user.first_name user.first_name = update_user_dto.new_auth_user.first_name
@ -384,8 +342,7 @@ class AuthService(AuthServiceABC):
if ( if (
update_user_dto.new_auth_user.last_name is not None update_user_dto.new_auth_user.last_name is not None
and update_user_dto.new_auth_user.last_name != "" and update_user_dto.new_auth_user.last_name != ""
and update_user_dto.auth_user.last_name and update_user_dto.auth_user.last_name != update_user_dto.new_auth_user.last_name
!= update_user_dto.new_auth_user.last_name
): ):
user.last_name = update_user_dto.new_auth_user.last_name user.last_name = update_user_dto.new_auth_user.last_name
@ -395,33 +352,22 @@ class AuthService(AuthServiceABC):
and update_user_dto.new_auth_user.email != "" and update_user_dto.new_auth_user.email != ""
and update_user_dto.auth_user.email != 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( user_by_new_e_mail = self._auth_users.find_auth_user_by_email(update_user_dto.new_auth_user.email)
update_user_dto.new_auth_user.email
)
if user_by_new_e_mail is not None: if user_by_new_e_mail is not None:
raise ServiceException( raise ServiceException(ServiceErrorCode.InvalidUser, "User already exists")
ServiceErrorCode.InvalidUser, "User already exists"
)
user.email = update_user_dto.new_auth_user.email user.email = update_user_dto.new_auth_user.email
update_user_dto.auth_user.password = self._hash_sha256( update_user_dto.auth_user.password = self._hash_sha256(update_user_dto.auth_user.password, user.password_salt)
update_user_dto.auth_user.password, user.password_salt
)
if update_user_dto.auth_user.password != user.password: if update_user_dto.auth_user.password != user.password:
raise ServiceException(ServiceErrorCode.InvalidUser, "Wrong password") raise ServiceException(ServiceErrorCode.InvalidUser, "Wrong password")
# update password # update password
if ( if (
update_user_dto.new_auth_user.password is not None update_user_dto.new_auth_user.password is not None
and self._hash_sha256( and self._hash_sha256(update_user_dto.new_auth_user.password, user.password_salt) != user.password
update_user_dto.new_auth_user.password, user.password_salt
)
!= user.password
): ):
user.password_salt = uuid.uuid4() user.password_salt = uuid.uuid4()
user.password = self._hash_sha256( user.password = self._hash_sha256(update_user_dto.new_auth_user.password, user.password_salt)
update_user_dto.new_auth_user.password, user.password_salt
)
self._auth_users.update_auth_user(user) self._auth_users.update_auth_user(user)
self._db.save_changes() self._db.save_changes()
@ -431,31 +377,23 @@ class AuthService(AuthServiceABC):
raise ServiceException(ServiceErrorCode.InvalidData, f"User is empty") raise ServiceException(ServiceErrorCode.InvalidData, f"User is empty")
if update_user_dto.auth_user is None: if update_user_dto.auth_user is None:
raise ServiceException( raise ServiceException(ServiceErrorCode.InvalidData, f"Existing user is empty")
ServiceErrorCode.InvalidData, f"Existing user is empty"
)
if update_user_dto.new_auth_user is None: if update_user_dto.new_auth_user is None:
raise ServiceException(ServiceErrorCode.InvalidData, f"New user is empty") raise ServiceException(ServiceErrorCode.InvalidData, f"New user is empty")
if not self._is_email_valid( if not self._is_email_valid(update_user_dto.auth_user.email) or not self._is_email_valid(
update_user_dto.auth_user.email update_user_dto.new_auth_user.email
) or not self._is_email_valid(update_user_dto.new_auth_user.email): ):
raise ServiceException(ServiceErrorCode.InvalidData, f"Invalid E-Mail") raise ServiceException(ServiceErrorCode.InvalidData, f"Invalid E-Mail")
user = self._auth_users.find_auth_user_by_email(update_user_dto.auth_user.email) user = self._auth_users.find_auth_user_by_email(update_user_dto.auth_user.email)
if user is None: if user is None:
raise ServiceException(ServiceErrorCode.InvalidUser, "User not found") raise ServiceException(ServiceErrorCode.InvalidUser, "User not found")
if ( if user.confirmation_id is not None and update_user_dto.new_auth_user.is_confirmed:
user.confirmation_id is not None
and update_user_dto.new_auth_user.is_confirmed
):
user.confirmation_id = None user.confirmation_id = None
elif ( elif user.confirmation_id is None and not update_user_dto.new_auth_user.is_confirmed:
user.confirmation_id is None
and not update_user_dto.new_auth_user.is_confirmed
):
user.confirmation_id = uuid.uuid4() user.confirmation_id = uuid.uuid4()
# else # else
# raise ServiceException(ServiceErrorCode.InvalidUser, 'E-Mail not confirmed') # raise ServiceException(ServiceErrorCode.InvalidUser, 'E-Mail not confirmed')
@ -463,8 +401,7 @@ class AuthService(AuthServiceABC):
# update first name # update first name
if ( if (
update_user_dto.new_auth_user.first_name is not None update_user_dto.new_auth_user.first_name is not None
and update_user_dto.auth_user.first_name and update_user_dto.auth_user.first_name != update_user_dto.new_auth_user.first_name
!= update_user_dto.new_auth_user.first_name
): ):
user.first_name = update_user_dto.new_auth_user.first_name user.first_name = update_user_dto.new_auth_user.first_name
@ -472,8 +409,7 @@ class AuthService(AuthServiceABC):
if ( if (
update_user_dto.new_auth_user.last_name is not None update_user_dto.new_auth_user.last_name is not None
and update_user_dto.new_auth_user.last_name != "" and update_user_dto.new_auth_user.last_name != ""
and update_user_dto.auth_user.last_name and update_user_dto.auth_user.last_name != update_user_dto.new_auth_user.last_name
!= update_user_dto.new_auth_user.last_name
): ):
user.last_name = update_user_dto.new_auth_user.last_name user.last_name = update_user_dto.new_auth_user.last_name
@ -483,28 +419,19 @@ class AuthService(AuthServiceABC):
and update_user_dto.new_auth_user.email != "" and update_user_dto.new_auth_user.email != ""
and update_user_dto.auth_user.email != 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( user_by_new_e_mail = self._auth_users.find_auth_user_by_email(update_user_dto.new_auth_user.email)
update_user_dto.new_auth_user.email
)
if user_by_new_e_mail is not None: if user_by_new_e_mail is not None:
raise ServiceException( raise ServiceException(ServiceErrorCode.InvalidUser, "User already exists")
ServiceErrorCode.InvalidUser, "User already exists"
)
user.email = update_user_dto.new_auth_user.email user.email = update_user_dto.new_auth_user.email
# update password # update password
if ( if (
update_user_dto.new_auth_user.password is not None update_user_dto.new_auth_user.password is not None
and update_user_dto.change_password and update_user_dto.change_password
and user.password and user.password != self._hash_sha256(update_user_dto.new_auth_user.password, user.password_salt)
!= self._hash_sha256(
update_user_dto.new_auth_user.password, user.password_salt
)
): ):
user.password_salt = uuid.uuid4() user.password_salt = uuid.uuid4()
user.password = self._hash_sha256( user.password = self._hash_sha256(update_user_dto.new_auth_user.password, user.password_salt)
update_user_dto.new_auth_user.password, user.password_salt
)
# update role # update role
if ( if (
@ -523,9 +450,7 @@ class AuthService(AuthServiceABC):
self._db.save_changes() self._db.save_changes()
except Exception as e: except Exception as e:
self._logger.error(__name__, f"Cannot delete user", e) self._logger.error(__name__, f"Cannot delete user", e)
raise ServiceException( raise ServiceException(ServiceErrorCode.UnableToDelete, f"Cannot delete user by mail {email}")
ServiceErrorCode.UnableToDelete, f"Cannot delete user by mail {email}"
)
async def delete_auth_user_async(self, user_dto: AuthUser): async def delete_auth_user_async(self, user_dto: AuthUser):
try: try:
@ -608,19 +533,13 @@ class AuthService(AuthServiceABC):
): ):
raise ServiceException(ServiceErrorCode.InvalidData, "Token expired") raise ServiceException(ServiceErrorCode.InvalidData, "Token expired")
return TokenDTO( return TokenDTO(self.generate_token(user), self._create_and_save_refresh_token(user))
self.generate_token(user), self._create_and_save_refresh_token(user)
)
except Exception as e: except Exception as e:
self._logger.error(__name__, f"Refreshing token failed", e) self._logger.error(__name__, f"Refreshing token failed", e)
return TokenDTO("", "") return TokenDTO("", "")
async def revoke_async(self, token_dto: TokenDTO): async def revoke_async(self, token_dto: TokenDTO):
if ( if token_dto is None or token_dto.token is None or token_dto.refresh_token is None:
token_dto is None
or token_dto.token is None
or token_dto.refresh_token is None
):
raise ServiceException(ServiceErrorCode.InvalidData, "Token not set") raise ServiceException(ServiceErrorCode.InvalidData, "Token not set")
try: try:
@ -673,9 +592,7 @@ class AuthService(AuthServiceABC):
) )
if user.confirmation_id is not None: if user.confirmation_id is not None:
raise ServiceException( raise ServiceException(ServiceErrorCode.InvalidUser, f"E-Mail not confirmed")
ServiceErrorCode.InvalidUser, f"E-Mail not confirmed"
)
if user.password is None or rp_dto.password == "": if user.password is None or rp_dto.password == "":
raise ServiceException(ServiceErrorCode.InvalidData, f"Password not set") raise ServiceException(ServiceErrorCode.InvalidData, f"Password not set")

View File

@ -55,17 +55,13 @@ class DiscordService:
if role != AuthRoleEnum.admin: if role != AuthRoleEnum.admin:
auth_user = self._auth_users.find_auth_user_by_email(token["email"]) auth_user = self._auth_users.find_auth_user_by_email(token["email"])
if auth_user is not None: if auth_user is not None:
user_ids = auth_user.users.select( user_ids = auth_user.users.select(lambda x: x.server is not None and x.server.server_id)
lambda x: x.server is not None and x.server.server_id
)
servers = servers.where(lambda x: x.server_id in user_ids) servers = servers.where(lambda x: x.server_id in user_ids)
servers = List(ServerDTO, servers) servers = List(ServerDTO, servers)
return servers.select(self._to_dto).where(lambda x: x.name != "") return servers.select(self._to_dto).where(lambda x: x.name != "")
async def get_filtered_servers_async( async def get_filtered_servers_async(self, criteria: ServerSelectCriteria) -> ServerFilteredResultDTO:
self, criteria: ServerSelectCriteria
) -> ServerFilteredResultDTO:
token = self._auth.get_decoded_token_from_request() token = self._auth.get_decoded_token_from_request()
if token is None or "email" not in token or "role" not in token: if token is None or "email" not in token or "role" not in token:
raise ServiceException(ServiceErrorCode.InvalidData, "Token invalid") raise ServiceException(ServiceErrorCode.InvalidData, "Token invalid")
@ -76,22 +72,15 @@ class DiscordService:
if role != AuthRoleEnum.admin: if role != AuthRoleEnum.admin:
auth_user = self._auth_users.find_auth_user_by_email(token["email"]) auth_user = self._auth_users.find_auth_user_by_email(token["email"])
if auth_user is not None: if auth_user is not None:
user_ids = auth_user.users.select( user_ids = auth_user.users.select(lambda x: x.server is not None and x.server.server_id)
lambda x: x.server is not None and x.server.server_id filtered_result.result = filtered_result.result.where(lambda x: x.server_id in user_ids)
)
filtered_result.result = filtered_result.result.where(
lambda x: x.server_id in user_ids
)
servers: List = filtered_result.result.select(self._to_dto).where( servers: List = filtered_result.result.select(self._to_dto).where(lambda x: x.name != "")
lambda x: x.name != ""
)
result = List(ServerDTO, servers) result = List(ServerDTO, servers)
if criteria.name is not None and criteria.name != "": if criteria.name is not None and criteria.name != "":
result = result.where( result = result.where(
lambda x: criteria.name.lower() in x.name.lower() lambda x: criteria.name.lower() in x.name.lower() or x.name.lower() == criteria.name.lower()
or x.name.lower() == criteria.name.lower()
) )
return ServerFilteredResultDTO(List(ServerDTO, result), servers.count()) return ServerFilteredResultDTO(List(ServerDTO, result), servers.count())
@ -100,7 +89,5 @@ class DiscordService:
server = self._servers.get_server_by_id(id) server = self._servers.get_server_by_id(id)
guild = self._bot.get_guild(server.discord_server_id) guild = self._bot.get_guild(server.discord_server_id)
server_dto = ServerTransformer.to_dto( server_dto = ServerTransformer.to_dto(server, guild.name, guild.member_count, guild.icon)
server, guild.name, guild.member_count, guild.icon
)
return server_dto return server_dto

View File

@ -20,9 +20,7 @@ class AuthUserTransformer(TransformerABC):
None, None,
None, None,
datetime.now(), datetime.now(),
AuthRoleEnum.normal AuthRoleEnum.normal if dto.auth_role is None else AuthRoleEnum(dto.auth_role),
if dto.auth_role is None
else AuthRoleEnum(dto.auth_role),
auth_user_id=0 if dto.id is None else dto.id, auth_user_id=0 if dto.id is None else dto.id,
) )

View File

@ -13,9 +13,7 @@ class ServerTransformer(TransformerABC):
return Server(dto.discord_id) return Server(dto.discord_id)
@staticmethod @staticmethod
def to_dto( def to_dto(db: Server, name: str, member_count: int, icon_url: Optional[discord.Asset]) -> ServerDTO:
db: Server, name: str, member_count: int, icon_url: Optional[discord.Asset]
) -> ServerDTO:
return ServerDTO( return ServerDTO(
db.server_id, db.server_id,
db.discord_server_id, db.discord_server_id,

View File

@ -43,9 +43,7 @@ class ClientUtilsABC(ABC):
pass pass
@abstractmethod @abstractmethod
def get_auto_complete_list( def get_auto_complete_list(self, _l: List, current: str, select: Callable = None) -> List:
self, _l: List, current: str, select: Callable = None
) -> List:
pass pass
@abstractmethod @abstractmethod

View File

@ -18,9 +18,7 @@ class CustomFileLoggerABC(Logger, ABC):
env: ApplicationEnvironmentABC, env: ApplicationEnvironmentABC,
): ):
self._key = key self._key = key
self._settings: LoggingSettings = config.get_configuration( self._settings: LoggingSettings = config.get_configuration(f"{FileLoggingSettings.__name__}_{key}")
f"{FileLoggingSettings.__name__}_{key}"
)
Logger.__init__(self, self._settings, time_format, env) Logger.__init__(self, self._settings, time_format, env)
self._begin_log() self._begin_log()
@ -34,9 +32,7 @@ class CustomFileLoggerABC(Logger, ABC):
self.info(__name__, f"Starting...") self.info(__name__, f"Starting...")
self._console = LoggingLevelEnum(console_level) self._console = LoggingLevelEnum(console_level)
def _get_string( def _get_string(self, name_list_as_str: str, level: LoggingLevelEnum, message: str) -> str:
self, name_list_as_str: str, level: LoggingLevelEnum, message: str
) -> str:
names = name_list_as_str.split(" ") names = name_list_as_str.split(" ")
log_level = level.name log_level = level.name
string = f"<{self._get_datetime_now()}> [ {log_level} ]" string = f"<{self._get_datetime_now()}> [ {log_level} ]"

View File

@ -13,9 +13,7 @@ class MessageServiceABC(ABC):
pass pass
@abstractmethod @abstractmethod
async def delete_messages( async def delete_messages(self, messages: List[discord.Message], guild_id: int, without_tracking=False):
self, messages: List[discord.Message], guild_id: int, without_tracking=False
):
pass pass
@abstractmethod @abstractmethod

View File

@ -27,10 +27,6 @@ class BotLoggingSettings(ConfigurationModelABC):
self._files = files self._files = files
except Exception as e: except Exception as e:
Console.set_foreground_color(ForegroundColorEnum.red) Console.set_foreground_color(ForegroundColorEnum.red)
Console.write_line( Console.write_line(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings" Console.write_line(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
)
Console.write_line(
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
)
Console.set_foreground_color(ForegroundColorEnum.default) Console.set_foreground_color(ForegroundColorEnum.default)

View File

@ -58,9 +58,5 @@ class BotSettings(ConfigurationModelABC):
servers.append(st) servers.append(st)
self._servers = servers self._servers = servers
except Exception as e: except Exception as e:
Console.error( Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings" Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
)
Console.error(
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
)

View File

@ -46,9 +46,5 @@ class FeatureFlagsSettings(ConfigurationModelABC):
for flag in [f.value for f in FeatureFlagsEnum]: for flag in [f.value for f in FeatureFlagsEnum]:
self._load_flag(settings, FeatureFlagsEnum(flag)) self._load_flag(settings, FeatureFlagsEnum(flag))
except Exception as e: except Exception as e:
Console.error( Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings" Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
)
Console.error(
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
)

View File

@ -19,9 +19,5 @@ class FileLoggingSettings(LoggingSettings):
self._key = settings["Key"] self._key = settings["Key"]
super().from_dict(settings) super().from_dict(settings)
except Exception as e: except Exception as e:
Console.error( Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings" Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
)
Console.error(
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
)

View File

@ -25,6 +25,4 @@ class ServerSettings(ConfigurationModelABC):
self._message_delete_timer = int(settings["MessageDeleteTimer"]) self._message_delete_timer = int(settings["MessageDeleteTimer"])
except Exception as e: except Exception as e:
Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in settings") Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in settings")
Console.error( Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
)

View File

@ -17,9 +17,7 @@ class CoreExtension(ApplicationExtensionABC):
ApplicationExtensionABC.__init__(self) ApplicationExtensionABC.__init__(self)
async def run(self, config: ConfigurationABC, services: ServiceProviderABC): async def run(self, config: ConfigurationABC, services: ServiceProviderABC):
feature_flags: FeatureFlagsSettings = config.get_configuration( feature_flags: FeatureFlagsSettings = config.get_configuration(FeatureFlagsSettings)
FeatureFlagsSettings
)
if not feature_flags.get_flag(FeatureFlagsEnum.core_module): if not feature_flags.get_flag(FeatureFlagsEnum.core_module):
return return

View File

@ -15,14 +15,8 @@ class CoreExtensionModule(ModuleABC):
def __init__(self, dc: DiscordCollectionABC): def __init__(self, dc: DiscordCollectionABC):
ModuleABC.__init__(self, dc, FeatureFlagsEnum.core_extension_module) ModuleABC.__init__(self, dc, FeatureFlagsEnum.core_extension_module)
def configure_configuration( def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
):
pass pass
def configure_services( def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC self._dc.add_event(DiscordEventTypesEnum.on_ready.value, CoreExtensionOnReadyEvent)
):
self._dc.add_event(
DiscordEventTypesEnum.on_ready.value, CoreExtensionOnReadyEvent
)

View File

@ -18,14 +18,10 @@ class CoreModule(ModuleABC):
def __init__(self, dc: DiscordCollectionABC): def __init__(self, dc: DiscordCollectionABC):
ModuleABC.__init__(self, dc, FeatureFlagsEnum.core_module) ModuleABC.__init__(self, dc, FeatureFlagsEnum.core_module)
def configure_configuration( def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
):
pass pass
def configure_services( def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
):
services.add_transient(MessageServiceABC, MessageService) services.add_transient(MessageServiceABC, MessageService)
services.add_transient(ClientUtilsABC, ClientUtilsService) services.add_transient(ClientUtilsABC, ClientUtilsService)

View File

@ -44,9 +44,7 @@ class CommandChecks:
async def check_is_member_admin(ctx: Context): async def check_is_member_admin(ctx: Context):
has_permission = cls._permissions.is_member_admin(ctx.author) has_permission = cls._permissions.is_member_admin(ctx.author)
if not has_permission: if not has_permission:
await cls._message_service.send_ctx_msg( await cls._message_service.send_ctx_msg(ctx, cls._t.transform("common.no_permission_message"))
ctx, cls._t.transform("common.no_permission_message")
)
raise CheckError(f"Member {ctx.author.name} is not admin") raise CheckError(f"Member {ctx.author.name} is not admin")
return has_permission return has_permission
@ -58,9 +56,7 @@ class CommandChecks:
async def check_is_member_technician(ctx: Context): async def check_is_member_technician(ctx: Context):
has_permission = cls._permissions.is_member_technician(ctx.author) has_permission = cls._permissions.is_member_technician(ctx.author)
if not has_permission: if not has_permission:
await cls._message_service.send_ctx_msg( await cls._message_service.send_ctx_msg(ctx, cls._t.transform("common.no_permission_message"))
ctx, cls._t.transform("common.no_permission_message")
)
raise CheckError(f"Member {ctx.author.name} is not technician") raise CheckError(f"Member {ctx.author.name} is not technician")
return has_permission return has_permission
@ -72,9 +68,7 @@ class CommandChecks:
async def check_is_member_moderator(ctx: Context): async def check_is_member_moderator(ctx: Context):
has_permission = cls._permissions.is_member_moderator(ctx.author) has_permission = cls._permissions.is_member_moderator(ctx.author)
if not has_permission: if not has_permission:
await cls._message_service.send_ctx_msg( await cls._message_service.send_ctx_msg(ctx, cls._t.transform("common.no_permission_message"))
ctx, cls._t.transform("common.no_permission_message")
)
raise CheckError(f"Member {ctx.author.name} is not moderator") raise CheckError(f"Member {ctx.author.name} is not moderator")
return has_permission return has_permission

View File

@ -60,36 +60,28 @@ class ClientUtilsService(ClientUtilsABC):
def received_command(self, guild_id: int): def received_command(self, guild_id: int):
server = self._servers.get_server_by_discord_id(guild_id) server = self._servers.get_server_by_discord_id(guild_id)
client = self._clients.find_client_by_discord_id_and_server_id( client = self._clients.find_client_by_discord_id_and_server_id(self._bot.user.id, server.server_id)
self._bot.user.id, server.server_id
)
client.received_command_count += 1 client.received_command_count += 1
self._clients.update_client(client) self._clients.update_client(client)
self._db.save_changes() self._db.save_changes()
def moved_user(self, guild_id: int): def moved_user(self, guild_id: int):
server = self._servers.get_server_by_discord_id(guild_id) server = self._servers.get_server_by_discord_id(guild_id)
client = self._clients.find_client_by_discord_id_and_server_id( client = self._clients.find_client_by_discord_id_and_server_id(self._bot.user.id, server.server_id)
self._bot.user.id, server.server_id
)
client.moved_users_count += 1 client.moved_users_count += 1
self._clients.update_client(client) self._clients.update_client(client)
self._db.save_changes() self._db.save_changes()
def moved_users(self, guild_id: int, count: int): def moved_users(self, guild_id: int, count: int):
server = self._servers.get_server_by_discord_id(guild_id) server = self._servers.get_server_by_discord_id(guild_id)
client = self._clients.find_client_by_discord_id_and_server_id( client = self._clients.find_client_by_discord_id_and_server_id(self._bot.user.id, server.server_id)
self._bot.user.id, server.server_id
)
client.moved_users_count += count client.moved_users_count += count
self._clients.update_client(client) self._clients.update_client(client)
self._db.save_changes() self._db.save_changes()
def get_client(self, dc_ic: int, guild_id: int): def get_client(self, dc_ic: int, guild_id: int):
server = self._servers.get_server_by_discord_id(guild_id) server = self._servers.get_server_by_discord_id(guild_id)
client = self._clients.find_client_by_discord_id_and_server_id( client = self._clients.find_client_by_discord_id_and_server_id(self._bot.user.id, server.server_id)
self._bot.user.id, server.server_id
)
return client return client
async def check_if_bot_is_ready_yet(self) -> bool: async def check_if_bot_is_ready_yet(self) -> bool:
@ -123,9 +115,7 @@ class ClientUtilsService(ClientUtilsABC):
await self._bot.change_presence(activity=discord.Game(name=name)) await self._bot.change_presence(activity=discord.Game(name=name))
self._logger.info(__name__, f"Set presence {name}") self._logger.info(__name__, f"Set presence {name}")
def get_auto_complete_list( def get_auto_complete_list(self, _l: List, current: str, select: Callable = None) -> List:
self, _l: List, current: str, select: Callable = None
) -> List:
if current != "": if current != "":
if select is None: if select is None:
select = lambda x: x select = lambda x: x
@ -148,9 +138,7 @@ class ClientUtilsService(ClientUtilsABC):
) -> bool: ) -> bool:
umcph = None umcph = None
try: try:
umcph = self._umcphs.find_user_message_count_per_hour_by_user_id_and_date( umcph = self._umcphs.find_user_message_count_per_hour_by_user_id_and_date(user.user_id, created_at)
user.user_id, created_at
)
if umcph is None: if umcph is None:
self._umcphs.add_user_message_count_per_hour( self._umcphs.add_user_message_count_per_hour(
UserMessageCountPerHour( UserMessageCountPerHour(
@ -163,11 +151,7 @@ class ClientUtilsService(ClientUtilsABC):
self._db.save_changes() self._db.save_changes()
umcph = ( umcph = self._umcphs.get_user_message_count_per_hour_by_user_id_and_date(user.user_id, created_at)
self._umcphs.get_user_message_count_per_hour_by_user_id_and_date(
user.user_id, created_at
)
)
except Exception as e: except Exception as e:
self._logger.error( self._logger.error(
__name__, __name__,
@ -199,13 +183,7 @@ class ClientUtilsService(ClientUtilsABC):
def get_ontime_for_user(self, user: User) -> float: def get_ontime_for_user(self, user: User) -> float:
return ( return (
self._user_joined_voice_channel.get_user_joined_voice_channels_by_user_id( self._user_joined_voice_channel.get_user_joined_voice_channels_by_user_id(user.user_id)
user.user_id
)
.where(lambda x: x.leaved_on is not None and x.joined_on is not None) .where(lambda x: x.leaved_on is not None and x.joined_on is not None)
.sum( .sum(lambda join: round((join.leaved_on - join.joined_on).total_seconds() / 3600, 2))
lambda join: round(
(join.leaved_on - join.joined_on).total_seconds() / 3600, 2
)
)
) )

View File

@ -31,23 +31,15 @@ class MessageService(MessageServiceABC):
self._clients = clients self._clients = clients
self._db = db self._db = db
async def delete_messages( async def delete_messages(self, messages: List[discord.Message], guild_id: int, without_tracking=False):
self, messages: List[discord.Message], guild_id: int, without_tracking=False
):
self._logger.debug(__name__, f"Try to delete {messages.count()} messages") self._logger.debug(__name__, f"Try to delete {messages.count()} messages")
server_st: ServerSettings = self._config.get_configuration( server_st: ServerSettings = self._config.get_configuration(f"ServerSettings_{guild_id}")
f"ServerSettings_{guild_id}"
)
await asyncio.sleep(server_st.message_delete_timer) await asyncio.sleep(server_st.message_delete_timer)
for message in messages: for message in messages:
await self.delete_message( await self.delete_message(message, mass_delete=True, without_tracking=without_tracking)
message, mass_delete=True, without_tracking=without_tracking
)
self._logger.debug(__name__, "Deleting messages finished") self._logger.debug(__name__, "Deleting messages finished")
async def delete_message( async def delete_message(self, message: discord.Message, mass_delete=False, without_tracking=False):
self, message: discord.Message, mass_delete=False, without_tracking=False
):
guild_id = ( guild_id = (
message.guild.id message.guild.id
if message.guild is not None if message.guild is not None
@ -58,9 +50,7 @@ class MessageService(MessageServiceABC):
else None else None
) )
server_st: ServerSettings = self._config.get_configuration( server_st: ServerSettings = self._config.get_configuration(f"ServerSettings_{guild_id}")
f"ServerSettings_{guild_id}"
)
if not mass_delete: if not mass_delete:
await asyncio.sleep(server_st.message_delete_timer) await asyncio.sleep(server_st.message_delete_timer)
self._logger.debug( self._logger.debug(
@ -74,9 +64,7 @@ class MessageService(MessageServiceABC):
self._logger.error(__name__, f"Deleting message failed", e) self._logger.error(__name__, f"Deleting message failed", e)
else: else:
if not without_tracking: if not without_tracking:
self._clients.append_deleted_message_count( self._clients.append_deleted_message_count(self._bot.user.id, guild_id, 1)
self._bot.user.id, guild_id, 1
)
self._db.save_changes() self._db.save_changes()
self._logger.info(__name__, f"Deleted message {message}") self._logger.info(__name__, f"Deleted message {message}")
@ -88,9 +76,7 @@ class MessageService(MessageServiceABC):
wait_before_delete: int = None, wait_before_delete: int = None,
without_tracking=False, without_tracking=False,
): ):
self._logger.debug( self._logger.debug(__name__, f"Try to send message\n\t{message}\n\tto: {channel}")
__name__, f"Try to send message\n\t{message}\n\tto: {channel}"
)
msg = None msg = None
try: try:
if isinstance(message, discord.Embed): if isinstance(message, discord.Embed):
@ -98,15 +84,11 @@ class MessageService(MessageServiceABC):
else: else:
msg = await channel.send(message) msg = await channel.send(message)
except Exception as e: except Exception as e:
self._logger.error( self._logger.error(__name__, f"Send message to channel {channel.id} failed", e)
__name__, f"Send message to channel {channel.id} failed", e
)
else: else:
self._logger.info(__name__, f"Sent message to channel {channel.id}") self._logger.info(__name__, f"Sent message to channel {channel.id}")
if not without_tracking: if not without_tracking:
self._clients.append_sent_message_count( self._clients.append_sent_message_count(self._bot.user.id, channel.guild.id, 1)
self._bot.user.id, channel.guild.id, 1
)
self._db.save_changes() self._db.save_changes()
if wait_before_delete is not None: if wait_before_delete is not None:
@ -123,23 +105,17 @@ class MessageService(MessageServiceABC):
receiver: Union[discord.User, discord.Member], receiver: Union[discord.User, discord.Member],
without_tracking=False, without_tracking=False,
): ):
self._logger.debug( self._logger.debug(__name__, f"Try to send message\n\t{message}\n\tto: {receiver}")
__name__, f"Try to send message\n\t{message}\n\tto: {receiver}"
)
try: try:
if isinstance(message, discord.Embed): if isinstance(message, discord.Embed):
msg = await receiver.send(embed=message) msg = await receiver.send(embed=message)
else: else:
msg = await receiver.send(message) msg = await receiver.send(message)
except Exception as e: except Exception as e:
self._logger.error( self._logger.error(__name__, f"Send message to user {receiver.id} failed", e)
__name__, f"Send message to user {receiver.id} failed", e
)
else: else:
if not without_tracking: if not without_tracking:
self._clients.append_sent_message_count( self._clients.append_sent_message_count(self._bot.user.id, receiver.guild.id, 1)
self._bot.user.id, receiver.guild.id, 1
)
self._db.save_changes() self._db.save_changes()
self._logger.info(__name__, f"Sent message to user {receiver.id}") self._logger.info(__name__, f"Sent message to user {receiver.id}")
@ -158,9 +134,7 @@ class MessageService(MessageServiceABC):
self._logger.debug(__name__, f"Message: {message}") self._logger.debug(__name__, f"Message: {message}")
return None return None
self._logger.debug( self._logger.debug(__name__, f"Try to send message\t\t{message}\n\tto: {ctx.channel}")
__name__, f"Try to send message\t\t{message}\n\tto: {ctx.channel}"
)
msg = None msg = None
try: try:
if isinstance(message, discord.Embed): if isinstance(message, discord.Embed):
@ -168,15 +142,11 @@ class MessageService(MessageServiceABC):
else: else:
msg = await ctx.send(message, file=file, ephemeral=not is_public) msg = await ctx.send(message, file=file, ephemeral=not is_public)
except Exception as e: except Exception as e:
self._logger.error( self._logger.error(__name__, f"Send message to channel {ctx.channel.id} failed", e)
__name__, f"Send message to channel {ctx.channel.id} failed", e
)
else: else:
self._logger.info(__name__, f"Sent message to channel {ctx.channel.id}") self._logger.info(__name__, f"Sent message to channel {ctx.channel.id}")
if not without_tracking and ctx.guild is not None: if not without_tracking and ctx.guild is not None:
self._clients.append_sent_message_count( self._clients.append_sent_message_count(self._bot.user.id, ctx.guild.id, 1)
self._bot.user.id, ctx.guild.id, 1
)
self._db.save_changes() self._db.save_changes()
if wait_before_delete is not None: if wait_before_delete is not None:
@ -205,30 +175,18 @@ class MessageService(MessageServiceABC):
self._logger.debug(__name__, f"Message: {message}") self._logger.debug(__name__, f"Message: {message}")
return return
self._logger.debug( self._logger.debug(__name__, f"Try to send message\t\t{message}\n\tto: {interaction.channel}")
__name__, f"Try to send message\t\t{message}\n\tto: {interaction.channel}"
)
try: try:
if isinstance(message, discord.Embed): if isinstance(message, discord.Embed):
await interaction.response.send_message( await interaction.response.send_message(embed=message, ephemeral=not is_public, **kwargs)
embed=message, ephemeral=not is_public, **kwargs
)
else: else:
await interaction.response.send_message( await interaction.response.send_message(message, ephemeral=not is_public, **kwargs)
message, ephemeral=not is_public, **kwargs
)
except Exception as e: except Exception as e:
self._logger.error( self._logger.error(__name__, f"Send message to channel {interaction.channel.id} failed", e)
__name__, f"Send message to channel {interaction.channel.id} failed", e
)
else: else:
self._logger.info( self._logger.info(__name__, f"Sent message to channel {interaction.channel.id}")
__name__, f"Sent message to channel {interaction.channel.id}"
)
if not without_tracking and interaction.guild is not None: if not without_tracking and interaction.guild is not None:
self._clients.append_sent_message_count( self._clients.append_sent_message_count(self._bot.user.id, interaction.guild.id, 1)
self._bot.user.id, interaction.guild.id, 1
)
self._db.save_changes() self._db.save_changes()
if wait_before_delete is not None: if wait_before_delete is not None:
@ -237,6 +195,4 @@ class MessageService(MessageServiceABC):
if is_persistent: if is_persistent:
return return
await self.delete_message( await self.delete_message(await interaction.original_response(), without_tracking)
await interaction.original_response(), without_tracking
)

View File

@ -19,9 +19,7 @@ class AuthUserRepositoryABC(ABC):
pass pass
@abstractmethod @abstractmethod
def get_filtered_auth_users( def get_filtered_auth_users(self, criteria: AuthUserSelectCriteria) -> FilteredResult:
self, criteria: AuthUserSelectCriteria
) -> FilteredResult:
pass pass
@abstractmethod @abstractmethod

View File

@ -31,9 +31,7 @@ class ClientRepositoryABC(ABC):
pass pass
@abstractmethod @abstractmethod
def find_client_by_discord_id_and_server_id( def find_client_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> Optional[Client]:
self, discord_id: int, server_id: int
) -> Optional[Client]:
pass pass
@abstractmethod @abstractmethod

View File

@ -19,21 +19,15 @@ class UserJoinedServerRepositoryABC(ABC):
pass pass
@abstractmethod @abstractmethod
def get_user_joined_servers_by_user_id( def get_user_joined_servers_by_user_id(self, user_id: int) -> list[UserJoinedServer]:
self, user_id: int
) -> list[UserJoinedServer]:
pass pass
@abstractmethod @abstractmethod
def get_active_user_joined_server_by_user_id( def get_active_user_joined_server_by_user_id(self, user_id: int) -> UserJoinedServer:
self, user_id: int
) -> UserJoinedServer:
pass pass
@abstractmethod @abstractmethod
def find_active_user_joined_server_by_user_id( def find_active_user_joined_server_by_user_id(self, user_id: int) -> Optional[UserJoinedServer]:
self, user_id: int
) -> Optional[UserJoinedServer]:
pass pass
@abstractmethod @abstractmethod

View File

@ -19,45 +19,31 @@ class UserJoinedVoiceChannelRepositoryABC(ABC):
pass pass
@abstractmethod @abstractmethod
def get_user_joined_voice_channels_by_user_id( def get_user_joined_voice_channels_by_user_id(self, user_id: int) -> List[UserJoinedVoiceChannel]:
self, user_id: int
) -> List[UserJoinedVoiceChannel]:
pass pass
@abstractmethod @abstractmethod
def get_active_user_joined_voice_channel_by_user_id( def get_active_user_joined_voice_channel_by_user_id(self, user_id: int) -> UserJoinedVoiceChannel:
self, user_id: int
) -> UserJoinedVoiceChannel:
pass pass
@abstractmethod @abstractmethod
def find_active_user_joined_voice_channel_by_user_id( def find_active_user_joined_voice_channel_by_user_id(self, user_id: int) -> Optional[UserJoinedVoiceChannel]:
self, user_id: int
) -> Optional[UserJoinedVoiceChannel]:
pass pass
@abstractmethod @abstractmethod
def find_active_user_joined_voice_channels_by_user_id( def find_active_user_joined_voice_channels_by_user_id(self, user_id: int) -> List[Optional[UserJoinedVoiceChannel]]:
self, user_id: int
) -> List[Optional[UserJoinedVoiceChannel]]:
pass pass
@abstractmethod @abstractmethod
def add_user_joined_voice_channel( def add_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel):
self, user_joined_voice_channel: UserJoinedVoiceChannel
):
pass pass
@abstractmethod @abstractmethod
def update_user_joined_voice_channel( def update_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel):
self, user_joined_voice_channel: UserJoinedVoiceChannel
):
pass pass
@abstractmethod @abstractmethod
def delete_user_joined_voice_channel( def delete_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel):
self, user_joined_voice_channel: UserJoinedVoiceChannel
):
pass pass
@abstractmethod @abstractmethod

View File

@ -17,9 +17,7 @@ class UserMessageCountPerHourRepositoryABC(ABC):
pass pass
@abstractmethod @abstractmethod
def find_user_message_count_per_hour_by_user_id( def find_user_message_count_per_hour_by_user_id(self, user_id: int) -> Optional[UserMessageCountPerHour]:
self, user_id: int
) -> Optional[UserMessageCountPerHour]:
pass pass
@abstractmethod @abstractmethod

View File

@ -28,15 +28,11 @@ class UserRepositoryABC(ABC):
pass pass
@abstractmethod @abstractmethod
def get_user_by_discord_id_and_server_id( def get_user_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> User:
self, discord_id: int, server_id: int
) -> User:
pass pass
@abstractmethod @abstractmethod
def find_user_by_discord_id_and_server_id( def find_user_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> Optional[User]:
self, discord_id: int, server_id: int
) -> Optional[User]:
pass pass
@abstractmethod @abstractmethod

View File

@ -44,25 +44,17 @@ class DataModule(ModuleABC):
def __init__(self, dc: DiscordCollectionABC): def __init__(self, dc: DiscordCollectionABC):
ModuleABC.__init__(self, dc, FeatureFlagsEnum.data_module) ModuleABC.__init__(self, dc, FeatureFlagsEnum.data_module)
def configure_configuration( def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
):
pass pass
def configure_services( def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
):
services.add_transient(AuthUserRepositoryABC, AuthUserRepositoryService) services.add_transient(AuthUserRepositoryABC, AuthUserRepositoryService)
services.add_transient(ServerRepositoryABC, ServerRepositoryService) services.add_transient(ServerRepositoryABC, ServerRepositoryService)
services.add_transient(UserRepositoryABC, UserRepositoryService) services.add_transient(UserRepositoryABC, UserRepositoryService)
services.add_transient(ClientRepositoryABC, ClientRepositoryService) services.add_transient(ClientRepositoryABC, ClientRepositoryService)
services.add_transient(KnownUserRepositoryABC, KnownUserRepositoryService) services.add_transient(KnownUserRepositoryABC, KnownUserRepositoryService)
services.add_transient( services.add_transient(UserJoinedServerRepositoryABC, UserJoinedServerRepositoryService)
UserJoinedServerRepositoryABC, UserJoinedServerRepositoryService services.add_transient(UserJoinedVoiceChannelRepositoryABC, UserJoinedVoiceChannelRepositoryService)
)
services.add_transient(
UserJoinedVoiceChannelRepositoryABC, UserJoinedVoiceChannelRepositoryService
)
services.add_transient(AutoRoleRepositoryABC, AutoRoleRepositoryService) services.add_transient(AutoRoleRepositoryABC, AutoRoleRepositoryService)
services.add_transient(LevelRepositoryABC, LevelRepositoryService) services.add_transient(LevelRepositoryABC, LevelRepositoryService)
services.add_transient(StatisticRepositoryABC, StatisticRepositoryService) services.add_transient(StatisticRepositoryABC, StatisticRepositoryService)

View File

@ -47,9 +47,7 @@ class AuthUser(TableABC):
TableABC.__init__(self) TableABC.__init__(self)
self._created_at = created_at if created_at is not None else self._created_at self._created_at = created_at if created_at is not None else self._created_at
self._modified_at = ( self._modified_at = modified_at if modified_at is not None else self._modified_at
modified_at if modified_at is not None else self._modified_at
)
@property @property
def id(self) -> int: def id(self) -> int:

View File

@ -19,9 +19,7 @@ class AuthUserUsersRelation(TableABC):
TableABC.__init__(self) TableABC.__init__(self)
self._created_at = created_at if created_at is not None else self._created_at self._created_at = created_at if created_at is not None else self._created_at
self._modified_at = ( self._modified_at = modified_at if modified_at is not None else self._modified_at
modified_at if modified_at is not None else self._modified_at
)
@property @property
def auth_user(self) -> AuthUser: def auth_user(self) -> AuthUser:

View File

@ -21,9 +21,7 @@ class AutoRole(TableABC):
TableABC.__init__(self) TableABC.__init__(self)
self._created_at = created_at if created_at is not None else self._created_at self._created_at = created_at if created_at is not None else self._created_at
self._modified_at = ( self._modified_at = modified_at if modified_at is not None else self._modified_at
modified_at if modified_at is not None else self._modified_at
)
@property @property
def auto_role_id(self) -> int: def auto_role_id(self) -> int:

View File

@ -21,9 +21,7 @@ class AutoRoleRule(TableABC):
TableABC.__init__(self) TableABC.__init__(self)
self._created_at = created_at if created_at is not None else self._created_at self._created_at = created_at if created_at is not None else self._created_at
self._modified_at = ( self._modified_at = modified_at if modified_at is not None else self._modified_at
modified_at if modified_at is not None else self._modified_at
)
@property @property
def auto_role_rule_id(self) -> int: def auto_role_rule_id(self) -> int:

View File

@ -29,9 +29,7 @@ class Client(TableABC):
TableABC.__init__(self) TableABC.__init__(self)
self._created_at = created_at if created_at is not None else self._created_at self._created_at = created_at if created_at is not None else self._created_at
self._modified_at = ( self._modified_at = modified_at if modified_at is not None else self._modified_at
modified_at if modified_at is not None else self._modified_at
)
@property @property
def client_id(self) -> int: def client_id(self) -> int:

View File

@ -18,9 +18,7 @@ class KnownUser(TableABC):
TableABC.__init__(self) TableABC.__init__(self)
self._created_at = created_at if created_at is not None else self._created_at self._created_at = created_at if created_at is not None else self._created_at
self._modified_at = ( self._modified_at = modified_at if modified_at is not None else self._modified_at
modified_at if modified_at is not None else self._modified_at
)
@property @property
def known_user_id(self) -> int: def known_user_id(self) -> int:

View File

@ -26,9 +26,7 @@ class Level(TableABC):
TableABC.__init__(self) TableABC.__init__(self)
self._created_at = created_at if created_at is not None else self._created_at self._created_at = created_at if created_at is not None else self._created_at
self._modified_at = ( self._modified_at = modified_at if modified_at is not None else self._modified_at
modified_at if modified_at is not None else self._modified_at
)
@property @property
def id(self) -> int: def id(self) -> int:

View File

@ -17,9 +17,7 @@ class Server(TableABC):
TableABC.__init__(self) TableABC.__init__(self)
self._created_at = created_at if created_at is not None else self._created_at self._created_at = created_at if created_at is not None else self._created_at
self._modified_at = ( self._modified_at = modified_at if modified_at is not None else self._modified_at
modified_at if modified_at is not None else self._modified_at
)
@property @property
def server_id(self) -> int: def server_id(self) -> int:

View File

@ -25,9 +25,7 @@ class Statistic(TableABC):
TableABC.__init__(self) TableABC.__init__(self)
self._created_at = created_at if created_at is not None else self._created_at self._created_at = created_at if created_at is not None else self._created_at
self._modified_at = ( self._modified_at = modified_at if modified_at is not None else self._modified_at
modified_at if modified_at is not None else self._modified_at
)
@property @property
def id(self) -> int: def id(self) -> int:

View File

@ -22,9 +22,7 @@ class User(TableABC):
TableABC.__init__(self) TableABC.__init__(self)
self._created_at = created_at if created_at is not None else self._created_at self._created_at = created_at if created_at is not None else self._created_at
self._modified_at = ( self._modified_at = modified_at if modified_at is not None else self._modified_at
modified_at if modified_at is not None else self._modified_at
)
@property @property
def user_id(self) -> int: def user_id(self) -> int:

View File

@ -24,9 +24,7 @@ class UserJoinedServer(TableABC):
TableABC.__init__(self) TableABC.__init__(self)
self._created_at = created_at if created_at is not None else self._created_at self._created_at = created_at if created_at is not None else self._created_at
self._modified_at = ( self._modified_at = modified_at if modified_at is not None else self._modified_at
modified_at if modified_at is not None else self._modified_at
)
@property @property
def join_id(self) -> int: def join_id(self) -> int:

View File

@ -24,9 +24,7 @@ class UserJoinedVoiceChannel(TableABC):
TableABC.__init__(self) TableABC.__init__(self)
self._created_at = created_at if created_at is not None else self._created_at self._created_at = created_at if created_at is not None else self._created_at
self._modified_at = ( self._modified_at = modified_at if modified_at is not None else self._modified_at
modified_at if modified_at is not None else self._modified_at
)
@property @property
def join_id(self) -> int: def join_id(self) -> int:

View File

@ -24,9 +24,7 @@ class UserMessageCountPerHour(TableABC):
TableABC.__init__(self) TableABC.__init__(self)
self._created_at = created_at if created_at is not None else self._created_at self._created_at = created_at if created_at is not None else self._created_at
self._modified_at = ( self._modified_at = modified_at if modified_at is not None else self._modified_at
modified_at if modified_at is not None else self._modified_at
)
@property @property
def id(self) -> int: def id(self) -> int:

View File

@ -67,9 +67,7 @@ class AuthUserRepositoryService(AuthUserRepositoryABC):
def get_all_auth_users(self) -> List[AuthUser]: def get_all_auth_users(self) -> List[AuthUser]:
users = List(AuthUser) users = List(AuthUser)
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {AuthUser.get_select_all_string()}")
__name__, f"Send SQL command: {AuthUser.get_select_all_string()}"
)
results = self._context.select(AuthUser.get_select_all_string()) results = self._context.select(AuthUser.get_select_all_string())
for result in results: for result in results:
self._logger.trace(__name__, f"Get auth user with id {result[0]}") self._logger.trace(__name__, f"Get auth user with id {result[0]}")
@ -77,36 +75,22 @@ class AuthUserRepositoryService(AuthUserRepositoryABC):
return users return users
def get_filtered_auth_users( def get_filtered_auth_users(self, criteria: AuthUserSelectCriteria) -> FilteredResult:
self, criteria: AuthUserSelectCriteria
) -> FilteredResult:
users = self.get_all_auth_users() users = self.get_all_auth_users()
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {AuthUser.get_select_all_string()}")
__name__, f"Send SQL command: {AuthUser.get_select_all_string()}"
)
query = users query = users
if criteria.first_name is not None and criteria.first_name != "": if criteria.first_name is not None and criteria.first_name != "":
query = query.where( query = query.where(lambda x: criteria.first_name in x.first_name or x.first_name == criteria.first_name)
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 != "": if criteria.last_name is not None and criteria.last_name != "":
query = query.where( query = query.where(lambda x: criteria.last_name in x.last_name or x.last_name == criteria.last_name)
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 != "": if criteria.email is not None and criteria.email != "":
query = query.where( query = query.where(lambda x: criteria.email in x.email or x.email == criteria.email)
lambda x: criteria.email in x.email or x.email == criteria.email
)
if criteria.auth_role is not None: if criteria.auth_role is not None:
query = query.where( query = query.where(lambda x: x.auth_role == AuthRoleEnum(criteria.auth_role))
lambda x: x.auth_role == AuthRoleEnum(criteria.auth_role)
)
# sort # sort
if ( if (
@ -117,9 +101,7 @@ class AuthUserRepositoryService(AuthUserRepositoryABC):
): ):
crit_sort_direction = criteria.sort_direction.lower() crit_sort_direction = criteria.sort_direction.lower()
if crit_sort_direction == "desc" or crit_sort_direction == "descending": if crit_sort_direction == "desc" or crit_sort_direction == "descending":
query = query.order_by_descending( query = query.order_by_descending(lambda x: getattr(x, criteria.sort_column))
lambda x: getattr(x, criteria.sort_column)
)
else: else:
query = query.order_by(lambda x: getattr(x, criteria.sort_column)) query = query.order_by(lambda x: getattr(x, criteria.sort_column))
@ -131,16 +113,12 @@ class AuthUserRepositoryService(AuthUserRepositoryABC):
return result return result
def get_auth_user_by_email(self, email: str) -> AuthUser: def get_auth_user_by_email(self, email: str) -> AuthUser:
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {AuthUser.get_select_by_email_string(email)}")
__name__, f"Send SQL command: {AuthUser.get_select_by_email_string(email)}"
)
result = self._context.select(AuthUser.get_select_by_email_string(email))[0] result = self._context.select(AuthUser.get_select_by_email_string(email))[0]
return self._user_from_result(result) return self._user_from_result(result)
def find_auth_user_by_email(self, email: str) -> Optional[AuthUser]: def find_auth_user_by_email(self, email: str) -> Optional[AuthUser]:
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {AuthUser.get_select_by_email_string(email)}")
__name__, f"Send SQL command: {AuthUser.get_select_by_email_string(email)}"
)
result = self._context.select(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: if result is None or len(result) == 0:
return None return None
@ -167,9 +145,7 @@ class AuthUserRepositoryService(AuthUserRepositoryABC):
__name__, __name__,
f"Send SQL command: {AuthUser.get_select_by_forgot_password_id_string(id)}", f"Send SQL command: {AuthUser.get_select_by_forgot_password_id_string(id)}",
) )
result = self._context.select( result = self._context.select(AuthUser.get_select_by_forgot_password_id_string(id))
AuthUser.get_select_by_forgot_password_id_string(id)
)
if result is None or len(result) == 0: if result is None or len(result) == 0:
return None return None

View File

@ -18,54 +18,34 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC):
def get_auto_roles(self) -> List[AutoRole]: def get_auto_roles(self) -> List[AutoRole]:
auto_roles = List(AutoRole) auto_roles = List(AutoRole)
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {AutoRole.get_select_all_string()}")
__name__, f"Send SQL command: {AutoRole.get_select_all_string()}"
)
results = self._context.select(AutoRole.get_select_all_string()) results = self._context.select(AutoRole.get_select_all_string())
for result in results: for result in results:
auto_roles.append( auto_roles.append(AutoRole(result[1], result[2], result[3], result[4], result[5], id=result[0]))
AutoRole(
result[1], result[2], result[3], result[4], result[5], id=result[0]
)
)
return auto_roles return auto_roles
def get_auto_role_by_id(self, id: int) -> AutoRole: def get_auto_role_by_id(self, id: int) -> AutoRole:
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {AutoRole.get_select_by_id_string(id)}")
__name__, f"Send SQL command: {AutoRole.get_select_by_id_string(id)}"
)
result = self._context.select(AutoRole.get_select_by_id_string(id))[0] result = self._context.select(AutoRole.get_select_by_id_string(id))[0]
return AutoRole( return AutoRole(result[1], result[2], result[3], result[4], result[5], id=result[0])
result[1], result[2], result[3], result[4], result[5], id=result[0]
)
def find_auto_role_by_id(self, id: int) -> Optional[AutoRole]: def find_auto_role_by_id(self, id: int) -> Optional[AutoRole]:
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {AutoRole.get_select_by_id_string(id)}")
__name__, f"Send SQL command: {AutoRole.get_select_by_id_string(id)}"
)
result = self._context.select(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: if result is None or len(result) == 0:
return None return None
result = result[0] result = result[0]
return AutoRole( return AutoRole(result[1], result[2], result[3], result[4], result[5], id=result[0])
result[1], result[2], result[3], result[4], result[5], id=result[0]
)
def get_auto_roles_by_server_id(self, id: int) -> List[AutoRole]: def get_auto_roles_by_server_id(self, id: int) -> List[AutoRole]:
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {AutoRole.get_select_by_server_id_string(id)}")
__name__, f"Send SQL command: {AutoRole.get_select_by_server_id_string(id)}"
)
auto_roles = List(AutoRole) auto_roles = List(AutoRole)
results = self._context.select(AutoRole.get_select_by_server_id_string(id)) results = self._context.select(AutoRole.get_select_by_server_id_string(id))
for result in results: for result in results:
auto_roles.append( auto_roles.append(AutoRole(result[1], result[2], result[3], result[4], result[5], id=result[0]))
AutoRole(
result[1], result[2], result[3], result[4], result[5], id=result[0]
)
)
return auto_roles return auto_roles
@ -75,9 +55,7 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC):
f"Send SQL command: {AutoRole.get_select_by_message_id_string(id)}", f"Send SQL command: {AutoRole.get_select_by_message_id_string(id)}",
) )
result = self._context.select(AutoRole.get_select_by_message_id_string(id))[0] result = self._context.select(AutoRole.get_select_by_message_id_string(id))[0]
return AutoRole( return AutoRole(result[1], result[2], result[3], result[4], result[5], id=result[0])
result[1], result[2], result[3], result[4], result[5], id=result[0]
)
def find_auto_role_by_message_id(self, id: int) -> Optional[AutoRole]: def find_auto_role_by_message_id(self, id: int) -> Optional[AutoRole]:
self._logger.trace( self._logger.trace(
@ -90,9 +68,7 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC):
result = result[0] result = result[0]
return AutoRole( return AutoRole(result[1], result[2], result[3], result[4], result[5], id=result[0])
result[1], result[2], result[3], result[4], result[5], id=result[0]
)
def add_auto_role(self, auto_role: AutoRole): def add_auto_role(self, auto_role: AutoRole):
self._logger.trace(__name__, f"Send SQL command: {auto_role.insert_string}") self._logger.trace(__name__, f"Send SQL command: {auto_role.insert_string}")
@ -108,27 +84,17 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC):
def get_auto_role_rules(self) -> List[AutoRoleRule]: def get_auto_role_rules(self) -> List[AutoRoleRule]:
auto_role_rules = List(AutoRoleRule) auto_role_rules = List(AutoRoleRule)
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {AutoRoleRule.get_select_all_string()}")
__name__, f"Send SQL command: {AutoRoleRule.get_select_all_string()}"
)
results = self._context.select(AutoRoleRule.get_select_all_string()) results = self._context.select(AutoRoleRule.get_select_all_string())
for result in results: for result in results:
auto_role_rules.append( auto_role_rules.append(AutoRoleRule(result[1], result[2], result[3], result[4], result[5], id=result[0]))
AutoRoleRule(
result[1], result[2], result[3], result[4], result[5], id=result[0]
)
)
return auto_role_rules return auto_role_rules
def get_auto_role_rule_by_id(self, id: int) -> AutoRoleRule: def get_auto_role_rule_by_id(self, id: int) -> AutoRoleRule:
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {AutoRoleRule.get_select_by_id_string(id)}")
__name__, f"Send SQL command: {AutoRoleRule.get_select_by_id_string(id)}"
)
result = self._context.select(AutoRoleRule.get_select_by_id_string(id))[0] result = self._context.select(AutoRoleRule.get_select_by_id_string(id))[0]
return AutoRoleRule( return AutoRoleRule(result[1], result[2], result[3], result[4], result[5], id=result[0])
result[1], result[2], result[3], result[4], result[5], id=result[0]
)
def get_auto_role_rules_by_auto_role_id(self, id: int) -> List[AutoRoleRule]: def get_auto_role_rules_by_auto_role_id(self, id: int) -> List[AutoRoleRule]:
auto_role_rules = List(AutoRoleRule) auto_role_rules = List(AutoRoleRule)
@ -136,32 +102,20 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC):
__name__, __name__,
f"Send SQL command: {AutoRoleRule.get_select_by_auto_role_id_string(id)}", f"Send SQL command: {AutoRoleRule.get_select_by_auto_role_id_string(id)}",
) )
results = self._context.select( results = self._context.select(AutoRoleRule.get_select_by_auto_role_id_string(id))
AutoRoleRule.get_select_by_auto_role_id_string(id)
)
for result in results: for result in results:
auto_role_rules.append( auto_role_rules.append(AutoRoleRule(result[1], result[2], result[3], result[4], result[5], id=result[0]))
AutoRoleRule(
result[1], result[2], result[3], result[4], result[5], id=result[0]
)
)
return auto_role_rules return auto_role_rules
def add_auto_role_rule(self, auto_role_rule: AutoRoleRule): def add_auto_role_rule(self, auto_role_rule: AutoRoleRule):
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {auto_role_rule.insert_string}")
__name__, f"Send SQL command: {auto_role_rule.insert_string}"
)
self._context.cursor.execute(auto_role_rule.insert_string) self._context.cursor.execute(auto_role_rule.insert_string)
def update_auto_role_rule(self, auto_role_rule: AutoRoleRule): def update_auto_role_rule(self, auto_role_rule: AutoRoleRule):
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {auto_role_rule.udpate_string}")
__name__, f"Send SQL command: {auto_role_rule.udpate_string}"
)
self._context.cursor.execute(auto_role_rule.udpate_string) self._context.cursor.execute(auto_role_rule.udpate_string)
def delete_auto_role_rule(self, auto_role_rule: AutoRoleRule): def delete_auto_role_rule(self, auto_role_rule: AutoRoleRule):
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {auto_role_rule.delete_string}")
__name__, f"Send SQL command: {auto_role_rule.delete_string}"
)
self._context.cursor.execute(auto_role_rule.delete_string) self._context.cursor.execute(auto_role_rule.delete_string)

View File

@ -25,9 +25,7 @@ class ClientRepositoryService(ClientRepositoryABC):
def get_clients(self) -> List[Client]: def get_clients(self) -> List[Client]:
clients = List(Client) clients = List(Client)
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {Client.get_select_all_string()}")
__name__, f"Send SQL command: {Client.get_select_all_string()}"
)
results = self._context.select(Client.get_select_all_string()) results = self._context.select(Client.get_select_all_string())
for result in results: for result in results:
self._logger.trace(__name__, f"Get client with id {result[0]}") self._logger.trace(__name__, f"Get client with id {result[0]}")
@ -47,9 +45,7 @@ class ClientRepositoryService(ClientRepositoryABC):
return clients return clients
def get_client_by_id(self, client_id: int) -> Client: def get_client_by_id(self, client_id: int) -> Client:
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {Client.get_select_by_id_string(client_id)}")
__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)) result = self._context.select(Client.get_select_by_id_string(client_id))
return Client( return Client(
result[1], result[1],
@ -67,9 +63,7 @@ class ClientRepositoryService(ClientRepositoryABC):
__name__, __name__,
f"Send SQL command: {Client.get_select_by_discord_id_string(discord_id)}", f"Send SQL command: {Client.get_select_by_discord_id_string(discord_id)}",
) )
result = self._context.select( result = self._context.select(Client.get_select_by_discord_id_string(discord_id))[0]
Client.get_select_by_discord_id_string(discord_id)
)[0]
return Client( return Client(
result[1], result[1],
result[2], result[2],
@ -86,9 +80,7 @@ class ClientRepositoryService(ClientRepositoryABC):
__name__, __name__,
f"Send SQL command: {Client.get_select_by_discord_id_string(discord_id)}", f"Send SQL command: {Client.get_select_by_discord_id_string(discord_id)}",
) )
result = self._context.select( result = self._context.select(Client.get_select_by_discord_id_string(discord_id))
Client.get_select_by_discord_id_string(discord_id)
)
if result is None or len(result) == 0: if result is None or len(result) == 0:
return None return None
@ -127,16 +119,12 @@ class ClientRepositoryService(ClientRepositoryABC):
id=result[0], id=result[0],
) )
def find_client_by_discord_id_and_server_id( def find_client_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> Optional[Client]:
self, discord_id: int, server_id: int
) -> Optional[Client]:
self._logger.trace( self._logger.trace(
__name__, __name__,
f"Send SQL command: {Client.get_select_by_discord_id_and_server_id_string(discord_id, server_id)}", f"Send SQL command: {Client.get_select_by_discord_id_and_server_id_string(discord_id, server_id)}",
) )
result = self._context.select( result = self._context.select(Client.get_select_by_discord_id_and_server_id_string(discord_id, server_id))
Client.get_select_by_discord_id_and_server_id_string(discord_id, server_id)
)
if result is None or len(result) == 0: if result is None or len(result) == 0:
return None return None
@ -173,9 +161,7 @@ class ClientRepositoryService(ClientRepositoryABC):
client = self.find_client_by_discord_id_and_server_id(id, server.server_id) client = self.find_client_by_discord_id_and_server_id(id, server.server_id)
if client is None: if client is None:
self._logger.warn( self._logger.warn(__name__, f"Cannot find client by ids {id}@{server.server_id}")
__name__, f"Cannot find client by ids {id}@{server.server_id}"
)
raise Exception("Value not found") raise Exception("Value not found")
return client return client

View File

@ -25,9 +25,7 @@ class KnownUserRepositoryService(KnownUserRepositoryABC):
def get_users(self) -> List[KnownUser]: def get_users(self) -> List[KnownUser]:
users = List(KnownUser) users = List(KnownUser)
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {KnownUser.get_select_all_string()}")
__name__, f"Send SQL command: {KnownUser.get_select_all_string()}"
)
results = self._context.select(KnownUser.get_select_all_string()) results = self._context.select(KnownUser.get_select_all_string())
for result in results: for result in results:
self._logger.trace(__name__, f"Get known_user with id {result[0]}") self._logger.trace(__name__, f"Get known_user with id {result[0]}")
@ -36,9 +34,7 @@ class KnownUserRepositoryService(KnownUserRepositoryABC):
return users return users
def get_user_by_id(self, id: int) -> KnownUser: def get_user_by_id(self, id: int) -> KnownUser:
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {KnownUser.get_select_by_id_string(id)}")
__name__, f"Send SQL command: {KnownUser.get_select_by_id_string(id)}"
)
result = self._context.select(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]) return KnownUser(result[1], result[2], result[3], id=result[0])
@ -47,9 +43,7 @@ class KnownUserRepositoryService(KnownUserRepositoryABC):
__name__, __name__,
f"Send SQL command: {KnownUser.get_select_by_discord_id_string(discord_id)}", f"Send SQL command: {KnownUser.get_select_by_discord_id_string(discord_id)}",
) )
result = self._context.select( result = self._context.select(KnownUser.get_select_by_discord_id_string(discord_id))[0]
KnownUser.get_select_by_discord_id_string(discord_id)
)[0]
return KnownUser(result[1], result[2], result[3], id=result[0]) return KnownUser(result[1], result[2], result[3], id=result[0])
def find_user_by_discord_id(self, discord_id: int) -> Optional[KnownUser]: def find_user_by_discord_id(self, discord_id: int) -> Optional[KnownUser]:
@ -57,9 +51,7 @@ class KnownUserRepositoryService(KnownUserRepositoryABC):
__name__, __name__,
f"Send SQL command: {KnownUser.get_select_by_discord_id_string(discord_id)}", f"Send SQL command: {KnownUser.get_select_by_discord_id_string(discord_id)}",
) )
result = self._context.select( result = self._context.select(KnownUser.get_select_by_discord_id_string(discord_id))
KnownUser.get_select_by_discord_id_string(discord_id)
)
if result is None or len(result) == 0: if result is None or len(result) == 0:
return None return None

View File

@ -42,9 +42,7 @@ class LevelRepositoryService(LevelRepositoryABC):
def get_levels(self) -> List[Level]: def get_levels(self) -> List[Level]:
levels = List(Level) levels = List(Level)
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {Level.get_select_all_string()}")
__name__, f"Send SQL command: {Level.get_select_all_string()}"
)
results = self._context.select(Level.get_select_all_string()) results = self._context.select(Level.get_select_all_string())
for result in results: for result in results:
self._logger.trace(__name__, f"Get level with id {result[0]}") self._logger.trace(__name__, f"Get level with id {result[0]}")
@ -53,17 +51,13 @@ class LevelRepositoryService(LevelRepositoryABC):
return levels return levels
def get_level_by_id(self, id: int) -> Level: def get_level_by_id(self, id: int) -> Level:
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {Level.get_select_by_id_string(id)}")
__name__, f"Send SQL command: {Level.get_select_by_id_string(id)}"
)
result = self._context.select(Level.get_select_by_id_string(id))[0] result = self._context.select(Level.get_select_by_id_string(id))[0]
return self._level_from_result(result) return self._level_from_result(result)
def find_level_by_id(self, id: int) -> Optional[Level]: def find_level_by_id(self, id: int) -> Optional[Level]:
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {Level.get_select_by_id_string(id)}")
__name__, f"Send SQL command: {Level.get_select_by_id_string(id)}"
)
result = self._context.select(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: if result is None or len(result) == 0:
return None return None

View File

@ -22,9 +22,7 @@ class MigrationService:
self._db = db self._db = db
self._cursor = db.cursor self._cursor = db.cursor
self._migrations = List(type, MigrationABC.__subclasses__()).order_by( self._migrations = List(type, MigrationABC.__subclasses__()).order_by(lambda x: x.name)
lambda x: x.name
)
def migrate(self): def migrate(self):
self._logger.info(__name__, f"Running Migrations") self._logger.info(__name__, f"Running Migrations")
@ -40,21 +38,15 @@ class MigrationService:
__name__, __name__,
f"Running SQL Command: {MigrationHistory.get_select_by_id_string(migration_id)}", f"Running SQL Command: {MigrationHistory.get_select_by_id_string(migration_id)}",
) )
migration_from_db = self._db.select( migration_from_db = self._db.select(MigrationHistory.get_select_by_id_string(migration_id))
MigrationHistory.get_select_by_id_string(migration_id)
)
if migration_from_db is not None and len(migration_from_db) > 0: if migration_from_db is not None and len(migration_from_db) > 0:
continue continue
self._logger.debug(__name__, f"Running Migration {migration_id}") self._logger.debug(__name__, f"Running Migration {migration_id}")
migration_as_service: MigrationABC = self._services.get_service( migration_as_service: MigrationABC = self._services.get_service(migration)
migration
)
migration_as_service.upgrade() migration_as_service.upgrade()
self._cursor.execute(MigrationHistory(migration_id).insert_string) self._cursor.execute(MigrationHistory(migration_id).insert_string)
self._db.save_changes() self._db.save_changes()
except Exception as e: except Exception as e:
self._logger.error( self._logger.error(__name__, f"Cannot get migration with id {migration}", e)
__name__, f"Cannot get migration with id {migration}", e
)

View File

@ -19,9 +19,7 @@ class ServerRepositoryService(ServerRepositoryABC):
def get_servers(self) -> List[Server]: def get_servers(self) -> List[Server]:
servers = List(Server) servers = List(Server)
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {Server.get_select_all_string()}")
__name__, f"Send SQL command: {Server.get_select_all_string()}"
)
results = self._context.select(Server.get_select_all_string()) results = self._context.select(Server.get_select_all_string())
for result in results: for result in results:
servers.append(Server(result[1], id=result[0])) servers.append(Server(result[1], id=result[0]))
@ -30,9 +28,7 @@ class ServerRepositoryService(ServerRepositoryABC):
def get_filtered_servers(self, criteria: ServerSelectCriteria) -> FilteredResult: def get_filtered_servers(self, criteria: ServerSelectCriteria) -> FilteredResult:
servers = self.get_servers() servers = self.get_servers()
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {Server.get_select_all_string()}")
__name__, f"Send SQL command: {Server.get_select_all_string()}"
)
query = servers query = servers
# sort # sort
@ -44,9 +40,7 @@ class ServerRepositoryService(ServerRepositoryABC):
): ):
crit_sort_direction = criteria.sort_direction.lower() crit_sort_direction = criteria.sort_direction.lower()
if crit_sort_direction == "desc" or crit_sort_direction == "descending": if crit_sort_direction == "desc" or crit_sort_direction == "descending":
query = query.order_by_descending( query = query.order_by_descending(lambda x: getattr(x, criteria.sort_column))
lambda x: getattr(x, criteria.sort_column)
)
else: else:
query = query.order_by(lambda x: getattr(x, criteria.sort_column)) query = query.order_by(lambda x: getattr(x, criteria.sort_column))
@ -58,9 +52,7 @@ class ServerRepositoryService(ServerRepositoryABC):
return result return result
def get_server_by_id(self, server_id: int) -> Server: def get_server_by_id(self, server_id: int) -> Server:
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {Server.get_select_by_id_string(server_id)}")
__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] result = self._context.select(Server.get_select_by_id_string(server_id))[0]
return Server(result[1], id=result[0]) return Server(result[1], id=result[0])
@ -69,9 +61,7 @@ class ServerRepositoryService(ServerRepositoryABC):
__name__, __name__,
f"Send SQL command: {Server.get_select_by_discord_id_string(discord_id)}", f"Send SQL command: {Server.get_select_by_discord_id_string(discord_id)}",
) )
result = self._context.select( result = self._context.select(Server.get_select_by_discord_id_string(discord_id))[0]
Server.get_select_by_discord_id_string(discord_id)
)[0]
return Server(result[1], id=result[0]) return Server(result[1], id=result[0])
def find_server_by_discord_id(self, discord_id: int) -> Optional[Server]: def find_server_by_discord_id(self, discord_id: int) -> Optional[Server]:
@ -79,9 +69,7 @@ class ServerRepositoryService(ServerRepositoryABC):
__name__, __name__,
f"Send SQL command: {Server.get_select_by_discord_id_string(discord_id)}", f"Send SQL command: {Server.get_select_by_discord_id_string(discord_id)}",
) )
result = self._context.select( result = self._context.select(Server.get_select_by_discord_id_string(discord_id))
Server.get_select_by_discord_id_string(discord_id)
)
if result is None or len(result) == 0: if result is None or len(result) == 0:
return None return None

View File

@ -48,9 +48,7 @@ class StatisticRepositoryService(StatisticRepositoryABC):
def get_statistics(self) -> List[Statistic]: def get_statistics(self) -> List[Statistic]:
statistics = List(Statistic) statistics = List(Statistic)
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {Statistic.get_select_all_string()}")
__name__, f"Send SQL command: {Statistic.get_select_all_string()}"
)
results = self._context.select(Statistic.get_select_all_string()) results = self._context.select(Statistic.get_select_all_string())
for result in results: for result in results:
statistics.append(self._statistic_from_result(result)) statistics.append(self._statistic_from_result(result))
@ -70,9 +68,7 @@ class StatisticRepositoryService(StatisticRepositoryABC):
return statistics return statistics
def get_statistic_by_id(self, id: int) -> Statistic: def get_statistic_by_id(self, id: int) -> Statistic:
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {Statistic.get_select_by_id_string(id)}")
__name__, f"Send SQL command: {Statistic.get_select_by_id_string(id)}"
)
result = self._context.select(Statistic.get_select_by_id_string(id))[0] result = self._context.select(Statistic.get_select_by_id_string(id))[0]
return self._statistic_from_result(result) return self._statistic_from_result(result)
@ -81,9 +77,7 @@ class StatisticRepositoryService(StatisticRepositoryABC):
__name__, __name__,
f"Send SQL command: {Statistic.get_select_by_name_string(name, server_id)}", f"Send SQL command: {Statistic.get_select_by_name_string(name, server_id)}",
) )
result = self._context.select( result = self._context.select(Statistic.get_select_by_name_string(name, server_id))[0]
Statistic.get_select_by_name_string(name, server_id)
)[0]
return self._statistic_from_result(result) return self._statistic_from_result(result)
def find_statistic_by_name(self, name: str, server_id: int) -> Optional[Statistic]: def find_statistic_by_name(self, name: str, server_id: int) -> Optional[Statistic]:
@ -91,9 +85,7 @@ class StatisticRepositoryService(StatisticRepositoryABC):
__name__, __name__,
f"Send SQL command: {Statistic.get_select_by_name_string(name, server_id)}", f"Send SQL command: {Statistic.get_select_by_name_string(name, server_id)}",
) )
result = self._context.select( result = self._context.select(Statistic.get_select_by_name_string(name, server_id))
Statistic.get_select_by_name_string(name, server_id)
)
if result is None or len(result) == 0: if result is None or len(result) == 0:
return None return None

View File

@ -25,9 +25,7 @@ class UserJoinedServerRepositoryService(UserJoinedServerRepositoryABC):
def get_user_joined_servers(self) -> List[UserJoinedServer]: def get_user_joined_servers(self) -> List[UserJoinedServer]:
joins = List(UserJoinedServer) joins = List(UserJoinedServer)
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {UserJoinedServer.get_select_all_string()}")
__name__, f"Send SQL command: {UserJoinedServer.get_select_all_string()}"
)
results = self._context.select(UserJoinedServer.get_select_all_string()) results = self._context.select(UserJoinedServer.get_select_all_string())
for result in results: for result in results:
self._logger.trace(__name__, f"Get user-joined-server with id {result[0]}") self._logger.trace(__name__, f"Get user-joined-server with id {result[0]}")
@ -59,17 +57,13 @@ class UserJoinedServerRepositoryService(UserJoinedServerRepositoryABC):
id=result[0], id=result[0],
) )
def get_user_joined_servers_by_user_id( def get_user_joined_servers_by_user_id(self, user_id: int) -> List[UserJoinedServer]:
self, user_id: int
) -> List[UserJoinedServer]:
joins = List(UserJoinedServer) joins = List(UserJoinedServer)
self._logger.trace( self._logger.trace(
__name__, __name__,
f"Send SQL command: {UserJoinedServer.get_select_by_user_id_string(user_id)}", f"Send SQL command: {UserJoinedServer.get_select_by_user_id_string(user_id)}",
) )
results = self._context.select( results = self._context.select(UserJoinedServer.get_select_by_user_id_string(user_id))
UserJoinedServer.get_select_by_user_id_string(user_id)
)
for result in results: for result in results:
joins.append( joins.append(
UserJoinedServer( UserJoinedServer(
@ -84,16 +78,12 @@ class UserJoinedServerRepositoryService(UserJoinedServerRepositoryABC):
return joins return joins
def get_active_user_joined_server_by_user_id( def get_active_user_joined_server_by_user_id(self, user_id: int) -> UserJoinedServer:
self, user_id: int
) -> UserJoinedServer:
self._logger.trace( self._logger.trace(
__name__, __name__,
f"Send SQL command: {UserJoinedServer.get_select_by_user_id_string(user_id)}", f"Send SQL command: {UserJoinedServer.get_select_by_user_id_string(user_id)}",
) )
result = self._context.select( result = self._context.select(UserJoinedServer.get_select_active_by_user_id_string(user_id))[0]
UserJoinedServer.get_select_active_by_user_id_string(user_id)
)[0]
return UserJoinedServer( return UserJoinedServer(
self._users.get_user_by_id(result[1]), self._users.get_user_by_id(result[1]),
result[2], result[2],
@ -103,16 +93,12 @@ class UserJoinedServerRepositoryService(UserJoinedServerRepositoryABC):
id=result[0], id=result[0],
) )
def find_active_user_joined_server_by_user_id( def find_active_user_joined_server_by_user_id(self, user_id: int) -> Optional[UserJoinedServer]:
self, user_id: int
) -> Optional[UserJoinedServer]:
self._logger.trace( self._logger.trace(
__name__, __name__,
f"Send SQL command: {UserJoinedServer.get_select_by_user_id_string(user_id)}", f"Send SQL command: {UserJoinedServer.get_select_by_user_id_string(user_id)}",
) )
result = self._context.select( result = self._context.select(UserJoinedServer.get_select_active_by_user_id_string(user_id))
UserJoinedServer.get_select_active_by_user_id_string(user_id)
)
if result is None or len(result) == 0: if result is None or len(result) == 0:
return None return None
@ -128,19 +114,13 @@ class UserJoinedServerRepositoryService(UserJoinedServerRepositoryABC):
) )
def add_user_joined_server(self, user_joined_server: UserJoinedServer): def add_user_joined_server(self, user_joined_server: UserJoinedServer):
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {user_joined_server.insert_string}")
__name__, f"Send SQL command: {user_joined_server.insert_string}"
)
self._context.cursor.execute(user_joined_server.insert_string) self._context.cursor.execute(user_joined_server.insert_string)
def update_user_joined_server(self, user_joined_server: UserJoinedServer): def update_user_joined_server(self, user_joined_server: UserJoinedServer):
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {user_joined_server.udpate_string}")
__name__, f"Send SQL command: {user_joined_server.udpate_string}"
)
self._context.cursor.execute(user_joined_server.udpate_string) self._context.cursor.execute(user_joined_server.udpate_string)
def delete_user_joined_server(self, user_joined_server: UserJoinedServer): def delete_user_joined_server(self, user_joined_server: UserJoinedServer):
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {user_joined_server.delete_string}")
__name__, f"Send SQL command: {user_joined_server.delete_string}"
)
self._context.cursor.execute(user_joined_server.delete_string) self._context.cursor.execute(user_joined_server.delete_string)

View File

@ -33,9 +33,7 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
) )
results = self._context.select(UserJoinedVoiceChannel.get_select_all_string()) results = self._context.select(UserJoinedVoiceChannel.get_select_all_string())
for result in results: for result in results:
self._logger.trace( self._logger.trace(__name__, f"Get user-joined-voice-channel with id {result[0]}")
__name__, f"Get user-joined-voice-channel with id {result[0]}"
)
joins.append( joins.append(
UserJoinedVoiceChannel( UserJoinedVoiceChannel(
self._users.get_user_by_id(result[1]), self._users.get_user_by_id(result[1]),
@ -54,9 +52,7 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
__name__, __name__,
f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_id_string(id)}", f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_id_string(id)}",
) )
result = self._context.select( result = self._context.select(UserJoinedVoiceChannel.get_select_by_id_string(id))[0]
UserJoinedVoiceChannel.get_select_by_id_string(id)
)[0]
return UserJoinedVoiceChannel( return UserJoinedVoiceChannel(
self._users.get_user_by_id(result[1]), self._users.get_user_by_id(result[1]),
result[2], result[2],
@ -66,17 +62,13 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
id=result[0], id=result[0],
) )
def get_user_joined_voice_channels_by_user_id( def get_user_joined_voice_channels_by_user_id(self, user_id: int) -> List[UserJoinedVoiceChannel]:
self, user_id: int
) -> List[UserJoinedVoiceChannel]:
joins = List(UserJoinedVoiceChannel) joins = List(UserJoinedVoiceChannel)
self._logger.trace( self._logger.trace(
__name__, __name__,
f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_user_id_string(user_id)}", f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_user_id_string(user_id)}",
) )
results = self._context.select( results = self._context.select(UserJoinedVoiceChannel.get_select_by_user_id_string(user_id))
UserJoinedVoiceChannel.get_select_by_user_id_string(user_id)
)
for result in results: for result in results:
joins.append( joins.append(
UserJoinedVoiceChannel( UserJoinedVoiceChannel(
@ -91,16 +83,12 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
return joins return joins
def get_active_user_joined_voice_channel_by_user_id( def get_active_user_joined_voice_channel_by_user_id(self, user_id: int) -> UserJoinedVoiceChannel:
self, user_id: int
) -> UserJoinedVoiceChannel:
self._logger.trace( self._logger.trace(
__name__, __name__,
f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_user_id_string(user_id)}", f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_user_id_string(user_id)}",
) )
result = self._context.select( result = self._context.select(UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id))[0]
UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id)
)[0]
return UserJoinedVoiceChannel( return UserJoinedVoiceChannel(
self._users.get_user_by_id(result[1]), self._users.get_user_by_id(result[1]),
result[2], result[2],
@ -110,16 +98,12 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
id=result[0], id=result[0],
) )
def find_active_user_joined_voice_channel_by_user_id( def find_active_user_joined_voice_channel_by_user_id(self, user_id: int) -> Optional[UserJoinedVoiceChannel]:
self, user_id: int
) -> Optional[UserJoinedVoiceChannel]:
self._logger.trace( self._logger.trace(
__name__, __name__,
f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_user_id_string(user_id)}", f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_user_id_string(user_id)}",
) )
result = self._context.select( result = self._context.select(UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id))
UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id)
)
if result is None or len(result) == 0: if result is None or len(result) == 0:
return None return None
@ -134,17 +118,13 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
id=result[0], id=result[0],
) )
def find_active_user_joined_voice_channels_by_user_id( def find_active_user_joined_voice_channels_by_user_id(self, user_id: int) -> List[Optional[UserJoinedVoiceChannel]]:
self, user_id: int
) -> List[Optional[UserJoinedVoiceChannel]]:
self._logger.trace( self._logger.trace(
__name__, __name__,
f"Send SQL command: {UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id)}", f"Send SQL command: {UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id)}",
) )
result = List(UserJoinedVoiceChannel) result = List(UserJoinedVoiceChannel)
db_results = self._context.select( db_results = self._context.select(UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id))
UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id)
)
for db_result in db_results: for db_result in db_results:
result.append( result.append(
@ -160,28 +140,16 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
return result return result
def add_user_joined_voice_channel( def add_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel):
self, user_joined_voice_channel: UserJoinedVoiceChannel self._logger.trace(__name__, f"Send SQL command: {user_joined_voice_channel.insert_string}")
):
self._logger.trace(
__name__, f"Send SQL command: {user_joined_voice_channel.insert_string}"
)
self._context.cursor.execute(user_joined_voice_channel.insert_string) self._context.cursor.execute(user_joined_voice_channel.insert_string)
def update_user_joined_voice_channel( def update_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel):
self, user_joined_voice_channel: UserJoinedVoiceChannel self._logger.trace(__name__, f"Send SQL command: {user_joined_voice_channel.udpate_string}")
):
self._logger.trace(
__name__, f"Send SQL command: {user_joined_voice_channel.udpate_string}"
)
self._context.cursor.execute(user_joined_voice_channel.udpate_string) self._context.cursor.execute(user_joined_voice_channel.udpate_string)
def delete_user_joined_voice_channel( def delete_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel):
self, user_joined_voice_channel: UserJoinedVoiceChannel self._logger.trace(__name__, f"Send SQL command: {user_joined_voice_channel.delete_string}")
):
self._logger.trace(
__name__, f"Send SQL command: {user_joined_voice_channel.delete_string}"
)
self._context.cursor.execute(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): def delete_user_joined_voice_channel_by_user_id(self, user_id: int):
@ -189,6 +157,4 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
__name__, __name__,
f"Send SQL command: {UserJoinedVoiceChannel.delete_by_user_id_string}", f"Send SQL command: {UserJoinedVoiceChannel.delete_by_user_id_string}",
) )
self._context.cursor.execute( self._context.cursor.execute(UserJoinedVoiceChannel.delete_by_user_id_string(user_id))
UserJoinedVoiceChannel.delete_by_user_id_string(user_id)
)

View File

@ -51,16 +51,12 @@ class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepository
) )
results = self._context.select(UserMessageCountPerHour.get_select_all_string()) results = self._context.select(UserMessageCountPerHour.get_select_all_string())
for result in results: for result in results:
self._logger.trace( self._logger.trace(__name__, f"Get user message count per hour with id {result[0]}")
__name__, f"Get user message count per hour with id {result[0]}"
)
umcphs.append(self._from_result(result)) umcphs.append(self._from_result(result))
return umcphs return umcphs
def find_user_message_count_per_hour_by_user_id( def find_user_message_count_per_hour_by_user_id(self, user_id: int) -> List[Optional[UserMessageCountPerHour]]:
self, user_id: int
) -> List[Optional[UserMessageCountPerHour]]:
umcphs = List(UserMessageCountPerHour) umcphs = List(UserMessageCountPerHour)
sql = UserMessageCountPerHour.get_select_by_user_id_string(user_id) sql = UserMessageCountPerHour.get_select_by_user_id_string(user_id)
self._logger.trace(__name__, f"Send SQL command: {sql}") self._logger.trace(__name__, f"Send SQL command: {sql}")
@ -69,9 +65,7 @@ class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepository
return umcphs return umcphs
for result in results: for result in results:
self._logger.trace( self._logger.trace(__name__, f"Get user message count per hour with id {result[0]}")
__name__, f"Get user message count per hour with id {result[0]}"
)
umcphs.append(self._from_result(result)) umcphs.append(self._from_result(result))
return umcphs return umcphs
@ -79,9 +73,7 @@ class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepository
def get_user_message_count_per_hour_by_user_id_and_date( def get_user_message_count_per_hour_by_user_id_and_date(
self, user_id: int, date: datetime self, user_id: int, date: datetime
) -> UserMessageCountPerHour: ) -> UserMessageCountPerHour:
sql = UserMessageCountPerHour.get_select_by_user_id_and_date_string( sql = UserMessageCountPerHour.get_select_by_user_id_and_date_string(user_id, date)
user_id, date
)
self._logger.trace(__name__, f"Send SQL command: {sql}") self._logger.trace(__name__, f"Send SQL command: {sql}")
result = self._context.select(sql)[0] result = self._context.select(sql)[0]
return self._from_result(result) return self._from_result(result)
@ -89,9 +81,7 @@ class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepository
def find_user_message_count_per_hour_by_user_id_and_date( def find_user_message_count_per_hour_by_user_id_and_date(
self, user_id: int, date: datetime self, user_id: int, date: datetime
) -> Optional[UserMessageCountPerHour]: ) -> Optional[UserMessageCountPerHour]:
sql = UserMessageCountPerHour.get_select_by_user_id_and_date_string( sql = UserMessageCountPerHour.get_select_by_user_id_and_date_string(user_id, date)
user_id, date
)
self._logger.trace(__name__, f"Send SQL command: {sql}") self._logger.trace(__name__, f"Send SQL command: {sql}")
result = self._context.select(sql) result = self._context.select(sql)
if result is None or len(result) == 0: if result is None or len(result) == 0:

View File

@ -25,9 +25,7 @@ class UserRepositoryService(UserRepositoryABC):
def get_users(self) -> List[User]: def get_users(self) -> List[User]:
users = List(User) users = List(User)
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {User.get_select_all_string()}")
__name__, f"Send SQL command: {User.get_select_all_string()}"
)
results = self._context.select(User.get_select_all_string()) results = self._context.select(User.get_select_all_string())
for result in results: for result in results:
self._logger.trace(__name__, f"Get user with id {result[0]}") self._logger.trace(__name__, f"Get user with id {result[0]}")
@ -43,9 +41,7 @@ class UserRepositoryService(UserRepositoryABC):
return users return users
def get_user_by_id(self, id: int) -> User: def get_user_by_id(self, id: int) -> User:
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {User.get_select_by_id_string(id)}")
__name__, f"Send SQL command: {User.get_select_by_id_string(id)}"
)
result = self._context.select(User.get_select_by_id_string(id))[0] result = self._context.select(User.get_select_by_id_string(id))[0]
return User( return User(
@ -56,9 +52,7 @@ class UserRepositoryService(UserRepositoryABC):
) )
def find_user_by_id(self, id: int) -> Optional[User]: def find_user_by_id(self, id: int) -> Optional[User]:
self._logger.trace( self._logger.trace(__name__, f"Send SQL command: {User.get_select_by_id_string(id)}")
__name__, f"Send SQL command: {User.get_select_by_id_string(id)}"
)
result = self._context.select(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: if result is None or len(result) == 0:
return None return None
@ -91,16 +85,12 @@ class UserRepositoryService(UserRepositoryABC):
return users return users
def get_user_by_discord_id_and_server_id( def get_user_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> User:
self, discord_id: int, server_id: int
) -> User:
self._logger.trace( self._logger.trace(
__name__, __name__,
f"Send SQL command: {User.get_select_by_discord_id_and_server_id_string(discord_id, server_id)}", f"Send SQL command: {User.get_select_by_discord_id_and_server_id_string(discord_id, server_id)}",
) )
result = self._context.select( result = self._context.select(User.get_select_by_discord_id_and_server_id_string(discord_id, server_id))[0]
User.get_select_by_discord_id_and_server_id_string(discord_id, server_id)
)[0]
return User( return User(
result[1], result[1],
@ -109,16 +99,12 @@ class UserRepositoryService(UserRepositoryABC):
id=result[0], id=result[0],
) )
def find_user_by_discord_id_and_server_id( def find_user_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> Optional[User]:
self, discord_id: int, server_id: int
) -> Optional[User]:
self._logger.trace( self._logger.trace(
__name__, __name__,
f"Send SQL command: {User.get_select_by_discord_id_and_server_id_string(discord_id, server_id)}", f"Send SQL command: {User.get_select_by_discord_id_and_server_id_string(discord_id, server_id)}",
) )
result = self._context.select( result = self._context.select(User.get_select_by_discord_id_and_server_id_string(discord_id, server_id))
User.get_select_by_discord_id_and_server_id_string(discord_id, server_id)
)
if result is None or len(result) == 0: if result is None or len(result) == 0:
return None return None

View File

@ -20,14 +20,10 @@ class AutoRoleModule(ModuleABC):
def __init__(self, dc: DiscordCollectionABC): def __init__(self, dc: DiscordCollectionABC):
ModuleABC.__init__(self, dc, FeatureFlagsEnum.auto_role_module) ModuleABC.__init__(self, dc, FeatureFlagsEnum.auto_role_module)
def configure_configuration( def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
):
pass pass
def configure_services( def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
):
services.add_transient(AutoRoleReactionHandler) services.add_transient(AutoRoleReactionHandler)
# commands # commands
self._dc.add_command(AutoRoleGroup) self._dc.add_command(AutoRoleGroup)

View File

@ -53,14 +53,10 @@ class AutoRoleGroup(DiscordCommandABC):
self, interaction: discord.Interaction, current: str self, interaction: discord.Interaction, current: str
) -> TList[app_commands.Choice[str]]: ) -> TList[app_commands.Choice[str]]:
server = self._servers.get_server_by_discord_id(interaction.guild.id) server = self._servers.get_server_by_discord_id(interaction.guild.id)
auto_roles = self._auto_roles.get_auto_roles_by_server_id( auto_roles = self._auto_roles.get_auto_roles_by_server_id(server.server_id).select(lambda x: x.auto_role_id)
server.server_id
).select(lambda x: x.auto_role_id)
return [ return [
app_commands.Choice(name=auto_role, value=auto_role) app_commands.Choice(name=auto_role, value=auto_role)
for auto_role in self._client_utils.get_auto_complete_list( for auto_role in self._client_utils.get_auto_complete_list(auto_roles, current)
auto_roles, current
)
] ]
@commands.hybrid_group(name="auto-role") @commands.hybrid_group(name="auto-role")
@ -86,9 +82,7 @@ class AutoRoleGroup(DiscordCommandABC):
server = self._servers.get_server_by_discord_id(ctx.guild.id) server = self._servers.get_server_by_discord_id(ctx.guild.id)
auto_roles = self._auto_roles.get_auto_roles_by_server_id(server.server_id) auto_roles = self._auto_roles.get_auto_roles_by_server_id(server.server_id)
if auto_roles.count() < 1: if auto_roles.count() < 1:
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.auto_role.error.nothing_found"))
ctx, self._t.transform("modules.auto_role.error.nothing_found")
)
self._logger.trace(__name__, f"Finished command auto-role list") self._logger.trace(__name__, f"Finished command auto-role list")
return return
@ -116,9 +110,7 @@ class AutoRoleGroup(DiscordCommandABC):
@CommandChecks.check_is_ready() @CommandChecks.check_is_ready()
@CommandChecks.check_is_member_moderator() @CommandChecks.check_is_member_moderator()
async def add(self, ctx: Context, channel: discord.TextChannel, message_id: str): async def add(self, ctx: Context, channel: discord.TextChannel, message_id: str):
self._logger.debug( self._logger.debug(__name__, f"Received command auto-role add {ctx} {message_id}")
__name__, f"Received command auto-role add {ctx} {message_id}"
)
message = ( message = (
List( List(
@ -129,56 +121,38 @@ class AutoRoleGroup(DiscordCommandABC):
.single_or_default() .single_or_default()
) )
if message is None: if message is None:
self._logger.debug( self._logger.debug(__name__, f"Message with id {message_id} not found in {channel.name}")
__name__, f"Message with id {message_id} not found in {channel.name}"
)
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(
ctx, ctx,
self._t.transform("modules.auto_role.add.error.not_found").format( self._t.transform("modules.auto_role.add.error.not_found").format(message_id, channel.mention),
message_id, channel.mention
),
) )
self._logger.trace(__name__, f"Finished command auto-role add") self._logger.trace(__name__, f"Finished command auto-role add")
return return
if self._auto_roles.find_auto_role_by_message_id(int(message_id)) is not None: if self._auto_roles.find_auto_role_by_message_id(int(message_id)) is not None:
self._logger.debug( self._logger.debug(__name__, f"auto-role for message {message_id} already exists")
__name__, f"auto-role for message {message_id} already exists"
)
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(
ctx, ctx,
self._t.transform("modules.auto_role.add.error.already_exists").format( self._t.transform("modules.auto_role.add.error.already_exists").format(message_id),
message_id
),
) )
self._logger.trace(__name__, f"Finished command auto-role add") self._logger.trace(__name__, f"Finished command auto-role add")
return return
server_id = self._servers.get_server_by_discord_id(ctx.guild.id).server_id server_id = self._servers.get_server_by_discord_id(ctx.guild.id).server_id
self._auto_roles.add_auto_role( self._auto_roles.add_auto_role(AutoRole(server_id, int(channel.id), int(message_id)))
AutoRole(server_id, int(channel.id), int(message_id))
)
self._db_context.save_changes() self._db_context.save_changes()
self._logger.info( self._logger.info(__name__, f"Saved auto-role for message {message_id} at server {server_id}")
__name__, f"Saved auto-role for message {message_id} at server {server_id}"
)
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(
ctx, self._t.transform("modules.auto_role.add.success").format(message_id) ctx, self._t.transform("modules.auto_role.add.success").format(message_id)
) )
self._logger.trace(__name__, f"Finished command auto-role add") self._logger.trace(__name__, f"Finished command auto-role add")
@add.autocomplete("message_id") @add.autocomplete("message_id")
async def add_autocomplete( async def add_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]:
self, interaction: discord.Interaction, current: str channel = discord.utils.get(interaction.guild.text_channels, id=interaction.channel_id)
) -> TList[app_commands.Choice[str]]:
channel = discord.utils.get(
interaction.guild.text_channels, id=interaction.channel_id
)
try: try:
channel_from_data = interaction.data["options"][0]["options"][0]["value"] channel_from_data = interaction.data["options"][0]["options"][0]["value"]
found_channel = discord.utils.get( found_channel = discord.utils.get(interaction.guild.text_channels, id=int(channel_from_data))
interaction.guild.text_channels, id=int(channel_from_data)
)
if found_channel is not None: if found_channel is not None:
channel = found_channel channel = found_channel
finally: finally:
@ -186,9 +160,7 @@ class AutoRoleGroup(DiscordCommandABC):
messages = [message async for message in channel.history(limit=10)] messages = [message async for message in channel.history(limit=10)]
return [ return [
app_commands.Choice( app_commands.Choice(name=f"{message.author}@{message.created_at}", value=str(message.id))
name=f"{message.author}@{message.created_at}", value=str(message.id)
)
for message in messages for message in messages
if current in str(message.id) if current in str(message.id)
] ]
@ -198,25 +170,19 @@ class AutoRoleGroup(DiscordCommandABC):
@CommandChecks.check_is_ready() @CommandChecks.check_is_ready()
@CommandChecks.check_is_member_moderator() @CommandChecks.check_is_member_moderator()
async def remove(self, ctx: Context, auto_role: int): async def remove(self, ctx: Context, auto_role: int):
self._logger.debug( self._logger.debug(__name__, f"Received command auto-role remove {ctx} {auto_role}")
__name__, f"Received command auto-role remove {ctx} {auto_role}"
)
auto_role_from_db = self._auto_roles.find_auto_role_by_id(auto_role) auto_role_from_db = self._auto_roles.find_auto_role_by_id(auto_role)
if auto_role_from_db is None: if auto_role_from_db is None:
self._logger.debug(__name__, f"auto-role {auto_role} not found") self._logger.debug(__name__, f"auto-role {auto_role} not found")
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(
ctx, ctx,
self._t.transform("modules.auto_role.remove.error.not_found").format( self._t.transform("modules.auto_role.remove.error.not_found").format(auto_role),
auto_role
),
) )
self._logger.trace(__name__, f"Finished command auto-role remove") self._logger.trace(__name__, f"Finished command auto-role remove")
return return
for rule in self._auto_roles.get_auto_role_rules_by_auto_role_id( for rule in self._auto_roles.get_auto_role_rules_by_auto_role_id(auto_role_from_db.auto_role_id):
auto_role_from_db.auto_role_id
):
self._auto_roles.delete_auto_role_rule(rule) self._auto_roles.delete_auto_role_rule(rule)
self._logger.info(__name__, f"Removed auto-role rule {rule.role_id}") self._logger.info(__name__, f"Removed auto-role rule {rule.role_id}")
@ -296,20 +262,14 @@ class AutoRoleGroup(DiscordCommandABC):
@CommandChecks.check_is_ready() @CommandChecks.check_is_ready()
@CommandChecks.check_is_member_moderator() @CommandChecks.check_is_member_moderator()
async def add(self, ctx: Context, auto_role: int, emoji_name: str, role_id: str): async def add(self, ctx: Context, auto_role: int, emoji_name: str, role_id: str):
self._logger.debug( self._logger.debug(__name__, f"Received command auto-role add {ctx} {auto_role}")
__name__, f"Received command auto-role add {ctx} {auto_role}"
)
emoji = discord.utils.get(self._bot.emojis, name=emoji_name) emoji = discord.utils.get(self._bot.emojis, name=emoji_name)
if emoji is None: if emoji is None:
self._logger.debug( self._logger.debug(__name__, f"auto-role rule add emoji {emoji_name} not found")
__name__, f"auto-role rule add emoji {emoji_name} not found"
)
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(
ctx, ctx,
self._t.transform( self._t.transform("modules.auto_role.rule.add.error.emoji_not_found").format(emoji_name, auto_role),
"modules.auto_role.rule.add.error.emoji_not_found"
).format(emoji_name, auto_role),
) )
self._logger.trace(__name__, f"Finished command auto-role add") self._logger.trace(__name__, f"Finished command auto-role add")
return return
@ -319,9 +279,7 @@ class AutoRoleGroup(DiscordCommandABC):
self._logger.debug(__name__, f"auto-role rule add role {role_id} not found") self._logger.debug(__name__, f"auto-role rule add role {role_id} not found")
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(
ctx, ctx,
self._t.transform( self._t.transform("modules.auto_role.rule.add.error.role_not_found").format(role_id, auto_role),
"modules.auto_role.rule.add.error.role_not_found"
).format(role_id, auto_role),
) )
self._logger.trace(__name__, f"Finished command auto-role add") self._logger.trace(__name__, f"Finished command auto-role add")
return return
@ -330,9 +288,7 @@ class AutoRoleGroup(DiscordCommandABC):
if auto_role_from_db is None: if auto_role_from_db is None:
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(
ctx, ctx,
self._t.transform("modules.auto_role.remove.error.not_found").format( self._t.transform("modules.auto_role.remove.error.not_found").format(auto_role),
auto_role
),
) )
self._logger.trace(__name__, f"Finished command auto-role rule add") self._logger.trace(__name__, f"Finished command auto-role rule add")
return return
@ -345,16 +301,12 @@ class AutoRoleGroup(DiscordCommandABC):
): ):
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(
ctx, ctx,
self._t.transform("modules.auto_role.add.error.already_exists").format( self._t.transform("modules.auto_role.add.error.already_exists").format(auto_role),
auto_role
),
) )
self._logger.trace(__name__, f"Finished command auto-role rule add") self._logger.trace(__name__, f"Finished command auto-role rule add")
return return
self._auto_roles.add_auto_role_rule( self._auto_roles.add_auto_role_rule(AutoRoleRule(auto_role, emoji_name, int(role_id)))
AutoRoleRule(auto_role, emoji_name, int(role_id))
)
self._db_context.save_changes() self._db_context.save_changes()
rule = ( rule = (
self._auto_roles.get_auto_role_rules_by_auto_role_id(auto_role) self._auto_roles.get_auto_role_rules_by_auto_role_id(auto_role)
@ -365,11 +317,7 @@ class AutoRoleGroup(DiscordCommandABC):
guild: Guild = self._bot.guilds.where(lambda g: g == ctx.guild).single() guild: Guild = self._bot.guilds.where(lambda g: g == ctx.guild).single()
channel = guild.get_channel(auto_role_from_db.discord_channel_id) channel = guild.get_channel(auto_role_from_db.discord_channel_id)
message = await channel.fetch_message(auto_role_from_db.discord_message_id) message = await channel.fetch_message(auto_role_from_db.discord_message_id)
emoji = ( emoji = List(discord.Emoji, guild.emojis).where(lambda x: x.name == rule.emoji_name).single()
List(discord.Emoji, guild.emojis)
.where(lambda x: x.name == rule.emoji_name)
.single()
)
if emoji is None: if emoji is None:
self._logger.debug(__name__, f"Emoji {rule.emoji_name} not found") self._logger.debug(__name__, f"Emoji {rule.emoji_name} not found")
@ -388,28 +336,20 @@ class AutoRoleGroup(DiscordCommandABC):
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(
ctx, ctx,
self._t.transform("modules.auto_role.rule.add.success").format( self._t.transform("modules.auto_role.rule.add.success").format(emoji, role.mention, auto_role),
emoji, role.mention, auto_role
),
) )
self._logger.trace(__name__, f"Finished command auto-role rule add") self._logger.trace(__name__, f"Finished command auto-role rule add")
@add.autocomplete("auto_role") @add.autocomplete("auto_role")
async def add_autocomplete( async def add_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]:
self, interaction: discord.Interaction, current: str
) -> TList[app_commands.Choice[str]]:
return await self._auto_role_auto_complete(interaction, current) return await self._auto_role_auto_complete(interaction, current)
@add.autocomplete("emoji_name") @add.autocomplete("emoji_name")
async def add_autocomplete( async def add_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]:
self, interaction: discord.Interaction, current: str
) -> TList[app_commands.Choice[str]]:
emojis = List(discord.Emoji, interaction.guild.emojis) emojis = List(discord.Emoji, interaction.guild.emojis)
return [ return [
app_commands.Choice(name=emoji.name, value=emoji.name) app_commands.Choice(name=emoji.name, value=emoji.name)
for emoji in self._client_utils.get_auto_complete_list( for emoji in self._client_utils.get_auto_complete_list(emojis, current, lambda e: e.name)
emojis, current, lambda e: e.name
)
] ]
@add.autocomplete("role_id") @add.autocomplete("role_id")
@ -419,9 +359,7 @@ class AutoRoleGroup(DiscordCommandABC):
roles = List(discord.Role, interaction.guild.roles) roles = List(discord.Role, interaction.guild.roles)
return [ return [
app_commands.Choice(name=role.name, value=str(role.id)) app_commands.Choice(name=role.name, value=str(role.id))
for role in self._client_utils.get_auto_complete_list( for role in self._client_utils.get_auto_complete_list(roles, current, lambda r: r.name)
roles, current, lambda r: r.name
)
] ]
@rule.command() @rule.command()
@ -429,18 +367,14 @@ class AutoRoleGroup(DiscordCommandABC):
@CommandChecks.check_is_ready() @CommandChecks.check_is_ready()
@CommandChecks.check_is_member_moderator() @CommandChecks.check_is_member_moderator()
async def remove(self, ctx: Context, auto_role_rule: int): async def remove(self, ctx: Context, auto_role_rule: int):
self._logger.debug( self._logger.debug(__name__, f"Received command auto-role remove {ctx} {auto_role_rule}")
__name__, f"Received command auto-role remove {ctx} {auto_role_rule}"
)
auto_role_from_db = self._auto_roles.get_auto_role_rule_by_id(auto_role_rule) auto_role_from_db = self._auto_roles.get_auto_role_rule_by_id(auto_role_rule)
if auto_role_from_db is None: if auto_role_from_db is None:
self._logger.debug(__name__, f"auto-role rule {auto_role_rule} not found") self._logger.debug(__name__, f"auto-role rule {auto_role_rule} not found")
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(
ctx, ctx,
self._t.transform("modules.auto_role.remove.error.not_found").format( self._t.transform("modules.auto_role.remove.error.not_found").format(auto_role_rule),
auto_role_rule
),
) )
self._logger.trace(__name__, f"Finished command auto-role rule remove") self._logger.trace(__name__, f"Finished command auto-role rule remove")
return return
@ -450,9 +384,7 @@ class AutoRoleGroup(DiscordCommandABC):
self._logger.info(__name__, f"Removed auto-role rule {auto_role_rule}") self._logger.info(__name__, f"Removed auto-role rule {auto_role_rule}")
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(
ctx, ctx,
self._t.transform("modules.auto_role.rule.remove.success").format( self._t.transform("modules.auto_role.rule.remove.success").format(auto_role_rule),
auto_role_rule
),
) )
self._logger.trace(__name__, f"Finished command auto-role remove") self._logger.trace(__name__, f"Finished command auto-role remove")
@ -461,18 +393,12 @@ class AutoRoleGroup(DiscordCommandABC):
self, interaction: discord.Interaction, current: str self, interaction: discord.Interaction, current: str
) -> TList[app_commands.Choice[str]]: ) -> TList[app_commands.Choice[str]]:
server = self._servers.get_server_by_discord_id(interaction.guild.id) server = self._servers.get_server_by_discord_id(interaction.guild.id)
auto_roles = self._auto_roles.get_auto_roles_by_server_id( auto_roles = self._auto_roles.get_auto_roles_by_server_id(server.server_id).select(lambda x: x.auto_role_id)
server.server_id rules = auto_roles.select_many(lambda ar: self._auto_roles.get_auto_role_rules_by_auto_role_id(ar))
).select(lambda x: x.auto_role_id)
rules = auto_roles.select_many(
lambda ar: self._auto_roles.get_auto_role_rules_by_auto_role_id(ar)
)
return [ return [
app_commands.Choice( app_commands.Choice(
name=f"{rule.auto_role_rule_id} {rule.emoji_name} {interaction.guild.get_role(int(rule.role_id))}", name=f"{rule.auto_role_rule_id} {rule.emoji_name} {interaction.guild.get_role(int(rule.role_id))}",
value=rule.auto_role_rule_id, value=rule.auto_role_rule_id,
) )
for rule in self._client_utils.get_auto_complete_list( for rule in self._client_utils.get_auto_complete_list(rules, current, lambda r: r.auto_role_rule_id)
rules, current, lambda r: r.auto_role_rule_id
)
] ]

View File

@ -23,9 +23,7 @@ class AutoRoleReactionHandler:
self._servers = servers self._servers = servers
self._auto_roles = auto_roles self._auto_roles = auto_roles
self._message_ids = self._auto_roles.get_auto_roles().select( self._message_ids = self._auto_roles.get_auto_roles().select(lambda x: x.discord_message_id)
lambda x: x.discord_message_id
)
self._roles = self._auto_roles.get_auto_roles() self._roles = self._auto_roles.get_auto_roles()
async def handle(self, payload: RawReactionActionEvent, r_type=None) -> None: async def handle(self, payload: RawReactionActionEvent, r_type=None) -> None:
@ -37,9 +35,7 @@ class AutoRoleReactionHandler:
guild = self._bot.get_guild(payload.guild_id) guild = self._bot.get_guild(payload.guild_id)
user = guild.get_member(payload.user_id) user = guild.get_member(payload.user_id)
if user is None: if user is None:
self._logger.warn( self._logger.warn(__name__, f"User {payload.user_id} in {guild.name} not found - skipping")
__name__, f"User {payload.user_id} in {guild.name} not found - skipping"
)
return return
if user.bot: if user.bot:
@ -54,9 +50,7 @@ class AutoRoleReactionHandler:
self._logger.debug(__name__, f"auto-role for message not found - skipping") self._logger.debug(__name__, f"auto-role for message not found - skipping")
return return
rules: List[ rules: List[AutoRoleRule] = self._auto_roles.get_auto_role_rules_by_auto_role_id(auto_role.auto_role_id)
AutoRoleRule
] = self._auto_roles.get_auto_role_rules_by_auto_role_id(auto_role.auto_role_id)
if rules.count() == 0: if rules.count() == 0:
self._logger.debug(__name__, f"auto-role rules not found - skipping") self._logger.debug(__name__, f"auto-role rules not found - skipping")
return return

View File

@ -37,14 +37,10 @@ class BaseModule(ModuleABC):
def __init__(self, dc: DiscordCollectionABC): def __init__(self, dc: DiscordCollectionABC):
ModuleABC.__init__(self, dc, FeatureFlagsEnum.base_module) ModuleABC.__init__(self, dc, FeatureFlagsEnum.base_module)
def configure_configuration( def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
):
pass pass
def configure_services( def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
):
services.add_transient(BaseHelperABC, BaseHelperService) services.add_transient(BaseHelperABC, BaseHelperService)
services.add_transient(BaseReactionHandler) services.add_transient(BaseReactionHandler)
# commands # commands
@ -59,22 +55,12 @@ class BaseModule(ModuleABC):
self._dc.add_command(UserGroup) self._dc.add_command(UserGroup)
# events # events
self._dc.add_event(DiscordEventTypesEnum.on_command.value, BaseOnCommandEvent) self._dc.add_event(DiscordEventTypesEnum.on_command.value, BaseOnCommandEvent)
self._dc.add_event( self._dc.add_event(DiscordEventTypesEnum.on_command_error.value, BaseOnCommandErrorEvent)
DiscordEventTypesEnum.on_command_error.value, BaseOnCommandErrorEvent self._dc.add_event(DiscordEventTypesEnum.on_member_join.value, BaseOnMemberJoinEvent)
) self._dc.add_event(DiscordEventTypesEnum.on_member_remove.value, BaseOnMemberRemoveEvent)
self._dc.add_event(
DiscordEventTypesEnum.on_member_join.value, BaseOnMemberJoinEvent
)
self._dc.add_event(
DiscordEventTypesEnum.on_member_remove.value, BaseOnMemberRemoveEvent
)
self._dc.add_event(DiscordEventTypesEnum.on_message.value, BaseOnMessageEvent) self._dc.add_event(DiscordEventTypesEnum.on_message.value, BaseOnMessageEvent)
self._dc.add_event( self._dc.add_event(DiscordEventTypesEnum.on_message_delete.value, BaseOnMessageDeleteEvent)
DiscordEventTypesEnum.on_message_delete.value, BaseOnMessageDeleteEvent self._dc.add_event(DiscordEventTypesEnum.on_raw_reaction_add.value, BaseOnRawReactionAddEvent)
)
self._dc.add_event(
DiscordEventTypesEnum.on_raw_reaction_add.value, BaseOnRawReactionAddEvent
)
self._dc.add_event( self._dc.add_event(
DiscordEventTypesEnum.on_raw_reaction_remove.value, DiscordEventTypesEnum.on_raw_reaction_remove.value,
BaseOnRawReactionRemoveEvent, BaseOnRawReactionRemoveEvent,

View File

@ -39,9 +39,7 @@ class AFKCommand(DiscordCommandABC):
@CommandChecks.check_is_ready() @CommandChecks.check_is_ready()
async def afk(self, ctx: Context): async def afk(self, ctx: Context):
self._logger.debug(__name__, f"Received command afk {ctx}") self._logger.debug(__name__, f"Received command afk {ctx}")
settings: BaseServerSettings = self._config.get_configuration( settings: BaseServerSettings = self._config.get_configuration(f"BaseServerSettings_{ctx.guild.id}")
f"BaseServerSettings_{ctx.guild.id}"
)
if ctx.author.voice is None or ctx.author.voice.channel is None: if ctx.author.voice is None or ctx.author.voice.channel is None:
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(
@ -52,9 +50,7 @@ class AFKCommand(DiscordCommandABC):
return return
self._bot.loop.create_task( self._bot.loop.create_task(
self._message_service.send_ctx_msg( self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.afk_command_move_message"))
ctx, self._t.transform("modules.base.afk_command_move_message")
)
) )
channel: VoiceChannel = ctx.guild.get_channel(settings.afk_command_channel_id) channel: VoiceChannel = ctx.guild.get_channel(settings.afk_command_channel_id)
try: try:
@ -66,8 +62,6 @@ class AFKCommand(DiscordCommandABC):
f"Cannot move user {ctx.author.id} to channel {ctx.channel.id}", f"Cannot move user {ctx.author.id} to channel {ctx.channel.id}",
e, e,
) )
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(ctx, self._t.transform("common.no_permission_message"))
ctx, self._t.transform("common.no_permission_message")
)
self._logger.trace(__name__, f"Finished afk command") self._logger.trace(__name__, f"Finished afk command")

View File

@ -39,9 +39,7 @@ class HelpCommand(DiscordCommandABC):
@CommandChecks.check_is_ready() @CommandChecks.check_is_ready()
async def help(self, ctx: Context, persistent_flag: str = None): async def help(self, ctx: Context, persistent_flag: str = None):
self._logger.debug(__name__, f"Received command help {ctx}:{persistent_flag}") self._logger.debug(__name__, f"Received command help {ctx}:{persistent_flag}")
settings: BaseServerSettings = self._config.get_configuration( settings: BaseServerSettings = self._config.get_configuration(f"BaseServerSettings_{ctx.guild.id}")
f"BaseServerSettings_{ctx.guild.id}"
)
is_persistent = persistent_flag == "--stay" is_persistent = persistent_flag == "--stay"
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(
ctx, ctx,
@ -52,8 +50,6 @@ class HelpCommand(DiscordCommandABC):
self._logger.trace(__name__, f"Finished help command") self._logger.trace(__name__, f"Finished help command")
@help.autocomplete("persistent_flag") @help.autocomplete("persistent_flag")
async def help_autocomplete( async def help_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
self, interaction: discord.Interaction, current: str
) -> List[app_commands.Choice[str]]:
flags = ["--stay"] flags = ["--stay"]
return [app_commands.Choice(name=key, value=key) for key in flags] return [app_commands.Choice(name=key, value=key) for key in flags]

View File

@ -55,10 +55,7 @@ class InfoCommand(DiscordCommandABC):
) )
start_time = self._config.get_configuration("Bot_StartTime") start_time = self._config.get_configuration("Bot_StartTime")
ontime = round( 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, 2,
) )
embed.add_field( embed.add_field(

View File

@ -56,9 +56,7 @@ class MassMoveCommand(DiscordCommandABC):
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(
ctx, ctx,
self._t.transform("modules.base.mass_move.moved").format( self._t.transform("modules.base.mass_move.moved").format(channel_from.mention, channel_to.mention),
channel_from.mention, channel_to.mention
),
) )
self._logger.trace(__name__, f"Finished mass-move command") self._logger.trace(__name__, f"Finished mass-move command")

View File

@ -59,16 +59,10 @@ class PingCommand(DiscordCommandABC):
color=int("ef9d0d", 16), color=int("ef9d0d", 16),
) )
server = self._servers.get_server_by_discord_id(ctx.guild.id) server = self._servers.get_server_by_discord_id(ctx.guild.id)
settings: BaseServerSettings = self._base_helper.get_config( settings: BaseServerSettings = self._base_helper.get_config(server.discord_server_id)
server.discord_server_id
)
for server in settings.ping_urls: for server in settings.ping_urls:
embed.add_field( embed.add_field(name=server, value=f"{self._get_ping(server)} ms", inline=False)
name=server, value=f"{self._get_ping(server)} ms", inline=False
)
await self._message_service.send_ctx_msg(ctx, embed) await self._message_service.send_ctx_msg(ctx, embed)
else: else:
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.pong"))
ctx, self._t.transform("modules.base.pong")
)
self._logger.trace(__name__, f"Finished ping command") self._logger.trace(__name__, f"Finished ping command")

View File

@ -34,9 +34,7 @@ class PresenceCommand(DiscordCommandABC):
if text == "": if text == "":
await self._bot.change_presence(activity=None) await self._bot.change_presence(activity=None)
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.presence.removed"))
ctx, self._t.transform("modules.base.presence.removed")
)
return return
if len(text) > 128: if len(text) > 128:
@ -46,8 +44,6 @@ class PresenceCommand(DiscordCommandABC):
return return
await self._bot.change_presence(activity=discord.Game(name=text)) await self._bot.change_presence(activity=discord.Game(name=text))
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.presence.changed"))
ctx, self._t.transform("modules.base.presence.changed")
)
self._logger.trace(__name__, f"Finished presence command") self._logger.trace(__name__, f"Finished presence command")

View File

@ -41,20 +41,14 @@ class PurgeCommand(DiscordCommandABC):
@CommandChecks.check_is_member_moderator() @CommandChecks.check_is_member_moderator()
async def purge(self, ctx: Context): async def purge(self, ctx: Context):
self._logger.debug(__name__, f"Received command purge {ctx}") self._logger.debug(__name__, f"Received command purge {ctx}")
server_settings: ServerSettings = self._config.get_configuration( server_settings: ServerSettings = self._config.get_configuration(f"ServerSettings_{ctx.guild.id}")
f"ServerSettings_{ctx.guild.id}"
)
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.moderator.purge_message"))
ctx, self._t.transform("modules.moderator.purge_message")
)
await asyncio.sleep(server_settings.message_delete_timer) await asyncio.sleep(server_settings.message_delete_timer)
try: try:
await ctx.channel.purge() await ctx.channel.purge()
except Exception as e: except Exception as e:
self._logger.error(__name__, f"Cannot purge channel {ctx.channel.id}", e) self._logger.error(__name__, f"Cannot purge channel {ctx.channel.id}", e)
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(ctx, self._t.transform("common.bot_has_no_permission_message"))
ctx, self._t.transform("common.bot_has_no_permission_message")
)
self._logger.trace(__name__, f"Finished purge command") self._logger.trace(__name__, f"Finished purge command")

View File

@ -81,9 +81,7 @@ class UserGroup(DiscordCommandABC):
member = ctx.author member = ctx.author
server = self._servers.find_server_by_discord_id(ctx.guild.id) server = self._servers.find_server_by_discord_id(ctx.guild.id)
user = self._users.find_user_by_discord_id_and_server_id( user = self._users.find_user_by_discord_id_and_server_id(member.id, server.server_id)
member.id, server.server_id
)
if atr == "xp": if atr == "xp":
if is_remove: if is_remove:
@ -104,9 +102,7 @@ class UserGroup(DiscordCommandABC):
type = "add" if not is_remove else "remove" type = "add" if not is_remove else "remove"
await self._message_service.send_interaction_msg( await self._message_service.send_interaction_msg(
ctx.interaction, ctx.interaction,
self._t.transform(f"modules.base.user.{type}.{atr.lower()}").format( self._t.transform(f"modules.base.user.{type}.{atr.lower()}").format(atr, value, member.mention),
atr, value, member.mention
),
) )
@commands.hybrid_group() @commands.hybrid_group()
@ -117,41 +113,25 @@ class UserGroup(DiscordCommandABC):
@user.command() @user.command()
@commands.guild_only() @commands.guild_only()
@CommandChecks.check_is_ready() @CommandChecks.check_is_ready()
async def info( async def info(self, ctx: Context, member: Optional[discord.Member] = None, *, wait: int = None):
self, ctx: Context, member: Optional[discord.Member] = None, *, wait: int = None self._logger.debug(__name__, f"Received command user-info {ctx}:{member},{wait}")
):
self._logger.debug(
__name__, f"Received command user-info {ctx}:{member},{wait}"
)
is_mod = self._permissions.is_member_moderator(ctx.author) is_mod = self._permissions.is_member_moderator(ctx.author)
if member is not None and not is_mod: if member is not None and not is_mod:
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(ctx, self._t.transform("common.no_permission_message"))
ctx, self._t.transform("common.no_permission_message")
)
return return
if member is None or not isinstance(member, discord.Member): if member is None or not isinstance(member, discord.Member):
member = ctx.author member = ctx.author
server = self._servers.find_server_by_discord_id(ctx.guild.id) server = self._servers.find_server_by_discord_id(ctx.guild.id)
user = self._users.find_user_by_discord_id_and_server_id( user = self._users.find_user_by_discord_id_and_server_id(member.id, server.server_id)
member.id, server.server_id joins = self._user_joined_servers.get_user_joined_servers_by_user_id(user.user_id)
)
joins = self._user_joined_servers.get_user_joined_servers_by_user_id(
user.user_id
)
embed = discord.Embed( embed = discord.Embed(title=member.name, description=member.name, color=int("ef9d0d", 16))
title=member.name, description=member.name, color=int("ef9d0d", 16)
)
embed.add_field( embed.add_field(name=self._t.transform("modules.base.user.atr.id"), value=member.id)
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.name"), value=member.name
)
embed.add_field( embed.add_field(
name=self._t.transform("modules.base.user.atr.discord_join"), name=self._t.transform("modules.base.user.atr.discord_join"),
value=self._date.transform(member.created_at), value=self._date.transform(member.created_at),
@ -162,9 +142,7 @@ class UserGroup(DiscordCommandABC):
value=self._date.transform(member.joined_at), value=self._date.transform(member.joined_at),
inline=False, inline=False,
) )
embed.add_field( embed.add_field(name=self._t.transform("modules.base.user.atr.xp"), value=str(user.xp))
name=self._t.transform("modules.base.user.atr.xp"), value=str(user.xp)
)
embed.add_field( embed.add_field(
name=self._t.transform("modules.base.user.atr.ontime"), name=self._t.transform("modules.base.user.atr.ontime"),
value=str(self._client_utils.get_ontime_for_user(user)), value=str(self._client_utils.get_ontime_for_user(user)),
@ -210,9 +188,7 @@ class UserGroup(DiscordCommandABC):
) )
# send to interaction because of sensitive data # send to interaction because of sensitive data
await self._message_service.send_interaction_msg( await self._message_service.send_interaction_msg(ctx.interaction, embed, wait_before_delete=wait)
ctx.interaction, embed, wait_before_delete=wait
)
self._logger.trace(__name__, f"Finished user-info command") self._logger.trace(__name__, f"Finished user-info command")
@user.command() @user.command()
@ -223,18 +199,14 @@ class UserGroup(DiscordCommandABC):
is_mod = self._permissions.is_member_moderator(ctx.author) is_mod = self._permissions.is_member_moderator(ctx.author)
if member is not None and not is_mod: if member is not None and not is_mod:
await self._message_service.send_ctx_msg( await self._message_service.send_ctx_msg(ctx, self._t.transform("common.no_permission_message"))
ctx, self._t.transform("common.no_permission_message")
)
return return
if member is None or not isinstance(member, discord.Member): if member is None or not isinstance(member, discord.Member):
member = ctx.author member = ctx.author
server = self._servers.find_server_by_discord_id(ctx.guild.id) server = self._servers.find_server_by_discord_id(ctx.guild.id)
user = self._users.find_user_by_discord_id_and_server_id( user = self._users.find_user_by_discord_id_and_server_id(member.id, server.server_id)
member.id, server.server_id
)
if atr == "xp": if atr == "xp":
value = str(user.xp) value = str(user.xp)
@ -251,43 +223,31 @@ class UserGroup(DiscordCommandABC):
await self._message_service.send_interaction_msg( await self._message_service.send_interaction_msg(
ctx.interaction, ctx.interaction,
self._t.transform(f"modules.base.user.get.{atr.lower()}").format( self._t.transform(f"modules.base.user.get.{atr.lower()}").format(member.mention, value),
member.mention, value
),
) )
@get.autocomplete("atr") @get.autocomplete("atr")
async def get_autocomplete( async def get_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
self, interaction: discord.Interaction, current: str return [app_commands.Choice(name=value, value=key) for key, value in self._atr_list]
) -> List[app_commands.Choice[str]]:
return [
app_commands.Choice(name=value, value=key) for key, value in self._atr_list
]
@user.command() @user.command()
@commands.guild_only() @commands.guild_only()
@CommandChecks.check_is_ready() @CommandChecks.check_is_ready()
@CommandChecks.check_is_member_moderator() @CommandChecks.check_is_member_moderator()
async def set( async def set(self, ctx: Context, atr: str, value: int, member: discord.Member = None):
self, ctx: Context, atr: str, value: int, member: discord.Member = None
):
self._logger.debug(__name__, f"Received command user-set {atr} {ctx}:{member}") self._logger.debug(__name__, f"Received command user-set {atr} {ctx}:{member}")
if member is None or not isinstance(member, discord.Member): if member is None or not isinstance(member, discord.Member):
member = ctx.author member = ctx.author
server = self._servers.find_server_by_discord_id(ctx.guild.id) server = self._servers.find_server_by_discord_id(ctx.guild.id)
user = self._users.find_user_by_discord_id_and_server_id( user = self._users.find_user_by_discord_id_and_server_id(member.id, server.server_id)
member.id, server.server_id
)
if atr == "xp": if atr == "xp":
try: try:
user.xp = value user.xp = value
except TypeError as te: except TypeError as te:
self._logger.error( self._logger.error(__name__, f"String value couldn't be converted to int", te)
__name__, f"String value couldn't be converted to int", te
)
await self._message_service.send_interaction_msg( await self._message_service.send_interaction_msg(
ctx.interaction, ctx.interaction,
self._t.transform("modules.base.user.set.error.type_error"), self._t.transform("modules.base.user.set.error.type_error"),
@ -307,15 +267,11 @@ class UserGroup(DiscordCommandABC):
await self._message_service.send_interaction_msg( await self._message_service.send_interaction_msg(
ctx.interaction, ctx.interaction,
self._t.transform(f"modules.base.user.set.{atr.lower()}").format( self._t.transform(f"modules.base.user.set.{atr.lower()}").format(member.mention, value),
member.mention, value
),
) )
@set.autocomplete("atr") @set.autocomplete("atr")
async def set_autocomplete( async def set_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
self, interaction: discord.Interaction, current: str
) -> List[app_commands.Choice[str]]:
atr_list = [("xp", self._atr_dict["xp"])] atr_list = [("xp", self._atr_dict["xp"])]
return [app_commands.Choice(name=value, value=key) for key, value in atr_list] return [app_commands.Choice(name=value, value=key) for key, value in atr_list]
@ -323,18 +279,12 @@ class UserGroup(DiscordCommandABC):
@commands.guild_only() @commands.guild_only()
@CommandChecks.check_is_ready() @CommandChecks.check_is_ready()
@CommandChecks.check_is_member_moderator() @CommandChecks.check_is_member_moderator()
async def add( async def add(self, ctx: Context, atr: str, value: int, member: discord.Member = None):
self, ctx: Context, atr: str, value: int, member: discord.Member = None self._logger.debug(__name__, f"Received command user-add {atr}-={value} {ctx}:{member}")
):
self._logger.debug(
__name__, f"Received command user-add {atr}-={value} {ctx}:{member}"
)
await self._handle_atr_calc(ctx, atr, value, member) await self._handle_atr_calc(ctx, atr, value, member)
@add.autocomplete("atr") @add.autocomplete("atr")
async def set_autocomplete( async def set_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
self, interaction: discord.Interaction, current: str
) -> List[app_commands.Choice[str]]:
atr_list = [("xp", self._atr_dict["xp"])] atr_list = [("xp", self._atr_dict["xp"])]
return [app_commands.Choice(name=value, value=key) for key, value in atr_list] return [app_commands.Choice(name=value, value=key) for key, value in atr_list]
@ -342,18 +292,12 @@ class UserGroup(DiscordCommandABC):
@commands.guild_only() @commands.guild_only()
@CommandChecks.check_is_ready() @CommandChecks.check_is_ready()
@CommandChecks.check_is_member_moderator() @CommandChecks.check_is_member_moderator()
async def remove( async def remove(self, ctx: Context, atr: str, value: int, member: discord.Member = None):
self, ctx: Context, atr: str, value: int, member: discord.Member = None self._logger.debug(__name__, f"Received command user-remove {atr}-={value} {ctx}:{member}")
):
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) await self._handle_atr_calc(ctx, atr, value, member, is_remove=True)
@remove.autocomplete("atr") @remove.autocomplete("atr")
async def set_autocomplete( async def set_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
self, interaction: discord.Interaction, current: str
) -> List[app_commands.Choice[str]]:
atr_list = [("xp", self._atr_dict["xp"])] atr_list = [("xp", self._atr_dict["xp"])]
return [app_commands.Choice(name=value, value=key) for key, value in atr_list] return [app_commands.Choice(name=value, value=key) for key, value in atr_list]
@ -362,17 +306,13 @@ class UserGroup(DiscordCommandABC):
@CommandChecks.check_is_ready() @CommandChecks.check_is_ready()
@CommandChecks.check_is_member_moderator() @CommandChecks.check_is_member_moderator()
async def reset(self, ctx: Context, atr: str, member: discord.Member = None): async def reset(self, ctx: Context, atr: str, member: discord.Member = None):
self._logger.debug( self._logger.debug(__name__, f"Received command user-reset {atr} {ctx}:{member}")
__name__, f"Received command user-reset {atr} {ctx}:{member}"
)
if member is None or not isinstance(member, discord.Member): if member is None or not isinstance(member, discord.Member):
member = ctx.author member = ctx.author
server = self._servers.find_server_by_discord_id(ctx.guild.id) server = self._servers.find_server_by_discord_id(ctx.guild.id)
user = self._users.find_user_by_discord_id_and_server_id( user = self._users.find_user_by_discord_id_and_server_id(member.id, server.server_id)
member.id, server.server_id
)
if atr == "xp": if atr == "xp":
user.xp = 0 user.xp = 0
@ -381,9 +321,7 @@ class UserGroup(DiscordCommandABC):
await self._level.check_level(member) await self._level.check_level(member)
elif atr == "ontime": elif atr == "ontime":
self._user_joined_voice_channel.delete_user_joined_voice_channel_by_user_id( self._user_joined_voice_channel.delete_user_joined_voice_channel_by_user_id(user.user_id)
user.user_id
)
self._db.save_changes() self._db.save_changes()
else: else:
@ -395,15 +333,11 @@ class UserGroup(DiscordCommandABC):
await self._message_service.send_interaction_msg( await self._message_service.send_interaction_msg(
ctx.interaction, ctx.interaction,
self._t.transform(f"modules.base.user.reset.{atr.lower()}").format( self._t.transform(f"modules.base.user.reset.{atr.lower()}").format(atr, member.mention),
atr, member.mention
),
) )
@reset.autocomplete("atr") @reset.autocomplete("atr")
async def reset_autocomplete( async def reset_autocomplete(
self, interaction: discord.Interaction, current: str self, interaction: discord.Interaction, current: str
) -> List[app_commands.Choice[str]]: ) -> List[app_commands.Choice[str]]:
return [ return [app_commands.Choice(name=value, value=key) for key, value in self._atr_list]
app_commands.Choice(name=value, value=key) for key, value in self._atr_list
]

View File

@ -81,9 +81,5 @@ class BaseServerSettings(ConfigurationModelABC):
for url in settings["PingURLs"]: for url in settings["PingURLs"]:
self._ping_urls.append(url) self._ping_urls.append(url)
except Exception as e: except Exception as e:
Console.error( Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings" Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
)
Console.error(
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
)

View File

@ -27,9 +27,5 @@ class BaseSettings(ConfigurationModelABC):
servers.append(st) servers.append(st)
self._servers = servers self._servers = servers
except Exception as e: except Exception as e:
Console.error( Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings" Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
)
Console.error(
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
)

View File

@ -169,9 +169,7 @@ class BaseOnCommandErrorEvent(OnCommandErrorABC):
) )
elif isinstance(error, commands.NotOwner): elif isinstance(error, commands.NotOwner):
await self._messenger.send_ctx_msg( await self._messenger.send_ctx_msg(ctx, self._t.transform("common.errors.not_owner"), without_tracking=True)
ctx, self._t.transform("common.errors.not_owner"), without_tracking=True
)
elif isinstance(error, commands.MissingPermissions): elif isinstance(error, commands.MissingPermissions):
await self._messenger.send_ctx_msg( await self._messenger.send_ctx_msg(
@ -263,19 +261,13 @@ class BaseOnCommandErrorEvent(OnCommandErrorABC):
self._t.transform("common.errors.command_error"), self._t.transform("common.errors.command_error"),
without_tracking=True, without_tracking=True,
) )
message = self._t.transform( message = self._t.transform("modules.base.technician_command_error_message").format(
"modules.base.technician_command_error_message"
).format(
ctx.command, ctx.command,
ctx.author, ctx.author,
error, error,
datetime.datetime.now().strftime( datetime.datetime.now().strftime(self._time_format_settings.date_time_format),
self._time_format_settings.date_time_format
),
uid, uid,
) )
for t in self._bot_settings.technicians: for t in self._bot_settings.technicians:
member = self._bot.get_user(t) member = self._bot.get_user(t)
await self._messenger.send_dm_message( await self._messenger.send_dm_message(message, member, without_tracking=True)
message, member, without_tracking=True
)

View File

@ -52,9 +52,7 @@ class BaseOnCommandEvent(OnCommandABC):
self._clients.append_received_command_count(self._bot.user.id, g_id, 1) self._clients.append_received_command_count(self._bot.user.id, g_id, 1)
self._db.save_changes() self._db.save_changes()
except Exception as e: except Exception as e:
self._logger.error( self._logger.error(__name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e)
__name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e
)
def _handle_message_for_xp(self, message: discord.Message): def _handle_message_for_xp(self, message: discord.Message):
dc_user_id = message.author.id dc_user_id = message.author.id
@ -66,9 +64,7 @@ class BaseOnCommandEvent(OnCommandABC):
user: Optional[User] = None user: Optional[User] = None
try: try:
user = self._users.get_user_by_discord_id_and_server_id( user = self._users.get_user_by_discord_id_and_server_id(dc_user_id, server.server_id)
dc_user_id, server.server_id
)
except Exception as e: except Exception as e:
self._logger.error(__name__, f"Cannot get user {dc_user_id}", e) self._logger.error(__name__, f"Cannot get user {dc_user_id}", e)
return return
@ -83,15 +79,11 @@ class BaseOnCommandEvent(OnCommandABC):
self._users.update_user(user) self._users.update_user(user)
self._db.save_changes() self._db.save_changes()
self._logger.debug( self._logger.debug(__name__, f"User {user} sent message. xp: from {old_xp} to {user.xp}")
__name__, f"User {user} sent message. xp: from {old_xp} to {user.xp}"
)
async def on_command(self, ctx: Context): async def on_command(self, ctx: Context):
self._logger.debug(__name__, f"Module {type(self)} started") self._logger.debug(__name__, f"Module {type(self)} started")
self._logger.info( self._logger.info(__name__, f"Received command: {ctx.command} from {ctx.channel}")
__name__, f"Received command: {ctx.command} from {ctx.channel}"
)
if ctx is None or ctx.guild is None: if ctx is None or ctx.guild is None:
return return
self._append_received_command_count(ctx.guild.id) self._append_received_command_count(ctx.guild.id)

View File

@ -63,9 +63,7 @@ class BaseOnMemberJoinEvent(OnMemberJoinABC):
except Exception as e: except Exception as e:
self._logger.error(__name__, f"Cannot get user {member.id}", e) self._logger.error(__name__, f"Cannot get user {member.id}", e)
async def _add_if_not_exists_user_async( async def _add_if_not_exists_user_async(self, member: Union[discord.User, discord.Member]):
self, member: Union[discord.User, discord.Member]
):
self._logger.debug(__name__, f"Check if user exists {member}") self._logger.debug(__name__, f"Check if user exists {member}")
settings: BaseServerSettings = self._base_helper.get_config(member.guild.id) settings: BaseServerSettings = self._base_helper.get_config(member.guild.id)
await self._messenger.send_dm_message( await self._messenger.send_dm_message(
@ -75,41 +73,29 @@ class BaseOnMemberJoinEvent(OnMemberJoinABC):
for admin in self._permission_service.get_admins(member.guild.id): for admin in self._permission_service.get_admins(member.guild.id):
await self._messenger.send_dm_message( await self._messenger.send_dm_message(
self._t.transform("modules.base.welcome_message_for_team").format( self._t.transform("modules.base.welcome_message_for_team").format(member.mention),
member.mention
),
admin, admin,
) )
for moderator in self._permission_service.get_moderators(member.guild.id): for moderator in self._permission_service.get_moderators(member.guild.id):
await self._messenger.send_dm_message( await self._messenger.send_dm_message(
self._t.transform("modules.base.welcome_message_for_team").format( self._t.transform("modules.base.welcome_message_for_team").format(member.mention),
member.mention
),
moderator, moderator,
) )
try: try:
server = self._servers.get_server_by_discord_id(member.guild.id) server = self._servers.get_server_by_discord_id(member.guild.id)
user = self._users.find_user_by_discord_id_and_server_id( user = self._users.find_user_by_discord_id_and_server_id(member.id, server.server_id)
member.id, server.server_id
)
if user is not None: if user is not None:
self._user_joins.add_user_joined_server( self._user_joins.add_user_joined_server(UserJoinedServer(user, datetime.now()))
UserJoinedServer(user, datetime.now())
)
self._db.save_changes() self._db.save_changes()
return return
self._logger.debug(__name__, f"Add user: {member.id}") self._logger.debug(__name__, f"Add user: {member.id}")
self._users.add_user(User(member.id, 0, server)) self._users.add_user(User(member.id, 0, server))
self._db.save_changes() self._db.save_changes()
user = self._users.get_user_by_discord_id_and_server_id( user = self._users.get_user_by_discord_id_and_server_id(member.id, server.server_id)
member.id, server.server_id 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() self._db.save_changes()
except Exception as e: except Exception as e:
self._logger.error(__name__, f"Cannot get user {member.id}", e) self._logger.error(__name__, f"Cannot get user {member.id}", e)

View File

@ -42,23 +42,17 @@ class BaseOnMemberRemoveEvent(OnMemberRemoveABC):
async def _remove_user(self, member: Union[discord.User, discord.Member]): async def _remove_user(self, member: Union[discord.User, discord.Member]):
self._logger.debug(__name__, f"Remove user {member}") self._logger.debug(__name__, f"Remove user {member}")
settings: BaseServerSettings = self._base_helper.get_config(member.guild.id) settings: BaseServerSettings = self._base_helper.get_config(member.guild.id)
await self._messenger.send_dm_message( await self._messenger.send_dm_message(self._t.transform("modules.base.goodbye_message"), member)
self._t.transform("modules.base.goodbye_message"), member
)
try: try:
server = self._servers.get_server_by_discord_id(member.guild.id) server = self._servers.get_server_by_discord_id(member.guild.id)
user = self._users.find_user_by_discord_id_and_server_id( user = self._users.find_user_by_discord_id_and_server_id(member.id, server.server_id)
member.id, server.server_id
)
if user is None: if user is None:
self._logger.error(__name__, f"Cannot find user {member}") self._logger.error(__name__, f"Cannot find user {member}")
return return
join = self._user_joins.get_active_user_joined_server_by_user_id( join = self._user_joins.get_active_user_joined_server_by_user_id(user.user_id)
user.user_id
)
join.leaved_on = datetime.now() join.leaved_on = datetime.now()
self._user_joins.update_user_joined_server(join) self._user_joins.update_user_joined_server(join)
self._db.save_changes() self._db.save_changes()

View File

@ -40,9 +40,7 @@ class BaseOnMessageDeleteEvent(OnMessageDeleteABC):
self._clients.append_deleted_message_count(self._bot.user.id, g_id, 1) self._clients.append_deleted_message_count(self._bot.user.id, g_id, 1)
self._db.save_changes() self._db.save_changes()
except Exception as e: except Exception as e:
self._logger.error( self._logger.error(__name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e)
__name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e
)
def _handle_message_delete(self, message: discord.Message): def _handle_message_delete(self, message: discord.Message):
dc_user_id = message.author.id dc_user_id = message.author.id
@ -54,9 +52,7 @@ class BaseOnMessageDeleteEvent(OnMessageDeleteABC):
user: Optional[User] = None user: Optional[User] = None
try: try:
user = self._users.find_user_by_discord_id_and_server_id( user = self._users.find_user_by_discord_id_and_server_id(dc_user_id, server.server_id)
dc_user_id, server.server_id
)
except Exception as e: except Exception as e:
self._logger.error(__name__, f"Cannot get user {dc_user_id}", e) self._logger.error(__name__, f"Cannot get user {dc_user_id}", e)
return return
@ -81,9 +77,7 @@ class BaseOnMessageDeleteEvent(OnMessageDeleteABC):
if message is None or message.guild is None: if message is None or message.guild is None:
return return
self._logger.info( self._logger.info(__name__, f"Received message: {LogMessageHelper.get_log_string(message)}")
__name__, f"Received message: {LogMessageHelper.get_log_string(message)}"
)
self._append_deleted_message_count(message.guild.id) self._append_deleted_message_count(message.guild.id)
if not message.author.bot: if not message.author.bot:

View File

@ -45,9 +45,7 @@ class BaseOnMessageEvent(OnMessageABC):
self._clients.append_received_message_count(self._bot.user.id, g_id, 1) self._clients.append_received_message_count(self._bot.user.id, g_id, 1)
self._db.save_changes() self._db.save_changes()
except Exception as e: except Exception as e:
self._logger.error( self._logger.error(__name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e)
__name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e
)
def _handle_message_for_xp(self, message: discord.Message): def _handle_message_for_xp(self, message: discord.Message):
dc_user_id = message.author.id dc_user_id = message.author.id
@ -59,9 +57,7 @@ class BaseOnMessageEvent(OnMessageABC):
user: Optional[User] = None user: Optional[User] = None
try: try:
user = self._users.find_user_by_discord_id_and_server_id( user = self._users.find_user_by_discord_id_and_server_id(dc_user_id, server.server_id)
dc_user_id, server.server_id
)
except Exception as e: except Exception as e:
self._logger.error(__name__, f"Cannot get user {dc_user_id}", e) self._logger.error(__name__, f"Cannot get user {dc_user_id}", e)
return return
@ -81,9 +77,7 @@ class BaseOnMessageEvent(OnMessageABC):
self._users.update_user(user) self._users.update_user(user)
self._db.save_changes() self._db.save_changes()
self._logger.debug( self._logger.debug(__name__, f"User {user} sent message. xp: from {old_xp} to {user.xp}")
__name__, f"User {user} sent message. xp: from {old_xp} to {user.xp}"
)
@EventChecks.check_is_ready() @EventChecks.check_is_ready()
async def on_message(self, message: discord.Message): async def on_message(self, message: discord.Message):
@ -91,9 +85,7 @@ class BaseOnMessageEvent(OnMessageABC):
if message is None or message.guild is None: if message is None or message.guild is None:
return return
self._logger.info( self._logger.info(__name__, f"Received message: {LogMessageHelper.get_log_string(message)}")
__name__, f"Received message: {LogMessageHelper.get_log_string(message)}"
)
self._append_received_message_count(message.guild.id) self._append_received_message_count(message.guild.id)
if not message.author.bot: if not message.author.bot:

View File

@ -51,14 +51,10 @@ class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC):
self._logger.info(__name__, f"Module {type(self)} loaded") self._logger.info(__name__, f"Module {type(self)} loaded")
def _update_voice_state( def _update_voice_state(self, joined: bool, dc_user_id: int, dc_channel_id: int, server: Server):
self, joined: bool, dc_user_id: int, dc_channel_id: int, server: Server
):
user: Optional[User] = None user: Optional[User] = None
try: try:
user = self._users.get_user_by_discord_id_and_server_id( user = self._users.get_user_by_discord_id_and_server_id(dc_user_id, server.server_id)
dc_user_id, server.server_id
)
except Exception as e: except Exception as e:
self._logger.error(__name__, f"Cannot get user {dc_user_id}", e) self._logger.error(__name__, f"Cannot get user {dc_user_id}", e)
return return
@ -74,13 +70,9 @@ class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC):
self._db.save_changes() self._db.save_changes()
return return
settings: BaseServerSettings = self._base_helper.get_config( settings: BaseServerSettings = self._base_helper.get_config(server.discord_server_id)
server.discord_server_id
)
join = self._user_joins_vc.get_active_user_joined_voice_channel_by_user_id( join = self._user_joins_vc.get_active_user_joined_voice_channel_by_user_id(user.user_id)
user.user_id
)
join.leaved_on = datetime.now() join.leaved_on = datetime.now()
# ontime as hours # ontime as hours
@ -136,36 +128,18 @@ class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC):
# channel to channel # channel to channel
elif before.channel is not None and after.channel is not None: elif before.channel is not None and after.channel is not None:
# joined # joined
if ( if before.channel.id in settings.afk_channel_ids and after.channel.id not in settings.afk_channel_ids:
before.channel.id in settings.afk_channel_ids self._logger.trace(__name__, f"User {member.id} joined {after.channel}")
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) self._update_voice_state(True, member.id, after.channel.id, server)
# left # left
elif ( elif after.channel.id in settings.afk_channel_ids and before.channel.id not in settings.afk_channel_ids:
after.channel.id in settings.afk_channel_ids self._logger.trace(__name__, f"User {member.id} left {before.channel}")
and before.channel.id not in settings.afk_channel_ids self._update_voice_state(False, member.id, before.channel.id, server)
):
self._logger.trace(
__name__, f"User {member.id} left {before.channel}"
)
self._update_voice_state(
False, member.id, before.channel.id, server
)
else: else:
self._logger.trace( self._logger.trace(__name__, f"User {member.id} switched to {after.channel}")
__name__, f"User {member.id} switched to {after.channel}" self._update_voice_state(False, member.id, before.channel.id, server)
)
self._update_voice_state(
False, member.id, before.channel.id, server
)
self._update_voice_state(True, member.id, after.channel.id, server) self._update_voice_state(True, member.id, after.channel.id, server)
except Exception as e: except Exception as e:
self._logger.error( self._logger.error(__name__, f"Cannot handle voice state for user {member.id}", e)
__name__, f"Cannot handle voice state for user {member.id}", e
)

View File

@ -43,9 +43,7 @@ class BaseOnVoiceStateUpdateEventHelpChannel(OnVoiceStateUpdateABC):
): ):
self._logger.debug(__name__, f"Module {type(self)} started") self._logger.debug(__name__, f"Module {type(self)} started")
server = self._servers.get_server_by_discord_id(member.guild.id) server = self._servers.get_server_by_discord_id(member.guild.id)
settings: BaseServerSettings = self._base_helper.get_config( settings: BaseServerSettings = self._base_helper.get_config(server.discord_server_id)
server.discord_server_id
)
if after.channel is None or after.channel.id != settings.help_voice_channel_id: if after.channel is None or after.channel.id != settings.help_voice_channel_id:
return return
@ -55,9 +53,7 @@ class BaseOnVoiceStateUpdateEventHelpChannel(OnVoiceStateUpdateABC):
] ]
for a in mods: for a in mods:
await self._message_service.send_dm_message( await self._message_service.send_dm_message(
self._t.transform( self._t.transform("modules.base.member_joined_help_voice_channel").format(member.mention),
"modules.base.member_joined_help_voice_channel"
).format(member.mention),
a, a,
) )

View File

@ -38,9 +38,7 @@ class BaseReactionHandler:
guild = self._bot.get_guild(payload.guild_id) guild = self._bot.get_guild(payload.guild_id)
member = guild.get_member(payload.user_id) member = guild.get_member(payload.user_id)
if member is None: if member is None:
self._logger.warn( self._logger.warn(__name__, f"User {payload.user_id} in {guild.name} not found - skipping")
__name__, f"User {payload.user_id} in {guild.name} not found - skipping"
)
return return
try: try:
@ -55,12 +53,8 @@ class BaseReactionHandler:
f"{log_msg} to message {LogMessageHelper.get_log_string(message)}", f"{log_msg} to message {LogMessageHelper.get_log_string(message)}",
) )
except Exception as e: except Exception as e:
self._logger.error( self._logger.error(__name__, f"Getting message for reaction logging failed", e)
__name__, f"Getting message for reaction logging failed", e self._logger.info(__name__, f"{log_msg} to message {payload.message_id}")
)
self._logger.info(
__name__, f"{log_msg} to message {payload.message_id}"
)
except Exception as e: except Exception as e:
self._logger.error(__name__, f"Reaction logging failed", e) self._logger.error(__name__, f"Reaction logging failed", e)
@ -68,9 +62,7 @@ class BaseReactionHandler:
return return
server = self._servers.get_server_by_discord_id(guild.id) server = self._servers.get_server_by_discord_id(guild.id)
user = self._users.get_user_by_discord_id_and_server_id( user = self._users.get_user_by_discord_id_and_server_id(member.id, server.server_id)
member.id, server.server_id
)
settings: BaseServerSettings = self._base_helper.get_config(guild.id) settings: BaseServerSettings = self._base_helper.get_config(guild.id)
if r_type == "add": if r_type == "add":

View File

@ -14,9 +14,7 @@ class BootLogExtension(ApplicationExtensionABC):
pass pass
async def run(self, config: ConfigurationABC, services: ServiceProviderABC): async def run(self, config: ConfigurationABC, services: ServiceProviderABC):
feature_flags: FeatureFlagsSettings = config.get_configuration( feature_flags: FeatureFlagsSettings = config.get_configuration(FeatureFlagsSettings)
FeatureFlagsSettings
)
if not feature_flags.get_flag(FeatureFlagsEnum.boot_log_module): if not feature_flags.get_flag(FeatureFlagsEnum.boot_log_module):
return return
logger: LoggerABC = services.get_service(LoggerABC) logger: LoggerABC = services.get_service(LoggerABC)

View File

@ -13,14 +13,10 @@ class BootLogModule(ModuleABC):
def __init__(self, dc: DiscordCollectionABC): def __init__(self, dc: DiscordCollectionABC):
ModuleABC.__init__(self, dc, FeatureFlagsEnum.boot_log_module) ModuleABC.__init__(self, dc, FeatureFlagsEnum.boot_log_module)
def configure_configuration( def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
):
pass pass
def configure_services( def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
):
# commands # commands
# events # events
self._dc.add_event(DiscordEventTypesEnum.on_ready.value, BootLogOnReadyEvent) self._dc.add_event(DiscordEventTypesEnum.on_ready.value, BootLogOnReadyEvent)

View File

@ -38,10 +38,7 @@ class BootLogOnReadyEvent(OnReadyABC):
try: try:
start_time = self._config.get_configuration("Bot_StartTime") start_time = self._config.get_configuration("Bot_StartTime")
init_time = round( 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, 2,
) )
self._config.add_configuration("InitTime", str(init_time)) self._config.add_configuration("InitTime", str(init_time))
@ -52,9 +49,7 @@ class BootLogOnReadyEvent(OnReadyABC):
# print error if initialisation took way too long # print error if initialisation took way too long
elif init_time >= 90: elif init_time >= 90:
self._logger.error( self._logger.error(__name__, "It takes far too long to start the bot!!!")
__name__, "It takes far too long to start the bot!!!"
)
except Exception as e: except Exception as e:
self._logger.error(__name__, "Init time calculation failed", e) self._logger.error(__name__, "Init time calculation failed", e)
return return
@ -63,22 +58,14 @@ class BootLogOnReadyEvent(OnReadyABC):
g: guild = g g: guild = g
self._logger.debug(__name__, f"Server detected: {g.id}") self._logger.debug(__name__, f"Server detected: {g.id}")
server_settings: ServerSettings = self._config.get_configuration( server_settings: ServerSettings = self._config.get_configuration(f"ServerSettings_{g.id}")
f"ServerSettings_{g.id}"
)
if server_settings is None: if server_settings is None:
self._logger.error( self._logger.error(__name__, f"BootLog settings for server {g.id} not found!")
__name__, f"BootLog settings for server {g.id} not found!"
)
return return
module_settings: BootLogServerSettings = self._config.get_configuration( module_settings: BootLogServerSettings = self._config.get_configuration(f"BootLogServerSettings_{g.id}")
f"BootLogServerSettings_{g.id}"
)
if module_settings is None: if module_settings is None:
self._logger.error( self._logger.error(__name__, f"Config {type(self).__name__}_{g.id} not found!")
__name__, f"Config {type(self).__name__}_{g.id} not found!"
)
return return
await self._message_service.send_channel_message( await self._message_service.send_channel_message(

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