Skip to content

Instantly share code, notes, and snippets.

@joelthelion
Created March 27, 2013 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelthelion/5257712 to your computer and use it in GitHub Desktop.
Save joelthelion/5257712 to your computer and use it in GitHub Desktop.
Simple prototype for weather notifications based on the Yahoo! weather API. Needs support for multiple locations and a way for people to subscribe.
#!/usr/bin/env python3
# coding: utf-8
import yweather
import shelve
import datetime
from conditions import conditions
def send_plain_mail(subject, body, from_mail, to):
import smtplib
from email.mime.text import MIMEText
from email.encoders import encode_quopri
msg = MIMEText(body, 'plain', 'iso-8859-1')
msg['Subject'] = subject
msg['From'] = from_mail
msg['To'] = to
s = smtplib.SMTP()
s.connect()
s.sendmail(from_mail, [to], msg.as_string())
s.close()
def recent(history,key="code",n=5):
if key == "code":
return [conditions[day[key]] for day in sorted(history.values(),key = lambda e:e["timestamp"])[-n:]]
else:
return [float(day[key]) for day in sorted(history.values(),key = lambda e:e["timestamp"])[-n:]]
def rain_test(history,forecast):
past_conditions = recent(history)
f_condition = conditions[forecast["code"]]
if "good" not in past_conditions and f_condition == "good":
return "good_alert"
elif "bad" not in past_conditions and f_condition == "bad":
return "bad_alert"
def temperature_test(history,forecast):
delta = 3
past_high = recent(history,"high")
f_high = float(forecast["high"])
past_low = recent(history,"low")
f_low = float(forecast["low"])
if f_high >= max(past_high) + delta:
return "high_temp_alert"
if f_low <= min(past_low) - delta:
return "low_temp_alert"
alert_subjects = {"good_alert": "Belle journée en perspective!",
"bad_alert": "Prends ton parapluie!",
"high_temp_alert": "Il va faire chaud!",
"low_temp_alert": "Attention, il va faire frisquet!"}
subscribers = ["test@example.com"]
if __name__ == '__main__':
data = shelve.open("history.db")
c = yweather.Client()
woeid = c.fetch_woeid("Springfield, NY")
weather = c.fetch_weather(woeid,metric=True)
today = weather["forecast"][0]
today["timestamp"]=datetime.datetime.now()
data[today["date"]] = today
tests = [rain_test,temperature_test]
for test in tests:
alert = test(data,weather["forecast"][1])
if alert:
for email in subscribers:
send_plain_mail(alert_subjects[alert],"http://fr.meteo.yahoo.com/place/","sender@example.com",email)
print("Alert sent!")
break # don't send a thousand alerts on the same day
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment