From 5e2afd21f1f2c021d48844d1fdbc8e28248af13d Mon Sep 17 00:00:00 2001 From: h7x4 Date: Tue, 26 May 2026 14:47:36 +0900 Subject: [PATCH] ruff format --- src/pvv_calendar_bot/event.py | 15 ++++-- src/pvv_calendar_bot/main.py | 40 +++++++++------- src/pvv_calendar_bot/scraping.py | 68 ++++++++++++++++++--------- src/pvv_calendar_bot/sql_connector.py | 30 +++++++----- 4 files changed, 97 insertions(+), 56 deletions(-) diff --git a/src/pvv_calendar_bot/event.py b/src/pvv_calendar_bot/event.py index 88baff4..e02bab3 100644 --- a/src/pvv_calendar_bot/event.py +++ b/src/pvv_calendar_bot/event.py @@ -1,7 +1,16 @@ import datetime + class Event: - def __init__(self, id: int, start: datetime.datetime, name: str, location: str, organizer: str, description: str): + def __init__( + self, + id: int, + start: datetime.datetime, + name: str, + location: str, + organizer: str, + description: str, + ): self.id = id self.start = start self.name = name @@ -10,7 +19,7 @@ class Event: self.description = description def __str__(self): - return f'{self.name} ({self.id})' + return f"{self.name} ({self.id})" def __repr__(self): - return f'Event({self.id}, {self.start}, {self.name})' + return f"Event({self.id}, {self.start}, {self.name})" diff --git a/src/pvv_calendar_bot/main.py b/src/pvv_calendar_bot/main.py index e8ab7cb..9e47fd7 100644 --- a/src/pvv_calendar_bot/main.py +++ b/src/pvv_calendar_bot/main.py @@ -10,16 +10,19 @@ from markdown2 import Markdown import asyncio from .sql_connector import fetch_events, Event -MATRIX_URL=os.environ.get("MATRIX_URL","https://matrix.pvv.ntnu.no").strip() -MATRIX_USER=os.environ.get("MATRIX_USER","@bot_calendar:pvv.ntnu.no").strip() -MATRIX_TOKEN=os.environ.get("MATRIX_TOKEN").strip() -ANNOUNCEMENT_CHANNEL=os.environ.get("ANNOUNCEMENT_CHANNEL", "!announcements:pvv.ntnu.no").strip() +MATRIX_URL = os.environ.get("MATRIX_URL", "https://matrix.pvv.ntnu.no").strip() +MATRIX_USER = os.environ.get("MATRIX_USER", "@bot_calendar:pvv.ntnu.no").strip() +MATRIX_TOKEN = os.environ.get("MATRIX_TOKEN").strip() +ANNOUNCEMENT_CHANNEL = os.environ.get( + "ANNOUNCEMENT_CHANNEL", "!announcements:pvv.ntnu.no" +).strip() client = None + def create_announcement(event: Event, atEveryone: bool) -> str: url = "https://www.pvv.ntnu.no/hendelser/info.php?id={}".format(event.id) - msgText = dedent('''\ + msgText = dedent("""\ ## Dagens arrangement / Event of the Day: "{name}" - 🕒 **{start}** - 📍 **{location}** @@ -27,26 +30,24 @@ def create_announcement(event: Event, atEveryone: bool) -> str: {description} [Les mer / Read More]({url}) - ''').format( - name=event.name, - start=event.start.strftime('%H:%M'), - location=event.location, - description=event.description, - url=url, - ) + """).format( + name=event.name, + start=event.start.strftime("%H:%M"), + location=event.location, + description=event.description, + url=url, + ) if atEveryone: - msgText = msgText + '\n@room' + msgText = msgText + "\n@room" return msgText async def sendMatrixAnnouncement( - event: Event, - channel: str = ANNOUNCEMENT_CHANNEL, - atEveryone: bool = False + event: Event, channel: str = ANNOUNCEMENT_CHANNEL, atEveryone: bool = False ) -> None: - msgText = create_announcement(event,atEveryone) + msgText = create_announcement(event, atEveryone) return await client.room_send( room_id=channel, message_type="m.room.message", @@ -55,9 +56,10 @@ async def sendMatrixAnnouncement( "body": msgText, "format": "org.matrix.custom.html", "formatted_body": Markdown().convert(msgText), - } + }, ) + async def sendCalendarEvents() -> None: global client client = AsyncClient(MATRIX_URL, MATRIX_USER) @@ -70,8 +72,10 @@ async def sendCalendarEvents() -> None: await client.close() + def main(): asyncio.run(sendCalendarEvents()) + if __name__ == "__main__": main() diff --git a/src/pvv_calendar_bot/scraping.py b/src/pvv_calendar_bot/scraping.py index 771c722..9c408a8 100644 --- a/src/pvv_calendar_bot/scraping.py +++ b/src/pvv_calendar_bot/scraping.py @@ -7,10 +7,11 @@ from operator import add from functools import reduce import datetime + def get_soup() -> BeautifulSoup: r = requests.get("http://www.pvv.ntnu.no/hendelser/") soup = BeautifulSoup(r.text, "html.parser") - return soup + return soup def process_soup(soup: BeautifulSoup) -> List[Event]: @@ -18,24 +19,49 @@ def process_soup(soup: BeautifulSoup) -> List[Event]: events = soup.find_all("ul", "events") for event in events: - times, locations, organizers = zip(*(list( - map(lambda x: map(lambda y: y.find("strong").text, x), - filter(lambda x: x != [], - map(lambda x: x.find_all("li"), - event.find_all("li"))))))) - times = list(map(lambda x: datetime.datetime.strptime(x, "%A %d. %b %H.%M").replace(year=datetime.datetime.now().year), times)) - names = list(map(lambda x: x[0].text, - filter(lambda x: x != [], - map(lambda x: x.find_all("a"), - event.find_all("li"))))) - descriptions = list(map(lambda x: x.text, - filter(lambda x: x is not None, - map(lambda x: x.find("p"), - event.find_all("li"))))) + times, locations, organizers = zip( + *( + list( + map( + lambda x: map(lambda y: y.find("strong").text, x), + filter( + lambda x: x != [], + map(lambda x: x.find_all("li"), event.find_all("li")), + ), + ) + ) + ) + ) + times = list( + map( + lambda x: datetime.datetime.strptime(x, "%A %d. %b %H.%M").replace( + year=datetime.datetime.now().year + ), + times, + ) + ) + names = list( + map( + lambda x: x[0].text, + filter( + lambda x: x != [], + map(lambda x: x.find_all("a"), event.find_all("li")), + ), + ) + ) + descriptions = list( + map( + lambda x: x.text, + filter( + lambda x: x is not None, + map(lambda x: x.find("p"), event.find_all("li")), + ), + ) + ) ids = [] for a in event.find_all("a", href=True): - if a['href'][:10] == '/hendelser': - ids.append(int(a['href'][a['href'].find("=")+1:])) + if a["href"][:10] == "/hendelser": + ids.append(int(a["href"][a["href"].find("=") + 1 :])) zips.append(list(zip(ids, times, names, organizers, locations, descriptions))) @@ -45,12 +71,10 @@ def process_soup(soup: BeautifulSoup) -> List[Event]: def get_events_today(events: List[Event]) -> List[Event]: - return list(filter(lambda e: e.start.date() == datetime.datetime.today().date(), events)) + return list( + filter(lambda e: e.start.date() == datetime.datetime.today().date(), events) + ) if __name__ == "__main__": print(get_events_today(process_soup(get_soup()))) - - - - diff --git a/src/pvv_calendar_bot/sql_connector.py b/src/pvv_calendar_bot/sql_connector.py index b86bdb6..370d4a5 100644 --- a/src/pvv_calendar_bot/sql_connector.py +++ b/src/pvv_calendar_bot/sql_connector.py @@ -4,11 +4,13 @@ from pprint import pprint import os from datetime import datetime + @dataclass class Event: """ An Event with id,name,start,stop,location,description,organiser """ + id: int name: str start: datetime @@ -20,10 +22,10 @@ class Event: def fetch_events(): mydb = mysql.connector.connect( - host = os.environ.get("MYSQL_URL","mysql.pvv.ntnu.no").strip(), - user = os.environ.get("MYSQL_USER","calendar-bot").strip(), - password = os.environ["MYSQL_PASSWORD"].strip(), - database = "www-data_nettside", + host=os.environ.get("MYSQL_URL", "mysql.pvv.ntnu.no").strip(), + user=os.environ.get("MYSQL_USER", "calendar-bot").strip(), + password=os.environ["MYSQL_PASSWORD"].strip(), + database="www-data_nettside", ) mycursor = mydb.cursor() @@ -37,15 +39,17 @@ def fetch_events(): results = [] for row in db_result: - results.append(Event( - id = row[0], - name = row[1], - start = datetime.fromisoformat(row[2]), - stop = datetime.fromisoformat(row[3]), - location = row[4], - description = row[5], - organiser = row[6], - )) + results.append( + Event( + id=row[0], + name=row[1], + start=datetime.fromisoformat(row[2]), + stop=datetime.fromisoformat(row[3]), + location=row[4], + description=row[5], + organiser=row[6], + ) + ) return results