A comprehensive Python wrapper around OpenWeatherMap web APIs providing weather data, forecasts, air pollution, UV index, and agricultural information
—
Weather alert system allowing creation of triggers that monitor weather conditions and fire alerts when specified criteria are met. Enables automated monitoring of weather parameters like temperature, humidity, wind speed, and precipitation across defined geographic areas.
Create and manage weather condition triggers that monitor specific weather parameters.
class AlertManager:
def alert_api_version(self) -> tuple:
"""
Get Alert API version.
Returns:
Tuple representing the API version
"""
def create_trigger(self, start, end, conditions, area, alert_channels=None) -> Trigger:
"""
Create a weather alert trigger.
Parameters:
- start: Start time for monitoring (UNIX timestamp, datetime, or ISO8601 string)
- end: End time for monitoring (UNIX timestamp, datetime, or ISO8601 string)
- conditions: List of Condition objects defining weather criteria
- area: List of geoJSON geometries defining monitoring area
- alert_channels: Optional list of alert delivery channels
Returns:
Trigger object representing the created trigger
"""
def get_triggers(self) -> List[Trigger]:
"""
Get all user triggers.
Returns:
List of all Trigger objects owned by the user
"""
def get_trigger(self, trigger_id: str) -> Trigger:
"""
Get a specific trigger by ID.
Parameters:
- trigger_id: Unique trigger identifier
Returns:
Trigger object for the specified ID
"""
def update_trigger(self, trigger: Trigger) -> None:
"""
Update trigger configuration.
Parameters:
- trigger: Trigger object with updated information
"""
def delete_trigger(self, trigger: Trigger) -> None:
"""
Delete a trigger.
Parameters:
- trigger: Trigger object to delete
"""Manage alerts fired by triggers when weather conditions are met.
class AlertManager:
def get_alerts_for(self, trigger: Trigger, since: int = None) -> List[Alert]:
"""
Get all alerts for a trigger.
Parameters:
- trigger: Trigger object to get alerts for
- since: UNIX timestamp to get alerts since (optional)
Returns:
List of Alert objects fired by the trigger
"""
def get_alert(self, alert_id: str, trigger: Trigger) -> Alert:
"""
Get a specific alert.
Parameters:
- alert_id: Unique alert identifier
- trigger: Parent trigger object
Returns:
Alert object for the specified ID
"""
def delete_all_alerts_for(self, trigger: Trigger) -> None:
"""
Delete all alerts for a trigger.
Parameters:
- trigger: Trigger object to delete alerts for
"""
def delete_alert(self, alert: Alert) -> None:
"""
Delete a specific alert.
Parameters:
- alert: Alert object to delete
"""from pyowm import OWM
from pyowm.alertapi30.condition import Condition
from datetime import datetime, timedelta
owm = OWM('your-api-key')
alert_mgr = owm.alert_manager()
# Define monitoring area (London area as geoJSON polygon)
london_area = [{
"type": "Polygon",
"coordinates": [[
[-0.2, 51.4], [-0.2, 51.6], [0.1, 51.6], [0.1, 51.4], [-0.2, 51.4]
]]
}]
# Create conditions for temperature alert
temp_condition = Condition('temp', 'GREATER_THAN', 30) # Temperature > 30°C
humidity_condition = Condition('humidity', 'LESS_THAN', 40) # Humidity < 40%
# Create trigger for hot, dry conditions
start_time = datetime.now()
end_time = start_time + timedelta(days=7) # Monitor for 1 week
trigger = alert_mgr.create_trigger(
start=start_time,
end=end_time,
conditions=[temp_condition, humidity_condition],
area=london_area
)
print(f"Created trigger: {trigger.id}")
print(f"Monitoring from {start_time} to {end_time}")
print(f"Conditions: Temperature > 30°C AND Humidity < 40%")# Create various weather monitoring triggers
# High wind speed alert
wind_condition = Condition('wind_speed', 'GREATER_THAN', 15) # Wind > 15 m/s
wind_trigger = alert_mgr.create_trigger(
start=datetime.now(),
end=datetime.now() + timedelta(days=3),
conditions=[wind_condition],
area=london_area
)
# Heavy precipitation alert
rain_condition = Condition('rain', 'GREATER_THAN', 10) # Rain > 10mm
rain_trigger = alert_mgr.create_trigger(
start=datetime.now(),
end=datetime.now() + timedelta(hours=24),
conditions=[rain_condition],
area=london_area
)
# Low temperature alert (frost warning)
frost_condition = Condition('temp', 'LESS_THAN', 0) # Temperature < 0°C
frost_trigger = alert_mgr.create_trigger(
start=datetime.now(),
end=datetime.now() + timedelta(days=5),
conditions=[frost_condition],
area=london_area
)
# Complex condition: Storm warning (high wind + heavy rain)
storm_conditions = [
Condition('wind_speed', 'GREATER_THAN', 20), # Wind > 20 m/s
Condition('rain', 'GREATER_THAN', 15) # Rain > 15mm
]
storm_trigger = alert_mgr.create_trigger(
start=datetime.now(),
end=datetime.now() + timedelta(days=2),
conditions=storm_conditions,
area=london_area
)
print(f"Created wind alert trigger: {wind_trigger.id}")
print(f"Created rain alert trigger: {rain_trigger.id}")
print(f"Created frost alert trigger: {frost_trigger.id}")
print(f"Created storm alert trigger: {storm_trigger.id}")# Check all triggers
triggers = alert_mgr.get_triggers()
print(f"Total active triggers: {len(triggers)}")
for trigger in triggers:
print(f"Trigger {trigger.id}:")
print(f" Conditions: {len(trigger.conditions)}")
print(f" Area polygons: {len(trigger.area)}")
# Check for alerts
alerts = alert_mgr.get_alerts_for(trigger)
print(f" Active alerts: {len(alerts)}")
if alerts:
for alert in alerts:
print(f" Alert {alert.id}:")
print(f" Conditions met: {alert.met_conditions}")
print(f" Location: {alert.coordinates}")
if alert.last_update:
print(f" Last update: {datetime.fromtimestamp(alert.last_update)}")
# Get alerts by weather parameter
temp_alerts = []
for trigger in triggers:
alerts = trigger.get_alerts_on('temp')
temp_alerts.extend(alerts)
print(f"Temperature-related alerts: {len(temp_alerts)}")from datetime import datetime
# Get alerts from the last 24 hours
yesterday = datetime.now() - timedelta(days=1)
recent_alerts = []
for trigger in triggers:
alerts = trigger.get_alerts_since(int(yesterday.timestamp()))
recent_alerts.extend(alerts)
print(f"Alerts in last 24 hours: {len(recent_alerts)}")
# Analyze alert patterns
alert_locations = {}
for alert in recent_alerts:
coords = f"{alert.coordinates['lat']:.2f},{alert.coordinates['lon']:.2f}"
alert_locations[coords] = alert_locations.get(coords, 0) + 1
print("Alert hotspots:")
for location, count in sorted(alert_locations.items(), key=lambda x: x[1], reverse=True):
print(f" {location}: {count} alerts")
# Clean up old alerts
for trigger in triggers:
old_alerts = alert_mgr.get_alerts_for(trigger)
if len(old_alerts) > 100: # Keep only latest 100 alerts
print(f"Cleaning up old alerts for trigger {trigger.id}")
alert_mgr.delete_all_alerts_for(trigger)class Trigger:
def __init__(self, start_after_millis: int, end_after_millis: int, conditions: List[Condition],
area: List, alerts: List[Alert] = None, alert_channels: List = None, id: str = None): ...
def get_alerts(self) -> List[Alert]:
"""Returns all alerts fired by this trigger."""
def get_alert(self, alert_id: str) -> Union[Alert, None]:
"""Returns specific alert by ID."""
def get_alerts_since(self, timestamp: int) -> List[Alert]:
"""Returns alerts fired since the specified timestamp."""
def get_alerts_on(self, weather_param: str) -> List[Alert]:
"""Returns alerts fired for the specified weather parameter."""
@property
def id(self) -> str: ...
@property
def start_after_millis(self) -> int: ...
@property
def end_after_millis(self) -> int: ...
@property
def conditions(self) -> List[Condition]: ...
@property
def area(self) -> List: ...
@property
def alerts(self) -> List[Alert]: ...
@property
def alert_channels(self) -> List: ...
def to_dict(self) -> dict: ...
class Alert:
def __init__(self, id: str, trigger_id: str, met_conditions: List[dict],
coordinates: dict, last_update: int = None): ...
@property
def id(self) -> str: ...
@property
def trigger_id(self) -> str: ...
@property
def met_conditions(self) -> List[dict]:
"""
List of condition details that were met:
[
{
'current_value': float,
'condition': {
'name': str, # Weather parameter name
'expression': str, # Comparison operator
'amount': float # Threshold value
}
}
]
"""
@property
def coordinates(self) -> dict:
"""Geographic coordinates where condition was met: {'lat': float, 'lon': float}"""
@property
def last_update(self) -> Union[int, None]: ...
def to_dict(self) -> dict: ...
class Condition:
def __init__(self, weather_param: str, operator: str, amount: Union[int, float], id: str = None): ...
@property
def id(self) -> str: ...
@property
def weather_param(self) -> str:
"""
Weather parameter to monitor:
- 'temp': Temperature (°C)
- 'pressure': Atmospheric pressure (hPa)
- 'humidity': Relative humidity (%)
- 'wind_speed': Wind speed (m/s)
- 'wind_direction': Wind direction (degrees)
- 'rain': Precipitation amount (mm)
- 'snow': Snow amount (mm)
- 'clouds': Cloud coverage (%)
"""
@property
def operator(self) -> str:
"""
Comparison operator:
- 'GREATER_THAN': >
- 'GREATER_THAN_OR_EQUAL': >=
- 'LESS_THAN': <
- 'LESS_THAN_OR_EQUAL': <=
- 'EQUAL': =
- 'NOT_EQUAL': !=
"""
@property
def amount(self) -> Union[int, float]: ...
def to_dict(self) -> dict: ...
class AlertChannel:
def __init__(self, name: str): ...
@property
def name(self) -> str:
"""
Alert delivery channel name.
Supported channels depend on subscription level.
"""
def to_dict(self) -> dict: ...The following weather parameters can be monitored in conditions:
Areas are defined using geoJSON geometry objects:
{"type": "Point", "coordinates": [lon, lat]}{"type": "Polygon", "coordinates": [[[lon, lat], ...]]}{"type": "MultiPolygon", "coordinates": [[[[lon, lat], ...]]]}Alerts can be delivered through various channels (availability depends on subscription level):
Install with Tessl CLI
npx tessl i tessl/pypi-pyowm