2017-01-14 13:58:03 -05:00
|
|
|
from __future__ import print_function
|
|
|
|
|
|
|
|
import logging
|
|
|
|
import os
|
|
|
|
import signal
|
|
|
|
import sys
|
|
|
|
import time
|
2017-02-16 16:56:32 -05:00
|
|
|
import re
|
2017-01-14 13:58:03 -05:00
|
|
|
|
2017-06-10 07:56:00 -04:00
|
|
|
from six.moves import configparser
|
|
|
|
|
2017-05-26 00:58:19 -04:00
|
|
|
if False:
|
|
|
|
from mypy_extensions import NoReturn
|
|
|
|
from typing import Any, Optional, List, Dict
|
|
|
|
from types import ModuleType
|
|
|
|
|
2017-01-14 13:58:03 -05:00
|
|
|
our_dir = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
|
|
|
|
# For dev setups, we can find the API in the repo itself.
|
2017-05-30 02:10:19 -04:00
|
|
|
if os.path.exists(os.path.join(our_dir, '../zulip')):
|
|
|
|
sys.path.insert(0, os.path.join(our_dir, '../'))
|
2017-01-14 13:58:03 -05:00
|
|
|
|
|
|
|
from zulip import Client
|
|
|
|
|
|
|
|
def exit_gracefully(signum, frame):
|
2017-05-26 00:58:19 -04:00
|
|
|
# type: (int, Optional[Any]) -> None
|
2017-01-14 13:58:03 -05:00
|
|
|
sys.exit(0)
|
|
|
|
|
|
|
|
class RateLimit(object):
|
|
|
|
def __init__(self, message_limit, interval_limit):
|
2017-05-26 00:58:19 -04:00
|
|
|
# type: (int, int) -> None
|
2017-01-14 13:58:03 -05:00
|
|
|
self.message_limit = message_limit
|
|
|
|
self.interval_limit = interval_limit
|
2017-06-04 05:30:42 -04:00
|
|
|
self.message_list = [] # type: List[float]
|
2017-05-23 20:25:01 -04:00
|
|
|
self.error_message = '-----> !*!*!*MESSAGE RATE LIMIT REACHED, EXITING*!*!*! <-----\n'
|
|
|
|
'Is your bot trapped in an infinite loop by reacting to its own messages?'
|
2017-01-14 13:58:03 -05:00
|
|
|
|
|
|
|
def is_legal(self):
|
2017-05-26 00:58:19 -04:00
|
|
|
# type: () -> bool
|
2017-01-14 13:58:03 -05:00
|
|
|
self.message_list.append(time.time())
|
|
|
|
if len(self.message_list) > self.message_limit:
|
|
|
|
self.message_list.pop(0)
|
|
|
|
time_diff = self.message_list[-1] - self.message_list[0]
|
|
|
|
return time_diff >= self.interval_limit
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
|
2017-05-23 20:25:01 -04:00
|
|
|
def show_error_and_exit(self):
|
2017-05-26 00:58:19 -04:00
|
|
|
# type: () -> NoReturn
|
2017-05-23 20:25:01 -04:00
|
|
|
logging.error(self.error_message)
|
|
|
|
sys.exit(1)
|
|
|
|
|
2017-06-18 14:42:28 -04:00
|
|
|
def send_reply(message, response, email, send_message):
|
|
|
|
# type: (Dict[str, Any], str, str, Any) -> Dict[str, Any]
|
|
|
|
if message['type'] == 'private':
|
|
|
|
return send_message(dict(
|
|
|
|
type='private',
|
|
|
|
to=[x['email'] for x in message['display_recipient'] if email != x['email']],
|
|
|
|
content=response,
|
|
|
|
))
|
|
|
|
else:
|
|
|
|
return send_message(dict(
|
|
|
|
type='stream',
|
|
|
|
to=message['display_recipient'],
|
|
|
|
subject=message['subject'],
|
|
|
|
content=response,
|
|
|
|
))
|
|
|
|
|
2017-05-23 20:25:01 -04:00
|
|
|
|
2017-06-07 22:49:42 -04:00
|
|
|
class ExternalBotHandler(object):
|
2017-01-14 13:58:03 -05:00
|
|
|
def __init__(self, client):
|
2017-05-26 00:58:19 -04:00
|
|
|
# type: (Client) -> None
|
2017-01-14 13:58:03 -05:00
|
|
|
# Only expose a subset of our Client's functionality
|
|
|
|
user_profile = client.get_profile()
|
|
|
|
self._rate_limit = RateLimit(20, 5)
|
|
|
|
self._client = client
|
|
|
|
try:
|
|
|
|
self.full_name = user_profile['full_name']
|
|
|
|
self.email = user_profile['email']
|
|
|
|
except KeyError:
|
|
|
|
logging.error('Cannot fetch user profile, make sure you have set'
|
|
|
|
' up the zuliprc file correctly.')
|
|
|
|
sys.exit(1)
|
|
|
|
|
2017-05-26 00:58:19 -04:00
|
|
|
def send_message(self, message):
|
|
|
|
# type: (Dict[str, Any]) -> Dict[str, Any]
|
2017-01-14 13:58:03 -05:00
|
|
|
if self._rate_limit.is_legal():
|
2017-05-26 00:58:19 -04:00
|
|
|
return self._client.send_message(message)
|
2017-05-23 20:12:36 -04:00
|
|
|
else:
|
2017-05-23 20:25:01 -04:00
|
|
|
self._rate_limit.show_error_and_exit()
|
2017-05-23 20:12:36 -04:00
|
|
|
|
2017-06-18 14:42:28 -04:00
|
|
|
def send_reply(self, message, response):
|
|
|
|
# type: (Dict[str, Any], str) -> Dict[str, Any]
|
|
|
|
return send_reply(message, response, self.email, self.send_message)
|
|
|
|
|
2017-05-26 00:58:19 -04:00
|
|
|
def update_message(self, message):
|
|
|
|
# type: (Dict[str, Any]) -> Dict[str, Any]
|
2017-05-23 20:12:36 -04:00
|
|
|
if self._rate_limit.is_legal():
|
2017-05-26 00:58:19 -04:00
|
|
|
return self._client.update_message(message)
|
2017-01-14 13:58:03 -05:00
|
|
|
else:
|
2017-05-23 20:25:01 -04:00
|
|
|
self._rate_limit.show_error_and_exit()
|
2017-01-14 13:58:03 -05:00
|
|
|
|
2017-06-18 14:42:28 -04:00
|
|
|
def get_config_info(self, bot_name, section=None):
|
|
|
|
# type: (str, Optional[str]) -> Dict[str, Any]
|
|
|
|
conf_file_path = os.path.realpath(os.path.join(
|
|
|
|
our_dir, '..', 'bots', bot_name, bot_name + '.conf'))
|
|
|
|
section = section or bot_name
|
|
|
|
config = configparser.ConfigParser()
|
|
|
|
config.readfp(open(conf_file_path)) # type: ignore
|
|
|
|
return dict(config.items(section))
|
|
|
|
|
2017-05-21 23:05:07 -04:00
|
|
|
class StateHandler(object):
|
|
|
|
def __init__(self):
|
2017-05-26 00:58:19 -04:00
|
|
|
# type: () -> None
|
2017-06-04 05:30:42 -04:00
|
|
|
self.state = None # type: Any
|
2017-05-21 23:05:07 -04:00
|
|
|
|
|
|
|
def set_state(self, state):
|
2017-05-26 00:58:19 -04:00
|
|
|
# type: (Any) -> None
|
2017-05-21 23:05:07 -04:00
|
|
|
self.state = state
|
|
|
|
|
|
|
|
def get_state(self):
|
2017-05-26 00:58:19 -04:00
|
|
|
# type: () -> Any
|
2017-05-21 23:05:07 -04:00
|
|
|
return self.state
|
|
|
|
|
2017-01-14 13:58:03 -05:00
|
|
|
def run_message_handler_for_bot(lib_module, quiet, config_file):
|
2017-05-26 00:58:19 -04:00
|
|
|
# type: (Any, bool, str) -> Any
|
|
|
|
#
|
|
|
|
# lib_module is of type Any, since it can contain any bot's
|
|
|
|
# handler class. Eventually, we want bot's handler classes to
|
|
|
|
# inherit from a common prototype specifying the handle_message
|
|
|
|
# function.
|
|
|
|
#
|
2017-01-14 13:58:03 -05:00
|
|
|
# Make sure you set up your ~/.zuliprc
|
|
|
|
client = Client(config_file=config_file)
|
2017-06-07 22:49:42 -04:00
|
|
|
restricted_client = ExternalBotHandler(client)
|
2017-01-14 13:58:03 -05:00
|
|
|
|
|
|
|
message_handler = lib_module.handler_class()
|
2017-06-10 05:55:55 -04:00
|
|
|
if hasattr(message_handler, 'initialize'):
|
|
|
|
message_handler.initialize(bot_handler=restricted_client)
|
2017-01-14 13:58:03 -05:00
|
|
|
|
|
|
|
state_handler = StateHandler()
|
|
|
|
|
|
|
|
if not quiet:
|
|
|
|
print(message_handler.usage())
|
|
|
|
|
2017-05-22 21:22:46 -04:00
|
|
|
def extract_query_without_mention(message, client):
|
2017-06-07 22:49:42 -04:00
|
|
|
# type: (Dict[str, Any], ExternalBotHandler) -> str
|
2017-05-22 21:22:46 -04:00
|
|
|
"""
|
|
|
|
If the bot is the first @mention in the message, then this function returns
|
|
|
|
the message with the bot's @mention removed. Otherwise, it returns None.
|
|
|
|
"""
|
2017-05-22 19:14:30 -04:00
|
|
|
bot_mention = r'^@(\*\*{0}\*\*)'.format(client.full_name)
|
2017-02-16 16:56:32 -05:00
|
|
|
start_with_mention = re.compile(bot_mention).match(message['content'])
|
2017-05-22 19:14:30 -04:00
|
|
|
if start_with_mention is None:
|
2017-05-23 11:17:18 -04:00
|
|
|
return None
|
2017-05-22 19:14:30 -04:00
|
|
|
query_without_mention = message['content'][len(start_with_mention.group()):]
|
2017-05-22 22:01:04 -04:00
|
|
|
return query_without_mention.lstrip()
|
2017-02-16 16:56:32 -05:00
|
|
|
|
|
|
|
def is_private(message, client):
|
2017-06-07 22:49:42 -04:00
|
|
|
# type: (Dict[str, Any], ExternalBotHandler) -> bool
|
2017-02-16 16:56:32 -05:00
|
|
|
# bot will not reply if the sender name is the same as the bot name
|
|
|
|
# to prevent infinite loop
|
|
|
|
if message['type'] == 'private':
|
|
|
|
return client.full_name != message['sender_full_name']
|
|
|
|
return False
|
|
|
|
|
2017-01-14 13:58:03 -05:00
|
|
|
def handle_message(message):
|
2017-05-26 00:58:19 -04:00
|
|
|
# type: (Dict[str, Any]) -> None
|
2017-01-14 13:58:03 -05:00
|
|
|
logging.info('waiting for next message')
|
2017-02-16 16:56:32 -05:00
|
|
|
|
2017-05-22 21:22:46 -04:00
|
|
|
# is_mentioned is true if the bot is mentioned at ANY position (not necessarily
|
|
|
|
# the first @mention in the message).
|
2017-02-16 16:56:32 -05:00
|
|
|
is_mentioned = message['is_mentioned']
|
|
|
|
is_private_message = is_private(message, restricted_client)
|
|
|
|
|
|
|
|
# Strip at-mention botname from the message
|
|
|
|
if is_mentioned:
|
2017-05-22 21:22:46 -04:00
|
|
|
# message['content'] will be None when the bot's @-mention is not at the beginning.
|
|
|
|
# In that case, the message shall not be handled.
|
|
|
|
message['content'] = extract_query_without_mention(message=message, client=restricted_client)
|
2017-02-16 16:56:32 -05:00
|
|
|
if message['content'] is None:
|
|
|
|
return
|
|
|
|
|
|
|
|
if is_private_message or is_mentioned:
|
2017-01-14 13:58:03 -05:00
|
|
|
message_handler.handle_message(
|
|
|
|
message=message,
|
2017-06-11 09:03:39 -04:00
|
|
|
bot_handler=restricted_client,
|
2017-01-14 13:58:03 -05:00
|
|
|
state_handler=state_handler
|
2017-01-24 00:34:26 -05:00
|
|
|
)
|
2017-01-14 13:58:03 -05:00
|
|
|
|
|
|
|
signal.signal(signal.SIGINT, exit_gracefully)
|
|
|
|
|
|
|
|
logging.info('starting message handling...')
|
|
|
|
client.call_on_each_message(handle_message)
|