Changed config loading from file to db #127

This commit is contained in:
Sven Heidemann 2023-08-06 17:52:13 +02:00
parent 09d63e7418
commit 52787d0fb5
62 changed files with 872 additions and 460 deletions

View File

@ -11,6 +11,7 @@
"auto-role": "src/modules/auto_role/auto-role.json",
"base": "src/modules/base/base.json",
"boot-log": "src/modules/boot_log/boot-log.json",
"config": "src/modules/config/modules/config.json",
"database": "src/modules/database/database.json",
"level": "src/modules/level/level.json",
"permission": "src/modules/permission/permission.json",

@ -1 +1 @@
Subproject commit 42b9291f1a8484b3866a2e013b0f980aea093c4b
Subproject commit 4264ba15970a28f8a50c888bbf635a15c438bcf9

View File

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

View File

@ -15,6 +15,7 @@ from bot.startup_settings_extension import StartupSettingsExtension
from bot_api.app_api_extension import AppApiExtension
from bot_core.core_extension.core_extension import CoreExtension
from modules.boot_log.boot_log_extension import BootLogExtension
from modules.config.config_extension import ConfigExtension
from modules.database.database_extension import DatabaseExtension
@ -30,6 +31,7 @@ class Program:
.use_extension(StartupDiscordExtension)
.use_extension(StartupModuleExtension)
.use_extension(StartupMigrationExtension)
.use_extension(ConfigExtension)
.use_extension(InitBotExtension)
.use_extension(BootLogExtension)
.use_extension(DatabaseExtension)

View File

@ -9,6 +9,7 @@ from modules.achievements.achievements_module import AchievementsModule
from modules.auto_role.auto_role_module import AutoRoleModule
from modules.base.base_module import BaseModule
from modules.boot_log.boot_log_module import BootLogModule
from modules.config.config_module import ConfigModule
from modules.database.database_module import DatabaseModule
from modules.level.level_module import LevelModule
from modules.permission.permission_module import PermissionModule
@ -24,9 +25,10 @@ class ModuleList:
[
CoreModule, # has to be first!
DataModule,
DatabaseModule,
ConfigModule, # has be to after db check
GraphQLModule,
PermissionModule,
DatabaseModule,
AutoRoleModule,
BaseModule,
LevelModule,

View File

@ -1,6 +1,6 @@
import os
from datetime import datetime
from typing import Callable, Type, Optional
from typing import Optional, Type, Callable
from cpl_core.application import StartupExtensionABC
from cpl_core.configuration import ConfigurationABC
@ -8,10 +8,6 @@ from cpl_core.dependency_injection import ServiceCollectionABC
from cpl_core.environment import ApplicationEnvironmentABC
from bot_core.configuration.bot_logging_settings import BotLoggingSettings
from bot_core.configuration.bot_settings import BotSettings
from modules.base.configuration.base_settings import BaseSettings
from modules.boot_log.configuration.boot_log_settings import BootLogSettings
from modules.permission.configuration.permission_settings import PermissionSettings
class StartupSettingsExtension(StartupExtensionABC):
@ -33,12 +29,6 @@ class StartupSettingsExtension(StartupExtensionABC):
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, PermissionSettings, lambda x: x.servers, lambda x: x.id
)
self._configure_settings_with_sub_settings(
configuration, BotLoggingSettings, lambda x: x.files, lambda x: x.key
)

View File

@ -7,8 +7,8 @@ from cpl_query.extension import List
from discord.ext.commands import Context
from bot_data.model.auto_role_rule import AutoRoleRule
from bot_data.model.server_config import ServerConfig
from bot_data.model.user import User
from modules.base.configuration.base_server_settings import BaseServerSettings
class ClientUtilsABC(ABC):
@ -53,7 +53,7 @@ class ClientUtilsABC(ABC):
self,
created_at: datetime,
user: User,
settings: BaseServerSettings,
settings: ServerConfig,
is_reaction: bool = False,
) -> bool:
pass

View File

@ -1,56 +0,0 @@
from cpl_core.configuration import ConfigurationModelABC
from cpl_core.utils.json_processor import JSONProcessor
from cpl_query.extension import List
from bot_core.configuration.server_settings import ServerSettings
class BotSettings(ConfigurationModelABC):
def __init__(
self,
technicians: list = None,
wait_for_restart: int = 2,
wait_for_shutdown: int = 2,
cache_max_messages: int = 1000,
**kwargs: dict,
):
ConfigurationModelABC.__init__(self)
self._technicians: List[int] = List(int) if technicians is None else technicians
self._wait_for_restart = wait_for_restart
self._wait_for_shutdown = wait_for_shutdown
self._cache_max_messages = cache_max_messages
self._servers: List[ServerSettings] = List(ServerSettings)
for s in kwargs:
kwargs[s]["Id"] = s
self._servers.append(JSONProcessor.process(ServerSettings, kwargs[s]))
@property
def servers(self) -> List[ServerSettings]:
return self._servers
@property
def technicians(self) -> List[int]:
return self._technicians
@property
def wait_for_restart(self) -> int:
return self._wait_for_restart
@property
def wait_for_shutdown(self) -> int:
return self._wait_for_shutdown
@property
def cache_max_messages(self) -> int:
return self._cache_max_messages
def _servers_from_dict(self, settings: dict):
servers = List(ServerSettings)
for s in settings:
settings[s]["id"] = int(s)
st = JSONProcessor.process(ServerSettings, settings[s])
servers.append(st)
self._servers = servers

View File

@ -16,8 +16,8 @@ class FeatureFlagsEnum(Enum):
level_module = "LevelModule"
moderator_module = "ModeratorModule"
permission_module = "PermissionModule"
config_module = "ConfigModule"
# features
api_only = "ApiOnly"
presence = "Presence"
version_in_presence = "VersionInPresence"
config_in_wi = "ConfigInWI"

View File

@ -4,10 +4,7 @@ from bot_core.configuration.feature_flags_enum import FeatureFlagsEnum
class FeatureFlagsSettings(ConfigurationModelABC):
def __init__(self, **kwargs: dict):
ConfigurationModelABC.__init__(self)
self._flags = {
_flags = {
# modules
FeatureFlagsEnum.achievements_module.value: False, # 14.06.2023 #268
FeatureFlagsEnum.api_module.value: False, # 13.10.2022 #70
@ -21,13 +18,16 @@ class FeatureFlagsSettings(ConfigurationModelABC):
FeatureFlagsEnum.database_module.value: True, # 02.10.2022 #48
FeatureFlagsEnum.moderator_module.value: False, # 02.10.2022 #48
FeatureFlagsEnum.permission_module.value: True, # 02.10.2022 #48
FeatureFlagsEnum.config_module.value: True, # 19.07.2023 #127
# features
FeatureFlagsEnum.api_only.value: False, # 13.10.2022 #70
FeatureFlagsEnum.presence.value: True, # 03.10.2022 #56
FeatureFlagsEnum.version_in_presence.value: False, # 21.03.2023 #253
FeatureFlagsEnum.config_in_wi.value: True, # 19.07.2023 #127
}
def __init__(self, **kwargs: dict):
ConfigurationModelABC.__init__(self)
if len(kwargs.keys()) == 0:
return

View File

@ -1,27 +0,0 @@
from cpl_core.configuration.configuration_model_abc import ConfigurationModelABC
class ServerSettings(ConfigurationModelABC):
def __init__(
self,
id: int = None,
message_delete_timer: int = None,
notification_chat_id: int = None,
):
ConfigurationModelABC.__init__(self)
self._id: int = 0 if id is None else id
self._message_delete_timer: int = 0 if message_delete_timer is None else message_delete_timer
self._notification_chat_id: int = 0 if notification_chat_id is None else notification_chat_id
@property
def id(self) -> int:
return self._id
@property
def message_delete_timer(self) -> int:
return self._message_delete_timer
@property
def notification_chat_id(self) -> int:
return self._notification_chat_id

View File

@ -25,9 +25,9 @@ from bot_data.abc.user_message_count_per_hour_repository_abc import (
UserMessageCountPerHourRepositoryABC,
)
from bot_data.model.auto_role_rule import AutoRoleRule
from bot_data.model.server_config import ServerConfig
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
class ClientUtilsService(ClientUtilsABC):
@ -139,7 +139,7 @@ class ClientUtilsService(ClientUtilsABC):
self,
created_at: datetime,
user: User,
settings: BaseServerSettings,
settings: ServerConfig,
is_reaction: bool = False,
) -> bool:
umcph = None

View File

@ -19,13 +19,13 @@ from bot_data.abc.user_repository_abc import UserRepositoryABC
from bot_data.model.client import Client
from bot_data.model.known_user import KnownUser
from bot_data.model.server import Server
from bot_data.model.server_config import ServerConfig
from bot_data.model.user import User
from bot_data.model.user_joined_server import UserJoinedServer
from bot_data.model.user_joined_voice_channel import UserJoinedVoiceChannel
from bot_data.service.seeder_service import SeederService
from bot_data.service.user_repository_service import ServerRepositoryABC
from modules.achievements.achievement_service import AchievementService
from modules.base.configuration.base_server_settings import BaseServerSettings
class DataIntegrityService:
@ -255,7 +255,7 @@ class DataIntegrityService:
self._logger.debug(__name__, f"Start checking UserJoinedVoiceChannel table")
for guild in self._bot.guilds:
guild: discord.Guild = guild
settings: BaseServerSettings = self._config.get_configuration(f"BaseServerSettings_{guild.id}")
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild.id}")
server = self._servers.find_server_by_discord_id(guild.id)
if server is None:
@ -347,7 +347,7 @@ class DataIntegrityService:
f"Active UserJoinedGameServer found in database: {guild.id}:{member.id}@{join.joined_on}",
)
join.leaved_on = datetime.now()
settings: BaseServerSettings = self._config.get_configuration(f"BaseServerSettings_{guild.id}")
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild.id}")
if (
(join.leaved_on - join.joined_on).total_seconds() / 60 / 60

View File

@ -10,10 +10,10 @@ from discord import Interaction
from discord.ext.commands import Context
from bot_core.abc.message_service_abc import MessageServiceABC
from bot_core.configuration.server_settings import ServerSettings
from bot_core.helper.log_message_helper import LogMessageHelper
from bot_core.logging.message_logger import MessageLogger
from bot_data.abc.client_repository_abc import ClientRepositoryABC
from bot_data.model.server_config import ServerConfig
class MessageService(MessageServiceABC):
@ -33,7 +33,7 @@ class MessageService(MessageServiceABC):
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: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild_id}")
await asyncio.sleep(server_st.message_delete_timer)
for message in messages:
await self.delete_message(message, mass_delete=True, without_tracking=without_tracking)
@ -50,7 +50,7 @@ class MessageService(MessageServiceABC):
else None
)
server_st: ServerSettings = self._config.get_configuration(f"ServerSettings_{guild_id}")
server_st: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild_id}")
if not mass_delete:
await asyncio.sleep(server_st.message_delete_timer)
self._logger.debug(

View File

@ -0,0 +1,55 @@
from abc import ABC, abstractmethod
from bot_data.model.server_afk_channel_ids_config import ServerAFKChannelIdsConfig
from bot_data.model.server_config import ServerConfig
from bot_data.model.server_team_role_ids_config import ServerTeamRoleIdsConfig
class ServerConfigRepositoryABC(ABC):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def does_server_config_exists(self, server_id: int) -> bool:
pass
@abstractmethod
def get_server_config(self, server_id: int) -> ServerConfig:
pass
@abstractmethod
def add_server_config(self, server_config: ServerConfig):
pass
@abstractmethod
def update_server_config(self, server_config: ServerConfig):
pass
@abstractmethod
def delete_server_config(self, server_config: ServerConfig):
pass
@abstractmethod
def add_server_team_role_id_config(self, server_team_role_id: ServerTeamRoleIdsConfig):
pass
@abstractmethod
def update_server_team_role_id_config(self, server_team_role_id: ServerTeamRoleIdsConfig):
pass
@abstractmethod
def delete_server_team_role_id_config(self, server_team_role_id: ServerTeamRoleIdsConfig):
pass
@abstractmethod
def add_server_afk_channel_config(self, server_afk_channel: ServerAFKChannelIdsConfig):
pass
@abstractmethod
def update_server_afk_channel_config(self, server_afk_channel: ServerAFKChannelIdsConfig):
pass
@abstractmethod
def delete_server_afk_channel_config(self, server_afk_channel: ServerAFKChannelIdsConfig):
pass

View File

@ -14,6 +14,7 @@ from bot_data.abc.data_seeder_abc import DataSeederABC
from bot_data.abc.game_server_repository_abc import GameServerRepositoryABC
from bot_data.abc.known_user_repository_abc import KnownUserRepositoryABC
from bot_data.abc.level_repository_abc import LevelRepositoryABC
from bot_data.abc.server_config_repository_abc import ServerConfigRepositoryABC
from bot_data.abc.server_repository_abc import ServerRepositoryABC
from bot_data.abc.technician_config_repository_abc import TechnicianConfigRepositoryABC
from bot_data.abc.user_game_ident_repository_abc import UserGameIdentRepositoryABC
@ -37,6 +38,8 @@ from bot_data.service.game_server_repository_service import GameServerRepository
from bot_data.service.known_user_repository_service import KnownUserRepositoryService
from bot_data.service.level_repository_service import LevelRepositoryService
from bot_data.service.seeder_service import SeederService
from bot_data.service.server_config_repository_service import ServerConfigRepositoryService
from bot_data.service.server_config_seeder import ServerConfigSeeder
from bot_data.service.server_repository_service import ServerRepositoryService
from bot_data.service.technician_config_repository_service import TechnicianConfigRepositoryService
from bot_data.service.technician_config_seeder import TechnicianConfigSeeder
@ -85,6 +88,8 @@ class DataModule(ModuleABC):
services.add_transient(UserGameIdentRepositoryABC, UserGameIdentRepositoryService)
services.add_transient(AchievementRepositoryABC, AchievementRepositoryService)
services.add_transient(TechnicianConfigRepositoryABC, TechnicianConfigRepositoryService)
services.add_transient(ServerConfigRepositoryABC, ServerConfigRepositoryService)
services.add_transient(SeederService)
services.add_transient(DataSeederABC, TechnicianConfigSeeder)
services.add_transient(DataSeederABC, ServerConfigSeeder)

View File

@ -0,0 +1,76 @@
from datetime import datetime
from cpl_core.database import TableABC
class ServerAFKChannelIdsConfig(TableABC):
def __init__(
self,
channel_id: int,
server_id: int,
created_at: datetime = None,
modified_at: datetime = None,
id=0,
):
self._id = id
self._channel_id = channel_id
self._server_id = server_id
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 channel_id(self) -> int:
return self._channel_id
@staticmethod
def get_select_all_string() -> str:
return str(
f"""
SELECT * FROM `CFG_ServerAFKChannelIds`;
"""
)
@staticmethod
def get_select_by_id_string(id: int) -> str:
return str(
f"""
SELECT * FROM `CFG_ServerAFKChannelIds`
WHERE `Id` = {id};
"""
)
@property
def insert_string(self) -> str:
return str(
f"""
INSERT INTO `CFG_ServerAFKChannelIds` (
`RoleId`,
`ServerId`
) VALUES (
{self._channel_id},
{self._server_id}
);
"""
)
@property
def udpate_string(self) -> str:
return str(
f"""
UPDATE `CFG_ServerAFKChannelIds`
SET `RoleId` = {self._channel_id},
`ServerId` = {self._server_id}
WHERE `Id` = {self._id};
"""
)
@property
def delete_string(self) -> str:
return str(
f"""
DELETE FROM `CFG_ServerAFKChannelIds`
WHERE `Id` = {self._id};
"""
)

View File

@ -0,0 +1,205 @@
from datetime import datetime
from cpl_core.configuration import ConfigurationModelABC
from cpl_core.database import TableABC
from cpl_query.extension import List
from bot_data.model.server import Server
from bot_data.model.server_team_role_ids_config import ServerTeamRoleIdsConfig
class ServerConfig(TableABC, ConfigurationModelABC):
def __init__(
self,
message_delete_timer: int,
notification_chat_id: int,
max_voice_state_hours: int,
xp_per_message: int,
xp_per_reaction: int,
max_message_xp_per_hour: int,
xp_per_ontime_hour: int,
xp_per_event_participation: int,
xp_per_achievement: int,
afk_command_channel_id: int,
help_voice_channel_id: int,
team_channel_id: int,
login_message_channel_id: int,
server: Server,
afk_channel_ids: List[int],
team_role_ids: List[ServerTeamRoleIdsConfig],
created_at: datetime = None,
modified_at: datetime = None,
id=0,
):
self._id = id
self._message_delete_timer = message_delete_timer
self._notification_chat_id = notification_chat_id
self._max_voice_state_hours = max_voice_state_hours
self._xp_per_message = xp_per_message
self._xp_per_reaction = xp_per_reaction
self._max_message_xp_per_hour = max_message_xp_per_hour
self._xp_per_ontime_hour = xp_per_ontime_hour
self._xp_per_event_participation = xp_per_event_participation
self._xp_per_achievement = xp_per_achievement
self._afk_command_channel_id = afk_command_channel_id
self._help_voice_channel_id = help_voice_channel_id
self._team_channel_id = team_channel_id
self._login_message_channel_id = login_message_channel_id
self._server = server
self._afk_channel_ids = afk_channel_ids
self._team_role_ids = team_role_ids
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 message_delete_timer(self) -> int:
return self._message_delete_timer
@property
def notification_chat_id(self) -> int:
return self._notification_chat_id
@property
def max_voice_state_hours(self) -> int:
return self._max_voice_state_hours
@property
def xp_per_message(self) -> int:
return self._xp_per_message
@property
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
@property
def xp_per_event_participation(self) -> int:
return self._xp_per_event_participation
@property
def xp_per_achievement(self) -> int:
return self._xp_per_achievement
@property
def afk_command_channel_id(self) -> int:
return self._afk_command_channel_id
@property
def help_voice_channel_id(self) -> int:
return self._help_voice_channel_id
@property
def team_channel_id(self) -> int:
return self._team_channel_id
@property
def login_message_channel_id(self) -> int:
return self._login_message_channel_id
@property
def afk_channel_ids(self) -> List[int]:
return self._afk_channel_ids
@property
def team_role_ids(self) -> List[ServerTeamRoleIdsConfig]:
return self._team_role_ids
@property
def server(self) -> Server:
return self._server
@staticmethod
def get_select_all_string() -> str:
return str(
f"""
SELECT * FROM `CFG_Server`;
"""
)
@staticmethod
def get_select_by_id_string(id: int) -> str:
return str(
f"""
SELECT * FROM `CFG_Server`
WHERE `Id` = {id};
"""
)
@property
def insert_string(self) -> str:
return str(
f"""
INSERT INTO `CFG_Server` (
`MessageDeleteTimer`,
`NotificationChatId`,
`MaxVoiceStateHours`,
`XpPerMessage`,
`XpPerReaction`,
`MaxMessageXpPerHour`,
`XpPerOntimeHour`,
`XpPerEventParticipation`,
`XpPerAchievement`,
`AFKCommandChannelId`,
`HelpVoiceChannelId`,
`TeamChannelId`,
`LoginMessageChannelId`,
`ServerId`
) VALUES (
{self._message_delete_timer},
{self._notification_chat_id},
{self._max_voice_state_hours},
{self._xp_per_message},
{self._xp_per_reaction},
{self._max_message_xp_per_hour},
{self._xp_per_ontime_hour},
{self._xp_per_event_participation},
{self._xp_per_achievement},
{self._afk_command_channel_id},
{self._help_voice_channel_id},
{self._team_channel_id},
{self._login_message_channel_id},
{self._server.id}
);
"""
)
@property
def udpate_string(self) -> str:
return str(
f"""
UPDATE `CFG_Server`
SET `MessageDeleteTimer` = {self._message_delete_timer},
`NotificationChatId` = {self._notification_chat_id},
`MaxVoiceStateHours` = {self._max_voice_state_hours},
`XpPerMessage` = {self._xp_per_message},
`XpPerReaction` = {self._xp_per_reaction},
`MaxMessageXpPerHour` = {self._max_message_xp_per_hour},
`XpPerOntimeHour` = {self._xp_per_ontime_hour},
`XpPerEventParticipation` = {self._xp_per_event_participation},
`XpPerAchievement` = {self._xp_per_achievement},
`AFKCommandChannelId` = {self._afk_command_channel_id},
`HelpVoiceChannelId` = {self._help_voice_channel_id},
`TeamChannelId` = {self._team_channel_id},
`LoginMessageChannelId` = {self._login_message_channel_id},
`ServerId` = {self._server.id}
WHERE `Id` = {self._id};
"""
)
@property
def delete_string(self) -> str:
return str(
f"""
DELETE FROM `CFG_Server`
WHERE `Id` = {self._id};
"""
)

View File

@ -0,0 +1,87 @@
from datetime import datetime
from cpl_core.database import TableABC
from bot_data.model.team_member_type_enum import TeamMemberTypeEnum
class ServerTeamRoleIdsConfig(TableABC):
def __init__(
self,
role_id: int,
team_member_type: TeamMemberTypeEnum,
server_id: int,
created_at: datetime = None,
modified_at: datetime = None,
id=0,
):
self._id = id
self._role_id = role_id
self._team_member_type = team_member_type
self._server_id = server_id
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 role_id(self) -> int:
return self._role_id
@property
def team_member_type(self) -> TeamMemberTypeEnum:
return self._team_member_type
@staticmethod
def get_select_all_string() -> str:
return str(
f"""
SELECT * FROM `CFG_ServerTeamRoleIds`;
"""
)
@staticmethod
def get_select_by_id_string(id: int) -> str:
return str(
f"""
SELECT * FROM `CFG_ServerTeamRoleIds`
WHERE `Id` = {id};
"""
)
@property
def insert_string(self) -> str:
return str(
f"""
INSERT INTO `CFG_ServerTeamRoleIds` (
`RoleId`,
`TeamMemberType`,
`ServerId`
) VALUES (
{self._role_id},
'{self._team_member_type.value}',
{self._server_id}
);
"""
)
@property
def udpate_string(self) -> str:
return str(
f"""
UPDATE `CFG_ServerTeamRoleIds`
SET `RoleId` = {self._role_id},
`TeamMemberType` = '{self._team_member_type.value}',
`ServerId` = {self._server_id}
WHERE `Id` = {self._id};
"""
)
@property
def delete_string(self) -> str:
return str(
f"""
DELETE FROM `CFG_ServerTeamRoleIds`
WHERE `Id` = {self._id};
"""
)

View File

@ -0,0 +1,6 @@
from enum import Enum
class TeamMemberTypeEnum(Enum):
moderator = "Moderator"
admin = "Admin"

View File

@ -1,10 +1,11 @@
from datetime import datetime
from cpl_core.configuration import ConfigurationModelABC
from cpl_core.database import TableABC
from cpl_query.extension import List
class TechnicianConfig(TableABC):
class TechnicianConfig(TableABC, ConfigurationModelABC):
def __init__(
self,
help_command_reference_url: str,

View File

@ -0,0 +1,118 @@
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.server_config_repository_abc import ServerConfigRepositoryABC
from bot_data.abc.server_repository_abc import ServerRepositoryABC
from bot_data.model.server_afk_channel_ids_config import ServerAFKChannelIdsConfig
from bot_data.model.server_config import ServerConfig
from bot_data.model.server_team_role_ids_config import ServerTeamRoleIdsConfig
from bot_data.model.team_member_type_enum import TeamMemberTypeEnum
class ServerConfigRepositoryService(ServerConfigRepositoryABC):
def __init__(self, logger: DatabaseLogger, db_context: DatabaseContextABC, servers: ServerRepositoryABC):
ServerConfigRepositoryABC.__init__(self)
self._logger = logger
self._context = db_context
self._servers = servers
def _get_team_role_ids(self, server_team_role_id: int) -> List[ServerTeamRoleIdsConfig]:
ids = List(ServerTeamRoleIdsConfig)
self._logger.trace(
__name__, f"Send SQL command: {ServerTeamRoleIdsConfig.get_select_by_id_string(server_team_role_id)}"
)
results = self._context.select(ServerTeamRoleIdsConfig.get_select_by_id_string(server_team_role_id))
for result in results:
self._logger.trace(__name__, f"Got ServerTeamRoleIdsConfig with id {result[0]}")
ids.append(
ServerTeamRoleIdsConfig(
result[1], TeamMemberTypeEnum(result[2]), result[3], result[4], result[5], id=result[0]
)
)
return ids
def _get_afk_channel_ids(self, server_team_role_id: int) -> List[int]:
urls = List(str)
self._logger.trace(
__name__, f"Send SQL command: {ServerAFKChannelIdsConfig.get_select_by_id_string(server_team_role_id)}"
)
results = self._context.select(ServerAFKChannelIdsConfig.get_select_by_id_string(server_team_role_id))
for result in results:
self._logger.trace(__name__, f"Got ServerAFKChannelIdsConfig with id {result[0]}")
urls.append(result[1])
return urls
def _from_result(self, result: tuple) -> ServerConfig:
return ServerConfig(
result[1],
result[2],
result[3],
result[4],
result[5],
result[6],
result[7],
result[8],
result[9],
result[10],
result[11],
result[12],
result[13],
self._servers.get_server_by_id(result[14]),
self._get_afk_channel_ids(result[0]),
self._get_team_role_ids(result[0]),
result[15],
result[16],
id=result[0],
)
def does_server_config_exists(self, server_id: int) -> bool:
self._logger.trace(__name__, f"Send SQL command: {ServerConfig.get_select_by_id_string(server_id)}")
result = self._context.select(ServerConfig.get_select_by_id_string(server_id))
return len(result) > 0
def get_server_config(self, server_id: int) -> ServerConfig:
self._logger.trace(__name__, f"Send SQL command: {ServerConfig.get_select_by_id_string(server_id)}")
result = self._context.select(ServerConfig.get_select_by_id_string(server_id))[0]
return self._from_result(result)
def add_server_config(self, server_config: ServerConfig):
self._logger.trace(__name__, f"Send SQL command: {server_config.insert_string}")
self._context.cursor.execute(server_config.insert_string)
def update_server_config(self, server_config: ServerConfig):
self._logger.trace(__name__, f"Send SQL command: {server_config.udpate_string}")
self._context.cursor.execute(server_config.udpate_string)
def delete_server_config(self, server_config: ServerConfig):
self._logger.trace(__name__, f"Send SQL command: {server_config.delete_string}")
self._context.cursor.execute(server_config.delete_string)
def add_server_team_role_id_config(self, server_team_role_id: ServerTeamRoleIdsConfig):
self._logger.trace(__name__, f"Send SQL command: {server_team_role_id.insert_string}")
self._context.cursor.execute(server_team_role_id.insert_string)
def update_server_team_role_id_config(self, server_team_role_id: ServerTeamRoleIdsConfig):
self._logger.trace(__name__, f"Send SQL command: {server_team_role_id.udpate_string}")
self._context.cursor.execute(server_team_role_id.udpate_string)
def delete_server_team_role_id_config(self, server_team_role_id: ServerTeamRoleIdsConfig):
self._logger.trace(__name__, f"Send SQL command: {server_team_role_id.delete_string}")
self._context.cursor.execute(server_team_role_id.delete_string)
def add_server_afk_channel_config(self, server_afk_channel: ServerAFKChannelIdsConfig):
self._logger.trace(__name__, f"Send SQL command: {server_afk_channel.insert_string}")
self._context.cursor.execute(server_afk_channel.insert_string)
def update_server_afk_channel_config(self, server_afk_channel: ServerAFKChannelIdsConfig):
self._logger.trace(__name__, f"Send SQL command: {server_afk_channel.udpate_string}")
self._context.cursor.execute(server_afk_channel.udpate_string)
def delete_server_afk_channel_config(self, server_afk_channel: ServerAFKChannelIdsConfig):
self._logger.trace(__name__, f"Send SQL command: {server_afk_channel.delete_string}")
self._context.cursor.execute(server_afk_channel.delete_string)

View File

@ -0,0 +1,62 @@
from cpl_core.database.context import DatabaseContextABC
from cpl_discord.container import Guild
from cpl_discord.service import DiscordBotServiceABC
from bot_core.logging.database_logger import DatabaseLogger
from bot_data.abc.data_seeder_abc import DataSeederABC
from bot_data.abc.server_config_repository_abc import ServerConfigRepositoryABC
from bot_data.abc.server_repository_abc import ServerRepositoryABC
from bot_data.model.server_config import ServerConfig
class ServerConfigSeeder(DataSeederABC):
def __init__(
self,
logger: DatabaseLogger,
bot: DiscordBotServiceABC,
servers: ServerRepositoryABC,
server_config: ServerConfigRepositoryABC,
db: DatabaseContextABC,
):
DataSeederABC.__init__(self)
self._logger = logger
self._bot = bot
self._servers = servers
self._server_config = server_config
self._db = db
async def seed(self):
try:
for guild in self._bot.guilds:
guild: Guild = guild
server = self._servers.get_server_by_discord_id(guild.id)
if self._server_config.does_server_config_exists(server.id):
continue
config = ServerConfig(
6,
guild.system_channel.id,
6,
1,
1,
20,
10,
10,
10,
guild.system_channel.id,
guild.system_channel.id,
guild.system_channel.id,
guild.system_channel.id,
server,
[],
[],
)
self._server_config.add_server_config(config)
self._db.save_changes()
self._logger.debug(__name__, "Seeded technician config")
except Exception as e:
self._logger.error(__name__, f"Seeding technician config failed", e)

View File

@ -24,7 +24,9 @@ class TechnicianConfigSeeder(DataSeederABC):
async def seed(self):
try:
if not self._technician_config.does_technician_config_exists():
if self._technician_config.does_technician_config_exists():
return
config = TechnicianConfig(
"https://git.sh-edraft.de/sh-edraft.de/kd_discord_bot/wiki/Befehle",
8,
@ -43,6 +45,5 @@ class TechnicianConfigSeeder(DataSeederABC):
self._db.save_changes()
self._logger.debug(__name__, "Seeded technician config")
except Exception as e:
self._logger.error(__name__, f"Seeding technician config failed", e)

View File

@ -2,6 +2,7 @@ import hashlib
from datetime import datetime
from typing import Optional
from cpl_core.configuration import ConfigurationABC
from cpl_core.database.context import DatabaseContextABC
from cpl_core.logging import LoggerABC
from cpl_discord.service import DiscordBotServiceABC
@ -15,19 +16,18 @@ from bot_data.abc.user_game_ident_repository_abc import UserGameIdentRepositoryA
from bot_data.abc.user_joined_game_server_repository_abc import UserJoinedGameServerRepositoryABC
from bot_data.abc.user_repository_abc import UserRepositoryABC
from bot_data.model.api_key import ApiKey
from bot_data.model.server_config import ServerConfig
from bot_data.model.user_joined_game_server import UserJoinedGameServer
from bot_data.model.user_role_enum import UserRoleEnum
from bot_graphql.abc.query_abc import QueryABC
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.configuration.base_server_settings import BaseServerSettings
from modules.permission.service.permission_service import PermissionService
class UserJoinedGameServerMutation(QueryABC):
def __init__(
self,
config: ConfigurationABC,
logger: LoggerABC,
base_helper: BaseHelperABC,
servers: ServerRepositoryABC,
users: UserRepositoryABC,
user_joined_game_servers: UserJoinedGameServerRepositoryABC,
@ -41,8 +41,8 @@ class UserJoinedGameServerMutation(QueryABC):
):
QueryABC.__init__(self, "UserJoinedGameServerMutation")
self._config = config
self._logger = logger
self._base_helper = base_helper
self._servers = servers
self._users = users
self._user_joined_game_servers = user_joined_game_servers
@ -116,7 +116,7 @@ class UserJoinedGameServerMutation(QueryABC):
return
active.leaved_on = datetime.now()
settings: BaseServerSettings = self._base_helper.get_config(user.server.discord_id)
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{user.server.discord_id}")
ontime = round((active.leaved_on - active.joined_on).total_seconds() / 3600, 2)
old_xp = user.xp

View File

@ -5,16 +5,15 @@ from cpl_discord.service import DiscordBotServiceABC
from cpl_query.extension import List
from cpl_translation import TranslatePipe
from bot_core.configuration.server_settings import ServerSettings
from bot_core.service.message_service import MessageService
from bot_data.abc.achievement_repository_abc import AchievementRepositoryABC
from bot_data.abc.user_repository_abc import UserRepositoryABC
from bot_data.model.achievement import Achievement
from bot_data.model.server_config import ServerConfig
from bot_data.model.user import User
from bot_data.model.user_got_achievement import UserGotAchievement
from modules.achievements.achievement_attribute_resolver import AchievementAttributeResolver
from modules.achievements.model.achievement_attribute import AchievementAttribute
from modules.base.configuration.base_server_settings import BaseServerSettings
class AchievementService:
@ -100,7 +99,7 @@ class AchievementService:
await self._send_achievement_notification(user.server.discord_id, user.discord_id, achievement.name)
def _give_user_xp(self, user: User):
settings: BaseServerSettings = self._config.get_configuration(f"BaseServerSettings_{user.server.discord_id}")
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{user.server.discord_id}")
user.xp += settings.xp_per_achievement
self._users.update_user(user)
self._db.save_changes()
@ -108,7 +107,7 @@ class AchievementService:
async def _send_achievement_notification(self, guild_id: int, member_id: int, achievement_name: str):
member = self._bot.get_guild(guild_id).get_member(member_id)
settings: ServerSettings = self._config.get_configuration(f"ServerSettings_{guild_id}")
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild_id}")
await self._message_service.send_channel_message(
self._bot.get_channel(settings.notification_chat_id),
self._t.transform("modules.achievements.got_new_achievement").format(member.mention, achievement_name),

View File

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

View File

@ -1,12 +0,0 @@
from abc import abstractmethod, ABC
from modules.base.configuration.base_server_settings import BaseServerSettings
class BaseHelperABC(ABC):
def __init__(self):
ABC.__init__(self)
@abstractmethod
def get_config(self, g_id: int) -> BaseServerSettings:
pass

View File

@ -6,7 +6,6 @@ from cpl_discord.service.discord_collection_abc import DiscordCollectionABC
from bot_core.abc.module_abc import ModuleABC
from bot_core.configuration.feature_flags_enum import FeatureFlagsEnum
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.command.afk_command import AFKCommand
from modules.base.command.game_server_group import GameServerGroup
from modules.base.command.help_command import HelpCommand
@ -40,7 +39,6 @@ from modules.base.events.base_on_voice_state_update_event_scheduled_event_bonus
from modules.base.forms.bug_report_form import BugReportForm
from modules.base.forms.complaint_form import ComplaintForm
from modules.base.helper.base_reaction_handler import BaseReactionHandler
from modules.base.service.base_helper_service import BaseHelperService
from modules.base.service.event_service import EventService
from modules.base.service.user_warnings_service import UserWarningsService
@ -53,7 +51,6 @@ class BaseModule(ModuleABC):
pass
def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
services.add_transient(BaseHelperABC, BaseHelperService)
services.add_transient(BaseReactionHandler)
services.add_singleton(EventService)
services.add_transient(UserWarningsService)

View File

@ -10,7 +10,6 @@ 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
from modules.base.configuration.base_server_settings import BaseServerSettings
class AFKCommand(DiscordCommandABC):
@ -39,7 +38,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: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}")
if ctx.author.voice is None or ctx.author.voice.channel is None:
await self._message_service.send_ctx_msg(

View File

@ -12,7 +12,6 @@ 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
from modules.base.configuration.base_server_settings import BaseServerSettings
class HelpCommand(DiscordCommandABC):
@ -39,7 +38,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: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}")
is_persistent = persistent_flag == "--stay"
await self._message_service.send_ctx_msg(
ctx,

View File

@ -10,8 +10,7 @@ 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
from bot_data.abc.server_repository_abc import ServerRepositoryABC
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.configuration.base_server_settings import BaseServerSettings
from bot_data.model.technician_config import TechnicianConfig
from modules.permission.abc.permission_service_abc import PermissionServiceABC
@ -24,8 +23,8 @@ class PingCommand(DiscordCommandABC):
client_utils: ClientUtilsABC,
translate: TranslatePipe,
permissions: PermissionServiceABC,
base_helper: BaseHelperABC,
servers: ServerRepositoryABC,
settings: TechnicianConfig,
):
DiscordCommandABC.__init__(self)
@ -35,8 +34,8 @@ class PingCommand(DiscordCommandABC):
self._client_utils = client_utils
self._t = translate
self._permissions = permissions
self._base_helper = base_helper
self._servers = servers
self._settings = settings
self._logger.trace(__name__, f"Loaded command service: {type(self).__name__}")
@ -58,9 +57,7 @@ class PingCommand(DiscordCommandABC):
description=self._t.transform("modules.base.info.description"),
color=int("ef9d0d", 16),
)
server = self._servers.get_server_by_discord_id(ctx.guild.id)
settings: BaseServerSettings = self._base_helper.get_config(server.discord_id)
for server in settings.ping_urls:
for server in self._settings.ping_urls:
embed.add_field(name=server, value=f"{self._get_ping(server)} ms", inline=False)
await self._message_service.send_ctx_msg(ctx, embed)
else:

View File

@ -8,9 +8,9 @@ from discord.ext.commands import Context
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
from bot_core.logging.command_logger import CommandLogger
from bot_data.model.server_config import ServerConfig
from modules.permission.abc.permission_service_abc import PermissionServiceABC
@ -41,7 +41,7 @@ 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: ServerConfig = self._config.get_configuration(f"ServerConfig_{ctx.guild.id}")
await self._message_service.send_ctx_msg(ctx, self._t.transform("modules.moderator.purge_message"))
await asyncio.sleep(server_settings.message_delete_timer)

View File

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

View File

@ -1,94 +0,0 @@
from cpl_core.configuration.configuration_model_abc import ConfigurationModelABC
from cpl_query.extension import List
class BaseServerSettings(ConfigurationModelABC):
def __init__(
self,
id: int = None,
max_voice_state_hours: int = None,
xp_per_message: int = None,
xp_per_reaction: int = None,
max_message_xp_per_hour: int = None,
xp_per_ontime_hour: int = None,
xp_per_event_participation: int = None,
xp_per_achievement: int = None,
afk_channel_ids: List = None,
afk_command_channel_id: int = None,
help_command_reference_url: str = None,
help_voice_channel_id: int = None,
team_channel_id: int = None,
ping_urls: list = None,
):
ConfigurationModelABC.__init__(self)
self._id = 0 if id is None else id
self._max_voice_state_hours = 0 if max_voice_state_hours is None else max_voice_state_hours
self._xp_per_message = 0 if xp_per_message is None else xp_per_message
self._xp_per_reaction = 0 if xp_per_reaction is None else xp_per_reaction
self._max_message_xp_per_hour = 0 if max_message_xp_per_hour is None else max_message_xp_per_hour
self._xp_per_ontime_hour = 0 if xp_per_ontime_hour is None else xp_per_ontime_hour
self._xp_per_event_participation = 0 if xp_per_event_participation is None else xp_per_event_participation
self._xp_per_achievement = 0 if xp_per_achievement is None else xp_per_achievement
self._afk_channel_ids = List(int) if afk_channel_ids is None else List(int, afk_channel_ids)
self._afk_command_channel_id = 0 if afk_command_channel_id is None else afk_command_channel_id
self._help_command_reference_url = "" if help_command_reference_url is None else help_command_reference_url
self._help_voice_channel_id = 0 if help_voice_channel_id is None else help_voice_channel_id
self._team_channel_id = 0 if team_channel_id is None else team_channel_id
self._ping_urls = List(str) if ping_urls is None else List(str, ping_urls)
@property
def id(self) -> int:
return self._id
@property
def max_voice_state_hours(self) -> int:
return self._max_voice_state_hours
@property
def xp_per_message(self) -> int:
return self._xp_per_message
@property
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
@property
def xp_per_event_participation(self) -> int:
return self._xp_per_event_participation
@property
def xp_per_achievement(self) -> int:
return self._xp_per_achievement
@property
def afk_channel_ids(self) -> List[int]:
return self._afk_channel_ids
@property
def afk_command_channel_id(self) -> int:
return self._afk_command_channel_id
@property
def help_command_reference_url(self) -> str:
return self._help_command_reference_url
@property
def team_channel_id(self) -> int:
return self._team_channel_id
@property
def help_voice_channel_id(self) -> int:
return self._help_voice_channel_id
@property
def ping_urls(self) -> List[str]:
return self._ping_urls

View File

@ -1,19 +0,0 @@
from cpl_core.configuration import ConfigurationModelABC
from cpl_core.utils.json_processor import JSONProcessor
from cpl_query.extension import List
from modules.base.configuration.base_server_settings import BaseServerSettings
class BaseSettings(ConfigurationModelABC):
def __init__(self, **kwargs: dict):
ConfigurationModelABC.__init__(self)
self._servers: List[BaseServerSettings] = List()
for s in kwargs:
kwargs[s]["Id"] = s
self._servers.append(JSONProcessor.process(BaseServerSettings, kwargs[s]))
@property
def servers(self) -> List[BaseServerSettings]:
return self._servers

View File

@ -1,18 +1,15 @@
import datetime
import traceback
import uuid
from cpl_core.logging import LoggerABC
from cpl_core.time import TimeFormatSettings
from cpl_discord.events.on_command_error_abc import OnCommandErrorABC
from cpl_discord.service import DiscordBotServiceABC
from cpl_translation import TranslatePipe
from discord.ext import commands
from discord.ext.commands import Context, CommandError
from cpl_core.logging import LoggerABC
from cpl_discord.events.on_command_error_abc import OnCommandErrorABC
from bot_core.abc.message_service_abc import MessageServiceABC
from bot_core.configuration.bot_settings import BotSettings
from bot_core.exception.check_error import CheckError
@ -22,7 +19,6 @@ class BaseOnCommandErrorEvent(OnCommandErrorABC):
logger: LoggerABC,
bot: DiscordBotServiceABC,
messenger: MessageServiceABC,
bot_settings: BotSettings,
time_format_settings: TimeFormatSettings,
translate: TranslatePipe,
):

View File

@ -9,14 +9,11 @@ from cpl_translation import TranslatePipe
from discord.ext.commands import Context
from bot_core.abc.message_service_abc import MessageServiceABC
from bot_core.configuration.bot_settings import BotSettings
from bot_core.logging.command_logger import CommandLogger
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
from bot_data.model.user import User
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.configuration.base_server_settings import BaseServerSettings
class BaseOnCommandEvent(OnCommandABC):
@ -25,10 +22,8 @@ class BaseOnCommandEvent(OnCommandABC):
logger: CommandLogger,
bot: DiscordBotServiceABC,
messenger: MessageServiceABC,
bot_settings: BotSettings,
time_format_settings: TimeFormatSettings,
translate: TranslatePipe,
bhs: BaseHelperABC,
db: DatabaseContextABC,
users: UserRepositoryABC,
clients: ClientRepositoryABC,
@ -38,10 +33,8 @@ class BaseOnCommandEvent(OnCommandABC):
self._logger = logger
self._bot = bot
self._messenger = messenger
self._bot_settings = bot_settings
self._time_format_settings = time_format_settings
self._t = translate
self._base_helper = bhs
self._db = db
self._users = users
self._clients = clients
@ -73,7 +66,7 @@ class BaseOnCommandEvent(OnCommandABC):
self._logger.error(__name__, f"User not found {dc_user_id}")
return
settings: BaseServerSettings = self._base_helper.get_config(message.guild.id)
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{message.guild.id}")
old_xp = user.xp
user.xp += settings.xp_per_message
self._users.update_user(user)

View File

@ -17,8 +17,6 @@ from bot_data.abc.user_repository_abc import UserRepositoryABC
from bot_data.model.known_user import KnownUser
from bot_data.model.user import User
from bot_data.model.user_joined_server import UserJoinedServer
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.configuration.base_server_settings import BaseServerSettings
from modules.permission.abc.permission_service_abc import PermissionServiceABC
@ -27,7 +25,6 @@ class BaseOnMemberJoinEvent(OnMemberJoinABC):
self,
config: ConfigurationABC,
logger: LoggerABC,
base_helper: BaseHelperABC,
messenger: MessageServiceABC,
permissions: PermissionServiceABC,
db: DatabaseContextABC,
@ -40,7 +37,6 @@ class BaseOnMemberJoinEvent(OnMemberJoinABC):
OnMemberJoinABC.__init__(self)
self._config = config
self._logger = logger
self._base_helper = base_helper
self._messenger = messenger
self._permission_service = permissions
self._db = db
@ -65,7 +61,6 @@ class BaseOnMemberJoinEvent(OnMemberJoinABC):
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(
self._t.transform("modules.base.welcome_message").format(member.guild.name),
member,

View File

@ -12,15 +12,12 @@ from bot_core.helper.event_checks import EventChecks
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_repository_abc import UserRepositoryABC
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.configuration.base_server_settings import BaseServerSettings
class BaseOnMemberRemoveEvent(OnMemberRemoveABC):
def __init__(
self,
logger: LoggerABC,
base_helper: BaseHelperABC,
db: DatabaseContextABC,
messenger: MessageServiceABC,
users: UserRepositoryABC,
@ -41,7 +38,7 @@ 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)
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{member.guild.id}")
await self._messenger.send_dm_message(self._t.transform("modules.base.goodbye_message"), member)
try:

View File

@ -11,15 +11,12 @@ 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
from bot_data.model.user import User
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.configuration.base_server_settings import BaseServerSettings
class BaseOnMessageDeleteEvent(OnMessageDeleteABC):
def __init__(
self,
logger: MessageLogger,
bhs: BaseHelperABC,
db: DatabaseContextABC,
bot: DiscordBotServiceABC,
users: UserRepositoryABC,
@ -28,7 +25,6 @@ class BaseOnMessageDeleteEvent(OnMessageDeleteABC):
):
OnMessageDeleteABC.__init__(self)
self._logger = logger
self._base_helper = bhs
self._db = db
self._bot = bot
self._users = users
@ -61,7 +57,7 @@ class BaseOnMessageDeleteEvent(OnMessageDeleteABC):
self._logger.error(__name__, f"User not found {dc_user_id}")
return
settings: BaseServerSettings = self._base_helper.get_config(message.guild.id)
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{message.guild.id}")
old_xp = user.xp
user.xp -= settings.xp_per_message
self._users.update_user(user)

View File

@ -12,16 +12,14 @@ 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
from bot_data.model.server_config import ServerConfig
from bot_data.model.user import User
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.configuration.base_server_settings import BaseServerSettings
class BaseOnMessageEvent(OnMessageABC):
def __init__(
self,
logger: MessageLogger,
bhs: BaseHelperABC,
client_utils: ClientUtilsService,
db: DatabaseContextABC,
bot: DiscordBotServiceABC,
@ -31,7 +29,6 @@ class BaseOnMessageEvent(OnMessageABC):
):
OnMessageABC.__init__(self)
self._logger = logger
self._base_helper = bhs
self._client_utils = client_utils
self._bot = bot
self._db = db
@ -66,7 +63,7 @@ class BaseOnMessageEvent(OnMessageABC):
self._logger.error(__name__, f"User not found {dc_user_id}")
return
settings: BaseServerSettings = self._base_helper.get_config(message.guild.id)
settings: ServerConfig = se
if self._client_utils.is_message_xp_count_by_hour_higher_that_max_message_count_per_hour(
message.created_at, user, settings
):

View File

@ -16,10 +16,9 @@ from bot_data.abc.user_joined_voice_channel_repository_abc import (
)
from bot_data.abc.user_repository_abc import UserRepositoryABC
from bot_data.model.server import Server
from bot_data.model.server_config import ServerConfig
from bot_data.model.user import User
from bot_data.model.user_joined_voice_channel import UserJoinedVoiceChannel
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.configuration.base_server_settings import BaseServerSettings
class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC):
@ -27,7 +26,6 @@ class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC):
self,
config: ConfigurationABC,
logger: LoggerABC,
base_helper: BaseHelperABC,
servers: ServerRepositoryABC,
known_users: KnownUserRepositoryABC,
users: UserRepositoryABC,
@ -38,7 +36,6 @@ class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC):
OnVoiceStateUpdateABC.__init__(self)
self._config = config
self._logger = logger
self._base_helper = base_helper
self._servers = servers
self._known_users = known_users
self._users = users
@ -67,7 +64,7 @@ class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC):
self._db.save_changes()
return
settings: BaseServerSettings = self._base_helper.get_config(server.discord_id)
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{server.discord_id}")
join = self._user_joins_vc.get_active_user_joined_voice_channel_by_user_id(user.id)
join.leaved_on = datetime.now()
@ -98,7 +95,7 @@ class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC):
__name__,
f"Detected on_voice_state_update {member.id} from {before} to {after}",
)
settings: BaseServerSettings = self._base_helper.get_config(member.guild.id)
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{member.guild.id}")
server = self._servers.get_server_by_discord_id(member.guild.id)
try:

View File

@ -7,8 +7,7 @@ from cpl_translation import TranslatePipe
from bot_core.abc.message_service_abc import MessageServiceABC
from bot_core.helper.event_checks import EventChecks
from bot_data.abc.server_repository_abc import ServerRepositoryABC
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.configuration.base_server_settings import BaseServerSettings
from bot_data.model.server_config import ServerConfig
from modules.permission.abc.permission_service_abc import PermissionServiceABC
@ -17,7 +16,6 @@ class BaseOnVoiceStateUpdateEventHelpChannel(OnVoiceStateUpdateABC):
self,
config: ConfigurationABC,
logger: LoggerABC,
base_helper: BaseHelperABC,
servers: ServerRepositoryABC,
permissions: PermissionServiceABC,
message_service: MessageServiceABC,
@ -26,7 +24,6 @@ class BaseOnVoiceStateUpdateEventHelpChannel(OnVoiceStateUpdateABC):
OnVoiceStateUpdateABC.__init__(self)
self._config = config
self._logger = logger
self._base_helper = base_helper
self._servers = servers
self._permissions = permissions
self._message_service = message_service
@ -43,7 +40,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_id)
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{server.discord_id}")
if after.channel is None or after.channel.id != settings.help_voice_channel_id:
return

View File

@ -7,8 +7,7 @@ from cpl_discord.events import OnVoiceStateUpdateABC
from bot_core.helper.event_checks import EventChecks
from bot_data.abc.server_repository_abc import ServerRepositoryABC
from bot_data.abc.user_repository_abc import UserRepositoryABC
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.configuration.base_server_settings import BaseServerSettings
from bot_data.model.server_config import ServerConfig
from modules.base.service.event_service import EventService
@ -17,7 +16,6 @@ class BaseOnVoiceStateUpdateEventScheduledEventBonus(OnVoiceStateUpdateABC):
self,
config: ConfigurationABC,
logger: LoggerABC,
base_helper: BaseHelperABC,
servers: ServerRepositoryABC,
users: UserRepositoryABC,
events: EventService,
@ -26,7 +24,6 @@ class BaseOnVoiceStateUpdateEventScheduledEventBonus(OnVoiceStateUpdateABC):
OnVoiceStateUpdateABC.__init__(self)
self._config = config
self._logger = logger
self._base_helper = base_helper
self._servers = servers
self._users = users
self._events = events
@ -57,7 +54,7 @@ class BaseOnVoiceStateUpdateEventScheduledEventBonus(OnVoiceStateUpdateABC):
self._logger.debug(__name__, f"Module {type(self)} stopped")
return
settings: BaseServerSettings = self._base_helper.get_config(server.discord_id)
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{server.discord_id}")
user.xp += settings.xp_per_event_participation
self._users.update_user(user)
self._db.save_changes()

View File

@ -5,9 +5,8 @@ from cpl_translation import TranslatePipe
from discord import ui, TextStyle
from bot_core.abc.message_service_abc import MessageServiceABC
from bot_core.configuration.bot_settings import BotSettings
from bot_core.logging.command_logger import CommandLogger
from modules.base.service.base_helper_service import BaseHelperService
from bot_data.model.technician_config import TechnicianConfig
class BugReportForm(ui.Modal):
@ -15,22 +14,20 @@ class BugReportForm(ui.Modal):
def __init__(
self,
bot_settings: BotSettings,
technician_config: TechnicianConfig,
bot: DiscordBotServiceABC,
db: DatabaseContextABC,
logger: CommandLogger,
message_service: MessageServiceABC,
base_helper: BaseHelperService,
t: TranslatePipe,
):
ui.Modal.__init__(self, title=t.transform("modules.base.bug.title"))
self._bot_settings = bot_settings
self._technician_config = technician_config
self._bot = bot
self._db = db
self._message_service = message_service
self._logger = logger
self._base_helper = base_helper
self._t = t
self.description.label = t.transform("modules.base.bug.label")
@ -38,7 +35,7 @@ class BugReportForm(ui.Modal):
async def on_submit(self, interaction: discord.Interaction):
self._logger.debug(__name__, f"Started bug report form")
for t in self._bot_settings.technicians:
for t in self._technician_config.technician_ids:
member = self._bot.get_user(t)
await self._message_service.send_dm_message(
self._t.transform("modules.base.bug.message").format(interaction.user.mention, self.description.value),

View File

@ -1,12 +1,12 @@
import discord
from cpl_core.configuration import ConfigurationABC
from cpl_core.database.context import DatabaseContextABC
from cpl_translation import TranslatePipe
from discord import ui, TextStyle
from bot_core.abc.message_service_abc import MessageServiceABC
from bot_core.logging.command_logger import CommandLogger
from modules.base.configuration.base_server_settings import BaseServerSettings
from modules.base.service.base_helper_service import BaseHelperService
from bot_data.model.server_config import ServerConfig
class ComplaintForm(ui.Modal):
@ -14,25 +14,25 @@ class ComplaintForm(ui.Modal):
def __init__(
self,
config: ConfigurationABC,
db: DatabaseContextABC,
logger: CommandLogger,
message_service: MessageServiceABC,
base_helper: BaseHelperService,
t: TranslatePipe,
):
ui.Modal.__init__(self, title=t.transform("modules.base.complaints.title"))
self._config = config
self._db = db
self._message_service = message_service
self._logger = logger
self._base_helper = base_helper
self._t = t
self.description.label = t.transform("modules.base.complaints.label")
async def on_submit(self, interaction: discord.Interaction):
self._logger.debug(__name__, f"Started complaint command form")
settings: BaseServerSettings = self._base_helper.get_config(interaction.guild.id)
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{interaction.guild.id}")
channel = interaction.guild.get_channel(settings.team_channel_id)
await self._message_service.send_channel_message(
channel,

View File

@ -1,5 +1,6 @@
from datetime import datetime
from cpl_core.configuration import ConfigurationABC
from cpl_core.database.context import DatabaseContextABC
from cpl_discord.service import DiscordBotServiceABC
from discord import RawReactionActionEvent
@ -9,26 +10,25 @@ from bot_core.helper.log_message_helper import LogMessageHelper
from bot_core.logging.message_logger import MessageLogger
from bot_data.abc.server_repository_abc import ServerRepositoryABC
from bot_data.abc.user_repository_abc import UserRepositoryABC
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.configuration.base_server_settings import BaseServerSettings
from bot_data.model.server_config import ServerConfig
class BaseReactionHandler:
def __init__(
self,
config: ConfigurationABC,
logger: MessageLogger,
bot: DiscordBotServiceABC,
servers: ServerRepositoryABC,
users: UserRepositoryABC,
base_helper: BaseHelperABC,
client_utils: ClientUtilsABC,
db: DatabaseContextABC,
):
self._config = config
self._logger = logger
self._bot = bot
self._servers = servers
self._users = users
self._base_helper = base_helper
self._client_utils = client_utils
self._db = db
@ -70,7 +70,7 @@ class BaseReactionHandler:
server = self._servers.get_server_by_discord_id(guild.id)
user = self._users.get_user_by_discord_id_and_server_id(member.id, server.id)
settings: BaseServerSettings = self._base_helper.get_config(guild.id)
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild.id}")
if r_type == "add":
if self._client_utils.is_message_xp_count_by_hour_higher_that_max_message_count_per_hour(

View File

@ -1,13 +0,0 @@
from cpl_core.configuration import ConfigurationABC
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.configuration.base_server_settings import BaseServerSettings
class BaseHelperService(BaseHelperABC):
def __init__(self, config: ConfigurationABC):
BaseHelperABC.__init__(self)
self._config = config
def get_config(self, g_id: int) -> BaseServerSettings:
return self._config.get_configuration(f"BaseServerSettings_{g_id}")

View File

@ -11,8 +11,6 @@ from bot_data.abc.user_repository_abc import UserRepositoryABC
from bot_data.abc.user_warnings_repository_abc import UserWarningsRepositoryABC
from bot_data.model.user import User
from bot_data.model.user_warnings import UserWarnings
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.configuration.base_server_settings import BaseServerSettings
from modules.level.service.level_service import LevelService
from modules.permission.abc.permission_service_abc import PermissionServiceABC
@ -31,7 +29,6 @@ class UserWarningsService:
message_service: MessageServiceABC,
t: TranslatePipe,
permissions: PermissionServiceABC,
base_helper: BaseHelperABC,
):
self._logger = logger
self._db = db
@ -44,11 +41,10 @@ class UserWarningsService:
self._message_service = message_service
self._t = t
self._permissions = permissions
self._base_helper = base_helper
async def notify_team(self, member: discord.Member, description: str, removed=False):
try:
settings: BaseServerSettings = self._base_helper.get_config(member.guild.id)
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{member.guild.id}")
channel = member.guild.get_channel(settings.team_channel_id)
if removed:
translation = self._t.transform("modules.base.warnings.team_removed").format(

View File

@ -8,9 +8,7 @@ from cpl_translation import TranslatePipe
from discord import guild
from bot_core.abc.message_service_abc import MessageServiceABC
from modules.boot_log.configuration.boot_log_server_settings import (
BootLogServerSettings,
)
from bot_data.model.server_config import ServerConfig
class BootLogOnReadyEvent(OnReadyABC):
@ -57,14 +55,14 @@ class BootLogOnReadyEvent(OnReadyABC):
g: guild = g
self._logger.debug(__name__, f"Server detected: {g.id}")
module_settings: BootLogServerSettings = self._config.get_configuration(f"BootLogServerSettings_{g.id}")
if module_settings is None:
server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{g.id}")
if server_config is None:
self._logger.error(__name__, f"Config {type(self).__name__}_{g.id} not found!")
return
self._bot.loop.create_task(
self._message_service.send_channel_message(
self._bot.get_channel(module_settings.login_message_channel_id),
self._bot.get_channel(server_config.login_message_channel_id),
self._t.transform("modules.boot_log.login_message").format(init_time),
)
)

View File

@ -0,0 +1 @@
# imports

View File

@ -0,0 +1,46 @@
{
"ProjectSettings": {
"Name": "config",
"Version": {
"Major": "0",
"Minor": "0",
"Micro": "0"
},
"Author": "",
"AuthorEmail": "",
"Description": "",
"LongDescription": "",
"URL": "",
"CopyrightDate": "",
"CopyrightName": "",
"LicenseName": "",
"LicenseDescription": "",
"Dependencies": [
"cpl-core>=2023.4.0.post5"
],
"DevDependencies": [
"cpl-cli>=2023.4.0.post3"
],
"PythonVersion": ">=3.10.4",
"PythonPath": {
"linux": ""
},
"Classifiers": []
},
"BuildSettings": {
"ProjectType": "library",
"SourcePath": "",
"OutputPath": "../../dist",
"Main": "config.main",
"EntryPoint": "config",
"IncludePackageData": false,
"Included": [],
"Excluded": [
"*/__pycache__",
"*/logs",
"*/tests"
],
"PackageData": {},
"ProjectReferences": []
}
}

View File

@ -0,0 +1,24 @@
from cpl_core.application.application_extension_abc import ApplicationExtensionABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.dependency_injection import ServiceProviderABC
from cpl_core.logging import LoggerABC
from bot_core.configuration.feature_flags_enum import FeatureFlagsEnum
from bot_core.configuration.feature_flags_settings import FeatureFlagsSettings
from bot_data.abc.technician_config_repository_abc import TechnicianConfigRepositoryABC
from bot_data.model.technician_config import TechnicianConfig
class ConfigExtension(ApplicationExtensionABC):
def __init__(self):
pass
async def run(self, config: ConfigurationABC, services: ServiceProviderABC):
feature_flags: FeatureFlagsSettings = config.get_configuration(FeatureFlagsSettings)
if not feature_flags.get_flag(FeatureFlagsEnum.config_module):
return
logger: LoggerABC = services.get_service(LoggerABC)
logger.debug(__name__, "Config extension started")
technician_config_repo: TechnicianConfigRepositoryABC = services.get_service(TechnicianConfigRepositoryABC)
technician_config = technician_config_repo.get_technician_config()
config.add_configuration(TechnicianConfig, technician_config)

View File

@ -0,0 +1,20 @@
from cpl_core.configuration import ConfigurationABC
from cpl_core.dependency_injection import ServiceCollectionABC
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.module_abc import ModuleABC
from bot_core.configuration.feature_flags_enum import FeatureFlagsEnum
from modules.config.events.config_on_ready_event import ConfigOnReadyEvent
class ConfigModule(ModuleABC):
def __init__(self, dc: DiscordCollectionABC):
ModuleABC.__init__(self, dc, FeatureFlagsEnum.config_module)
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, ConfigOnReadyEvent)

View File

@ -0,0 +1 @@
# imports

View File

@ -0,0 +1,35 @@
from cpl_core.configuration import ConfigurationABC
from cpl_core.logging import LoggerABC
from cpl_discord.container import Guild
from cpl_discord.events import OnReadyABC
from cpl_discord.service import DiscordBotServiceABC
from bot_data.abc.server_config_repository_abc import ServerConfigRepositoryABC
from bot_data.abc.server_repository_abc import ServerRepositoryABC
class ConfigOnReadyEvent(OnReadyABC):
def __init__(
self,
config: ConfigurationABC,
logger: LoggerABC,
bot: DiscordBotServiceABC,
servers: ServerRepositoryABC,
server_config_repo: ServerConfigRepositoryABC,
):
OnReadyABC.__init__(self)
self._config = config
self._logger = logger
self._bot = bot
self._servers = servers
self._server_config_repo = server_config_repo
async def on_ready(self):
for guild in self._bot.guilds:
guild: Guild = guild
server = self._servers.get_server_by_discord_id(guild.id)
server_config = self._server_config_repo.get_server_config(server.id)
self._config.add_configuration(
f"{type(server_config).__name__}_{server_config.server.discord_id}", server_config
)

View File

@ -6,7 +6,6 @@ from cpl_discord.container import Guild, Role, Member
from cpl_discord.service import DiscordBotServiceABC
from cpl_translation import TranslatePipe
from bot_core.configuration.server_settings import ServerSettings
from bot_core.service.message_service import MessageService
from bot_data.model.level import Level
from bot_data.model.user import User
@ -75,7 +74,7 @@ class LevelService:
self._logger.error(__name__, f"Adding role {level_role.name} to {member.name} failed!", e)
if notification_needed:
settings: ServerSettings = self._config.get_configuration(f"ServerSettings_{guild.id}")
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild.id}")
await self._message_service.send_channel_message(
self._bot.get_channel(settings.notification_chat_id),
self._t.transform("modules.level.new_level_message").format(member.mention, level.name),

View File

@ -3,25 +3,25 @@ from cpl_core.configuration import ConfigurationABC
from cpl_core.logging import LoggerABC
from cpl_discord.service import DiscordBotServiceABC
from bot_core.configuration.bot_settings import BotSettings
from bot_data.model.server_config import ServerConfig
from bot_data.model.team_member_type_enum import TeamMemberTypeEnum
from bot_data.model.technician_config import TechnicianConfig
from modules.permission.abc.permission_service_abc import PermissionServiceABC
from modules.permission.configuration.permission_server_settings import (
PermissionServerSettings,
)
class PermissionService(PermissionServiceABC):
def __init__(
self,
technician_settings: TechnicianConfig,
logger: LoggerABC,
bot: DiscordBotServiceABC,
config: ConfigurationABC,
bot_settings: BotSettings,
):
PermissionServiceABC.__init__(self)
self._logger = logger
self._bot = bot
self._config = config
self._technician_settings = technician_settings
self._admin_role_ids: dict[int, list[int]] = {}
self._admin_roles: dict[int, list[discord.Role]] = {}
@ -31,7 +31,7 @@ class PermissionService(PermissionServiceABC):
self._moderator_roles: dict[int, list[discord.Role]] = {}
self._moderators: dict[int, list[discord.Member]] = {}
self._technician_ids: list[int] = bot_settings.technicians
self._technician_ids: list[int] = technician_settings.technician_ids.to_list()
self._technicians: list[discord.Member] = []
def on_ready(self):
@ -45,13 +45,21 @@ class PermissionService(PermissionServiceABC):
continue
self._technicians.append(technician)
settings: PermissionServerSettings = self._config.get_configuration(f"PermissionServerSettings_{guild.id}")
settings: ServerConfig = self._config.get_configuration(f"ServerConfig_{guild.id}")
if settings is None:
self._logger.error(__name__, "Permission settings not found")
self._logger.error(__name__, "Server settings not found")
return
self._admin_role_ids[guild.id] = settings.admin_roles
self._moderator_role_ids[guild.id] = settings.moderator_roles
self._admin_role_ids[guild.id] = (
settings.team_role_ids.where(lambda x: x.team_member_type == TeamMemberTypeEnum.admin)
.select(lambda x: x.role_id)
.to_list()
)
self._moderator_role_ids[guild.id] = (
settings.team_role_ids.where(lambda x: x.team_member_type == TeamMemberTypeEnum.moderator)
.select(lambda x: x.role_id)
.to_list()
)
admin_roles = []
admins = []

View File

@ -9,7 +9,6 @@ from discord.ext.commands import Context
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
from bot_core.logging.command_logger import CommandLogger
from modules.permission.abc.permission_service_abc import PermissionServiceABC
@ -25,7 +24,6 @@ class RestartCommand(DiscordCommandABC):
client_utils: ClientUtilsABC,
translate: TranslatePipe,
permissions: PermissionServiceABC,
settings: BotSettings,
):
DiscordCommandABC.__init__(self)
@ -36,7 +34,6 @@ class RestartCommand(DiscordCommandABC):
self._client_utils = client_utils
self._t = translate
self._permissions = permissions
self._settings = settings
self._logger.trace(__name__, f"Loaded command service: {type(self).__name__}")

View File

@ -1,6 +1,5 @@
import asyncio
import discord
from cpl_core.configuration import ConfigurationABC
from cpl_discord.command import DiscordCommandABC
from cpl_discord.service import DiscordBotServiceABC
@ -10,9 +9,9 @@ from discord.ext.commands import Context
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
from bot_core.logging.command_logger import CommandLogger
from bot_data.model.technician_config import TechnicianConfig
from modules.permission.abc.permission_service_abc import PermissionServiceABC
@ -26,7 +25,7 @@ class ShutdownCommand(DiscordCommandABC):
client_utils: ClientUtilsABC,
translate: TranslatePipe,
permissions: PermissionServiceABC,
settings: BotSettings,
settings: TechnicianConfig,
):
DiscordCommandABC.__init__(self)

View File

@ -6,8 +6,6 @@ from cpl_discord.service.discord_collection_abc import DiscordCollectionABC
from bot_core.abc.module_abc import ModuleABC
from bot_core.configuration.feature_flags_enum import FeatureFlagsEnum
from bot_data.abc.data_seeder_abc import DataSeederABC
from modules.base.abc.base_helper_abc import BaseHelperABC
from modules.base.service.base_helper_service import BaseHelperService
from modules.technician.api_key_seeder import ApiKeySeeder
from modules.technician.command.api_key_group import ApiKeyGroup
from modules.technician.command.log_command import LogCommand
@ -24,7 +22,6 @@ class TechnicianModule(ModuleABC):
def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC):
services.add_transient(DataSeederABC, ApiKeySeeder)
services.add_transient(BaseHelperABC, BaseHelperService)
# commands
self._dc.add_command(RestartCommand)
self._dc.add_command(ShutdownCommand)