88 lines
2.0 KiB
Python
Executable File
88 lines
2.0 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
Read weather predictions for the next days, and if it's high enough,
|
|
recommend that Dennis buys witbier.
|
|
"""
|
|
import datetime
|
|
import json
|
|
import os
|
|
import textwrap
|
|
import smtplib
|
|
import sys
|
|
from collections import defaultdict
|
|
from email.message import EmailMessage
|
|
from urllib.request import urlopen
|
|
|
|
|
|
EMAIL_SENDER = 'Witbierbot <witbier@example.org>'
|
|
EMAIL_RECIPIENT = 'RECIPIENT'
|
|
|
|
|
|
def load_weather():
|
|
url = 'https://api.openweathermap.org/data/2.5/forecast?q=Leiden' \
|
|
+ '&units=metric' \
|
|
+ '&appid=' + os.environ['API_KEY']
|
|
|
|
result = urlopen(url)
|
|
|
|
return json.load(result)
|
|
|
|
|
|
def get_maxima(weather):
|
|
days = defaultdict(float)
|
|
for day in weather['list']:
|
|
instant = datetime.datetime.fromtimestamp(day['dt'])
|
|
date = instant.date()
|
|
days[date] = max(days[date], day['main']['temp_max'])
|
|
|
|
return days
|
|
|
|
|
|
def notify(best_day, best_temp):
|
|
best_day = best_day.strftime('%d/%m')
|
|
|
|
message = f'''\
|
|
Lief DB,
|
|
|
|
De komende dagen wordt het wederom prachtig weer. Zo wordt het
|
|
op {best_day} maar liefst {best_temp} °C!
|
|
|
|
Met zulke mooie berichten kan het niet anders dan dat er
|
|
binnenkort witbier verkocht wordt. Toch? Ik kijk er in ieder
|
|
geval naar uit.
|
|
|
|
Knuffels,
|
|
|
|
Witbierbot.
|
|
'''
|
|
|
|
message = textwrap.dedent(message)
|
|
|
|
report_date = datetime.datetime.now().strftime('%d/%m/%y')
|
|
|
|
mail = EmailMessage()
|
|
mail.set_content(message)
|
|
mail['Subject'] = 'Witbier alert voor ' + report_date
|
|
mail['To'] = EMAIL_RECIPIENT
|
|
mail['From'] = EMAIL_SENDER
|
|
|
|
with smtplib.SMTP('localhost') as smtp:
|
|
smtp.send_message(mail)
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) > 1:
|
|
with open(sys.argv[1]) as f:
|
|
weather = json.load(f)
|
|
else:
|
|
weather = load_weather()
|
|
|
|
maxima = get_maxima(weather)
|
|
best, temp = max(maxima.items(), key=lambda x: x[1])
|
|
if temp > 10:
|
|
notify(best, temp)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|