Skip to content

Commit

Permalink
Display Google Calendar "flair" banners in front of /events and daily…
Browse files Browse the repository at this point in the history
… announcements if the first event listed matches on of its patterns.

Note that the selection of flair (both whether flair is displayed or not, and which image is used) is currently decided permanently during the initial daily announcement. If the first event is removed, pushed down by a new event, or changes its summary/description to no longer match the chosen image, the image will remain in place; only the text will be updated.

See #74.
  • Loading branch information
nmlorg committed Aug 25, 2019
1 parent 7b8c3f0 commit 35da2c6
Show file tree
Hide file tree
Showing 5 changed files with 769 additions and 18 deletions.
14 changes: 10 additions & 4 deletions metabot/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def _dont_mangle_callback_data(monkeypatch):


def _format_message(response):
text = response.pop('text', '(EMPTY MESSAGE)')
text = response.pop('text', None) or response.pop('caption', '(EMPTY MESSAGE)')
reply_markup = response.pop('reply_markup', None)
header = ' '.join('%s=%s' % (field, value) for field, value in sorted(response.items()))
text = '[%s]\n%s\n' % (header, text)
Expand Down Expand Up @@ -87,12 +87,18 @@ def raw_message(self, text, user_id=1000, chat_type='private'):
responses = []

def _handler(request, unused_context):
responses.append(json.loads(request.body.decode('ascii')))
return {'ok': True, 'result': {'message_id': 12345}}

response = json.loads(request.body.decode('ascii'))
responses.append(response)
message = {'message_id': 12345}
if response.get('caption'):
message['caption'] = 'CAPTION'
return {'ok': True, 'result': message}

self.bot.edit_message_caption.respond(json=_handler)
self.bot.edit_message_text.respond(json=_handler)
self.bot.forward_message.respond(json=_handler)
self.bot.send_message.respond(json=_handler)
self.bot.send_photo.respond(json=_handler)
self.multibot.dispatcher(self.bot, update)
return responses

Expand Down
40 changes: 29 additions & 11 deletions metabot/modules/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from metabot.util import adminui
from metabot.util import html
from metabot.util import humanize
from metabot.util import icons
from metabot.util import pickleutil
from metabot.util import tickets

Expand Down Expand Up @@ -65,12 +66,20 @@ def _daily_messages(multibot, records): # pylint: disable=too-many-branches,too
if events:
preambles = groupconf['daily'].get('text', '').splitlines()
preamble = (preambles and preambles[nowdt.toordinal() % len(preambles)] or '')
message = bot.send_message(chat_id=groupid,
text=_format_daily_message(
preamble, list(map(form, events))),
parse_mode='HTML',
disable_web_page_preview=True,
disable_notification=True)
text = _format_daily_message(preamble, list(map(form, events)))
url = icons.match(events[0]['summary']) or icons.match(events[0]['description'])
if url:
message = bot.send_photo(chat_id=groupid,
photo=url,
caption=text,
parse_mode='HTML',
disable_notification=True)
else:
message = bot.send_message(chat_id=groupid,
text=text,
parse_mode='HTML',
disable_web_page_preview=True,
disable_notification=True)
records[botuser, groupid] = (now, [event.copy() for event in events], message)
elif (botuser, groupid) in records:
lastnow, lastevents, lastmessage = records[botuser, groupid]
Expand Down Expand Up @@ -129,11 +138,17 @@ def _daily_messages(multibot, records): # pylint: disable=too-many-branches,too
-1000000000000 - groupidnum, message['message_id'], updated)
text = '%s\n\n[%s]' % (_format_daily_message(preamble, list(map(form,
events))), updated)
message = bot.edit_message_text(chat_id=groupid,
message_id=lastmessage['message_id'],
text=text,
parse_mode='HTML',
disable_web_page_preview=True)
if lastmessage.get('caption'):
message = bot.edit_message_caption(chat_id=groupid,
message_id=lastmessage['message_id'],
caption=text,
parse_mode='HTML')
else:
message = bot.edit_message_text(chat_id=groupid,
message_id=lastmessage['message_id'],
text=text,
parse_mode='HTML',
disable_web_page_preview=True)

records[botuser, groupid] = (lastnow, [event.copy() for event in events], message)

Expand Down Expand Up @@ -235,6 +250,9 @@ def group(ctx, msg):
if not events:
msg.add('No events in the next %s days!', days)
else:
url = icons.match(events[0]['summary']) or icons.match(events[0]['description'])
if url:
msg.add('photo:' + url)
msg.add('\n'.join(format_event(ctx.bot, event, tzinfo, full=False) for event in events))


Expand Down
124 changes: 123 additions & 1 deletion metabot/modules/test_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ def test_format_daily_message(): # pylint: disable=missing-docstring
# yapf: enable


def test_daily_messages(conversation, monkeypatch): # pylint: disable=redefined-outer-name
def test_daily_messages(conversation, monkeypatch): # pylint: disable=redefined-outer-name,too-many-statements
"""Test daily announcement logic."""

monkeypatch.setattr('time.time', lambda: 0)
Expand Down Expand Up @@ -755,6 +755,128 @@ def test_daily_messages(conversation, monkeypatch): # pylint: disable=redefined
}
assert conversation.format_messages(replies) == ''

cal.events['6fc2c510:alpha']['description'] = 'Board Games!'

events._daily_messages(conversation.multibot, records) # pylint: disable=protected-access
assert records == {
('modulestestbot', '-1002000002000'): (0, [{
'description': 'Board Games!',
'end': 2060,
'local_id': '6fc2c510:alpha',
'location': 'Alpha Venue, Rest of Alpha Location',
'start': 1000,
'summary': 'Edited Summary',
'updated': 23456,
}, {
'description': 'New Description',
'end': 3000,
'local_id': '6fc2c510:new',
'location': 'New Venue, Rest of New Location',
'start': 2000,
'summary': 'New Summary',
}], {
'message_id': 12345,
}),
}
assert conversation.format_messages(replies) == """\
[chat_id=-1002000002000 disable_notification=True disable_web_page_preview=True parse_mode=HTML reply_to_message_id=12345]
Updated:
Edited Summary
• <i>Multi Line Description</i> → <b>Board Games!</b>
[chat_id=-1002000002000 disable_web_page_preview=True message_id=12345 parse_mode=HTML]
There are a couple events coming up:
<b>Edited Summary</b>
<a href="https://t.me/modulestestbot?start=L2V2ZW50cyA2ZmMyYzUxMDphbHBoYSBVVEM">NOW, Thu 1ˢᵗ, 12:16–12:34 am</a> @ <a href="https://maps.google.com/maps?q=Alpha+Venue%2C+Rest+of+Alpha+Location">Alpha Venue</a>
<b>New Summary</b>
<a href="https://t.me/modulestestbot?start=L2V2ZW50cyA2ZmMyYzUxMDpuZXcgVVRD">TODAY, Thu 1ˢᵗ, 12:33–12:50 am</a> @ <a href="https://maps.google.com/maps?q=New+Venue%2C+Rest+of+New+Location">New Venue</a>
[<a href="https://t.me/c/2000002000/12345">Updated</a>]
"""
replies.clear()

conversation.bot.config['issue37']['moderator']['-1002000002000']['daily']['hour'] = 0
records = {}

events._daily_messages(conversation.multibot, records) # pylint: disable=protected-access
assert records == {
('modulestestbot', '-1002000002000'): (1000, [{
'description': 'Board Games!',
'end': 2060,
'local_id': '6fc2c510:alpha',
'location': 'Alpha Venue, Rest of Alpha Location',
'start': 1000,
'summary': 'Edited Summary',
'updated': 23456,
}, {
'description': 'New Description',
'end': 3000,
'local_id': '6fc2c510:new',
'location': 'New Venue, Rest of New Location',
'start': 2000,
'summary': 'New Summary',
}], {
'caption': 'CAPTION',
'message_id': 12345,
}),
}
assert conversation.format_messages(replies) == """\
[chat_id=-1002000002000 disable_notification=True parse_mode=HTML photo=https://ssl.gstatic.com/calendar/images/eventillustrations/v1/img_gamenight_2x.jpg]
There are a couple events coming up:
<b>Edited Summary</b>
<a href="https://t.me/modulestestbot?start=L2V2ZW50cyA2ZmMyYzUxMDphbHBoYSBVVEM">NOW, Thu 1ˢᵗ, 12:16–12:34 am</a> @ <a href="https://maps.google.com/maps?q=Alpha+Venue%2C+Rest+of+Alpha+Location">Alpha Venue</a>
<b>New Summary</b>
<a href="https://t.me/modulestestbot?start=L2V2ZW50cyA2ZmMyYzUxMDpuZXcgVVRD">TODAY, Thu 1ˢᵗ, 12:33–12:50 am</a> @ <a href="https://maps.google.com/maps?q=New+Venue%2C+Rest+of+New+Location">New Venue</a>
"""
replies.clear()

conversation.bot.config['issue37']['moderator']['-1002000002000']['daily']['hour'] = 1
cal.events['6fc2c510:alpha']['description'] = 'Fun Games!'

events._daily_messages(conversation.multibot, records) # pylint: disable=protected-access
assert records == {
('modulestestbot', '-1002000002000'): (1000, [{
'description': 'Fun Games!',
'end': 2060,
'local_id': '6fc2c510:alpha',
'location': 'Alpha Venue, Rest of Alpha Location',
'start': 1000,
'summary': 'Edited Summary',
'updated': 23456,
}, {
'description': 'New Description',
'end': 3000,
'local_id': '6fc2c510:new',
'location': 'New Venue, Rest of New Location',
'start': 2000,
'summary': 'New Summary',
}], {
'caption': 'CAPTION',
'message_id': 12345,
}),
}
assert conversation.format_messages(replies) == """\
[chat_id=-1002000002000 disable_notification=True disable_web_page_preview=True parse_mode=HTML reply_to_message_id=12345]
Updated:
Edited Summary
• <i>Board Games!</i> → <b>Fun Games!</b>
[chat_id=-1002000002000 message_id=12345 parse_mode=HTML]
There are a couple events coming up:
<b>Edited Summary</b>
<a href="https://t.me/modulestestbot?start=L2V2ZW50cyA2ZmMyYzUxMDphbHBoYSBVVEM">NOW, Thu 1ˢᵗ, 12:16–12:34 am</a> @ <a href="https://maps.google.com/maps?q=Alpha+Venue%2C+Rest+of+Alpha+Location">Alpha Venue</a>
<b>New Summary</b>
<a href="https://t.me/modulestestbot?start=L2V2ZW50cyA2ZmMyYzUxMDpuZXcgVVRD">TODAY, Thu 1ˢᵗ, 12:33–12:50 am</a> @ <a href="https://maps.google.com/maps?q=New+Venue%2C+Rest+of+New+Location">New Venue</a>
[<a href="https://t.me/c/2000002000/12345">Updated</a>]
"""
replies.clear()


def test_quick_diff():
"""Test description string differ."""
Expand Down
Loading

0 comments on commit 35da2c6

Please sign in to comment.