Categories We Write About

Build a weather notification script

Here’s a straightforward Python script that fetches weather data and sends a notification. This example uses the OpenWeatherMap API and sends desktop notifications using the plyer library. It’s easily customizable for other notification methods (email, SMS, etc.).


python
import requests from plyer import notification # Configuration API_KEY = 'your_openweathermap_api_key' # Get from https://openweathermap.org/api CITY = 'London' UNITS = 'metric' # or 'imperial' def get_weather(api_key, city, units='metric'): url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units={units}" response = requests.get(url) if response.status_code == 200: return response.json() else: print(f"Failed to get weather data: {response.status_code}") return None def build_notification_message(weather_data): temp = weather_data['main']['temp'] description = weather_data['weather'][0]['description'].capitalize() city = weather_data['name'] return f"{city}: {description}, Temp: {temp}°{'C' if UNITS == 'metric' else 'F'}" def send_notification(title, message): notification.notify( title=title, message=message, timeout=10 ) if __name__ == '__main__': weather = get_weather(API_KEY, CITY, UNITS) if weather: message = build_notification_message(weather) send_notification("Weather Update", message)

How to use:

  1. Get a free API key from OpenWeatherMap.

  2. Install dependencies:

    nginx
    pip install requests plyer
  3. Replace 'your_openweathermap_api_key' with your API key.

  4. Run the script. It will show a desktop notification with the current weather in the specified city.

You can schedule this script using cron (Linux/macOS) or Task Scheduler (Windows) for periodic updates. If you want notifications via email or SMS, let me know!

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