Merge pull request 'Levelsystem per Befehl neuladen #164' (#175) from #164 into 0.3.1

Reviewed-on: sh-edraft.de/kd_discord_bot#175
Reviewed-by: Ebola-Chan <nick.jungmann@gmail.com>
Closes #164
This commit is contained in:
Sven Heidemann 2023-01-13 22:15:11 +01:00
commit 624625d4b5
3 changed files with 188 additions and 64 deletions

View File

@ -1,5 +1,5 @@
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from typing import Union from typing import Union, Optional
import discord import discord
from cpl_query.extension import List from cpl_query.extension import List
@ -19,13 +19,24 @@ class MessageServiceABC(ABC):
async def delete_message(self, message: discord.Message, without_tracking=False): pass async def delete_message(self, message: discord.Message, without_tracking=False): pass
@abstractmethod @abstractmethod
async def send_channel_message(self, channel: discord.TextChannel, message: Union[str, discord.Embed], without_tracking=True): pass async def send_channel_message(
self, channel: discord.TextChannel, message: Union[str, discord.Embed], without_tracking=True
): pass
@abstractmethod @abstractmethod
async def send_dm_message(self, message: Union[str, discord.Embed], receiver: Union[discord.User, discord.Member], without_tracking=False): pass async def send_dm_message(
self, message: Union[str, discord.Embed], receiver: Union[discord.User, discord.Member],
without_tracking=False
): pass
@abstractmethod @abstractmethod
async def send_ctx_msg(self, ctx: Context, message: Union[str, discord.Embed], file: discord.File = None, is_persistent: bool = False, is_public: bool = False, wait_before_delete: int = None, without_tracking=True): pass async def send_ctx_msg(
self, ctx: Context, message: Union[str, discord.Embed], file: discord.File = None,
is_persistent: bool = False, is_public: bool = False, wait_before_delete: int = None, without_tracking=True
) -> Optional[discord.Message]: pass
@abstractmethod @abstractmethod
async def send_interaction_msg(self, interaction: Interaction, message: Union[str, discord.Embed], is_persistent: bool = False, is_public: bool = False, wait_before_delete: int = None, without_tracking=True, **kwargs): pass async def send_interaction_msg(
self, interaction: Interaction, message: Union[str, discord.Embed], is_persistent: bool = False,
is_public: bool = False, wait_before_delete: int = None, without_tracking=True, **kwargs
): pass

View File

@ -1,5 +1,5 @@
import asyncio import asyncio
from typing import Union from typing import Union, Optional
import discord import discord
from cpl_core.configuration.configuration_abc import ConfigurationABC from cpl_core.configuration.configuration_abc import ConfigurationABC
@ -18,7 +18,8 @@ from bot_data.abc.client_repository_abc import ClientRepositoryABC
class MessageService(MessageServiceABC): class MessageService(MessageServiceABC):
def __init__(self, config: ConfigurationABC, logger: MessageLogger, bot: DiscordBotServiceABC, clients: ClientRepositoryABC, db: DatabaseContextABC): def __init__(self, config: ConfigurationABC, logger: MessageLogger, bot: DiscordBotServiceABC,
clients: ClientRepositoryABC, db: DatabaseContextABC):
self._config = config self._config = config
self._logger = logger self._logger = logger
self._bot = bot self._bot = bot
@ -34,11 +35,16 @@ class MessageService(MessageServiceABC):
self._logger.debug(__name__, 'Deleting messages finished') self._logger.debug(__name__, 'Deleting messages finished')
async def delete_message(self, message: discord.Message, mass_delete=False, without_tracking=False): async def delete_message(self, message: discord.Message, mass_delete=False, without_tracking=False):
server_st: ServerSettings = self._config.get_configuration(f'ServerSettings_{message.guild.id}') guild_id = \
message.guild.id if message.guild is not None else \
message.channel.guild.id if message.channel is not None and message.channel.guild is not None else \
message.reference.guild_id if message.reference is not None and message.reference.guild_id is not None \
else None
server_st: ServerSettings = self._config.get_configuration(f'ServerSettings_{guild_id}')
if not mass_delete: if not mass_delete:
await asyncio.sleep(server_st.message_delete_timer) await asyncio.sleep(server_st.message_delete_timer)
self._logger.debug(__name__, f'Try to delete message: {LogMessageHelper.get_log_string(message)}') self._logger.debug(__name__, f'Try to delete message: {LogMessageHelper.get_log_string(message)}')
guild_id = message.guild.id
try: try:
await message.delete() await message.delete()
await asyncio.sleep(server_st.message_delete_timer) await asyncio.sleep(server_st.message_delete_timer)
@ -50,7 +56,10 @@ class MessageService(MessageServiceABC):
self._db.save_changes() self._db.save_changes()
self._logger.info(__name__, f'Deleted message {message}') self._logger.info(__name__, f'Deleted message {message}')
async def send_channel_message(self, channel: discord.TextChannel, message: Union[str, discord.Embed], is_persistent: bool = False, wait_before_delete: int = None, without_tracking=False): async def send_channel_message(
self, channel: discord.TextChannel, message: Union[str, discord.Embed], is_persistent: bool = False,
wait_before_delete: int = None, without_tracking=False
):
self._logger.debug(__name__, f'Try to send message\n\t{message}\n\tto: {channel}') self._logger.debug(__name__, f'Try to send message\n\t{message}\n\tto: {channel}')
msg = None msg = None
try: try:
@ -74,7 +83,10 @@ class MessageService(MessageServiceABC):
await self.delete_message(msg, without_tracking) await self.delete_message(msg, without_tracking)
async def send_dm_message(self, message: Union[str, discord.Embed], receiver: Union[discord.User, discord.Member], without_tracking=False): async def send_dm_message(
self, message: Union[str, discord.Embed], receiver: Union[discord.User, discord.Member],
without_tracking=False
):
self._logger.debug(__name__, f'Try to send message\n\t{message}\n\tto: {receiver}') self._logger.debug(__name__, f'Try to send message\n\t{message}\n\tto: {receiver}')
try: try:
if isinstance(message, discord.Embed): if isinstance(message, discord.Embed):
@ -89,11 +101,14 @@ class MessageService(MessageServiceABC):
self._db.save_changes() self._db.save_changes()
self._logger.info(__name__, f'Sent message to user {receiver.id}') self._logger.info(__name__, f'Sent message to user {receiver.id}')
async def send_ctx_msg(self, ctx: Context, message: Union[str, discord.Embed], file: discord.File = None, is_persistent: bool = False, is_public: bool = False, wait_before_delete: int = None, without_tracking=False): async def send_ctx_msg(
self, ctx: Context, message: Union[str, discord.Embed], file: discord.File = None,
is_persistent: bool = False, is_public: bool = False, wait_before_delete: int = None, without_tracking=False
) -> Optional[discord.Message]:
if ctx is None: if ctx is None:
self._logger.warn(__name__, 'Message context is empty') self._logger.warn(__name__, 'Message context is empty')
self._logger.debug(__name__, f'Message: {message}') self._logger.debug(__name__, f'Message: {message}')
return return None
self._logger.debug(__name__, f'Try to send message\t\t{message}\n\tto: {ctx.channel}') self._logger.debug(__name__, f'Try to send message\t\t{message}\n\tto: {ctx.channel}')
msg = None msg = None
@ -114,12 +129,17 @@ class MessageService(MessageServiceABC):
await asyncio.sleep(wait_before_delete) await asyncio.sleep(wait_before_delete)
if is_persistent: if is_persistent:
return return msg
if ctx.guild is not None: if ctx.guild is not None:
await self.delete_message(msg, without_tracking) await self.delete_message(msg, without_tracking)
async def send_interaction_msg(self, interaction: Interaction, message: Union[str, discord.Embed], is_persistent: bool = False, is_public: bool = False, wait_before_delete: int = None, without_tracking=False, **kwargs): return msg
async def send_interaction_msg(
self, interaction: Interaction, message: Union[str, discord.Embed], is_persistent: bool = False,
is_public: bool = False, wait_before_delete: int = None, without_tracking=False, **kwargs
):
if interaction is None: if interaction is None:
self._logger.warn(__name__, 'Message context is empty') self._logger.warn(__name__, 'Message context is empty')
self._logger.debug(__name__, f'Message: {message}') self._logger.debug(__name__, f'Message: {message}')

View File

@ -83,20 +83,34 @@ class LevelGroup(DiscordCommandABC):
self._logger.trace(__name__, f'Loaded command service: {type(self).__name__}') self._logger.trace(__name__, f'Loaded command service: {type(self).__name__}')
async def _seed_levels(self, channel: discord.TextChannel): async def _seed_levels(self, ctx: Context):
# send message to ctx.channel because send_ctx_msg resolves ctx # send message to ctx.channel because send_ctx_msg resolves ctx
try: try:
await self._message_service.send_channel_message(channel, self._t.transform('modules.level.seeding_started')) start = await self._message_service.send_ctx_msg(
ctx,
self._t.transform('modules.level.seeding_started'),
is_persistent=True
)
await self._level_seeder.seed() await self._level_seeder.seed()
await self._message_service.send_channel_message(channel, self._t.transform('modules.level.seeding_finished'))
end = await self._message_service.send_ctx_msg(
ctx,
self._t.transform('modules.level.seeding_finished'),
is_persistent=True
)
await self._message_service.delete_message(start)
await self._message_service.delete_message(end)
except Exception as e: except Exception as e:
self._logger.error(__name__, f'Level seeding failed', e) self._logger.error(__name__, f'Level seeding failed', e)
await self._message_service.send_channel_message(channel, self._t.transform('modules.level.seeding_failed')) await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.seeding_failed'))
async def _level_auto_complete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: async def _level_auto_complete(self, interaction: discord.Interaction, current: str) -> TList[
app_commands.Choice[str]]:
server = self._servers.get_server_by_discord_id(interaction.guild.id) server = self._servers.get_server_by_discord_id(interaction.guild.id)
levels = self._levels.get_levels_by_server_id(server.server_id).select(lambda l: l.name) levels = self._levels.get_levels_by_server_id(server.server_id).select(lambda l: l.name)
return [app_commands.Choice(name=level, value=level) for level in self._client_utils.get_auto_complete_list(levels, current)] return [app_commands.Choice(name=level, value=level) for level in
self._client_utils.get_auto_complete_list(levels, current)]
@commands.hybrid_group() @commands.hybrid_group()
@commands.guild_only() @commands.guild_only()
@ -167,41 +181,66 @@ class LevelGroup(DiscordCommandABC):
if levels.where(lambda l: l.name == level.name).first_or_default() is not None: if levels.where(lambda l: l.name == level.name).first_or_default() is not None:
self._logger.debug(__name__, f'Level with name {level.name} already exists') self._logger.debug(__name__, f'Level with name {level.name} already exists')
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.error.level_with_name_already_exists').format(level.name)) await self._message_service.send_ctx_msg(
ctx,
self._t.transform('modules.level.error.level_with_name_already_exists').format(level.name)
)
elif levels.where(lambda l: l.min_xp == level.min_xp).first_or_default() is not None: elif levels.where(lambda l: l.min_xp == level.min_xp).first_or_default() is not None:
self._logger.debug(__name__, f'Level with min_xp {level.min_xp} already exists {level.name}') self._logger.debug(__name__, f'Level with min_xp {level.min_xp} already exists {level.name}')
found_level = levels.where(lambda l: l.min_xp == level.min_xp).first_or_default() found_level = levels.where(lambda l: l.min_xp == level.min_xp).first_or_default()
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.error.level_with_xp_already_exists').format(found_level.name, found_level.min_xp)) await self._message_service.send_ctx_msg(ctx, self._t.transform(
'modules.level.error.level_with_xp_already_exists').format(found_level.name, found_level.min_xp))
else: else:
try: try:
self._levels.add_level(level) self._levels.add_level(level)
self._db.save_changes() self._db.save_changes()
self._logger.info(__name__, f'Saved level {name} with color {color}, min_xp {min_xp} and permissions {permissions}') self._logger.info(
__name__, f'Saved level {name} with color {color}, min_xp {min_xp} and permissions {permissions}'
)
except Exception as e: except Exception as e:
self._logger.error(__name__, f'Could not save level {name} with color {color}, min_xp {min_xp} and permissions {permissions}', e) self._logger.error(
__name__,
f'Could not save level {name} with color {color}, min_xp {min_xp} and permissions {permissions}',
e
)
else: else:
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.create.created').format(name, permissions)) await self._message_service.send_ctx_msg(
await self._seed_levels(ctx.channel) ctx,
self._t.transform('modules.level.create.created').format(name, permissions)
)
await self._seed_levels(ctx)
self._logger.trace(__name__, f'Finished command level create') self._logger.trace(__name__, f'Finished command level create')
@create.autocomplete('color') @create.autocomplete('color')
async def create_color_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: async def create_color_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[
app_commands.Choice[str]]:
# value in rg format see: # value in rg format see:
# https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour.to_rgb # https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour.to_rgb
return [app_commands.Choice(name=self._t.transform(f'common.colors.{color}'), value=f'rgb({code[0]}, {code[1]}, {code[2]})') for color, code in self._colors] return [
app_commands.Choice(
name=self._t.transform(f'common.colors.{color}'), value=f'rgb({code[0]}, {code[1]}, {code[2]})'
) for color, code in self._colors
]
@level.command() @level.command()
@commands.guild_only() @commands.guild_only()
@CommandChecks.check_is_ready() @CommandChecks.check_is_ready()
@CommandChecks.check_is_member_admin() @CommandChecks.check_is_member_admin()
async def edit(self, ctx: Context, level: str, name: str = None, color: str = None, min_xp: int = None, permissions: int = None): async def edit(
self, ctx: Context, level: str, name: str = None, color: str = None, min_xp: int = None,
permissions: int = None
):
self._logger.debug(__name__, f'Received command level edit {ctx}') self._logger.debug(__name__, f'Received command level edit {ctx}')
server = self._servers.get_server_by_discord_id(ctx.guild.id) server = self._servers.get_server_by_discord_id(ctx.guild.id)
level_from_db = self._levels.get_levels_by_server_id(server.server_id).where(lambda l: l.name == level).single_or_default() level_from_db = self._levels.get_levels_by_server_id(server.server_id).where(
lambda l: l.name == level).single_or_default()
if level_from_db is None: if level_from_db is None:
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.edit.not_found').format(level)) await self._message_service.send_ctx_msg(
ctx,
self._t.transform('modules.level.edit.not_found').format(level)
)
return return
guild: Guild = self._bot.guilds.where(lambda g: g == ctx.guild).single() guild: Guild = self._bot.guilds.where(lambda g: g == ctx.guild).single()
@ -214,7 +253,10 @@ class LevelGroup(DiscordCommandABC):
try: try:
level_from_db.color = hex(discord.Colour.from_str(color).value) level_from_db.color = hex(discord.Colour.from_str(color).value)
except Exception as e: except Exception as e:
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.edit.color_invalid').format(color)) await self._message_service.send_ctx_msg(
ctx,
self._t.transform('modules.level.edit.color_invalid').format(color)
)
self._logger.error(__name__, f'Error parsing color {color}', e) self._logger.error(__name__, f'Error parsing color {color}', e)
return return
@ -225,33 +267,51 @@ class LevelGroup(DiscordCommandABC):
try: try:
level_from_db.permissions = discord.Permissions(permissions).value level_from_db.permissions = discord.Permissions(permissions).value
except Exception as e: except Exception as e:
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.edit.permission_invalid').format(permissions)) await self._message_service.send_ctx_msg(ctx, self._t.transform(
'modules.level.edit.permission_invalid').format(permissions))
self._logger.error(__name__, f'Error parsing permissions {permissions}', e) self._logger.error(__name__, f'Error parsing permissions {permissions}', e)
return return
try: try:
self._levels.update_level(level_from_db) self._levels.update_level(level_from_db)
self._db.save_changes() self._db.save_changes()
await role.edit(name=level_from_db.name, permissions=discord.Permissions(level_from_db.permissions), colour=discord.Colour(int(level_from_db.color, 16))) await role.edit(
self._logger.info(__name__, name=level_from_db.name,
f'Saved level {level_from_db.name} with color {level_from_db.color}, min_xp {level_from_db.min_xp} and permissions {level_from_db.permissions}') permissions=discord.Permissions(level_from_db.permissions),
colour=discord.Colour(int(level_from_db.color, 16))
)
self._logger.info(
__name__,
f'Saved level {level_from_db.name} with color {level_from_db.color}, min_xp {level_from_db.min_xp} and permissions {level_from_db.permissions}'
)
except Exception as e: except Exception as e:
self._logger.error(__name__, f'Could not save level {level} with color {color}, min_xp {min_xp} and permissions {permissions}', e) self._logger.error(
__name__,
f'Could not save level {level} with color {color}, min_xp {min_xp} and permissions {permissions}',
e
)
else: else:
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.edit.edited').format(level)) await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.edit.edited').format(level))
await self._seed_levels(ctx.channel) await self._seed_levels(ctx)
self._logger.trace(__name__, f'Finished command level edit') self._logger.trace(__name__, f'Finished command level edit')
@edit.autocomplete('level') @edit.autocomplete('level')
async def edit_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: async def edit_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[
app_commands.Choice[str]]:
return await self._level_auto_complete(interaction, current) return await self._level_auto_complete(interaction, current)
@edit.autocomplete('color') @edit.autocomplete('color')
async def edit_color_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: async def edit_color_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[
app_commands.Choice[str]]:
# value in rg format see: # value in rg format see:
# https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour.to_rgb # https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour.to_rgb
return [app_commands.Choice(name=self._t.transform(f'common.colors.{color}'), value=f'rgb({code[0]}, {code[1]}, {code[2]})') for color, code in self._colors] return [
app_commands.Choice(
name=self._t.transform(f'common.colors.{color}'),
value=f'rgb({code[0]}, {code[1]}, {code[2]})'
) for color, code in self._colors
]
@level.command() @level.command()
@commands.guild_only() @commands.guild_only()
@ -261,10 +321,14 @@ class LevelGroup(DiscordCommandABC):
self._logger.debug(__name__, f'Received command level remove {ctx}') self._logger.debug(__name__, f'Received command level remove {ctx}')
server = self._servers.get_server_by_discord_id(ctx.guild.id) server = self._servers.get_server_by_discord_id(ctx.guild.id)
level_from_db = self._levels.get_levels_by_server_id(server.server_id).where(lambda l: l.name == level).first_or_default() level_from_db = self._levels.get_levels_by_server_id(server.server_id).where(
lambda l: l.name == level).first_or_default()
if level_from_db is None: if level_from_db is None:
self._logger.debug(__name__, f'level {level} not found') self._logger.debug(__name__, f'level {level} not found')
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.remove.error.not_found').format(level)) await self._message_service.send_ctx_msg(
ctx,
self._t.transform('modules.level.remove.error.not_found').format(level)
)
self._logger.trace(__name__, f'Finished command level remove') self._logger.trace(__name__, f'Finished command level remove')
return return
@ -279,13 +343,17 @@ class LevelGroup(DiscordCommandABC):
except Exception as e: except Exception as e:
self._logger.error(__name__, f'Could not remove level {level}', e) self._logger.error(__name__, f'Could not remove level {level}', e)
else: else:
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.remove.success').format(level)) await self._message_service.send_ctx_msg(
await self._seed_levels(ctx.channel) ctx,
self._t.transform('modules.level.remove.success').format(level)
)
await self._seed_levels(ctx)
self._logger.trace(__name__, f'Finished command level remove') self._logger.trace(__name__, f'Finished command level remove')
@remove.autocomplete('level') @remove.autocomplete('level')
async def remove_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: async def remove_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[
app_commands.Choice[str]]:
return await self._level_auto_complete(interaction, current) return await self._level_auto_complete(interaction, current)
@level.command() @level.command()
@ -304,7 +372,9 @@ class LevelGroup(DiscordCommandABC):
levels = self._levels.get_levels_by_server_id(server.server_id).order_by(lambda l: l.min_xp) levels = self._levels.get_levels_by_server_id(server.server_id).order_by(lambda l: l.min_xp)
if level == levels.first(): if level == levels.first():
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.down.already_first').format(member.mention)) await self._message_service.send_ctx_msg(
ctx, self._t.transform('modules.level.down.already_first').format(member.mention)
)
self._logger.trace(__name__, f'Finished command level down') self._logger.trace(__name__, f'Finished command level down')
return return
@ -313,11 +383,13 @@ class LevelGroup(DiscordCommandABC):
user.xp = new_level.min_xp user.xp = new_level.min_xp
self._users.update_user(user) self._users.update_user(user)
self._db.save_changes() self._db.save_changes()
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.down.success').format(member.mention, new_level.name)) await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.down.success').format(
member.mention, new_level.name))
await self._level_service.set_level(user) await self._level_service.set_level(user)
except Exception as e: except Exception as e:
self._logger.error(__name__, f'Cannot level down {member.name} with level {level.name}', e) self._logger.error(__name__, f'Cannot level down {member.name} with level {level.name}', e)
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.down.failed').format(member.mention)) await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.down.failed').format(
member.mention))
self._logger.trace(__name__, f'Finished command level down') self._logger.trace(__name__, f'Finished command level down')
@ -337,7 +409,10 @@ class LevelGroup(DiscordCommandABC):
levels = self._levels.get_levels_by_server_id(server.server_id).order_by(lambda l: l.min_xp) levels = self._levels.get_levels_by_server_id(server.server_id).order_by(lambda l: l.min_xp)
if level.name == levels.last().name: if level.name == levels.last().name:
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.up.already_last').format(member.mention)) await self._message_service.send_ctx_msg(
ctx,
self._t.transform('modules.level.up.already_last').format(member.mention)
)
self._logger.trace(__name__, f'Finished command level up') self._logger.trace(__name__, f'Finished command level up')
return return
@ -346,11 +421,13 @@ class LevelGroup(DiscordCommandABC):
user.xp = new_level.min_xp user.xp = new_level.min_xp
self._users.update_user(user) self._users.update_user(user)
self._db.save_changes() self._db.save_changes()
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.up.success').format(member.mention, new_level.name)) await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.up.success').format(
member.mention, new_level.name))
await self._level_service.set_level(user) await self._level_service.set_level(user)
except Exception as e: except Exception as e:
self._logger.error(__name__, f'Cannot level up {member.name} with level {level.name}', e) self._logger.error(__name__, f'Cannot level up {member.name} with level {level.name}', e)
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.up.failed').format(member.mention)) await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.up.failed').format(
member.mention))
self._logger.trace(__name__, f'Finished command level up') self._logger.trace(__name__, f'Finished command level up')
@ -367,15 +444,20 @@ class LevelGroup(DiscordCommandABC):
server = self._servers.get_server_by_discord_id(ctx.guild.id) server = self._servers.get_server_by_discord_id(ctx.guild.id)
user = self._users.get_user_by_discord_id_and_server_id(member.id, server.server_id) user = self._users.get_user_by_discord_id_and_server_id(member.id, server.server_id)
current_level = self._level_service.get_level(user) current_level = self._level_service.get_level(user)
new_level = self._levels.get_levels_by_server_id(server.server_id).where(lambda l: l.name == level).single_or_default() new_level = self._levels.get_levels_by_server_id(server.server_id).where(
lambda l: l.name == level).single_or_default()
if new_level is None: if new_level is None:
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.set.not_found').format(level)) await self._message_service.send_ctx_msg(
ctx,
self._t.transform('modules.level.set.not_found').format(level)
)
self._logger.trace(__name__, f'Finished command level set') self._logger.trace(__name__, f'Finished command level set')
return return
if current_level.name == level: if current_level.name == level:
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.set.already_level').format(member.mention, level)) await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.set.already_level').format(
member.mention, level))
self._logger.trace(__name__, f'Finished command level set') self._logger.trace(__name__, f'Finished command level set')
return return
@ -383,14 +465,25 @@ class LevelGroup(DiscordCommandABC):
user.xp = new_level.min_xp user.xp = new_level.min_xp
self._users.update_user(user) self._users.update_user(user)
self._db.save_changes() self._db.save_changes()
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.set.success').format(member.mention, new_level.name)) await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.set.success').format(
member.mention, new_level.name))
await self._level_service.set_level(user) await self._level_service.set_level(user)
except Exception as e: except Exception as e:
self._logger.error(__name__, f'Cannot set level {level} for {member.name}', e) self._logger.error(__name__, f'Cannot set level {level} for {member.name}', e)
await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.set.failed').format(member.mention)) await self._message_service.send_ctx_msg(ctx, self._t.transform('modules.level.set.failed').format(
member.mention))
self._logger.trace(__name__, f'Finished command level set') self._logger.trace(__name__, f'Finished command level set')
@set.autocomplete('level') @set.autocomplete('level')
async def set_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]: async def set_autocomplete(self, interaction: discord.Interaction, current: str) -> TList[app_commands.Choice[str]]:
return await self._level_auto_complete(interaction, current) return await self._level_auto_complete(interaction, current)
@level.command()
@commands.guild_only()
@CommandChecks.check_is_ready()
@CommandChecks.check_is_member_moderator()
async def reload(self, ctx: Context):
self._logger.debug(__name__, f'Received command level reload {ctx}')
await self._seed_levels(ctx)
self._logger.trace(__name__, f'Finished command level reload')