From 3d01c9f798ceac5b58bcbabec721313eb7f1cd99 Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Wed, 11 Jan 2023 18:27:43 +0100 Subject: [PATCH 1/6] Added max_message_xp_per_hour #168 --- kdb-bot/src/bot/config | 2 +- .../src/modules/base/configuration/base_server_settings.py | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/kdb-bot/src/bot/config b/kdb-bot/src/bot/config index 28bd879d..54b1b386 160000 --- a/kdb-bot/src/bot/config +++ b/kdb-bot/src/bot/config @@ -1 +1 @@ -Subproject commit 28bd879dab2e5ea6ca8bb38e44c7786eb67cb7a2 +Subproject commit 54b1b3860cb570d29c8ba2590dd082a1fa744265 diff --git a/kdb-bot/src/modules/base/configuration/base_server_settings.py b/kdb-bot/src/modules/base/configuration/base_server_settings.py index b5838633..2c5acf5f 100644 --- a/kdb-bot/src/modules/base/configuration/base_server_settings.py +++ b/kdb-bot/src/modules/base/configuration/base_server_settings.py @@ -14,6 +14,7 @@ class BaseServerSettings(ConfigurationModelABC): self._max_voice_state_hours: int = 0 self._xp_per_message: int = 0 self._xp_per_reaction: int = 0 + self._max_message_xp_per_hour: int = 0 self._xp_per_ontime_hour: int = 0 self._afk_channel_ids: List[int] = List(int) self._afk_command_channel_id: int = 0 @@ -37,6 +38,10 @@ class BaseServerSettings(ConfigurationModelABC): def xp_per_reaction(self) -> int: return self._xp_per_reaction + @property + def max_message_xp_per_hour(self) -> int: + return self._max_message_xp_per_hour + @property def xp_per_ontime_hour(self) -> int: return self._xp_per_ontime_hour @@ -67,6 +72,7 @@ class BaseServerSettings(ConfigurationModelABC): self._max_voice_state_hours = int(settings['MaxVoiceStateHours']) self._xp_per_message = int(settings['XpPerMessage']) self._xp_per_reaction = int(settings['XpPerReaction']) + self._max_message_xp_per_hour = int(settings['MaxMessageXpPerHour']) self._xp_per_ontime_hour = int(settings['XpPerOntimeHour']) for index in settings['AFKChannelIds']: self._afk_channel_ids.append(int(index)) From a216506a37485684f7856caa207f76c14d8d914c Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Wed, 11 Jan 2023 19:08:00 +0100 Subject: [PATCH 2/6] Added UserMessageCountPerHour model #168 --- .../src/bot/startup_migration_extension.py | 2 + ...er_joined_voice_channel_repository_abc.py} | 0 ...r_message_count_per_hour_repository_abc.py | 33 +++++ kdb-bot/src/bot_data/data_module.py | 5 +- .../user_message_count_per_hour_migration.py | 36 ++++++ .../model/user_message_count_per_hour.py | 117 ++++++++++++++++++ ...joined_voice_channel_repository_service.py | 101 +++++++++++++++ .../user_joined_voice_channel_service.py | 2 +- .../src/modules/base/command/user_group.py | 2 +- .../base_on_voice_state_update_event.py | 2 +- .../database/database_on_ready_event.py | 2 +- .../stats/service/statistic_service.py | 2 +- 12 files changed, 298 insertions(+), 6 deletions(-) rename kdb-bot/src/bot_data/abc/{user_joined_voice_channel_abc.py => user_joined_voice_channel_repository_abc.py} (100%) create mode 100644 kdb-bot/src/bot_data/abc/user_message_count_per_hour_repository_abc.py create mode 100644 kdb-bot/src/bot_data/migration/user_message_count_per_hour_migration.py create mode 100644 kdb-bot/src/bot_data/model/user_message_count_per_hour.py create mode 100644 kdb-bot/src/bot_data/service/user_joined_voice_channel_repository_service.py diff --git a/kdb-bot/src/bot/startup_migration_extension.py b/kdb-bot/src/bot/startup_migration_extension.py index a4bd452c..eb4481b9 100644 --- a/kdb-bot/src/bot/startup_migration_extension.py +++ b/kdb-bot/src/bot/startup_migration_extension.py @@ -10,6 +10,7 @@ from bot_data.migration.auto_role_migration import AutoRoleMigration from bot_data.migration.initial_migration import InitialMigration from bot_data.migration.level_migration import LevelMigration from bot_data.migration.stats_migration import StatsMigration +from bot_data.migration.user_message_count_per_hour_migration import UserMessageCountPerHourMigration from bot_data.service.migration_service import MigrationService @@ -29,3 +30,4 @@ class StartupMigrationExtension(StartupExtensionABC): 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 diff --git a/kdb-bot/src/bot_data/abc/user_joined_voice_channel_abc.py b/kdb-bot/src/bot_data/abc/user_joined_voice_channel_repository_abc.py similarity index 100% rename from kdb-bot/src/bot_data/abc/user_joined_voice_channel_abc.py rename to kdb-bot/src/bot_data/abc/user_joined_voice_channel_repository_abc.py diff --git a/kdb-bot/src/bot_data/abc/user_message_count_per_hour_repository_abc.py b/kdb-bot/src/bot_data/abc/user_message_count_per_hour_repository_abc.py new file mode 100644 index 00000000..e5610c63 --- /dev/null +++ b/kdb-bot/src/bot_data/abc/user_message_count_per_hour_repository_abc.py @@ -0,0 +1,33 @@ +from abc import ABC, abstractmethod +from typing import Optional + +from cpl_query.extension import List + +from bot_data.model.user_message_count_per_hour import UserMessageCountPerHour + + +class UserMessageCountPerHourRepositoryABC(ABC): + + @abstractmethod + def __init__(self): pass + + @abstractmethod + def get_user_message_count_per_hours(self) -> List[UserMessageCountPerHour]: pass + + @abstractmethod + def find_user_message_count_per_hours_by_user_id(self, user_id: int) -> List[Optional[UserMessageCountPerHour]]: pass + + @abstractmethod + def find_user_message_count_per_hours_by_user_id_and_active_hour(self, user_id: int) -> List[Optional[UserMessageCountPerHour]]: pass + + @abstractmethod + def add_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): pass + + @abstractmethod + def update_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): pass + + @abstractmethod + def delete_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): pass + + @abstractmethod + def delete_user_message_count_per_hour_by_user_id(self, user_id: int): pass diff --git a/kdb-bot/src/bot_data/data_module.py b/kdb-bot/src/bot_data/data_module.py index e32d8039..0fc82a26 100644 --- a/kdb-bot/src/bot_data/data_module.py +++ b/kdb-bot/src/bot_data/data_module.py @@ -13,7 +13,8 @@ from bot_data.abc.level_repository_abc import LevelRepositoryABC from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.statistic_repository_abc import StatisticRepositoryABC from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC -from bot_data.abc.user_joined_voice_channel_abc import UserJoinedVoiceChannelRepositoryABC +from bot_data.abc.user_joined_voice_channel_repository_abc import UserJoinedVoiceChannelRepositoryABC +from bot_data.abc.user_message_count_per_hour_repository_abc import UserMessageCountPerHourRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC from bot_data.service.auth_user_repository_service import AuthUserRepositoryService from bot_data.service.auto_role_repository_service import AutoRoleRepositoryService @@ -24,6 +25,7 @@ from bot_data.service.seeder_service import SeederService from bot_data.service.server_repository_service import ServerRepositoryService from bot_data.service.statistic_repository_service import StatisticRepositoryService from bot_data.service.user_joined_server_repository_service import UserJoinedServerRepositoryService +from bot_data.service.user_joined_voice_channel_repository_service import UserMessageCountPerHourRepositoryService from bot_data.service.user_joined_voice_channel_service import UserJoinedVoiceChannelRepositoryService from bot_data.service.user_repository_service import UserRepositoryService @@ -47,5 +49,6 @@ class DataModule(ModuleABC): services.add_transient(AutoRoleRepositoryABC, AutoRoleRepositoryService) services.add_transient(LevelRepositoryABC, LevelRepositoryService) services.add_transient(StatisticRepositoryABC, StatisticRepositoryService) + services.add_transient(UserMessageCountPerHourRepositoryABC, UserMessageCountPerHourRepositoryService) services.add_transient(SeederService) diff --git a/kdb-bot/src/bot_data/migration/user_message_count_per_hour_migration.py b/kdb-bot/src/bot_data/migration/user_message_count_per_hour_migration.py new file mode 100644 index 00000000..2e67d996 --- /dev/null +++ b/kdb-bot/src/bot_data/migration/user_message_count_per_hour_migration.py @@ -0,0 +1,36 @@ +from bot_core.logging.database_logger import DatabaseLogger +from bot_data.abc.migration_abc import MigrationABC +from bot_data.db_context import DBContext + + +class UserMessageCountPerHourMigration(MigrationABC): + name = '0.3.1_UserMessageCountPerHourMigration' + + def __init__(self, logger: DatabaseLogger, db: DBContext): + MigrationABC.__init__(self) + self._logger = logger + self._db = db + self._cursor = db.cursor + + def upgrade(self): + self._logger.debug(__name__, 'Running upgrade') + + self._cursor.execute( + str(f""" + CREATE TABLE IF NOT EXISTS `UserMessageCountPerHour` ( + `Id` BIGINT NOT NULL AUTO_INCREMENT, + `Date` DATETIME(6) NOT NULL, + `Hour` BIGINT, + `Count` BIGINT, + `UserId` BIGINT, + `CreatedAt` DATETIME(6), + `LastModifiedAt` DATETIME(6), + PRIMARY KEY(`Id`), + FOREIGN KEY (`UserId`) REFERENCES `Users`(`UserId`) + ); + """) + ) + + def downgrade(self): + self._cursor.execute('DROP TABLE `UserMessageCountPerHour`;') + diff --git a/kdb-bot/src/bot_data/model/user_message_count_per_hour.py b/kdb-bot/src/bot_data/model/user_message_count_per_hour.py new file mode 100644 index 00000000..85a51028 --- /dev/null +++ b/kdb-bot/src/bot_data/model/user_message_count_per_hour.py @@ -0,0 +1,117 @@ +from datetime import datetime + +from cpl_core.database import TableABC + +from bot_data.model.user import User + + +class UserMessageCountPerHour(TableABC): + + def __init__( + self, + date: datetime, + hour: int, + count: int, + user: User, + created_at: datetime = None, + modified_at: datetime = None, + id=0): + self._id = id + self._date = date + self._hour = hour + self._count = count + self._user = user + + 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 + + @property + def id(self) -> int: + return self._id + + @property + def date(self) -> datetime: + return self._date + + @property + def hour(self) -> int: + return self._hour + + @property + def count(self) -> int: + return self._count + + @property + def user(self) -> User: + return self._user + + @staticmethod + def get_select_all_string() -> str: + return str(f""" + SELECT * FROM `UserMessageCountPerHour`; + """) + + @staticmethod + def get_select_by_id_string(id: int) -> str: + return str(f""" + SELECT * FROM `UserMessageCountPerHour` + WHERE `Id` = {id}; + """) + + @staticmethod + def get_select_by_user_id_string(id: int) -> str: + return str(f""" + SELECT * FROM `UserMessageCountPerHour` + WHERE `UserId` = {id}; + """) + + @staticmethod + def get_select_by_user_id_and_current_hour_string(id: int) -> str: + now = datetime.now() + date = f'{now.year}-{now.month}-{now.day}%' + + return str(f""" + SELECT * FROM `UserMessageCountPerHour` + WHERE `UserId` = {id} + AND `Date` LIKE '{date}' + AND `Hour` = {now.hour}; + """) + + @property + def insert_string(self) -> str: + return str(f""" + INSERT INTO `UserMessageCountPerHour` ( + `UserId`, `Date`, `JoinedOn`, `Count`, `CreatedAt`, `LastModifiedAt` + ) VALUES ( + {self._user.user_id}, + '{self._date}', + {self._hour}, + {self._count}, + '{self._created_at}', + '{self._modified_at}' + ); + """) + + @property + def udpate_string(self) -> str: + return str(f""" + UPDATE `UserMessageCountPerHour` + SET `Count` = '{self._count}', + `LastModifiedAt` = '{self._modified_at}' + WHERE `Id` = {self._id}; + """) + + @property + def delete_string(self) -> str: + return str(f""" + DELETE FROM `UserMessageCountPerHour` + WHERE `Id` = {self._id}; + """) + + @staticmethod + def delete_by_user_id_string(id: int) -> str: + return str(f""" + DELETE FROM `UserMessageCountPerHour` + WHERE `UserId` = {id} + """) diff --git a/kdb-bot/src/bot_data/service/user_joined_voice_channel_repository_service.py b/kdb-bot/src/bot_data/service/user_joined_voice_channel_repository_service.py new file mode 100644 index 00000000..297f75bb --- /dev/null +++ b/kdb-bot/src/bot_data/service/user_joined_voice_channel_repository_service.py @@ -0,0 +1,101 @@ +from typing import Optional + +from cpl_core.database.context import DatabaseContextABC +from cpl_query.extension import List + +from bot_core.logging.database_logger import DatabaseLogger +from bot_data.abc.user_message_count_per_hour_repository_abc import UserMessageCountPerHourRepositoryABC +from bot_data.abc.user_repository_abc import UserRepositoryABC +from bot_data.model.user_message_count_per_hour import UserMessageCountPerHour + + +class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepositoryABC): + + def __init__( + self, + logger: DatabaseLogger, + db_context: DatabaseContextABC, + users: UserRepositoryABC, + umcphs: UserMessageCountPerHourRepositoryABC, + ): + UserMessageCountPerHourRepositoryABC.__init__(self) + + self._logger = logger + self._context = db_context + self._users = users + self._umcphs = umcphs + + @staticmethod + def _get_value_from_result(value: any) -> Optional[any]: + if isinstance(value, str) and 'NULL' in value: + return None + + return value + + def _from_result(self, result: tuple) -> UserMessageCountPerHour: + return UserMessageCountPerHour( + self._get_value_from_result(result[1]), + self._get_value_from_result(result[2]), + self._get_value_from_result(result[3]), + self._users.get_user_by_id(self._get_value_from_result(result[4])), + self._get_value_from_result(result[5]), + self._get_value_from_result(result[6]), + id=self._get_value_from_result(result[0]) + ) + + def get_user_message_count_per_hours(self) -> List[UserMessageCountPerHour]: + umcphs = List(UserMessageCountPerHour) + self._logger.trace(__name__, f'Send SQL command: {UserMessageCountPerHour.get_select_all_string()}') + 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]}') + umcphs.append(self._from_result(result)) + + return umcphs + + def find_user_message_count_per_hours_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}') + results = self._context.select(sql) + if results is None or len(results) == 0: + return umcphs + + for result in results: + 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_hours_by_user_id_and_active_hour(self, user_id: int) -> List[ + Optional[UserMessageCountPerHour] + ]: + umcphs = List(UserMessageCountPerHour) + sql = UserMessageCountPerHour.get_select_by_user_id_and_current_hour_string(user_id) + self._logger.trace(__name__, f'Send SQL command: {sql}') + results = self._context.select(sql) + if results is None or len(results) == 0: + return umcphs + + for result in results: + self._logger.trace(__name__, f'Get user message count per hour with id {result[0]}') + umcphs.append(self._from_result(result)) + + return umcphs + + def add_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): + self._logger.trace(__name__, f'Send SQL command: {umcph.insert_string}') + self._context.cursor.execute(umcph.insert_string) + + def update_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): + self._logger.trace(__name__, f'Send SQL command: {umcph.udpate_string}') + self._context.cursor.execute(umcph.udpate_string) + + def delete_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): + self._logger.trace(__name__, f'Send SQL command: {umcph.delete_string}') + self._context.cursor.execute(umcph.delete_string) + + def delete_user_message_count_per_hour_by_user_id(self, user_id: int): + sql = UserMessageCountPerHour.delete_by_user_id_string(user_id) + self._logger.trace(__name__, f'Send SQL command: {sql}') + self._context.cursor.execute(sql) diff --git a/kdb-bot/src/bot_data/service/user_joined_voice_channel_service.py b/kdb-bot/src/bot_data/service/user_joined_voice_channel_service.py index 4d99065a..362228c5 100644 --- a/kdb-bot/src/bot_data/service/user_joined_voice_channel_service.py +++ b/kdb-bot/src/bot_data/service/user_joined_voice_channel_service.py @@ -4,7 +4,7 @@ from cpl_core.database.context import DatabaseContextABC from cpl_query.extension import List from bot_core.logging.database_logger import DatabaseLogger -from bot_data.abc.user_joined_voice_channel_abc import UserJoinedVoiceChannelRepositoryABC +from bot_data.abc.user_joined_voice_channel_repository_abc import UserJoinedVoiceChannelRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC from bot_data.model.user_joined_voice_channel import UserJoinedVoiceChannel diff --git a/kdb-bot/src/modules/base/command/user_group.py b/kdb-bot/src/modules/base/command/user_group.py index b0f41230..bd7ee7f3 100644 --- a/kdb-bot/src/modules/base/command/user_group.py +++ b/kdb-bot/src/modules/base/command/user_group.py @@ -17,7 +17,7 @@ from bot_core.logging.command_logger import CommandLogger from bot_core.pipes.date_time_offset_pipe import DateTimeOffsetPipe from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC -from bot_data.abc.user_joined_voice_channel_abc import UserJoinedVoiceChannelRepositoryABC +from bot_data.abc.user_joined_voice_channel_repository_abc import UserJoinedVoiceChannelRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC from modules.level.service.level_service import LevelService from modules.permission.abc.permission_service_abc import PermissionServiceABC diff --git a/kdb-bot/src/modules/base/events/base_on_voice_state_update_event.py b/kdb-bot/src/modules/base/events/base_on_voice_state_update_event.py index c9fcd41b..73ec95ce 100644 --- a/kdb-bot/src/modules/base/events/base_on_voice_state_update_event.py +++ b/kdb-bot/src/modules/base/events/base_on_voice_state_update_event.py @@ -12,7 +12,7 @@ from bot_core.helper.event_checks import EventChecks from bot_data.abc.known_user_repository_abc import KnownUserRepositoryABC from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC -from bot_data.abc.user_joined_voice_channel_abc import UserJoinedVoiceChannelRepositoryABC +from bot_data.abc.user_joined_voice_channel_repository_abc import UserJoinedVoiceChannelRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC from bot_data.model.server import Server from bot_data.model.user import User diff --git a/kdb-bot/src/modules/database/database_on_ready_event.py b/kdb-bot/src/modules/database/database_on_ready_event.py index 96f013ee..0b9515e8 100644 --- a/kdb-bot/src/modules/database/database_on_ready_event.py +++ b/kdb-bot/src/modules/database/database_on_ready_event.py @@ -12,7 +12,7 @@ from bot_core.pipes.date_time_offset_pipe import DateTimeOffsetPipe from bot_data.abc.client_repository_abc import ClientRepositoryABC from bot_data.abc.known_user_repository_abc import KnownUserRepositoryABC from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC -from bot_data.abc.user_joined_voice_channel_abc import UserJoinedVoiceChannelRepositoryABC +from bot_data.abc.user_joined_voice_channel_repository_abc import UserJoinedVoiceChannelRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC from bot_data.model.client import Client from bot_data.model.known_user import KnownUser diff --git a/kdb-bot/src/modules/stats/service/statistic_service.py b/kdb-bot/src/modules/stats/service/statistic_service.py index cee56335..9fccc1a0 100644 --- a/kdb-bot/src/modules/stats/service/statistic_service.py +++ b/kdb-bot/src/modules/stats/service/statistic_service.py @@ -10,7 +10,7 @@ from bot_data.abc.known_user_repository_abc import KnownUserRepositoryABC from bot_data.abc.level_repository_abc import LevelRepositoryABC from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC -from bot_data.abc.user_joined_voice_channel_abc import UserJoinedVoiceChannelRepositoryABC +from bot_data.abc.user_joined_voice_channel_repository_abc import UserJoinedVoiceChannelRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC from bot_data.model.auto_role import AutoRole from bot_data.model.client import Client From 1ff70af72bc14073ca61794e3b17712198ec512c Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Wed, 11 Jan 2023 20:13:09 +0100 Subject: [PATCH 3/6] Added logic to handle max message xp per hour #168 --- ...ils_service_abc.py => client_utils_abc.py} | 11 +++- .../bot_core/core_extension/core_extension.py | 4 +- .../core_extension_on_ready_event.py | 4 +- kdb-bot/src/bot_core/core_module.py | 4 +- .../bot_core/events/core_on_ready_event.py | 4 +- kdb-bot/src/bot_core/helper/command_checks.py | 6 +- kdb-bot/src/bot_core/helper/event_checks.py | 6 +- .../bot_core/service/client_utils_service.py | 64 +++++++++++++++++-- ...r_message_count_per_hour_repository_abc.py | 18 ++++-- .../user_message_count_per_hour_migration.py | 4 +- kdb-bot/src/bot_data/model/level.py | 5 ++ .../model/user_message_count_per_hour.py | 30 +++++---- ...joined_voice_channel_repository_service.py | 30 ++++----- .../auto_role/command/auto_role_group.py | 4 +- .../src/modules/base/command/afk_command.py | 4 +- .../src/modules/base/command/help_command.py | 4 +- .../src/modules/base/command/info_command.py | 4 +- .../src/modules/base/command/ping_command.py | 4 +- .../src/modules/base/command/purge_command.py | 4 +- .../src/modules/base/command/user_group.py | 4 +- .../base/events/base_on_message_event.py | 9 +++ .../base/helper/base_reaction_handler.py | 10 +++ .../src/modules/level/command/level_group.py | 4 +- .../src/modules/stats/command/stats_group.py | 4 +- .../modules/technician/command/log_command.py | 4 +- .../technician/command/restart_command.py | 4 +- .../technician/command/shutdown_command.py | 4 +- 27 files changed, 177 insertions(+), 80 deletions(-) rename kdb-bot/src/bot_core/abc/{client_utils_service_abc.py => client_utils_abc.py} (72%) diff --git a/kdb-bot/src/bot_core/abc/client_utils_service_abc.py b/kdb-bot/src/bot_core/abc/client_utils_abc.py similarity index 72% rename from kdb-bot/src/bot_core/abc/client_utils_service_abc.py rename to kdb-bot/src/bot_core/abc/client_utils_abc.py index 531e21c3..4a46ee26 100644 --- a/kdb-bot/src/bot_core/abc/client_utils_service_abc.py +++ b/kdb-bot/src/bot_core/abc/client_utils_abc.py @@ -5,9 +5,12 @@ from cpl_query.extension import List from discord.ext.commands import Context from bot_data.model.user import User +from modules.base.configuration.base_server_settings import BaseServerSettings +from bot_data.model.user import User -class ClientUtilsServiceABC(ABC): + +class ClientUtilsABC(ABC): @abstractmethod def __init__(self): pass @@ -36,5 +39,11 @@ class ClientUtilsServiceABC(ABC): @abstractmethod def get_auto_complete_list(self, _l: List, current: str, select: Callable = None) -> List: pass + @abstractmethod + def is_message_xp_count_by_hour_higher_that_max_message_count_per_hour( + self, created_at: datetime, user: User, settings: BaseServerSettings, + is_reaction: bool = False + ) -> bool: pass + @abstractmethod def get_ontime_for_user(self, user: User) -> float: pass diff --git a/kdb-bot/src/bot_core/core_extension/core_extension.py b/kdb-bot/src/bot_core/core_extension/core_extension.py index a482bcc3..fe7de819 100644 --- a/kdb-bot/src/bot_core/core_extension/core_extension.py +++ b/kdb-bot/src/bot_core/core_extension/core_extension.py @@ -3,7 +3,7 @@ from cpl_core.configuration import ConfigurationABC from cpl_core.dependency_injection import ServiceProviderABC from cpl_translation import TranslatePipe -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.configuration.feature_flags_enum import FeatureFlagsEnum from bot_core.configuration.feature_flags_settings import FeatureFlagsSettings @@ -23,7 +23,7 @@ class CoreExtension(ApplicationExtensionABC): return permissions: PermissionServiceABC = services.get_service(PermissionServiceABC) - client_utils: ClientUtilsServiceABC = services.get_service(ClientUtilsServiceABC) + client_utils: ClientUtilsABC = services.get_service(ClientUtilsABC) message_service: MessageServiceABC = services.get_service(MessageServiceABC) t: TranslatePipe = services.get_service(TranslatePipe) CommandChecks.init(permissions, client_utils, message_service, t) diff --git a/kdb-bot/src/bot_core/core_extension/core_extension_on_ready_event.py b/kdb-bot/src/bot_core/core_extension/core_extension_on_ready_event.py index fd1f42c6..8245dc40 100644 --- a/kdb-bot/src/bot_core/core_extension/core_extension_on_ready_event.py +++ b/kdb-bot/src/bot_core/core_extension/core_extension_on_ready_event.py @@ -5,7 +5,7 @@ from cpl_discord.events import OnReadyABC from cpl_discord.service import DiscordBotServiceABC from cpl_translation import TranslatePipe -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC class CoreExtensionOnReadyEvent(OnReadyABC): @@ -14,7 +14,7 @@ class CoreExtensionOnReadyEvent(OnReadyABC): self, logger: LoggerABC, bot: DiscordBotServiceABC, - client_utils: ClientUtilsServiceABC, + client_utils: ClientUtilsABC, t: TranslatePipe ): OnReadyABC.__init__(self) diff --git a/kdb-bot/src/bot_core/core_module.py b/kdb-bot/src/bot_core/core_module.py index 60d4337a..22bc5b68 100644 --- a/kdb-bot/src/bot_core/core_module.py +++ b/kdb-bot/src/bot_core/core_module.py @@ -4,7 +4,7 @@ from cpl_core.environment import ApplicationEnvironmentABC from cpl_discord.discord_event_types_enum import DiscordEventTypesEnum from cpl_discord.service.discord_collection_abc import DiscordCollectionABC -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.abc.module_abc import ModuleABC from bot_core.configuration.feature_flags_enum import FeatureFlagsEnum @@ -24,7 +24,7 @@ class CoreModule(ModuleABC): def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): services.add_transient(MessageServiceABC, MessageService) - services.add_transient(ClientUtilsServiceABC, ClientUtilsService) + services.add_transient(ClientUtilsABC, ClientUtilsService) # pipes services.add_transient(DateTimeOffsetPipe) diff --git a/kdb-bot/src/bot_core/events/core_on_ready_event.py b/kdb-bot/src/bot_core/events/core_on_ready_event.py index 540f9d1f..2a694962 100644 --- a/kdb-bot/src/bot_core/events/core_on_ready_event.py +++ b/kdb-bot/src/bot_core/events/core_on_ready_event.py @@ -3,7 +3,7 @@ from cpl_discord.events import OnReadyABC from cpl_discord.service import DiscordBotServiceABC from cpl_translation import TranslatePipe -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC class CoreOnReadyEvent(OnReadyABC): @@ -12,7 +12,7 @@ class CoreOnReadyEvent(OnReadyABC): self, logger: LoggerABC, bot: DiscordBotServiceABC, - client_utils: ClientUtilsServiceABC, + client_utils: ClientUtilsABC, t: TranslatePipe, ): OnReadyABC.__init__(self) diff --git a/kdb-bot/src/bot_core/helper/command_checks.py b/kdb-bot/src/bot_core/helper/command_checks.py index 6bb3fa30..2716b616 100644 --- a/kdb-bot/src/bot_core/helper/command_checks.py +++ b/kdb-bot/src/bot_core/helper/command_checks.py @@ -4,7 +4,7 @@ from cpl_translation import TranslatePipe from discord.ext import commands from discord.ext.commands import Context -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.exception.check_error import CheckError from modules.permission.abc.permission_service_abc import PermissionServiceABC @@ -12,7 +12,7 @@ from modules.permission.abc.permission_service_abc import PermissionServiceABC class CommandChecks: _permissions: Optional[PermissionServiceABC] = None - _client_utils: Optional[ClientUtilsServiceABC] = None + _client_utils: Optional[ClientUtilsABC] = None _message_service: Optional[MessageServiceABC] = None _t: Optional[TranslatePipe] = None @@ -20,7 +20,7 @@ class CommandChecks: def init( cls, permissions: PermissionServiceABC, - client_utils: ClientUtilsServiceABC, + client_utils: ClientUtilsABC, message_service: MessageServiceABC, translate: TranslatePipe, ): diff --git a/kdb-bot/src/bot_core/helper/event_checks.py b/kdb-bot/src/bot_core/helper/event_checks.py index 0eba341c..c6d340e9 100644 --- a/kdb-bot/src/bot_core/helper/event_checks.py +++ b/kdb-bot/src/bot_core/helper/event_checks.py @@ -4,19 +4,19 @@ from cpl_translation import TranslatePipe from discord.ext import commands from discord.ext.commands import Context -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.exception.check_error import CheckError from modules.permission.abc.permission_service_abc import PermissionServiceABC class EventChecks: - _client_utils: Optional[ClientUtilsServiceABC] = None + _client_utils: Optional[ClientUtilsABC] = None @classmethod def init( cls, - client_utils: ClientUtilsServiceABC, + client_utils: ClientUtilsABC, ): cls._client_utils = client_utils diff --git a/kdb-bot/src/bot_core/service/client_utils_service.py b/kdb-bot/src/bot_core/service/client_utils_service.py index 48d87d84..5df4a062 100644 --- a/kdb-bot/src/bot_core/service/client_utils_service.py +++ b/kdb-bot/src/bot_core/service/client_utils_service.py @@ -4,43 +4,50 @@ import discord from cpl_core.configuration import ConfigurationABC from cpl_core.database.context import DatabaseContextABC from cpl_core.logging import LoggerABC - +from cpl_core.time import TimeFormatSettings from cpl_discord.service import DiscordBotServiceABC from cpl_query.extension import List from cpl_translation import TranslatePipe -from discord import app_commands from discord.ext.commands import Context -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.configuration.feature_flags_enum import FeatureFlagsEnum from bot_core.configuration.feature_flags_settings import FeatureFlagsSettings from bot_data.abc.client_repository_abc import ClientRepositoryABC from bot_data.abc.server_repository_abc import ServerRepositoryABC +from bot_data.abc.user_message_count_per_hour_repository_abc import UserMessageCountPerHourRepositoryABC +from bot_data.model.user import User +from bot_data.model.user_message_count_per_hour import UserMessageCountPerHour +from modules.base.configuration.base_server_settings import BaseServerSettings from bot_data.abc.user_joined_voice_channel_abc import UserJoinedVoiceChannelRepositoryABC from bot_data.model.user import User -class ClientUtilsService(ClientUtilsServiceABC): +class ClientUtilsService(ClientUtilsABC): def __init__( self, config: ConfigurationABC, logger: LoggerABC, + time_format: TimeFormatSettings, bot: DiscordBotServiceABC, servers: ServerRepositoryABC, clients: ClientRepositoryABC, + umcphs: UserMessageCountPerHourRepositoryABC, user_joined_vc: UserJoinedVoiceChannelRepositoryABC, message_service: MessageServiceABC, db: DatabaseContextABC, t: TranslatePipe, feature_flags: FeatureFlagsSettings ): - ClientUtilsServiceABC.__init__(self) + ClientUtilsABC.__init__(self) self._config = config self._logger = logger + self._time_format = time_format self._bot = bot self._servers = servers + self._umcphs = umcphs self._clients = clients self._user_joined_voice_channel = user_joined_vc self._message_service = message_service @@ -84,6 +91,8 @@ class ClientUtilsService(ClientUtilsServiceABC): async def check_if_bot_is_ready_yet_and_respond(self, ctx: Context) -> bool: result = await self.check_if_bot_is_ready_yet() if not result: + await self._message_service.send_ctx_msg(ctx, self._t.transform('common.errors.bot_not_ready_yet'), + without_tracking=True) await self._message_service.send_ctx_msg( ctx, self._t.transform('common.errors.bot_not_ready_yet'), @@ -115,6 +124,51 @@ class ClientUtilsService(ClientUtilsServiceABC): return _l.take(25) + def is_message_xp_count_by_hour_higher_that_max_message_count_per_hour( + self, + created_at: datetime, + user: User, + settings: BaseServerSettings, + is_reaction: bool = False + ) -> bool: + umcph = None + try: + 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( + created_at.strftime(self._time_format.date_time_format), + created_at.hour, + 0, + user + )) + + self._db.save_changes() + + 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__, f'Cannot add user message count per hour with id {umcph.id}', e) + return False + + try: + if is_reaction: + umcph.xp_count += settings.xp_per_reaction + else: + umcph.xp_count += settings.xp_per_reaction + + self._umcphs.update_user_message_count_per_hour(umcph) + self._db.save_changes() + except Exception as e: + self._logger.error(__name__, f'Cannot update user message count per hour with id {umcph.id}', e) + return False + + if umcph.xp_count is None: + return False + + return umcph.xp_count > settings.max_message_xp_per_hour + 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) \ .where(lambda x: x.leaved_on is not None and x.joined_on is not None) \ diff --git a/kdb-bot/src/bot_data/abc/user_message_count_per_hour_repository_abc.py b/kdb-bot/src/bot_data/abc/user_message_count_per_hour_repository_abc.py index e5610c63..20a34cbe 100644 --- a/kdb-bot/src/bot_data/abc/user_message_count_per_hour_repository_abc.py +++ b/kdb-bot/src/bot_data/abc/user_message_count_per_hour_repository_abc.py @@ -1,4 +1,5 @@ from abc import ABC, abstractmethod +from datetime import datetime from typing import Optional from cpl_query.extension import List @@ -10,22 +11,27 @@ class UserMessageCountPerHourRepositoryABC(ABC): @abstractmethod def __init__(self): pass - + @abstractmethod def get_user_message_count_per_hours(self) -> List[UserMessageCountPerHour]: pass @abstractmethod - def find_user_message_count_per_hours_by_user_id(self, user_id: int) -> List[Optional[UserMessageCountPerHour]]: pass + def find_user_message_count_per_hour_by_user_id(self, user_id: int) -> Optional[UserMessageCountPerHour]: pass @abstractmethod - def find_user_message_count_per_hours_by_user_id_and_active_hour(self, user_id: int) -> List[Optional[UserMessageCountPerHour]]: pass - + def get_user_message_count_per_hour_by_user_id_and_date(self, user_id: int, date: datetime) -> \ + Optional[UserMessageCountPerHour]: pass + + @abstractmethod + def find_user_message_count_per_hour_by_user_id_and_date(self, user_id: int, date: datetime) -> \ + Optional[UserMessageCountPerHour]: pass + @abstractmethod def add_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): pass - + @abstractmethod def update_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): pass - + @abstractmethod def delete_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): pass diff --git a/kdb-bot/src/bot_data/migration/user_message_count_per_hour_migration.py b/kdb-bot/src/bot_data/migration/user_message_count_per_hour_migration.py index 2e67d996..83f12475 100644 --- a/kdb-bot/src/bot_data/migration/user_message_count_per_hour_migration.py +++ b/kdb-bot/src/bot_data/migration/user_message_count_per_hour_migration.py @@ -19,9 +19,9 @@ class UserMessageCountPerHourMigration(MigrationABC): str(f""" CREATE TABLE IF NOT EXISTS `UserMessageCountPerHour` ( `Id` BIGINT NOT NULL AUTO_INCREMENT, - `Date` DATETIME(6) NOT NULL, + `Date` VARCHAR(255) NOT NULL, `Hour` BIGINT, - `Count` BIGINT, + `XPCount` BIGINT, `UserId` BIGINT, `CreatedAt` DATETIME(6), `LastModifiedAt` DATETIME(6), diff --git a/kdb-bot/src/bot_data/model/level.py b/kdb-bot/src/bot_data/model/level.py index 9cfc63f1..c3a9509b 100644 --- a/kdb-bot/src/bot_data/model/level.py +++ b/kdb-bot/src/bot_data/model/level.py @@ -29,6 +29,7 @@ class Level(TableABC): @name.setter def name(self, value: str): + self._modified_at = datetime.now().isoformat() self._name = value @property @@ -37,6 +38,7 @@ class Level(TableABC): @color.setter def color(self, value: str): + self._modified_at = datetime.now().isoformat() self._color = value @property @@ -45,6 +47,7 @@ class Level(TableABC): @min_xp.setter def min_xp(self, value: int): + self._modified_at = datetime.now().isoformat() self._min_xp = value @property @@ -53,6 +56,7 @@ class Level(TableABC): @permissions.setter def permissions(self, value: int): + self._modified_at = datetime.now().isoformat() self._permissions = value @property @@ -61,6 +65,7 @@ class Level(TableABC): @server.setter def server(self, value: Server): + self._modified_at = datetime.now().isoformat() self._server = value @staticmethod diff --git a/kdb-bot/src/bot_data/model/user_message_count_per_hour.py b/kdb-bot/src/bot_data/model/user_message_count_per_hour.py index 85a51028..218908e3 100644 --- a/kdb-bot/src/bot_data/model/user_message_count_per_hour.py +++ b/kdb-bot/src/bot_data/model/user_message_count_per_hour.py @@ -9,9 +9,9 @@ class UserMessageCountPerHour(TableABC): def __init__( self, - date: datetime, + date: str, hour: int, - count: int, + xp_count: int, user: User, created_at: datetime = None, modified_at: datetime = None, @@ -19,7 +19,7 @@ class UserMessageCountPerHour(TableABC): self._id = id self._date = date self._hour = hour - self._count = count + self._xp_count = xp_count self._user = user TableABC.__init__(self) @@ -39,8 +39,13 @@ class UserMessageCountPerHour(TableABC): return self._hour @property - def count(self) -> int: - return self._count + def xp_count(self) -> int: + return self._xp_count + + @xp_count.setter + def xp_count(self, value: int): + self._modified_at = datetime.now().isoformat() + self._xp_count = value @property def user(self) -> User: @@ -67,27 +72,26 @@ class UserMessageCountPerHour(TableABC): """) @staticmethod - def get_select_by_user_id_and_current_hour_string(id: int) -> str: - now = datetime.now() - date = f'{now.year}-{now.month}-{now.day}%' + def get_select_by_user_id_and_date_string(id: int, date: datetime) -> str: + date_str = f'{str(date.year).zfill(4)}-{str(date.month).zfill(2)}-{str(date.day).zfill(2)}%' return str(f""" SELECT * FROM `UserMessageCountPerHour` WHERE `UserId` = {id} - AND `Date` LIKE '{date}' - AND `Hour` = {now.hour}; + AND `Date` LIKE '{date_str}' + AND `Hour` = {date.hour}; """) @property def insert_string(self) -> str: return str(f""" INSERT INTO `UserMessageCountPerHour` ( - `UserId`, `Date`, `JoinedOn`, `Count`, `CreatedAt`, `LastModifiedAt` + `UserId`, `Date`, `Hour`, `XPCount`, `CreatedAt`, `LastModifiedAt` ) VALUES ( {self._user.user_id}, '{self._date}', {self._hour}, - {self._count}, + {self._xp_count}, '{self._created_at}', '{self._modified_at}' ); @@ -97,7 +101,7 @@ class UserMessageCountPerHour(TableABC): def udpate_string(self) -> str: return str(f""" UPDATE `UserMessageCountPerHour` - SET `Count` = '{self._count}', + SET `XPCount` = '{self._xp_count}', `LastModifiedAt` = '{self._modified_at}' WHERE `Id` = {self._id}; """) diff --git a/kdb-bot/src/bot_data/service/user_joined_voice_channel_repository_service.py b/kdb-bot/src/bot_data/service/user_joined_voice_channel_repository_service.py index 297f75bb..5389366c 100644 --- a/kdb-bot/src/bot_data/service/user_joined_voice_channel_repository_service.py +++ b/kdb-bot/src/bot_data/service/user_joined_voice_channel_repository_service.py @@ -1,3 +1,4 @@ +from datetime import datetime from typing import Optional from cpl_core.database.context import DatabaseContextABC @@ -16,14 +17,12 @@ class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepository logger: DatabaseLogger, db_context: DatabaseContextABC, users: UserRepositoryABC, - umcphs: UserMessageCountPerHourRepositoryABC, ): UserMessageCountPerHourRepositoryABC.__init__(self) self._logger = logger self._context = db_context self._users = users - self._umcphs = umcphs @staticmethod def _get_value_from_result(value: any) -> Optional[any]: @@ -53,7 +52,7 @@ class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepository return umcphs - def find_user_message_count_per_hours_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}') @@ -67,21 +66,22 @@ class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepository return umcphs - def find_user_message_count_per_hours_by_user_id_and_active_hour(self, user_id: int) -> List[ - Optional[UserMessageCountPerHour] - ]: - umcphs = List(UserMessageCountPerHour) - sql = UserMessageCountPerHour.get_select_by_user_id_and_current_hour_string(user_id) + def get_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) self._logger.trace(__name__, f'Send SQL command: {sql}') - results = self._context.select(sql) - if results is None or len(results) == 0: - return umcphs + result = self._context.select(sql)[0] + return self._from_result(result) - for result in results: - self._logger.trace(__name__, f'Get user message count per hour with id {result[0]}') - umcphs.append(self._from_result(result)) + 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) + self._logger.trace(__name__, f'Send SQL command: {sql}') + result = self._context.select(sql) + if result is None or len(result) == 0: + return None - return umcphs + return self._from_result(result[0]) def add_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): self._logger.trace(__name__, f'Send SQL command: {umcph.insert_string}') diff --git a/kdb-bot/src/modules/auto_role/command/auto_role_group.py b/kdb-bot/src/modules/auto_role/command/auto_role_group.py index fd636bf3..e90995e2 100644 --- a/kdb-bot/src/modules/auto_role/command/auto_role_group.py +++ b/kdb-bot/src/modules/auto_role/command/auto_role_group.py @@ -11,7 +11,7 @@ from discord import app_commands, Guild from discord.ext import commands from discord.ext.commands import Context -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.helper.command_checks import CommandChecks from bot_core.logging.command_logger import CommandLogger @@ -29,7 +29,7 @@ class AutoRoleGroup(DiscordCommandABC): logger: CommandLogger, message_service: MessageServiceABC, bot: DiscordBotServiceABC, - client_utils: ClientUtilsServiceABC, + client_utils: ClientUtilsABC, translate: TranslatePipe, servers: ServerRepositoryABC, auto_roles: AutoRoleRepositoryABC, diff --git a/kdb-bot/src/modules/base/command/afk_command.py b/kdb-bot/src/modules/base/command/afk_command.py index 234c24fe..ffa7a6cb 100644 --- a/kdb-bot/src/modules/base/command/afk_command.py +++ b/kdb-bot/src/modules/base/command/afk_command.py @@ -6,7 +6,7 @@ from discord import VoiceChannel from discord.ext import commands from discord.ext.commands import Context -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.helper.command_checks import CommandChecks from bot_core.logging.command_logger import CommandLogger @@ -21,7 +21,7 @@ class AFKCommand(DiscordCommandABC): config: ConfigurationABC, message_service: MessageServiceABC, bot: DiscordBotServiceABC, - client_utils: ClientUtilsServiceABC, + client_utils: ClientUtilsABC, translate: TranslatePipe ): DiscordCommandABC.__init__(self) diff --git a/kdb-bot/src/modules/base/command/help_command.py b/kdb-bot/src/modules/base/command/help_command.py index dd252740..ddbafd73 100644 --- a/kdb-bot/src/modules/base/command/help_command.py +++ b/kdb-bot/src/modules/base/command/help_command.py @@ -8,7 +8,7 @@ from discord import app_commands from discord.ext import commands from discord.ext.commands import Context -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.helper.command_checks import CommandChecks from bot_core.logging.command_logger import CommandLogger @@ -23,7 +23,7 @@ class HelpCommand(DiscordCommandABC): logger: CommandLogger, message_service: MessageServiceABC, bot: DiscordBotServiceABC, - client_utils: ClientUtilsServiceABC + client_utils: ClientUtilsABC ): DiscordCommandABC.__init__(self) diff --git a/kdb-bot/src/modules/base/command/info_command.py b/kdb-bot/src/modules/base/command/info_command.py index 974bc491..b9152aaf 100644 --- a/kdb-bot/src/modules/base/command/info_command.py +++ b/kdb-bot/src/modules/base/command/info_command.py @@ -9,7 +9,7 @@ from discord.ext import commands from discord.ext.commands import Context import bot -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.helper.command_checks import CommandChecks from bot_core.logging.command_logger import CommandLogger @@ -23,7 +23,7 @@ class InfoCommand(DiscordCommandABC): logger: CommandLogger, message_service: MessageServiceABC, bot: DiscordBotServiceABC, - client_utils: ClientUtilsServiceABC, + client_utils: ClientUtilsABC, translate: TranslatePipe ): DiscordCommandABC.__init__(self) diff --git a/kdb-bot/src/modules/base/command/ping_command.py b/kdb-bot/src/modules/base/command/ping_command.py index 7633d8a0..77514716 100644 --- a/kdb-bot/src/modules/base/command/ping_command.py +++ b/kdb-bot/src/modules/base/command/ping_command.py @@ -5,7 +5,7 @@ from cpl_translation import TranslatePipe from discord.ext import commands from discord.ext.commands import Context -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.helper.command_checks import CommandChecks from bot_core.logging.command_logger import CommandLogger @@ -22,7 +22,7 @@ class PingCommand(DiscordCommandABC): logger: CommandLogger, message_service: MessageServiceABC, bot: DiscordBotServiceABC, - client_utils: ClientUtilsServiceABC, + client_utils: ClientUtilsABC, translate: TranslatePipe, permissions: PermissionServiceABC, base_helper: BaseHelperABC, diff --git a/kdb-bot/src/modules/base/command/purge_command.py b/kdb-bot/src/modules/base/command/purge_command.py index 8ec78eff..ab08883e 100644 --- a/kdb-bot/src/modules/base/command/purge_command.py +++ b/kdb-bot/src/modules/base/command/purge_command.py @@ -6,7 +6,7 @@ from cpl_translation import TranslatePipe from discord.ext import commands from discord.ext.commands import Context -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.configuration.server_settings import ServerSettings from bot_core.helper.command_checks import CommandChecks @@ -22,7 +22,7 @@ class PurgeCommand(DiscordCommandABC): config: ConfigurationABC, message_service: MessageServiceABC, permissions: PermissionServiceABC, - client_utils: ClientUtilsServiceABC, + client_utils: ClientUtilsABC, translate: TranslatePipe ): DiscordCommandABC.__init__(self) diff --git a/kdb-bot/src/modules/base/command/user_group.py b/kdb-bot/src/modules/base/command/user_group.py index bd7ee7f3..c38a7898 100644 --- a/kdb-bot/src/modules/base/command/user_group.py +++ b/kdb-bot/src/modules/base/command/user_group.py @@ -10,7 +10,7 @@ from discord import app_commands from discord.ext import commands from discord.ext.commands import Context -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.helper.command_checks import CommandChecks from bot_core.logging.command_logger import CommandLogger @@ -31,7 +31,7 @@ class UserGroup(DiscordCommandABC): logger: CommandLogger, message_service: MessageServiceABC, bot: DiscordBotServiceABC, - client_utils: ClientUtilsServiceABC, + client_utils: ClientUtilsABC, permissions: PermissionServiceABC, servers: ServerRepositoryABC, db: DatabaseContextABC, diff --git a/kdb-bot/src/modules/base/events/base_on_message_event.py b/kdb-bot/src/modules/base/events/base_on_message_event.py index 2d562c66..d9a19641 100644 --- a/kdb-bot/src/modules/base/events/base_on_message_event.py +++ b/kdb-bot/src/modules/base/events/base_on_message_event.py @@ -8,6 +8,7 @@ from cpl_discord.service import DiscordBotServiceABC from bot_core.helper.event_checks import EventChecks from bot_core.helper.log_message_helper import LogMessageHelper from bot_core.logging.message_logger import MessageLogger +from bot_core.service.client_utils_service import ClientUtilsService from bot_data.abc.client_repository_abc import ClientRepositoryABC from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC @@ -22,6 +23,7 @@ class BaseOnMessageEvent(OnMessageABC): self, logger: MessageLogger, bhs: BaseHelperABC, + client_utils: ClientUtilsService, db: DatabaseContextABC, bot: DiscordBotServiceABC, users: UserRepositoryABC, @@ -31,6 +33,8 @@ class BaseOnMessageEvent(OnMessageABC): OnMessageABC.__init__(self) self._logger = logger self._base_helper = bhs + self._client_utils = client_utils + self._bot = bot self._db = db self._bot = bot self._users = users @@ -64,6 +68,9 @@ class BaseOnMessageEvent(OnMessageABC): return settings: BaseServerSettings = self._base_helper.get_config(message.guild.id) + if self._client_utils.is_message_xp_count_by_hour_higher_that_max_message_count_per_hour(message.created_at, user, settings): + return + old_xp = user.xp user.xp += settings.xp_per_message self._users.update_user(user) @@ -71,6 +78,8 @@ class BaseOnMessageEvent(OnMessageABC): 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): self._logger.debug(__name__, f'Module {type(self)} started') diff --git a/kdb-bot/src/modules/base/helper/base_reaction_handler.py b/kdb-bot/src/modules/base/helper/base_reaction_handler.py index a5fd0099..6086206f 100644 --- a/kdb-bot/src/modules/base/helper/base_reaction_handler.py +++ b/kdb-bot/src/modules/base/helper/base_reaction_handler.py @@ -1,8 +1,11 @@ +from datetime import datetime + from cpl_core.database.context import DatabaseContextABC from cpl_core.logging import LoggerABC from cpl_discord.service import DiscordBotServiceABC from discord import RawReactionActionEvent +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.helper.log_message_helper import LogMessageHelper from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC @@ -19,6 +22,7 @@ class BaseReactionHandler: servers: ServerRepositoryABC, users: UserRepositoryABC, base_helper: BaseHelperABC, + client_utils: ClientUtilsABC, db: DatabaseContextABC, ): self._logger = logger @@ -26,6 +30,7 @@ class BaseReactionHandler: self._servers = servers self._users = users self._base_helper = base_helper + self._client_utils = client_utils self._db = db async def handle(self, payload: RawReactionActionEvent, r_type=None) -> None: @@ -59,6 +64,11 @@ class BaseReactionHandler: settings: BaseServerSettings = self._base_helper.get_config(guild.id) if r_type == 'add': + if self._client_utils.is_message_xp_count_by_hour_higher_that_max_message_count_per_hour( + datetime.now(), user, settings, is_reaction=True + ): + return + user.xp += settings.xp_per_reaction self._users.update_user(user) self._db.save_changes() diff --git a/kdb-bot/src/modules/level/command/level_group.py b/kdb-bot/src/modules/level/command/level_group.py index e4fbdbab..cd3f0b3c 100644 --- a/kdb-bot/src/modules/level/command/level_group.py +++ b/kdb-bot/src/modules/level/command/level_group.py @@ -10,7 +10,7 @@ from discord import app_commands from discord.ext import commands from discord.ext.commands import Context -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.helper.command_checks import CommandChecks from bot_core.logging.command_logger import CommandLogger @@ -30,7 +30,7 @@ class LevelGroup(DiscordCommandABC): logger: CommandLogger, message_service: MessageServiceABC, bot: DiscordBotServiceABC, - client_utils: ClientUtilsServiceABC, + client_utils: ClientUtilsABC, permission_service: PermissionServiceABC, translate: TranslatePipe, db: DatabaseContextABC, diff --git a/kdb-bot/src/modules/stats/command/stats_group.py b/kdb-bot/src/modules/stats/command/stats_group.py index b035e54a..21abc20e 100644 --- a/kdb-bot/src/modules/stats/command/stats_group.py +++ b/kdb-bot/src/modules/stats/command/stats_group.py @@ -8,7 +8,7 @@ from discord import app_commands from discord.ext import commands from discord.ext.commands import Context -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.helper.command_checks import CommandChecks from bot_core.logging.command_logger import CommandLogger @@ -25,7 +25,7 @@ class StatsGroup(DiscordCommandABC): self, logger: CommandLogger, message_service: MessageServiceABC, - client_utils: ClientUtilsServiceABC, + client_utils: ClientUtilsABC, translate: TranslatePipe, permission_service: PermissionServiceABC, statistic: StatisticService, diff --git a/kdb-bot/src/modules/technician/command/log_command.py b/kdb-bot/src/modules/technician/command/log_command.py index 3988ce63..4ac83eeb 100644 --- a/kdb-bot/src/modules/technician/command/log_command.py +++ b/kdb-bot/src/modules/technician/command/log_command.py @@ -13,7 +13,7 @@ from cpl_translation import TranslatePipe from discord.ext import commands from discord.ext.commands import Context -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.custom_file_logger_abc import CustomFileLoggerABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.helper.command_checks import CommandChecks @@ -29,7 +29,7 @@ class LogCommand(DiscordCommandABC): logging_settings: LoggingSettings, services: ServiceProviderABC, message_service: MessageServiceABC, - client_utils: ClientUtilsServiceABC, + client_utils: ClientUtilsABC, translate: TranslatePipe, permissions: PermissionServiceABC, time_format: TimeFormatSettings, diff --git a/kdb-bot/src/modules/technician/command/restart_command.py b/kdb-bot/src/modules/technician/command/restart_command.py index 0a14e41b..24d085a6 100644 --- a/kdb-bot/src/modules/technician/command/restart_command.py +++ b/kdb-bot/src/modules/technician/command/restart_command.py @@ -7,7 +7,7 @@ from cpl_translation import TranslatePipe from discord.ext import commands from discord.ext.commands import Context -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.configuration.bot_settings import BotSettings from bot_core.helper.command_checks import CommandChecks @@ -23,7 +23,7 @@ class RestartCommand(DiscordCommandABC): config: ConfigurationABC, message_service: MessageServiceABC, bot: DiscordBotServiceABC, - client_utils: ClientUtilsServiceABC, + client_utils: ClientUtilsABC, translate: TranslatePipe, permissions: PermissionServiceABC, settings: BotSettings diff --git a/kdb-bot/src/modules/technician/command/shutdown_command.py b/kdb-bot/src/modules/technician/command/shutdown_command.py index f81d127a..5e19794e 100644 --- a/kdb-bot/src/modules/technician/command/shutdown_command.py +++ b/kdb-bot/src/modules/technician/command/shutdown_command.py @@ -8,7 +8,7 @@ from cpl_translation import TranslatePipe from discord.ext import commands from discord.ext.commands import Context -from bot_core.abc.client_utils_service_abc import ClientUtilsServiceABC +from bot_core.abc.client_utils_abc import ClientUtilsABC from bot_core.abc.message_service_abc import MessageServiceABC from bot_core.configuration.bot_settings import BotSettings from bot_core.helper.command_checks import CommandChecks @@ -24,7 +24,7 @@ class ShutdownCommand(DiscordCommandABC): config: ConfigurationABC, message_service: MessageServiceABC, bot: DiscordBotServiceABC, - client_utils: ClientUtilsServiceABC, + client_utils: ClientUtilsABC, translate: TranslatePipe, permissions: PermissionServiceABC, settings: BotSettings From d91ff392ca53e038673ad930d3178c423bd820d8 Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Fri, 13 Jan 2023 22:27:05 +0100 Subject: [PATCH 4/6] Fixed is_message_xp_count_by_hour_higher_that_max_message_count_per_hour #168 --- kdb-bot/src/bot_core/service/client_utils_service.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/kdb-bot/src/bot_core/service/client_utils_service.py b/kdb-bot/src/bot_core/service/client_utils_service.py index 5df4a062..94adbaf3 100644 --- a/kdb-bot/src/bot_core/service/client_utils_service.py +++ b/kdb-bot/src/bot_core/service/client_utils_service.py @@ -1,6 +1,7 @@ from typing import Callable import discord +from bot_data.abc.user_joined_voice_channel_abc import UserJoinedVoiceChannelRepositoryABC from cpl_core.configuration import ConfigurationABC from cpl_core.database.context import DatabaseContextABC from cpl_core.logging import LoggerABC @@ -20,8 +21,6 @@ from bot_data.abc.user_message_count_per_hour_repository_abc import UserMessageC from bot_data.model.user import User from bot_data.model.user_message_count_per_hour import UserMessageCountPerHour from modules.base.configuration.base_server_settings import BaseServerSettings -from bot_data.abc.user_joined_voice_channel_abc import UserJoinedVoiceChannelRepositoryABC -from bot_data.model.user import User class ClientUtilsService(ClientUtilsABC): @@ -156,7 +155,7 @@ class ClientUtilsService(ClientUtilsABC): if is_reaction: umcph.xp_count += settings.xp_per_reaction else: - umcph.xp_count += settings.xp_per_reaction + umcph.xp_count += settings.xp_per_message self._umcphs.update_user_message_count_per_hour(umcph) self._db.save_changes() From 84f8690bdf6ca23cbb552cc71e98e724790ae0b4 Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Fri, 13 Jan 2023 22:35:46 +0100 Subject: [PATCH 5/6] Updated migration #168 --- .../migration/user_message_count_per_hour_migration.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/kdb-bot/src/bot_data/migration/user_message_count_per_hour_migration.py b/kdb-bot/src/bot_data/migration/user_message_count_per_hour_migration.py index 83f12475..8913a4aa 100644 --- a/kdb-bot/src/bot_data/migration/user_message_count_per_hour_migration.py +++ b/kdb-bot/src/bot_data/migration/user_message_count_per_hour_migration.py @@ -19,7 +19,7 @@ class UserMessageCountPerHourMigration(MigrationABC): str(f""" CREATE TABLE IF NOT EXISTS `UserMessageCountPerHour` ( `Id` BIGINT NOT NULL AUTO_INCREMENT, - `Date` VARCHAR(255) NOT NULL, + `Date` DATETIME(6) NOT NULL, `Hour` BIGINT, `XPCount` BIGINT, `UserId` BIGINT, @@ -33,4 +33,3 @@ class UserMessageCountPerHourMigration(MigrationABC): def downgrade(self): self._cursor.execute('DROP TABLE `UserMessageCountPerHour`;') - From 59fc1e1442c8f9a656e195ab6cfaff62923a3a4e Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Fri, 13 Jan 2023 22:43:30 +0100 Subject: [PATCH 6/6] Fixed naming error #168 --- kdb-bot/src/bot_data/data_module.py | 4 +- ...joined_voice_channel_repository_service.py | 178 ++++++++++-------- .../user_joined_voice_channel_service.py | 127 ------------- ...ssage_count_per_hour_repository_service.py | 101 ++++++++++ 4 files changed, 205 insertions(+), 205 deletions(-) delete mode 100644 kdb-bot/src/bot_data/service/user_joined_voice_channel_service.py create mode 100644 kdb-bot/src/bot_data/service/user_message_count_per_hour_repository_service.py diff --git a/kdb-bot/src/bot_data/data_module.py b/kdb-bot/src/bot_data/data_module.py index 0fc82a26..daa56568 100644 --- a/kdb-bot/src/bot_data/data_module.py +++ b/kdb-bot/src/bot_data/data_module.py @@ -25,8 +25,8 @@ from bot_data.service.seeder_service import SeederService from bot_data.service.server_repository_service import ServerRepositoryService from bot_data.service.statistic_repository_service import StatisticRepositoryService from bot_data.service.user_joined_server_repository_service import UserJoinedServerRepositoryService -from bot_data.service.user_joined_voice_channel_repository_service import UserMessageCountPerHourRepositoryService -from bot_data.service.user_joined_voice_channel_service import UserJoinedVoiceChannelRepositoryService +from bot_data.service.user_joined_voice_channel_repository_service import UserJoinedVoiceChannelRepositoryService +from bot_data.service.user_message_count_per_hour_repository_service import UserMessageCountPerHourRepositoryService from bot_data.service.user_repository_service import UserRepositoryService diff --git a/kdb-bot/src/bot_data/service/user_joined_voice_channel_repository_service.py b/kdb-bot/src/bot_data/service/user_joined_voice_channel_repository_service.py index 5389366c..362228c5 100644 --- a/kdb-bot/src/bot_data/service/user_joined_voice_channel_repository_service.py +++ b/kdb-bot/src/bot_data/service/user_joined_voice_channel_repository_service.py @@ -1,101 +1,127 @@ -from datetime import datetime from typing import Optional from cpl_core.database.context import DatabaseContextABC from cpl_query.extension import List from bot_core.logging.database_logger import DatabaseLogger -from bot_data.abc.user_message_count_per_hour_repository_abc import UserMessageCountPerHourRepositoryABC +from bot_data.abc.user_joined_voice_channel_repository_abc import UserJoinedVoiceChannelRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC -from bot_data.model.user_message_count_per_hour import UserMessageCountPerHour +from bot_data.model.user_joined_voice_channel import UserJoinedVoiceChannel -class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepositoryABC): - - def __init__( - self, - logger: DatabaseLogger, - db_context: DatabaseContextABC, - users: UserRepositoryABC, - ): - UserMessageCountPerHourRepositoryABC.__init__(self) +class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryABC): + def __init__(self, logger: DatabaseLogger, db_context: DatabaseContextABC, users: UserRepositoryABC): self._logger = logger self._context = db_context + self._users = users - @staticmethod - def _get_value_from_result(value: any) -> Optional[any]: - if isinstance(value, str) and 'NULL' in value: - return None + UserJoinedVoiceChannelRepositoryABC.__init__(self) - return value + def get_user_joined_voice_channels(self) -> List[UserJoinedVoiceChannel]: + joins = List(UserJoinedVoiceChannel) + self._logger.trace(__name__, f'Send SQL command: {UserJoinedVoiceChannel.get_select_all_string()}') + 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]}') + joins.append(UserJoinedVoiceChannel( + self._users.get_user_by_id(result[1]), + result[2], + result[3], + result[4], + result[5], + id=result[0] + )) - def _from_result(self, result: tuple) -> UserMessageCountPerHour: - return UserMessageCountPerHour( - self._get_value_from_result(result[1]), - self._get_value_from_result(result[2]), - self._get_value_from_result(result[3]), - self._users.get_user_by_id(self._get_value_from_result(result[4])), - self._get_value_from_result(result[5]), - self._get_value_from_result(result[6]), - id=self._get_value_from_result(result[0]) + return joins + + def get_user_joined_voice_channel_by_id(self, id: int) -> UserJoinedVoiceChannel: + self._logger.trace(__name__, f'Send SQL command: {UserJoinedVoiceChannel.get_select_by_id_string(id)}') + result = self._context.select(UserJoinedVoiceChannel.get_select_by_id_string(id))[0] + return UserJoinedVoiceChannel( + self._users.get_user_by_id(result[1]), + result[2], + result[3], + result[4], + result[5], + id=result[0] ) - - def get_user_message_count_per_hours(self) -> List[UserMessageCountPerHour]: - umcphs = List(UserMessageCountPerHour) - self._logger.trace(__name__, f'Send SQL command: {UserMessageCountPerHour.get_select_all_string()}') - results = self._context.select(UserMessageCountPerHour.get_select_all_string()) + + 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)) for result in results: - 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]]: - umcphs = List(UserMessageCountPerHour) - sql = UserMessageCountPerHour.get_select_by_user_id_string(user_id) - self._logger.trace(__name__, f'Send SQL command: {sql}') - results = self._context.select(sql) - if results is None or len(results) == 0: - return umcphs - - for result in results: - self._logger.trace(__name__, f'Get user message count per hour with id {result[0]}') - umcphs.append(self._from_result(result)) - - return umcphs - - def get_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) - self._logger.trace(__name__, f'Send SQL command: {sql}') - result = self._context.select(sql)[0] - return self._from_result(result) - - 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) - self._logger.trace(__name__, f'Send SQL command: {sql}') - result = self._context.select(sql) + joins.append(UserJoinedVoiceChannel( + self._users.get_user_by_id(result[1]), + result[2], + result[3], + result[4], + result[5], + id=result[0] + )) + + return joins + + 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] + return UserJoinedVoiceChannel( + self._users.get_user_by_id(result[1]), + result[2], + result[3], + result[4], + result[5], + id=result[0] + ) + + 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)) if result is None or len(result) == 0: return None - return self._from_result(result[0]) + result = result[0] - def add_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): - self._logger.trace(__name__, f'Send SQL command: {umcph.insert_string}') - self._context.cursor.execute(umcph.insert_string) + return UserJoinedVoiceChannel( + self._users.get_user_by_id(result[1]), + result[2], + result[3], + result[4], + result[5], + id=result[0] + ) - def update_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): - self._logger.trace(__name__, f'Send SQL command: {umcph.udpate_string}') - self._context.cursor.execute(umcph.udpate_string) + 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)) - def delete_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): - self._logger.trace(__name__, f'Send SQL command: {umcph.delete_string}') - self._context.cursor.execute(umcph.delete_string) + for db_result in db_results: + result.append(UserJoinedVoiceChannel( + self._users.get_user_by_id(db_result[1]), + db_result[2], + db_result[3], + db_result[4], + db_result[5], + id=db_result[0] + )) - def delete_user_message_count_per_hour_by_user_id(self, user_id: int): - sql = UserMessageCountPerHour.delete_by_user_id_string(user_id) - self._logger.trace(__name__, f'Send SQL command: {sql}') - self._context.cursor.execute(sql) + 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}') + 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}') + 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}') + self._context.cursor.execute(user_joined_voice_channel.delete_string) + + def delete_user_joined_voice_channel_by_user_id(self, user_id: int): + self._logger.trace(__name__, f'Send SQL command: {UserJoinedVoiceChannel.delete_by_user_id_string}') + self._context.cursor.execute(UserJoinedVoiceChannel.delete_by_user_id_string(user_id)) diff --git a/kdb-bot/src/bot_data/service/user_joined_voice_channel_service.py b/kdb-bot/src/bot_data/service/user_joined_voice_channel_service.py deleted file mode 100644 index 362228c5..00000000 --- a/kdb-bot/src/bot_data/service/user_joined_voice_channel_service.py +++ /dev/null @@ -1,127 +0,0 @@ -from typing import Optional - -from cpl_core.database.context import DatabaseContextABC -from cpl_query.extension import List - -from bot_core.logging.database_logger import DatabaseLogger -from bot_data.abc.user_joined_voice_channel_repository_abc import UserJoinedVoiceChannelRepositoryABC -from bot_data.abc.user_repository_abc import UserRepositoryABC -from bot_data.model.user_joined_voice_channel import UserJoinedVoiceChannel - - -class UserJoinedVoiceChannelRepositoryService(UserJoinedVoiceChannelRepositoryABC): - - def __init__(self, logger: DatabaseLogger, db_context: DatabaseContextABC, users: UserRepositoryABC): - self._logger = logger - self._context = db_context - - self._users = users - - UserJoinedVoiceChannelRepositoryABC.__init__(self) - - def get_user_joined_voice_channels(self) -> List[UserJoinedVoiceChannel]: - joins = List(UserJoinedVoiceChannel) - self._logger.trace(__name__, f'Send SQL command: {UserJoinedVoiceChannel.get_select_all_string()}') - 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]}') - joins.append(UserJoinedVoiceChannel( - self._users.get_user_by_id(result[1]), - result[2], - result[3], - result[4], - result[5], - id=result[0] - )) - - return joins - - def get_user_joined_voice_channel_by_id(self, id: int) -> UserJoinedVoiceChannel: - self._logger.trace(__name__, f'Send SQL command: {UserJoinedVoiceChannel.get_select_by_id_string(id)}') - result = self._context.select(UserJoinedVoiceChannel.get_select_by_id_string(id))[0] - return UserJoinedVoiceChannel( - self._users.get_user_by_id(result[1]), - result[2], - result[3], - result[4], - result[5], - id=result[0] - ) - - 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)) - for result in results: - joins.append(UserJoinedVoiceChannel( - self._users.get_user_by_id(result[1]), - result[2], - result[3], - result[4], - result[5], - id=result[0] - )) - - return joins - - 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] - return UserJoinedVoiceChannel( - self._users.get_user_by_id(result[1]), - result[2], - result[3], - result[4], - result[5], - id=result[0] - ) - - 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)) - if result is None or len(result) == 0: - return None - - result = result[0] - - return UserJoinedVoiceChannel( - self._users.get_user_by_id(result[1]), - result[2], - result[3], - result[4], - result[5], - id=result[0] - ) - - 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)) - - for db_result in db_results: - result.append(UserJoinedVoiceChannel( - self._users.get_user_by_id(db_result[1]), - db_result[2], - db_result[3], - db_result[4], - db_result[5], - id=db_result[0] - )) - - 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}') - 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}') - 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}') - self._context.cursor.execute(user_joined_voice_channel.delete_string) - - def delete_user_joined_voice_channel_by_user_id(self, user_id: int): - self._logger.trace(__name__, f'Send SQL command: {UserJoinedVoiceChannel.delete_by_user_id_string}') - self._context.cursor.execute(UserJoinedVoiceChannel.delete_by_user_id_string(user_id)) diff --git a/kdb-bot/src/bot_data/service/user_message_count_per_hour_repository_service.py b/kdb-bot/src/bot_data/service/user_message_count_per_hour_repository_service.py new file mode 100644 index 00000000..bb1a02c3 --- /dev/null +++ b/kdb-bot/src/bot_data/service/user_message_count_per_hour_repository_service.py @@ -0,0 +1,101 @@ +from datetime import datetime +from typing import Optional + +from cpl_core.database.context import DatabaseContextABC +from cpl_query.extension import List + +from bot_core.logging.database_logger import DatabaseLogger +from bot_data.abc.user_message_count_per_hour_repository_abc import UserMessageCountPerHourRepositoryABC +from bot_data.abc.user_repository_abc import UserRepositoryABC +from bot_data.model.user_message_count_per_hour import UserMessageCountPerHour + + +class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepositoryABC): + + def __init__( + self, + logger: DatabaseLogger, + db_context: DatabaseContextABC, + users: UserRepositoryABC, + ): + UserMessageCountPerHourRepositoryABC.__init__(self) + + self._logger = logger + self._context = db_context + self._users = users + + @staticmethod + def _get_value_from_result(value: any) -> Optional[any]: + if isinstance(value, str) and 'NULL' in value: + return None + + return value + + def _from_result(self, result: tuple) -> UserMessageCountPerHour: + return UserMessageCountPerHour( + self._get_value_from_result(result[1]), + self._get_value_from_result(result[2]), + self._get_value_from_result(result[3]), + self._users.get_user_by_id(self._get_value_from_result(result[4])), + self._get_value_from_result(result[5]), + self._get_value_from_result(result[6]), + id=self._get_value_from_result(result[0]) + ) + + def get_user_message_count_per_hours(self) -> List[UserMessageCountPerHour]: + umcphs = List(UserMessageCountPerHour) + self._logger.trace(__name__, f'Send SQL command: {UserMessageCountPerHour.get_select_all_string()}') + 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]}') + 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]]: + umcphs = List(UserMessageCountPerHour) + sql = UserMessageCountPerHour.get_select_by_user_id_string(user_id) + self._logger.trace(__name__, f'Send SQL command: {sql}') + results = self._context.select(sql) + if results is None or len(results) == 0: + return umcphs + + for result in results: + self._logger.trace(__name__, f'Get user message count per hour with id {result[0]}') + umcphs.append(self._from_result(result)) + + return umcphs + + 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) + self._logger.trace(__name__, f'Send SQL command: {sql}') + result = self._context.select(sql)[0] + return self._from_result(result) + + 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) + self._logger.trace(__name__, f'Send SQL command: {sql}') + result = self._context.select(sql) + if result is None or len(result) == 0: + return None + + return self._from_result(result[0]) + + def add_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): + self._logger.trace(__name__, f'Send SQL command: {umcph.insert_string}') + self._context.cursor.execute(umcph.insert_string) + + def update_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): + self._logger.trace(__name__, f'Send SQL command: {umcph.udpate_string}') + self._context.cursor.execute(umcph.udpate_string) + + def delete_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): + self._logger.trace(__name__, f'Send SQL command: {umcph.delete_string}') + self._context.cursor.execute(umcph.delete_string) + + def delete_user_message_count_per_hour_by_user_id(self, user_id: int): + sql = UserMessageCountPerHour.delete_by_user_id_string(user_id) + self._logger.trace(__name__, f'Send SQL command: {sql}') + self._context.cursor.execute(sql)