Skip to content

Commit 09aa017

Browse files
authored
Merge pull request #16 from Telomelonia/weatheralert
Adds weather Alert notification system
2 parents 5207c8d + 8136ae8 commit 09aa017

File tree

5 files changed

+130
-0
lines changed

5 files changed

+130
-0
lines changed

Weather Alert/.env.example

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
OPEN_WEATHER_MAP_API_KEY=

Weather Alert/README.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Weather Alert Script 🌦️
2+
3+
A simple Python script that fetches weather data for your city and alerts you if the temperature or wind speed crosses your set thresholds. Perfect for staying on top of weather changes and preparing for unexpected conditions! 🚀
4+
5+
## Features
6+
7+
- **Fetch Weather Data**: Retrieves up-to-date weather information for any city using the OpenWeatherMap API.
8+
- **Custom Alerts**: Set your own temperature and wind speed thresholds. If the weather conditions exceed these, the script will alert you!
9+
- **Hourly Updates**: The script automatically checks the weather every hour, so you’re always in the loop.
10+
11+
## Getting Started
12+
13+
### Prerequisites
14+
15+
- Python 3.x
16+
- `requests` and `python-dotenv` libraries
17+
18+
Install the required libraries using:
19+
20+
```bash
21+
pip install requests python-dotenv
22+
```
23+
24+
## Setup
25+
26+
- Clone or download this repository.
27+
- Get an API key from OpenWeatherMap. (It’s free!)
28+
- Create a .env file in the root directory and add your API key like shown in `.env.example`
29+
- Run the script
30+
31+
```
32+
python weather_alert.py
33+
```
34+
35+
## Troubleshooting
36+
37+
- Missing API Key Error: Double-check that your .env file contains the correct OPEN_WEATHER_MAP_API_KEY. Make sure there are no typos or extra spaces.
38+
- Error fetching data: This could happen if the API key is incorrect or if the city name is misspelled. Verify both and try again.

Weather Alert/main.py

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import requests
2+
import json
3+
import time
4+
import os
5+
from dotenv import load_dotenv
6+
7+
# Load environment variables from .env file
8+
load_dotenv()
9+
10+
# Load API key from environment variable (security fix)
11+
API_KEY = os.getenv('OPEN_WEATHER_MAP_API_KEY')
12+
13+
if not API_KEY:
14+
raise ValueError("Missing environment variable 'OPEN_WEATHER_MAP_API_KEY'")
15+
16+
UNIT = 'metric'
17+
BASE_URL = 'https://api.openweathermap.org/data/2.5/find'
18+
19+
20+
def fetch_weather(city):
21+
"""Fetches weather data for a given city.
22+
23+
Args:
24+
city (str): Name of the city.
25+
26+
Returns:
27+
dict: Weather data if successful, None otherwise.
28+
"""
29+
30+
url = f"{BASE_URL}?q={city}&appid={API_KEY}&units={UNIT}"
31+
response = requests.get(url)
32+
33+
if response.status_code == 200:
34+
return response.json()
35+
else:
36+
print(f"Error fetching data: {response.status_code}")
37+
return None
38+
39+
40+
def check_alerts(data, temp_threshold, wind_speed_threshold):
41+
"""Checks for temperature and wind speed alerts in weather data.
42+
43+
Args:
44+
data (dict): Weather data.
45+
temp_threshold (float): Temperature threshold in °C.
46+
wind_speed_threshold (float): Wind speed threshold in m/s.
47+
48+
Prints alerts if any, otherwise prints a message indicating normal weather conditions.
49+
"""
50+
51+
if not data or 'list' not in data or not data['list']:
52+
print("No data available to check alerts.")
53+
return
54+
55+
weather_info = data['list'][0]
56+
temp = weather_info['main']['temp']
57+
wind_speed = weather_info['wind']['speed']
58+
59+
alerts = []
60+
if temp > temp_threshold:
61+
alerts.append(f"Temperature alert! Current temperature: {temp}°C")
62+
if wind_speed > wind_speed_threshold:
63+
alerts.append(f"Wind speed alert! Current wind speed: {wind_speed} m/s")
64+
65+
if alerts:
66+
print("\n".join(alerts))
67+
else:
68+
print("No alerts. Weather conditions are normal.")
69+
70+
71+
def main():
72+
"""Prompts user for city name, temperature and wind speed thresholds,
73+
and continuously checks for alerts.
74+
"""
75+
76+
city = input("Enter city name: ")
77+
temp_threshold = float(input("Enter temperature threshold (°C): "))
78+
wind_speed_threshold = float(input("Enter wind speed threshold (m/s): "))
79+
80+
while True:
81+
weather_data = fetch_weather(city)
82+
check_alerts(weather_data, temp_threshold, wind_speed_threshold)
83+
print("Waiting for the next check...")
84+
time.sleep(3600) # check every hour
85+
86+
87+
if __name__ == "__main__":
88+
main()

Weather Alert/requirement.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
requests
2+
python-dotenv

Weather Alert/runtime.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
python-3.10.7

0 commit comments

Comments
 (0)