zonnebot/mattermost_bot.py
2021-02-24 23:37:43 +01:00

74 lines
2 KiB
Python
Executable file

#!/usr/bin/env python3
import os
import datetime
from time import sleep
import requests
import astral
from astral.sun import sun
CHANNEL = os.environ["SUNBOT_ANNOUNCE_CHANNEL"]
AUTHORIZATION = "Bearer " + os.environ["SUNBOT_ANNOUNCE_MATTERMOST_TOKEN"]
URL = os.environ["SUNBOT_ANNOUNCE_MATTERMOST_API_ENDPOINT"] + "/posts"
GHENT = astral.LocationInfo("Gent", "Belgium", "Europe/Brussels", 51.05, 3.72)
def post(message):
payload = {
"channel_id": CHANNEL,
"message": message
}
print("Posting " + str(payload), flush=True)
requests.post(URL, json=payload, headers={"Authorization": AUTHORIZATION})
def format_in(diff):
total_minutes = round(diff.total_seconds() / 60)
hours, minutes = divmod(total_minutes, 60)
return "{}h{}".format(hours, minutes)
def wait_until(t, now):
seconds = (t - now).total_seconds()
print("Waiting {} seconds until {}".format(seconds, t), flush=True)
sleep(seconds)
def announce_sunrise(today):
print("Announcing sunrise", flush=True)
now = datetime.datetime.now(GHENT.tzinfo)
post(":sunrise: De zon komt op in Gent!\nZonnemiddag om {} (binnen {})\nZonsondergang om {} (binnen {})".format(
tomorrow["noon"],
format_in(now - tomorrow["noon"]),
tomorrow["sunset"],
format_in(now - tomorrow["sunset"]),
))
def announce_sunset(tomorrow):
print("Announcing sunset", flush=True)
now = datetime.datetime.now(GHENT.tzinfo)
post(":sunset: De zon gaat onder in Gent!\nZonsopkomst om {} (binnen {})".format(
tomorrow["sunrise"],
format_in(now - tomorrow["sunrise"]),
))
if __name__ == "__main__":
print("Starting Sunbot", flush=True)
while True:
today = sun(GHENT.observer, date=datetime.date.today())
tomorrow = sun(GHENT.observer, date=datetime.date.today() + datetime.timedelta(days=1))
now = datetime.datetime.now(GHENT.tzinfo)
if now >= today["sunset"]:
wait_until(tomorrow["sunrise"], now)
announce_sunrise(tomorrow)
elif now >= today["sunrise"]:
wait_until(today["sunset"], now)
announce_sunset(tomorrow)
else:
wait_until(today["sunrise"], now)
announce_sunrise(today)