Home Assistant Unofficial Reference 2024.12.1
intent.py
Go to the documentation of this file.
1 """Intents for the todo integration."""
2 
3 from __future__ import annotations
4 
5 import voluptuous as vol
6 
7 from homeassistant.core import HomeAssistant
8 from homeassistant.helpers import intent
9 
10 from . import TodoItem, TodoItemStatus, TodoListEntity
11 from .const import DATA_COMPONENT, DOMAIN
12 
13 INTENT_LIST_ADD_ITEM = "HassListAddItem"
14 
15 
16 async def async_setup_intents(hass: HomeAssistant) -> None:
17  """Set up the todo intents."""
18  intent.async_register(hass, ListAddItemIntent())
19 
20 
21 class ListAddItemIntent(intent.IntentHandler):
22  """Handle ListAddItem intents."""
23 
24  intent_type = INTENT_LIST_ADD_ITEM
25  description = "Add item to a todo list"
26  slot_schema = {
27  vol.Required("item"): intent.non_empty_string,
28  vol.Required("name"): intent.non_empty_string,
29  }
30  platforms = {DOMAIN}
31 
32  async def async_handle(self, intent_obj: intent.Intent) -> intent.IntentResponse:
33  """Handle the intent."""
34  hass = intent_obj.hass
35 
36  slots = self.async_validate_slots(intent_obj.slots)
37  item = slots["item"]["value"].strip()
38  list_name = slots["name"]["value"]
39 
40  target_list: TodoListEntity | None = None
41 
42  # Find matching list
43  match_constraints = intent.MatchTargetsConstraints(
44  name=list_name, domains=[DOMAIN], assistant=intent_obj.assistant
45  )
46  match_result = intent.async_match_targets(hass, match_constraints)
47  if not match_result.is_match:
48  raise intent.MatchFailedError(
49  result=match_result, constraints=match_constraints
50  )
51 
52  target_list = hass.data[DATA_COMPONENT].get_entity(
53  match_result.states[0].entity_id
54  )
55  if target_list is None:
56  raise intent.IntentHandleError(f"No to-do list: {list_name}")
57 
58  # Add to list
59  await target_list.async_create_todo_item(
60  TodoItem(summary=item, status=TodoItemStatus.NEEDS_ACTION)
61  )
62 
63  response = intent_obj.create_response()
64  response.response_type = intent.IntentResponseType.ACTION_DONE
65  response.async_set_results(
66  [
67  intent.IntentResponseTarget(
68  type=intent.IntentResponseTargetType.ENTITY,
69  name=list_name,
70  id=match_result.states[0].entity_id,
71  )
72  ]
73  )
74  return response
intent.IntentResponse async_handle(self, intent.Intent intent_obj)
Definition: intent.py:32
CalendarEntity get_entity(HomeAssistant hass, str entity_id)
Definition: trigger.py:96
None async_setup_intents(HomeAssistant hass)
Definition: intent.py:16