Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removed service from Entity and updated welcome's embeds #101

Merged
merged 2 commits into from
Feb 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ min-public-methods=0
# Disable the message "C0114: Missing module docstring"
# Disabled the message "W0511: fixme"
# Disabled the message "R0913: Too many arguments"
disable=C0114, W0511, R0913
# Disabled the message "W0212: Access to a protected member _ of a client class"
disable=C0114, W0511, R0913, W0212

[FORMAT]
# Disabled the message "W0603: Using the global statement"
Expand Down
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
20 changes: 5 additions & 15 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 @@ -11,7 +13,7 @@ class GlobalConfig:
The name of the config.
"""

__slots__ = ("_id",)
__slots__ = ()

def __init__(self, _id: str) -> None:
"""
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
42 changes: 1 addition & 41 deletions bot/db/models/entity.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
"""Base entity class for all models"""

from abc import abstractmethod
from datetime import datetime

from bot.db.services import BaseService


class Entity:
"""
Expand All @@ -22,43 +19,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 +32,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."""
5 changes: 0 additions & 5 deletions bot/db/models/user.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""ADEPT User model."""

from bot.db.models.entity import Entity
from bot.db.services.user_service import UserService


class AdeptMember(Entity):
Expand Down Expand Up @@ -59,7 +58,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
4 changes: 2 additions & 2 deletions bot/db/services/configs_service.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""Service for dynamic bot configs."""

from ..models.bot_configs import GlobalConfig, SpamConfigs
from bot.db.models.bot_configs import GlobalConfig, SpamConfigs

from .base_service import BaseService
from bot.db.services.base_service import BaseService


class ConfigsService(BaseService):
Expand Down
2 changes: 1 addition & 1 deletion bot/db/services/user_service.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""User service."""

from .base_service import BaseService
from bot.db.services.base_service import BaseService


class UserService(BaseService):
Expand Down
10 changes: 9 additions & 1 deletion bot/management/welcome.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,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 +40,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
Loading