trhlina-calendar/get_json.py
Pták 6427a50272 changes to json events from array
Adds support for webhook creation and init of events.json. I have no clue how i fixed it, or why does it work.
2024-02-25 10:09:00 +01:00

81 lines
2.5 KiB
Python

import requests as r
import json
from datetime import datetime as dt
from datetime import timedelta
from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.environ.get("API-KEY")
URL = os.environ.get("URL")
timezone = int(os.environ.get("TIMEZONE"))
def get_json(url):
headers={ 'Api-Key' :api_key}
result = r.get(url, headers=headers)
return result.json()
class Event:
def __init__(self, title, start_date, end_date):
self.title = title
self.start_date = start_date
self.end_date = end_date
def offset_time(timestamp, offset):
return timestamp + timedelta(hours=offset)
def save_to_json(event_list):
event_array=[]
for event in event_list:
event_array.append({"title":event[1], "start":event[0].strftime("%Y-%m-%dT%H:%M:%S"), "end":event[2].strftime("%Y-%m-%dT%H:%M:%S")})
with open('events.json', 'w') as fp:
json.dump(event_array, fp)
def parse_time(timestring):
if timestring!= None:
datetime=dt.strptime(timestring, '%Y-%m-%dT%H:%M:%S.%fZ') + timedelta(hours=timezone)
return datetime
def create_event_list(json):
event_list = []
for raw_event in json["events"]:
event_first_start_datetime = parse_time(raw_event["starts_at"])
event_end_time = parse_time(raw_event["ends_at"])
if event_end_time == None or event_first_start_datetime==event_end_time:
event_end_time=offset_time(event_first_start_datetime, 1.5)
if raw_event["post"]["topic"]["tags"][0] == 'closed-event':
event_name = "Closed"
else:
event_name = raw_event["post"]["topic"]["title"]
event_list.append((event_first_start_datetime,event_name,event_end_time))
try:
for reocurring_event in raw_event["upcoming_dates"]:
event_start_time = parse_time(reocurring_event["starts_at"][0:reocurring_event["starts_at"].find("+")]+"Z")
event_end_time = parse_time(reocurring_event["ends_at"][0:reocurring_event["ends_at"].find("+")]+"Z")
if event_end_time == None or event_start_time == event_end_time:
event_end_time = offset_time(event_start_time, 1.5)
event_list.append((event_start_time,event_name,event_end_time))
except:
pass
return event_list
def main():
event_json = get_json(URL)
event_list = create_event_list(event_json)
save_to_json(event_list)
if __name__ == "__main__":
main()