main: working monitor

main
Jae Lo Presti 2 months ago
parent f2fd607036
commit 545c279557
Signed by: jae
SSH Key Fingerprint: SHA256:hmKix/+XG+9GEGHgDdiqXfmB2O7BU4CPVOoQoIYIQ2Y
  1. 57
      main.py

@ -1,7 +1,11 @@
from os import environ
from logging import getLogger
from datetime import datetime, timedelta
from threading import Timer
from json import dumps
from requests import get, post
from markdown import markdown
log = getLogger("main")
@ -10,6 +14,8 @@ MATRIX_TOKEN = environ.get("MATRIX_TOKEN")
MATRIX_HOMESERVER = environ.get("MATRIX_HOMESERVER")
MATRIX_PROTO = environ.get("MATRIX_SERVER_PROTO") or "https"
HSL_NOTIFICATION_LANGUAGE = environ.get("HSL_NOTIFICATION_LANGUAGE") or "en"
def check_matrix_rooms_for_joins():
# Check for env variables
@ -17,11 +23,11 @@ def check_matrix_rooms_for_joins():
log.fatal("NO HOMESERVER ADDRESS NOR TOKEN, CANNOT PROCEED")
return
r = requests.get(
r = get(
f"{MATRIX_PROTO}://{MATRIX_HOMESERVER}/_matrix/client/v3/sync?access_token={MATRIX_TOKEN}"
)
if r.status_code == 200:
json_data = json.loads(r.text)
json_data = r.json()
rooms = json_data.get("rooms")
if not "invite" in rooms:
@ -29,7 +35,7 @@ def check_matrix_rooms_for_joins():
else:
for room in rooms["invite"]:
log.info(f"Joining room {room}")
r = requests.post(
r = post(
f"{MATRIX_PROTO}://{MATRIX_HOMESERVER}/_matrix/client/v3/join/{room}?access_token={MATRIX_TOKEN}"
)
@ -42,10 +48,10 @@ def send_to_matrix(message=None):
"msgtype": "m.notice",
"body": message,
"format": "org.matrix.custom.html",
"formatted_body": markdown.markdown(message),
"formatted_body": markdown(message),
}
r = requests.get(
r = get(
f"{MATRIX_PROTO}://{MATRIX_HOMESERVER}/_matrix/client/v3/joined_rooms?access_token={MATRIX_TOKEN}"
)
@ -53,9 +59,46 @@ def send_to_matrix(message=None):
log.error(f"Something bad happened: {r.text}")
return
joined_rooms = json.loads(r.text)
joined_rooms = r.json()
for room in joined_rooms.get("joined_rooms"):
msg = f"{MATRIX_PROTO}://{MATRIX_HOMESERVER}/_matrix/client/r0/rooms/{room}/send/m.room.message?access_token={MATRIX_TOKEN}"
r = requests.post(msg, data=json.dumps(payload))
r = post(msg, data=dumps(payload))
if r.status_code != 200:
log.error(f"Something bad happened: {r.text}")
def cron_task():
check_matrix_rooms_for_joins()
built_uri = f"https://content.hsl.fi/api/v1/search/traffic-feed?language={HSL_NOTIFICATION_LANGUAGE}&page=1&pageSize=10&validityPeriod=true&transportMode=1&transportMode=2&transportMode=4&transportMode=3&transportMode=5&transportMode=6&favouritesOnly=false"
raw_req = get(built_uri)
if raw_req.status_code != 200:
log.error("Error, not 200")
else:
json_res = raw_req.json()
final_array = []
for hit in json_res["hits"]:
until = datetime.fromisoformat(hit["validUntil"])
if until.timestamp() >= datetime.now().timestamp():
title = hit["title"]
date_from = hit["validFrom"]
date_until = hit["validUntil"]
built_string = f"/!\\ HSL ALERT REMINDER: {title} from {date_from} to {date_until} /!\\"
final_array.append(built_string)
last_string = ""
for incident in final_array:
last_string += incident + "<br>"
send_to_matrix(last_string)
Timer(60 * 60 * 12, cron_task).start()
cron_task()