Added maintenance mode #423
All checks were successful
Deploy dev on push / on-push-deploy_sh-edraft (push) Successful in 4m9s

This commit is contained in:
Sven Heidemann 2023-11-05 22:22:39 +01:00
parent 2f161d2f43
commit a7c833b9db
36 changed files with 106 additions and 37 deletions

View File

@ -58,8 +58,9 @@ class Application(DiscordBotApplicationABC):
return
self._logger.info(__name__, f"Try to start {DiscordBotService.__name__}")
for task in self._tasks:
await self._bot.add_cog(task)
if not self._config.get_configuration("MAINTENANCE"):
for task in self._tasks:
await self._bot.add_cog(task)
await self._bot.start_async()
await self._bot.stop_async()

View File

@ -19,6 +19,12 @@ class StartupSettingsExtension(StartupExtensionABC):
environment.set_working_directory(os.path.dirname(os.path.realpath(__file__)))
configuration.add_environment_variables("SDB_")
configuration.add_environment_variables("DISCORD_")
configuration.add_configuration(
"MAINTENANCE", configuration.get_configuration("MAINTENANCE") in [True, "true", "True"]
)
configuration.add_configuration(
"MIGRATION_ONLY", configuration.get_configuration("MIGRATION_ONLY") in [True, "true", "True"]
)
configuration.add_json_file(f"config/appsettings.json", optional=False)
configuration.add_json_file(f"config/appsettings.{environment.environment_name}.json", optional=True)

View File

@ -90,7 +90,8 @@
"booting": "Ich fahre gerade hoch...",
"restart": "Muss neue Kekse holen...",
"running": "Ich esse Kekse :D",
"shutdown": "Ich werde bestimmt wieder kommen..."
"shutdown": "Ich werde bestimmt wieder kommen...",
"maintenance": "In Wartung!"
}
},
"modules": {

View File

@ -14,14 +14,18 @@ class TaskABC(commands.Cog):
def __init__(self):
commands.Cog.__init__(self)
@ServiceProviderABC.inject
def _is_maintenance(self, config: ConfigurationABC) -> bool:
return config.get_configuration("MAINTENANCE") is True
@ServiceProviderABC.inject
async def _wait_until_ready(self, config: ConfigurationABC, logger: TaskLogger, bot: DiscordBotServiceABC):
logger.debug(__name__, f"Waiting before {type(self).__name__}")
await bot.wait_until_ready()
async def wait():
is_ready = config.get_configuration("IS_READY")
if is_ready != "true":
is_ready = config.get_configuration("IS_READY") is True
if not is_ready:
await asyncio.sleep(1)
await wait()

View File

@ -1,5 +1,6 @@
import asyncio
from cpl_core.configuration import ConfigurationABC
from cpl_core.logging import LoggerABC
from cpl_discord.events import OnReadyABC
from cpl_discord.service import DiscordBotServiceABC
@ -11,6 +12,7 @@ from bot_core.abc.client_utils_abc import ClientUtilsABC
class CoreExtensionOnReadyEvent(OnReadyABC):
def __init__(
self,
config: ConfigurationABC,
logger: LoggerABC,
bot: DiscordBotServiceABC,
client_utils: ClientUtilsABC,
@ -18,6 +20,7 @@ class CoreExtensionOnReadyEvent(OnReadyABC):
):
OnReadyABC.__init__(self)
self._config = config
self._logger = logger
self._bot = bot
self._client_utils = client_utils
@ -27,5 +30,8 @@ class CoreExtensionOnReadyEvent(OnReadyABC):
async def on_ready(self):
self._logger.debug(__name__, f"Module {type(self)} started")
await self._client_utils.presence_game("common.presence.running")
if self._config.get_configuration("MAINTENANCE"):
await self._client_utils.presence_game("common.presence.maintenance")
else:
await self._client_utils.presence_game("common.presence.running")
self._logger.trace(__name__, f"Module {type(self)} stopped")

View File

@ -1,3 +1,4 @@
import inspect
from typing import Optional
from discord.ext import commands
@ -17,11 +18,19 @@ class EventChecks:
cls._client_utils = client_utils
@classmethod
def check_is_ready(cls):
async def check_if_bot_is_ready() -> bool:
def check_is_ready(cls, func):
async def check_if_bot_is_ready(*args, **kwargs):
result = await cls._client_utils.check_if_bot_is_ready_yet()
if not result:
raise CheckError(f"Bot is not ready")
return result
return commands.check(check_if_bot_is_ready)
def empty(*args, **kwargs):
pass
return empty
return await func(*args, **kwargs)
# return commands.check(check_if_bot_is_ready)
check_if_bot_is_ready.__name__ = func.__name__
sig = inspect.signature(func)
check_if_bot_is_ready.__signature__ = sig.replace(parameters=tuple(sig.parameters.values())[1:])
return check_if_bot_is_ready

View File

@ -87,7 +87,14 @@ class ClientUtilsService(ClientUtilsABC):
return client
async def check_if_bot_is_ready_yet(self) -> bool:
if self._config.get_configuration("IS_READY") == "true":
if self._config.get_configuration("MAINTENANCE"):
self._logger.warn(
__name__,
f"Bot is in maintenance mode",
)
return False
if self._config.get_configuration("IS_READY") is True:
return True
self._logger.debug(

View File

@ -1,6 +1,7 @@
from typing import Callable
from ariadne import ObjectType
from cpl_core.configuration import ConfigurationABC
from cpl_core.dependency_injection import ServiceProviderABC
from cpl_core.type import T
from cpl_discord.service import DiscordBotServiceABC
@ -75,9 +76,14 @@ class QueryABC(ObjectType):
def get_services(services: ServiceProviderABC) -> ServiceProviderABC:
return services
@ServiceProviderABC.inject
def get_config(config: ConfigurationABC) -> ConfigurationABC:
return config
services = get_services()
permissions: PermissionService = services.get_service(PermissionService)
bot: DiscordBotServiceABC = services.get_service(DiscordBotServiceABC)
config = get_config()
if user.auth_role == AuthRoleEnum.admin:
return True
@ -87,6 +93,9 @@ class QueryABC(ObjectType):
if permissions.is_member_technician(guild.get_member(u.discord_id)):
return True
if config.get_configuration("MAINTENANCE"):
return False
access = False
if type(element) == Achievement:
element: Achievement = element
@ -215,7 +224,9 @@ class QueryABC(ObjectType):
return access
@ServiceProviderABC.inject
def _can_user_mutate_data(self, server: Server, permission: UserRoleEnum, services: ServiceProviderABC):
def _can_user_mutate_data(
self, server: Server, permission: UserRoleEnum, services: ServiceProviderABC, config: ConfigurationABC
):
permissions: PermissionService = services.get_service(PermissionService)
bot: DiscordBotServiceABC = services.get_service(DiscordBotServiceABC)
@ -227,16 +238,20 @@ class QueryABC(ObjectType):
auth_user.users.where(lambda x: x.server.id == server.id).single().discord_id
)
check_perm = lambda x: True
can_edit = lambda x: False
match permission:
case UserRoleEnum.moderator:
check_perm = lambda x: permissions.is_member_moderator(x)
can_edit = permissions.is_member_moderator
if config.get_configuration("MAINTENANCE"):
can_edit = lambda x: False
case UserRoleEnum.admin:
check_perm = lambda x: permissions.is_member_admin(x)
can_edit = permissions.is_member_admin
if config.get_configuration("MAINTENANCE"):
can_edit = lambda x: False
case UserRoleEnum.technician:
check_perm = lambda x: permissions.is_member_technician(x)
can_edit = permissions.is_member_technician
if not check_perm(member):
if not can_edit(member):
ex = ServiceException(ServiceErrorCode.Forbidden, f"User not allowed to mutate data")
raise ex

View File

@ -35,7 +35,7 @@ class AchievementOnMessageEvent(OnMessageABC):
self._servers = servers
self._users = users
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_message(self, message: discord.Message):
if message.guild is None:
return

View File

@ -9,6 +9,7 @@ from cpl_discord.service import DiscordBotServiceABC
from bot_core.configuration.feature_flags_enum import FeatureFlagsEnum
from bot_core.configuration.feature_flags_settings import FeatureFlagsSettings
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 bot_data.model.server_config import ServerConfig
@ -36,6 +37,7 @@ class AchievementOnReactionAddEvent(OnReactionAddABC):
self._servers = servers
self._users = users
@EventChecks.check_is_ready
async def on_reaction_add(
self,
reaction: discord.reaction.Reaction,

View File

@ -9,6 +9,7 @@ from cpl_discord.service import DiscordBotServiceABC
from bot_core.configuration.feature_flags_enum import FeatureFlagsEnum
from bot_core.configuration.feature_flags_settings import FeatureFlagsSettings
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 bot_data.model.server_config import ServerConfig
@ -36,6 +37,7 @@ class AchievementOnReactionRemoveEvent(OnReactionRemoveABC):
self._servers = servers
self._users = users
@EventChecks.check_is_ready
async def on_reaction_remove(
self,
reaction: discord.reaction.Reaction,

View File

@ -7,6 +7,7 @@ from cpl_discord.service import DiscordBotServiceABC
from bot_core.configuration.feature_flags_enum import FeatureFlagsEnum
from bot_core.configuration.feature_flags_settings import FeatureFlagsSettings
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 bot_data.model.server_config import ServerConfig
@ -34,6 +35,7 @@ class AchievementOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC):
self._servers = servers
self._users = users
@EventChecks.check_is_ready
async def on_voice_state_update(
self,
member: discord.member.Member,

View File

@ -32,7 +32,7 @@ class AutoRoleOnRawReactionAddEvent(OnRawReactionAddABC):
self._auto_roles = auto_roles
self._reaction_handler = reaction_handler
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_raw_reaction_add(self, payload: RawReactionActionEvent):
self._logger.debug(__name__, f"Module {type(self)} started")
server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{payload.guild_id}")

View File

@ -32,7 +32,7 @@ class AutoRoleOnRawReactionRemoveEvent(OnRawReactionRemoveABC):
self._auto_roles = auto_roles
self._reaction_handler = reaction_handler
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_raw_reaction_remove(self, payload: RawReactionActionEvent):
self._logger.debug(__name__, f"Module {type(self)} started")
server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{payload.guild_id}")

View File

@ -34,7 +34,8 @@ class BirthdayWatcher(TaskABC):
self._message_service = message_service
self._t = t
self.watch.start()
if not self._is_maintenance():
self.watch.start()
@tasks.loop(time=datetime.time(hour=8, minute=0))
async def watch(self):

View File

@ -11,6 +11,7 @@ from discord.ext.commands import Context, CommandError
from bot_core.abc.message_service_abc import MessageServiceABC
from bot_core.exception.check_error import CheckError
from bot_core.helper.event_checks import EventChecks
from bot_data.model.technician_config import TechnicianConfig
@ -32,6 +33,7 @@ class BaseOnCommandErrorEvent(OnCommandErrorABC):
self._time_format_settings = time_format_settings
self._t = translate
@EventChecks.check_is_ready
async def on_command_error(self, ctx: Context, error: CommandError):
if isinstance(error, CheckError):
return

View File

@ -10,6 +10,7 @@ from cpl_translation import TranslatePipe
from discord.ext.commands import Context
from bot_core.abc.message_service_abc import MessageServiceABC
from bot_core.helper.event_checks import EventChecks
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
@ -78,6 +79,7 @@ class BaseOnCommandEvent(OnCommandABC):
self._logger.debug(__name__, f"User {user} sent message. xp: from {old_xp} to {user.xp}")
@EventChecks.check_is_ready
async def on_command(self, ctx: Context):
self._logger.debug(__name__, f"Module {type(self)} started")
self._logger.info(__name__, f"Received command: {ctx.command} from {ctx.channel}")

View File

@ -4,6 +4,7 @@ from cpl_discord.events import OnGuildJoinABC
from cpl_discord.service import DiscordBotServiceABC
from discord import Guild
from bot_core.helper.event_checks import EventChecks
from bot_data.abc.server_config_repository_abc import ServerConfigRepositoryABC
from bot_data.abc.server_repository_abc import ServerRepositoryABC
from bot_data.model.server import Server
@ -29,6 +30,7 @@ class BaseOnGuildJoinEvent(OnGuildJoinABC):
self._db = db
self._seeder = seeder
@EventChecks.check_is_ready
async def on_guild_join(self, guild: Guild):
if self._servers.find_server_by_discord_id(guild.id) is None:
self._servers.add_server(Server(guild.id))

View File

@ -101,7 +101,7 @@ class BaseOnMemberJoinEvent(OnMemberJoinABC):
)
self._logger.trace(__name__, f"Notified team that a member left")
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_member_join(self, member: discord.Member):
self._logger.debug(__name__, f"Module {type(self)} started")
if member.bot:

View File

@ -69,7 +69,7 @@ class BaseOnMemberRemoveEvent(OnMemberRemoveABC):
)
self._logger.trace(__name__, f"Notified team that a member left")
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_member_remove(self, member: discord.Member):
self._logger.debug(__name__, f"Module {type(self)} started")
await self._remove_user(member)

View File

@ -6,6 +6,7 @@ from cpl_core.database.context import DatabaseContextABC
from cpl_discord.events import OnMessageDeleteABC
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_data.abc.client_repository_abc import ClientRepositoryABC
@ -72,6 +73,7 @@ class BaseOnMessageDeleteEvent(OnMessageDeleteABC):
f"Removed message from user {user}. xp: from {old_xp} to {user.xp}",
)
@EventChecks.check_is_ready
async def on_message_delete(self, message: discord.Message):
self._logger.debug(__name__, f"Module {type(self)} started")
if message is None or message.guild is None:

View File

@ -79,7 +79,7 @@ class BaseOnMessageEvent(OnMessageABC):
self._logger.debug(__name__, f"User {user} sent message. xp: from {old_xp} to {user.xp}")
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_message(self, message: discord.Message):
self._logger.debug(__name__, f"Module {type(self)} started")
if message is None or message.guild is None:

View File

@ -26,7 +26,7 @@ class BaseOnRawReactionAddEvent(OnRawReactionAddABC):
self._auto_roles = auto_roles
self._reaction_handler = reaction_handler
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_raw_reaction_add(self, payload: RawReactionActionEvent):
self._logger.debug(__name__, f"Module {type(self)} started")

View File

@ -26,7 +26,7 @@ class BaseOnRawReactionRemoveEvent(OnRawReactionRemoveABC):
self._auto_roles = auto_roles
self._reaction_handler = reaction_handler
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_raw_reaction_remove(self, payload: RawReactionActionEvent):
self._logger.debug(__name__, f"Module {type(self)} started")

View File

@ -4,6 +4,7 @@ from cpl_discord.events.on_scheduled_event_update_abc import OnScheduledEventUpd
from cpl_discord.service import DiscordBotServiceABC
from discord import EventStatus
from bot_core.helper.event_checks import EventChecks
from modules.base.model.active_event import ActiveEvent
from modules.base.service.event_service import EventService
@ -21,6 +22,7 @@ class BaseOnScheduledEventUpdateEvent(OnScheduledEventUpdateABC):
self._bot = bot
self._events = events
@EventChecks.check_is_ready
async def on_scheduled_event_update(self, before: discord.ScheduledEvent, after: discord.ScheduledEvent):
self._logger.debug(__name__, f"Module {type(self)} started")

View File

@ -83,7 +83,7 @@ class BaseOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC):
except Exception as e:
self._logger.error(__name__, f"Ontime validation failed", e)
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_voice_state_update(
self,
member: discord.Member,

View File

@ -42,7 +42,7 @@ class BaseOnVoiceStateUpdateEventHelpChannel(OnVoiceStateUpdateABC):
)
self._logger.trace(__name__, f"Notified team that a member need help")
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_voice_state_update(
self,
member: discord.Member,

View File

@ -30,7 +30,7 @@ class BaseOnVoiceStateUpdateEventScheduledEventBonus(OnVoiceStateUpdateABC):
self._logger.info(__name__, f"Module {type(self)} loaded")
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_voice_state_update(
self,
member: discord.Member,

View File

@ -82,6 +82,6 @@ class BootLogOnReadyEvent(OnReadyABC):
)
)
self._config.add_configuration("IS_READY", "true")
self._config.add_configuration("IS_READY", True)
self._logger.info(__name__, "Bot is ready")
self._logger.trace(__name__, f"Module {type(self)} stopped")

View File

@ -17,7 +17,7 @@ class LevelOnMemberJoinEvent(OnMemberJoinABC):
self._logger = logger
self._level = level
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_member_join(self, member: discord.Member):
self._logger.debug(__name__, f"Module {type(self)} started")
server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{member.guild.id}")

View File

@ -17,7 +17,7 @@ class LevelOnMessageEvent(OnMessageABC):
self._logger = logger
self._level = level
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_message(self, message: discord.Message):
self._logger.debug(__name__, f"Module {type(self)} started")
if message.guild is None:

View File

@ -26,7 +26,7 @@ class LevelOnRawReactionAddEvent(OnRawReactionAddABC):
self._bot = bot
self._level = level
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_raw_reaction_add(self, payload: RawReactionActionEvent):
self._logger.debug(__name__, f"Module {type(self)} started")
server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{payload.guild_id}")

View File

@ -26,7 +26,7 @@ class LevelOnRawReactionRemoveEvent(OnRawReactionRemoveABC):
self._bot = bot
self._level = level
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_raw_reaction_remove(self, payload: RawReactionActionEvent):
self._logger.debug(__name__, f"Module {type(self)} started")
server_config: ServerConfig = self._config.get_configuration(f"ServerConfig_{payload.guild_id}")

View File

@ -19,7 +19,7 @@ class LevelOnVoiceStateUpdateEvent(OnVoiceStateUpdateABC):
self._logger.info(__name__, f"Module {type(self)} loaded")
@EventChecks.check_is_ready()
@EventChecks.check_is_ready
async def on_voice_state_update(
self,
member: discord.Member,

View File

@ -1,6 +1,7 @@
import discord
from cpl_discord.events import OnMemberUpdateABC
from bot_core.helper.event_checks import EventChecks
from modules.short_role_name.service.short_role_name_service import ShortRoleNameService
@ -9,6 +10,7 @@ class ShortRoleNameOnMemberUpdateEvent(OnMemberUpdateABC):
OnMemberUpdateABC.__init__(self)
self._service = service
@EventChecks.check_is_ready
async def on_member_update(self, before: discord.member.Member, after: discord.member.Member):
if before.roles != after.roles or before.name != after.name:
await self._service.check_short_role_names(after)

View File

@ -51,7 +51,8 @@ class SteamOfferWatcher(TaskABC):
self._urls = {}
self._image_urls = {}
self.watch.start()
if not self._is_maintenance():
self.watch.start()
@staticmethod
def _get_max_count() -> int: