Home Assistant Unofficial Reference 2024.12.1
notify.py
Go to the documentation of this file.
1 """MessageBird platform for notify component."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 import messagebird
8 from messagebird.client import ErrorException
9 import voluptuous as vol
10 
12  ATTR_TARGET,
13  PLATFORM_SCHEMA as NOTIFY_PLATFORM_SCHEMA,
14  BaseNotificationService,
15 )
16 from homeassistant.const import CONF_API_KEY, CONF_SENDER
17 from homeassistant.core import HomeAssistant
19 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
20 
21 _LOGGER = logging.getLogger(__name__)
22 
23 PLATFORM_SCHEMA = NOTIFY_PLATFORM_SCHEMA.extend(
24  {
25  vol.Required(CONF_API_KEY): cv.string,
26  vol.Optional(CONF_SENDER, default="HA"): vol.All(
27  cv.string, vol.Match(r"^(\+?[1-9]\d{1,14}|\w{1,11})$")
28  ),
29  }
30 )
31 
32 
34  hass: HomeAssistant,
35  config: ConfigType,
36  discovery_info: DiscoveryInfoType | None = None,
37 ) -> MessageBirdNotificationService | None:
38  """Get the MessageBird notification service."""
39  client = messagebird.Client(config[CONF_API_KEY])
40  try:
41  # validates the api key
42  client.balance()
43  except messagebird.client.ErrorException:
44  _LOGGER.error("The specified MessageBird API key is invalid")
45  return None
46 
47  return MessageBirdNotificationService(config.get(CONF_SENDER), client)
48 
49 
50 class MessageBirdNotificationService(BaseNotificationService):
51  """Implement the notification service for MessageBird."""
52 
53  def __init__(self, sender, client):
54  """Initialize the service."""
55  self.sendersender = sender
56  self.clientclient = client
57 
58  def send_message(self, message=None, **kwargs):
59  """Send a message to a specified target."""
60  if not (targets := kwargs.get(ATTR_TARGET)):
61  _LOGGER.error("No target specified")
62  return
63 
64  for target in targets:
65  try:
66  self.clientclient.message_create(
67  self.sendersender, target, message, {"reference": "HA"}
68  )
69  except ErrorException as exception:
70  _LOGGER.error("Failed to notify %s: %s", target, exception)
71  continue
MessageBirdNotificationService|None get_service(HomeAssistant hass, ConfigType config, DiscoveryInfoType|None discovery_info=None)
Definition: notify.py:37