zonnebot/mattermost_bot.py

82 lines
2.2 KiB
Python
Raw Permalink Normal View History

2021-02-24 22:27:17 +00:00
#!/usr/bin/env python3
import os
import datetime
from time import sleep
import requests
import astral
from astral.sun import sun
2021-02-25 11:41:57 +00:00
from pytz import utc
2021-02-24 22:27:17 +00:00
CHANNEL = os.environ["SUNBOT_ANNOUNCE_CHANNEL"]
AUTHORIZATION = "Bearer " + os.environ["SUNBOT_ANNOUNCE_MATTERMOST_TOKEN"]
URL = os.environ["SUNBOT_ANNOUNCE_MATTERMOST_API_ENDPOINT"] + "/v4/posts"
2021-02-24 22:27:17 +00:00
2021-02-25 11:33:43 +00:00
LOCATION = astral.LocationInfo("Gent", "Belgium", "Europe/Brussels", 51.05, 3.72)
2021-02-24 22:27:17 +00:00
2021-02-25 11:41:57 +00:00
def in_timezone(d):
return d.astimezone(LOCATION.tzinfo)
2021-02-24 22:27:17 +00:00
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()
2021-02-24 22:27:17 +00:00
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()
2021-02-25 11:41:57 +00:00
print("Waiting {} seconds until {}".format(seconds, in_timezone(t)), flush=True)
2021-02-24 22:27:17 +00:00
sleep(seconds)
def announce_sunrise(today):
print("Announcing sunrise", flush=True)
2021-02-25 11:41:57 +00:00
now = datetime.datetime.now(utc)
2021-02-25 11:33:43 +00:00
post(":sunrise: De zon komt op in Gent!\nZonnemiddag om {:%H:%M %Z} (binnen {})\nZonsondergang om {:%H:%M %Z} (binnen {})".format(
2021-02-25 11:41:57 +00:00
in_timezone(today["noon"]), format_in(today["noon"] - now),
in_timezone(today["sunset"]), format_in(today["sunset"] - now),
2021-02-24 22:27:17 +00:00
))
2021-02-25 11:41:57 +00:00
2021-02-24 22:27:17 +00:00
def announce_sunset(tomorrow):
print("Announcing sunset", flush=True)
2021-02-25 11:41:57 +00:00
now = datetime.datetime.now(utc)
2021-02-25 11:33:43 +00:00
post(":city_sunset: De zon gaat onder in Gent!\nZonsopkomst om {:%H:%M %Z} (binnen {})".format(
2021-02-25 11:41:57 +00:00
in_timezone(tomorrow["sunrise"]), format_in(tomorrow["sunrise"] - now),
2021-02-24 22:27:17 +00:00
))
2021-02-25 11:41:57 +00:00
def main():
2021-02-24 22:27:17 +00:00
print("Starting Sunbot", flush=True)
while True:
2021-02-25 11:41:57 +00:00
now = datetime.datetime.now(utc)
2021-02-25 11:33:43 +00:00
today = sun(LOCATION.observer, date=now.date())
tomorrow = sun(LOCATION.observer, date=now.date() + datetime.timedelta(days=1))
2021-02-24 22:27:17 +00:00
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)
2021-02-25 11:41:57 +00:00
if __name__ == "__main__":
main()