Пример #1
0
 def test_extract_query_without_mention(self):
     client = FakeClient()
     handler = ExternalBotHandler(
         client=client, root_dir=None, bot_details=None, bot_config_file=None
     )
     message = {"content": "@**Alice** Hello World"}
     self.assertEqual(extract_query_without_mention(message, handler), "Hello World")
     message = {"content": "@**Alice|alice** Hello World"}
     self.assertEqual(extract_query_without_mention(message, handler), "Hello World")
     message = {"content": "@**Alice Renamed|alice** Hello World"}
     self.assertEqual(extract_query_without_mention(message, handler), "Hello World")
     message = {"content": "Not at start @**Alice|alice** Hello World"}
     self.assertEqual(extract_query_without_mention(message, handler), None)
Пример #2
0
    def consume(self, event: Mapping[str, Any]) -> None:
        user_profile_id = event['user_profile_id']
        user_profile = get_user_profile_by_id(user_profile_id)

        message = cast(Dict[str, Any], event['message'])

        # TODO: Do we actually want to allow multiple Services per bot user?
        services = get_bot_services(user_profile_id)
        for service in services:
            bot_handler = get_bot_handler(str(service.name))
            if bot_handler is None:
                logging.error(
                    "Error: User %s has bot with invalid embedded bot service %s"
                    % (user_profile_id, service.name))
                continue
            try:
                if hasattr(bot_handler, 'initialize'):
                    bot_handler.initialize(
                        self.get_bot_api_client(user_profile))
                if event['trigger'] == 'mention':
                    message['content'] = extract_query_without_mention(
                        message=message,
                        client=self.get_bot_api_client(user_profile),
                    )
                    assert message['content'] is not None
                bot_handler.handle_message(
                    message=message,
                    bot_handler=self.get_bot_api_client(user_profile))
            except EmbeddedBotQuitException as e:
                logging.warning(str(e))
Пример #3
0
    def consume(self, event):
        # type: (Mapping[str, Any]) -> None
        user_profile_id = event['user_profile_id']
        user_profile = get_user_profile_by_id(user_profile_id)

        message = cast(Dict[str, Any], event['message'])

        # TODO: Do we actually want to allow multiple Services per bot user?
        services = get_bot_services(user_profile_id)
        for service in services:
            bot_handler = get_bot_handler(str(service.name))
            if bot_handler is None:
                logging.error(
                    "Error: User %s has bot with invalid embedded bot service %s"
                    % (user_profile_id, service.name))
                continue
            if event['trigger'] == 'mention':
                message['content'] = extract_query_without_mention(
                    message=message,
                    client=self.get_bot_api_client(user_profile),
                )
                if message['content'] is None:
                    return
            bot_handler.handle_message(
                message=message,
                bot_handler=self.get_bot_api_client(user_profile))
Пример #4
0
    def consume(self, event: Mapping[str, Any]) -> None:
        user_profile_id = event['user_profile_id']
        user_profile = get_user_profile_by_id(user_profile_id)

        message = cast(Dict[str, Any], event['message'])

        # TODO: Do we actually want to allow multiple Services per bot user?
        services = get_bot_services(user_profile_id)
        for service in services:
            bot_handler = get_bot_handler(str(service.name))
            if bot_handler is None:
                logging.error("Error: User %s has bot with invalid embedded bot service %s" % (
                    user_profile_id, service.name))
                continue
            try:
                if hasattr(bot_handler, 'initialize'):
                    bot_handler.initialize(self.get_bot_api_client(user_profile))
                if event['trigger'] == 'mention':
                    message['content'] = extract_query_without_mention(
                        message=message,
                        client=self.get_bot_api_client(user_profile),
                    )
                    assert message['content'] is not None
                bot_handler.handle_message(
                    message=message,
                    bot_handler=self.get_bot_api_client(user_profile)
                )
            except EmbeddedBotQuitException as e:
                logging.warning(str(e))
Пример #5
0
    def consume(self, event: Mapping[str, Any]) -> None:
        user_profile_id = event["user_profile_id"]
        user_profile = get_user_profile_by_id(user_profile_id)

        message: Dict[str, Any] = event["message"]

        # TODO: Do we actually want to allow multiple Services per bot user?
        services = get_bot_services(user_profile_id)
        for service in services:
            bot_handler = get_bot_handler(str(service.name))
            if bot_handler is None:
                logging.error(
                    "Error: User %s has bot with invalid embedded bot service %s",
                    user_profile_id,
                    service.name,
                )
                continue
            try:
                if hasattr(bot_handler, "initialize"):
                    bot_handler.initialize(
                        self.get_bot_api_client(user_profile))
                if event["trigger"] == "mention":
                    message["content"] = extract_query_without_mention(
                        message=message,
                        client=cast(ExternalBotHandler,
                                    self.get_bot_api_client(user_profile)),
                    )
                    assert message["content"] is not None
                bot_handler.handle_message(
                    message=message,
                    bot_handler=self.get_bot_api_client(user_profile),
                )
            except EmbeddedBotQuitException as e:
                logging.warning(str(e))
Пример #6
0
def handle_bot() -> str:
    event = request.get_json(force=True)
    for bot_name, config in bots_config.items():
        if config['email'] == event['bot_email']:
            bot = bot_name
            bot_config = config
            break
    else:
        raise BadRequest("Cannot find a bot with email {} in the Botserver "
                         "configuration file. Do the emails in your botserverrc "
                         "match the bot emails on the server?".format(event['bot_email']))
    if bot_config['token'] != event['token']:
        raise Unauthorized("Request token does not match token found for bot {} in the "
                           "Botserver configuration file. Do the outgoing webhooks in "
                           "Zulip point to the right Botserver?".format(event['bot_email']))
    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("")
Пример #7
0
def handle_bot() -> Union[str, BadRequest, Unauthorized]:
    event = request.get_json(force=True)
    for bot_name, config in bots_config.items():
        if config['email'] == event['bot_email']:
            bot = bot_name
            bot_config = config
            break
    else:
        return BadRequest("Cannot find a bot with email {} in the Botserver "
                          "configuration file. Do the emails in your botserverrc "
                          "match the bot emails on the server?".format(event['bot_email']))
    if bot_config['token'] != event['token']:
        return Unauthorized("Request token does not match token found for bot {} in the "
                            "Botserver configuration file. Do the outgoing webhooks in "
                            "Zulip point to the right Botserver?".format(event['bot_email']))
    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("")
Пример #8
0
 def test_message(name: str, message: str,
                  expected_return: Optional[str]) -> None:
     mock_client = mock.MagicMock()
     mock_client.full_name = name
     mock_message = {'content': message}
     self.assertEqual(
         expected_return,
         extract_query_without_mention(mock_message, mock_client))
Пример #9
0
 def test_message(name: str, message: str, expected_return: Optional[str]) -> None:
     mock_client = mock.MagicMock()
     mock_client.full_name = name
     mock_message = {'content': message}
     self.assertEqual(expected_return, extract_query_without_mention(mock_message, mock_client))