Skip to content

Commit

Permalink
Merge branch 'main' into release
Browse files Browse the repository at this point in the history
  • Loading branch information
danydudiot committed Oct 9, 2024
2 parents 4271f80 + 1ba78d3 commit 3b1dcf9
Show file tree
Hide file tree
Showing 8 changed files with 7,878 additions and 13,307 deletions.
6,781 changes: 3,404 additions & 3,377 deletions data/INGE.ics

Large diffs are not rendered by default.

5,507 changes: 0 additions & 5,507 deletions data/INGE_OLD.ics

This file was deleted.

8,766 changes: 4,383 additions & 4,383 deletions data/MIAGE.ics

Large diffs are not rendered by default.

53 changes: 38 additions & 15 deletions src/Calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@

class Calendar:
"""Classe utilisée pour stocker une liste d'objet Event."""
def __init__(self, update : bool, fleg_exam:list[str]) -> None:
def __init__(self, update : bool, argument) -> None:
""" Update : Si l'on doit télécharger les fichiers ics."""
# Dictionnaire qui stock les Event associé à l'UID.
self.events_dict : dict[str:Event]
self.events_list : list[Event]
self.exams_list : list[Event]

self.update_events(update, fleg_exam)
self.update_events(update, argument)

def fetch_calendar(self, url:str, filename:str) -> None:
"""Télécharge le fichier .ics.
Expand All @@ -38,7 +38,7 @@ def convert_timestamp(self, input: str) -> datetime:
iso_date = f"{input[0:4]}-{input[4:6]}-{input[6:11]}:{input[11:13]}:{input[13:]}"
return datetime.fromisoformat(iso_date).astimezone(timezone("Europe/Paris"))

def update_events(self, update: bool, flag_exam : list[str]) -> None:
def update_events(self, update: bool, argument) -> None:
"""Met à jour la liste d'événements en mêlant les événements issus des deux .ics.
Update : Si l'on doit télécharger les fichiers ics.
"""
Expand All @@ -54,7 +54,7 @@ def update_events(self, update: bool, flag_exam : list[str]) -> None:
self.fetch_calendar(url["MIAGE"], filenameMIAGE)

# | sert à concaténer deux dictionnaires.
output = self.parse_calendar(filenameINGE, flag_exam) | self.parse_calendar(filenameMIAGE, flag_exam)
output = self.parse_calendar(filenameINGE, argument) | self.parse_calendar(filenameMIAGE, argument)


self.events_dict = output
Expand All @@ -63,7 +63,7 @@ def update_events(self, update: bool, flag_exam : list[str]) -> None:

self.exams_list = sorted(list(self.exams_list),key=lambda event: event.start_timestamp)

def parse_calendar(self, filename:str, flag_exam:list[str]) -> dict[str:Event]:
def parse_calendar(self, filename:str, argument) -> dict[str:Event]:
"""Extrait les données du fichier .ics passé dans filename.
Filename : Chemin du fichier."""
# On lit tout le fichiers ICS
Expand All @@ -90,7 +90,7 @@ def parse_calendar(self, filename:str, flag_exam:list[str]) -> dict[str:Event]:
event["LOCATION"],
event["DESCRIPTION"],
event["UID"],
flag_exam
argument
)
if e.isEXAM:
exams.append(e)
Expand All @@ -106,15 +106,38 @@ def parse_calendar(self, filename:str, flag_exam:list[str]) -> dict[str:Event]:
event[prefix.removesuffix(":")] = line.removeprefix(prefix).removesuffix("\n")
break

# Exam list.

exams += [
# Event(
# start=datetime(day=3, month=6, year=2024, hour=13, minute=30, second=0, microsecond=0, tzinfo=timezone("Europe/Paris")),
# end=datetime(day=3, month=6, year=2024, hour=13, minute=30, second=0, microsecond=0, tzinfo=timezone("Europe/Paris")),
# subject="Exam Anglais", group=Group.CM, location="S103", teacher="Anne-Cécile Alzy", isINGE=True, isMIAGE=True, uid="EXAM01",
# isEXAM=True)
]
for new_event in argument.get("add_event").values():
e = Event(
self.convert_timestamp(new_event["start"]),
self.convert_timestamp(new_event["end"]),
new_event["subject"],
new_event["group"],
new_event["location"],
new_event["teacher"],
new_event["isINGE"]=="True",
new_event["isMIAGE"]=="True",
new_event["uid"],
new_event["isEXAM"]=="True"
)
if e.isEXAM:
exams.append(e)
else:
events[e.uid] = e

for over_uid in argument.get("override_event").keys():
override_event = argument.get("override_event").get(over_uid)
events[over_uid] = Event(
self.convert_timestamp(override_event["start"]),
self.convert_timestamp(override_event["end"]),
override_event["subject"],
override_event["group"],
override_event["location"],
override_event["teacher"],
override_event["isINGE"]=="True",
override_event["isMIAGE"]=="True",
override_event["uid"],
override_event["isEXAM"]=="True"
)

self.exams_list = exams

Expand Down
8 changes: 6 additions & 2 deletions src/Event.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def ics(self) -> str:
return ics


def get_event_from_data(start:datetime, end:datetime, sum:str, loc:str, desc:str, uid:str, flag_exam: list[str]) -> Event:
def get_event_from_data(start:datetime, end:datetime, sum:str, loc:str, desc:str, uid:str, argument) -> Event:
"""Permet d'extraire les informations des données parsées."""
# Événements spéciaux.
if sum == "Réunion rentrée - L3 INGENIERIE INFORMATIQUE":
Expand All @@ -158,7 +158,7 @@ def get_event_from_data(start:datetime, end:datetime, sum:str, loc:str, desc:str
teacher = descsplit[-3].replace("\n", "").removeprefix(" ") if descsplit[-3] != "L3 INFORMAT-UPEX MINERVE" else "Enseignant ?"
location = loc if not loc == "" else "Salle ?"

is_exam = uid in flag_exam
is_exam = uid in argument.get("exam_list")


# Valeur par défaut.
Expand Down Expand Up @@ -259,5 +259,9 @@ def get_event_from_data(start:datetime, end:datetime, sum:str, loc:str, desc:str
print(exception)
sentry_sdk.capture_exception(exception)


if "CC" in sum:
teacher = "équipe enseignante"

# Crée un nouvel Objet Event à partir des infos calculées.
return Event(start, end, subject, group, location, teacher, isINGE, isMIAGE, uid, is_exam)
15 changes: 1 addition & 14 deletions src/MySlashCommand.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,17 +349,4 @@ async def nuke(self, ctx: SlashContext) -> None:
@contexts(guild=True, bot_dm=False)
async def bd(self, ctx: SlashContext) -> None:
"""Permet d'obtenir la BD."""
await ctx.send("Voici la BD.", file="data/UserBase.pkl", ephemeral=False)

@slash_command(name="test_change", description="Permet de modifier le ics.",
default_member_permissions=Permissions.ADMINISTRATOR)
@contexts(guild=True, bot_dm=False)
async def test_change(self, ctx: SlashContext) -> None:
"""Permet d'obtenir la BD."""
with open("data/INGE_OLD.ics", "r") as file_source:
content = file_source.read()

with open("data/INGE.ics", "w") as file_prod:
file_prod.write(content)

await ctx.send("Le fichier ics à été modifier.", ephemeral=False)
await ctx.send("Voici la BD.", file="data/UserBase.pkl", ephemeral=False)
14 changes: 5 additions & 9 deletions src/MyTask.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,11 @@ async def update_calendar(self) -> None:
await self.bot.get_channel(os.getenv("ERROR_CHANNEL_ID")).send("Exécution de `update_calendar`")
except:
pass
channels = self.bot.guilds[0].channels
arguement: dict[str:dict[str:str]] = None
for channel in channels:
if channel.name =="arguement-bot":
contenu = (await channel.fetch_messages(1))[0].content
arguement = json.loads(contenu)

old_calendar = Calendar(False, list(arguement.get("exam_list").values()))
new_calendar = Calendar(True, list(arguement.get("exam_list").values()))

arguement = await self.tool.get_arguement()

old_calendar = Calendar(False, arguement)
new_calendar = Calendar(True, arguement)
sup, add, mod, changed_id = changed_events(old_calendar, new_calendar)
try:
await self.bot.get_channel(os.getenv("ERROR_CHANNEL_ID")).send(f"Fichier du {datetime.now()}", files=["data/INGE.ics", "data/MIAGE.ics"])
Expand Down
41 changes: 41 additions & 0 deletions src/Tool.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import json
import urllib
from http.client import HTTPException
from time import sleep
from urllib.error import URLError
from urllib.request import urlretrieve

import aiohttp
import sentry_sdk
from interactions import Client, ActionRow, Button, ButtonStyle, SlashContext, Guild, Role, Embed, User, Member, \
ModalContext, ContextMenuContext, ComponentContext
Expand Down Expand Up @@ -379,6 +385,41 @@ async def userscan(self, ctx: SlashContext) -> None:

await ctx.send("Les membres du serveur ont été ajoutée et mit à jour.", ephemeral=True)

async def download_file(self, url, filename):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
if resp.status == 200:
with open(filename, 'wb') as f:
f.write(await resp.read())
else:
raise ValueError("Le fichier n'à pas été télécharger")


async def get_arguement(self):
channels = self.bot.guilds[0].channels
arguement: dict[str:dict[str:str]] = None
for channel in channels:
if channel.name == "arguement-bot":
url = (await channel.fetch_messages(1))[0].attachments[0].url
filename = "arguement.json"
try:
await self.download_file(url, filename)
except ValueError as exception:
await self.send_error(exception)
sentry_sdk.capture_exception(exception)

try:
with open(filename, 'r', encoding='utf-8') as file:
arguement = json.load(file)
except BaseException as exception:
exception.add_note("C'est le chargement du fichier d'argument qui à foiré")
await self.send_error(exception)
sentry_sdk.capture_exception(exception)
arguement = {} # Pour éviter de planter

os.remove(filename)
return arguement

tool: Tool | None = None


Expand Down

0 comments on commit 3b1dcf9

Please sign in to comment.