From 9f3f12e2724d89e29f6f7e425fb17e551941112d Mon Sep 17 00:00:00 2001 From: DeveloperAnonymous <40847862+DeveloperAnonymous@users.noreply.github.com> Date: Sat, 17 Feb 2024 21:27:28 -0500 Subject: [PATCH] Removed service from Entity and updated welcome's embeds --- bot/botcommands/bot_configs.py | 12 ++++++- bot/db/models/bot_configs.py | 18 +++-------- bot/db/models/entity.py | 39 +---------------------- bot/db/models/user.py | 4 --- bot/db/services/__init__.py | 2 +- bot/management/welcome.py | 11 ++++++- bot/welcome.py | 58 ++++++++++++++++------------------ 7 files changed, 55 insertions(+), 89 deletions(-) diff --git a/bot/botcommands/bot_configs.py b/bot/botcommands/bot_configs.py index 779d94a..616613e 100644 --- a/bot/botcommands/bot_configs.py +++ b/bot/botcommands/bot_configs.py @@ -21,7 +21,13 @@ async def get_spam_configs(self, ctx: commands.Context): """Affiche la configuration du spam.""" spam_config = self.configs_service.find_or_create_spam_configs() - await ctx.send(spam_config.__getstate__()) + data = spam_config.__getstate__() + message = "```json\n" + for key in spam_config.__slots__: + message += f"{key}: {data[key]}\n" + message += "```" + + await ctx.send(message) @commands.command(name="editspamconfig", aliases=["esc"]) @commands.guild_only() @@ -30,6 +36,10 @@ async def edit_spam_config(self, ctx: commands.Context, key: str, value: int): """ Modifie la configuration du spam. + Paramètres: + Repetition: Le nombre de messages qui peuvent être envoyés avant d'être mute. + Mute_time: Le temps en secondes que l'utilisateur sera mute. + Utilisation: !editspamconfig repetition 10 !editspamconfig mute_time 60 diff --git a/bot/db/models/bot_configs.py b/bot/db/models/bot_configs.py index f673efc..415a6d9 100644 --- a/bot/db/models/bot_configs.py +++ b/bot/db/models/bot_configs.py @@ -1,7 +1,9 @@ """Models for dynamic bot configs.""" +from bot.db.models.entity import Entity -class GlobalConfig: + +class GlobalConfig(Entity): """ Model for global configs. @@ -20,22 +22,13 @@ def __init__(self, _id: str) -> None: `_id` : str The name of the config. """ - self._id = _id + super().__init__(_id) @property def config_id(self): """The id of the config.""" return self._id - def __getstate__(self): - state = {} - for cls in self.__class__.__mro__: - if hasattr(cls, "__slots__"): - for slot in cls.__slots__: - if hasattr(self, slot): - state[slot] = getattr(self, slot) - return state - class SpamConfigs(GlobalConfig): """ @@ -51,9 +44,6 @@ class SpamConfigs(GlobalConfig): __slots__ = ("repetition", "mute_time") - repetition: int - mute_time: int - def __init__(self) -> None: super().__init__("spam") self.repetition = 3 diff --git a/bot/db/models/entity.py b/bot/db/models/entity.py index 28ea169..a2802f4 100644 --- a/bot/db/models/entity.py +++ b/bot/db/models/entity.py @@ -22,43 +22,11 @@ class Entity: __slots__ = ("_id", "created_at", "updated_at") - def __init__(self, _id: int, created_at: datetime = None, updated_at: datetime = None): + def __init__(self, _id: int, created_at: datetime = datetime.utcnow(), updated_at: datetime = datetime.utcnow()): self._id = _id self.created_at = created_at self.updated_at = updated_at - if self._id is not None: - self._load() - - def save(self, upsert=True): - """ - Save the entity to the database. - - Parameters - ---------- - `upsert` : bool - Whether to insert the entity if it doesn't exist. Defaults to True. - """ - if self.created_at is None: - self.created_at = datetime.utcnow() - self.updated_at = self.created_at - else: - self.updated_at = datetime.utcnow() - - return self.service.update_one({"_id": self._id}, self.__getstate__(), upsert=upsert) - - def delete(self): - """Delete the entity from the database.""" - return self.service.delete_one({"_id": self._id}) - - def _load(self): - """Load the entity from the database.""" - entity: dict = self.service.find_one({"_id": self._id}) - - if entity is not None: - self.created_at = entity.get("created_at") - self.updated_at = entity.get("updated_at") - def __getstate__(self): state = {} for cls in self.__class__.__mro__: @@ -67,8 +35,3 @@ def __getstate__(self): if hasattr(self, slot): state[slot] = getattr(self, slot) return state - - @property - @abstractmethod - def service(self) -> BaseService: - """The service for the entity.""" diff --git a/bot/db/models/user.py b/bot/db/models/user.py index 2f3660c..d387fdf 100644 --- a/bot/db/models/user.py +++ b/bot/db/models/user.py @@ -59,7 +59,3 @@ def __init__( self.program = program super().__init__(discord_id, **kwargs) - - @property - def service(self) -> UserService: - return UserService() diff --git a/bot/db/services/__init__.py b/bot/db/services/__init__.py index 893d55a..4bfe99a 100644 --- a/bot/db/services/__init__.py +++ b/bot/db/services/__init__.py @@ -1,5 +1,5 @@ """This module contains all the services that are used to interact with the database.""" from .base_service import BaseService -from .configs_service import ConfigsService, SpamConfigs +from .configs_service import ConfigsService from .user_service import UserService diff --git a/bot/management/welcome.py b/bot/management/welcome.py index e35cc51..1fa82b7 100644 --- a/bot/management/welcome.py +++ b/bot/management/welcome.py @@ -6,6 +6,7 @@ import configs from bot import util, welcome from bot.db.services import UserService +from bot.db.models import AdeptMember class WelcomeCog(commands.Cog): @@ -18,10 +19,14 @@ def __init__(self) -> None: @commands.guild_only() async def setup(self, ctx: commands.Context): """Setup the member.""" - author: discord.Member = ctx.author + author = ctx.author message = await ctx.reply("Nous vous avons envoyé un message en privé avec les instructions!") try: result = await welcome.walk_through_welcome(author) + if not result: + return + + self.user_service.update_one({"_id": result._id}, result.__getstate__(), upsert=True) await welcome.process_welcome_result(author, result) except discord.Forbidden as error: await message.delete() @@ -36,4 +41,8 @@ async def on_member_join(self, member: discord.Member): await util.say(configs.WELCOME_CHANNEL, configs.WELCOME_SERVER.format(name=member.mention)) result = await welcome.walk_through_welcome(member) + if not result: + return + + self.user_service.update_one({"_id": result._id}, result.__getstate__(), upsert=True) await welcome.process_welcome_result(member, result) diff --git a/bot/welcome.py b/bot/welcome.py index db09c24..8cb3b23 100644 --- a/bot/welcome.py +++ b/bot/welcome.py @@ -57,7 +57,7 @@ async def __handle_on_timeout(member: discord.Member, message: discord.Message) raise NoReplyException(member) -async def walk_through_welcome(member: discord.Member): +async def walk_through_welcome(member: discord.Member) -> AdeptMember | None: """ Walks through the welcome process with the given member @@ -82,47 +82,45 @@ async def walk_through_welcome(member: discord.Member): welcome_user = AdeptMember(member.id, full_name, email, is_student) - confirmation_embed = discord.Embed(title="Est-ce que ces informations sont tous exactes?", color=0xF9E18B) - confirmation_embed.add_field(name="Nom:", value=full_name, inline=False) - confirmation_embed.add_field(name="Email:", value=email, inline=False) - confirmation_embed.add_field(name="Étudiant:", value="Oui" if is_student else "Non", inline=False) - if is_student: process_student_result = await __process_student(member, original_message) welcome_user.student_id = process_student_result.student_number welcome_user.program = process_student_result.program welcome_user.is_it_student = process_student_result.is_it_student - - confirmation_embed.add_field( - name="Numéro étudiant:", - value=process_student_result.student_number, - inline=False, - ) - if process_student_result.program is not None: - confirmation_embed.add_field(name="Programme:", value=process_student_result.program, inline=False) else: is_teacher = await __process_teacher(member, original_message) welcome_user.is_teacher = is_teacher - confirmation_embed.add_field(name="Professeur:", value="Oui" if is_teacher else "Non", inline=False) - - confirmed = await __process_confirmation(member, confirmation_embed) + confirmed = await __process_confirmation(member, welcome_user) if confirmed is None: - welcome_user.save() - return welcome_user if confirmed: return await walk_through_welcome(member) - return await member.send("Parfait, on ne recommence pas!") + await member.send("Parfait, on ne recommence pas!") -async def __process_confirmation(member: discord.Member, embed: discord.Embed): +async def __process_confirmation(member: discord.Member, result: AdeptMember): + confirmation_embed = discord.Embed(title="Est-ce que ces informations sont tous exactes?", color=0xF9E18B) + confirmation_embed.add_field(name="Nom:", value=result.name, inline=False) + confirmation_embed.add_field(name="Email:", value=result.email, inline=False) + + if result.is_student: + confirmation_embed.add_field( + name="Numéro étudiant:", + value=result.student_id, + inline=False, + ) + if result.program is not None: + confirmation_embed.add_field(name="Programme:", value=result.program, inline=False) + elif result.is_teacher: + confirmation_embed.add_field(name="Professeur:", value="Oui" if result.is_teacher else "Non", inline=False) + confirmation_view = YesNoInteraction() - confirmation_message: discord.Message = await member.send(embed=embed, view=confirmation_view) + confirmation_message: discord.Message = await member.send(embed=confirmation_embed, view=confirmation_view) confirmed = await confirmation_view.start() if confirmed is None: @@ -136,7 +134,7 @@ async def __process_confirmation(member: discord.Member, embed: discord.Embed): restart_message = await member.send("D'accord, voulez-vous recommencer?", view=confirmation_view) restart = await confirmation_view.start() - await restart_message.edit(view=confirmation_view) + await restart_message.edit(view=None) if restart is None: await __handle_on_timeout(member, restart_message) @@ -233,7 +231,7 @@ async def __process_student(member: discord.Member, original_message: discord.Me return result -async def create_welcome_embed(member: discord.User, adept_member: AdeptMember): +async def create_welcome_embed(member: discord.User, result: AdeptMember): """ Creates the welcome embed for the new member. @@ -249,22 +247,22 @@ async def create_welcome_embed(member: discord.User, adept_member: AdeptMember): color=0xF9E18B, timestamp=discord.utils.utcnow(), ) - embed.add_field(name="Nom:", value=adept_member.name, inline=False) - embed.add_field(name="Email:", value=adept_member.email, inline=False) - embed.add_field(name="Numéro étudiant:", value=adept_member.student_id, inline=False) + embed.add_field(name="Nom:", value=result.name, inline=False) + embed.add_field(name="Email:", value=result.email, inline=False) + embed.add_field(name="Numéro étudiant:", value=result.student_id if result.is_student else "N/A", inline=False) embed.add_field( name="Étudiant:", - value="Oui" if adept_member.is_student else "Non", + value="Oui" if result.is_student else "Non", inline=False, ) embed.add_field( name="Professeur:", - value="Oui" if adept_member.is_teacher else "Non", + value="Oui" if result.is_teacher else "Non", inline=False, ) embed.add_field( name="Programme:", - value=(adept_member.program if adept_member.is_it_student else "N'est pas en informatique"), + value=(result.program if result.is_it_student else "N'est pas en informatique"), inline=False, ) embed.set_footer(text=f"ID: {member.id}")