Home Assistant Unofficial Reference 2024.12.1
notify.py
Go to the documentation of this file.
1 """Twilio Call platform for notify component."""
2 
3 from __future__ import annotations
4 
5 import logging
6 import urllib
7 
8 from twilio.base.exceptions import TwilioRestException
9 import voluptuous as vol
10 
12  ATTR_TARGET,
13  PLATFORM_SCHEMA as NOTIFY_PLATFORM_SCHEMA,
14  BaseNotificationService,
15 )
16 from homeassistant.components.twilio import DATA_TWILIO
17 from homeassistant.core import HomeAssistant
19 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
20 
21 _LOGGER = logging.getLogger(__name__)
22 
23 CONF_FROM_NUMBER = "from_number"
24 
25 PLATFORM_SCHEMA = NOTIFY_PLATFORM_SCHEMA.extend(
26  {
27  vol.Required(CONF_FROM_NUMBER): vol.All(
28  cv.string, vol.Match(r"^\+?[1-9]\d{1,14}$")
29  )
30  }
31 )
32 
33 
35  hass: HomeAssistant,
36  config: ConfigType,
37  discovery_info: DiscoveryInfoType | None = None,
38 ) -> TwilioCallNotificationService:
39  """Get the Twilio Call notification service."""
41  hass.data[DATA_TWILIO], config[CONF_FROM_NUMBER]
42  )
43 
44 
45 class TwilioCallNotificationService(BaseNotificationService):
46  """Implement the notification service for the Twilio Call service."""
47 
48  def __init__(self, twilio_client, from_number):
49  """Initialize the service."""
50  self.clientclient = twilio_client
51  self.from_numberfrom_number = from_number
52 
53  def send_message(self, message="", **kwargs):
54  """Call to specified target users."""
55  if not (targets := kwargs.get(ATTR_TARGET)):
56  _LOGGER.warning("At least 1 target is required")
57  return
58 
59  if message.startswith(("http://", "https://")):
60  twimlet_url = message
61  else:
62  twimlet_url = "http://twimlets.com/message?Message="
63  twimlet_url += urllib.parse.quote(message, safe="")
64 
65  for target in targets:
66  try:
67  self.clientclient.calls.create(
68  to=target, url=twimlet_url, from_=self.from_numberfrom_number
69  )
70  except TwilioRestException as exc:
71  _LOGGER.error(exc)
TwilioCallNotificationService get_service(HomeAssistant hass, ConfigType config, DiscoveryInfoType|None discovery_info=None)
Definition: notify.py:38