- Download and unzip all files
- Sign up for a Sendgrid account: https://signup.sendgrid.com/
- Get an API key from https://app.sendgrid.com/settings/api_keys
- Paste API key into the SENDGRID_API_KEY field of the .env file
- Set other .env variables (particularly SENDER and RECIPIENTS, which can be a comma-separated list of emails)
- Ensure required Python libraries are installed: python -m pip install python-dotenv sendgrid
- Run script: python rainy_day.py
-
-
Save bdunnette/11d1dc3ceb61d961f36041f4d969d7ff to your computer and use it in GitHub Desktop.
Send email notifications if 6-hour precipitation is above threshold
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SENDGRID_API_KEY=Paste key from https://app.sendgrid.com/settings/api_keys here | |
[email protected] | |
RECIPIENTS=${SENDER},[email protected] | |
NWS_STATION=KMIC | |
MIN_PRECIP=25 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from datetime import datetime | |
import logging | |
import requests | |
from sendgrid import SendGridAPIClient | |
from sendgrid.helpers.mail import Mail | |
from dotenv import load_dotenv | |
load_dotenv() | |
consoleHandler = logging.StreamHandler() | |
consoleHandler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) | |
logger = logging.getLogger(__name__) | |
logger.setLevel(logging.DEBUG) | |
logger.addHandler(consoleHandler) | |
# Weather station code from https://forecast.weather.gov/stations.php | |
NWS_STATION = os.getenv("NWS_STATION",default="KMIC") | |
# Minimium precipitation to alert for - set this to 0 for testing | |
MIN_PRECIP = float(os.getenv("MIN_PRECIP",default=25)) | |
# Find your API key at https://app.sendgrid.com/settings/api_keys | |
SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY") | |
SENDER = os.getenv("SENDER",default="[email protected]") | |
RECIPIENTS = os.getenv("RECIPIENTS",default=[SENDER]) | |
def get_nws_obs(station=NWS_STATION): | |
"""Get the latest weather conditions for a given NWS station""" | |
try: | |
observation = requests.get( | |
f"https://api.weather.gov/stations/{station}/observations/latest" | |
) | |
observation.raise_for_status() | |
except requests.exceptions.HTTPError as e: | |
logger.error(e) | |
obs_data = observation.json()["properties"] | |
obs_time = datetime.fromisoformat(obs_data["timestamp"]) | |
precipitationLast6Hours = obs_data["precipitationLast6Hours"]["value"] | |
return obs_time, precipitationLast6Hours | |
def send_message( | |
from_email=SENDER, | |
to_emails=RECIPIENTS, | |
# Default subject and text - we'll override these when the function is actually run! | |
subject="TEST NOTIFICATION - PLEASE IGNORE", | |
html_content="<em>Test email - please ignore</em>" | |
): | |
"""Send a message via the Sendgrid API""" | |
try: | |
message = Mail( | |
from_email=from_email, | |
to_emails=to_emails, | |
subject=subject, | |
html_content=html_content) | |
sg = SendGridAPIClient(SENDGRID_API_KEY) | |
response = sg.send(message) | |
logger.debug(response) | |
except Exception as e: | |
logger.error(e.message) | |
def send_message_if_precip(): | |
"""Send a message if precipitation is above threshold""" | |
obs_time, precipitation = get_nws_obs(NWS_STATION) | |
precipitation = 0 if precipitation == None else precipitation | |
obs_time = obs_time.strftime("%Y-%m-%d %H:%M %Z") | |
msg = f"{NWS_STATION} at {obs_time} - {precipitation} mm of rain in the last 6 hours." | |
if precipitation >= MIN_PRECIP: | |
subject = f"RAIN ALERT for {NWS_STATION}" | |
html_content = f"<strong>RAIN ALERT</strong> for {msg}" | |
logger.info(html_content) | |
send_message(from_email=SENDER,to_emails=RECIPIENTS,subject=subject,html_content=html_content) | |
else: | |
logger.info( | |
f"No rain alert for {msg}" | |
) | |
if __name__=="__main__": | |
send_message_if_precip() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment