diff --git a/db/Calendar.py b/db/Calendar.py index 4c0e776..5dbe11d 100644 --- a/db/Calendar.py +++ b/db/Calendar.py @@ -37,7 +37,7 @@ class Calendar(Base): def events(self, first_date: datetime, last_date: datetime) -> [ics.Event]: events = [] - for e in list(self.cal(first_date, last_date).events)[::-1]: + for e in sorted(list(self.cal(first_date, last_date).events), key=lambda x: x.begin): e.begin = e.begin.replace(tzinfo=timezone.utc).astimezone(tz=None) e.end = e.begin.replace(tzinfo=timezone.utc).astimezone(tz=None) e.organizer = name_re.findall(e.description)[0] diff --git a/extensions/calendar.py b/extensions/calendar.py index b60d8c5..1f65eb0 100644 --- a/extensions/calendar.py +++ b/extensions/calendar.py @@ -1,5 +1,5 @@ import re -from datetime import datetime, timezone +from datetime import datetime, timedelta import ics import requests @@ -17,6 +17,15 @@ url_re = re.compile(r"http:\/\/adelb\.univ-lyon1\.fr\/jsp\/custom\/modules\/plan r"([0-9]+)&projectId=([0-9]+)") +def query_calendar(name: str, guild: int) -> db.Calendar: + s = db.Session() + c: db.Calendar = s.query(db.Calendar).filter(db.Calendar.server == guild).filter(db.Calendar.name == name).first() + s.close() + if not c: + raise BadArgument() + return c + + class Calendar(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot @@ -82,10 +91,7 @@ class Calendar(commands.Cog): @calendar.group("day", pass_context=True) async def calendar_day(self, ctx: commands.Context, name: str, day: str = None): - s = db.Session() - c: db.Calendar = s.query(db.Calendar).filter(db.Calendar.server == ctx.guild.id).filter(db.Calendar.name == name).first() - if not c: - raise BadArgument() + c = query_calendar(name, ctx.guild.id) if day is None: date = datetime.now() else: @@ -99,6 +105,28 @@ class Calendar(commands.Cog): value=f"{e.name} | {e.location} - {e.organizer}", inline=False) await ctx.send(embed=embed) + @calendar.group("week", pass_context=True) + async def calendar_week(self, ctx: commands.Context, name: str, day: str = None): + c = query_calendar(name, ctx.guild.id) + if day is None: + date = datetime.now() + else: + try: + date = datetime.strptime(day, "%d/%m/%Y") + except ValueError: + raise BadArgument() + date -= timedelta(days=date.weekday()) + embed = Embed(title=f"Week calendar: {c.name}", + description=f"{date.strftime('%d/%m/%Y')} - {(date + timedelta(days=4)).strftime('%d/%m/%Y')}") + for d in range(5): + events = [] + for e in c.events(date, date): + events.append(f"*{e.begin.strftime('%H:%M')} - {e.end.strftime('%H:%M')}*: " + f"**{e.name}** | {e.location} - {e.organizer}") + embed.add_field(name=date.strftime("%d/%m/%Y"), value="\n".join(events) or "Nothing !", inline=False) + date = date + timedelta(days=1) + await ctx.send(embed=embed) + @commands.Cog.listener() async def on_command_error(self, ctx: commands.Context, error): if ctx.invoked_with == extension_name or \