python-zulip-api/zulip_bots/zulip_bots/bots/incrementor/incrementor.py
Marco Burstein 3c66894aff incrementor: Clean up type annotation/conversion.
This adds mypy annotations, and we also make the type
conversions in `handle_message` be a little more clear.

(@showell helped clean up this commit a bit)
2017-12-11 10:59:40 -06:00

45 lines
1.5 KiB
Python

# See readme.md for instructions on running this code.
from zulip_bots.lib import ExternalBotHandler
class IncrementorHandler(object):
META = {
'name': 'Incrementor',
'description': 'Example bot to test the update_message() function.',
}
def usage(self) -> str:
return '''
This is a boilerplate bot that makes use of the
update_message function. For the first @-mention, it initially
replies with one message containing a `1`. Every time the bot
is @-mentioned, this number will be incremented in the same message.
'''
def initialize(self, bot_handler: ExternalBotHandler) -> None:
storage = bot_handler.storage
if not storage.contains('number') or not storage.contains('message_id'):
storage.put('number', 0)
storage.put('message_id', None)
def handle_message(self, message: dict, bot_handler: ExternalBotHandler) -> None:
storage = bot_handler.storage
num = storage.get('number')
# num should already be an int, but we do `int()` to force an
# explicit type check
num = int(num) + 1
storage.put('number', num)
if storage.get('message_id') is None:
result = bot_handler.send_reply(message, str(num))
storage.put('message_id', result['id'])
else:
bot_handler.update_message(dict(
message_id=storage.get('message_id'),
content=str(num)
))
handler_class = IncrementorHandler