Skip to content

Instantly share code, notes, and snippets.

@binwiederhier
Last active November 29, 2023 01:43
Show Gist options
  • Save binwiederhier/7c8c3e2a70612d74a891e9df009f73e3 to your computer and use it in GitHub Desktop.
Save binwiederhier/7c8c3e2a70612d74a891e9df009f73e3 to your computer and use it in GitHub Desktop.
Alerts via ntfy.sh with a "pipe freeze alert" when the temperature in the next 3 days falls below a threshold
#!/usr/bin/env python3
import json
from datetime import datetime
import requests
latitude = 25.2510383
longitude = 55.2936404
threshold = -4
ntfy_url = "https://ntfy.sh/mytopic"
def main():
api_url = f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&hourly=temperature_2m&timezone=America%2FNew_York&forecast_days=3"
response = requests.get(api_url)
data = response.json()
timestamps = data["hourly"]["time"]
temperatures = data["hourly"]["temperature_2m"]
alert_timestamp = False
alert_temperature = 100
current_time = datetime.utcnow()
for timestamp, temperature in zip(timestamps, temperatures):
timestamp_datetime = datetime.fromisoformat(timestamp)
if timestamp_datetime > current_time and temperature < alert_temperature:
alert_timestamp = timestamp_datetime
alert_temperature = temperature
if alert_temperature <= threshold:
data = f"Lowest temperature is {alert_temperature}°C at {alert_timestamp}. Be sure to let the water drip from the faucet to prevent pipes from freezing.".encode(encoding='utf-8')
headers = {
"Title": f"Pipe freeze alert, {alert_temperature}°C!".encode(encoding='utf-8'),
"Tags": "cloud_with_snow,cold_face",
"Priority": "high"
}
requests.post(ntfy_url, data=data, headers=headers)
print(data)
print(f"Sent high priority alert to {ntfy_url}")
else:
data = f"Lowest temperature is {alert_temperature}°C at {alert_timestamp}. That's fine, no need to worry about the pipes.".encode(encoding='utf-8')
headers = {
"Title": f"Lowest temperature is {alert_temperature}°C, all good".encode(encoding='utf-8'),
"Tags": "+1",
"Priority": "low"
}
requests.post(ntfy_url, data=data, headers=headers)
print(data)
print(f"Sent low priority message to {ntfy_url}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment