Initial commit

This commit is contained in:
Midgard 2021-02-24 23:27:17 +01:00
commit 2060d2b4b5
Signed by: midgard
GPG key ID: 511C112F1331BBB4
4 changed files with 83 additions and 0 deletions

4
.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
venv/
__pycache__/
.idea/
.mypy_cache/

0
README.md Normal file
View file

73
mattermost_bot.py Executable file
View file

@ -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)

6
requirements.txt Normal file
View file

@ -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