zonnebot/mattermost_bot.py

82 lines
2.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
from pytz import utc
CHANNEL = os.environ["SUNBOT_ANNOUNCE_CHANNEL"]
AUTHORIZATION = "Bearer " + os.environ["SUNBOT_ANNOUNCE_MATTERMOST_TOKEN"]
URL = os.environ["SUNBOT_ANNOUNCE_MATTERMOST_API_ENDPOINT"] + "/v4/posts"
LOCATION = astral.LocationInfo("Gent", "Belgium", "Europe/Brussels", 51.05, 3.72)
def in_timezone(d):
return d.astimezone(LOCATION.tzinfo)
def post(message):
payload = {
"channel_id": CHANNEL,
"message": message
}
print("Posting " + str(payload), flush=True)
r = requests.post(URL, json=payload, headers={"Authorization": AUTHORIZATION})
r.raise_for_status()
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, in_timezone(t)), flush=True)
sleep(seconds)
def announce_sunrise(today):
print("Announcing sunrise", flush=True)
now = datetime.datetime.now(utc)
post(":sunrise: De zon komt op in Gent!\nZonnemiddag om {:%H:%M %Z} (binnen {})\nZonsondergang om {:%H:%M %Z} (binnen {})".format(
in_timezone(today["noon"]), format_in(today["noon"] - now),
in_timezone(today["sunset"]), format_in(today["sunset"] - now),
))
def announce_sunset(tomorrow):
print("Announcing sunset", flush=True)
now = datetime.datetime.now(utc)
post(":city_sunset: De zon gaat onder in Gent!\nZonsopkomst om {:%H:%M %Z} (binnen {})".format(
in_timezone(tomorrow["sunrise"]), format_in(tomorrow["sunrise"] - now),
))
def main():
print("Starting Sunbot", flush=True)
while True:
now = datetime.datetime.now(utc)
today = sun(LOCATION.observer, date=now.date())
tomorrow = sun(LOCATION.observer, date=now.date() + datetime.timedelta(days=1))
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)
if __name__ == "__main__":
main()