botserver: Make handle_bot logic more concise.

This commit is contained in:
Robert Hönig 2018-05-29 10:03:59 +02:00
parent e6ef34a964
commit 3859bef05f

View file

@ -104,33 +104,32 @@ bots_config = {} # type: Dict[str, Dict[str, str]]
@app.route('/', methods=['POST']) @app.route('/', methods=['POST'])
def handle_bot() -> Union[str, BadRequest]: def handle_bot() -> Union[str, BadRequest]:
event = request.get_json(force=True) event = request.get_json(force=True)
bot = None
for bot_name, config in bots_config.items(): for bot_name, config in bots_config.items():
if config['email'] == event['bot_email']: if config['email'] == event['bot_email']:
bot = bot_name bot = bot_name
if bot is None: break
else:
return BadRequest("Cannot find a bot with email {} in the bot server " return BadRequest("Cannot find a bot with email {} in the bot server "
"configuration file. Do the emails in your flaskbotrc " "configuration file. Do the emails in your flaskbotrc "
"match the bot emails on the server?".format(event['bot_email'])) "match the bot emails on the server?".format(event['bot_email']))
else: lib_module = app.config.get("BOTS_LIB_MODULES", {})[bot]
lib_module = app.config.get("BOTS_LIB_MODULES", {})[bot] bot_handler = app.config.get("BOT_HANDLERS", {})[bot]
bot_handler = app.config.get("BOT_HANDLERS", {})[bot] message_handler = app.config.get("MESSAGE_HANDLERS", {})[bot]
message_handler = app.config.get("MESSAGE_HANDLERS", {})[bot] is_mentioned = event['trigger'] == "mention"
is_mentioned = event['trigger'] == "mention" is_private_message = event['trigger'] == "private_message"
is_private_message = event['trigger'] == "private_message" message = event["message"]
message = event["message"] message['full_content'] = message['content']
message['full_content'] = message['content'] # Strip at-mention botname from the message
# Strip at-mention botname from the message if is_mentioned:
if is_mentioned: # message['content'] will be None when the bot's @-mention is not at the beginning.
# message['content'] will be None when the bot's @-mention is not at the beginning. # In that case, the message shall not be handled.
# In that case, the message shall not be handled. message['content'] = lib.extract_query_without_mention(message=message, client=bot_handler)
message['content'] = lib.extract_query_without_mention(message=message, client=bot_handler) if message['content'] is None:
if message['content'] is None: return json.dumps("")
return json.dumps("")
if is_private_message or is_mentioned: if is_private_message or is_mentioned:
message_handler.handle_message(message=message, bot_handler=bot_handler) message_handler.handle_message(message=message, bot_handler=bot_handler)
return json.dumps("") return json.dumps("")
def main() -> None: def main() -> None: