From 9a259fba3aa916bab64fad360509d3a4378a8a8a Mon Sep 17 00:00:00 2001 From: Dany Date: Tue, 27 Aug 2024 14:39:49 +0200 Subject: [PATCH] =?UTF-8?q?ajout=20de=20l'option=20ics=20=C3=A0=20Envoi=20?= =?UTF-8?q?Automatique=20d'EDT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- data/UserBase.pkl | Bin 2150 -> 868 bytes src/MySlashCommand.py | 69 ++++++++++++++++++++++++++++-------------- src/MyTask.py | 5 +-- src/Tool.py | 47 ++++++++++++++++++++-------- src/UserBase.py | 53 ++++++++++++++++++++++++++++++-- 5 files changed, 134 insertions(+), 40 deletions(-) diff --git a/data/UserBase.pkl b/data/UserBase.pkl index 3f7474878c452dcb3fde567929249807ac08adcf..80a5342729a2895ca9502a48d10ac9630bb135da 100644 GIT binary patch delta 408 zcmaDR@Pv)Efpuym^F-DJHitznJ~qq~vwbE{Vis01R`AVCOi!KCIwfdIhDeW4h>L;| zL`cCgFFhwQvv}e@14RY~21_lrX)LW%8mDCNXf{r%ouZM!pP`W<5DR38XGl$+$82Ds zn4wmhl)=%(!OGyUt#K|7JDPH1kn#-i#0!S+u6$tufeJz1R1sNPrs zD4Ytj8Z4U%RBj0|SA>D7{PAK>E;MsJk{O^@BKgj=Xsy^eS3BB z{rQmoN%_qp8+3R@R_0((t_;g3WUHhLDM2y)xsn%-ut9J85k4S@wyuDW^@}ziFSZAQ zKAR{6x;y;dgRCqW_GG^YtB+9L+ zq+5khmnciR`czCoB~4wU+$ZmrIg4a;JDGJ%Bk%2G(;-&M>)`!78&rIor92n;Ru<_f z6l&x0Pvz%8viqiCIAf(SQz2K(t>8?pGFR&5%D8e#*C2F09#1RJFPbzn2#?2SJ%%V%`k) zqkA88;Jpn~PXx3;^ulb>89cKmDM-v));NxLX?GQ(Do<08C@zNHZ?Li-E5;~D6ieZu zxyPhR9an+F;4Ch?K4Lt9qVkJm%jDp1DVsJk4^xVeN zGOhwEKzn!FCcvle8fW6Fm2Dw;ncm3q$&1_~l=l{uBb5Ny6V4qq_$1v)fvHhBMkeF0 zdysBFK(a1i-GY}tpm|7rRw#-O%{?_DLlg6PERrF8+bVZr=CW1t8r)4x9kVb}l4Vr$ zNb;;R!Ql57s)kQdL!?9N?b>L3y&LcKGzE#`25_)$Qv#3K3I3>5fCI{d3$aj}?GJr@_tpRa diff --git a/src/MySlashCommand.py b/src/MySlashCommand.py index c3dad48..bacd3a6 100644 --- a/src/MySlashCommand.py +++ b/src/MySlashCommand.py @@ -160,7 +160,18 @@ async def ics(self, ctx: SlashContext, debut: str, fin: str) -> None: @slash_option( name="service", description="Mise a jour Quotidienne `DAILY`, Hebdomadaire `WEEKLY`, ou les deux `BOTH`.", - required=True, + required=False, + opt_type=OptionType.STRING, + choices=[ + SlashCommandChoice(name="Daily", value="DAILY"), + SlashCommandChoice(name="Weekly", value="WEEKLY"), + SlashCommandChoice(name="Both", value="BOTH") + ] + ) + @slash_option( + name="ics", + description="L'envoie du fichier ICS, Quotidienne `DAILY`, Hebdomadaire `WEEKLY`, ou les deux `BOTH`.", + required=False, opt_type=OptionType.STRING, choices=[ SlashCommandChoice(name="Daily", value="DAILY"), @@ -168,7 +179,7 @@ async def ics(self, ctx: SlashContext, debut: str, fin: str) -> None: SlashCommandChoice(name="Both", value="BOTH") ] ) - async def subscribe(self, ctx: SlashContext, service: str) -> None: + async def subscribe(self, ctx: SlashContext, service: str = "None", ics: str = "None") -> None: """Permet de s'abonnée à l'envoi automatique de l'EDT.""" user_base = get_user_base() id = ctx.author_id @@ -181,17 +192,22 @@ async def subscribe(self, ctx: SlashContext, service: str) -> None: user_base.user_subscribe(id, Subscription.WEEKLY) case "BOTH": user_base.user_subscribe(id, Subscription.BOTH) - await ctx.send( - embed=Embed(f"Abonnements de {ctx.author.display_name}", - f"- Mise à Jour Quotidienne : {'✅' if (user_base.is_user_subscribed(id, Subscription.DAILY)) else '❌'}\n" - f"- Mise à Jour Hebdomadaire : {'✅' if (user_base.is_user_subscribed(id, Subscription.WEEKLY)) else '❌'}"), - ephemeral=self.tool.is_guild_chan(ctx.author)) + + match ics: + case "DAILY": + user_base.user_subscribe_ics(id, Subscription.DAILY) + case "WEEKLY": + user_base.user_subscribe_ics(id, Subscription.WEEKLY) + case "BOTH": + user_base.user_subscribe_ics(id, Subscription.BOTH) + + await self.tool.check_subscription(ctx) @slash_command(name="unsubscribe", description="Vous permet de vous désabonner à l'envoi de l'EDT dans vos DM.") @slash_option( name="service", description="mise a jour Quotidienne `DAILY`, Hebdomadaire `WEEKLY`, ou les deux `BOTH`.", - required=True, + required=False, opt_type=OptionType.STRING, choices=[ SlashCommandChoice(name="Daily", value="DAILY"), @@ -199,7 +215,18 @@ async def subscribe(self, ctx: SlashContext, service: str) -> None: SlashCommandChoice(name="Both", value="BOTH") ] ) - async def unsubscribe(self, ctx: SlashContext, service: str) -> None: + @slash_option( + name="ics", + description="L'envoie du fichier ICS, Quotidienne `DAILY`, Hebdomadaire `WEEKLY`, ou les deux `BOTH`.", + required=False, + opt_type=OptionType.STRING, + choices=[ + SlashCommandChoice(name="Daily", value="DAILY"), + SlashCommandChoice(name="Weekly", value="WEEKLY"), + SlashCommandChoice(name="Both", value="BOTH") + ] + ) + async def unsubscribe(self, ctx: SlashContext, service: str = "None", ics: str = "None") -> None: """Permet de se désabonnée à l'envoi automatique de l'EDT.""" user_base = get_user_base() id = ctx.author_id @@ -212,25 +239,21 @@ async def unsubscribe(self, ctx: SlashContext, service: str) -> None: user_base.user_unsubscribe(id, Subscription.WEEKLY) case "BOTH": user_base.user_unsubscribe(id, Subscription.BOTH) - await ctx.send( - embed=Embed(f"Abonnements de {ctx.author.display_name}", - f"- Mise à Jour Quotidienne : {'✅' if (user_base.is_user_subscribed(id, Subscription.DAILY)) else '❌'}\n" - f"- Mise à Jour Hebdomadaire : {'✅' if (user_base.is_user_subscribed(id, Subscription.WEEKLY)) else '❌'}"), - ephemeral=self.tool.is_guild_chan(ctx.author) - ) + + match ics: + case "DAILY": + user_base.user_unsubscribe_ics(id, Subscription.DAILY) + case "WEEKLY": + user_base.user_unsubscribe_ics(id, Subscription.WEEKLY) + case "BOTH": + user_base.user_unsubscribe_ics(id, Subscription.BOTH) + await self.tool.check_subscription(ctx) @slash_command(name="check_subscription", description="Vous permet de consulter à quels service d'envoi d'EDT vous êtes inscrit.") async def check_subscription(self, ctx: SlashContext) -> None: """Permet d'afficher quel sont les abonnements d'un utilisateur.""" - user_base = get_user_base() - id = ctx.author_id - await ctx.send( - embed=Embed(f"Abonnements de {ctx.author.display_name}", - f"- Mise à Jour Quotidienne : {'✅' if (user_base.is_user_subscribed(id, Subscription.DAILY)) else '❌'}\n" - f"- Mise à Jour Hebdomadaire : {'✅' if (user_base.is_user_subscribed(id, Subscription.WEEKLY)) else '❌'}"), - ephemeral=self.tool.is_guild_chan(ctx.author) - ) + await self.tool.check_subscription(ctx) @slash_command(name="exam", description="Vous permet de consulter la liste des exams.") async def exam(self, ctx: SlashContext) -> None: diff --git a/src/MyTask.py b/src/MyTask.py index 9b6a546..72843e2 100644 --- a/src/MyTask.py +++ b/src/MyTask.py @@ -8,6 +8,7 @@ from Calendar import Calendar, changed_events from UserBase import get_user_base from Tool import get_tool +from Enums import Subscription load_dotenv("keys.env") @@ -76,8 +77,8 @@ async def daily_morning_update(self) -> None: # Pour l'envoi hebdomadaire. if datetime.today().weekday() == 0: for id in user_base.weekly_subscribed_users: - await self.tool.send_weekly_update(self.bot.get_user(id)) + await self.tool.send_weekly_update(self.bot.get_user(id), user_base.is_user_subscribed_ics(id, Subscription.WEEKLY)) # Pour l'envoi quotidien. if datetime.today().weekday() <= 4: # Si on est le week end for id in user_base.daily_subscribed_users: - await self.tool.send_daily_update(self.bot.get_user(id)) + await self.tool.send_daily_update(self.bot.get_user(id), user_base.is_user_subscribed_ics(id, Subscription.DAILY)) diff --git a/src/Tool.py b/src/Tool.py index 7130b8a..13e1470 100644 --- a/src/Tool.py +++ b/src/Tool.py @@ -6,7 +6,7 @@ from UserBase import get_user_base from Calendar import get_calendar from Filter import * -from Enums import RoleEnum, Group, colors +from Enums import RoleEnum, Group, colors, Subscription from datetime import datetime, date, timedelta @@ -208,26 +208,49 @@ async def get_week_bt(self, ctx: SlashContext | ModalContext | ContextMenuContex except ValueError: await ctx.send(embeds=[self.create_error_embed(f"La valeur `{semaine}` ne correspond pas à une date")], ephemeral=True) - async def send_daily_update(self, user: User): + async def send_daily_update(self, user: User, ics: bool): """Permet d'envoyer les EDT automatiquement pour le jour.""" events = filter_events(get_calendar().get_events(), [TimeFilter(date.today(), Timing.DURING), self.get_filiere(user), self.get_groupes(user)] ) embeds = get_embeds(events, user, date.today()) - filename = str(user.id) - ics_file = get_ics(events, filename=filename) - await user.send("Bonjour voici votre EDT pour aujourd'hui.\n:warning: : Le calendrier n'est pas mis a jour dynamiquement", embeds=embeds, files=[f"{filename}.ics"], ephemeral=False) - os.remove(f"{filename}.ics") + if ics: + filename = str(user.id) + ics_file = get_ics(events, filename=filename) + await user.send("Bonjour voici votre EDT pour aujourd'hui.\n:warning: : Le calendrier n'est pas mis a jour dynamiquement", embeds=embeds, files=[f"{filename}.ics"], ephemeral=False) + os.remove(f"{filename}.ics") + else: + await user.send("Bonjour voici votre EDT pour aujourd'hui.\n:warning: : Le calendrier n'est pas mis a jour dynamiquement", embeds=embeds, ephemeral=False) + - async def send_weekly_update(self, user: User): + async def send_weekly_update(self, user: User, ics: bool): """Permet d'envoyer les EDT automatiquement pour la semaine.""" days_since_monday = date.today().weekday() monday_date = date.today() - timedelta(days=days_since_monday) sunday_date = monday_date + timedelta(days=6) - filename = str(user.id) - events = filter_events (get_calendar().get_events(), [TimeFilter(monday_date, Timing.AFTER), TimeFilter(sunday_date, Timing.BEFORE), self.get_filiere(user), self.get_groupes(user)]) - ics_file = get_ics(events, filename=filename) - await user.send("Bonjour voici votre EDT pour la semaine.\n:warning: : Le calendrier n'est pas mis a jour dynamiquement", embeds=get_embeds(events, user, monday_date, sunday_date), files=[f"{filename}.ics"], ephemeral=False) - os.remove(f"{filename}.ics") + embeds = get_embeds(events, user, monday_date, sunday_date) + + if ics: + filename = str(user.id) + ics_file = get_ics(events, filename=filename) + await user.send("Bonjour voici votre EDT pour la semaine.\n:warning: : Le calendrier n'est pas mis a jour dynamiquement", embeds=embeds, files=[f"{filename}.ics"], ephemeral=False) + os.remove(f"{filename}.ics") + else: + await user.send("Bonjour voici votre EDT pour la semaine.\n:warning: : Le calendrier n'est pas mis a jour dynamiquement", embeds=embeds, ephemeral=False) + + + async def check_subscription(self, ctx: SlashContext) -> None: + """Permet d'afficher quel sont les abonnements d'un utilisateur.""" + user_base = get_user_base() + id = ctx.author_id + await ctx.send( + embed=Embed(f"Abonnements de {ctx.author.display_name}", + f"- Mise à Jour Quotidienne : {'✅' if (user_base.is_user_subscribed(id, Subscription.DAILY)) else '❌'}\n" + f"- Mise à Jour Hebdomadaire : {'✅' if (user_base.is_user_subscribed(id, Subscription.WEEKLY)) else '❌'}\n" + f"- Mise à Jour Quotidienne ICS: {'✅' if (user_base.is_user_subscribed_ics(id, Subscription.DAILY)) else '❌'}\n" + f"- Mise à Jour Hebdomadaire ICS: {'✅' if (user_base.is_user_subscribed_ics(id, Subscription.WEEKLY)) else '❌'}\n" + ), + ephemeral=self.is_guild_chan(ctx.author) + ) diff --git a/src/UserBase.py b/src/UserBase.py index 768b8b4..bc24b1b 100644 --- a/src/UserBase.py +++ b/src/UserBase.py @@ -17,10 +17,13 @@ def __str__(self) -> str: class UserBase: - def __init__(self, users: dict[int:DBUser], daily_subscribed_users: set, weekly_subscribed_users: set) -> None: + def __init__(self, users: dict[int:DBUser], daily_subscribed_users: set, weekly_subscribed_users: set, daily_subscribed_users_ics: set, weekly_subscribed_users_ics: set) -> None: self.users = users self.daily_subscribed_users = daily_subscribed_users self.weekly_subscribed_users = weekly_subscribed_users + self.daily_subscribed_users_ics = daily_subscribed_users_ics + self.weekly_subscribed_users_ics = weekly_subscribed_users_ics + def __str__(self) -> str: return f"" @@ -43,6 +46,20 @@ def is_user_subscribed(self, id: int, subscription: Subscription) -> bool: case Subscription.NONE: return (not is_daily) and (not is_weekly) + def is_user_subscribed_ics(self, id: int, subscription: Subscription) -> bool: + if self.has_user(id): + is_daily = id in self.daily_subscribed_users_ics + is_weekly = id in self.weekly_subscribed_users_ics + match subscription: + case Subscription.DAILY: + return is_daily + case Subscription.WEEKLY: + return is_weekly + case Subscription.BOTH: + return is_daily and is_weekly + case Subscription.NONE: + return (not is_daily) and (not is_weekly) + def add_user(self, id: int, groups: list[Group], filiere: Filiere) -> None: """Enregistre l'utilisateur s'il n'est pas déjà enregistré, sinon ne fait rien""" if not self.has_user(id): @@ -72,6 +89,7 @@ def user_subscribe(self, id: int, subscription: Subscription) -> None: def user_unsubscribe(self, id: int, subscription: Subscription) -> None: """Désabonne un utilisateur à une ou plusieurs des listes""" if self.has_user(id): + self.user_unsubscribe_ics(id, subscription) match subscription: case Subscription.DAILY if self.is_user_subscribed(id, subscription): self.daily_subscribed_users.remove(id) @@ -84,6 +102,35 @@ def user_unsubscribe(self, id: int, subscription: Subscription) -> None: self.weekly_subscribed_users.remove(id) dump_user_base(self) + def user_subscribe_ics(self, id: int, subscription: Subscription) -> None: + """Abonne un utilisateur à une ou plusieurs des listes""" + if self.has_user(id): + self.user_subscribe(id, subscription) + match subscription: + case Subscription.DAILY: + self.daily_subscribed_users_ics.add(id) + case Subscription.WEEKLY: + self.weekly_subscribed_users_ics.add(id) + case Subscription.BOTH: + self.daily_subscribed_users_ics.add(id) + self.weekly_subscribed_users_ics.add(id) + dump_user_base(self) + + def user_unsubscribe_ics(self, id: int, subscription: Subscription) -> None: + """Désabonne un utilisateur à une ou plusieurs des listes""" + if self.has_user(id): + match subscription: + case Subscription.DAILY if self.is_user_subscribed_ics(id, subscription): + self.daily_subscribed_users_ics.remove(id) + case Subscription.WEEKLY if self.is_user_subscribed_ics(id, subscription): + self.weekly_subscribed_users_ics.remove(id) + case Subscription.BOTH: + if self.is_user_subscribed_ics(id, Subscription.DAILY): + self.daily_subscribed_users_ics.remove(id) + if self.is_user_subscribed_ics(id, Subscription.WEEKLY): + self.weekly_subscribed_users_ics.remove(id) + dump_user_base(self) + def get_user(self, id: int) -> DBUser | None: """Retourne un Objet utilisateur s'il est présent dans la base de donnée, None sinon""" if self.has_user(id): @@ -110,7 +157,7 @@ def dump_user_base(user_base: UserBase): # puis arrêter le bot, # ensuite inverser les commentaires. -# user_base : UserBase = UserBase({}, set(), set()) +# user_base : UserBase = UserBase({}, set(), set(), set(), set()) def get_user_base() -> UserBase: global user_base @@ -119,5 +166,5 @@ def get_user_base() -> UserBase: def nuke(): global user_base - user_base = UserBase({}, set(), set()) + user_base = UserBase({}, set(), set(), set(), set()) dump_user_base(user_base)