예제 #1
0
 def test_save_channel_config(self):
     ChatDataProcessor.save_channel_config({"connector_type": "slack",
                                            "config": {
                                                "bot_user_oAuth_token": "xoxb-801939352912-801478018484-v3zq6MYNu62oSs8vammWOY8K",
                                                "slack_signing_secret": "79f036b9894eef17c064213b90d1042b"}},
                                           "test",
                                           "test")
예제 #2
0
    def test_get_channel_config_slack(self):
        slack = ChatDataProcessor.get_channel_config("slack", "test")
        assert slack.get("connector_type") == "slack"
        assert str(slack["config"].get("bot_user_oAuth_token")).__contains__("***")
        assert str(slack["config"].get("slack_signing_secret")).__contains__("***")

        slack = ChatDataProcessor.get_channel_config("slack", "test", mask_characters=False)
        assert slack.get("connector_type") == "slack"
        assert not str(slack["config"].get("bot_user_oAuth_token")).__contains__("***")
        assert not str(slack["config"].get("slack_signing_secret")).__contains__("***")
예제 #3
0
 def test_update_channel_config(self):
     ChatDataProcessor.save_channel_config({"connector_type": "slack",
                                            "config": {
                                                "bot_user_oAuth_token": "Test-801478018484-v3zq6MYNu62oSs8vammWOY8K",
                                                "slack_signing_secret": "79f036b9894eef17c064213b90d1042b"}},
                                           "test",
                                           "test")
     slack = ChatDataProcessor.get_channel_config("slack", "test", mask_characters=False)
     assert slack.get("connector_type") == "slack"
     assert str(slack["config"].get("bot_user_oAuth_token")).startswith("Test")
     assert not str(slack["config"].get("slack_signing_secret")).__contains__("***")
예제 #4
0
    def test_list_channel_config(self):
        channels = list(ChatDataProcessor.list_channel_config("test"))
        slack = channels[0]
        assert channels.__len__() == 1
        assert slack.get("connector_type") == "slack"
        assert str(slack["config"].get("bot_user_oAuth_token")).__contains__("***")
        assert str(slack["config"].get("slack_signing_secret")).__contains__("***")

        channels = list(ChatDataProcessor.list_channel_config("test", mask_characters=False))
        slack = channels[0]
        assert channels.__len__() == 1
        assert slack.get("connector_type") == "slack"
        assert not str(slack["config"].get("bot_user_oAuth_token")).__contains__("***")
        assert not str(slack["config"].get("slack_signing_secret")).__contains__("***")
예제 #5
0
    async def post(self, bot: str, token: str):
        super().authenticate_channel(token, bot, self.request)
        telegram = ChatDataProcessor.get_channel_config("telegram", bot, mask_characters=False)
        out_channel = TelegramOutput(telegram['config']['access_token'])
        request_dict = json_decode(self.request.body)
        update = Update.de_json(request_dict)
        if not out_channel.get_me().username == telegram['config'].get("username_for_bot"):
            logger.debug("Invalid access token, check it matches Telegram")
            self.write("failed")
            return

        if self._is_button(update):
            msg = update.callback_query.message
            text = update.callback_query.data
        elif self._is_edited_message(update):
            msg = update.edited_message
            text = update.edited_message.text
        else:
            msg = update.message
            if self._is_user_message(msg):
                text = msg.text.replace("/bot", "")
            elif self._is_location(msg):
                text = '{{"lng":{0}, "lat":{1}}}'.format(
                    msg.location.longitude, msg.location.latitude
                )
            else:
                self.write("success")
                return
        sender_id = msg.chat.id
        metadata = {"out_channel": out_channel.name()}
        try:
            if text == (INTENT_MESSAGE_PREFIX + USER_INTENT_RESTART):
                await self.process_message(bot, UserMessage(
                        text,
                        out_channel,
                        sender_id,
                        input_channel=self.name(),
                        metadata=metadata,
                    ))
                await self.process_message(bot, UserMessage(
                        "/start",
                        out_channel,
                        sender_id,
                        input_channel=self.name(),
                        metadata=metadata,
                    ))
            else:
                await self.process_message(bot, UserMessage(
                        text,
                        out_channel,
                        sender_id,
                        input_channel=self.name(),
                        metadata=metadata,
                    ))
        except Exception as e:
            logger.error(f"Exception when trying to handle message.{e}")
            logger.debug(e, exc_info=True)
        self.write("success")
        return
예제 #6
0
    def test_save_channel_config_telegram(self):
        access_token = "xoxb-801939352912-801478018484-v3zq6MYNu62oSs8vammWOY8K"
        webhook = urlencode({'url': "https://[email protected]/api/bot/telegram/tests/test"}, quote_via=quote_plus)
        responses.add("GET",
                      json={'result': True},
                      url=f"{Utility.environment['channels']['telegram']['api']['url']}/bot{access_token}/setWebhook?{webhook}")

        def __mock_endpoint(*args):
            return f"https://[email protected]/api/bot/telegram/tests/test"

        with patch('kairon.shared.data.utils.DataUtility.get_channel_endpoint', __mock_endpoint):
            ChatDataProcessor.save_channel_config({"connector_type": "telegram",
                                               "config": {
                                                   "access_token": access_token,
                                                   "webhook_url": webhook,
                                                   "username_for_bot": "test"}},
                                              "test",
                                              "test")
예제 #7
0
    def test_save_channel_config_invalid(self):
        with pytest.raises(ValidationError, match="Invalid channel type custom"):
            ChatDataProcessor.save_channel_config({"connector_type": "custom",
                                                   "config": {
                                                       "bot_user_oAuth_token": "xoxb-801939352912-801478018484-v3zq6MYNu62oSs8vammWOY8K",
                                                       "slack_signing_secret": "79f036b9894eef17c064213b90d1042b"}},
                                                  "test",
                                                  "test")

        with pytest.raises(ValidationError,
                           match=escape("Missing ['bot_user_oAuth_token', 'slack_signing_secret'] all or any in config")):
            ChatDataProcessor.save_channel_config({"connector_type": "slack",
                                                   "config": {
                                                       "slack_signing_secret": "79f036b9894eef17c064213b90d1042b"}},
                                                  "test",
                                                  "test")

        with pytest.raises(ValidationError,
                           match=escape("Missing ['bot_user_oAuth_token', 'slack_signing_secret'] all or any in config")):
            ChatDataProcessor.save_channel_config({"connector_type": "slack",
                                                   "config": {
                                                       "bot_user_oAuth_token": "xoxb-801939352912-801478018484-v3zq6MYNu62oSs8vammWOY8K",
                                                   }},
                                                  "test",
                                                  "test")
예제 #8
0
    async def get(self, bot: str, token: str):
        super().authenticate_channel(token, bot, self.request)
        self.set_status(HTTPStatus.OK)
        messenger_conf = ChatDataProcessor.get_channel_config("messenger", bot, mask_characters=False)

        fb_verify = messenger_conf["config"]["verity_token"]

        if (self.request.query_arguments.get("hub.verify_token")[0]).decode() == fb_verify:
            hub_challenge = (self.request.query_arguments.get("hub.challenge")[0]).decode()
            self.write(html.escape(hub_challenge))
            return
        else:
            logger.warning(
                "Invalid fb verify token! Make sure this matches "
                "your webhook settings on the facebook app."
            )
            self.write(json.dumps({"status": "failure, invalid verify_token"}))
            return
예제 #9
0
    async def post(self, bot: str, token: str):
        super().authenticate_channel(token, bot, self.request)
        messenger_conf = ChatDataProcessor.get_channel_config("messenger", bot, mask_characters=False)

        fb_secret = messenger_conf["config"]["app_secret"]
        page_access_token = messenger_conf["config"]["page_access_token"]

        signature = self.request.headers.get("X-Hub-Signature") or ""
        if not self.validate_hub_signature(fb_secret, self.request.body, signature):
            logger.warning(
                "Wrong fb secret! Make sure this matches the "
                "secret in your facebook app settings"
            )
            self.write("not validated")
            return

        messenger = Messenger(page_access_token)

        metadata = self.get_metadata(self.request)
        await messenger.handle(json_decode(self.request.body), metadata, bot)
        self.write("success")
        return
예제 #10
0
    async def post(self, bot: str, token: str):
        super().authenticate_channel(token, bot, self.request)
        hangout = ChatDataProcessor.get_channel_config("hangouts", bot=bot, mask_characters=False)
        project_id = hangout['config']['project_id']
        request_data = json_decode(self.request.body)
        if project_id:
            token = self.request.headers.get("Authorization").replace("Bearer ", "")
            self._check_token(token, project_id)

        sender_id = self._extract_sender(request_data)
        room_name = self._extract_room(request_data)
        text = self._extract_message(request_data)
        if text is None:
            return response.text("OK")
        input_channel = self._extract_input_channel()

        collector = HangoutsOutput()

        try:
            await AgentProcessor.get_agent(bot).handle_message(UserMessage(
                    text,
                    collector,
                    sender_id,
                    input_channel=input_channel,
                    metadata={"room": room_name, "out_channel": collector.name()},
                ))
        except CancelledError:
            logger.error(
                "Message handling timed out for " "user message '{}'.".format(text)
            )
        except Exception as e:
            logger.exception(
                f"An exception occurred while handling user message: {e}, "
                f"text: {text}"
            )

        self.write(json_encode(collector.messages))
        return
예제 #11
0
파일: slack.py 프로젝트: udit-pandey/kairon
    async def post(self, bot: Text, token: Text):
        super().authenticate_channel(token, bot, self.request)
        content_type = self.request.headers.get("content-type")
        conversation_granularity = "sender"
        slack_config = ChatDataProcessor.get_channel_config("slack", bot=bot, mask_characters=False)
        slack_token = slack_config['config']['bot_user_oAuth_token']
        slack_signing_secret = slack_config['config']['slack_signing_secret']
        slack_channel = slack_config['config'].get('slack_channel')
        self.set_status(HTTPStatus.OK)
        if 'x-slack-retry-num' in self.request.headers:
            return
        if not self.is_request_from_slack_authentic(self.request, slack_signing_secret=slack_signing_secret):
            self.set_status(HTTPStatus.BAD_REQUEST)
            self.write("Message is not properly signed with a valid "
                       "X-Slack-Signature header")
            return
        # Slack API sends either a JSON-encoded or a URL-encoded body
        # depending on the content

        if content_type == "application/json":
            # if JSON-encoded message is received
            output = json_decode(self.request.body)
            event = output.get("event", {})
            user_message = event.get("text", "")
            sender_id = event.get("user", "")
            metadata = self.get_metadata(self.request)
            channel_id = metadata.get("out_channel")
            thread_id = metadata.get("thread_id")
            conversation_id = self._get_conversation_id(
                conversation_granularity, sender_id, channel_id, thread_id
            )

            if "challenge" in output:
                self.write(output.get("challenge"))
                return

            if not self._is_user_message(output):
                logger.debug(
                    "Received message from Slack which doesn't look like "
                    "a user message. Skipping message."
                )
                self.write("Bot message delivered.")
                return

            if not self._is_supported_channel(output, metadata, slack_channel):
                logger.warning(
                    f"Received message on unsupported "
                    f"channel: {metadata['out_channel']}"
                )
                self.write("channel not supported.")
                return
            await self.process_message(
                self.request,
                bot,
                text=self._sanitize_user_message(user_message, metadata["users"]),
                sender_id=conversation_id,
                metadata=metadata,
                slack_token=slack_token
            )
            return
        elif content_type == "application/x-www-form-urlencoded":
            # if URL-encoded message is received
            output = parse_qs(self.request.body)
            payload = json.loads(output["payload"][0])

            if self._is_interactive_message(payload):
                sender_id = payload["user"]["id"]
                text = self._get_interactive_response(payload["actions"][0])
                if text is not None:
                    metadata = self.get_metadata(self.request)
                    channel_id = metadata.get("out_channel")
                    thread_id = metadata.get("thread_id")
                    conversation_id = self._get_conversation_id(
                        conversation_granularity, sender_id, channel_id, thread_id
                    )
                    await self.process_message(
                        self.request, bot, text, conversation_id, metadata, slack_token=slack_token
                    )
                    return
                if payload["actions"][0]["type"] == "button":
                    # link buttons don't have "value", don't send their clicks to
                    # bot
                    self.write("User clicked link button")
                    return
            self.set_status(HTTPStatus.INTERNAL_SERVER_ERROR)
            self.write("The input message could not be processed.")
            return
        self.write("Bot message delivered.")
        return
예제 #12
0
user = AccountProcessor.get_complete_user_details("*****@*****.**")
bot = user['bots']['account_owned'][0]['_id']
start_training(bot, "*****@*****.**")
bot2 = AccountProcessor.add_bot("testChat2", user['account'],
                                "*****@*****.**")['_id'].__str__()
loop.run_until_complete(MongoProcessor().save_from_path(
    "template/use-cases/Hi-Hello", bot2, user="******"))
start_training(bot2, "*****@*****.**")
bot3 = AccountProcessor.add_bot("testChat3", user['account'],
                                "*****@*****.**")['_id'].__str__()
ChatDataProcessor.save_channel_config(
    {
        "connector_type": "slack",
        "config": {
            "bot_user_oAuth_token":
            "xoxb-801939352912-801478018484-v3zq6MYNu62oSs8vammWOY8K",
            "slack_signing_secret": "79f036b9894eef17c064213b90d1042b"
        }
    },
    bot,
    user="******")
responses.start()
encoded_url = urlencode(
    {'url': f"https://[email protected]/api/bot/telegram/{bot}/test"},
    quote_via=quote_plus)
responses.add(
    "GET",
    json={"result": True},
    url=
    f"https://api.telegram.org/botxoxb-801939352912-801478018484/setWebhook?{encoded_url}"
)
예제 #13
0
 def test_delete_channel_config_slack(self):
     ChatDataProcessor.delete_channel_config("slack", "test")
     assert list(ChatDataProcessor.list_channel_config("test")).__len__() == 0