Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for Twilio."""
2 
3 from aiohttp import web
4 from twilio.rest import Client
5 import voluptuous as vol
6 
7 from homeassistant.components import webhook
8 from homeassistant.config_entries import ConfigEntry
9 from homeassistant.const import CONF_WEBHOOK_ID
10 from homeassistant.core import HomeAssistant
11 from homeassistant.helpers import config_entry_flow
13 from homeassistant.helpers.typing import ConfigType
14 
15 from .const import DOMAIN
16 
17 CONF_ACCOUNT_SID = "account_sid"
18 CONF_AUTH_TOKEN = "auth_token"
19 
20 DATA_TWILIO = DOMAIN
21 
22 RECEIVED_DATA = f"{DOMAIN}_data_received"
23 
24 CONFIG_SCHEMA = vol.Schema(
25  {
26  vol.Optional(DOMAIN): vol.Schema(
27  {
28  vol.Required(CONF_ACCOUNT_SID): cv.string,
29  vol.Required(CONF_AUTH_TOKEN): cv.string,
30  }
31  )
32  },
33  extra=vol.ALLOW_EXTRA,
34 )
35 
36 
37 async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
38  """Set up the Twilio component."""
39  if DOMAIN not in config:
40  return True
41 
42  conf = config[DOMAIN]
43  hass.data[DATA_TWILIO] = Client(
44  conf.get(CONF_ACCOUNT_SID), conf.get(CONF_AUTH_TOKEN)
45  )
46  return True
47 
48 
49 async def handle_webhook(
50  hass: HomeAssistant, webhook_id: str, request: web.Request
51 ) -> web.Response:
52  """Handle incoming webhook from Twilio for inbound messages and calls."""
53  data = dict(await request.post())
54  data["webhook_id"] = webhook_id
55  hass.bus.async_fire(RECEIVED_DATA, dict(data))
56 
57  return web.Response(text="")
58 
59 
60 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
61  """Configure based on config entry."""
62  webhook.async_register(
63  hass, DOMAIN, "Twilio", entry.data[CONF_WEBHOOK_ID], handle_webhook
64  )
65  return True
66 
67 
68 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
69  """Unload a config entry."""
70  webhook.async_unregister(hass, entry.data[CONF_WEBHOOK_ID])
71  return True
72 
73 
74 async_remove_entry = config_entry_flow.webhook_async_remove_entry
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:68
web.Response handle_webhook(HomeAssistant hass, str webhook_id, web.Request request)
Definition: __init__.py:51
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:60
bool async_setup(HomeAssistant hass, ConfigType config)
Definition: __init__.py:37