2017-01-14 13:58:03 -05:00
|
|
|
from __future__ import print_function
|
|
|
|
|
2017-10-24 07:15:51 -04:00
|
|
|
import json
|
2017-01-14 13:58:03 -05:00
|
|
|
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
|
|
|
|
2018-01-06 04:43:54 -05:00
|
|
|
import configparser
|
2017-06-10 07:56:00 -04:00
|
|
|
|
2017-07-23 14:26:40 -04:00
|
|
|
from contextlib import contextmanager
|
|
|
|
|
2017-05-26 00:58:19 -04:00
|
|
|
if False:
|
|
|
|
from mypy_extensions import NoReturn
|
2017-11-01 08:26:20 -04:00
|
|
|
from typing import Any, Optional, List, Dict, IO, Text, Set
|
2017-05-26 00:58:19 -04:00
|
|
|
from types import ModuleType
|
|
|
|
|
2017-11-21 17:21:04 -05:00
|
|
|
from zulip import Client, ZulipError
|
2017-01-14 13:58:03 -05:00
|
|
|
|
2017-11-27 16:45:05 -05:00
|
|
|
class NoBotConfigException(Exception):
|
|
|
|
pass
|
|
|
|
|
2017-01-14 13:58:03 -05:00
|
|
|
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)
|
|
|
|
|
2017-08-15 18:15:17 -04:00
|
|
|
def get_bots_directory_path():
|
|
|
|
# type: () -> str
|
|
|
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
return os.path.join(current_dir, 'bots')
|
|
|
|
|
2017-01-14 13:58:03 -05:00
|
|
|
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-11-01 08:26:20 -04:00
|
|
|
class StateHandlerError(Exception):
|
|
|
|
pass
|
|
|
|
|
2017-10-23 06:17:46 -04:00
|
|
|
class StateHandler(object):
|
2017-11-01 08:26:20 -04:00
|
|
|
def __init__(self, client):
|
|
|
|
# type: (Client) -> None
|
|
|
|
self._client = client
|
2017-11-01 08:04:54 -04:00
|
|
|
self.marshal = lambda obj: json.dumps(obj)
|
|
|
|
self.demarshal = lambda obj: json.loads(obj)
|
2017-11-13 03:57:41 -05:00
|
|
|
response = self._client.get_storage()
|
2017-11-01 08:26:20 -04:00
|
|
|
if response['result'] == 'success':
|
2017-11-28 14:34:25 -05:00
|
|
|
self.state_ = response['storage']
|
2017-11-01 08:26:20 -04:00
|
|
|
else:
|
|
|
|
raise StateHandlerError("Error initializing state: {}".format(str(response)))
|
2017-10-23 06:17:46 -04:00
|
|
|
|
2017-10-24 07:15:51 -04:00
|
|
|
def put(self, key, value):
|
2017-12-11 11:35:03 -05:00
|
|
|
# type: (Text, Any) -> None
|
2017-10-24 07:15:51 -04:00
|
|
|
self.state_[key] = self.marshal(value)
|
2017-11-28 14:34:25 -05:00
|
|
|
response = self._client.update_storage({'storage': {key: self.state_[key]}})
|
2017-11-24 13:37:13 -05:00
|
|
|
if response['result'] != 'success':
|
|
|
|
raise StateHandlerError("Error updating state: {}".format(str(response)))
|
2017-10-23 06:17:46 -04:00
|
|
|
|
2017-10-24 07:15:51 -04:00
|
|
|
def get(self, key):
|
2017-12-11 11:35:03 -05:00
|
|
|
# type: (Text) -> Any
|
2017-10-24 07:15:51 -04:00
|
|
|
return self.demarshal(self.state_[key])
|
2017-10-23 06:17:46 -04:00
|
|
|
|
2017-10-24 07:15:51 -04:00
|
|
|
def contains(self, key):
|
|
|
|
# type: (Text) -> bool
|
|
|
|
return key in self.state_
|
2017-10-23 06:17:46 -04:00
|
|
|
|
2017-06-07 22:49:42 -04:00
|
|
|
class ExternalBotHandler(object):
|
2017-11-27 16:45:05 -05:00
|
|
|
def __init__(self, client, root_dir, bot_details, bot_config_file):
|
|
|
|
# type: (Client, str, Dict[str, Any], str) -> None
|
2017-01-14 13:58:03 -05:00
|
|
|
# Only expose a subset of our Client's functionality
|
2017-11-21 17:21:04 -05:00
|
|
|
try:
|
|
|
|
user_profile = client.get_profile()
|
|
|
|
except ZulipError as e:
|
|
|
|
print('''
|
|
|
|
ERROR: {}
|
|
|
|
|
|
|
|
Have you not started the server?
|
|
|
|
Or did you mis-specify the URL?
|
|
|
|
'''.format(e))
|
|
|
|
sys.exit(1)
|
|
|
|
|
2017-11-22 11:42:07 -05:00
|
|
|
if user_profile.get('result') == 'error':
|
|
|
|
msg = user_profile.get('msg', 'unknown')
|
|
|
|
print('''
|
|
|
|
ERROR: {}
|
|
|
|
'''.format(msg))
|
|
|
|
sys.exit(1)
|
|
|
|
|
2017-01-14 13:58:03 -05:00
|
|
|
self._rate_limit = RateLimit(20, 5)
|
|
|
|
self._client = client
|
2017-07-25 10:04:38 -04:00
|
|
|
self._root_dir = root_dir
|
2017-11-13 05:49:23 -05:00
|
|
|
self.bot_details = bot_details
|
2017-11-27 16:45:05 -05:00
|
|
|
self.bot_config_file = bot_config_file
|
2017-11-24 13:37:13 -05:00
|
|
|
self._storage = StateHandler(client)
|
2017-01-14 13:58:03 -05:00
|
|
|
try:
|
2017-08-18 07:29:55 -04:00
|
|
|
self.user_id = user_profile['user_id']
|
2017-01-14 13:58:03 -05:00
|
|
|
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-11-13 05:49:23 -05:00
|
|
|
@property
|
|
|
|
def storage(self):
|
|
|
|
# type: () -> StateHandler
|
|
|
|
return self._storage
|
|
|
|
|
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]
|
2017-07-18 13:59:55 -04:00
|
|
|
if message['type'] == 'private':
|
|
|
|
return self.send_message(dict(
|
|
|
|
type='private',
|
|
|
|
to=[x['email'] for x in message['display_recipient'] if self.email != x['email']],
|
|
|
|
content=response,
|
|
|
|
))
|
|
|
|
else:
|
|
|
|
return self.send_message(dict(
|
|
|
|
type='stream',
|
|
|
|
to=message['display_recipient'],
|
|
|
|
subject=message['subject'],
|
|
|
|
content=response,
|
|
|
|
))
|
2017-06-18 14:42:28 -04:00
|
|
|
|
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-11-06 09:13:24 -05:00
|
|
|
def get_config_info(self, bot_name, optional=False):
|
|
|
|
# type: (str, Optional[bool]) -> Dict[str, Any]
|
2017-11-27 16:45:05 -05:00
|
|
|
|
|
|
|
if self.bot_config_file is None:
|
2017-06-17 08:12:58 -04:00
|
|
|
if optional:
|
|
|
|
return dict()
|
2017-11-27 16:45:05 -05:00
|
|
|
|
|
|
|
# Well written bots should catch this exception
|
|
|
|
# and provide nice error messages with instructions
|
|
|
|
# on setting up the configuration specfic to this bot.
|
|
|
|
# And then `run.py` should also catch exceptions on how
|
|
|
|
# to specify the file in the command line.
|
|
|
|
raise NoBotConfigException(bot_name)
|
|
|
|
|
|
|
|
if bot_name not in self.bot_config_file:
|
|
|
|
print('''
|
|
|
|
WARNING!
|
|
|
|
|
|
|
|
{} does not adhere to the
|
|
|
|
file naming convention, and it could be a
|
|
|
|
sign that you passed in the
|
|
|
|
wrong third-party configuration file.
|
|
|
|
|
|
|
|
The suggested name is {}.conf
|
|
|
|
|
|
|
|
We will proceed anyway.
|
|
|
|
'''.format(self.bot_config_file, bot_name))
|
|
|
|
|
|
|
|
# We expect the caller to pass in None if the user does
|
|
|
|
# not specify a bot_config_file. If they pass in a bogus
|
|
|
|
# filename, we'll let an IOError happen here. Callers
|
|
|
|
# like `run.py` will do the command line parsing and checking
|
|
|
|
# for the existence of the file.
|
|
|
|
config = configparser.ConfigParser()
|
|
|
|
with open(self.bot_config_file) as conf:
|
|
|
|
try:
|
|
|
|
config.readfp(conf) # type: ignore # readfp->read_file in python 3, so not in stubs
|
|
|
|
except configparser.Error as e:
|
|
|
|
display_config_file_errors(str(e), self.bot_config_file)
|
|
|
|
sys.exit(1)
|
|
|
|
|
2017-11-06 09:13:24 -05:00
|
|
|
return dict(config.items(bot_name))
|
2017-06-18 14:42:28 -04:00
|
|
|
|
2017-07-25 10:04:38 -04:00
|
|
|
def open(self, filepath):
|
2017-10-10 02:23:01 -04:00
|
|
|
# type: (str) -> IO[str]
|
2017-07-25 10:04:38 -04:00
|
|
|
filepath = os.path.normpath(filepath)
|
|
|
|
abs_filepath = os.path.join(self._root_dir, filepath)
|
|
|
|
if abs_filepath.startswith(self._root_dir):
|
|
|
|
return open(abs_filepath)
|
|
|
|
else:
|
|
|
|
raise PermissionError("Cannot open file \"{}\". Bots may only access "
|
|
|
|
"files in their local directory.".format(abs_filepath))
|
|
|
|
|
2017-12-30 15:40:24 -05:00
|
|
|
def quit(self, message = ""):
|
|
|
|
# type: (str) -> None
|
|
|
|
sys.exit(message)
|
|
|
|
|
2017-08-17 13:53:36 -04:00
|
|
|
def extract_query_without_mention(message, client):
|
2017-12-22 14:15:08 -05:00
|
|
|
# type: (Dict[str, Any], ExternalBotHandler) -> Optional[str]
|
2017-08-17 13:53:36 -04:00
|
|
|
"""
|
|
|
|
If the bot is the first @mention in the message, then this function returns
|
2017-11-10 18:58:57 -05:00
|
|
|
the stripped message with the bot's @mention removed. Otherwise, it returns None.
|
2017-08-17 13:53:36 -04:00
|
|
|
"""
|
2017-11-10 18:58:57 -05:00
|
|
|
mention = '@**' + client.full_name + '**'
|
|
|
|
if not message['content'].startswith(mention):
|
2017-08-17 13:53:36 -04:00
|
|
|
return None
|
2017-11-10 18:58:57 -05:00
|
|
|
return message['content'][len(mention):].lstrip()
|
2017-08-17 13:53:36 -04:00
|
|
|
|
2017-08-18 12:41:37 -04:00
|
|
|
def is_private_message_from_another_user(message_dict, current_user_id):
|
|
|
|
# type: (Dict[str, Any], int) -> bool
|
|
|
|
"""
|
|
|
|
Checks whether a message dict represents a PM from another user.
|
|
|
|
|
|
|
|
This function is used by the embedded bot system in the
|
|
|
|
zulip/zulip project, so refactor with care. See the comments in
|
|
|
|
extract_query_without_mention.
|
|
|
|
"""
|
|
|
|
if message_dict['type'] == 'private':
|
|
|
|
return current_user_id != message_dict['sender_id']
|
2017-08-17 13:53:36 -04:00
|
|
|
return False
|
|
|
|
|
2017-11-27 17:47:59 -05:00
|
|
|
def display_config_file_errors(error_msg, config_file):
|
|
|
|
# type: (str, str) -> None
|
|
|
|
file_contents = open(config_file).read()
|
|
|
|
print('\nERROR: {} seems to be broken:\n\n{}'.format(config_file, file_contents))
|
|
|
|
print('\nMore details here:\n\n{}\n'.format(error_msg))
|
|
|
|
|
2017-11-27 16:45:05 -05:00
|
|
|
def run_message_handler_for_bot(lib_module, quiet, config_file, bot_config_file, bot_name):
|
|
|
|
# type: (Any, bool, str, str, str) -> Any
|
2017-05-26 00:58:19 -04:00
|
|
|
#
|
|
|
|
# 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-11-13 05:49:23 -05:00
|
|
|
# Set default bot_details, then override from class, if provided
|
|
|
|
bot_details = {
|
|
|
|
'name': bot_name.capitalize(),
|
|
|
|
'description': "",
|
|
|
|
}
|
|
|
|
bot_details.update(getattr(lib_module.handler_class, 'META', {}))
|
2017-01-14 13:58:03 -05:00
|
|
|
# Make sure you set up your ~/.zuliprc
|
2017-11-21 14:26:12 -05:00
|
|
|
|
|
|
|
client_name = "Zulip{}Bot".format(bot_name.capitalize())
|
2017-11-21 14:54:59 -05:00
|
|
|
|
|
|
|
try:
|
|
|
|
client = Client(config_file=config_file, client=client_name)
|
|
|
|
except configparser.Error as e:
|
2017-11-27 17:47:59 -05:00
|
|
|
display_config_file_errors(str(e), config_file)
|
2017-11-21 14:54:59 -05:00
|
|
|
sys.exit(1)
|
2017-11-21 14:26:12 -05:00
|
|
|
|
2017-07-25 10:04:38 -04:00
|
|
|
bot_dir = os.path.dirname(lib_module.__file__)
|
2017-11-27 16:45:05 -05:00
|
|
|
restricted_client = ExternalBotHandler(client, bot_dir, bot_details, bot_config_file)
|
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
|
|
|
|
|
|
|
if not quiet:
|
2017-09-25 15:50:26 -04:00
|
|
|
print("Running {} Bot:".format(bot_details['name']))
|
|
|
|
if bot_details['description'] != "":
|
|
|
|
print("\n\t{}".format(bot_details['description']))
|
2017-01-14 13:58:03 -05:00
|
|
|
print(message_handler.usage())
|
|
|
|
|
2017-10-20 19:35:21 -04:00
|
|
|
def handle_message(message, flags):
|
2017-10-10 02:23:01 -04:00
|
|
|
# type: (Dict[str, Any], List[str]) -> None
|
2017-01-14 13:58:03 -05:00
|
|
|
logging.info('waiting for next message')
|
2017-10-20 19:35:21 -04:00
|
|
|
# `mentioned` will be in `flags` if the bot is mentioned at ANY position
|
|
|
|
# (not necessarily the first @mention in the message).
|
|
|
|
is_mentioned = 'mentioned' in flags
|
2017-08-18 12:41:37 -04:00
|
|
|
is_private_message = is_private_message_from_another_user(message, restricted_client.user_id)
|
2017-02-16 16:56:32 -05:00
|
|
|
|
2017-12-25 13:14:38 -05:00
|
|
|
# Provide bots with a way to access the full, unstripped message
|
|
|
|
message['full_content'] = message['content']
|
2017-02-16 16:56:32 -05:00
|
|
|
# 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-10-23 06:17:46 -04:00
|
|
|
bot_handler=restricted_client
|
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...')
|
2017-10-20 19:35:21 -04:00
|
|
|
|
|
|
|
def event_callback(event):
|
2017-10-10 02:23:01 -04:00
|
|
|
# type: (Dict[str, Any]) -> None
|
2017-10-20 19:35:21 -04:00
|
|
|
if event['type'] == 'message':
|
|
|
|
handle_message(event['message'], event['flags'])
|
|
|
|
|
|
|
|
client.call_on_each_event(event_callback, ['message'])
|