Skip to content

Commit fa4c3b8

Browse files
committed
Remove weather alerts.
See #80 (comment). Obsoletes #85 and #86.
1 parent e8dc92a commit fa4c3b8

File tree

5 files changed

+10
-224
lines changed

5 files changed

+10
-224
lines changed

metabot/modules/events.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def group(ctx, msg):
4545
"I'm not configured for this group! Ask a bot admin to go into the <b>moderator</b> "
4646
'module settings, group <b>%s</b>, and %s.', group_id, humanize.list(missing))
4747

48-
events, unused_alerts = calconf.get_events(ctx.bot)
48+
events = calconf.get_events(ctx.bot)
4949
if not events:
5050
msg.add('No events in the next %s days!', calconf.days)
5151
else:

metabot/modules/reminders.py

Lines changed: 6 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@ def queue():
3131
records = pickleutil.load(recordsfname) or {}
3232

3333
for key, record in records.items():
34-
botuser, unused_groupid = key
35-
if botuser != 'alerts' and len(record) == 3:
34+
if len(record) == 3:
3635
records[key] += ('', '')
3736
else:
3837
recordsfname = None
@@ -64,7 +63,7 @@ def get_events(self, bot, eventtime, base, *, countdown=True):
6463
"""Get (and format) events for the given time."""
6564

6665
calconf = self.calconf
67-
events, alerts = calconf.get_events(bot, when=eventtime)
66+
events = calconf.get_events(bot, when=eventtime)
6867
if self.preambles:
6968
preamble = self.preambles[int(eventtime / (60 * 60 * 24)) % len(self.preambles)]
7069
else:
@@ -77,7 +76,7 @@ def get_events(self, bot, eventtime, base, *, countdown=True):
7776
base=base,
7877
countdown=countdown)
7978
text = f'{text}\n\n{ev}'
80-
return events, alerts, text
79+
return events, text
8180

8281

8382
class Announcement(collections.namedtuple('Announcement', 'time events message text suffix')):
@@ -112,22 +111,20 @@ def _daily_messages(multibot, records): # pylint: disable=too-many-branches,too
112111

113112
if perioddt.hour == annconf.hour and not annconf.dow & 1 << perioddt.weekday() and (
114113
not last or startofhour > last.time // 3600):
115-
events, alerts, text = annconf.get_events(bot, period, perioddt)
116-
_handle_alerts(bot, records, groupid, alerts)
114+
events, text = annconf.get_events(bot, period, perioddt)
117115
if events:
118116
url = eventutil.get_image(events[0], botconf)
119117
message = reminder_send(bot, groupid, text, url)
120118
if message:
121119
records[key] = (period, [event.copy() for event in events], message, text,
122120
'')
123121
if last:
124-
text = annconf.get_events(bot, last.time, perioddt, countdown=False)[2]
122+
text = annconf.get_events(bot, last.time, perioddt, countdown=False)[1]
125123
reminder_edit(bot, last.message, text)
126124
continue
127125

128126
if last:
129-
events, alerts, text = annconf.get_events(bot, last.time, perioddt)
130-
_handle_alerts(bot, records, groupid, alerts)
127+
events, text = annconf.get_events(bot, last.time, perioddt)
131128
edits = diff_events(multibot, calconf.tzinfo, perioddt, last.events, events)
132129

133130
suffix = last.suffix
@@ -366,67 +363,3 @@ def _generate_preamble(preamble, events):
366363
text = 'Also, ' + text
367364
text = preamble + text
368365
return text
369-
370-
371-
def _handle_alerts(bot, records, groupid, alerts):
372-
# See https://github.com/nmlorg/metabot/issues/85.
373-
alerts = [
374-
alert for alert in alerts
375-
if alert['urgency'] in ('Immediate', 'Expected') and alert['severity'] in (
376-
'Extreme', 'Severe') and alert['certainty'] == 'Observed'
377-
]
378-
379-
text = _format_alerts(alerts)
380-
381-
kwargs = {}
382-
key = ('alerts', groupid)
383-
if key in records:
384-
if not text:
385-
records.pop(key)
386-
return
387-
lasttext, lastmessage = records[key]
388-
if lasttext == text:
389-
return
390-
kwargs['reply_to_message_id'] = lastmessage['message_id']
391-
if text:
392-
message = None
393-
try:
394-
message = bot.send_message(chat_id=groupid,
395-
text=_truncate(text,
396-
ntelebot.limits.message_text_length_max),
397-
parse_mode='HTML',
398-
disable_web_page_preview=True,
399-
disable_notification=True,
400-
**kwargs)
401-
except ntelebot.errors.Error:
402-
logging.exception('While sending to %s:\n%s', groupid, text)
403-
if not message and kwargs:
404-
try:
405-
message = bot.send_message(chat_id=groupid,
406-
text=text,
407-
parse_mode='HTML',
408-
disable_web_page_preview=True,
409-
disable_notification=True)
410-
except ntelebot.errors.Error:
411-
logging.exception('While sending to %s:\n%s', groupid, text)
412-
if message:
413-
records[key] = (text, message)
414-
415-
416-
def _format_alerts(alerts):
417-
if not alerts:
418-
return ''
419-
text = []
420-
for alert in alerts:
421-
text.append('<a href="https://alerts-v2.weather.gov/products/%s">%s %s</a>' %
422-
(alert['id'], alert['event'], alert['id']))
423-
text.append('')
424-
desc = '%s\n\n%s\n\n%s' % (alert['description'], alert['instruction'], alert['areaDesc'])
425-
desc = re.sub(r'\s*\n\s*', ' ', re.sub(r'\s*\n\s*\n\s*', '\0',
426-
desc)).replace('\0', '\n\n').strip()
427-
if len(desc) > 250:
428-
desc = desc[:249] + '\u2026'
429-
text.append(desc)
430-
text.append('')
431-
text.append('')
432-
return '\n'.join(text).strip()

metabot/modules/test_reminders.py

Lines changed: 0 additions & 111 deletions
Original file line numberDiff line numberDiff line change
@@ -1136,114 +1136,3 @@ def test_sanitize(daily_messages): # pylint: disable=redefined-outer-name
11361136
11371137
[<a href="https://t.me/c/2000002000/12346">Updated 12:33ᵃᵐ</a>]
11381138
"""
1139-
1140-
1141-
@pytest.fixture
1142-
def handle_alerts(conversation): # pylint: disable=missing-docstring,redefined-outer-name
1143-
replies = conversation.raw_message('/dummy')
1144-
assert conversation.format_messages(replies) == ''
1145-
1146-
records = {}
1147-
groupid = '-1001000001000'
1148-
1149-
def _handle_alerts(alerts):
1150-
replies.clear()
1151-
reminders._handle_alerts(conversation.bot, records, groupid, alerts) # pylint: disable=protected-access
1152-
return conversation.format_messages(replies)
1153-
1154-
return _handle_alerts
1155-
1156-
1157-
def test_handle_alerts(handle_alerts): # pylint: disable=redefined-outer-name
1158-
"""Test basic behavior of reminders._handle_alerts."""
1159-
1160-
# First poll; no active alerts.
1161-
assert handle_alerts([]) == ''
1162-
1163-
# Second poll; brand-new alert.
1164-
alerts = [{
1165-
'id': 'alert-id',
1166-
'areaDesc': 'Area description',
1167-
'description': 'Alert Description',
1168-
'instruction': 'Alert Instructions',
1169-
'event': 'Winter Storm Warning',
1170-
'messageType': 'Alert',
1171-
'urgency': 'Immediate',
1172-
'severity': 'Extreme',
1173-
'certainty': 'Observed',
1174-
}]
1175-
assert handle_alerts(alerts) == """\
1176-
[chat_id=-1001000001000 disable_notification=True disable_web_page_preview=True parse_mode=HTML]
1177-
<a href="https://alerts-v2.weather.gov/products/alert-id">Winter Storm Warning alert-id</a>
1178-
1179-
Alert Description
1180-
1181-
Alert Instructions
1182-
1183-
Area description
1184-
"""
1185-
1186-
# Third poll; same alert is active.
1187-
assert handle_alerts(alerts) == ''
1188-
1189-
# Fourth poll; existing alert is modified.
1190-
alerts[0]['instruction'] = 'Run for your lives!'
1191-
assert handle_alerts(alerts) == """\
1192-
[chat_id=-1001000001000 disable_notification=True disable_web_page_preview=True parse_mode=HTML reply_to_message_id=12345]
1193-
<a href="https://alerts-v2.weather.gov/products/alert-id">Winter Storm Warning alert-id</a>
1194-
1195-
Alert Description
1196-
1197-
Run for your lives!
1198-
1199-
Area description
1200-
"""
1201-
1202-
# Fifth poll; another new alert.
1203-
alerts.append({
1204-
'id': 'alert-id-2',
1205-
'areaDesc': 'Second area description',
1206-
'description': 'Second Description',
1207-
'instruction': 'Second Instructions',
1208-
'event': 'Winter Storm Watch',
1209-
'messageType': 'Alert',
1210-
'urgency': 'Immediate',
1211-
'severity': 'Extreme',
1212-
'certainty': 'Observed',
1213-
})
1214-
assert handle_alerts(alerts) == """\
1215-
[chat_id=-1001000001000 disable_notification=True disable_web_page_preview=True parse_mode=HTML reply_to_message_id=12346]
1216-
<a href="https://alerts-v2.weather.gov/products/alert-id">Winter Storm Warning alert-id</a>
1217-
1218-
Alert Description
1219-
1220-
Run for your lives!
1221-
1222-
Area description
1223-
1224-
1225-
<a href="https://alerts-v2.weather.gov/products/alert-id-2">Winter Storm Watch alert-id-2</a>
1226-
1227-
Second Description
1228-
1229-
Second Instructions
1230-
1231-
Second area description
1232-
"""
1233-
1234-
# Sixth poll; both alerts have been canceled.
1235-
assert handle_alerts([]) == ''
1236-
1237-
# Seventh poll; a new alert that we don't care about.
1238-
alerts = [{
1239-
'id': 'alert-id-3',
1240-
'areaDesc': 'Third area description',
1241-
'description': 'Third Description',
1242-
'instruction': 'Third Instructions',
1243-
'event': 'Special Weather Statement',
1244-
'messageType': 'Alert',
1245-
'urgency': 'Immediate',
1246-
'severity': 'Moderate',
1247-
'certainty': 'Observed',
1248-
}]
1249-
assert handle_alerts([]) == ''

metabot/util/eventutil.py

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -30,34 +30,21 @@ def __init__(self, groupconf):
3030
self.tzinfo = timezone and pytz.timezone(timezone)
3131

3232
def get_events(self, bot, *, when=None):
33-
"""Build lists of events and weather alerts for the given time (or now)."""
33+
"""Build lists of events for the given time (or now)."""
3434

3535
return _get_group_events(bot, self.calcodes, self.tzinfo, self.count, self.days, now=when)
3636

3737

3838
def _get_group_events(bot, calcodes, tzinfo, count, days, *, now=None): # pylint: disable=too-many-arguments,too-many-locals
39-
"""Build lists of events and weather alerts for the given calendar configuration."""
39+
"""Build lists of events for the given calendar configuration."""
4040

4141
calendar_view = bot.multibot.multical.view(calcodes)
4242
if now is None:
4343
now = time.time()
4444
nowdt = datetime.datetime.fromtimestamp(now, tzinfo)
4545
midnight = nowdt.replace(hour=0, minute=0, second=0, microsecond=0)
4646
period = (midnight + datetime.timedelta(days=days + 1) - nowdt).total_seconds()
47-
all_events = list(calendar_view.get_overlap(now, now + max(period, 60 * 60 * 24 * 100)))
48-
alerts = {}
49-
for event in all_events:
50-
if event['location']:
51-
try:
52-
alertlist = geoutil.weatheralerts(event['location'])
53-
except Exception: # pylint: disable=broad-except
54-
logging.exception('Ignoring:')
55-
else:
56-
for alert in alertlist or ():
57-
alerts[alert['id']] = alert
58-
end = now + period
59-
return ([event for event in all_events[:count] if event['start'] <= end],
60-
[alert for alertid, alert in sorted(alerts.items())])
47+
return list(calendar_view.get_overlap(now, now + period))[:count]
6148

6249

6350
def format_event(bot, event, tzinfo, *, full=True, base=None, countdown=True): # pylint: disable=too-many-arguments

metabot/util/geoutil.py

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -91,26 +91,3 @@ def hourlyforecast(address, when):
9191
return
9292
return _hourlyforecast(geo[0]['geometry']['location']['lat'],
9393
geo[0]['geometry']['location']['lng'], when)
94-
95-
96-
def _weatheralerts(lat, lon):
97-
point = _weatherpoint(lat, lon)
98-
if not point.get('properties'):
99-
return
100-
now = time.time()
101-
url = 'alerts/active?zone=' + point['properties']['forecastZone'].rsplit('/', 1)[1]
102-
last, ret = _SHORTCACHE.get(url) or (0, None)
103-
if last < now - 10 * 60:
104-
ret = [feature['properties'] for feature in _weatherfetch(url)['features']]
105-
_SHORTCACHE[url] = (now, ret)
106-
return ret
107-
108-
109-
def weatheralerts(address):
110-
"""Retrieve active NWS weather alerts for the given address."""
111-
112-
geo = geocode(address)
113-
if not geo:
114-
return
115-
return _weatheralerts(geo[0]['geometry']['location']['lat'],
116-
geo[0]['geometry']['location']['lng'])

0 commit comments

Comments
 (0)