From a06fb98f211777a78ceae4bb23f2d50234c645b1 Mon Sep 17 00:00:00 2001 From: dkvasov Date: Thu, 17 May 2018 17:35:09 +0300 Subject: [PATCH] zulip_bots and zulip_botserver: Extract common function. --- zulip_bots/zulip_bots/lib.py | 35 +++++++++++------------ zulip_botserver/tests/test_server.py | 4 +-- zulip_botserver/zulip_botserver/server.py | 16 ++++------- 3 files changed, 23 insertions(+), 32 deletions(-) diff --git a/zulip_bots/zulip_bots/lib.py b/zulip_bots/zulip_bots/lib.py index 0a9e1a8..6c8c593 100644 --- a/zulip_bots/zulip_bots/lib.py +++ b/zulip_bots/zulip_bots/lib.py @@ -7,7 +7,6 @@ import sys import time -from mypy_extensions import NoReturn from typing import Any, Optional, List, Dict, IO, Text from zulip import Client, ZulipError @@ -48,7 +47,7 @@ class RateLimit(object): else: return True - def show_error_and_exit(self) -> NoReturn: + def show_error_and_exit(self) -> None: logging.error(self.error_message) sys.exit(1) @@ -131,10 +130,9 @@ class ExternalBotHandler(object): return self._storage def send_message(self, message: (Dict[str, Any])) -> Dict[str, Any]: - if self._rate_limit.is_legal(): - return self._client.send_message(message) - else: + if not self._rate_limit.is_legal(): self._rate_limit.show_error_and_exit() + return self._client.send_message(message) def send_reply(self, message: Dict[str, Any], response: str) -> Dict[str, Any]: if message['type'] == 'private': @@ -152,10 +150,9 @@ class ExternalBotHandler(object): )) def update_message(self, message: Dict[str, Any]) -> Dict[str, Any]: - if self._rate_limit.is_legal(): - return self._client.update_message(message) - else: + if not self._rate_limit.is_legal(): self._rate_limit.show_error_and_exit() + return self._client.update_message(message) def get_config_info(self, bot_name: str, optional: Optional[bool]=False) -> Dict[str, Any]: if self._bot_config_parser is not None: @@ -244,6 +241,16 @@ def display_config_file_errors(error_msg: str, config_file: str) -> None: print('\nMore details here:\n\n{}\n'.format(error_msg)) +def prepare_message_handler(bot: str, bot_handler: ExternalBotHandler, bot_lib_module: Any) -> Any: + message_handler = bot_lib_module.handler_class() + if hasattr(message_handler, 'validate_config'): + config_data = bot_handler.get_config_info(bot) + bot_lib_module.handler_class.validate_config(config_data) + if hasattr(message_handler, 'initialize'): + message_handler.initialize(bot_handler=bot_handler) + return message_handler + + def run_message_handler_for_bot( lib_module: Any, quiet: bool, @@ -277,17 +284,7 @@ def run_message_handler_for_bot( bot_dir = os.path.dirname(lib_module.__file__) restricted_client = ExternalBotHandler(client, bot_dir, bot_details, bot_config_file) - message_handler = lib_module.handler_class() - if hasattr(message_handler, 'validate_config'): - config_data = restricted_client.get_config_info(bot_name) - try: - lib_module.handler_class.validate_config(config_data) - except ConfigValidationError as e: - print("There was a problem validating your config file:\n\n{}".format(e)) - sys.exit(1) - - if hasattr(message_handler, 'initialize'): - message_handler.initialize(bot_handler=restricted_client) + message_handler = prepare_message_handler(bot_name, restricted_client, lib_module) if not quiet: print("Running {} Bot:".format(bot_details['name'])) diff --git a/zulip_botserver/tests/test_server.py b/zulip_botserver/tests/test_server.py index ce4d6c7..38d51c2 100644 --- a/zulip_botserver/tests/test_server.py +++ b/zulip_botserver/tests/test_server.py @@ -14,7 +14,7 @@ class BotServerTests(BotServerTestCase): def handler_class(self) -> Any: return BotServerTests.MockMessageHandler() - @mock.patch('zulip_botserver.server.ExternalBotHandler') + @mock.patch('zulip_bots.lib.ExternalBotHandler') def test_successful_request(self, mock_ExternalBotHandler: mock.Mock) -> None: available_bots = ['helloworld'] bots_config = { @@ -28,7 +28,7 @@ class BotServerTests(BotServerTestCase): bots_config=bots_config, check_success=True) - @mock.patch('zulip_botserver.server.ExternalBotHandler') + @mock.patch('zulip_bots.lib.ExternalBotHandler') def test_successful_request_from_two_bots(self, mock_ExternalBotHandler: mock.Mock) -> None: available_bots = ['helloworld', 'help'] bots_config = { diff --git a/zulip_botserver/zulip_botserver/server.py b/zulip_botserver/zulip_botserver/server.py index f85a779..14d9f8b 100644 --- a/zulip_botserver/zulip_botserver/server.py +++ b/zulip_botserver/zulip_botserver/server.py @@ -9,7 +9,7 @@ from typing import Any, Dict, Union, List, Optional from werkzeug.exceptions import BadRequest from zulip import Client -from zulip_bots.lib import ExternalBotHandler +from zulip_bots import lib from zulip_botserver.input_parameters import parse_args @@ -65,14 +65,14 @@ def load_bot_handlers( available_bots: List[str], bots_config: Dict[str, Dict[str, str]], third_party_bot_conf: Optional[configparser.ConfigParser]=None, -) -> Dict[str, ExternalBotHandler]: +) -> Dict[str, lib.ExternalBotHandler]: bot_handlers = {} for bot in available_bots: client = Client(email=bots_config[bot]["email"], api_key=bots_config[bot]["key"], site=bots_config[bot]["site"]) bot_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bots', bot) - bot_handler = ExternalBotHandler( + bot_handler = lib.ExternalBotHandler( client, bot_dir, bot_details={}, @@ -86,19 +86,13 @@ def load_bot_handlers( def init_message_handlers( available_bots: List[str], bots_lib_modules: Dict[str, Any], - bot_handlers: Dict[str, ExternalBotHandler], + bot_handlers: Dict[str, lib.ExternalBotHandler], ) -> Dict[str, Any]: message_handlers = {} for bot in available_bots: bot_lib_module = bots_lib_modules[bot] bot_handler = bot_handlers[bot] - message_handler = bot_lib_module.handler_class() - if hasattr(message_handler, 'validate_config'): - config_data = bot_handler.get_config_info(bot) - bot_lib_module.handler_class.validate_config(config_data) - - if hasattr(message_handler, 'initialize'): - message_handler.initialize(bot_handler=bot_handler) + message_handler = lib.prepare_message_handler(bot, bot_handler, bot_lib_module) message_handlers[bot] = message_handler return message_handlers