From 3859bef05fd333c61589d7a5c7542551dbb0e73c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20H=C3=B6nig?= Date: Tue, 29 May 2018 10:03:59 +0200 Subject: [PATCH] botserver: Make handle_bot logic more concise. --- zulip_botserver/zulip_botserver/server.py | 39 +++++++++++------------ 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/zulip_botserver/zulip_botserver/server.py b/zulip_botserver/zulip_botserver/server.py index 680de18..34ae537 100644 --- a/zulip_botserver/zulip_botserver/server.py +++ b/zulip_botserver/zulip_botserver/server.py @@ -104,33 +104,32 @@ bots_config = {} # type: Dict[str, Dict[str, str]] @app.route('/', methods=['POST']) def handle_bot() -> Union[str, BadRequest]: event = request.get_json(force=True) - bot = None for bot_name, config in bots_config.items(): if config['email'] == event['bot_email']: bot = bot_name - if bot is None: + break + else: return BadRequest("Cannot find a bot with email {} in the bot server " "configuration file. Do the emails in your flaskbotrc " "match the bot emails on the server?".format(event['bot_email'])) - else: - lib_module = app.config.get("BOTS_LIB_MODULES", {})[bot] - bot_handler = app.config.get("BOT_HANDLERS", {})[bot] - message_handler = app.config.get("MESSAGE_HANDLERS", {})[bot] - is_mentioned = event['trigger'] == "mention" - is_private_message = event['trigger'] == "private_message" - message = event["message"] - message['full_content'] = message['content'] - # Strip at-mention botname from the message - if is_mentioned: - # 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'] = lib.extract_query_without_mention(message=message, client=bot_handler) - if message['content'] is None: - return json.dumps("") + lib_module = app.config.get("BOTS_LIB_MODULES", {})[bot] + bot_handler = app.config.get("BOT_HANDLERS", {})[bot] + message_handler = app.config.get("MESSAGE_HANDLERS", {})[bot] + is_mentioned = event['trigger'] == "mention" + is_private_message = event['trigger'] == "private_message" + message = event["message"] + message['full_content'] = message['content'] + # Strip at-mention botname from the message + if is_mentioned: + # 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'] = lib.extract_query_without_mention(message=message, client=bot_handler) + if message['content'] is None: + return json.dumps("") - if is_private_message or is_mentioned: - message_handler.handle_message(message=message, bot_handler=bot_handler) - return json.dumps("") + if is_private_message or is_mentioned: + message_handler.handle_message(message=message, bot_handler=bot_handler) + return json.dumps("") def main() -> None: