Home Assistant Unofficial Reference 2024.12.1
notify.py
Go to the documentation of this file.
1 """Twilio SMS platform for notify component."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 import voluptuous as vol
8 
10  ATTR_DATA,
11  ATTR_TARGET,
12  PLATFORM_SCHEMA as NOTIFY_PLATFORM_SCHEMA,
13  BaseNotificationService,
14 )
15 from homeassistant.components.twilio import DATA_TWILIO
16 from homeassistant.core import HomeAssistant
18 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
19 
20 _LOGGER = logging.getLogger(__name__)
21 
22 CONF_FROM_NUMBER = "from_number"
23 ATTR_MEDIAURL = "media_url"
24 
25 PLATFORM_SCHEMA = NOTIFY_PLATFORM_SCHEMA.extend(
26  {
27  vol.Required(CONF_FROM_NUMBER): vol.All(
28  cv.string,
29  vol.Match(
30  r"^\+?[1-9]\d{1,14}$|"
31  r"^(?=.{1,11}$)[a-zA-Z0-9\s]*"
32  r"[a-zA-Z][a-zA-Z0-9\s]*$"
33  r"^(?:[a-zA-Z]+)\:?\+?[1-9]\d{1,14}$|"
34  ),
35  )
36  }
37 )
38 
39 
41  hass: HomeAssistant,
42  config: ConfigType,
43  discovery_info: DiscoveryInfoType | None = None,
44 ) -> TwilioSMSNotificationService | None:
45  """Get the Twilio SMS notification service."""
47  hass.data[DATA_TWILIO], config[CONF_FROM_NUMBER]
48  )
49 
50 
51 class TwilioSMSNotificationService(BaseNotificationService):
52  """Implement the notification service for the Twilio SMS service."""
53 
54  def __init__(self, twilio_client, from_number):
55  """Initialize the service."""
56  self.clientclient = twilio_client
57  self.from_numberfrom_number = from_number
58 
59  def send_message(self, message="", **kwargs):
60  """Send SMS to specified target user cell."""
61  targets = kwargs.get(ATTR_TARGET)
62  data = kwargs.get(ATTR_DATA) or {}
63  twilio_args = {"body": message, "from_": self.from_numberfrom_number}
64 
65  if ATTR_MEDIAURL in data:
66  twilio_args[ATTR_MEDIAURL] = data[ATTR_MEDIAURL]
67 
68  if not targets:
69  _LOGGER.warning("At least 1 target is required")
70  return
71 
72  for target in targets:
73  self.clientclient.messages.create(to=target, **twilio_args)
TwilioSMSNotificationService|None get_service(HomeAssistant hass, ConfigType config, DiscoveryInfoType|None discovery_info=None)
Definition: notify.py:44