Categories We Write About

Build a weather alert system

Here is a complete implementation of a basic weather alert system in Python using the OpenWeatherMap API. It fetches weather data, checks for extreme weather conditions, and sends alerts via email.


Requirements:

  1. Python 3.7+

  2. OpenWeatherMap API Key (https://openweathermap.org/)

  3. requests, smtplib, and email modules (standard except requests)


Step-by-Step Weather Alert System Code

python
import requests import smtplib from email.message import EmailMessage # Configuration API_KEY = 'YOUR_OPENWEATHERMAP_API_KEY' CITY = 'New York' THRESHOLD_TEMP = 35 # Celsius EMAIL_SENDER = 'your_email@example.com' EMAIL_PASSWORD = 'your_email_password' EMAIL_RECEIVER = 'receiver_email@example.com' def get_weather(city): url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric' response = requests.get(url) response.raise_for_status() return response.json() def check_alert_conditions(weather_data): temp = weather_data['main']['temp'] weather = weather_data['weather'][0]['main'].lower() alerts = [] if temp > THRESHOLD_TEMP: alerts.append(f'Temperature Alert: {temp}°C exceeds {THRESHOLD_TEMP}°C') if 'storm' in weather or 'rain' in weather: alerts.append(f'Weather Alert: Detected "{weather}" conditions') return alerts def send_email(subject, body): msg = EmailMessage() msg['From'] = EMAIL_SENDER msg['To'] = EMAIL_RECEIVER msg['Subject'] = subject msg.set_content(body) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(EMAIL_SENDER, EMAIL_PASSWORD) smtp.send_message(msg) print('Alert email sent.') def main(): try: weather_data = get_weather(CITY) alerts = check_alert_conditions(weather_data) if alerts: subject = 'Weather Alert Notification' body = 'n'.join(alerts) send_email(subject, body) else: print('No weather alerts.') except Exception as e: print(f'Error occurred: {e}') if __name__ == '__main__': main()

How It Works:

  • Fetches current weather using OpenWeatherMap API.

  • Compares temperature and conditions to defined thresholds.

  • Sends an email alert if the conditions match.


Optional Enhancements:

  • Use cron or Task Scheduler for periodic checks.

  • Integrate with Twilio or Telegram API for SMS or chatbot alerts.

  • Extend to multiple cities or weather parameters (wind speed, humidity).

  • Log events for historical alert records.

Let me know if you want this adapted into a web app, mobile app, or embedded system.

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About