Home Assistant Unofficial Reference 2024.12.1
intent.py
Go to the documentation of this file.
1 """Intents for the Shopping List integration."""
2 
3 from __future__ import annotations
4 
5 from homeassistant.core import HomeAssistant
6 from homeassistant.helpers import intent
8 
9 from . import DOMAIN, EVENT_SHOPPING_LIST_UPDATED
10 
11 INTENT_ADD_ITEM = "HassShoppingListAddItem"
12 INTENT_LAST_ITEMS = "HassShoppingListLastItems"
13 
14 
15 async def async_setup_intents(hass: HomeAssistant) -> None:
16  """Set up the Shopping List intents."""
17  intent.async_register(hass, AddItemIntent())
18  intent.async_register(hass, ListTopItemsIntent())
19 
20 
21 class AddItemIntent(intent.IntentHandler):
22  """Handle AddItem intents."""
23 
24  intent_type = INTENT_ADD_ITEM
25  description = "Adds an item to the shopping list"
26  slot_schema = {"item": cv.string}
27  platforms = {DOMAIN}
28 
29  async def async_handle(self, intent_obj: intent.Intent) -> intent.IntentResponse:
30  """Handle the intent."""
31  slots = self.async_validate_slots(intent_obj.slots)
32  item = slots["item"]["value"].strip()
33  await intent_obj.hass.data[DOMAIN].async_add(item)
34 
35  response = intent_obj.create_response()
36  intent_obj.hass.bus.async_fire(EVENT_SHOPPING_LIST_UPDATED)
37  return response
38 
39 
40 class ListTopItemsIntent(intent.IntentHandler):
41  """Handle AddItem intents."""
42 
43  intent_type = INTENT_LAST_ITEMS
44  description = "List the top five items on the shopping list"
45  slot_schema = {"item": cv.string}
46  platforms = {DOMAIN}
47 
48  async def async_handle(self, intent_obj: intent.Intent) -> intent.IntentResponse:
49  """Handle the intent."""
50  items = intent_obj.hass.data[DOMAIN].items[-5:]
51  response = intent_obj.create_response()
52 
53  if not items:
54  response.async_set_speech("There are no items on your shopping list")
55  else:
56  items_list = ", ".join(itm["name"] for itm in reversed(items))
57  response.async_set_speech(
58  f"These are the top {min(len(items), 5)} items on your shopping list: {items_list}"
59  )
60  return response
intent.IntentResponse async_handle(self, intent.Intent intent_obj)
Definition: intent.py:29
intent.IntentResponse async_handle(self, intent.Intent intent_obj)
Definition: intent.py:48
None async_setup_intents(HomeAssistant hass)
Definition: intent.py:15