0.3.1 #187
@ -25,8 +25,8 @@
|
||||
"gv": "cpl get-version",
|
||||
"get-version": "export VERSION=$(cpl run get-version --dev); echo $VERSION;",
|
||||
|
||||
"pre-build": "cpl set-version $ARGS; black src;",
|
||||
"post-build": "cpl run post-build --dev; black src;",
|
||||
"pre-build": "cpl set-version $ARGS; black ./;",
|
||||
"post-build": "cpl run post-build --dev; black ./;",
|
||||
|
||||
"pre-prod": "cpl build",
|
||||
"prod": "export KDB_ENVIRONMENT=production; export KDB_NAME=KDB-Prod; cpl start;",
|
||||
|
2
kdb-bot/pyproject.toml
Normal file
2
kdb-bot/pyproject.toml
Normal file
@ -0,0 +1,2 @@
|
||||
[tool.black]
|
||||
line-length = 120
|
@ -23,18 +23,12 @@ class Application(DiscordBotApplicationABC):
|
||||
self._logger: LoggerABC = services.get_service(LoggerABC)
|
||||
# cpl-discord
|
||||
self._bot: DiscordBotServiceABC = services.get_service(DiscordBotServiceABC)
|
||||
self._bot_settings: DiscordBotSettings = config.get_configuration(
|
||||
DiscordBotSettings
|
||||
)
|
||||
self._bot_settings: DiscordBotSettings = config.get_configuration(DiscordBotSettings)
|
||||
# cpl-translation
|
||||
self._translation: TranslationServiceABC = services.get_service(
|
||||
TranslationServiceABC
|
||||
)
|
||||
self._translation: TranslationServiceABC = services.get_service(TranslationServiceABC)
|
||||
self._t: TranslatePipe = services.get_service(TranslatePipe)
|
||||
|
||||
self._feature_flags: FeatureFlagsSettings = config.get_configuration(
|
||||
FeatureFlagsSettings
|
||||
)
|
||||
self._feature_flags: FeatureFlagsSettings = config.get_configuration(FeatureFlagsSettings)
|
||||
|
||||
# api
|
||||
if self._feature_flags.get_flag(FeatureFlagsEnum.api_module):
|
||||
@ -43,9 +37,7 @@ class Application(DiscordBotApplicationABC):
|
||||
self._is_stopping = False
|
||||
|
||||
async def configure(self):
|
||||
self._translation.load_by_settings(
|
||||
self._configuration.get_configuration(TranslationSettings)
|
||||
)
|
||||
self._translation.load_by_settings(self._configuration.get_configuration(TranslationSettings))
|
||||
|
||||
async def main(self):
|
||||
try:
|
||||
@ -81,8 +73,4 @@ class Application(DiscordBotApplicationABC):
|
||||
Console.write_line()
|
||||
|
||||
def is_restart(self):
|
||||
return (
|
||||
True
|
||||
if self._configuration.get_configuration("IS_RESTART") == "true"
|
||||
else False
|
||||
) #
|
||||
return True if self._configuration.get_configuration("IS_RESTART") == "true" else False #
|
||||
|
@ -13,6 +13,4 @@ class InitBotExtension(ApplicationExtensionABC):
|
||||
async def run(self, config: ConfigurationABC, services: ServiceProviderABC):
|
||||
settings = config.get_configuration(BotSettings)
|
||||
|
||||
bot: DiscordBotServiceABC = services.get_service(
|
||||
DiscordBotServiceABC, max_messages=settings.cache_max_messages
|
||||
)
|
||||
bot: DiscordBotServiceABC = services.get_service(DiscordBotServiceABC, max_messages=settings.cache_max_messages)
|
||||
|
@ -48,9 +48,7 @@ class Startup(StartupABC):
|
||||
services.add_singleton(CustomFileLoggerABC, ApiLogger)
|
||||
|
||||
services.add_translation()
|
||||
services.add_db_context(
|
||||
DBContext, self._config.get_configuration(DatabaseSettings)
|
||||
)
|
||||
services.add_db_context(DBContext, self._config.get_configuration(DatabaseSettings))
|
||||
|
||||
provider = services.build_service_provider()
|
||||
# instantiate custom logger
|
||||
|
@ -9,13 +9,9 @@ class StartupDiscordExtension(StartupExtensionABC):
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def configure_configuration(
|
||||
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
|
||||
pass
|
||||
|
||||
def configure_services(
|
||||
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
|
||||
services.add_discord()
|
||||
dcc = get_discord_collection(services)
|
||||
|
@ -20,25 +20,15 @@ class StartupMigrationExtension(StartupExtensionABC):
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def configure_configuration(
|
||||
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
|
||||
pass
|
||||
|
||||
def configure_services(
|
||||
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
|
||||
services.add_transient(MigrationService)
|
||||
services.add_transient(MigrationABC, InitialMigration)
|
||||
services.add_transient(
|
||||
MigrationABC, AutoRoleMigration
|
||||
) # 03.10.2022 #54 - 0.2.2
|
||||
services.add_transient(MigrationABC, AutoRoleMigration) # 03.10.2022 #54 - 0.2.2
|
||||
services.add_transient(MigrationABC, ApiMigration) # 15.10.2022 #70 - 0.3.0
|
||||
services.add_transient(MigrationABC, LevelMigration) # 06.11.2022 #25 - 0.3.0
|
||||
services.add_transient(MigrationABC, StatsMigration) # 09.11.2022 #46 - 0.3.0
|
||||
services.add_transient(
|
||||
MigrationABC, AutoRoleFix1Migration
|
||||
) # 30.12.2022 #151 - 0.3.0
|
||||
services.add_transient(
|
||||
MigrationABC, UserMessageCountPerHourMigration
|
||||
) # 11.01.2023 #168 - 0.3.1
|
||||
services.add_transient(MigrationABC, AutoRoleFix1Migration) # 30.12.2022 #151 - 0.3.0
|
||||
services.add_transient(MigrationABC, UserMessageCountPerHourMigration) # 11.01.2023 #168 - 0.3.1
|
||||
|
@ -18,15 +18,11 @@ class StartupModuleExtension(StartupExtensionABC):
|
||||
|
||||
self._modules = ModuleList.get_modules()
|
||||
|
||||
def configure_configuration(
|
||||
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
|
||||
self._config = config
|
||||
self._feature_flags = config.get_configuration(FeatureFlagsSettings)
|
||||
|
||||
def configure_services(
|
||||
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
|
||||
provider = services.build_service_provider()
|
||||
dc_collection: DiscordCollectionABC = provider.get_service(DiscordCollectionABC)
|
||||
|
||||
|
@ -19,43 +19,25 @@ class StartupSettingsExtension(StartupExtensionABC):
|
||||
def __init__(self):
|
||||
self._start_time = datetime.now()
|
||||
|
||||
def configure_configuration(
|
||||
self, configuration: ConfigurationABC, environment: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_configuration(self, configuration: ConfigurationABC, environment: ApplicationEnvironmentABC):
|
||||
# this shit has to be done here because we need settings in subsequent startup extensions
|
||||
environment.set_working_directory(os.path.dirname(os.path.realpath(__file__)))
|
||||
configuration.add_environment_variables("KDB_")
|
||||
configuration.add_environment_variables("DISCORD_")
|
||||
|
||||
configuration.add_json_file(f"config/appsettings.json", optional=False)
|
||||
configuration.add_json_file(
|
||||
f"config/appsettings.{environment.environment_name}.json", optional=True
|
||||
)
|
||||
configuration.add_json_file(
|
||||
f"config/appsettings.{environment.host_name}.json", optional=True
|
||||
)
|
||||
configuration.add_json_file(f"config/appsettings.{environment.environment_name}.json", optional=True)
|
||||
configuration.add_json_file(f"config/appsettings.{environment.host_name}.json", optional=True)
|
||||
# load feature-flags
|
||||
configuration.add_json_file(f"config/feature-flags.json", optional=False)
|
||||
configuration.add_json_file(
|
||||
f"config/feature-flags.{environment.environment_name}.json", optional=True
|
||||
)
|
||||
configuration.add_json_file(
|
||||
f"config/feature-flags.{environment.host_name}.json", optional=True
|
||||
)
|
||||
configuration.add_json_file(f"config/feature-flags.{environment.environment_name}.json", optional=True)
|
||||
configuration.add_json_file(f"config/feature-flags.{environment.host_name}.json", optional=True)
|
||||
|
||||
configuration.add_configuration("Startup_StartTime", str(self._start_time))
|
||||
self._configure_settings_with_sub_settings(
|
||||
configuration, 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(
|
||||
configuration, LevelSettings, lambda x: x.servers, lambda x: x.id
|
||||
)
|
||||
self._configure_settings_with_sub_settings(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(configuration, LevelSettings, lambda x: x.servers, lambda x: x.id)
|
||||
self._configure_settings_with_sub_settings(
|
||||
configuration, PermissionSettings, lambda x: x.servers, lambda x: x.id
|
||||
)
|
||||
@ -63,9 +45,7 @@ class StartupSettingsExtension(StartupExtensionABC):
|
||||
configuration, BotLoggingSettings, lambda x: x.files, lambda x: x.key
|
||||
)
|
||||
|
||||
def configure_services(
|
||||
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@ -77,6 +57,4 @@ class StartupSettingsExtension(StartupExtensionABC):
|
||||
return
|
||||
|
||||
for sub_settings in list_atr(settings):
|
||||
config.add_configuration(
|
||||
f"{type(sub_settings).__name__}_{atr(sub_settings)}", sub_settings
|
||||
)
|
||||
config.add_configuration(f"{type(sub_settings).__name__}_{atr(sub_settings)}", sub_settings)
|
||||
|
@ -40,15 +40,11 @@ class AuthServiceABC(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_filtered_auth_users_async(
|
||||
self, criteria: AuthUserSelectCriteria
|
||||
) -> AuthUserFilteredResultDTO:
|
||||
async def get_filtered_auth_users_async(self, criteria: AuthUserSelectCriteria) -> AuthUserFilteredResultDTO:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_auth_user_by_email_async(
|
||||
self, email: str, with_password: bool = False
|
||||
) -> AuthUserDTO:
|
||||
async def get_auth_user_by_email_async(self, email: str, with_password: bool = False) -> AuthUserDTO:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@ -64,9 +60,7 @@ class AuthServiceABC(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def add_auth_user_by_discord_async(
|
||||
self, user_dto: AuthUserDTO, dc_id: int
|
||||
) -> OAuthDTO:
|
||||
async def add_auth_user_by_discord_async(self, user_dto: AuthUserDTO, dc_id: int) -> OAuthDTO:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
|
@ -3,9 +3,7 @@ from abc import ABC, abstractmethod
|
||||
|
||||
class SelectCriteriaABC(ABC):
|
||||
@abstractmethod
|
||||
def __init__(
|
||||
self, page_index: int, page_size: int, sort_direction: str, sort_column: str
|
||||
):
|
||||
def __init__(self, page_index: int, page_size: int, sort_direction: str, sort_column: str):
|
||||
self.page_index = page_index
|
||||
self.page_size = page_size
|
||||
self.sort_direction = sort_direction
|
||||
|
@ -140,9 +140,7 @@ class Api(Flask):
|
||||
data = request.get_data()
|
||||
data = "" if len(data) == 0 else str(data.decode(encoding="utf-8"))
|
||||
|
||||
text = textwrap.dedent(
|
||||
f"Request: {request_id}:\n\tHeader:\n\t\t{headers}\n\tResponse: {data}"
|
||||
)
|
||||
text = textwrap.dedent(f"Request: {request_id}:\n\tHeader:\n\t\t{headers}\n\tResponse: {data}")
|
||||
self._logger.trace(__name__, text)
|
||||
|
||||
return response
|
||||
|
@ -26,21 +26,15 @@ class ApiModule(ModuleABC):
|
||||
def __init__(self, dc: DiscordCollectionABC):
|
||||
ModuleABC.__init__(self, dc, FeatureFlagsEnum.api_module)
|
||||
|
||||
def configure_configuration(
|
||||
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
|
||||
cwd = env.working_directory
|
||||
env.set_working_directory(os.path.dirname(os.path.realpath(__file__)))
|
||||
config.add_json_file(f"config/apisettings.json", optional=False)
|
||||
config.add_json_file(
|
||||
f"config/apisettings.{env.environment_name}.json", optional=True
|
||||
)
|
||||
config.add_json_file(f"config/apisettings.{env.environment_name}.json", optional=True)
|
||||
config.add_json_file(f"config/apisettings.{env.host_name}.json", optional=True)
|
||||
env.set_working_directory(cwd)
|
||||
|
||||
def configure_services(
|
||||
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
|
||||
services.add_singleton(EMailClientABC, EMailClient)
|
||||
|
||||
services.add_singleton(ApiThread)
|
||||
|
@ -15,15 +15,11 @@ class AppApiExtension(ApplicationExtensionABC):
|
||||
ApplicationExtensionABC.__init__(self)
|
||||
|
||||
async def run(self, config: ConfigurationABC, services: ServiceProviderABC):
|
||||
feature_flags: FeatureFlagsSettings = config.get_configuration(
|
||||
FeatureFlagsSettings
|
||||
)
|
||||
feature_flags: FeatureFlagsSettings = config.get_configuration(FeatureFlagsSettings)
|
||||
if not feature_flags.get_flag(FeatureFlagsEnum.api_module):
|
||||
return
|
||||
|
||||
auth_settings: AuthenticationSettings = config.get_configuration(
|
||||
AuthenticationSettings
|
||||
)
|
||||
auth_settings: AuthenticationSettings = config.get_configuration(AuthenticationSettings)
|
||||
auth_users: AuthUserRepositoryABC = services.get_service(AuthUserRepositoryABC)
|
||||
auth: AuthServiceABC = services.get_service(AuthServiceABC)
|
||||
Route.init_authorize(auth_users, auth)
|
||||
|
@ -30,9 +30,5 @@ class ApiSettings(ConfigurationModelABC):
|
||||
self._host = settings["Host"]
|
||||
self._redirect_to_https = bool(settings["RedirectToHTTPS"])
|
||||
except Exception as e:
|
||||
Console.error(
|
||||
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings"
|
||||
)
|
||||
Console.error(
|
||||
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
|
||||
)
|
||||
Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
|
||||
Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
|
||||
|
@ -43,9 +43,5 @@ class AuthenticationSettings(ConfigurationModelABC):
|
||||
self._token_expire_time = int(settings["TokenExpireTime"])
|
||||
self._refresh_token_expire_time = int(settings["RefreshTokenExpireTime"])
|
||||
except Exception as e:
|
||||
Console.error(
|
||||
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings"
|
||||
)
|
||||
Console.error(
|
||||
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
|
||||
)
|
||||
Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
|
||||
Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
|
||||
|
@ -43,9 +43,5 @@ class DiscordAuthenticationSettings(ConfigurationModelABC):
|
||||
self._token_url = settings["TokenURL"]
|
||||
self._auth_url = settings["AuthURL"]
|
||||
except Exception as e:
|
||||
Console.error(
|
||||
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings"
|
||||
)
|
||||
Console.error(
|
||||
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
|
||||
)
|
||||
Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
|
||||
Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
|
||||
|
@ -18,9 +18,5 @@ class FrontendSettings(ConfigurationModelABC):
|
||||
try:
|
||||
self._url = settings["URL"]
|
||||
except Exception as e:
|
||||
Console.error(
|
||||
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings"
|
||||
)
|
||||
Console.error(
|
||||
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
|
||||
)
|
||||
Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
|
||||
Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
|
||||
|
@ -72,9 +72,7 @@ class AuthController:
|
||||
|
||||
@Route.post(f"{BasePath}/register")
|
||||
async def register(self):
|
||||
dto: AuthUserDTO = JSONProcessor.process(
|
||||
AuthUserDTO, request.get_json(force=True, silent=True)
|
||||
)
|
||||
dto: AuthUserDTO = JSONProcessor.process(AuthUserDTO, request.get_json(force=True, silent=True))
|
||||
await self._auth_service.add_auth_user_async(dto)
|
||||
return "", 200
|
||||
|
||||
@ -85,9 +83,7 @@ class AuthController:
|
||||
|
||||
@Route.post(f"{BasePath}/login")
|
||||
async def login(self) -> Response:
|
||||
dto: AuthUserDTO = JSONProcessor.process(
|
||||
AuthUserDTO, request.get_json(force=True, silent=True)
|
||||
)
|
||||
dto: AuthUserDTO = JSONProcessor.process(AuthUserDTO, request.get_json(force=True, silent=True))
|
||||
result = await self._auth_service.login_async(dto)
|
||||
return jsonify(result.to_dict())
|
||||
|
||||
@ -116,53 +112,41 @@ class AuthController:
|
||||
|
||||
@Route.post(f"{BasePath}/reset-password")
|
||||
async def reset_password(self):
|
||||
dto: ResetPasswordDTO = JSONProcessor.process(
|
||||
ResetPasswordDTO, request.get_json(force=True, silent=True)
|
||||
)
|
||||
dto: ResetPasswordDTO = JSONProcessor.process(ResetPasswordDTO, request.get_json(force=True, silent=True))
|
||||
await self._auth_service.reset_password_async(dto)
|
||||
return "", 200
|
||||
|
||||
@Route.post(f"{BasePath}/update-user")
|
||||
@Route.authorize
|
||||
async def update_user(self):
|
||||
dto: UpdateAuthUserDTO = JSONProcessor.process(
|
||||
UpdateAuthUserDTO, request.get_json(force=True, silent=True)
|
||||
)
|
||||
dto: UpdateAuthUserDTO = JSONProcessor.process(UpdateAuthUserDTO, request.get_json(force=True, silent=True))
|
||||
await self._auth_service.update_user_async(dto)
|
||||
return "", 200
|
||||
|
||||
@Route.post(f"{BasePath}/update-user-as-admin")
|
||||
@Route.authorize(role=AuthRoleEnum.admin)
|
||||
async def update_user_as_admin(self):
|
||||
dto: UpdateAuthUserDTO = JSONProcessor.process(
|
||||
UpdateAuthUserDTO, request.get_json(force=True, silent=True)
|
||||
)
|
||||
dto: UpdateAuthUserDTO = JSONProcessor.process(UpdateAuthUserDTO, request.get_json(force=True, silent=True))
|
||||
await self._auth_service.update_user_as_admin_async(dto)
|
||||
return "", 200
|
||||
|
||||
@Route.post(f"{BasePath}/refresh")
|
||||
@Route.authorize
|
||||
async def refresh(self) -> Response:
|
||||
dto: TokenDTO = JSONProcessor.process(
|
||||
TokenDTO, request.get_json(force=True, silent=True)
|
||||
)
|
||||
dto: TokenDTO = JSONProcessor.process(TokenDTO, request.get_json(force=True, silent=True))
|
||||
result = await self._auth_service.refresh_async(dto)
|
||||
return jsonify(result.to_dict())
|
||||
|
||||
@Route.post(f"{BasePath}/revoke")
|
||||
async def revoke(self):
|
||||
dto: TokenDTO = JSONProcessor.process(
|
||||
TokenDTO, request.get_json(force=True, silent=True)
|
||||
)
|
||||
dto: TokenDTO = JSONProcessor.process(TokenDTO, request.get_json(force=True, silent=True))
|
||||
await self._auth_service.revoke_async(dto)
|
||||
return "", 200
|
||||
|
||||
@Route.post(f"{BasePath}/delete-user")
|
||||
@Route.authorize(role=AuthRoleEnum.admin)
|
||||
async def delete_user(self):
|
||||
dto: AuthUserDTO = JSONProcessor.process(
|
||||
AuthUserDTO, request.get_json(force=True, silent=True)
|
||||
)
|
||||
dto: AuthUserDTO = JSONProcessor.process(AuthUserDTO, request.get_json(force=True, silent=True))
|
||||
await self._auth_service.delete_auth_user_async(dto)
|
||||
return "", 200
|
||||
|
||||
|
@ -13,9 +13,7 @@ class AuthUserSelectCriteria(SelectCriteriaABC):
|
||||
email: str,
|
||||
auth_role: int,
|
||||
):
|
||||
SelectCriteriaABC.__init__(
|
||||
self, page_index, page_size, sort_direction, sort_column
|
||||
)
|
||||
SelectCriteriaABC.__init__(self, page_index, page_size, sort_direction, sort_column)
|
||||
|
||||
self.first_name = first_name
|
||||
self.last_name = last_name
|
||||
|
@ -10,8 +10,6 @@ class ServerSelectCriteria(SelectCriteriaABC):
|
||||
sort_column: str,
|
||||
name: str,
|
||||
):
|
||||
SelectCriteriaABC.__init__(
|
||||
self, page_index, page_size, sort_direction, sort_column
|
||||
)
|
||||
SelectCriteriaABC.__init__(self, page_index, page_size, sort_direction, sort_column)
|
||||
|
||||
self.name = name
|
||||
|
@ -11,9 +11,7 @@ class ErrorDTO(DtoABC):
|
||||
def __init__(self, error_code: Optional[ServiceErrorCode], message: str):
|
||||
DtoABC.__init__(self)
|
||||
|
||||
self._error_code = (
|
||||
ServiceErrorCode.Unknown if error_code is None else error_code
|
||||
)
|
||||
self._error_code = ServiceErrorCode.Unknown if error_code is None else error_code
|
||||
self._message = message
|
||||
|
||||
@property
|
||||
|
@ -34,9 +34,7 @@ class UpdateAuthUserDTO(DtoABC):
|
||||
def from_dict(self, values: dict):
|
||||
self._auth_user = AuthUserDTO().from_dict(values["authUser"])
|
||||
self._new_auth_user = AuthUserDTO().from_dict(values["newAuthUser"])
|
||||
self._change_password = (
|
||||
False if "changePassword" not in values else bool(values["changePassword"])
|
||||
)
|
||||
self._change_password = False if "changePassword" not in values else bool(values["changePassword"])
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
|
@ -42,9 +42,7 @@ class Route:
|
||||
return jsonify(error.to_dict()), 401
|
||||
|
||||
if cls._auth_users is None or cls._auth is None:
|
||||
ex = ServiceException(
|
||||
ServiceErrorCode.Unauthorized, f"Authorize is not initialized"
|
||||
)
|
||||
ex = ServiceException(ServiceErrorCode.Unauthorized, f"Authorize is not initialized")
|
||||
error = ErrorDTO(ex.error_code, ex.message)
|
||||
return jsonify(error.to_dict()), 401
|
||||
|
||||
@ -66,9 +64,7 @@ class Route:
|
||||
return jsonify(error.to_dict()), 401
|
||||
|
||||
if role is not None and user.auth_role.value < role.value:
|
||||
ex = ServiceException(
|
||||
ServiceErrorCode.Unauthorized, f"Role {role} required"
|
||||
)
|
||||
ex = ServiceException(ServiceErrorCode.Unauthorized, f"Role {role} required")
|
||||
error = ErrorDTO(ex.error_code, ex.message)
|
||||
return jsonify(error.to_dict()), 403
|
||||
|
||||
|
@ -88,8 +88,7 @@ class AuthService(AuthServiceABC):
|
||||
"user_id": user.id,
|
||||
"email": user.email,
|
||||
"role": user.auth_role.value,
|
||||
"exp": datetime.now(tz=timezone.utc)
|
||||
+ timedelta(days=self._auth_settings.token_expire_time),
|
||||
"exp": datetime.now(tz=timezone.utc) + timedelta(days=self._auth_settings.token_expire_time),
|
||||
"iss": self._auth_settings.issuer,
|
||||
"aud": self._auth_settings.audience,
|
||||
},
|
||||
@ -145,9 +144,7 @@ class AuthService(AuthServiceABC):
|
||||
def _create_and_save_refresh_token(self, user: AuthUser) -> str:
|
||||
token = str(uuid.uuid4())
|
||||
user.refresh_token = token
|
||||
user.refresh_token_expire_time = datetime.now() + timedelta(
|
||||
days=self._auth_settings.refresh_token_expire_time
|
||||
)
|
||||
user.refresh_token_expire_time = datetime.now() + timedelta(days=self._auth_settings.refresh_token_expire_time)
|
||||
self._auth_users.update_auth_user(user)
|
||||
self._db.save_changes()
|
||||
return token
|
||||
@ -180,12 +177,8 @@ class AuthService(AuthServiceABC):
|
||||
|
||||
self._send_link_mail(
|
||||
user.email,
|
||||
self._t.transform("api.auth.confirmation.subject").format(
|
||||
user.first_name, user.last_name
|
||||
),
|
||||
self._t.transform("api.auth.confirmation.message").format(
|
||||
url, user.confirmation_id
|
||||
),
|
||||
self._t.transform("api.auth.confirmation.subject").format(user.first_name, user.last_name),
|
||||
self._t.transform("api.auth.confirmation.message").format(url, user.confirmation_id),
|
||||
)
|
||||
|
||||
def _send_forgot_password_id_to_user(self, user: AuthUser):
|
||||
@ -195,38 +188,28 @@ class AuthService(AuthServiceABC):
|
||||
|
||||
self._send_link_mail(
|
||||
user.email,
|
||||
self._t.transform("api.auth.forgot_password.subject").format(
|
||||
user.first_name, user.last_name
|
||||
),
|
||||
self._t.transform("api.auth.forgot_password.message").format(
|
||||
url, user.forgot_password_id
|
||||
),
|
||||
self._t.transform("api.auth.forgot_password.subject").format(user.first_name, user.last_name),
|
||||
self._t.transform("api.auth.forgot_password.message").format(url, user.forgot_password_id),
|
||||
)
|
||||
|
||||
async def get_all_auth_users_async(self) -> List[AuthUserDTO]:
|
||||
result = self._auth_users.get_all_auth_users().select(lambda x: AUT.to_dto(x))
|
||||
return List(AuthUserDTO, result)
|
||||
|
||||
async def get_filtered_auth_users_async(
|
||||
self, criteria: AuthUserSelectCriteria
|
||||
) -> AuthUserFilteredResultDTO:
|
||||
async def get_filtered_auth_users_async(self, criteria: AuthUserSelectCriteria) -> AuthUserFilteredResultDTO:
|
||||
users = self._auth_users.get_filtered_auth_users(criteria)
|
||||
result = users.result.select(lambda x: AUT.to_dto(x))
|
||||
|
||||
return AuthUserFilteredResultDTO(List(AuthUserDTO, result), users.total_count)
|
||||
|
||||
async def get_auth_user_by_email_async(
|
||||
self, email: str, with_password: bool = False
|
||||
) -> AuthUserDTO:
|
||||
async def get_auth_user_by_email_async(self, email: str, with_password: bool = False) -> AuthUserDTO:
|
||||
try:
|
||||
# todo: check if logged in user is admin then send mail
|
||||
user = self._auth_users.get_auth_user_by_email(email)
|
||||
return AUT.to_dto(user, password=user.password if with_password else None)
|
||||
except Exception as e:
|
||||
self._logger.error(__name__, f"AuthUser not found", e)
|
||||
raise ServiceException(
|
||||
ServiceErrorCode.InvalidData, f"User not found {email}"
|
||||
)
|
||||
raise ServiceException(ServiceErrorCode.InvalidData, f"User not found {email}")
|
||||
|
||||
async def find_auth_user_by_email_async(self, email: str) -> Optional[AuthUser]:
|
||||
user = self._auth_users.find_auth_user_by_email(email)
|
||||
@ -244,22 +227,16 @@ class AuthService(AuthServiceABC):
|
||||
user.password_salt = uuid.uuid4()
|
||||
user.password = self._hash_sha256(user_dto.password, user.password_salt)
|
||||
if not self._is_email_valid(user.email):
|
||||
raise ServiceException(
|
||||
ServiceErrorCode.InvalidData, "Invalid E-Mail address"
|
||||
)
|
||||
raise ServiceException(ServiceErrorCode.InvalidData, "Invalid E-Mail address")
|
||||
|
||||
try:
|
||||
user.confirmation_id = uuid.uuid4()
|
||||
self._auth_users.add_auth_user(user)
|
||||
self._send_confirmation_id_to_user(user)
|
||||
self._db.save_changes()
|
||||
self._logger.info(
|
||||
__name__, f"Added auth user with E-Mail: {user_dto.email}"
|
||||
)
|
||||
self._logger.info(__name__, f"Added auth user with E-Mail: {user_dto.email}")
|
||||
except Exception as e:
|
||||
self._logger.error(
|
||||
__name__, f"Cannot add user with E-Mail {user_dto.email}", e
|
||||
)
|
||||
self._logger.error(__name__, f"Cannot add user with E-Mail {user_dto.email}", e)
|
||||
raise ServiceException(ServiceErrorCode.UnableToAdd, "Invalid E-Mail")
|
||||
|
||||
async def add_auth_user_by_oauth_async(self, dto: OAuthDTO):
|
||||
@ -275,27 +252,19 @@ class AuthService(AuthServiceABC):
|
||||
db_user.first_name = dto.user.first_name
|
||||
db_user.last_name = dto.user.last_name
|
||||
db_user.password_salt = uuid.uuid4()
|
||||
db_user.password = self._hash_sha256(
|
||||
dto.user.password, db_user.password_salt
|
||||
)
|
||||
db_user.password = self._hash_sha256(dto.user.password, db_user.password_salt)
|
||||
db_user.oauth_id = None
|
||||
db_user.confirmation_id = uuid.uuid4()
|
||||
self._send_confirmation_id_to_user(db_user)
|
||||
self._auth_users.update_auth_user(db_user)
|
||||
self._logger.info(
|
||||
__name__, f"Added auth user with E-Mail: {dto.user.email}"
|
||||
)
|
||||
self._logger.info(__name__, f"Added auth user with E-Mail: {dto.user.email}")
|
||||
except Exception as e:
|
||||
self._logger.error(
|
||||
__name__, f"Cannot add user with E-Mail {dto.user.email}", e
|
||||
)
|
||||
self._logger.error(__name__, f"Cannot add user with E-Mail {dto.user.email}", e)
|
||||
raise ServiceException(ServiceErrorCode.UnableToAdd, "Invalid E-Mail")
|
||||
|
||||
self._db.save_changes()
|
||||
|
||||
async def add_auth_user_by_discord_async(
|
||||
self, user_dto: AuthUserDTO, dc_id: int
|
||||
) -> OAuthDTO:
|
||||
async def add_auth_user_by_discord_async(self, user_dto: AuthUserDTO, dc_id: int) -> OAuthDTO:
|
||||
db_auth_user = self._auth_users.find_auth_user_by_email(user_dto.email)
|
||||
|
||||
# user exists
|
||||
@ -306,9 +275,7 @@ class AuthService(AuthServiceABC):
|
||||
|
||||
# user exists but discord user id not set
|
||||
elif db_auth_user is not None and db_auth_user.users.count() == 0:
|
||||
self._logger.debug(
|
||||
__name__, f"Auth user exists but not linked with discord"
|
||||
)
|
||||
self._logger.debug(__name__, f"Auth user exists but not linked with discord")
|
||||
# users = self._users.get_users_by_discord_id(user_dto.user_id)
|
||||
# add auth_user to user refs
|
||||
db_auth_user.oauth_id = None
|
||||
@ -317,11 +284,7 @@ class AuthService(AuthServiceABC):
|
||||
# user does not exists
|
||||
self._logger.debug(__name__, f"Auth user does not exist")
|
||||
try:
|
||||
user_dto.user_id = (
|
||||
self._users.get_users_by_discord_id(user_dto.user_id)
|
||||
.single()
|
||||
.user_id
|
||||
)
|
||||
user_dto.user_id = self._users.get_users_by_discord_id(user_dto.user_id).single().user_id
|
||||
except Exception as e:
|
||||
self._logger.error(__name__, f"User not found")
|
||||
user_dto.user_id = None
|
||||
@ -340,9 +303,7 @@ class AuthService(AuthServiceABC):
|
||||
for user in users:
|
||||
if user.server.server_id != server.server_id:
|
||||
continue
|
||||
self._auth_users.add_auth_user_user_rel(
|
||||
AuthUserUsersRelation(db_auth_user, user)
|
||||
)
|
||||
self._auth_users.add_auth_user_user_rel(AuthUserUsersRelation(db_auth_user, user))
|
||||
|
||||
self._auth_users.update_auth_user(db_auth_user)
|
||||
self._db.save_changes()
|
||||
@ -353,16 +314,14 @@ class AuthService(AuthServiceABC):
|
||||
raise ServiceException(ServiceErrorCode.InvalidData, f"User is empty")
|
||||
|
||||
if update_user_dto.auth_user is None:
|
||||
raise ServiceException(
|
||||
ServiceErrorCode.InvalidData, f"Existing user is empty"
|
||||
)
|
||||
raise ServiceException(ServiceErrorCode.InvalidData, f"Existing user is empty")
|
||||
|
||||
if update_user_dto.new_auth_user is None:
|
||||
raise ServiceException(ServiceErrorCode.InvalidData, f"New user is empty")
|
||||
|
||||
if not self._is_email_valid(
|
||||
update_user_dto.auth_user.email
|
||||
) or not self._is_email_valid(update_user_dto.new_auth_user.email):
|
||||
if not self._is_email_valid(update_user_dto.auth_user.email) or not self._is_email_valid(
|
||||
update_user_dto.new_auth_user.email
|
||||
):
|
||||
raise ServiceException(ServiceErrorCode.InvalidData, f"Invalid E-Mail")
|
||||
|
||||
user = self._auth_users.find_auth_user_by_email(update_user_dto.auth_user.email)
|
||||
@ -375,8 +334,7 @@ class AuthService(AuthServiceABC):
|
||||
# update first name
|
||||
if (
|
||||
update_user_dto.new_auth_user.first_name is not None
|
||||
and update_user_dto.auth_user.first_name
|
||||
!= update_user_dto.new_auth_user.first_name
|
||||
and update_user_dto.auth_user.first_name != update_user_dto.new_auth_user.first_name
|
||||
):
|
||||
user.first_name = update_user_dto.new_auth_user.first_name
|
||||
|
||||
@ -384,8 +342,7 @@ class AuthService(AuthServiceABC):
|
||||
if (
|
||||
update_user_dto.new_auth_user.last_name is not None
|
||||
and update_user_dto.new_auth_user.last_name != ""
|
||||
and update_user_dto.auth_user.last_name
|
||||
!= update_user_dto.new_auth_user.last_name
|
||||
and update_user_dto.auth_user.last_name != update_user_dto.new_auth_user.last_name
|
||||
):
|
||||
user.last_name = update_user_dto.new_auth_user.last_name
|
||||
|
||||
@ -395,33 +352,22 @@ class AuthService(AuthServiceABC):
|
||||
and update_user_dto.new_auth_user.email != ""
|
||||
and update_user_dto.auth_user.email != update_user_dto.new_auth_user.email
|
||||
):
|
||||
user_by_new_e_mail = self._auth_users.find_auth_user_by_email(
|
||||
update_user_dto.new_auth_user.email
|
||||
)
|
||||
user_by_new_e_mail = self._auth_users.find_auth_user_by_email(update_user_dto.new_auth_user.email)
|
||||
if user_by_new_e_mail is not None:
|
||||
raise ServiceException(
|
||||
ServiceErrorCode.InvalidUser, "User already exists"
|
||||
)
|
||||
raise ServiceException(ServiceErrorCode.InvalidUser, "User already exists")
|
||||
user.email = update_user_dto.new_auth_user.email
|
||||
|
||||
update_user_dto.auth_user.password = self._hash_sha256(
|
||||
update_user_dto.auth_user.password, user.password_salt
|
||||
)
|
||||
update_user_dto.auth_user.password = self._hash_sha256(update_user_dto.auth_user.password, user.password_salt)
|
||||
if update_user_dto.auth_user.password != user.password:
|
||||
raise ServiceException(ServiceErrorCode.InvalidUser, "Wrong password")
|
||||
|
||||
# update password
|
||||
if (
|
||||
update_user_dto.new_auth_user.password is not None
|
||||
and self._hash_sha256(
|
||||
update_user_dto.new_auth_user.password, user.password_salt
|
||||
)
|
||||
!= user.password
|
||||
and self._hash_sha256(update_user_dto.new_auth_user.password, user.password_salt) != user.password
|
||||
):
|
||||
user.password_salt = uuid.uuid4()
|
||||
user.password = self._hash_sha256(
|
||||
update_user_dto.new_auth_user.password, user.password_salt
|
||||
)
|
||||
user.password = self._hash_sha256(update_user_dto.new_auth_user.password, user.password_salt)
|
||||
|
||||
self._auth_users.update_auth_user(user)
|
||||
self._db.save_changes()
|
||||
@ -431,31 +377,23 @@ class AuthService(AuthServiceABC):
|
||||
raise ServiceException(ServiceErrorCode.InvalidData, f"User is empty")
|
||||
|
||||
if update_user_dto.auth_user is None:
|
||||
raise ServiceException(
|
||||
ServiceErrorCode.InvalidData, f"Existing user is empty"
|
||||
)
|
||||
raise ServiceException(ServiceErrorCode.InvalidData, f"Existing user is empty")
|
||||
|
||||
if update_user_dto.new_auth_user is None:
|
||||
raise ServiceException(ServiceErrorCode.InvalidData, f"New user is empty")
|
||||
|
||||
if not self._is_email_valid(
|
||||
update_user_dto.auth_user.email
|
||||
) or not self._is_email_valid(update_user_dto.new_auth_user.email):
|
||||
if not self._is_email_valid(update_user_dto.auth_user.email) or not self._is_email_valid(
|
||||
update_user_dto.new_auth_user.email
|
||||
):
|
||||
raise ServiceException(ServiceErrorCode.InvalidData, f"Invalid E-Mail")
|
||||
|
||||
user = self._auth_users.find_auth_user_by_email(update_user_dto.auth_user.email)
|
||||
if user is None:
|
||||
raise ServiceException(ServiceErrorCode.InvalidUser, "User not found")
|
||||
|
||||
if (
|
||||
user.confirmation_id is not None
|
||||
and update_user_dto.new_auth_user.is_confirmed
|
||||
):
|
||||
if user.confirmation_id is not None and update_user_dto.new_auth_user.is_confirmed:
|
||||
user.confirmation_id = None
|
||||
elif (
|
||||
user.confirmation_id is None
|
||||
and not update_user_dto.new_auth_user.is_confirmed
|
||||
):
|
||||
elif user.confirmation_id is None and not update_user_dto.new_auth_user.is_confirmed:
|
||||
user.confirmation_id = uuid.uuid4()
|
||||
# else
|
||||
# raise ServiceException(ServiceErrorCode.InvalidUser, 'E-Mail not confirmed')
|
||||
@ -463,8 +401,7 @@ class AuthService(AuthServiceABC):
|
||||
# update first name
|
||||
if (
|
||||
update_user_dto.new_auth_user.first_name is not None
|
||||
and update_user_dto.auth_user.first_name
|
||||
!= update_user_dto.new_auth_user.first_name
|
||||
and update_user_dto.auth_user.first_name != update_user_dto.new_auth_user.first_name
|
||||
):
|
||||
user.first_name = update_user_dto.new_auth_user.first_name
|
||||
|
||||
@ -472,8 +409,7 @@ class AuthService(AuthServiceABC):
|
||||
if (
|
||||
update_user_dto.new_auth_user.last_name is not None
|
||||
and update_user_dto.new_auth_user.last_name != ""
|
||||
and update_user_dto.auth_user.last_name
|
||||
!= update_user_dto.new_auth_user.last_name
|
||||
and update_user_dto.auth_user.last_name != update_user_dto.new_auth_user.last_name
|
||||
):
|
||||
user.last_name = update_user_dto.new_auth_user.last_name
|
||||
|
||||
@ -483,28 +419,19 @@ class AuthService(AuthServiceABC):
|
||||
and update_user_dto.new_auth_user.email != ""
|
||||
and update_user_dto.auth_user.email != update_user_dto.new_auth_user.email
|
||||
):
|
||||
user_by_new_e_mail = self._auth_users.find_auth_user_by_email(
|
||||
update_user_dto.new_auth_user.email
|
||||
)
|
||||
user_by_new_e_mail = self._auth_users.find_auth_user_by_email(update_user_dto.new_auth_user.email)
|
||||
if user_by_new_e_mail is not None:
|
||||
raise ServiceException(
|
||||
ServiceErrorCode.InvalidUser, "User already exists"
|
||||
)
|
||||
raise ServiceException(ServiceErrorCode.InvalidUser, "User already exists")
|
||||
user.email = update_user_dto.new_auth_user.email
|
||||
|
||||
# update password
|
||||
if (
|
||||
update_user_dto.new_auth_user.password is not None
|
||||
and update_user_dto.change_password
|
||||
and user.password
|
||||
!= self._hash_sha256(
|
||||
update_user_dto.new_auth_user.password, user.password_salt
|
||||
)
|
||||
and user.password != self._hash_sha256(update_user_dto.new_auth_user.password, user.password_salt)
|
||||
):
|
||||
user.password_salt = uuid.uuid4()
|
||||
user.password = self._hash_sha256(
|
||||
update_user_dto.new_auth_user.password, user.password_salt
|
||||
)
|
||||
user.password = self._hash_sha256(update_user_dto.new_auth_user.password, user.password_salt)
|
||||
|
||||
# update role
|
||||
if (
|
||||
@ -523,9 +450,7 @@ class AuthService(AuthServiceABC):
|
||||
self._db.save_changes()
|
||||
except Exception as e:
|
||||
self._logger.error(__name__, f"Cannot delete user", e)
|
||||
raise ServiceException(
|
||||
ServiceErrorCode.UnableToDelete, f"Cannot delete user by mail {email}"
|
||||
)
|
||||
raise ServiceException(ServiceErrorCode.UnableToDelete, f"Cannot delete user by mail {email}")
|
||||
|
||||
async def delete_auth_user_async(self, user_dto: AuthUser):
|
||||
try:
|
||||
@ -608,19 +533,13 @@ class AuthService(AuthServiceABC):
|
||||
):
|
||||
raise ServiceException(ServiceErrorCode.InvalidData, "Token expired")
|
||||
|
||||
return TokenDTO(
|
||||
self.generate_token(user), self._create_and_save_refresh_token(user)
|
||||
)
|
||||
return TokenDTO(self.generate_token(user), self._create_and_save_refresh_token(user))
|
||||
except Exception as e:
|
||||
self._logger.error(__name__, f"Refreshing token failed", e)
|
||||
return TokenDTO("", "")
|
||||
|
||||
async def revoke_async(self, token_dto: TokenDTO):
|
||||
if (
|
||||
token_dto is None
|
||||
or token_dto.token is None
|
||||
or token_dto.refresh_token is None
|
||||
):
|
||||
if token_dto is None or token_dto.token is None or token_dto.refresh_token is None:
|
||||
raise ServiceException(ServiceErrorCode.InvalidData, "Token not set")
|
||||
|
||||
try:
|
||||
@ -673,9 +592,7 @@ class AuthService(AuthServiceABC):
|
||||
)
|
||||
|
||||
if user.confirmation_id is not None:
|
||||
raise ServiceException(
|
||||
ServiceErrorCode.InvalidUser, f"E-Mail not confirmed"
|
||||
)
|
||||
raise ServiceException(ServiceErrorCode.InvalidUser, f"E-Mail not confirmed")
|
||||
|
||||
if user.password is None or rp_dto.password == "":
|
||||
raise ServiceException(ServiceErrorCode.InvalidData, f"Password not set")
|
||||
|
@ -55,17 +55,13 @@ class DiscordService:
|
||||
if role != AuthRoleEnum.admin:
|
||||
auth_user = self._auth_users.find_auth_user_by_email(token["email"])
|
||||
if auth_user is not None:
|
||||
user_ids = auth_user.users.select(
|
||||
lambda x: x.server is not None and x.server.server_id
|
||||
)
|
||||
user_ids = auth_user.users.select(lambda x: x.server is not None and x.server.server_id)
|
||||
servers = servers.where(lambda x: x.server_id in user_ids)
|
||||
|
||||
servers = List(ServerDTO, servers)
|
||||
return servers.select(self._to_dto).where(lambda x: x.name != "")
|
||||
|
||||
async def get_filtered_servers_async(
|
||||
self, criteria: ServerSelectCriteria
|
||||
) -> ServerFilteredResultDTO:
|
||||
async def get_filtered_servers_async(self, criteria: ServerSelectCriteria) -> ServerFilteredResultDTO:
|
||||
token = self._auth.get_decoded_token_from_request()
|
||||
if token is None or "email" not in token or "role" not in token:
|
||||
raise ServiceException(ServiceErrorCode.InvalidData, "Token invalid")
|
||||
@ -76,22 +72,15 @@ class DiscordService:
|
||||
if role != AuthRoleEnum.admin:
|
||||
auth_user = self._auth_users.find_auth_user_by_email(token["email"])
|
||||
if auth_user is not None:
|
||||
user_ids = auth_user.users.select(
|
||||
lambda x: x.server is not None and x.server.server_id
|
||||
)
|
||||
filtered_result.result = filtered_result.result.where(
|
||||
lambda x: x.server_id in user_ids
|
||||
)
|
||||
user_ids = auth_user.users.select(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)
|
||||
|
||||
servers: List = filtered_result.result.select(self._to_dto).where(
|
||||
lambda x: x.name != ""
|
||||
)
|
||||
servers: List = filtered_result.result.select(self._to_dto).where(lambda x: x.name != "")
|
||||
result = List(ServerDTO, servers)
|
||||
|
||||
if criteria.name is not None and criteria.name != "":
|
||||
result = result.where(
|
||||
lambda x: criteria.name.lower() in x.name.lower()
|
||||
or x.name.lower() == criteria.name.lower()
|
||||
lambda x: criteria.name.lower() in x.name.lower() or x.name.lower() == criteria.name.lower()
|
||||
)
|
||||
|
||||
return ServerFilteredResultDTO(List(ServerDTO, result), servers.count())
|
||||
@ -100,7 +89,5 @@ class DiscordService:
|
||||
server = self._servers.get_server_by_id(id)
|
||||
guild = self._bot.get_guild(server.discord_server_id)
|
||||
|
||||
server_dto = ServerTransformer.to_dto(
|
||||
server, guild.name, guild.member_count, guild.icon
|
||||
)
|
||||
server_dto = ServerTransformer.to_dto(server, guild.name, guild.member_count, guild.icon)
|
||||
return server_dto
|
||||
|
@ -20,9 +20,7 @@ class AuthUserTransformer(TransformerABC):
|
||||
None,
|
||||
None,
|
||||
datetime.now(),
|
||||
AuthRoleEnum.normal
|
||||
if dto.auth_role is None
|
||||
else AuthRoleEnum(dto.auth_role),
|
||||
AuthRoleEnum.normal if dto.auth_role is None else AuthRoleEnum(dto.auth_role),
|
||||
auth_user_id=0 if dto.id is None else dto.id,
|
||||
)
|
||||
|
||||
|
@ -13,9 +13,7 @@ class ServerTransformer(TransformerABC):
|
||||
return Server(dto.discord_id)
|
||||
|
||||
@staticmethod
|
||||
def to_dto(
|
||||
db: Server, name: str, member_count: int, icon_url: Optional[discord.Asset]
|
||||
) -> ServerDTO:
|
||||
def to_dto(db: Server, name: str, member_count: int, icon_url: Optional[discord.Asset]) -> ServerDTO:
|
||||
return ServerDTO(
|
||||
db.server_id,
|
||||
db.discord_server_id,
|
||||
|
@ -43,9 +43,7 @@ class ClientUtilsABC(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_auto_complete_list(
|
||||
self, _l: List, current: str, select: Callable = None
|
||||
) -> List:
|
||||
def get_auto_complete_list(self, _l: List, current: str, select: Callable = None) -> List:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
|
@ -18,9 +18,7 @@ class CustomFileLoggerABC(Logger, ABC):
|
||||
env: ApplicationEnvironmentABC,
|
||||
):
|
||||
self._key = key
|
||||
self._settings: LoggingSettings = config.get_configuration(
|
||||
f"{FileLoggingSettings.__name__}_{key}"
|
||||
)
|
||||
self._settings: LoggingSettings = config.get_configuration(f"{FileLoggingSettings.__name__}_{key}")
|
||||
Logger.__init__(self, self._settings, time_format, env)
|
||||
self._begin_log()
|
||||
|
||||
@ -34,9 +32,7 @@ class CustomFileLoggerABC(Logger, ABC):
|
||||
self.info(__name__, f"Starting...")
|
||||
self._console = LoggingLevelEnum(console_level)
|
||||
|
||||
def _get_string(
|
||||
self, name_list_as_str: str, level: LoggingLevelEnum, message: str
|
||||
) -> str:
|
||||
def _get_string(self, name_list_as_str: str, level: LoggingLevelEnum, message: str) -> str:
|
||||
names = name_list_as_str.split(" ")
|
||||
log_level = level.name
|
||||
string = f"<{self._get_datetime_now()}> [ {log_level} ]"
|
||||
|
@ -13,9 +13,7 @@ class MessageServiceABC(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def delete_messages(
|
||||
self, messages: List[discord.Message], guild_id: int, without_tracking=False
|
||||
):
|
||||
async def delete_messages(self, messages: List[discord.Message], guild_id: int, without_tracking=False):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
|
@ -27,10 +27,6 @@ class BotLoggingSettings(ConfigurationModelABC):
|
||||
self._files = files
|
||||
except Exception as e:
|
||||
Console.set_foreground_color(ForegroundColorEnum.red)
|
||||
Console.write_line(
|
||||
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings"
|
||||
)
|
||||
Console.write_line(
|
||||
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
|
||||
)
|
||||
Console.write_line(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
|
||||
Console.write_line(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
|
||||
Console.set_foreground_color(ForegroundColorEnum.default)
|
||||
|
@ -58,9 +58,5 @@ class BotSettings(ConfigurationModelABC):
|
||||
servers.append(st)
|
||||
self._servers = servers
|
||||
except Exception as e:
|
||||
Console.error(
|
||||
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings"
|
||||
)
|
||||
Console.error(
|
||||
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
|
||||
)
|
||||
Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
|
||||
Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
|
||||
|
@ -46,9 +46,5 @@ class FeatureFlagsSettings(ConfigurationModelABC):
|
||||
for flag in [f.value for f in FeatureFlagsEnum]:
|
||||
self._load_flag(settings, FeatureFlagsEnum(flag))
|
||||
except Exception as e:
|
||||
Console.error(
|
||||
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings"
|
||||
)
|
||||
Console.error(
|
||||
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
|
||||
)
|
||||
Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
|
||||
Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
|
||||
|
@ -19,9 +19,5 @@ class FileLoggingSettings(LoggingSettings):
|
||||
self._key = settings["Key"]
|
||||
super().from_dict(settings)
|
||||
except Exception as e:
|
||||
Console.error(
|
||||
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings"
|
||||
)
|
||||
Console.error(
|
||||
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
|
||||
)
|
||||
Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
|
||||
Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
|
||||
|
@ -25,6 +25,4 @@ class ServerSettings(ConfigurationModelABC):
|
||||
self._message_delete_timer = int(settings["MessageDeleteTimer"])
|
||||
except Exception as e:
|
||||
Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in settings")
|
||||
Console.error(
|
||||
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
|
||||
)
|
||||
Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
|
||||
|
@ -17,9 +17,7 @@ class CoreExtension(ApplicationExtensionABC):
|
||||
ApplicationExtensionABC.__init__(self)
|
||||
|
||||
async def run(self, config: ConfigurationABC, services: ServiceProviderABC):
|
||||
feature_flags: FeatureFlagsSettings = config.get_configuration(
|
||||
FeatureFlagsSettings
|
||||
)
|
||||
feature_flags: FeatureFlagsSettings = config.get_configuration(FeatureFlagsSettings)
|
||||
if not feature_flags.get_flag(FeatureFlagsEnum.core_module):
|
||||
return
|
||||
|
||||
|
@ -15,14 +15,8 @@ class CoreExtensionModule(ModuleABC):
|
||||
def __init__(self, dc: DiscordCollectionABC):
|
||||
ModuleABC.__init__(self, dc, FeatureFlagsEnum.core_extension_module)
|
||||
|
||||
def configure_configuration(
|
||||
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
|
||||
pass
|
||||
|
||||
def configure_services(
|
||||
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
self._dc.add_event(
|
||||
DiscordEventTypesEnum.on_ready.value, CoreExtensionOnReadyEvent
|
||||
)
|
||||
def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
|
||||
self._dc.add_event(DiscordEventTypesEnum.on_ready.value, CoreExtensionOnReadyEvent)
|
||||
|
@ -18,14 +18,10 @@ class CoreModule(ModuleABC):
|
||||
def __init__(self, dc: DiscordCollectionABC):
|
||||
ModuleABC.__init__(self, dc, FeatureFlagsEnum.core_module)
|
||||
|
||||
def configure_configuration(
|
||||
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
|
||||
pass
|
||||
|
||||
def configure_services(
|
||||
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
|
||||
services.add_transient(MessageServiceABC, MessageService)
|
||||
services.add_transient(ClientUtilsABC, ClientUtilsService)
|
||||
|
||||
|
@ -44,9 +44,7 @@ class CommandChecks:
|
||||
async def check_is_member_admin(ctx: Context):
|
||||
has_permission = cls._permissions.is_member_admin(ctx.author)
|
||||
if not has_permission:
|
||||
await cls._message_service.send_ctx_msg(
|
||||
ctx, cls._t.transform("common.no_permission_message")
|
||||
)
|
||||
await cls._message_service.send_ctx_msg(ctx, cls._t.transform("common.no_permission_message"))
|
||||
raise CheckError(f"Member {ctx.author.name} is not admin")
|
||||
|
||||
return has_permission
|
||||
@ -58,9 +56,7 @@ class CommandChecks:
|
||||
async def check_is_member_technician(ctx: Context):
|
||||
has_permission = cls._permissions.is_member_technician(ctx.author)
|
||||
if not has_permission:
|
||||
await cls._message_service.send_ctx_msg(
|
||||
ctx, cls._t.transform("common.no_permission_message")
|
||||
)
|
||||
await cls._message_service.send_ctx_msg(ctx, cls._t.transform("common.no_permission_message"))
|
||||
raise CheckError(f"Member {ctx.author.name} is not technician")
|
||||
|
||||
return has_permission
|
||||
@ -72,9 +68,7 @@ class CommandChecks:
|
||||
async def check_is_member_moderator(ctx: Context):
|
||||
has_permission = cls._permissions.is_member_moderator(ctx.author)
|
||||
if not has_permission:
|
||||
await cls._message_service.send_ctx_msg(
|
||||
ctx, cls._t.transform("common.no_permission_message")
|
||||
)
|
||||
await cls._message_service.send_ctx_msg(ctx, cls._t.transform("common.no_permission_message"))
|
||||
raise CheckError(f"Member {ctx.author.name} is not moderator")
|
||||
|
||||
return has_permission
|
||||
|
@ -60,36 +60,28 @@ class ClientUtilsService(ClientUtilsABC):
|
||||
|
||||
def received_command(self, guild_id: int):
|
||||
server = self._servers.get_server_by_discord_id(guild_id)
|
||||
client = self._clients.find_client_by_discord_id_and_server_id(
|
||||
self._bot.user.id, server.server_id
|
||||
)
|
||||
client = self._clients.find_client_by_discord_id_and_server_id(self._bot.user.id, server.server_id)
|
||||
client.received_command_count += 1
|
||||
self._clients.update_client(client)
|
||||
self._db.save_changes()
|
||||
|
||||
def moved_user(self, guild_id: int):
|
||||
server = self._servers.get_server_by_discord_id(guild_id)
|
||||
client = self._clients.find_client_by_discord_id_and_server_id(
|
||||
self._bot.user.id, server.server_id
|
||||
)
|
||||
client = self._clients.find_client_by_discord_id_and_server_id(self._bot.user.id, server.server_id)
|
||||
client.moved_users_count += 1
|
||||
self._clients.update_client(client)
|
||||
self._db.save_changes()
|
||||
|
||||
def moved_users(self, guild_id: int, count: int):
|
||||
server = self._servers.get_server_by_discord_id(guild_id)
|
||||
client = self._clients.find_client_by_discord_id_and_server_id(
|
||||
self._bot.user.id, server.server_id
|
||||
)
|
||||
client = self._clients.find_client_by_discord_id_and_server_id(self._bot.user.id, server.server_id)
|
||||
client.moved_users_count += count
|
||||
self._clients.update_client(client)
|
||||
self._db.save_changes()
|
||||
|
||||
def get_client(self, dc_ic: int, guild_id: int):
|
||||
server = self._servers.get_server_by_discord_id(guild_id)
|
||||
client = self._clients.find_client_by_discord_id_and_server_id(
|
||||
self._bot.user.id, server.server_id
|
||||
)
|
||||
client = self._clients.find_client_by_discord_id_and_server_id(self._bot.user.id, server.server_id)
|
||||
return client
|
||||
|
||||
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))
|
||||
self._logger.info(__name__, f"Set presence {name}")
|
||||
|
||||
def get_auto_complete_list(
|
||||
self, _l: List, current: str, select: Callable = None
|
||||
) -> List:
|
||||
def get_auto_complete_list(self, _l: List, current: str, select: Callable = None) -> List:
|
||||
if current != "":
|
||||
if select is None:
|
||||
select = lambda x: x
|
||||
@ -148,9 +138,7 @@ class ClientUtilsService(ClientUtilsABC):
|
||||
) -> bool:
|
||||
umcph = None
|
||||
try:
|
||||
umcph = self._umcphs.find_user_message_count_per_hour_by_user_id_and_date(
|
||||
user.user_id, created_at
|
||||
)
|
||||
umcph = self._umcphs.find_user_message_count_per_hour_by_user_id_and_date(user.user_id, created_at)
|
||||
if umcph is None:
|
||||
self._umcphs.add_user_message_count_per_hour(
|
||||
UserMessageCountPerHour(
|
||||
@ -163,11 +151,7 @@ class ClientUtilsService(ClientUtilsABC):
|
||||
|
||||
self._db.save_changes()
|
||||
|
||||
umcph = (
|
||||
self._umcphs.get_user_message_count_per_hour_by_user_id_and_date(
|
||||
user.user_id, created_at
|
||||
)
|
||||
)
|
||||
umcph = self._umcphs.get_user_message_count_per_hour_by_user_id_and_date(user.user_id, created_at)
|
||||
except Exception as e:
|
||||
self._logger.error(
|
||||
__name__,
|
||||
@ -199,13 +183,7 @@ class ClientUtilsService(ClientUtilsABC):
|
||||
|
||||
def get_ontime_for_user(self, user: User) -> float:
|
||||
return (
|
||||
self._user_joined_voice_channel.get_user_joined_voice_channels_by_user_id(
|
||||
user.user_id
|
||||
)
|
||||
self._user_joined_voice_channel.get_user_joined_voice_channels_by_user_id(user.user_id)
|
||||
.where(lambda x: x.leaved_on is not None and x.joined_on is not None)
|
||||
.sum(
|
||||
lambda join: round(
|
||||
(join.leaved_on - join.joined_on).total_seconds() / 3600, 2
|
||||
)
|
||||
)
|
||||
.sum(lambda join: round((join.leaved_on - join.joined_on).total_seconds() / 3600, 2))
|
||||
)
|
||||
|
@ -31,23 +31,15 @@ class MessageService(MessageServiceABC):
|
||||
self._clients = clients
|
||||
self._db = db
|
||||
|
||||
async def delete_messages(
|
||||
self, messages: List[discord.Message], guild_id: int, without_tracking=False
|
||||
):
|
||||
async def delete_messages(self, messages: List[discord.Message], guild_id: int, without_tracking=False):
|
||||
self._logger.debug(__name__, f"Try to delete {messages.count()} messages")
|
||||
server_st: ServerSettings = self._config.get_configuration(
|
||||
f"ServerSettings_{guild_id}"
|
||||
)
|
||||
server_st: ServerSettings = self._config.get_configuration(f"ServerSettings_{guild_id}")
|
||||
await asyncio.sleep(server_st.message_delete_timer)
|
||||
for message in messages:
|
||||
await self.delete_message(
|
||||
message, mass_delete=True, without_tracking=without_tracking
|
||||
)
|
||||
await self.delete_message(message, mass_delete=True, without_tracking=without_tracking)
|
||||
self._logger.debug(__name__, "Deleting messages finished")
|
||||
|
||||
async def delete_message(
|
||||
self, message: discord.Message, mass_delete=False, without_tracking=False
|
||||
):
|
||||
async def delete_message(self, message: discord.Message, mass_delete=False, without_tracking=False):
|
||||
guild_id = (
|
||||
message.guild.id
|
||||
if message.guild is not None
|
||||
@ -58,9 +50,7 @@ class MessageService(MessageServiceABC):
|
||||
else None
|
||||
)
|
||||
|
||||
server_st: ServerSettings = self._config.get_configuration(
|
||||
f"ServerSettings_{guild_id}"
|
||||
)
|
||||
server_st: ServerSettings = self._config.get_configuration(f"ServerSettings_{guild_id}")
|
||||
if not mass_delete:
|
||||
await asyncio.sleep(server_st.message_delete_timer)
|
||||
self._logger.debug(
|
||||
@ -74,9 +64,7 @@ class MessageService(MessageServiceABC):
|
||||
self._logger.error(__name__, f"Deleting message failed", e)
|
||||
else:
|
||||
if not without_tracking:
|
||||
self._clients.append_deleted_message_count(
|
||||
self._bot.user.id, guild_id, 1
|
||||
)
|
||||
self._clients.append_deleted_message_count(self._bot.user.id, guild_id, 1)
|
||||
self._db.save_changes()
|
||||
self._logger.info(__name__, f"Deleted message {message}")
|
||||
|
||||
@ -88,9 +76,7 @@ class MessageService(MessageServiceABC):
|
||||
wait_before_delete: int = None,
|
||||
without_tracking=False,
|
||||
):
|
||||
self._logger.debug(
|
||||
__name__, f"Try to send message\n\t{message}\n\tto: {channel}"
|
||||
)
|
||||
self._logger.debug(__name__, f"Try to send message\n\t{message}\n\tto: {channel}")
|
||||
msg = None
|
||||
try:
|
||||
if isinstance(message, discord.Embed):
|
||||
@ -98,15 +84,11 @@ class MessageService(MessageServiceABC):
|
||||
else:
|
||||
msg = await channel.send(message)
|
||||
except Exception as e:
|
||||
self._logger.error(
|
||||
__name__, f"Send message to channel {channel.id} failed", e
|
||||
)
|
||||
self._logger.error(__name__, f"Send message to channel {channel.id} failed", e)
|
||||
else:
|
||||
self._logger.info(__name__, f"Sent message to channel {channel.id}")
|
||||
if not without_tracking:
|
||||
self._clients.append_sent_message_count(
|
||||
self._bot.user.id, channel.guild.id, 1
|
||||
)
|
||||
self._clients.append_sent_message_count(self._bot.user.id, channel.guild.id, 1)
|
||||
self._db.save_changes()
|
||||
|
||||
if wait_before_delete is not None:
|
||||
@ -123,23 +105,17 @@ class MessageService(MessageServiceABC):
|
||||
receiver: Union[discord.User, discord.Member],
|
||||
without_tracking=False,
|
||||
):
|
||||
self._logger.debug(
|
||||
__name__, f"Try to send message\n\t{message}\n\tto: {receiver}"
|
||||
)
|
||||
self._logger.debug(__name__, f"Try to send message\n\t{message}\n\tto: {receiver}")
|
||||
try:
|
||||
if isinstance(message, discord.Embed):
|
||||
msg = await receiver.send(embed=message)
|
||||
else:
|
||||
msg = await receiver.send(message)
|
||||
except Exception as e:
|
||||
self._logger.error(
|
||||
__name__, f"Send message to user {receiver.id} failed", e
|
||||
)
|
||||
self._logger.error(__name__, f"Send message to user {receiver.id} failed", e)
|
||||
else:
|
||||
if not without_tracking:
|
||||
self._clients.append_sent_message_count(
|
||||
self._bot.user.id, receiver.guild.id, 1
|
||||
)
|
||||
self._clients.append_sent_message_count(self._bot.user.id, receiver.guild.id, 1)
|
||||
self._db.save_changes()
|
||||
self._logger.info(__name__, f"Sent message to user {receiver.id}")
|
||||
|
||||
@ -158,9 +134,7 @@ class MessageService(MessageServiceABC):
|
||||
self._logger.debug(__name__, f"Message: {message}")
|
||||
return None
|
||||
|
||||
self._logger.debug(
|
||||
__name__, f"Try to send message\t\t{message}\n\tto: {ctx.channel}"
|
||||
)
|
||||
self._logger.debug(__name__, f"Try to send message\t\t{message}\n\tto: {ctx.channel}")
|
||||
msg = None
|
||||
try:
|
||||
if isinstance(message, discord.Embed):
|
||||
@ -168,15 +142,11 @@ class MessageService(MessageServiceABC):
|
||||
else:
|
||||
msg = await ctx.send(message, file=file, ephemeral=not is_public)
|
||||
except Exception as e:
|
||||
self._logger.error(
|
||||
__name__, f"Send message to channel {ctx.channel.id} failed", e
|
||||
)
|
||||
self._logger.error(__name__, f"Send message to channel {ctx.channel.id} failed", e)
|
||||
else:
|
||||
self._logger.info(__name__, f"Sent message to channel {ctx.channel.id}")
|
||||
if not without_tracking and ctx.guild is not None:
|
||||
self._clients.append_sent_message_count(
|
||||
self._bot.user.id, ctx.guild.id, 1
|
||||
)
|
||||
self._clients.append_sent_message_count(self._bot.user.id, ctx.guild.id, 1)
|
||||
self._db.save_changes()
|
||||
|
||||
if wait_before_delete is not None:
|
||||
@ -205,30 +175,18 @@ class MessageService(MessageServiceABC):
|
||||
self._logger.debug(__name__, f"Message: {message}")
|
||||
return
|
||||
|
||||
self._logger.debug(
|
||||
__name__, f"Try to send message\t\t{message}\n\tto: {interaction.channel}"
|
||||
)
|
||||
self._logger.debug(__name__, f"Try to send message\t\t{message}\n\tto: {interaction.channel}")
|
||||
try:
|
||||
if isinstance(message, discord.Embed):
|
||||
await interaction.response.send_message(
|
||||
embed=message, ephemeral=not is_public, **kwargs
|
||||
)
|
||||
await interaction.response.send_message(embed=message, ephemeral=not is_public, **kwargs)
|
||||
else:
|
||||
await interaction.response.send_message(
|
||||
message, ephemeral=not is_public, **kwargs
|
||||
)
|
||||
await interaction.response.send_message(message, ephemeral=not is_public, **kwargs)
|
||||
except Exception as e:
|
||||
self._logger.error(
|
||||
__name__, f"Send message to channel {interaction.channel.id} failed", e
|
||||
)
|
||||
self._logger.error(__name__, f"Send message to channel {interaction.channel.id} failed", e)
|
||||
else:
|
||||
self._logger.info(
|
||||
__name__, f"Sent message to channel {interaction.channel.id}"
|
||||
)
|
||||
self._logger.info(__name__, f"Sent message to channel {interaction.channel.id}")
|
||||
if not without_tracking and interaction.guild is not None:
|
||||
self._clients.append_sent_message_count(
|
||||
self._bot.user.id, interaction.guild.id, 1
|
||||
)
|
||||
self._clients.append_sent_message_count(self._bot.user.id, interaction.guild.id, 1)
|
||||
self._db.save_changes()
|
||||
|
||||
if wait_before_delete is not None:
|
||||
@ -237,6 +195,4 @@ class MessageService(MessageServiceABC):
|
||||
if is_persistent:
|
||||
return
|
||||
|
||||
await self.delete_message(
|
||||
await interaction.original_response(), without_tracking
|
||||
)
|
||||
await self.delete_message(await interaction.original_response(), without_tracking)
|
||||
|
@ -19,9 +19,7 @@ class AuthUserRepositoryABC(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_filtered_auth_users(
|
||||
self, criteria: AuthUserSelectCriteria
|
||||
) -> FilteredResult:
|
||||
def get_filtered_auth_users(self, criteria: AuthUserSelectCriteria) -> FilteredResult:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
|
@ -31,9 +31,7 @@ class ClientRepositoryABC(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def find_client_by_discord_id_and_server_id(
|
||||
self, discord_id: int, server_id: int
|
||||
) -> Optional[Client]:
|
||||
def find_client_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> Optional[Client]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
|
@ -19,21 +19,15 @@ class UserJoinedServerRepositoryABC(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_user_joined_servers_by_user_id(
|
||||
self, user_id: int
|
||||
) -> list[UserJoinedServer]:
|
||||
def get_user_joined_servers_by_user_id(self, user_id: int) -> list[UserJoinedServer]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_active_user_joined_server_by_user_id(
|
||||
self, user_id: int
|
||||
) -> UserJoinedServer:
|
||||
def get_active_user_joined_server_by_user_id(self, user_id: int) -> UserJoinedServer:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def find_active_user_joined_server_by_user_id(
|
||||
self, user_id: int
|
||||
) -> Optional[UserJoinedServer]:
|
||||
def find_active_user_joined_server_by_user_id(self, user_id: int) -> Optional[UserJoinedServer]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
|
@ -19,45 +19,31 @@ class UserJoinedVoiceChannelRepositoryABC(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_user_joined_voice_channels_by_user_id(
|
||||
self, user_id: int
|
||||
) -> List[UserJoinedVoiceChannel]:
|
||||
def get_user_joined_voice_channels_by_user_id(self, user_id: int) -> List[UserJoinedVoiceChannel]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_active_user_joined_voice_channel_by_user_id(
|
||||
self, user_id: int
|
||||
) -> UserJoinedVoiceChannel:
|
||||
def get_active_user_joined_voice_channel_by_user_id(self, user_id: int) -> UserJoinedVoiceChannel:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def find_active_user_joined_voice_channel_by_user_id(
|
||||
self, user_id: int
|
||||
) -> Optional[UserJoinedVoiceChannel]:
|
||||
def find_active_user_joined_voice_channel_by_user_id(self, user_id: int) -> Optional[UserJoinedVoiceChannel]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def find_active_user_joined_voice_channels_by_user_id(
|
||||
self, user_id: int
|
||||
) -> List[Optional[UserJoinedVoiceChannel]]:
|
||||
def find_active_user_joined_voice_channels_by_user_id(self, user_id: int) -> List[Optional[UserJoinedVoiceChannel]]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def add_user_joined_voice_channel(
|
||||
self, user_joined_voice_channel: UserJoinedVoiceChannel
|
||||
):
|
||||
def add_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def update_user_joined_voice_channel(
|
||||
self, user_joined_voice_channel: UserJoinedVoiceChannel
|
||||
):
|
||||
def update_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def delete_user_joined_voice_channel(
|
||||
self, user_joined_voice_channel: UserJoinedVoiceChannel
|
||||
):
|
||||
def delete_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
|
@ -17,9 +17,7 @@ class UserMessageCountPerHourRepositoryABC(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def find_user_message_count_per_hour_by_user_id(
|
||||
self, user_id: int
|
||||
) -> Optional[UserMessageCountPerHour]:
|
||||
def find_user_message_count_per_hour_by_user_id(self, user_id: int) -> Optional[UserMessageCountPerHour]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
|
@ -28,15 +28,11 @@ class UserRepositoryABC(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_user_by_discord_id_and_server_id(
|
||||
self, discord_id: int, server_id: int
|
||||
) -> User:
|
||||
def get_user_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> User:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def find_user_by_discord_id_and_server_id(
|
||||
self, discord_id: int, server_id: int
|
||||
) -> Optional[User]:
|
||||
def find_user_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> Optional[User]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
|
@ -44,25 +44,17 @@ class DataModule(ModuleABC):
|
||||
def __init__(self, dc: DiscordCollectionABC):
|
||||
ModuleABC.__init__(self, dc, FeatureFlagsEnum.data_module)
|
||||
|
||||
def configure_configuration(
|
||||
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
|
||||
pass
|
||||
|
||||
def configure_services(
|
||||
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
|
||||
services.add_transient(AuthUserRepositoryABC, AuthUserRepositoryService)
|
||||
services.add_transient(ServerRepositoryABC, ServerRepositoryService)
|
||||
services.add_transient(UserRepositoryABC, UserRepositoryService)
|
||||
services.add_transient(ClientRepositoryABC, ClientRepositoryService)
|
||||
services.add_transient(KnownUserRepositoryABC, KnownUserRepositoryService)
|
||||
services.add_transient(
|
||||
UserJoinedServerRepositoryABC, UserJoinedServerRepositoryService
|
||||
)
|
||||
services.add_transient(
|
||||
UserJoinedVoiceChannelRepositoryABC, UserJoinedVoiceChannelRepositoryService
|
||||
)
|
||||
services.add_transient(UserJoinedServerRepositoryABC, UserJoinedServerRepositoryService)
|
||||
services.add_transient(UserJoinedVoiceChannelRepositoryABC, UserJoinedVoiceChannelRepositoryService)
|
||||
services.add_transient(AutoRoleRepositoryABC, AutoRoleRepositoryService)
|
||||
services.add_transient(LevelRepositoryABC, LevelRepositoryService)
|
||||
services.add_transient(StatisticRepositoryABC, StatisticRepositoryService)
|
||||
|
@ -47,9 +47,7 @@ class AuthUser(TableABC):
|
||||
|
||||
TableABC.__init__(self)
|
||||
self._created_at = created_at if created_at is not None else self._created_at
|
||||
self._modified_at = (
|
||||
modified_at if modified_at is not None else self._modified_at
|
||||
)
|
||||
self._modified_at = modified_at if modified_at is not None else self._modified_at
|
||||
|
||||
@property
|
||||
def id(self) -> int:
|
||||
|
@ -19,9 +19,7 @@ class AuthUserUsersRelation(TableABC):
|
||||
|
||||
TableABC.__init__(self)
|
||||
self._created_at = created_at if created_at is not None else self._created_at
|
||||
self._modified_at = (
|
||||
modified_at if modified_at is not None else self._modified_at
|
||||
)
|
||||
self._modified_at = modified_at if modified_at is not None else self._modified_at
|
||||
|
||||
@property
|
||||
def auth_user(self) -> AuthUser:
|
||||
|
@ -21,9 +21,7 @@ class AutoRole(TableABC):
|
||||
|
||||
TableABC.__init__(self)
|
||||
self._created_at = created_at if created_at is not None else self._created_at
|
||||
self._modified_at = (
|
||||
modified_at if modified_at is not None else self._modified_at
|
||||
)
|
||||
self._modified_at = modified_at if modified_at is not None else self._modified_at
|
||||
|
||||
@property
|
||||
def auto_role_id(self) -> int:
|
||||
|
@ -21,9 +21,7 @@ class AutoRoleRule(TableABC):
|
||||
|
||||
TableABC.__init__(self)
|
||||
self._created_at = created_at if created_at is not None else self._created_at
|
||||
self._modified_at = (
|
||||
modified_at if modified_at is not None else self._modified_at
|
||||
)
|
||||
self._modified_at = modified_at if modified_at is not None else self._modified_at
|
||||
|
||||
@property
|
||||
def auto_role_rule_id(self) -> int:
|
||||
|
@ -29,9 +29,7 @@ class Client(TableABC):
|
||||
|
||||
TableABC.__init__(self)
|
||||
self._created_at = created_at if created_at is not None else self._created_at
|
||||
self._modified_at = (
|
||||
modified_at if modified_at is not None else self._modified_at
|
||||
)
|
||||
self._modified_at = modified_at if modified_at is not None else self._modified_at
|
||||
|
||||
@property
|
||||
def client_id(self) -> int:
|
||||
|
@ -18,9 +18,7 @@ class KnownUser(TableABC):
|
||||
|
||||
TableABC.__init__(self)
|
||||
self._created_at = created_at if created_at is not None else self._created_at
|
||||
self._modified_at = (
|
||||
modified_at if modified_at is not None else self._modified_at
|
||||
)
|
||||
self._modified_at = modified_at if modified_at is not None else self._modified_at
|
||||
|
||||
@property
|
||||
def known_user_id(self) -> int:
|
||||
|
@ -26,9 +26,7 @@ class Level(TableABC):
|
||||
|
||||
TableABC.__init__(self)
|
||||
self._created_at = created_at if created_at is not None else self._created_at
|
||||
self._modified_at = (
|
||||
modified_at if modified_at is not None else self._modified_at
|
||||
)
|
||||
self._modified_at = modified_at if modified_at is not None else self._modified_at
|
||||
|
||||
@property
|
||||
def id(self) -> int:
|
||||
|
@ -17,9 +17,7 @@ class Server(TableABC):
|
||||
|
||||
TableABC.__init__(self)
|
||||
self._created_at = created_at if created_at is not None else self._created_at
|
||||
self._modified_at = (
|
||||
modified_at if modified_at is not None else self._modified_at
|
||||
)
|
||||
self._modified_at = modified_at if modified_at is not None else self._modified_at
|
||||
|
||||
@property
|
||||
def server_id(self) -> int:
|
||||
|
@ -25,9 +25,7 @@ class Statistic(TableABC):
|
||||
|
||||
TableABC.__init__(self)
|
||||
self._created_at = created_at if created_at is not None else self._created_at
|
||||
self._modified_at = (
|
||||
modified_at if modified_at is not None else self._modified_at
|
||||
)
|
||||
self._modified_at = modified_at if modified_at is not None else self._modified_at
|
||||
|
||||
@property
|
||||
def id(self) -> int:
|
||||
|
@ -22,9 +22,7 @@ class User(TableABC):
|
||||
|
||||
TableABC.__init__(self)
|
||||
self._created_at = created_at if created_at is not None else self._created_at
|
||||
self._modified_at = (
|
||||
modified_at if modified_at is not None else self._modified_at
|
||||
)
|
||||
self._modified_at = modified_at if modified_at is not None else self._modified_at
|
||||
|
||||
@property
|
||||
def user_id(self) -> int:
|
||||
|
@ -24,9 +24,7 @@ class UserJoinedServer(TableABC):
|
||||
|
||||
TableABC.__init__(self)
|
||||
self._created_at = created_at if created_at is not None else self._created_at
|
||||
self._modified_at = (
|
||||
modified_at if modified_at is not None else self._modified_at
|
||||
)
|
||||
self._modified_at = modified_at if modified_at is not None else self._modified_at
|
||||
|
||||
@property
|
||||
def join_id(self) -> int:
|
||||
|
@ -24,9 +24,7 @@ class UserJoinedVoiceChannel(TableABC):
|
||||
|
||||
TableABC.__init__(self)
|
||||
self._created_at = created_at if created_at is not None else self._created_at
|
||||
self._modified_at = (
|
||||
modified_at if modified_at is not None else self._modified_at
|
||||
)
|
||||
self._modified_at = modified_at if modified_at is not None else self._modified_at
|
||||
|
||||
@property
|
||||
def join_id(self) -> int:
|
||||
|
@ -24,9 +24,7 @@ class UserMessageCountPerHour(TableABC):
|
||||
|
||||
TableABC.__init__(self)
|
||||
self._created_at = created_at if created_at is not None else self._created_at
|
||||
self._modified_at = (
|
||||
modified_at if modified_at is not None else self._modified_at
|
||||
)
|
||||
self._modified_at = modified_at if modified_at is not None else self._modified_at
|
||||
|
||||
@property
|
||||
def id(self) -> int:
|
||||
|
@ -67,9 +67,7 @@ class AuthUserRepositoryService(AuthUserRepositoryABC):
|
||||
|
||||
def get_all_auth_users(self) -> List[AuthUser]:
|
||||
users = List(AuthUser)
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {AuthUser.get_select_all_string()}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {AuthUser.get_select_all_string()}")
|
||||
results = self._context.select(AuthUser.get_select_all_string())
|
||||
for result in results:
|
||||
self._logger.trace(__name__, f"Get auth user with id {result[0]}")
|
||||
@ -77,36 +75,22 @@ class AuthUserRepositoryService(AuthUserRepositoryABC):
|
||||
|
||||
return users
|
||||
|
||||
def get_filtered_auth_users(
|
||||
self, criteria: AuthUserSelectCriteria
|
||||
) -> FilteredResult:
|
||||
def get_filtered_auth_users(self, criteria: AuthUserSelectCriteria) -> FilteredResult:
|
||||
users = self.get_all_auth_users()
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {AuthUser.get_select_all_string()}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {AuthUser.get_select_all_string()}")
|
||||
query = users
|
||||
|
||||
if criteria.first_name is not None and criteria.first_name != "":
|
||||
query = query.where(
|
||||
lambda x: criteria.first_name in x.first_name
|
||||
or x.first_name == criteria.first_name
|
||||
)
|
||||
query = query.where(lambda x: criteria.first_name in x.first_name or x.first_name == criteria.first_name)
|
||||
|
||||
if criteria.last_name is not None and criteria.last_name != "":
|
||||
query = query.where(
|
||||
lambda x: criteria.last_name in x.last_name
|
||||
or x.last_name == criteria.last_name
|
||||
)
|
||||
query = query.where(lambda x: criteria.last_name in x.last_name or x.last_name == criteria.last_name)
|
||||
|
||||
if criteria.email is not None and criteria.email != "":
|
||||
query = query.where(
|
||||
lambda x: criteria.email in x.email or x.email == criteria.email
|
||||
)
|
||||
query = query.where(lambda x: criteria.email in x.email or x.email == criteria.email)
|
||||
|
||||
if criteria.auth_role is not None:
|
||||
query = query.where(
|
||||
lambda x: x.auth_role == AuthRoleEnum(criteria.auth_role)
|
||||
)
|
||||
query = query.where(lambda x: x.auth_role == AuthRoleEnum(criteria.auth_role))
|
||||
|
||||
# sort
|
||||
if (
|
||||
@ -117,9 +101,7 @@ class AuthUserRepositoryService(AuthUserRepositoryABC):
|
||||
):
|
||||
crit_sort_direction = criteria.sort_direction.lower()
|
||||
if crit_sort_direction == "desc" or crit_sort_direction == "descending":
|
||||
query = query.order_by_descending(
|
||||
lambda x: getattr(x, criteria.sort_column)
|
||||
)
|
||||
query = query.order_by_descending(lambda x: getattr(x, criteria.sort_column))
|
||||
else:
|
||||
query = query.order_by(lambda x: getattr(x, criteria.sort_column))
|
||||
|
||||
@ -131,16 +113,12 @@ class AuthUserRepositoryService(AuthUserRepositoryABC):
|
||||
return result
|
||||
|
||||
def get_auth_user_by_email(self, email: str) -> AuthUser:
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {AuthUser.get_select_by_email_string(email)}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {AuthUser.get_select_by_email_string(email)}")
|
||||
result = self._context.select(AuthUser.get_select_by_email_string(email))[0]
|
||||
return self._user_from_result(result)
|
||||
|
||||
def find_auth_user_by_email(self, email: str) -> Optional[AuthUser]:
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {AuthUser.get_select_by_email_string(email)}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {AuthUser.get_select_by_email_string(email)}")
|
||||
result = self._context.select(AuthUser.get_select_by_email_string(email))
|
||||
if result is None or len(result) == 0:
|
||||
return None
|
||||
@ -167,9 +145,7 @@ class AuthUserRepositoryService(AuthUserRepositoryABC):
|
||||
__name__,
|
||||
f"Send SQL command: {AuthUser.get_select_by_forgot_password_id_string(id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
AuthUser.get_select_by_forgot_password_id_string(id)
|
||||
)
|
||||
result = self._context.select(AuthUser.get_select_by_forgot_password_id_string(id))
|
||||
if result is None or len(result) == 0:
|
||||
return None
|
||||
|
||||
|
@ -18,54 +18,34 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC):
|
||||
|
||||
def get_auto_roles(self) -> List[AutoRole]:
|
||||
auto_roles = List(AutoRole)
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {AutoRole.get_select_all_string()}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {AutoRole.get_select_all_string()}")
|
||||
results = self._context.select(AutoRole.get_select_all_string())
|
||||
for result in results:
|
||||
auto_roles.append(
|
||||
AutoRole(
|
||||
result[1], result[2], result[3], result[4], result[5], id=result[0]
|
||||
)
|
||||
)
|
||||
auto_roles.append(AutoRole(result[1], result[2], result[3], result[4], result[5], id=result[0]))
|
||||
|
||||
return auto_roles
|
||||
|
||||
def get_auto_role_by_id(self, id: int) -> AutoRole:
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {AutoRole.get_select_by_id_string(id)}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {AutoRole.get_select_by_id_string(id)}")
|
||||
result = self._context.select(AutoRole.get_select_by_id_string(id))[0]
|
||||
return AutoRole(
|
||||
result[1], result[2], result[3], result[4], result[5], id=result[0]
|
||||
)
|
||||
return AutoRole(result[1], result[2], result[3], result[4], result[5], id=result[0])
|
||||
|
||||
def find_auto_role_by_id(self, id: int) -> Optional[AutoRole]:
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {AutoRole.get_select_by_id_string(id)}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {AutoRole.get_select_by_id_string(id)}")
|
||||
result = self._context.select(AutoRole.get_select_by_id_string(id))
|
||||
if result is None or len(result) == 0:
|
||||
return None
|
||||
|
||||
result = result[0]
|
||||
|
||||
return AutoRole(
|
||||
result[1], result[2], result[3], result[4], result[5], id=result[0]
|
||||
)
|
||||
return AutoRole(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]:
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {AutoRole.get_select_by_server_id_string(id)}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {AutoRole.get_select_by_server_id_string(id)}")
|
||||
auto_roles = List(AutoRole)
|
||||
results = self._context.select(AutoRole.get_select_by_server_id_string(id))
|
||||
for result in results:
|
||||
auto_roles.append(
|
||||
AutoRole(
|
||||
result[1], result[2], result[3], result[4], result[5], id=result[0]
|
||||
)
|
||||
)
|
||||
auto_roles.append(AutoRole(result[1], result[2], result[3], result[4], result[5], id=result[0]))
|
||||
|
||||
return auto_roles
|
||||
|
||||
@ -75,9 +55,7 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC):
|
||||
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]
|
||||
return AutoRole(
|
||||
result[1], result[2], result[3], result[4], result[5], id=result[0]
|
||||
)
|
||||
return AutoRole(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]:
|
||||
self._logger.trace(
|
||||
@ -90,9 +68,7 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC):
|
||||
|
||||
result = result[0]
|
||||
|
||||
return AutoRole(
|
||||
result[1], result[2], result[3], result[4], result[5], id=result[0]
|
||||
)
|
||||
return AutoRole(result[1], result[2], result[3], result[4], result[5], id=result[0])
|
||||
|
||||
def add_auto_role(self, auto_role: AutoRole):
|
||||
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]:
|
||||
auto_role_rules = List(AutoRoleRule)
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {AutoRoleRule.get_select_all_string()}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {AutoRoleRule.get_select_all_string()}")
|
||||
results = self._context.select(AutoRoleRule.get_select_all_string())
|
||||
for result in results:
|
||||
auto_role_rules.append(
|
||||
AutoRoleRule(
|
||||
result[1], result[2], result[3], result[4], result[5], id=result[0]
|
||||
)
|
||||
)
|
||||
auto_role_rules.append(AutoRoleRule(result[1], result[2], result[3], result[4], result[5], id=result[0]))
|
||||
|
||||
return auto_role_rules
|
||||
|
||||
def get_auto_role_rule_by_id(self, id: int) -> AutoRoleRule:
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {AutoRoleRule.get_select_by_id_string(id)}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {AutoRoleRule.get_select_by_id_string(id)}")
|
||||
result = self._context.select(AutoRoleRule.get_select_by_id_string(id))[0]
|
||||
return AutoRoleRule(
|
||||
result[1], result[2], result[3], result[4], result[5], id=result[0]
|
||||
)
|
||||
return AutoRoleRule(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]:
|
||||
auto_role_rules = List(AutoRoleRule)
|
||||
@ -136,32 +102,20 @@ class AutoRoleRepositoryService(AutoRoleRepositoryABC):
|
||||
__name__,
|
||||
f"Send SQL command: {AutoRoleRule.get_select_by_auto_role_id_string(id)}",
|
||||
)
|
||||
results = self._context.select(
|
||||
AutoRoleRule.get_select_by_auto_role_id_string(id)
|
||||
)
|
||||
results = self._context.select(AutoRoleRule.get_select_by_auto_role_id_string(id))
|
||||
for result in results:
|
||||
auto_role_rules.append(
|
||||
AutoRoleRule(
|
||||
result[1], result[2], result[3], result[4], result[5], id=result[0]
|
||||
)
|
||||
)
|
||||
auto_role_rules.append(AutoRoleRule(result[1], result[2], result[3], result[4], result[5], id=result[0]))
|
||||
|
||||
return auto_role_rules
|
||||
|
||||
def add_auto_role_rule(self, auto_role_rule: AutoRoleRule):
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {auto_role_rule.insert_string}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {auto_role_rule.insert_string}")
|
||||
self._context.cursor.execute(auto_role_rule.insert_string)
|
||||
|
||||
def update_auto_role_rule(self, auto_role_rule: AutoRoleRule):
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {auto_role_rule.udpate_string}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {auto_role_rule.udpate_string}")
|
||||
self._context.cursor.execute(auto_role_rule.udpate_string)
|
||||
|
||||
def delete_auto_role_rule(self, auto_role_rule: AutoRoleRule):
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {auto_role_rule.delete_string}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {auto_role_rule.delete_string}")
|
||||
self._context.cursor.execute(auto_role_rule.delete_string)
|
||||
|
@ -25,9 +25,7 @@ class ClientRepositoryService(ClientRepositoryABC):
|
||||
|
||||
def get_clients(self) -> List[Client]:
|
||||
clients = List(Client)
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {Client.get_select_all_string()}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {Client.get_select_all_string()}")
|
||||
results = self._context.select(Client.get_select_all_string())
|
||||
for result in results:
|
||||
self._logger.trace(__name__, f"Get client with id {result[0]}")
|
||||
@ -47,9 +45,7 @@ class ClientRepositoryService(ClientRepositoryABC):
|
||||
return clients
|
||||
|
||||
def get_client_by_id(self, client_id: int) -> Client:
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {Client.get_select_by_id_string(client_id)}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {Client.get_select_by_id_string(client_id)}")
|
||||
result = self._context.select(Client.get_select_by_id_string(client_id))
|
||||
return Client(
|
||||
result[1],
|
||||
@ -67,9 +63,7 @@ class ClientRepositoryService(ClientRepositoryABC):
|
||||
__name__,
|
||||
f"Send SQL command: {Client.get_select_by_discord_id_string(discord_id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
Client.get_select_by_discord_id_string(discord_id)
|
||||
)[0]
|
||||
result = self._context.select(Client.get_select_by_discord_id_string(discord_id))[0]
|
||||
return Client(
|
||||
result[1],
|
||||
result[2],
|
||||
@ -86,9 +80,7 @@ class ClientRepositoryService(ClientRepositoryABC):
|
||||
__name__,
|
||||
f"Send SQL command: {Client.get_select_by_discord_id_string(discord_id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
Client.get_select_by_discord_id_string(discord_id)
|
||||
)
|
||||
result = self._context.select(Client.get_select_by_discord_id_string(discord_id))
|
||||
if result is None or len(result) == 0:
|
||||
return None
|
||||
|
||||
@ -127,16 +119,12 @@ class ClientRepositoryService(ClientRepositoryABC):
|
||||
id=result[0],
|
||||
)
|
||||
|
||||
def find_client_by_discord_id_and_server_id(
|
||||
self, discord_id: int, server_id: int
|
||||
) -> Optional[Client]:
|
||||
def find_client_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> Optional[Client]:
|
||||
self._logger.trace(
|
||||
__name__,
|
||||
f"Send SQL command: {Client.get_select_by_discord_id_and_server_id_string(discord_id, server_id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
Client.get_select_by_discord_id_and_server_id_string(discord_id, server_id)
|
||||
)
|
||||
result = self._context.select(Client.get_select_by_discord_id_and_server_id_string(discord_id, server_id))
|
||||
if result is None or len(result) == 0:
|
||||
return None
|
||||
|
||||
@ -173,9 +161,7 @@ class ClientRepositoryService(ClientRepositoryABC):
|
||||
|
||||
client = self.find_client_by_discord_id_and_server_id(id, server.server_id)
|
||||
if client is None:
|
||||
self._logger.warn(
|
||||
__name__, f"Cannot find client by ids {id}@{server.server_id}"
|
||||
)
|
||||
self._logger.warn(__name__, f"Cannot find client by ids {id}@{server.server_id}")
|
||||
raise Exception("Value not found")
|
||||
|
||||
return client
|
||||
|
@ -25,9 +25,7 @@ class KnownUserRepositoryService(KnownUserRepositoryABC):
|
||||
|
||||
def get_users(self) -> List[KnownUser]:
|
||||
users = List(KnownUser)
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {KnownUser.get_select_all_string()}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {KnownUser.get_select_all_string()}")
|
||||
results = self._context.select(KnownUser.get_select_all_string())
|
||||
for result in results:
|
||||
self._logger.trace(__name__, f"Get known_user with id {result[0]}")
|
||||
@ -36,9 +34,7 @@ class KnownUserRepositoryService(KnownUserRepositoryABC):
|
||||
return users
|
||||
|
||||
def get_user_by_id(self, id: int) -> KnownUser:
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {KnownUser.get_select_by_id_string(id)}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {KnownUser.get_select_by_id_string(id)}")
|
||||
result = self._context.select(KnownUser.get_select_by_id_string(id))
|
||||
return KnownUser(result[1], result[2], result[3], id=result[0])
|
||||
|
||||
@ -47,9 +43,7 @@ class KnownUserRepositoryService(KnownUserRepositoryABC):
|
||||
__name__,
|
||||
f"Send SQL command: {KnownUser.get_select_by_discord_id_string(discord_id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
KnownUser.get_select_by_discord_id_string(discord_id)
|
||||
)[0]
|
||||
result = self._context.select(KnownUser.get_select_by_discord_id_string(discord_id))[0]
|
||||
return KnownUser(result[1], result[2], result[3], id=result[0])
|
||||
|
||||
def find_user_by_discord_id(self, discord_id: int) -> Optional[KnownUser]:
|
||||
@ -57,9 +51,7 @@ class KnownUserRepositoryService(KnownUserRepositoryABC):
|
||||
__name__,
|
||||
f"Send SQL command: {KnownUser.get_select_by_discord_id_string(discord_id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
KnownUser.get_select_by_discord_id_string(discord_id)
|
||||
)
|
||||
result = self._context.select(KnownUser.get_select_by_discord_id_string(discord_id))
|
||||
if result is None or len(result) == 0:
|
||||
return None
|
||||
|
||||
|
@ -42,9 +42,7 @@ class LevelRepositoryService(LevelRepositoryABC):
|
||||
|
||||
def get_levels(self) -> List[Level]:
|
||||
levels = List(Level)
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {Level.get_select_all_string()}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {Level.get_select_all_string()}")
|
||||
results = self._context.select(Level.get_select_all_string())
|
||||
for result in results:
|
||||
self._logger.trace(__name__, f"Get level with id {result[0]}")
|
||||
@ -53,17 +51,13 @@ class LevelRepositoryService(LevelRepositoryABC):
|
||||
return levels
|
||||
|
||||
def get_level_by_id(self, id: int) -> Level:
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {Level.get_select_by_id_string(id)}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {Level.get_select_by_id_string(id)}")
|
||||
result = self._context.select(Level.get_select_by_id_string(id))[0]
|
||||
|
||||
return self._level_from_result(result)
|
||||
|
||||
def find_level_by_id(self, id: int) -> Optional[Level]:
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {Level.get_select_by_id_string(id)}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {Level.get_select_by_id_string(id)}")
|
||||
result = self._context.select(Level.get_select_by_id_string(id))
|
||||
if result is None or len(result) == 0:
|
||||
return None
|
||||
|
@ -22,9 +22,7 @@ class MigrationService:
|
||||
self._db = db
|
||||
self._cursor = db.cursor
|
||||
|
||||
self._migrations = List(type, MigrationABC.__subclasses__()).order_by(
|
||||
lambda x: x.name
|
||||
)
|
||||
self._migrations = List(type, MigrationABC.__subclasses__()).order_by(lambda x: x.name)
|
||||
|
||||
def migrate(self):
|
||||
self._logger.info(__name__, f"Running Migrations")
|
||||
@ -40,21 +38,15 @@ class MigrationService:
|
||||
__name__,
|
||||
f"Running SQL Command: {MigrationHistory.get_select_by_id_string(migration_id)}",
|
||||
)
|
||||
migration_from_db = self._db.select(
|
||||
MigrationHistory.get_select_by_id_string(migration_id)
|
||||
)
|
||||
migration_from_db = self._db.select(MigrationHistory.get_select_by_id_string(migration_id))
|
||||
if migration_from_db is not None and len(migration_from_db) > 0:
|
||||
continue
|
||||
|
||||
self._logger.debug(__name__, f"Running Migration {migration_id}")
|
||||
migration_as_service: MigrationABC = self._services.get_service(
|
||||
migration
|
||||
)
|
||||
migration_as_service: MigrationABC = self._services.get_service(migration)
|
||||
migration_as_service.upgrade()
|
||||
self._cursor.execute(MigrationHistory(migration_id).insert_string)
|
||||
self._db.save_changes()
|
||||
|
||||
except Exception as e:
|
||||
self._logger.error(
|
||||
__name__, f"Cannot get migration with id {migration}", e
|
||||
)
|
||||
self._logger.error(__name__, f"Cannot get migration with id {migration}", e)
|
||||
|
@ -19,9 +19,7 @@ class ServerRepositoryService(ServerRepositoryABC):
|
||||
|
||||
def get_servers(self) -> List[Server]:
|
||||
servers = List(Server)
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {Server.get_select_all_string()}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {Server.get_select_all_string()}")
|
||||
results = self._context.select(Server.get_select_all_string())
|
||||
for result in results:
|
||||
servers.append(Server(result[1], id=result[0]))
|
||||
@ -30,9 +28,7 @@ class ServerRepositoryService(ServerRepositoryABC):
|
||||
|
||||
def get_filtered_servers(self, criteria: ServerSelectCriteria) -> FilteredResult:
|
||||
servers = self.get_servers()
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {Server.get_select_all_string()}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {Server.get_select_all_string()}")
|
||||
query = servers
|
||||
|
||||
# sort
|
||||
@ -44,9 +40,7 @@ class ServerRepositoryService(ServerRepositoryABC):
|
||||
):
|
||||
crit_sort_direction = criteria.sort_direction.lower()
|
||||
if crit_sort_direction == "desc" or crit_sort_direction == "descending":
|
||||
query = query.order_by_descending(
|
||||
lambda x: getattr(x, criteria.sort_column)
|
||||
)
|
||||
query = query.order_by_descending(lambda x: getattr(x, criteria.sort_column))
|
||||
else:
|
||||
query = query.order_by(lambda x: getattr(x, criteria.sort_column))
|
||||
|
||||
@ -58,9 +52,7 @@ class ServerRepositoryService(ServerRepositoryABC):
|
||||
return result
|
||||
|
||||
def get_server_by_id(self, server_id: int) -> Server:
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {Server.get_select_by_id_string(server_id)}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {Server.get_select_by_id_string(server_id)}")
|
||||
result = self._context.select(Server.get_select_by_id_string(server_id))[0]
|
||||
return Server(result[1], id=result[0])
|
||||
|
||||
@ -69,9 +61,7 @@ class ServerRepositoryService(ServerRepositoryABC):
|
||||
__name__,
|
||||
f"Send SQL command: {Server.get_select_by_discord_id_string(discord_id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
Server.get_select_by_discord_id_string(discord_id)
|
||||
)[0]
|
||||
result = self._context.select(Server.get_select_by_discord_id_string(discord_id))[0]
|
||||
return Server(result[1], id=result[0])
|
||||
|
||||
def find_server_by_discord_id(self, discord_id: int) -> Optional[Server]:
|
||||
@ -79,9 +69,7 @@ class ServerRepositoryService(ServerRepositoryABC):
|
||||
__name__,
|
||||
f"Send SQL command: {Server.get_select_by_discord_id_string(discord_id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
Server.get_select_by_discord_id_string(discord_id)
|
||||
)
|
||||
result = self._context.select(Server.get_select_by_discord_id_string(discord_id))
|
||||
if result is None or len(result) == 0:
|
||||
return None
|
||||
|
||||
|
@ -48,9 +48,7 @@ class StatisticRepositoryService(StatisticRepositoryABC):
|
||||
|
||||
def get_statistics(self) -> List[Statistic]:
|
||||
statistics = List(Statistic)
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {Statistic.get_select_all_string()}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {Statistic.get_select_all_string()}")
|
||||
results = self._context.select(Statistic.get_select_all_string())
|
||||
for result in results:
|
||||
statistics.append(self._statistic_from_result(result))
|
||||
@ -70,9 +68,7 @@ class StatisticRepositoryService(StatisticRepositoryABC):
|
||||
return statistics
|
||||
|
||||
def get_statistic_by_id(self, id: int) -> Statistic:
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {Statistic.get_select_by_id_string(id)}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {Statistic.get_select_by_id_string(id)}")
|
||||
result = self._context.select(Statistic.get_select_by_id_string(id))[0]
|
||||
return self._statistic_from_result(result)
|
||||
|
||||
@ -81,9 +77,7 @@ class StatisticRepositoryService(StatisticRepositoryABC):
|
||||
__name__,
|
||||
f"Send SQL command: {Statistic.get_select_by_name_string(name, server_id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
Statistic.get_select_by_name_string(name, server_id)
|
||||
)[0]
|
||||
result = self._context.select(Statistic.get_select_by_name_string(name, server_id))[0]
|
||||
return self._statistic_from_result(result)
|
||||
|
||||
def find_statistic_by_name(self, name: str, server_id: int) -> Optional[Statistic]:
|
||||
@ -91,9 +85,7 @@ class StatisticRepositoryService(StatisticRepositoryABC):
|
||||
__name__,
|
||||
f"Send SQL command: {Statistic.get_select_by_name_string(name, server_id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
Statistic.get_select_by_name_string(name, server_id)
|
||||
)
|
||||
result = self._context.select(Statistic.get_select_by_name_string(name, server_id))
|
||||
if result is None or len(result) == 0:
|
||||
return None
|
||||
|
||||
|
@ -25,9 +25,7 @@ class UserJoinedServerRepositoryService(UserJoinedServerRepositoryABC):
|
||||
|
||||
def get_user_joined_servers(self) -> List[UserJoinedServer]:
|
||||
joins = List(UserJoinedServer)
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {UserJoinedServer.get_select_all_string()}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {UserJoinedServer.get_select_all_string()}")
|
||||
results = self._context.select(UserJoinedServer.get_select_all_string())
|
||||
for result in results:
|
||||
self._logger.trace(__name__, f"Get user-joined-server with id {result[0]}")
|
||||
@ -59,17 +57,13 @@ class UserJoinedServerRepositoryService(UserJoinedServerRepositoryABC):
|
||||
id=result[0],
|
||||
)
|
||||
|
||||
def get_user_joined_servers_by_user_id(
|
||||
self, user_id: int
|
||||
) -> List[UserJoinedServer]:
|
||||
def get_user_joined_servers_by_user_id(self, user_id: int) -> List[UserJoinedServer]:
|
||||
joins = List(UserJoinedServer)
|
||||
self._logger.trace(
|
||||
__name__,
|
||||
f"Send SQL command: {UserJoinedServer.get_select_by_user_id_string(user_id)}",
|
||||
)
|
||||
results = self._context.select(
|
||||
UserJoinedServer.get_select_by_user_id_string(user_id)
|
||||
)
|
||||
results = self._context.select(UserJoinedServer.get_select_by_user_id_string(user_id))
|
||||
for result in results:
|
||||
joins.append(
|
||||
UserJoinedServer(
|
||||
@ -84,16 +78,12 @@ class UserJoinedServerRepositoryService(UserJoinedServerRepositoryABC):
|
||||
|
||||
return joins
|
||||
|
||||
def get_active_user_joined_server_by_user_id(
|
||||
self, user_id: int
|
||||
) -> UserJoinedServer:
|
||||
def get_active_user_joined_server_by_user_id(self, user_id: int) -> UserJoinedServer:
|
||||
self._logger.trace(
|
||||
__name__,
|
||||
f"Send SQL command: {UserJoinedServer.get_select_by_user_id_string(user_id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
UserJoinedServer.get_select_active_by_user_id_string(user_id)
|
||||
)[0]
|
||||
result = self._context.select(UserJoinedServer.get_select_active_by_user_id_string(user_id))[0]
|
||||
return UserJoinedServer(
|
||||
self._users.get_user_by_id(result[1]),
|
||||
result[2],
|
||||
@ -103,16 +93,12 @@ class UserJoinedServerRepositoryService(UserJoinedServerRepositoryABC):
|
||||
id=result[0],
|
||||
)
|
||||
|
||||
def find_active_user_joined_server_by_user_id(
|
||||
self, user_id: int
|
||||
) -> Optional[UserJoinedServer]:
|
||||
def find_active_user_joined_server_by_user_id(self, user_id: int) -> Optional[UserJoinedServer]:
|
||||
self._logger.trace(
|
||||
__name__,
|
||||
f"Send SQL command: {UserJoinedServer.get_select_by_user_id_string(user_id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
UserJoinedServer.get_select_active_by_user_id_string(user_id)
|
||||
)
|
||||
result = self._context.select(UserJoinedServer.get_select_active_by_user_id_string(user_id))
|
||||
if result is None or len(result) == 0:
|
||||
return None
|
||||
|
||||
@ -128,19 +114,13 @@ class UserJoinedServerRepositoryService(UserJoinedServerRepositoryABC):
|
||||
)
|
||||
|
||||
def add_user_joined_server(self, user_joined_server: UserJoinedServer):
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {user_joined_server.insert_string}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {user_joined_server.insert_string}")
|
||||
self._context.cursor.execute(user_joined_server.insert_string)
|
||||
|
||||
def update_user_joined_server(self, user_joined_server: UserJoinedServer):
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {user_joined_server.udpate_string}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {user_joined_server.udpate_string}")
|
||||
self._context.cursor.execute(user_joined_server.udpate_string)
|
||||
|
||||
def delete_user_joined_server(self, user_joined_server: UserJoinedServer):
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {user_joined_server.delete_string}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {user_joined_server.delete_string}")
|
||||
self._context.cursor.execute(user_joined_server.delete_string)
|
||||
|
@ -33,9 +33,7 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
|
||||
)
|
||||
results = self._context.select(UserJoinedVoiceChannel.get_select_all_string())
|
||||
for result in results:
|
||||
self._logger.trace(
|
||||
__name__, f"Get user-joined-voice-channel with id {result[0]}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Get user-joined-voice-channel with id {result[0]}")
|
||||
joins.append(
|
||||
UserJoinedVoiceChannel(
|
||||
self._users.get_user_by_id(result[1]),
|
||||
@ -54,9 +52,7 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
|
||||
__name__,
|
||||
f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_id_string(id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
UserJoinedVoiceChannel.get_select_by_id_string(id)
|
||||
)[0]
|
||||
result = self._context.select(UserJoinedVoiceChannel.get_select_by_id_string(id))[0]
|
||||
return UserJoinedVoiceChannel(
|
||||
self._users.get_user_by_id(result[1]),
|
||||
result[2],
|
||||
@ -66,17 +62,13 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
|
||||
id=result[0],
|
||||
)
|
||||
|
||||
def get_user_joined_voice_channels_by_user_id(
|
||||
self, user_id: int
|
||||
) -> List[UserJoinedVoiceChannel]:
|
||||
def get_user_joined_voice_channels_by_user_id(self, user_id: int) -> List[UserJoinedVoiceChannel]:
|
||||
joins = List(UserJoinedVoiceChannel)
|
||||
self._logger.trace(
|
||||
__name__,
|
||||
f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_user_id_string(user_id)}",
|
||||
)
|
||||
results = self._context.select(
|
||||
UserJoinedVoiceChannel.get_select_by_user_id_string(user_id)
|
||||
)
|
||||
results = self._context.select(UserJoinedVoiceChannel.get_select_by_user_id_string(user_id))
|
||||
for result in results:
|
||||
joins.append(
|
||||
UserJoinedVoiceChannel(
|
||||
@ -91,16 +83,12 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
|
||||
|
||||
return joins
|
||||
|
||||
def get_active_user_joined_voice_channel_by_user_id(
|
||||
self, user_id: int
|
||||
) -> UserJoinedVoiceChannel:
|
||||
def get_active_user_joined_voice_channel_by_user_id(self, user_id: int) -> UserJoinedVoiceChannel:
|
||||
self._logger.trace(
|
||||
__name__,
|
||||
f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_user_id_string(user_id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id)
|
||||
)[0]
|
||||
result = self._context.select(UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id))[0]
|
||||
return UserJoinedVoiceChannel(
|
||||
self._users.get_user_by_id(result[1]),
|
||||
result[2],
|
||||
@ -110,16 +98,12 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
|
||||
id=result[0],
|
||||
)
|
||||
|
||||
def find_active_user_joined_voice_channel_by_user_id(
|
||||
self, user_id: int
|
||||
) -> Optional[UserJoinedVoiceChannel]:
|
||||
def find_active_user_joined_voice_channel_by_user_id(self, user_id: int) -> Optional[UserJoinedVoiceChannel]:
|
||||
self._logger.trace(
|
||||
__name__,
|
||||
f"Send SQL command: {UserJoinedVoiceChannel.get_select_by_user_id_string(user_id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id)
|
||||
)
|
||||
result = self._context.select(UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id))
|
||||
if result is None or len(result) == 0:
|
||||
return None
|
||||
|
||||
@ -134,17 +118,13 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
|
||||
id=result[0],
|
||||
)
|
||||
|
||||
def find_active_user_joined_voice_channels_by_user_id(
|
||||
self, user_id: int
|
||||
) -> List[Optional[UserJoinedVoiceChannel]]:
|
||||
def find_active_user_joined_voice_channels_by_user_id(self, user_id: int) -> List[Optional[UserJoinedVoiceChannel]]:
|
||||
self._logger.trace(
|
||||
__name__,
|
||||
f"Send SQL command: {UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id)}",
|
||||
)
|
||||
result = List(UserJoinedVoiceChannel)
|
||||
db_results = self._context.select(
|
||||
UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id)
|
||||
)
|
||||
db_results = self._context.select(UserJoinedVoiceChannel.get_select_active_by_user_id_string(user_id))
|
||||
|
||||
for db_result in db_results:
|
||||
result.append(
|
||||
@ -160,28 +140,16 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
|
||||
|
||||
return result
|
||||
|
||||
def add_user_joined_voice_channel(
|
||||
self, user_joined_voice_channel: UserJoinedVoiceChannel
|
||||
):
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {user_joined_voice_channel.insert_string}"
|
||||
)
|
||||
def add_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel):
|
||||
self._logger.trace(__name__, f"Send SQL command: {user_joined_voice_channel.insert_string}")
|
||||
self._context.cursor.execute(user_joined_voice_channel.insert_string)
|
||||
|
||||
def update_user_joined_voice_channel(
|
||||
self, user_joined_voice_channel: UserJoinedVoiceChannel
|
||||
):
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {user_joined_voice_channel.udpate_string}"
|
||||
)
|
||||
def update_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel):
|
||||
self._logger.trace(__name__, f"Send SQL command: {user_joined_voice_channel.udpate_string}")
|
||||
self._context.cursor.execute(user_joined_voice_channel.udpate_string)
|
||||
|
||||
def delete_user_joined_voice_channel(
|
||||
self, user_joined_voice_channel: UserJoinedVoiceChannel
|
||||
):
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {user_joined_voice_channel.delete_string}"
|
||||
)
|
||||
def delete_user_joined_voice_channel(self, user_joined_voice_channel: UserJoinedVoiceChannel):
|
||||
self._logger.trace(__name__, f"Send SQL command: {user_joined_voice_channel.delete_string}")
|
||||
self._context.cursor.execute(user_joined_voice_channel.delete_string)
|
||||
|
||||
def delete_user_joined_voice_channel_by_user_id(self, user_id: int):
|
||||
@ -189,6 +157,4 @@ class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryAB
|
||||
__name__,
|
||||
f"Send SQL command: {UserJoinedVoiceChannel.delete_by_user_id_string}",
|
||||
)
|
||||
self._context.cursor.execute(
|
||||
UserJoinedVoiceChannel.delete_by_user_id_string(user_id)
|
||||
)
|
||||
self._context.cursor.execute(UserJoinedVoiceChannel.delete_by_user_id_string(user_id))
|
||||
|
@ -51,16 +51,12 @@ class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepository
|
||||
)
|
||||
results = self._context.select(UserMessageCountPerHour.get_select_all_string())
|
||||
for result in results:
|
||||
self._logger.trace(
|
||||
__name__, f"Get user message count per hour with id {result[0]}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Get user message count per hour with id {result[0]}")
|
||||
umcphs.append(self._from_result(result))
|
||||
|
||||
return umcphs
|
||||
|
||||
def find_user_message_count_per_hour_by_user_id(
|
||||
self, user_id: int
|
||||
) -> List[Optional[UserMessageCountPerHour]]:
|
||||
def find_user_message_count_per_hour_by_user_id(self, user_id: int) -> List[Optional[UserMessageCountPerHour]]:
|
||||
umcphs = List(UserMessageCountPerHour)
|
||||
sql = UserMessageCountPerHour.get_select_by_user_id_string(user_id)
|
||||
self._logger.trace(__name__, f"Send SQL command: {sql}")
|
||||
@ -69,9 +65,7 @@ class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepository
|
||||
return umcphs
|
||||
|
||||
for result in results:
|
||||
self._logger.trace(
|
||||
__name__, f"Get user message count per hour with id {result[0]}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Get user message count per hour with id {result[0]}")
|
||||
umcphs.append(self._from_result(result))
|
||||
|
||||
return umcphs
|
||||
@ -79,9 +73,7 @@ class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepository
|
||||
def get_user_message_count_per_hour_by_user_id_and_date(
|
||||
self, user_id: int, date: datetime
|
||||
) -> UserMessageCountPerHour:
|
||||
sql = UserMessageCountPerHour.get_select_by_user_id_and_date_string(
|
||||
user_id, date
|
||||
)
|
||||
sql = UserMessageCountPerHour.get_select_by_user_id_and_date_string(user_id, date)
|
||||
self._logger.trace(__name__, f"Send SQL command: {sql}")
|
||||
result = self._context.select(sql)[0]
|
||||
return self._from_result(result)
|
||||
@ -89,9 +81,7 @@ class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepository
|
||||
def find_user_message_count_per_hour_by_user_id_and_date(
|
||||
self, user_id: int, date: datetime
|
||||
) -> Optional[UserMessageCountPerHour]:
|
||||
sql = UserMessageCountPerHour.get_select_by_user_id_and_date_string(
|
||||
user_id, date
|
||||
)
|
||||
sql = UserMessageCountPerHour.get_select_by_user_id_and_date_string(user_id, date)
|
||||
self._logger.trace(__name__, f"Send SQL command: {sql}")
|
||||
result = self._context.select(sql)
|
||||
if result is None or len(result) == 0:
|
||||
|
@ -25,9 +25,7 @@ class UserRepositoryService(UserRepositoryABC):
|
||||
|
||||
def get_users(self) -> List[User]:
|
||||
users = List(User)
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {User.get_select_all_string()}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {User.get_select_all_string()}")
|
||||
results = self._context.select(User.get_select_all_string())
|
||||
for result in results:
|
||||
self._logger.trace(__name__, f"Get user with id {result[0]}")
|
||||
@ -43,9 +41,7 @@ class UserRepositoryService(UserRepositoryABC):
|
||||
return users
|
||||
|
||||
def get_user_by_id(self, id: int) -> User:
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {User.get_select_by_id_string(id)}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {User.get_select_by_id_string(id)}")
|
||||
result = self._context.select(User.get_select_by_id_string(id))[0]
|
||||
|
||||
return User(
|
||||
@ -56,9 +52,7 @@ class UserRepositoryService(UserRepositoryABC):
|
||||
)
|
||||
|
||||
def find_user_by_id(self, id: int) -> Optional[User]:
|
||||
self._logger.trace(
|
||||
__name__, f"Send SQL command: {User.get_select_by_id_string(id)}"
|
||||
)
|
||||
self._logger.trace(__name__, f"Send SQL command: {User.get_select_by_id_string(id)}")
|
||||
result = self._context.select(User.get_select_by_id_string(id))
|
||||
if result is None or len(result) == 0:
|
||||
return None
|
||||
@ -91,16 +85,12 @@ class UserRepositoryService(UserRepositoryABC):
|
||||
|
||||
return users
|
||||
|
||||
def get_user_by_discord_id_and_server_id(
|
||||
self, discord_id: int, server_id: int
|
||||
) -> User:
|
||||
def get_user_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> User:
|
||||
self._logger.trace(
|
||||
__name__,
|
||||
f"Send SQL command: {User.get_select_by_discord_id_and_server_id_string(discord_id, server_id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
User.get_select_by_discord_id_and_server_id_string(discord_id, server_id)
|
||||
)[0]
|
||||
result = self._context.select(User.get_select_by_discord_id_and_server_id_string(discord_id, server_id))[0]
|
||||
|
||||
return User(
|
||||
result[1],
|
||||
@ -109,16 +99,12 @@ class UserRepositoryService(UserRepositoryABC):
|
||||
id=result[0],
|
||||
)
|
||||
|
||||
def find_user_by_discord_id_and_server_id(
|
||||
self, discord_id: int, server_id: int
|
||||
) -> Optional[User]:
|
||||
def find_user_by_discord_id_and_server_id(self, discord_id: int, server_id: int) -> Optional[User]:
|
||||
self._logger.trace(
|
||||
__name__,
|
||||
f"Send SQL command: {User.get_select_by_discord_id_and_server_id_string(discord_id, server_id)}",
|
||||
)
|
||||
result = self._context.select(
|
||||
User.get_select_by_discord_id_and_server_id_string(discord_id, server_id)
|
||||
)
|
||||
result = self._context.select(User.get_select_by_discord_id_and_server_id_string(discord_id, server_id))
|
||||
if result is None or len(result) == 0:
|
||||
return None
|
||||
|
||||
|
@ -20,14 +20,10 @@ class AutoRoleModule(ModuleABC):
|
||||
def __init__(self, dc: DiscordCollectionABC):
|
||||
ModuleABC.__init__(self, dc, FeatureFlagsEnum.auto_role_module)
|
||||
|
||||
def configure_configuration(
|
||||
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
|
||||
pass
|
||||
|
||||
def configure_services(
|
||||
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
|
||||
services.add_transient(AutoRoleReactionHandler)
|
||||
# commands
|
||||
self._dc.add_command(AutoRoleGroup)
|
||||
|
@ -53,14 +53,10 @@ class AutoRoleGroup(DiscordCommandABC):
|
||||
self, interaction: discord.Interaction, current: str
|
||||
) -> TList[app_commands.Choice[str]]:
|
||||
server = self._servers.get_server_by_discord_id(interaction.guild.id)
|
||||
auto_roles = self._auto_roles.get_auto_roles_by_server_id(
|
||||
server.server_id
|
||||
).select(lambda x: x.auto_role_id)
|
||||
auto_roles = self._auto_roles.get_auto_roles_by_server_id(server.server_id).select(lambda x: x.auto_role_id)
|
||||
return [
|
||||
app_commands.Choice(name=auto_role, value=auto_role)
|
||||
for auto_role in self._client_utils.get_auto_complete_list(
|
||||
auto_roles, current
|
||||
)
|
||||
for auto_role in self._client_utils.get_auto_complete_list(auto_roles, current)
|
||||
]
|
||||
|
||||
@commands.hybrid_group(name="auto-role")
|
||||
@ -86,9 +82,7 @@ class AutoRoleGroup(DiscordCommandABC):
|
||||
server = self._servers.get_server_by_discord_id(ctx.guild.id)
|
||||
auto_roles = self._auto_roles.get_auto_roles_by_server_id(server.server_id)
|
||||
if auto_roles.count() < 1:
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx, self._t.transform("modules.auto_role.error.nothing_found")
|
||||
)
|
||||
await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.auto_role.error.nothing_found"))
|
||||
self._logger.trace(__name__, f"Finished command auto-role list")
|
||||
return
|
||||
|
||||
@ -116,9 +110,7 @@ class AutoRoleGroup(DiscordCommandABC):
|
||||
@CommandChecks.check_is_ready()
|
||||
@CommandChecks.check_is_member_moderator()
|
||||
async def add(self, ctx: Context, channel: discord.TextChannel, message_id: str):
|
||||
self._logger.debug(
|
||||
__name__, f"Received command auto-role add {ctx} {message_id}"
|
||||
)
|
||||
self._logger.debug(__name__, f"Received command auto-role add {ctx} {message_id}")
|
||||
|
||||
message = (
|
||||
List(
|
||||
@ -129,56 +121,38 @@ class AutoRoleGroup(DiscordCommandABC):
|
||||
.single_or_default()
|
||||
)
|
||||
if message is None:
|
||||
self._logger.debug(
|
||||
__name__, f"Message with id {message_id} not found in {channel.name}"
|
||||
)
|
||||
self._logger.debug(__name__, f"Message with id {message_id} not found in {channel.name}")
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx,
|
||||
self._t.transform("modules.auto_role.add.error.not_found").format(
|
||||
message_id, channel.mention
|
||||
),
|
||||
self._t.transform("modules.auto_role.add.error.not_found").format(message_id, channel.mention),
|
||||
)
|
||||
self._logger.trace(__name__, f"Finished command auto-role add")
|
||||
return
|
||||
|
||||
if self._auto_roles.find_auto_role_by_message_id(int(message_id)) is not None:
|
||||
self._logger.debug(
|
||||
__name__, f"auto-role for message {message_id} already exists"
|
||||
)
|
||||
self._logger.debug(__name__, f"auto-role for message {message_id} already exists")
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx,
|
||||
self._t.transform("modules.auto_role.add.error.already_exists").format(
|
||||
message_id
|
||||
),
|
||||
self._t.transform("modules.auto_role.add.error.already_exists").format(message_id),
|
||||
)
|
||||
self._logger.trace(__name__, f"Finished command auto-role add")
|
||||
return
|
||||
|
||||
server_id = self._servers.get_server_by_discord_id(ctx.guild.id).server_id
|
||||
self._auto_roles.add_auto_role(
|
||||
AutoRole(server_id, int(channel.id), int(message_id))
|
||||
)
|
||||
self._auto_roles.add_auto_role(AutoRole(server_id, int(channel.id), int(message_id)))
|
||||
self._db_context.save_changes()
|
||||
self._logger.info(
|
||||
__name__, f"Saved auto-role for message {message_id} at server {server_id}"
|
||||
)
|
||||
self._logger.info(__name__, f"Saved auto-role for message {message_id} at server {server_id}")
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx, self._t.transform("modules.auto_role.add.success").format(message_id)
|
||||
)
|
||||
self._logger.trace(__name__, f"Finished command auto-role add")
|
||||
|
||||
@add.autocomplete("message_id")
|
||||
async def add_autocomplete(
|
||||
self, interaction: discord.Interaction, current: str
|
||||
) -> TList[app_commands.Choice[str]]:
|
||||
channel = discord.utils.get(
|
||||
interaction.guild.text_channels, id=interaction.channel_id
|
||||
)
|
||||
async def add_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]:
|
||||
channel = discord.utils.get(interaction.guild.text_channels, id=interaction.channel_id)
|
||||
try:
|
||||
channel_from_data = interaction.data["options"][0]["options"][0]["value"]
|
||||
found_channel = discord.utils.get(
|
||||
interaction.guild.text_channels, id=int(channel_from_data)
|
||||
)
|
||||
found_channel = discord.utils.get(interaction.guild.text_channels, id=int(channel_from_data))
|
||||
if found_channel is not None:
|
||||
channel = found_channel
|
||||
finally:
|
||||
@ -186,9 +160,7 @@ class AutoRoleGroup(DiscordCommandABC):
|
||||
|
||||
messages = [message async for message in channel.history(limit=10)]
|
||||
return [
|
||||
app_commands.Choice(
|
||||
name=f"{message.author}@{message.created_at}", value=str(message.id)
|
||||
)
|
||||
app_commands.Choice(name=f"{message.author}@{message.created_at}", value=str(message.id))
|
||||
for message in messages
|
||||
if current in str(message.id)
|
||||
]
|
||||
@ -198,25 +170,19 @@ class AutoRoleGroup(DiscordCommandABC):
|
||||
@CommandChecks.check_is_ready()
|
||||
@CommandChecks.check_is_member_moderator()
|
||||
async def remove(self, ctx: Context, auto_role: int):
|
||||
self._logger.debug(
|
||||
__name__, f"Received command auto-role remove {ctx} {auto_role}"
|
||||
)
|
||||
self._logger.debug(__name__, f"Received command auto-role remove {ctx} {auto_role}")
|
||||
|
||||
auto_role_from_db = self._auto_roles.find_auto_role_by_id(auto_role)
|
||||
if auto_role_from_db is None:
|
||||
self._logger.debug(__name__, f"auto-role {auto_role} not found")
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx,
|
||||
self._t.transform("modules.auto_role.remove.error.not_found").format(
|
||||
auto_role
|
||||
),
|
||||
self._t.transform("modules.auto_role.remove.error.not_found").format(auto_role),
|
||||
)
|
||||
self._logger.trace(__name__, f"Finished command auto-role remove")
|
||||
return
|
||||
|
||||
for rule in self._auto_roles.get_auto_role_rules_by_auto_role_id(
|
||||
auto_role_from_db.auto_role_id
|
||||
):
|
||||
for rule in self._auto_roles.get_auto_role_rules_by_auto_role_id(auto_role_from_db.auto_role_id):
|
||||
self._auto_roles.delete_auto_role_rule(rule)
|
||||
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_member_moderator()
|
||||
async def add(self, ctx: Context, auto_role: int, emoji_name: str, role_id: str):
|
||||
self._logger.debug(
|
||||
__name__, f"Received command auto-role add {ctx} {auto_role}"
|
||||
)
|
||||
self._logger.debug(__name__, f"Received command auto-role add {ctx} {auto_role}")
|
||||
|
||||
emoji = discord.utils.get(self._bot.emojis, name=emoji_name)
|
||||
if emoji is None:
|
||||
self._logger.debug(
|
||||
__name__, f"auto-role rule add emoji {emoji_name} not found"
|
||||
)
|
||||
self._logger.debug(__name__, f"auto-role rule add emoji {emoji_name} not found")
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx,
|
||||
self._t.transform(
|
||||
"modules.auto_role.rule.add.error.emoji_not_found"
|
||||
).format(emoji_name, auto_role),
|
||||
self._t.transform("modules.auto_role.rule.add.error.emoji_not_found").format(emoji_name, auto_role),
|
||||
)
|
||||
self._logger.trace(__name__, f"Finished command auto-role add")
|
||||
return
|
||||
@ -319,9 +279,7 @@ class AutoRoleGroup(DiscordCommandABC):
|
||||
self._logger.debug(__name__, f"auto-role rule add role {role_id} not found")
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx,
|
||||
self._t.transform(
|
||||
"modules.auto_role.rule.add.error.role_not_found"
|
||||
).format(role_id, auto_role),
|
||||
self._t.transform("modules.auto_role.rule.add.error.role_not_found").format(role_id, auto_role),
|
||||
)
|
||||
self._logger.trace(__name__, f"Finished command auto-role add")
|
||||
return
|
||||
@ -330,9 +288,7 @@ class AutoRoleGroup(DiscordCommandABC):
|
||||
if auto_role_from_db is None:
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx,
|
||||
self._t.transform("modules.auto_role.remove.error.not_found").format(
|
||||
auto_role
|
||||
),
|
||||
self._t.transform("modules.auto_role.remove.error.not_found").format(auto_role),
|
||||
)
|
||||
self._logger.trace(__name__, f"Finished command auto-role rule add")
|
||||
return
|
||||
@ -345,16 +301,12 @@ class AutoRoleGroup(DiscordCommandABC):
|
||||
):
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx,
|
||||
self._t.transform("modules.auto_role.add.error.already_exists").format(
|
||||
auto_role
|
||||
),
|
||||
self._t.transform("modules.auto_role.add.error.already_exists").format(auto_role),
|
||||
)
|
||||
self._logger.trace(__name__, f"Finished command auto-role rule add")
|
||||
return
|
||||
|
||||
self._auto_roles.add_auto_role_rule(
|
||||
AutoRoleRule(auto_role, emoji_name, int(role_id))
|
||||
)
|
||||
self._auto_roles.add_auto_role_rule(AutoRoleRule(auto_role, emoji_name, int(role_id)))
|
||||
self._db_context.save_changes()
|
||||
rule = (
|
||||
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()
|
||||
channel = guild.get_channel(auto_role_from_db.discord_channel_id)
|
||||
message = await channel.fetch_message(auto_role_from_db.discord_message_id)
|
||||
emoji = (
|
||||
List(discord.Emoji, guild.emojis)
|
||||
.where(lambda x: x.name == rule.emoji_name)
|
||||
.single()
|
||||
)
|
||||
emoji = List(discord.Emoji, guild.emojis).where(lambda x: x.name == rule.emoji_name).single()
|
||||
|
||||
if emoji is None:
|
||||
self._logger.debug(__name__, f"Emoji {rule.emoji_name} not found")
|
||||
@ -388,28 +336,20 @@ class AutoRoleGroup(DiscordCommandABC):
|
||||
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx,
|
||||
self._t.transform("modules.auto_role.rule.add.success").format(
|
||||
emoji, role.mention, auto_role
|
||||
),
|
||||
self._t.transform("modules.auto_role.rule.add.success").format(emoji, role.mention, auto_role),
|
||||
)
|
||||
self._logger.trace(__name__, f"Finished command auto-role rule add")
|
||||
|
||||
@add.autocomplete("auto_role")
|
||||
async def add_autocomplete(
|
||||
self, interaction: discord.Interaction, current: str
|
||||
) -> TList[app_commands.Choice[str]]:
|
||||
async def add_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]:
|
||||
return await self._auto_role_auto_complete(interaction, current)
|
||||
|
||||
@add.autocomplete("emoji_name")
|
||||
async def add_autocomplete(
|
||||
self, interaction: discord.Interaction, current: str
|
||||
) -> TList[app_commands.Choice[str]]:
|
||||
async def add_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]:
|
||||
emojis = List(discord.Emoji, interaction.guild.emojis)
|
||||
return [
|
||||
app_commands.Choice(name=emoji.name, value=emoji.name)
|
||||
for emoji in self._client_utils.get_auto_complete_list(
|
||||
emojis, current, lambda e: e.name
|
||||
)
|
||||
for emoji in self._client_utils.get_auto_complete_list(emojis, current, lambda e: e.name)
|
||||
]
|
||||
|
||||
@add.autocomplete("role_id")
|
||||
@ -419,9 +359,7 @@ class AutoRoleGroup(DiscordCommandABC):
|
||||
roles = List(discord.Role, interaction.guild.roles)
|
||||
return [
|
||||
app_commands.Choice(name=role.name, value=str(role.id))
|
||||
for role in self._client_utils.get_auto_complete_list(
|
||||
roles, current, lambda r: r.name
|
||||
)
|
||||
for role in self._client_utils.get_auto_complete_list(roles, current, lambda r: r.name)
|
||||
]
|
||||
|
||||
@rule.command()
|
||||
@ -429,18 +367,14 @@ class AutoRoleGroup(DiscordCommandABC):
|
||||
@CommandChecks.check_is_ready()
|
||||
@CommandChecks.check_is_member_moderator()
|
||||
async def remove(self, ctx: Context, auto_role_rule: int):
|
||||
self._logger.debug(
|
||||
__name__, f"Received command auto-role remove {ctx} {auto_role_rule}"
|
||||
)
|
||||
self._logger.debug(__name__, f"Received command auto-role remove {ctx} {auto_role_rule}")
|
||||
|
||||
auto_role_from_db = self._auto_roles.get_auto_role_rule_by_id(auto_role_rule)
|
||||
if auto_role_from_db is None:
|
||||
self._logger.debug(__name__, f"auto-role rule {auto_role_rule} not found")
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx,
|
||||
self._t.transform("modules.auto_role.remove.error.not_found").format(
|
||||
auto_role_rule
|
||||
),
|
||||
self._t.transform("modules.auto_role.remove.error.not_found").format(auto_role_rule),
|
||||
)
|
||||
self._logger.trace(__name__, f"Finished command auto-role rule remove")
|
||||
return
|
||||
@ -450,9 +384,7 @@ class AutoRoleGroup(DiscordCommandABC):
|
||||
self._logger.info(__name__, f"Removed auto-role rule {auto_role_rule}")
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx,
|
||||
self._t.transform("modules.auto_role.rule.remove.success").format(
|
||||
auto_role_rule
|
||||
),
|
||||
self._t.transform("modules.auto_role.rule.remove.success").format(auto_role_rule),
|
||||
)
|
||||
self._logger.trace(__name__, f"Finished command auto-role remove")
|
||||
|
||||
@ -461,18 +393,12 @@ class AutoRoleGroup(DiscordCommandABC):
|
||||
self, interaction: discord.Interaction, current: str
|
||||
) -> TList[app_commands.Choice[str]]:
|
||||
server = self._servers.get_server_by_discord_id(interaction.guild.id)
|
||||
auto_roles = self._auto_roles.get_auto_roles_by_server_id(
|
||||
server.server_id
|
||||
).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)
|
||||
)
|
||||
auto_roles = self._auto_roles.get_auto_roles_by_server_id(server.server_id).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 [
|
||||
app_commands.Choice(
|
||||
name=f"{rule.auto_role_rule_id} {rule.emoji_name} {interaction.guild.get_role(int(rule.role_id))}",
|
||||
value=rule.auto_role_rule_id,
|
||||
)
|
||||
for rule in self._client_utils.get_auto_complete_list(
|
||||
rules, current, lambda r: r.auto_role_rule_id
|
||||
)
|
||||
for rule in self._client_utils.get_auto_complete_list(rules, current, lambda r: r.auto_role_rule_id)
|
||||
]
|
||||
|
@ -23,9 +23,7 @@ class AutoRoleReactionHandler:
|
||||
self._servers = servers
|
||||
self._auto_roles = auto_roles
|
||||
|
||||
self._message_ids = self._auto_roles.get_auto_roles().select(
|
||||
lambda x: x.discord_message_id
|
||||
)
|
||||
self._message_ids = self._auto_roles.get_auto_roles().select(lambda x: x.discord_message_id)
|
||||
self._roles = self._auto_roles.get_auto_roles()
|
||||
|
||||
async def handle(self, payload: RawReactionActionEvent, r_type=None) -> None:
|
||||
@ -37,9 +35,7 @@ class AutoRoleReactionHandler:
|
||||
guild = self._bot.get_guild(payload.guild_id)
|
||||
user = guild.get_member(payload.user_id)
|
||||
if user is None:
|
||||
self._logger.warn(
|
||||
__name__, f"User {payload.user_id} in {guild.name} not found - skipping"
|
||||
)
|
||||
self._logger.warn(__name__, f"User {payload.user_id} in {guild.name} not found - skipping")
|
||||
return
|
||||
|
||||
if user.bot:
|
||||
@ -54,9 +50,7 @@ class AutoRoleReactionHandler:
|
||||
self._logger.debug(__name__, f"auto-role for message not found - skipping")
|
||||
return
|
||||
|
||||
rules: List[
|
||||
AutoRoleRule
|
||||
] = self._auto_roles.get_auto_role_rules_by_auto_role_id(auto_role.auto_role_id)
|
||||
rules: List[AutoRoleRule] = self._auto_roles.get_auto_role_rules_by_auto_role_id(auto_role.auto_role_id)
|
||||
if rules.count() == 0:
|
||||
self._logger.debug(__name__, f"auto-role rules not found - skipping")
|
||||
return
|
||||
|
@ -37,14 +37,10 @@ class BaseModule(ModuleABC):
|
||||
def __init__(self, dc: DiscordCollectionABC):
|
||||
ModuleABC.__init__(self, dc, FeatureFlagsEnum.base_module)
|
||||
|
||||
def configure_configuration(
|
||||
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
|
||||
pass
|
||||
|
||||
def configure_services(
|
||||
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
|
||||
services.add_transient(BaseHelperABC, BaseHelperService)
|
||||
services.add_transient(BaseReactionHandler)
|
||||
# commands
|
||||
@ -59,22 +55,12 @@ class BaseModule(ModuleABC):
|
||||
self._dc.add_command(UserGroup)
|
||||
# events
|
||||
self._dc.add_event(DiscordEventTypesEnum.on_command.value, BaseOnCommandEvent)
|
||||
self._dc.add_event(
|
||||
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_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_message.value, BaseOnMessageEvent)
|
||||
self._dc.add_event(
|
||||
DiscordEventTypesEnum.on_message_delete.value, BaseOnMessageDeleteEvent
|
||||
)
|
||||
self._dc.add_event(
|
||||
DiscordEventTypesEnum.on_raw_reaction_add.value, BaseOnRawReactionAddEvent
|
||||
)
|
||||
self._dc.add_event(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_remove.value,
|
||||
BaseOnRawReactionRemoveEvent,
|
||||
|
@ -39,9 +39,7 @@ class AFKCommand(DiscordCommandABC):
|
||||
@CommandChecks.check_is_ready()
|
||||
async def afk(self, ctx: Context):
|
||||
self._logger.debug(__name__, f"Received command afk {ctx}")
|
||||
settings: BaseServerSettings = self._config.get_configuration(
|
||||
f"BaseServerSettings_{ctx.guild.id}"
|
||||
)
|
||||
settings: BaseServerSettings = self._config.get_configuration(f"BaseServerSettings_{ctx.guild.id}")
|
||||
|
||||
if ctx.author.voice is None or ctx.author.voice.channel is None:
|
||||
await self._message_service.send_ctx_msg(
|
||||
@ -52,9 +50,7 @@ class AFKCommand(DiscordCommandABC):
|
||||
return
|
||||
|
||||
self._bot.loop.create_task(
|
||||
self._message_service.send_ctx_msg(
|
||||
ctx, self._t.transform("modules.base.afk_command_move_message")
|
||||
)
|
||||
self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.afk_command_move_message"))
|
||||
)
|
||||
channel: VoiceChannel = ctx.guild.get_channel(settings.afk_command_channel_id)
|
||||
try:
|
||||
@ -66,8 +62,6 @@ class AFKCommand(DiscordCommandABC):
|
||||
f"Cannot move user {ctx.author.id} to channel {ctx.channel.id}",
|
||||
e,
|
||||
)
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx, self._t.transform("common.no_permission_message")
|
||||
)
|
||||
await self._message_service.send_ctx_msg(ctx, self._t.transform("common.no_permission_message"))
|
||||
|
||||
self._logger.trace(__name__, f"Finished afk command")
|
||||
|
@ -39,9 +39,7 @@ class HelpCommand(DiscordCommandABC):
|
||||
@CommandChecks.check_is_ready()
|
||||
async def help(self, ctx: Context, persistent_flag: str = None):
|
||||
self._logger.debug(__name__, f"Received command help {ctx}:{persistent_flag}")
|
||||
settings: BaseServerSettings = self._config.get_configuration(
|
||||
f"BaseServerSettings_{ctx.guild.id}"
|
||||
)
|
||||
settings: BaseServerSettings = self._config.get_configuration(f"BaseServerSettings_{ctx.guild.id}")
|
||||
is_persistent = persistent_flag == "--stay"
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx,
|
||||
@ -52,8 +50,6 @@ class HelpCommand(DiscordCommandABC):
|
||||
self._logger.trace(__name__, f"Finished help command")
|
||||
|
||||
@help.autocomplete("persistent_flag")
|
||||
async def help_autocomplete(
|
||||
self, interaction: discord.Interaction, current: str
|
||||
) -> List[app_commands.Choice[str]]:
|
||||
async def help_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
|
||||
flags = ["--stay"]
|
||||
return [app_commands.Choice(name=key, value=key) for key in flags]
|
||||
|
@ -55,10 +55,7 @@ class InfoCommand(DiscordCommandABC):
|
||||
)
|
||||
start_time = self._config.get_configuration("Bot_StartTime")
|
||||
ontime = round(
|
||||
(
|
||||
datetime.now() - datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S.%f")
|
||||
).total_seconds()
|
||||
/ 3600,
|
||||
(datetime.now() - datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S.%f")).total_seconds() / 3600,
|
||||
2,
|
||||
)
|
||||
embed.add_field(
|
||||
|
@ -56,9 +56,7 @@ class MassMoveCommand(DiscordCommandABC):
|
||||
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx,
|
||||
self._t.transform("modules.base.mass_move.moved").format(
|
||||
channel_from.mention, channel_to.mention
|
||||
),
|
||||
self._t.transform("modules.base.mass_move.moved").format(channel_from.mention, channel_to.mention),
|
||||
)
|
||||
|
||||
self._logger.trace(__name__, f"Finished mass-move command")
|
||||
|
@ -59,16 +59,10 @@ class PingCommand(DiscordCommandABC):
|
||||
color=int("ef9d0d", 16),
|
||||
)
|
||||
server = self._servers.get_server_by_discord_id(ctx.guild.id)
|
||||
settings: BaseServerSettings = self._base_helper.get_config(
|
||||
server.discord_server_id
|
||||
)
|
||||
settings: BaseServerSettings = self._base_helper.get_config(server.discord_server_id)
|
||||
for server in settings.ping_urls:
|
||||
embed.add_field(
|
||||
name=server, value=f"{self._get_ping(server)} ms", inline=False
|
||||
)
|
||||
embed.add_field(name=server, value=f"{self._get_ping(server)} ms", inline=False)
|
||||
await self._message_service.send_ctx_msg(ctx, embed)
|
||||
else:
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx, self._t.transform("modules.base.pong")
|
||||
)
|
||||
await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.pong"))
|
||||
self._logger.trace(__name__, f"Finished ping command")
|
||||
|
@ -34,9 +34,7 @@ class PresenceCommand(DiscordCommandABC):
|
||||
|
||||
if text == "":
|
||||
await self._bot.change_presence(activity=None)
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx, self._t.transform("modules.base.presence.removed")
|
||||
)
|
||||
await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.presence.removed"))
|
||||
return
|
||||
|
||||
if len(text) > 128:
|
||||
@ -46,8 +44,6 @@ class PresenceCommand(DiscordCommandABC):
|
||||
return
|
||||
|
||||
await self._bot.change_presence(activity=discord.Game(name=text))
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx, self._t.transform("modules.base.presence.changed")
|
||||
)
|
||||
await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.base.presence.changed"))
|
||||
|
||||
self._logger.trace(__name__, f"Finished presence command")
|
||||
|
@ -41,20 +41,14 @@ class PurgeCommand(DiscordCommandABC):
|
||||
@CommandChecks.check_is_member_moderator()
|
||||
async def purge(self, ctx: Context):
|
||||
self._logger.debug(__name__, f"Received command purge {ctx}")
|
||||
server_settings: ServerSettings = self._config.get_configuration(
|
||||
f"ServerSettings_{ctx.guild.id}"
|
||||
)
|
||||
server_settings: ServerSettings = self._config.get_configuration(f"ServerSettings_{ctx.guild.id}")
|
||||
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx, self._t.transform("modules.moderator.purge_message")
|
||||
)
|
||||
await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.moderator.purge_message"))
|
||||
await asyncio.sleep(server_settings.message_delete_timer)
|
||||
try:
|
||||
await ctx.channel.purge()
|
||||
except Exception as e:
|
||||
self._logger.error(__name__, f"Cannot purge channel {ctx.channel.id}", e)
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx, self._t.transform("common.bot_has_no_permission_message")
|
||||
)
|
||||
await self._message_service.send_ctx_msg(ctx, self._t.transform("common.bot_has_no_permission_message"))
|
||||
|
||||
self._logger.trace(__name__, f"Finished purge command")
|
||||
|
@ -81,9 +81,7 @@ class UserGroup(DiscordCommandABC):
|
||||
member = ctx.author
|
||||
|
||||
server = self._servers.find_server_by_discord_id(ctx.guild.id)
|
||||
user = self._users.find_user_by_discord_id_and_server_id(
|
||||
member.id, server.server_id
|
||||
)
|
||||
user = self._users.find_user_by_discord_id_and_server_id(member.id, server.server_id)
|
||||
|
||||
if atr == "xp":
|
||||
if is_remove:
|
||||
@ -104,9 +102,7 @@ class UserGroup(DiscordCommandABC):
|
||||
type = "add" if not is_remove else "remove"
|
||||
await self._message_service.send_interaction_msg(
|
||||
ctx.interaction,
|
||||
self._t.transform(f"modules.base.user.{type}.{atr.lower()}").format(
|
||||
atr, value, member.mention
|
||||
),
|
||||
self._t.transform(f"modules.base.user.{type}.{atr.lower()}").format(atr, value, member.mention),
|
||||
)
|
||||
|
||||
@commands.hybrid_group()
|
||||
@ -117,41 +113,25 @@ class UserGroup(DiscordCommandABC):
|
||||
@user.command()
|
||||
@commands.guild_only()
|
||||
@CommandChecks.check_is_ready()
|
||||
async def info(
|
||||
self, ctx: Context, member: Optional[discord.Member] = None, *, wait: int = None
|
||||
):
|
||||
self._logger.debug(
|
||||
__name__, f"Received command user-info {ctx}:{member},{wait}"
|
||||
)
|
||||
async def info(self, ctx: Context, member: Optional[discord.Member] = None, *, wait: int = None):
|
||||
self._logger.debug(__name__, f"Received command user-info {ctx}:{member},{wait}")
|
||||
|
||||
is_mod = self._permissions.is_member_moderator(ctx.author)
|
||||
if member is not None and not is_mod:
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx, self._t.transform("common.no_permission_message")
|
||||
)
|
||||
await self._message_service.send_ctx_msg(ctx, self._t.transform("common.no_permission_message"))
|
||||
return
|
||||
|
||||
if member is None or not isinstance(member, discord.Member):
|
||||
member = ctx.author
|
||||
|
||||
server = self._servers.find_server_by_discord_id(ctx.guild.id)
|
||||
user = self._users.find_user_by_discord_id_and_server_id(
|
||||
member.id, server.server_id
|
||||
)
|
||||
joins = self._user_joined_servers.get_user_joined_servers_by_user_id(
|
||||
user.user_id
|
||||
)
|
||||
user = self._users.find_user_by_discord_id_and_server_id(member.id, server.server_id)
|
||||
joins = self._user_joined_servers.get_user_joined_servers_by_user_id(user.user_id)
|
||||
|
||||
embed = discord.Embed(
|
||||
title=member.name, description=member.name, color=int("ef9d0d", 16)
|
||||
)
|
||||
embed = discord.Embed(title=member.name, description=member.name, color=int("ef9d0d", 16))
|
||||
|
||||
embed.add_field(
|
||||
name=self._t.transform("modules.base.user.atr.id"), value=member.id
|
||||
)
|
||||
embed.add_field(
|
||||
name=self._t.transform("modules.base.user.atr.name"), value=member.name
|
||||
)
|
||||
embed.add_field(name=self._t.transform("modules.base.user.atr.id"), value=member.id)
|
||||
embed.add_field(name=self._t.transform("modules.base.user.atr.name"), value=member.name)
|
||||
embed.add_field(
|
||||
name=self._t.transform("modules.base.user.atr.discord_join"),
|
||||
value=self._date.transform(member.created_at),
|
||||
@ -162,9 +142,7 @@ class UserGroup(DiscordCommandABC):
|
||||
value=self._date.transform(member.joined_at),
|
||||
inline=False,
|
||||
)
|
||||
embed.add_field(
|
||||
name=self._t.transform("modules.base.user.atr.xp"), value=str(user.xp)
|
||||
)
|
||||
embed.add_field(name=self._t.transform("modules.base.user.atr.xp"), value=str(user.xp))
|
||||
embed.add_field(
|
||||
name=self._t.transform("modules.base.user.atr.ontime"),
|
||||
value=str(self._client_utils.get_ontime_for_user(user)),
|
||||
@ -210,9 +188,7 @@ class UserGroup(DiscordCommandABC):
|
||||
)
|
||||
|
||||
# send to interaction because of sensitive data
|
||||
await self._message_service.send_interaction_msg(
|
||||
ctx.interaction, embed, wait_before_delete=wait
|
||||
)
|
||||
await self._message_service.send_interaction_msg(ctx.interaction, embed, wait_before_delete=wait)
|
||||
self._logger.trace(__name__, f"Finished user-info command")
|
||||
|
||||
@user.command()
|
||||
@ -223,18 +199,14 @@ class UserGroup(DiscordCommandABC):
|
||||
|
||||
is_mod = self._permissions.is_member_moderator(ctx.author)
|
||||
if member is not None and not is_mod:
|
||||
await self._message_service.send_ctx_msg(
|
||||
ctx, self._t.transform("common.no_permission_message")
|
||||
)
|
||||
await self._message_service.send_ctx_msg(ctx, self._t.transform("common.no_permission_message"))
|
||||
return
|
||||
|
||||
if member is None or not isinstance(member, discord.Member):
|
||||
member = ctx.author
|
||||
|
||||
server = self._servers.find_server_by_discord_id(ctx.guild.id)
|
||||
user = self._users.find_user_by_discord_id_and_server_id(
|
||||
member.id, server.server_id
|
||||
)
|
||||
user = self._users.find_user_by_discord_id_and_server_id(member.id, server.server_id)
|
||||
|
||||
if atr == "xp":
|
||||
value = str(user.xp)
|
||||
@ -251,43 +223,31 @@ class UserGroup(DiscordCommandABC):
|
||||
|
||||
await self._message_service.send_interaction_msg(
|
||||
ctx.interaction,
|
||||
self._t.transform(f"modules.base.user.get.{atr.lower()}").format(
|
||||
member.mention, value
|
||||
),
|
||||
self._t.transform(f"modules.base.user.get.{atr.lower()}").format(member.mention, value),
|
||||
)
|
||||
|
||||
@get.autocomplete("atr")
|
||||
async def get_autocomplete(
|
||||
self, interaction: discord.Interaction, current: str
|
||||
) -> List[app_commands.Choice[str]]:
|
||||
return [
|
||||
app_commands.Choice(name=value, value=key) for key, value in self._atr_list
|
||||
]
|
||||
async def get_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
|
||||
return [app_commands.Choice(name=value, value=key) for key, value in self._atr_list]
|
||||
|
||||
@user.command()
|
||||
@commands.guild_only()
|
||||
@CommandChecks.check_is_ready()
|
||||
@CommandChecks.check_is_member_moderator()
|
||||
async def set(
|
||||
self, ctx: Context, atr: str, value: int, member: discord.Member = None
|
||||
):
|
||||
async def set(self, ctx: Context, atr: str, value: int, member: discord.Member = None):
|
||||
self._logger.debug(__name__, f"Received command user-set {atr} {ctx}:{member}")
|
||||
|
||||
if member is None or not isinstance(member, discord.Member):
|
||||
member = ctx.author
|
||||
|
||||
server = self._servers.find_server_by_discord_id(ctx.guild.id)
|
||||
user = self._users.find_user_by_discord_id_and_server_id(
|
||||
member.id, server.server_id
|
||||
)
|
||||
user = self._users.find_user_by_discord_id_and_server_id(member.id, server.server_id)
|
||||
|
||||
if atr == "xp":
|
||||
try:
|
||||
user.xp = value
|
||||
except TypeError as te:
|
||||
self._logger.error(
|
||||
__name__, f"String value couldn't be converted to int", te
|
||||
)
|
||||
self._logger.error(__name__, f"String value couldn't be converted to int", te)
|
||||
await self._message_service.send_interaction_msg(
|
||||
ctx.interaction,
|
||||
self._t.transform("modules.base.user.set.error.type_error"),
|
||||
@ -307,15 +267,11 @@ class UserGroup(DiscordCommandABC):
|
||||
|
||||
await self._message_service.send_interaction_msg(
|
||||
ctx.interaction,
|
||||
self._t.transform(f"modules.base.user.set.{atr.lower()}").format(
|
||||
member.mention, value
|
||||
),
|
||||
self._t.transform(f"modules.base.user.set.{atr.lower()}").format(member.mention, value),
|
||||
)
|
||||
|
||||
@set.autocomplete("atr")
|
||||
async def set_autocomplete(
|
||||
self, interaction: discord.Interaction, current: str
|
||||
) -> List[app_commands.Choice[str]]:
|
||||
async def set_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
|
||||
atr_list = [("xp", self._atr_dict["xp"])]
|
||||
return [app_commands.Choice(name=value, value=key) for key, value in atr_list]
|
||||
|
||||
@ -323,18 +279,12 @@ class UserGroup(DiscordCommandABC):
|
||||
@commands.guild_only()
|
||||
@CommandChecks.check_is_ready()
|
||||
@CommandChecks.check_is_member_moderator()
|
||||
async def add(
|
||||
self, ctx: Context, atr: str, value: int, member: discord.Member = None
|
||||
):
|
||||
self._logger.debug(
|
||||
__name__, f"Received command user-add {atr}-={value} {ctx}:{member}"
|
||||
)
|
||||
async def add(self, ctx: Context, atr: str, value: int, member: discord.Member = None):
|
||||
self._logger.debug(__name__, f"Received command user-add {atr}-={value} {ctx}:{member}")
|
||||
await self._handle_atr_calc(ctx, atr, value, member)
|
||||
|
||||
@add.autocomplete("atr")
|
||||
async def set_autocomplete(
|
||||
self, interaction: discord.Interaction, current: str
|
||||
) -> List[app_commands.Choice[str]]:
|
||||
async def set_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
|
||||
atr_list = [("xp", self._atr_dict["xp"])]
|
||||
return [app_commands.Choice(name=value, value=key) for key, value in atr_list]
|
||||
|
||||
@ -342,18 +292,12 @@ class UserGroup(DiscordCommandABC):
|
||||
@commands.guild_only()
|
||||
@CommandChecks.check_is_ready()
|
||||
@CommandChecks.check_is_member_moderator()
|
||||
async def remove(
|
||||
self, ctx: Context, atr: str, value: int, member: discord.Member = None
|
||||
):
|
||||
self._logger.debug(
|
||||
__name__, f"Received command user-remove {atr}-={value} {ctx}:{member}"
|
||||
)
|
||||
async def remove(self, ctx: Context, atr: str, value: int, member: discord.Member = None):
|
||||
self._logger.debug(__name__, f"Received command user-remove {atr}-={value} {ctx}:{member}")
|
||||
await self._handle_atr_calc(ctx, atr, value, member, is_remove=True)
|
||||
|
||||
@remove.autocomplete("atr")
|
||||
async def set_autocomplete(
|
||||
self, interaction: discord.Interaction, current: str
|
||||
) -> List[app_commands.Choice[str]]:
|
||||
async def set_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
|
||||
atr_list = [("xp", self._atr_dict["xp"])]
|
||||
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_member_moderator()
|
||||
async def reset(self, ctx: Context, atr: str, member: discord.Member = None):
|
||||
self._logger.debug(
|
||||
__name__, f"Received command user-reset {atr} {ctx}:{member}"
|
||||
)
|
||||
self._logger.debug(__name__, f"Received command user-reset {atr} {ctx}:{member}")
|
||||
|
||||
if member is None or not isinstance(member, discord.Member):
|
||||
member = ctx.author
|
||||
|
||||
server = self._servers.find_server_by_discord_id(ctx.guild.id)
|
||||
user = self._users.find_user_by_discord_id_and_server_id(
|
||||
member.id, server.server_id
|
||||
)
|
||||
user = self._users.find_user_by_discord_id_and_server_id(member.id, server.server_id)
|
||||
|
||||
if atr == "xp":
|
||||
user.xp = 0
|
||||
@ -381,9 +321,7 @@ class UserGroup(DiscordCommandABC):
|
||||
await self._level.check_level(member)
|
||||
|
||||
elif atr == "ontime":
|
||||
self._user_joined_voice_channel.delete_user_joined_voice_channel_by_user_id(
|
||||
user.user_id
|
||||
)
|
||||
self._user_joined_voice_channel.delete_user_joined_voice_channel_by_user_id(user.user_id)
|
||||
self._db.save_changes()
|
||||
|
||||
else:
|
||||
@ -395,15 +333,11 @@ class UserGroup(DiscordCommandABC):
|
||||
|
||||
await self._message_service.send_interaction_msg(
|
||||
ctx.interaction,
|
||||
self._t.transform(f"modules.base.user.reset.{atr.lower()}").format(
|
||||
atr, member.mention
|
||||
),
|
||||
self._t.transform(f"modules.base.user.reset.{atr.lower()}").format(atr, member.mention),
|
||||
)
|
||||
|
||||
@reset.autocomplete("atr")
|
||||
async def reset_autocomplete(
|
||||
self, interaction: discord.Interaction, current: str
|
||||
) -> List[app_commands.Choice[str]]:
|
||||
return [
|
||||
app_commands.Choice(name=value, value=key) for key, value in self._atr_list
|
||||
]
|
||||
return [app_commands.Choice(name=value, value=key) for key, value in self._atr_list]
|
||||
|
@ -81,9 +81,5 @@ class BaseServerSettings(ConfigurationModelABC):
|
||||
for url in settings["PingURLs"]:
|
||||
self._ping_urls.append(url)
|
||||
except Exception as e:
|
||||
Console.error(
|
||||
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings"
|
||||
)
|
||||
Console.error(
|
||||
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
|
||||
)
|
||||
Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
|
||||
Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
|
||||
|
@ -27,9 +27,5 @@ class BaseSettings(ConfigurationModelABC):
|
||||
servers.append(st)
|
||||
self._servers = servers
|
||||
except Exception as e:
|
||||
Console.error(
|
||||
f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings"
|
||||
)
|
||||
Console.error(
|
||||
f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}"
|
||||
)
|
||||
Console.error(f"[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings")
|
||||
Console.error(f"[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}")
|
||||
|
@ -169,9 +169,7 @@ class BaseOnCommandErrorEvent(OnCommandErrorABC):
|
||||
)
|
||||
|
||||
elif isinstance(error, commands.NotOwner):
|
||||
await self._messenger.send_ctx_msg(
|
||||
ctx, self._t.transform("common.errors.not_owner"), without_tracking=True
|
||||
)
|
||||
await self._messenger.send_ctx_msg(ctx, self._t.transform("common.errors.not_owner"), without_tracking=True)
|
||||
|
||||
elif isinstance(error, commands.MissingPermissions):
|
||||
await self._messenger.send_ctx_msg(
|
||||
@ -263,19 +261,13 @@ class BaseOnCommandErrorEvent(OnCommandErrorABC):
|
||||
self._t.transform("common.errors.command_error"),
|
||||
without_tracking=True,
|
||||
)
|
||||
message = self._t.transform(
|
||||
"modules.base.technician_command_error_message"
|
||||
).format(
|
||||
message = self._t.transform("modules.base.technician_command_error_message").format(
|
||||
ctx.command,
|
||||
ctx.author,
|
||||
error,
|
||||
datetime.datetime.now().strftime(
|
||||
self._time_format_settings.date_time_format
|
||||
),
|
||||
datetime.datetime.now().strftime(self._time_format_settings.date_time_format),
|
||||
uid,
|
||||
)
|
||||
for t in self._bot_settings.technicians:
|
||||
member = self._bot.get_user(t)
|
||||
await self._messenger.send_dm_message(
|
||||
message, member, without_tracking=True
|
||||
)
|
||||
await self._messenger.send_dm_message(message, member, without_tracking=True)
|
||||
|
@ -52,9 +52,7 @@ class BaseOnCommandEvent(OnCommandABC):
|
||||
self._clients.append_received_command_count(self._bot.user.id, g_id, 1)
|
||||
self._db.save_changes()
|
||||
except Exception as e:
|
||||
self._logger.error(
|
||||
__name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e
|
||||
)
|
||||
self._logger.error(__name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e)
|
||||
|
||||
def _handle_message_for_xp(self, message: discord.Message):
|
||||
dc_user_id = message.author.id
|
||||
@ -66,9 +64,7 @@ class BaseOnCommandEvent(OnCommandABC):
|
||||
|
||||
user: Optional[User] = None
|
||||
try:
|
||||
user = self._users.get_user_by_discord_id_and_server_id(
|
||||
dc_user_id, server.server_id
|
||||
)
|
||||
user = self._users.get_user_by_discord_id_and_server_id(dc_user_id, server.server_id)
|
||||
except Exception as e:
|
||||
self._logger.error(__name__, f"Cannot get user {dc_user_id}", e)
|
||||
return
|
||||
@ -83,15 +79,11 @@ class BaseOnCommandEvent(OnCommandABC):
|
||||
self._users.update_user(user)
|
||||
self._db.save_changes()
|
||||
|
||||
self._logger.debug(
|
||||
__name__, f"User {user} sent message. xp: from {old_xp} to {user.xp}"
|
||||
)
|
||||
self._logger.debug(__name__, f"User {user} sent message. xp: from {old_xp} to {user.xp}")
|
||||
|
||||
async def on_command(self, ctx: Context):
|
||||
self._logger.debug(__name__, f"Module {type(self)} started")
|
||||
self._logger.info(
|
||||
__name__, f"Received command: {ctx.command} from {ctx.channel}"
|
||||
)
|
||||
self._logger.info(__name__, f"Received command: {ctx.command} from {ctx.channel}")
|
||||
if ctx is None or ctx.guild is None:
|
||||
return
|
||||
self._append_received_command_count(ctx.guild.id)
|
||||
|
@ -63,9 +63,7 @@ class BaseOnMemberJoinEvent(OnMemberJoinABC):
|
||||
except Exception as e:
|
||||
self._logger.error(__name__, f"Cannot get user {member.id}", e)
|
||||
|
||||
async def _add_if_not_exists_user_async(
|
||||
self, member: Union[discord.User, discord.Member]
|
||||
):
|
||||
async def _add_if_not_exists_user_async(self, member: Union[discord.User, discord.Member]):
|
||||
self._logger.debug(__name__, f"Check if user exists {member}")
|
||||
settings: BaseServerSettings = self._base_helper.get_config(member.guild.id)
|
||||
await self._messenger.send_dm_message(
|
||||
@ -75,41 +73,29 @@ class BaseOnMemberJoinEvent(OnMemberJoinABC):
|
||||
|
||||
for admin in self._permission_service.get_admins(member.guild.id):
|
||||
await self._messenger.send_dm_message(
|
||||
self._t.transform("modules.base.welcome_message_for_team").format(
|
||||
member.mention
|
||||
),
|
||||
self._t.transform("modules.base.welcome_message_for_team").format(member.mention),
|
||||
admin,
|
||||
)
|
||||
|
||||
for moderator in self._permission_service.get_moderators(member.guild.id):
|
||||
await self._messenger.send_dm_message(
|
||||
self._t.transform("modules.base.welcome_message_for_team").format(
|
||||
member.mention
|
||||
),
|
||||
self._t.transform("modules.base.welcome_message_for_team").format(member.mention),
|
||||
moderator,
|
||||
)
|
||||
|
||||
try:
|
||||
server = self._servers.get_server_by_discord_id(member.guild.id)
|
||||
user = self._users.find_user_by_discord_id_and_server_id(
|
||||
member.id, server.server_id
|
||||
)
|
||||
user = self._users.find_user_by_discord_id_and_server_id(member.id, server.server_id)
|
||||
if user is not None:
|
||||
self._user_joins.add_user_joined_server(
|
||||
UserJoinedServer(user, datetime.now())
|
||||
)
|
||||
self._user_joins.add_user_joined_server(UserJoinedServer(user, datetime.now()))
|
||||
self._db.save_changes()
|
||||
return
|
||||
|
||||
self._logger.debug(__name__, f"Add user: {member.id}")
|
||||
self._users.add_user(User(member.id, 0, server))
|
||||
self._db.save_changes()
|
||||
user = self._users.get_user_by_discord_id_and_server_id(
|
||||
member.id, server.server_id
|
||||
)
|
||||
self._user_joins.add_user_joined_server(
|
||||
UserJoinedServer(user, datetime.now())
|
||||
)
|
||||
user = self._users.get_user_by_discord_id_and_server_id(member.id, server.server_id)
|
||||
self._user_joins.add_user_joined_server(UserJoinedServer(user, datetime.now()))
|
||||
self._db.save_changes()
|
||||
except Exception as e:
|
||||
self._logger.error(__name__, f"Cannot get user {member.id}", e)
|
||||
|
@ -42,23 +42,17 @@ class BaseOnMemberRemoveEvent(OnMemberRemoveABC):
|
||||
async def _remove_user(self, member: Union[discord.User, discord.Member]):
|
||||
self._logger.debug(__name__, f"Remove user {member}")
|
||||
settings: BaseServerSettings = self._base_helper.get_config(member.guild.id)
|
||||
await self._messenger.send_dm_message(
|
||||
self._t.transform("modules.base.goodbye_message"), member
|
||||
)
|
||||
await self._messenger.send_dm_message(self._t.transform("modules.base.goodbye_message"), member)
|
||||
|
||||
try:
|
||||
server = self._servers.get_server_by_discord_id(member.guild.id)
|
||||
|
||||
user = self._users.find_user_by_discord_id_and_server_id(
|
||||
member.id, server.server_id
|
||||
)
|
||||
user = self._users.find_user_by_discord_id_and_server_id(member.id, server.server_id)
|
||||
if user is None:
|
||||
self._logger.error(__name__, f"Cannot find user {member}")
|
||||
return
|
||||
|
||||
join = self._user_joins.get_active_user_joined_server_by_user_id(
|
||||
user.user_id
|
||||
)
|
||||
join = self._user_joins.get_active_user_joined_server_by_user_id(user.user_id)
|
||||
join.leaved_on = datetime.now()
|
||||
self._user_joins.update_user_joined_server(join)
|
||||
self._db.save_changes()
|
||||
|
@ -40,9 +40,7 @@ class BaseOnMessageDeleteEvent(OnMessageDeleteABC):
|
||||
self._clients.append_deleted_message_count(self._bot.user.id, g_id, 1)
|
||||
self._db.save_changes()
|
||||
except Exception as e:
|
||||
self._logger.error(
|
||||
__name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e
|
||||
)
|
||||
self._logger.error(__name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e)
|
||||
|
||||
def _handle_message_delete(self, message: discord.Message):
|
||||
dc_user_id = message.author.id
|
||||
@ -54,9 +52,7 @@ class BaseOnMessageDeleteEvent(OnMessageDeleteABC):
|
||||
|
||||
user: Optional[User] = None
|
||||
try:
|
||||
user = self._users.find_user_by_discord_id_and_server_id(
|
||||
dc_user_id, server.server_id
|
||||
)
|
||||
user = self._users.find_user_by_discord_id_and_server_id(dc_user_id, server.server_id)
|
||||
except Exception as e:
|
||||
self._logger.error(__name__, f"Cannot get user {dc_user_id}", e)
|
||||
return
|
||||
@ -81,9 +77,7 @@ class BaseOnMessageDeleteEvent(OnMessageDeleteABC):
|
||||
if message is None or message.guild is None:
|
||||
return
|
||||
|
||||
self._logger.info(
|
||||
__name__, f"Received message: {LogMessageHelper.get_log_string(message)}"
|
||||
)
|
||||
self._logger.info(__name__, f"Received message: {LogMessageHelper.get_log_string(message)}")
|
||||
self._append_deleted_message_count(message.guild.id)
|
||||
|
||||
if not message.author.bot:
|
||||
|
@ -45,9 +45,7 @@ class BaseOnMessageEvent(OnMessageABC):
|
||||
self._clients.append_received_message_count(self._bot.user.id, g_id, 1)
|
||||
self._db.save_changes()
|
||||
except Exception as e:
|
||||
self._logger.error(
|
||||
__name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e
|
||||
)
|
||||
self._logger.error(__name__, f"Cannot edit client {self._bot.user.id}@{g_id}", e)
|
||||
|
||||
def _handle_message_for_xp(self, message: discord.Message):
|
||||
dc_user_id = message.author.id
|
||||
@ -59,9 +57,7 @@ class BaseOnMessageEvent(OnMessageABC):
|
||||
|
||||
user: Optional[User] = None
|
||||
try:
|
||||
user = self._users.find_user_by_discord_id_and_server_id(
|
||||
dc_user_id, server.server_id
|
||||
)
|
||||
user = self._users.find_user_by_discord_id_and_server_id(dc_user_id, server.server_id)
|
||||
except Exception as e:
|
||||
self._logger.error(__name__, f"Cannot get user {dc_user_id}", e)
|
||||
return
|
||||
@ -81,9 +77,7 @@ class BaseOnMessageEvent(OnMessageABC):
|
||||
self._users.update_user(user)
|
||||
self._db.save_changes()
|
||||
|
||||
self._logger.debug(
|
||||
__name__, f"User {user} sent message. xp: from {old_xp} to {user.xp}"
|
||||
)
|
||||
self._logger.debug(__name__, f"User {user} sent message. xp: from {old_xp} to {user.xp}")
|
||||
|
||||
@EventChecks.check_is_ready()
|
||||
async def on_message(self, message: discord.Message):
|
||||
@ -91,9 +85,7 @@ class BaseOnMessageEvent(OnMessageABC):
|
||||
if message is None or message.guild is None:
|
||||
return
|
||||
|
||||
self._logger.info(
|
||||
__name__, f"Received message: {LogMessageHelper.get_log_string(message)}"
|
||||
)
|
||||
self._logger.info(__name__, f"Received message: {LogMessageHelper.get_log_string(message)}")
|
||||
self._append_received_message_count(message.guild.id)
|
||||
|
||||
if not message.author.bot:
|
||||
|
@ -51,14 +51,10 @@ class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC):
|
||||
|
||||
self._logger.info(__name__, f"Module {type(self)} loaded")
|
||||
|
||||
def _update_voice_state(
|
||||
self, joined: bool, dc_user_id: int, dc_channel_id: int, server: Server
|
||||
):
|
||||
def _update_voice_state(self, joined: bool, dc_user_id: int, dc_channel_id: int, server: Server):
|
||||
user: Optional[User] = None
|
||||
try:
|
||||
user = self._users.get_user_by_discord_id_and_server_id(
|
||||
dc_user_id, server.server_id
|
||||
)
|
||||
user = self._users.get_user_by_discord_id_and_server_id(dc_user_id, server.server_id)
|
||||
except Exception as e:
|
||||
self._logger.error(__name__, f"Cannot get user {dc_user_id}", e)
|
||||
return
|
||||
@ -74,13 +70,9 @@ class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC):
|
||||
self._db.save_changes()
|
||||
return
|
||||
|
||||
settings: BaseServerSettings = self._base_helper.get_config(
|
||||
server.discord_server_id
|
||||
)
|
||||
settings: BaseServerSettings = self._base_helper.get_config(server.discord_server_id)
|
||||
|
||||
join = self._user_joins_vc.get_active_user_joined_voice_channel_by_user_id(
|
||||
user.user_id
|
||||
)
|
||||
join = self._user_joins_vc.get_active_user_joined_voice_channel_by_user_id(user.user_id)
|
||||
join.leaved_on = datetime.now()
|
||||
|
||||
# ontime as hours
|
||||
@ -136,36 +128,18 @@ class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC):
|
||||
# channel to channel
|
||||
elif before.channel is not None and after.channel is not None:
|
||||
# joined
|
||||
if (
|
||||
before.channel.id in settings.afk_channel_ids
|
||||
and after.channel.id not in settings.afk_channel_ids
|
||||
):
|
||||
self._logger.trace(
|
||||
__name__, f"User {member.id} joined {after.channel}"
|
||||
)
|
||||
if before.channel.id in settings.afk_channel_ids and after.channel.id not in settings.afk_channel_ids:
|
||||
self._logger.trace(__name__, f"User {member.id} joined {after.channel}")
|
||||
self._update_voice_state(True, member.id, after.channel.id, server)
|
||||
|
||||
# left
|
||||
elif (
|
||||
after.channel.id in settings.afk_channel_ids
|
||||
and before.channel.id not in settings.afk_channel_ids
|
||||
):
|
||||
self._logger.trace(
|
||||
__name__, f"User {member.id} left {before.channel}"
|
||||
)
|
||||
self._update_voice_state(
|
||||
False, member.id, before.channel.id, server
|
||||
)
|
||||
elif after.channel.id in settings.afk_channel_ids and before.channel.id not in settings.afk_channel_ids:
|
||||
self._logger.trace(__name__, f"User {member.id} left {before.channel}")
|
||||
self._update_voice_state(False, member.id, before.channel.id, server)
|
||||
|
||||
else:
|
||||
self._logger.trace(
|
||||
__name__, f"User {member.id} switched to {after.channel}"
|
||||
)
|
||||
self._update_voice_state(
|
||||
False, member.id, before.channel.id, server
|
||||
)
|
||||
self._logger.trace(__name__, f"User {member.id} switched to {after.channel}")
|
||||
self._update_voice_state(False, member.id, before.channel.id, server)
|
||||
self._update_voice_state(True, member.id, after.channel.id, server)
|
||||
except Exception as e:
|
||||
self._logger.error(
|
||||
__name__, f"Cannot handle voice state for user {member.id}", e
|
||||
)
|
||||
self._logger.error(__name__, f"Cannot handle voice state for user {member.id}", e)
|
||||
|
@ -43,9 +43,7 @@ class BaseOnVoiceStateUpdateEventHelpChannel(OnVoiceStateUpdateABC):
|
||||
):
|
||||
self._logger.debug(__name__, f"Module {type(self)} started")
|
||||
server = self._servers.get_server_by_discord_id(member.guild.id)
|
||||
settings: BaseServerSettings = self._base_helper.get_config(
|
||||
server.discord_server_id
|
||||
)
|
||||
settings: BaseServerSettings = self._base_helper.get_config(server.discord_server_id)
|
||||
if after.channel is None or after.channel.id != settings.help_voice_channel_id:
|
||||
return
|
||||
|
||||
@ -55,9 +53,7 @@ class BaseOnVoiceStateUpdateEventHelpChannel(OnVoiceStateUpdateABC):
|
||||
]
|
||||
for a in mods:
|
||||
await self._message_service.send_dm_message(
|
||||
self._t.transform(
|
||||
"modules.base.member_joined_help_voice_channel"
|
||||
).format(member.mention),
|
||||
self._t.transform("modules.base.member_joined_help_voice_channel").format(member.mention),
|
||||
a,
|
||||
)
|
||||
|
||||
|
@ -38,9 +38,7 @@ class BaseReactionHandler:
|
||||
guild = self._bot.get_guild(payload.guild_id)
|
||||
member = guild.get_member(payload.user_id)
|
||||
if member is None:
|
||||
self._logger.warn(
|
||||
__name__, f"User {payload.user_id} in {guild.name} not found - skipping"
|
||||
)
|
||||
self._logger.warn(__name__, f"User {payload.user_id} in {guild.name} not found - skipping")
|
||||
return
|
||||
|
||||
try:
|
||||
@ -55,12 +53,8 @@ class BaseReactionHandler:
|
||||
f"{log_msg} to message {LogMessageHelper.get_log_string(message)}",
|
||||
)
|
||||
except Exception as e:
|
||||
self._logger.error(
|
||||
__name__, f"Getting message for reaction logging failed", e
|
||||
)
|
||||
self._logger.info(
|
||||
__name__, f"{log_msg} to message {payload.message_id}"
|
||||
)
|
||||
self._logger.error(__name__, f"Getting message for reaction logging failed", e)
|
||||
self._logger.info(__name__, f"{log_msg} to message {payload.message_id}")
|
||||
except Exception as e:
|
||||
self._logger.error(__name__, f"Reaction logging failed", e)
|
||||
|
||||
@ -68,9 +62,7 @@ class BaseReactionHandler:
|
||||
return
|
||||
|
||||
server = self._servers.get_server_by_discord_id(guild.id)
|
||||
user = self._users.get_user_by_discord_id_and_server_id(
|
||||
member.id, server.server_id
|
||||
)
|
||||
user = self._users.get_user_by_discord_id_and_server_id(member.id, server.server_id)
|
||||
settings: BaseServerSettings = self._base_helper.get_config(guild.id)
|
||||
|
||||
if r_type == "add":
|
||||
|
@ -14,9 +14,7 @@ class BootLogExtension(ApplicationExtensionABC):
|
||||
pass
|
||||
|
||||
async def run(self, config: ConfigurationABC, services: ServiceProviderABC):
|
||||
feature_flags: FeatureFlagsSettings = config.get_configuration(
|
||||
FeatureFlagsSettings
|
||||
)
|
||||
feature_flags: FeatureFlagsSettings = config.get_configuration(FeatureFlagsSettings)
|
||||
if not feature_flags.get_flag(FeatureFlagsEnum.boot_log_module):
|
||||
return
|
||||
logger: LoggerABC = services.get_service(LoggerABC)
|
||||
|
@ -13,14 +13,10 @@ class BootLogModule(ModuleABC):
|
||||
def __init__(self, dc: DiscordCollectionABC):
|
||||
ModuleABC.__init__(self, dc, FeatureFlagsEnum.boot_log_module)
|
||||
|
||||
def configure_configuration(
|
||||
self, config: ConfigurationABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC):
|
||||
pass
|
||||
|
||||
def configure_services(
|
||||
self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC
|
||||
):
|
||||
def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
|
||||
# commands
|
||||
# events
|
||||
self._dc.add_event(DiscordEventTypesEnum.on_ready.value, BootLogOnReadyEvent)
|
||||
|
@ -38,10 +38,7 @@ class BootLogOnReadyEvent(OnReadyABC):
|
||||
try:
|
||||
start_time = self._config.get_configuration("Bot_StartTime")
|
||||
init_time = round(
|
||||
(
|
||||
datetime.now()
|
||||
- datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S.%f")
|
||||
).total_seconds(),
|
||||
(datetime.now() - datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S.%f")).total_seconds(),
|
||||
2,
|
||||
)
|
||||
self._config.add_configuration("InitTime", str(init_time))
|
||||
@ -52,9 +49,7 @@ class BootLogOnReadyEvent(OnReadyABC):
|
||||
|
||||
# print error if initialisation took way too long
|
||||
elif init_time >= 90:
|
||||
self._logger.error(
|
||||
__name__, "It takes far too long to start the bot!!!"
|
||||
)
|
||||
self._logger.error(__name__, "It takes far too long to start the bot!!!")
|
||||
except Exception as e:
|
||||
self._logger.error(__name__, "Init time calculation failed", e)
|
||||
return
|
||||
@ -63,22 +58,14 @@ class BootLogOnReadyEvent(OnReadyABC):
|
||||
g: guild = g
|
||||
self._logger.debug(__name__, f"Server detected: {g.id}")
|
||||
|
||||
server_settings: ServerSettings = self._config.get_configuration(
|
||||
f"ServerSettings_{g.id}"
|
||||
)
|
||||
server_settings: ServerSettings = self._config.get_configuration(f"ServerSettings_{g.id}")
|
||||
if server_settings is None:
|
||||
self._logger.error(
|
||||
__name__, f"BootLog settings for server {g.id} not found!"
|
||||
)
|
||||
self._logger.error(__name__, f"BootLog settings for server {g.id} not found!")
|
||||
return
|
||||
|
||||
module_settings: BootLogServerSettings = self._config.get_configuration(
|
||||
f"BootLogServerSettings_{g.id}"
|
||||
)
|
||||
module_settings: BootLogServerSettings = self._config.get_configuration(f"BootLogServerSettings_{g.id}")
|
||||
if module_settings is None:
|
||||
self._logger.error(
|
||||
__name__, f"Config {type(self).__name__}_{g.id} not found!"
|
||||
)
|
||||
self._logger.error(__name__, f"Config {type(self).__name__}_{g.id} not found!")
|
||||
return
|
||||
|
||||
await self._message_service.send_channel_message(
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user