commit 2060d2b4b5301ff06f0225d4636ceb641b9b7573 Author: Midgard Date: Wed Feb 24 23:27:17 2021 +0100 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..09f0109 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +venv/ +__pycache__/ +.idea/ +.mypy_cache/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/mattermost_bot.py b/mattermost_bot.py new file mode 100755 index 0000000..ff1525d --- /dev/null +++ b/mattermost_bot.py @@ -0,0 +1,73 @@ +#!/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) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..b89d9b1 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +astral==2.2 +certifi==2020.12.5 +chardet==4.0.0 +idna==2.10 +requests==2.25.1 +urllib3==1.26.3