Ejemplo n.º 1
0
    async def _async_handle_conversation_message(self,
                                                 conv_id, user_id, event):
        """Handle a message sent to a conversation."""
        user = self._user_list.get_user(user_id)
        if user.is_self:
            return
        message = event.text

        _LOGGER.debug("Handling message '%s' from %s",
                      message, user.full_name)

        intents = self._conversation_intents.get(conv_id)
        if intents is not None:
            is_error = False
            try:
                intent_result = await self._async_process(intents, message)
            except (intent.UnknownIntent, intent.IntentHandleError) as err:
                is_error = True
                intent_result = intent.IntentResponse()
                intent_result.async_set_speech(str(err))

            if intent_result is None:
                is_error = True
                intent_result = intent.IntentResponse()
                intent_result.async_set_speech(
                    "Sorry, I didn't understand that")

            message = intent_result.as_dict().get('speech', {})\
                .get('plain', {}).get('speech')

            if (message is not None) and not (
                    is_error and conv_id in self._error_suppressed_conv_ids):
                await self._async_send_message(
                    [{'text': message, 'parse_str': True}],
                    [{CONF_CONVERSATION_ID: conv_id}])
Ejemplo n.º 2
0
async def _async_converse(hass: core.HomeAssistant, text: str,
                          conversation_id: str,
                          context: core.Context) -> intent.IntentResponse:
    """Process text and get intent."""
    agent = await _get_agent(hass)
    ha_agent = await _get_ha_agent(hass)

    try:
        intent_result = await ha_agent.async_process(text, context,
                                                     conversation_id)
    except intent.IntentHandleError as err:
        _LOGGER.warning("converse: " + str(err))

    if intent_result is None:
        try:
            intent_result = await agent.async_process(text, context,
                                                      conversation_id)
        except intent.IntentHandleError as err:
            intent_result = intent.IntentResponse()
            intent_result.async_set_speech(str(err))

    if intent_result is None:
        intent_result = intent.IntentResponse()
        intent_result.async_set_speech("Przepraszam, nie zrozumiałem tego.")

    return intent_result
Ejemplo n.º 3
0
async def get_intent(hass: core.HomeAssistant, text: str,
                     conversation_id: str):
    """Process text and get intent."""
    try:
        intent_result = await process(hass, text, conversation_id)
    except intent.IntentHandleError as err:
        intent_result = intent.IntentResponse()
        intent_result.async_set_speech(str(err))

    if intent_result is None:
        intent_result = intent.IntentResponse()
        intent_result.async_set_speech("Sorry, I didn't understand that")

    return intent_result
Ejemplo n.º 4
0
    async def post(self, request, data):
        """Send a request for processing."""
        hass = request.app['hass']

        try:
            intent_result = await _process(hass, data['text'])
        except intent.IntentHandleError as err:
            intent_result = intent.IntentResponse()
            intent_result.async_set_speech(str(err))

        if intent_result is None:
            intent_result = intent.IntentResponse()
            intent_result.async_set_speech("Sorry, I didn't understand that")

        return self.json(intent_result)
Ejemplo n.º 5
0
    async def async_process(
            self,
            text: str,
            context: Context,
            conversation_id: Optional[str] = None) -> intent.IntentResponse:
        """Process a sentence."""
        response = await self.api.async_converse_text(text, conversation_id)

        first_choice = True
        buffer = ""
        for message in response["messages"]:
            if message["type"] == "text":
                buffer += f"\n{message['text']}"
            elif message["type"] == "picture":
                buffer += f"\n Picture: {message['url']}"
            elif message["type"] == "rdl":
                buffer += (f"\n Link: {message['rdl']['displayTitle']} "
                           f"{message['rdl']['webCallback']}")
            elif message["type"] == "choice":
                if first_choice:
                    first_choice = False
                else:
                    buffer += ","
                buffer += f" {message['title']}"

        intent_result = intent.IntentResponse()
        intent_result.async_set_speech(buffer.strip())
        return intent_result
Ejemplo n.º 6
0
    async def post(self, request, data):
        """Send a request for processing."""
        from homeassistant.components import ais_ai_service as ais_ai_service

        hass = request.app["hass"]

        try:
            intent_result = await ais_ai_service._process(hass, data["text"])
        except intent.IntentHandleError as err:
            intent_result = intent.IntentResponse()
            intent_result.async_set_speech(str(err))

        if intent_result is None:
            intent_result = intent.IntentResponse()
            intent_result.async_set_speech("Sorry, I didn't understand that")

        return self.json(intent_result)
Ejemplo n.º 7
0
    async def post(self, request, data):
        """Send a request for processing."""
        hass = request.app["hass"]

        try:
            intent_result = await _process(hass, data["text"])
        except intent.IntentHandleError as err:
            intent_result = intent.IntentResponse()
            intent_result.async_set_speech(str(err))

        if intent_result is None:
            # ais-dom ask
            from homeassistant.components import ais_ai_service as ais_ai
            intent_result = await ais_ai._process(hass, data['text'])
            if intent_result is None:
                intent_result = intent.IntentResponse()
                intent_result.async_set_speech(
                    "Przepraszam, jeszcze tego nie potrafie zrozumieć")

        return self.json(intent_result)
Ejemplo n.º 8
0
    def post(self, request, data):
        """Send a request for processing."""
        hass = request.app['hass']

        intent_result = yield from _process(hass, data['text'])

        if intent_result is None:
            intent_result = intent.IntentResponse()
            intent_result.async_set_speech("Sorry, I didn't understand that")

        return self.json(intent_result)
Ejemplo n.º 9
0
    async def post(self, request, data):
        """Handle intent with name/data."""
        hass = request.app["hass"]

        try:
            intent_name = data["name"]
            slots = {
                key: {"value": value} for key, value in data.get("data", {}).items()
            }
            intent_result = await intent.async_handle(
                hass, DOMAIN, intent_name, slots, "", self.context(request)
            )
        except intent.IntentHandleError as err:
            intent_result = intent.IntentResponse()
            intent_result.async_set_speech(str(err))

        if intent_result is None:
            intent_result = intent.IntentResponse()
            intent_result.async_set_speech("Sorry, I couldn't handle that")

        return self.json(intent_result)
Ejemplo n.º 10
0
async def _async_converse(hass: core.HomeAssistant, text: str,
                          conversation_id: str,
                          context: core.Context) -> intent.IntentResponse:
    """Process text and get intent."""
    agent = await _get_agent(hass)
    voice = hass.data[DATA_VOICE]
    try:
        # 去掉前后标点符号
        _text = voice.fire_text(text)
        # 执行自定义语句
        result = await voice.execute_action(_text)
        if result is not None:
            return result

        # 开关控制
        result = await voice.execute_switch(_text)
        if result is not None:
            return result

        # 内置处理指令
        intent_result = await agent.async_process(_text, context,
                                                  conversation_id)
    except intent.IntentHandleError as err:
        # 错误信息处理
        err_msg = voice.error_msg(str(err))

        intent_result = intent.IntentResponse()
        intent_result.async_set_speech(err_msg)

    if intent_result is None:
        # 调用聊天机器人
        message = await voice.chat_robot(text)
        intent_result = intent.IntentResponse()
        intent_result.async_set_speech(message)

    return intent_result
Ejemplo n.º 11
0
    async def async_process(
            self,
            text: str,
            context: Context,
            conversation_id: Optional[str] = None) -> intent.IntentResponse:
        """Process a sentence."""
        from homeassistant.components import ais_ai_service as ais_ai

        intent_result = await ais_ai._async_process(self.hass, text)
        if intent_result is None:
            intent_result = intent.IntentResponse()
            intent_result.async_set_speech(
                "Przepraszam, jeszcze tego nie potrafię zrozumieć.")

        return intent_result
Ejemplo n.º 12
0
    async def async_process(
            self,
            text: str,
            conversation_id: Optional[str] = None) -> intent.IntentResponse:
        """Process a sentence."""
        response = await self.api.async_converse_text(text, conversation_id)

        buffer = ""
        for message in response["messages"]:
            if message["type"] == "text":
                buffer += "\n" + message["text"]
            elif message["type"] == "picture":
                buffer += "\n Picture: " + message["url"]
            elif message["type"] == "rdl":
                buffer += ("\n Link: " + message["rdl"]["displayTitle"] + " " +
                           message["rdl"]["webCallback"])
            elif message["type"] == "choice":
                buffer += "\n Choice: " + message["title"]

        intent_result = intent.IntentResponse()
        intent_result.async_set_speech(buffer.strip())
        return intent_result
    def post(self, request):
        """Send a request for processing."""
        hass = request.app['hass']
        try:
            data = yield from request.json()
        except ValueError:
            return self.json_message('Invalid JSON specified',
                                     HTTP_BAD_REQUEST)

        text = data.get('text')

        if text is None:
            return self.json_message('Missing "text" key in JSON.',
                                     HTTP_BAD_REQUEST)

        intent_result = yield from _process(hass, text)

        if intent_result is None:
            intent_result = intent.IntentResponse()
            intent_result.async_set_speech("Sorry, I didn't understand that")

        return self.json(intent_result)
Ejemplo n.º 14
0
 def intent_result(self, message, extra_data=None):
     intent_result = intent.IntentResponse()
     intent_result.async_set_speech(message, 'plain', extra_data)
     return intent_result
Ejemplo n.º 15
0
 async def async_process(self, text, context, conversation_id):
     """Process some text."""
     calls.append((text, context, conversation_id))
     response = intent.IntentResponse()
     response.async_set_speech("Test response")
     return response
Ejemplo n.º 16
0
 async def async_process(self, text):
     """Process some text."""
     response = intent.IntentResponse()
     response.async_set_speech("Test response")
     return response
Ejemplo n.º 17
0
 def intent_result(self, message):
     intent_result = intent.IntentResponse()
     intent_result.async_set_speech(message)
     return intent_result