Skip to content

Commit

Permalink
Removed service from Entity and updated welcome's embeds
Browse files Browse the repository at this point in the history
  • Loading branch information
DeveloperAnonymous committed Feb 18, 2024
1 parent 7d1024f commit 9f3f12e
Show file tree
Hide file tree
Showing 7 changed files with 55 additions and 89 deletions.
12 changes: 11 additions & 1 deletion bot/botcommands/bot_configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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
Expand Down
18 changes: 4 additions & 14 deletions bot/db/models/bot_configs.py
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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):
"""
Expand All @@ -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
Expand Down
39 changes: 1 addition & 38 deletions bot/db/models/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__:
Expand All @@ -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."""
4 changes: 0 additions & 4 deletions bot/db/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,3 @@ def __init__(
self.program = program

super().__init__(discord_id, **kwargs)

@property
def service(self) -> UserService:
return UserService()
2 changes: 1 addition & 1 deletion bot/db/services/__init__.py
Original file line number Diff line number Diff line change
@@ -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
11 changes: 10 additions & 1 deletion bot/management/welcome.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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()
Expand All @@ -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)
58 changes: 28 additions & 30 deletions bot/welcome.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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)

Expand Down Expand Up @@ -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.
Expand All @@ -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}")
Expand Down

0 comments on commit 9f3f12e

Please sign in to comment.