Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds weather Alert notification system #16

Merged
merged 4 commits into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Weather Alert/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
OPEN_WEATHER_MAP_API_KEY=
88 changes: 88 additions & 0 deletions Weather Alert/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import requests
import json
import time
import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Load API key from environment variable (security fix)
API_KEY = os.getenv('OPEN_WEATHER_MAP_API_KEY')

if not API_KEY:
raise ValueError("Missing environment variable 'OPEN_WEATHER_MAP_API_KEY'")

UNIT = 'metric'
BASE_URL = 'https://api.openweathermap.org/data/2.5/find'


def fetch_weather(city):
"""Fetches weather data for a given city.

Args:
city (str): Name of the city.

Returns:
dict: Weather data if successful, None otherwise.
"""

url = f"{BASE_URL}?q={city}&appid={API_KEY}&units={UNIT}"
response = requests.get(url)

if response.status_code == 200:
return response.json()
else:
print(f"Error fetching data: {response.status_code}")
return None


def check_alerts(data, temp_threshold, wind_speed_threshold):
"""Checks for temperature and wind speed alerts in weather data.

Args:
data (dict): Weather data.
temp_threshold (float): Temperature threshold in °C.
wind_speed_threshold (float): Wind speed threshold in m/s.

Prints alerts if any, otherwise prints a message indicating normal weather conditions.
"""

if not data or 'list' not in data or not data['list']:
print("No data available to check alerts.")
return

weather_info = data['list'][0]
temp = weather_info['main']['temp']
wind_speed = weather_info['wind']['speed']

alerts = []
if temp > temp_threshold:
alerts.append(f"Temperature alert! Current temperature: {temp}°C")
if wind_speed > wind_speed_threshold:
alerts.append(f"Wind speed alert! Current wind speed: {wind_speed} m/s")

if alerts:
print("\n".join(alerts))
else:
print("No alerts. Weather conditions are normal.")


def main():
"""Prompts user for city name, temperature and wind speed thresholds,
and continuously checks for alerts.
"""

city = input("Enter city name: ")
temp_threshold = float(input("Enter temperature threshold (°C): "))
wind_speed_threshold = float(input("Enter wind speed threshold (m/s): "))

while True:
weather_data = fetch_weather(city)
check_alerts(weather_data, temp_threshold, wind_speed_threshold)
print("Waiting for the next check...")
time.sleep(3600) # check every hour


if __name__ == "__main__":
main()
2 changes: 2 additions & 0 deletions Weather Alert/requirement.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
requests
python-dotenv
1 change: 1 addition & 0 deletions Weather Alert/runtime.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python-3.10.7