0
# Weather Alerts
1
2
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.
3
4
## Capabilities
5
6
### Trigger Management
7
8
Create and manage weather condition triggers that monitor specific weather parameters.
9
10
```python { .api }
11
class AlertManager:
12
def alert_api_version(self) -> tuple:
13
"""
14
Get Alert API version.
15
16
Returns:
17
Tuple representing the API version
18
"""
19
20
def create_trigger(self, start, end, conditions, area, alert_channels=None) -> Trigger:
21
"""
22
Create a weather alert trigger.
23
24
Parameters:
25
- start: Start time for monitoring (UNIX timestamp, datetime, or ISO8601 string)
26
- end: End time for monitoring (UNIX timestamp, datetime, or ISO8601 string)
27
- conditions: List of Condition objects defining weather criteria
28
- area: List of geoJSON geometries defining monitoring area
29
- alert_channels: Optional list of alert delivery channels
30
31
Returns:
32
Trigger object representing the created trigger
33
"""
34
35
def get_triggers(self) -> List[Trigger]:
36
"""
37
Get all user triggers.
38
39
Returns:
40
List of all Trigger objects owned by the user
41
"""
42
43
def get_trigger(self, trigger_id: str) -> Trigger:
44
"""
45
Get a specific trigger by ID.
46
47
Parameters:
48
- trigger_id: Unique trigger identifier
49
50
Returns:
51
Trigger object for the specified ID
52
"""
53
54
def update_trigger(self, trigger: Trigger) -> None:
55
"""
56
Update trigger configuration.
57
58
Parameters:
59
- trigger: Trigger object with updated information
60
"""
61
62
def delete_trigger(self, trigger: Trigger) -> None:
63
"""
64
Delete a trigger.
65
66
Parameters:
67
- trigger: Trigger object to delete
68
"""
69
```
70
71
### Alert Management
72
73
Manage alerts fired by triggers when weather conditions are met.
74
75
```python { .api }
76
class AlertManager:
77
def get_alerts_for(self, trigger: Trigger, since: int = None) -> List[Alert]:
78
"""
79
Get all alerts for a trigger.
80
81
Parameters:
82
- trigger: Trigger object to get alerts for
83
- since: UNIX timestamp to get alerts since (optional)
84
85
Returns:
86
List of Alert objects fired by the trigger
87
"""
88
89
def get_alert(self, alert_id: str, trigger: Trigger) -> Alert:
90
"""
91
Get a specific alert.
92
93
Parameters:
94
- alert_id: Unique alert identifier
95
- trigger: Parent trigger object
96
97
Returns:
98
Alert object for the specified ID
99
"""
100
101
def delete_all_alerts_for(self, trigger: Trigger) -> None:
102
"""
103
Delete all alerts for a trigger.
104
105
Parameters:
106
- trigger: Trigger object to delete alerts for
107
"""
108
109
def delete_alert(self, alert: Alert) -> None:
110
"""
111
Delete a specific alert.
112
113
Parameters:
114
- alert: Alert object to delete
115
"""
116
```
117
118
## Usage Examples
119
120
### Creating Weather Triggers
121
122
```python
123
from pyowm import OWM
124
from pyowm.alertapi30.condition import Condition
125
from datetime import datetime, timedelta
126
127
owm = OWM('your-api-key')
128
alert_mgr = owm.alert_manager()
129
130
# Define monitoring area (London area as geoJSON polygon)
131
london_area = [{
132
"type": "Polygon",
133
"coordinates": [[
134
[-0.2, 51.4], [-0.2, 51.6], [0.1, 51.6], [0.1, 51.4], [-0.2, 51.4]
135
]]
136
}]
137
138
# Create conditions for temperature alert
139
temp_condition = Condition('temp', 'GREATER_THAN', 30) # Temperature > 30°C
140
humidity_condition = Condition('humidity', 'LESS_THAN', 40) # Humidity < 40%
141
142
# Create trigger for hot, dry conditions
143
start_time = datetime.now()
144
end_time = start_time + timedelta(days=7) # Monitor for 1 week
145
146
trigger = alert_mgr.create_trigger(
147
start=start_time,
148
end=end_time,
149
conditions=[temp_condition, humidity_condition],
150
area=london_area
151
)
152
153
print(f"Created trigger: {trigger.id}")
154
print(f"Monitoring from {start_time} to {end_time}")
155
print(f"Conditions: Temperature > 30°C AND Humidity < 40%")
156
```
157
158
### Monitoring Different Weather Parameters
159
160
```python
161
# Create various weather monitoring triggers
162
163
# High wind speed alert
164
wind_condition = Condition('wind_speed', 'GREATER_THAN', 15) # Wind > 15 m/s
165
wind_trigger = alert_mgr.create_trigger(
166
start=datetime.now(),
167
end=datetime.now() + timedelta(days=3),
168
conditions=[wind_condition],
169
area=london_area
170
)
171
172
# Heavy precipitation alert
173
rain_condition = Condition('rain', 'GREATER_THAN', 10) # Rain > 10mm
174
rain_trigger = alert_mgr.create_trigger(
175
start=datetime.now(),
176
end=datetime.now() + timedelta(hours=24),
177
conditions=[rain_condition],
178
area=london_area
179
)
180
181
# Low temperature alert (frost warning)
182
frost_condition = Condition('temp', 'LESS_THAN', 0) # Temperature < 0°C
183
frost_trigger = alert_mgr.create_trigger(
184
start=datetime.now(),
185
end=datetime.now() + timedelta(days=5),
186
conditions=[frost_condition],
187
area=london_area
188
)
189
190
# Complex condition: Storm warning (high wind + heavy rain)
191
storm_conditions = [
192
Condition('wind_speed', 'GREATER_THAN', 20), # Wind > 20 m/s
193
Condition('rain', 'GREATER_THAN', 15) # Rain > 15mm
194
]
195
storm_trigger = alert_mgr.create_trigger(
196
start=datetime.now(),
197
end=datetime.now() + timedelta(days=2),
198
conditions=storm_conditions,
199
area=london_area
200
)
201
202
print(f"Created wind alert trigger: {wind_trigger.id}")
203
print(f"Created rain alert trigger: {rain_trigger.id}")
204
print(f"Created frost alert trigger: {frost_trigger.id}")
205
print(f"Created storm alert trigger: {storm_trigger.id}")
206
```
207
208
### Managing Alerts
209
210
```python
211
# Check all triggers
212
triggers = alert_mgr.get_triggers()
213
print(f"Total active triggers: {len(triggers)}")
214
215
for trigger in triggers:
216
print(f"Trigger {trigger.id}:")
217
print(f" Conditions: {len(trigger.conditions)}")
218
print(f" Area polygons: {len(trigger.area)}")
219
220
# Check for alerts
221
alerts = alert_mgr.get_alerts_for(trigger)
222
print(f" Active alerts: {len(alerts)}")
223
224
if alerts:
225
for alert in alerts:
226
print(f" Alert {alert.id}:")
227
print(f" Conditions met: {alert.met_conditions}")
228
print(f" Location: {alert.coordinates}")
229
if alert.last_update:
230
print(f" Last update: {datetime.fromtimestamp(alert.last_update)}")
231
232
# Get alerts by weather parameter
233
temp_alerts = []
234
for trigger in triggers:
235
alerts = trigger.get_alerts_on('temp')
236
temp_alerts.extend(alerts)
237
238
print(f"Temperature-related alerts: {len(temp_alerts)}")
239
```
240
241
### Alert Analysis and Cleanup
242
243
```python
244
from datetime import datetime
245
246
# Get alerts from the last 24 hours
247
yesterday = datetime.now() - timedelta(days=1)
248
249
recent_alerts = []
250
for trigger in triggers:
251
alerts = trigger.get_alerts_since(int(yesterday.timestamp()))
252
recent_alerts.extend(alerts)
253
254
print(f"Alerts in last 24 hours: {len(recent_alerts)}")
255
256
# Analyze alert patterns
257
alert_locations = {}
258
for alert in recent_alerts:
259
coords = f"{alert.coordinates['lat']:.2f},{alert.coordinates['lon']:.2f}"
260
alert_locations[coords] = alert_locations.get(coords, 0) + 1
261
262
print("Alert hotspots:")
263
for location, count in sorted(alert_locations.items(), key=lambda x: x[1], reverse=True):
264
print(f" {location}: {count} alerts")
265
266
# Clean up old alerts
267
for trigger in triggers:
268
old_alerts = alert_mgr.get_alerts_for(trigger)
269
if len(old_alerts) > 100: # Keep only latest 100 alerts
270
print(f"Cleaning up old alerts for trigger {trigger.id}")
271
alert_mgr.delete_all_alerts_for(trigger)
272
```
273
274
## Data Types
275
276
```python { .api }
277
class Trigger:
278
def __init__(self, start_after_millis: int, end_after_millis: int, conditions: List[Condition],
279
area: List, alerts: List[Alert] = None, alert_channels: List = None, id: str = None): ...
280
281
def get_alerts(self) -> List[Alert]:
282
"""Returns all alerts fired by this trigger."""
283
284
def get_alert(self, alert_id: str) -> Union[Alert, None]:
285
"""Returns specific alert by ID."""
286
287
def get_alerts_since(self, timestamp: int) -> List[Alert]:
288
"""Returns alerts fired since the specified timestamp."""
289
290
def get_alerts_on(self, weather_param: str) -> List[Alert]:
291
"""Returns alerts fired for the specified weather parameter."""
292
293
@property
294
def id(self) -> str: ...
295
@property
296
def start_after_millis(self) -> int: ...
297
@property
298
def end_after_millis(self) -> int: ...
299
@property
300
def conditions(self) -> List[Condition]: ...
301
@property
302
def area(self) -> List: ...
303
@property
304
def alerts(self) -> List[Alert]: ...
305
@property
306
def alert_channels(self) -> List: ...
307
308
def to_dict(self) -> dict: ...
309
310
class Alert:
311
def __init__(self, id: str, trigger_id: str, met_conditions: List[dict],
312
coordinates: dict, last_update: int = None): ...
313
314
@property
315
def id(self) -> str: ...
316
@property
317
def trigger_id(self) -> str: ...
318
@property
319
def met_conditions(self) -> List[dict]:
320
"""
321
List of condition details that were met:
322
[
323
{
324
'current_value': float,
325
'condition': {
326
'name': str, # Weather parameter name
327
'expression': str, # Comparison operator
328
'amount': float # Threshold value
329
}
330
}
331
]
332
"""
333
@property
334
def coordinates(self) -> dict:
335
"""Geographic coordinates where condition was met: {'lat': float, 'lon': float}"""
336
@property
337
def last_update(self) -> Union[int, None]: ...
338
339
def to_dict(self) -> dict: ...
340
341
class Condition:
342
def __init__(self, weather_param: str, operator: str, amount: Union[int, float], id: str = None): ...
343
344
@property
345
def id(self) -> str: ...
346
@property
347
def weather_param(self) -> str:
348
"""
349
Weather parameter to monitor:
350
- 'temp': Temperature (°C)
351
- 'pressure': Atmospheric pressure (hPa)
352
- 'humidity': Relative humidity (%)
353
- 'wind_speed': Wind speed (m/s)
354
- 'wind_direction': Wind direction (degrees)
355
- 'rain': Precipitation amount (mm)
356
- 'snow': Snow amount (mm)
357
- 'clouds': Cloud coverage (%)
358
"""
359
@property
360
def operator(self) -> str:
361
"""
362
Comparison operator:
363
- 'GREATER_THAN': >
364
- 'GREATER_THAN_OR_EQUAL': >=
365
- 'LESS_THAN': <
366
- 'LESS_THAN_OR_EQUAL': <=
367
- 'EQUAL': =
368
- 'NOT_EQUAL': !=
369
"""
370
@property
371
def amount(self) -> Union[int, float]: ...
372
373
def to_dict(self) -> dict: ...
374
375
class AlertChannel:
376
def __init__(self, name: str): ...
377
378
@property
379
def name(self) -> str:
380
"""
381
Alert delivery channel name.
382
Supported channels depend on subscription level.
383
"""
384
385
def to_dict(self) -> dict: ...
386
```
387
388
## Weather Parameters
389
390
The following weather parameters can be monitored in conditions:
391
392
- **temp**: Temperature in Celsius
393
- **pressure**: Atmospheric pressure in hPa
394
- **humidity**: Relative humidity as percentage (0-100)
395
- **wind_speed**: Wind speed in meters per second
396
- **wind_direction**: Wind direction in degrees (0-360)
397
- **rain**: Precipitation amount in millimeters
398
- **snow**: Snow amount in millimeters
399
- **clouds**: Cloud coverage as percentage (0-100)
400
401
## Comparison Operators
402
403
- **GREATER_THAN**: Value is greater than threshold
404
- **GREATER_THAN_OR_EQUAL**: Value is greater than or equal to threshold
405
- **LESS_THAN**: Value is less than threshold
406
- **LESS_THAN_OR_EQUAL**: Value is less than or equal to threshold
407
- **EQUAL**: Value equals threshold
408
- **NOT_EQUAL**: Value does not equal threshold
409
410
## Geographic Areas
411
412
Areas are defined using geoJSON geometry objects:
413
414
- **Point**: Single coordinate `{"type": "Point", "coordinates": [lon, lat]}`
415
- **Polygon**: Closed area `{"type": "Polygon", "coordinates": [[[lon, lat], ...]]}`
416
- **MultiPolygon**: Multiple areas `{"type": "MultiPolygon", "coordinates": [[[[lon, lat], ...]]]}`
417
418
## Alert Delivery
419
420
Alerts can be delivered through various channels (availability depends on subscription level):
421
422
- **HTTP callbacks**: POST requests to specified URLs
423
- **Email notifications**: Alerts sent to email addresses
424
- **SMS notifications**: Text message alerts (premium feature)
425
- **Push notifications**: Mobile app notifications (premium feature)