Merge pull request 'XP abziehen bei löschen einer Nachricht #178' (#180) from #178 into 0.3.1

Reviewed-on: sh-edraft.de/kd_discord_bot#180
Reviewed-by: Ebola-Chan <nick.jungmann@gmail.com>
Closes #178
This commit is contained in:
Sven Heidemann 2023-01-13 23:06:22 +01:00
commit 0c76269e40
9 changed files with 128 additions and 7 deletions

View File

@ -44,7 +44,9 @@ class Application(DiscordBotApplicationABC):
try: try:
self._logger.debug(__name__, f'Starting...') self._logger.debug(__name__, f'Starting...')
if self._feature_flags.get_flag(FeatureFlagsEnum.api_module) and self._feature_flags.get_flag(FeatureFlagsEnum.api_only) and self._environment.environment_name == 'development': if self._feature_flags.get_flag(FeatureFlagsEnum.api_module) and \
self._feature_flags.get_flag(FeatureFlagsEnum.api_only) and \
self._environment.environment_name == 'development':
self._api.start() self._api.start()
self._api.join() self._api.join()
return return

View File

@ -16,10 +16,10 @@
"LicenseName": "MIT", "LicenseName": "MIT",
"LicenseDescription": "MIT, see LICENSE for more details.", "LicenseDescription": "MIT, see LICENSE for more details.",
"Dependencies": [ "Dependencies": [
"cpl-core==2022.12.0", "cpl-core==2022.12.1.post2",
"cpl-translation==2022.10.0.post2", "cpl-translation==2022.12.1",
"cpl-query==2022.12.2", "cpl-query==2022.12.2.post1",
"cpl-discord==2022.12.0", "cpl-discord==2022.12.1.post2",
"Flask==2.2.2", "Flask==2.2.2",
"Flask-Classful==0.14.2", "Flask-Classful==0.14.2",
"Flask-Cors==3.0.10", "Flask-Cors==3.0.10",
@ -31,7 +31,7 @@
"icmplib==3.0.3" "icmplib==3.0.3"
], ],
"DevDependencies": [ "DevDependencies": [
"cpl-cli==2022.12.0" "cpl-cli==2022.12.1.post2"
], ],
"PythonVersion": ">=3.10.4", "PythonVersion": ">=3.10.4",
"PythonPath": {}, "PythonPath": {},

View File

View File

@ -0,0 +1,20 @@
from cpl_core.application import ApplicationExtensionABC
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
class InitBotExtension(ApplicationExtensionABC):
def __init__(self):
ApplicationExtensionABC.__init__(self)
async def run(self, config: ConfigurationABC, services: ServiceProviderABC):
settings = config.get_configuration(BotSettings)
bot: DiscordBotServiceABC = services.get_service(
DiscordBotServiceABC,
max_messages=settings.cache_max_messages
)

View File

@ -6,6 +6,7 @@ from cpl_core.application import ApplicationBuilder
from cpl_core.console import Console from cpl_core.console import Console
from bot.application import Application from bot.application import Application
from bot.extension.init_bot_extension import InitBotExtension
from bot.startup import Startup from bot.startup import Startup
from bot.startup_discord_extension import StartupDiscordExtension from bot.startup_discord_extension import StartupDiscordExtension
from bot.startup_migration_extension import StartupMigrationExtension from bot.startup_migration_extension import StartupMigrationExtension
@ -29,6 +30,7 @@ class Program:
.use_extension(StartupDiscordExtension) \ .use_extension(StartupDiscordExtension) \
.use_extension(StartupModuleExtension) \ .use_extension(StartupModuleExtension) \
.use_extension(StartupMigrationExtension) \ .use_extension(StartupMigrationExtension) \
.use_extension(InitBotExtension) \
.use_extension(BootLogExtension) \ .use_extension(BootLogExtension) \
.use_extension(DatabaseExtension) \ .use_extension(DatabaseExtension) \
.use_extension(AppApiExtension) \ .use_extension(AppApiExtension) \

View File

@ -16,6 +16,7 @@ class BotSettings(ConfigurationModelABC):
self._technicians: List[int] = List(int) self._technicians: List[int] = List(int)
self._wait_for_restart = 2 self._wait_for_restart = 2
self._wait_for_shutdown = 2 self._wait_for_shutdown = 2
self._cache_max_messages = 1000
@property @property
def servers(self) -> List[ServerSettings]: def servers(self) -> List[ServerSettings]:
@ -33,6 +34,10 @@ class BotSettings(ConfigurationModelABC):
def wait_for_shutdown(self) -> int: def wait_for_shutdown(self) -> int:
return self._wait_for_shutdown return self._wait_for_shutdown
@property
def cache_max_messages(self) -> int:
return self._cache_max_messages
def from_dict(self, settings: dict): def from_dict(self, settings: dict):
try: try:
self._technicians = settings["Technicians"] self._technicians = settings["Technicians"]
@ -41,6 +46,11 @@ class BotSettings(ConfigurationModelABC):
settings.pop("Technicians") settings.pop("Technicians")
settings.pop("WaitForRestart") settings.pop("WaitForRestart")
settings.pop("WaitForShutdown") settings.pop("WaitForShutdown")
if 'CacheMaxMessages' in settings:
self._cache_max_messages = settings["CacheMaxMessages"]
settings.pop("CacheMaxMessages")
servers = List(ServerSettings) servers = List(ServerSettings)
for s in settings: for s in settings:
st = ServerSettings() st = ServerSettings()

View File

@ -19,6 +19,7 @@ from modules.base.events.base_on_command_error_event import BaseOnCommandErrorEv
from modules.base.events.base_on_command_event import BaseOnCommandEvent from modules.base.events.base_on_command_event import BaseOnCommandEvent
from modules.base.events.base_on_member_join_event import BaseOnMemberJoinEvent from modules.base.events.base_on_member_join_event import BaseOnMemberJoinEvent
from modules.base.events.base_on_member_remove_event import BaseOnMemberRemoveEvent from modules.base.events.base_on_member_remove_event import BaseOnMemberRemoveEvent
from modules.base.events.base_on_message_delete_event import BaseOnMessageDeleteEvent
from modules.base.events.base_on_message_event import BaseOnMessageEvent from modules.base.events.base_on_message_event import BaseOnMessageEvent
from modules.base.events.base_on_raw_reaction_add import BaseOnRawReactionAddEvent from modules.base.events.base_on_raw_reaction_add import BaseOnRawReactionAddEvent
from modules.base.events.base_on_raw_reaction_remove import BaseOnRawReactionRemoveEvent from modules.base.events.base_on_raw_reaction_remove import BaseOnRawReactionRemoveEvent
@ -55,6 +56,7 @@ class BaseModule(ModuleABC):
self._dc.add_event(DiscordEventTypesEnum.on_member_join.value, BaseOnMemberJoinEvent) self._dc.add_event(DiscordEventTypesEnum.on_member_join.value, BaseOnMemberJoinEvent)
self._dc.add_event(DiscordEventTypesEnum.on_member_remove.value, BaseOnMemberRemoveEvent) self._dc.add_event(DiscordEventTypesEnum.on_member_remove.value, BaseOnMemberRemoveEvent)
self._dc.add_event(DiscordEventTypesEnum.on_message.value, BaseOnMessageEvent) self._dc.add_event(DiscordEventTypesEnum.on_message.value, BaseOnMessageEvent)
self._dc.add_event(DiscordEventTypesEnum.on_message_delete.value, BaseOnMessageDeleteEvent)
self._dc.add_event(DiscordEventTypesEnum.on_raw_reaction_add.value, BaseOnRawReactionAddEvent) self._dc.add_event(DiscordEventTypesEnum.on_raw_reaction_add.value, BaseOnRawReactionAddEvent)
self._dc.add_event(DiscordEventTypesEnum.on_raw_reaction_remove.value, BaseOnRawReactionRemoveEvent) self._dc.add_event(DiscordEventTypesEnum.on_raw_reaction_remove.value, BaseOnRawReactionRemoveEvent)
self._dc.add_event(DiscordEventTypesEnum.on_voice_state_update.value, BaseOnVoiceStateUpdateEvent) self._dc.add_event(DiscordEventTypesEnum.on_voice_state_update.value, BaseOnVoiceStateUpdateEvent)

View File

@ -0,0 +1,83 @@
from typing import Optional
import discord
from cpl_core.database.context import DatabaseContextABC
from cpl_discord.events import OnMessageDeleteABC
from cpl_discord.service import DiscordBotServiceABC
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.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,
clients: ClientRepositoryABC,
servers: ServerRepositoryABC,
):
OnMessageDeleteABC.__init__(self)
self._logger = logger
self._base_helper = bhs
self._db = db
self._bot = bot
self._users = users
self._clients = clients
self._servers = servers
def _append_deleted_message_count(self, g_id: int):
try:
self._clients.append_deleted_message_count(self._bot.user.id, g_id, 1)
self._db.save_changes()
except Exception as e:
self._logger.error(__name__, f'Cannot edit client {self._bot.user.id}@{g_id}', e)
def _handle_message_delete(self, message: discord.Message):
dc_user_id = message.author.id
try:
server = self._servers.get_server_by_discord_id(message.guild.id)
except Exception as e:
self._logger.error(__name__, f'Cannot get server {message.guild.id}', e)
return
user: Optional[User] = None
try:
user = self._users.find_user_by_discord_id_and_server_id(dc_user_id, server.server_id)
except Exception as e:
self._logger.error(__name__, f'Cannot get user {dc_user_id}', e)
return
if user is None:
self._logger.error(__name__, f'User not found {dc_user_id}')
return
settings: BaseServerSettings = self._base_helper.get_config(message.guild.id)
old_xp = user.xp
user.xp -= settings.xp_per_message
self._users.update_user(user)
self._db.save_changes()
self._logger.debug(__name__, f'Removed message from user {user}. xp: from {old_xp} to {user.xp}')
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:
return
self._logger.info(__name__, f'Received message: {LogMessageHelper.get_log_string(message)}')
self._append_deleted_message_count(message.guild.id)
if not message.author.bot:
self._handle_message_delete(message)
self._logger.debug(__name__, f'Module {type(self)} stopped')

View File

@ -83,10 +83,12 @@ class BaseOnMessageEvent(OnMessageABC):
@EventChecks.check_is_ready() @EventChecks.check_is_ready()
async def on_message(self, message: discord.Message): async def on_message(self, message: discord.Message):
self._logger.debug(__name__, f'Module {type(self)} started') self._logger.debug(__name__, f'Module {type(self)} started')
self._logger.info(__name__, f'Received message: {LogMessageHelper.get_log_string(message)}')
if message is None or message.guild is None: if message is None or message.guild is None:
return return
self._logger.info(__name__, f'Received message: {LogMessageHelper.get_log_string(message)}')
self._append_received_message_count(message.guild.id) self._append_received_message_count(message.guild.id)
if not message.author.bot: if not message.author.bot:
self._handle_message_for_xp(message) self._handle_message_for_xp(message)
self._logger.debug(__name__, f'Module {type(self)} stopped')