Home Assistant Unofficial Reference 2024.12.1
notify.py
Go to the documentation of this file.
1 """Clicksend platform for notify component."""
2 
3 from __future__ import annotations
4 
5 from http import HTTPStatus
6 import json
7 import logging
8 from typing import Any
9 
10 import requests
11 import voluptuous as vol
12 
14  PLATFORM_SCHEMA as NOTIFY_PLATFORM_SCHEMA,
15  BaseNotificationService,
16 )
17 from homeassistant.const import (
18  CONF_API_KEY,
19  CONF_RECIPIENT,
20  CONF_SENDER,
21  CONF_USERNAME,
22  CONTENT_TYPE_JSON,
23 )
24 from homeassistant.core import HomeAssistant
26 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
27 
28 _LOGGER = logging.getLogger(__name__)
29 
30 BASE_API_URL = "https://rest.clicksend.com/v3"
31 DEFAULT_SENDER = "hass"
32 TIMEOUT = 5
33 
34 HEADERS = {"Content-Type": CONTENT_TYPE_JSON}
35 
36 
37 PLATFORM_SCHEMA = NOTIFY_PLATFORM_SCHEMA.extend(
38  {
39  vol.Required(CONF_USERNAME): cv.string,
40  vol.Required(CONF_API_KEY): cv.string,
41  vol.Required(CONF_RECIPIENT, default=[]): vol.All(cv.ensure_list, [cv.string]),
42  vol.Optional(CONF_SENDER, default=DEFAULT_SENDER): cv.string,
43  }
44 )
45 
46 
48  hass: HomeAssistant,
49  config: ConfigType,
50  discovery_info: DiscoveryInfoType | None = None,
51 ) -> ClicksendNotificationService | None:
52  """Get the ClickSend notification service."""
53  if not _authenticate(config):
54  _LOGGER.error("You are not authorized to access ClickSend")
55  return None
56  return ClicksendNotificationService(config)
57 
58 
59 class ClicksendNotificationService(BaseNotificationService):
60  """Implementation of a notification service for the ClickSend service."""
61 
62  def __init__(self, config: ConfigType) -> None:
63  """Initialize the service."""
64  self.username: str = config[CONF_USERNAME]
65  self.api_key: str = config[CONF_API_KEY]
66  self.recipients: list[str] = config[CONF_RECIPIENT]
67  self.sender: str = config[CONF_SENDER]
68 
69  def send_message(self, message: str = "", **kwargs: Any) -> None:
70  """Send a message to a user."""
71  data: dict[str, Any] = {"messages": []}
72  for recipient in self.recipients:
73  data["messages"].append(
74  {
75  "source": "hass.notify",
76  "from": self.sender,
77  "to": recipient,
78  "body": message,
79  }
80  )
81 
82  api_url = f"{BASE_API_URL}/sms/send"
83  resp = requests.post(
84  api_url,
85  data=json.dumps(data),
86  headers=HEADERS,
87  auth=(self.username, self.api_key),
88  timeout=TIMEOUT,
89  )
90  if resp.status_code == HTTPStatus.OK:
91  return
92 
93  obj = json.loads(resp.text)
94  response_msg = obj.get("response_msg")
95  response_code = obj.get("response_code")
96  _LOGGER.error(
97  "Error %s : %s (Code %s)", resp.status_code, response_msg, response_code
98  )
99 
100 
101 def _authenticate(config: ConfigType) -> bool:
102  """Authenticate with ClickSend."""
103  api_url = f"{BASE_API_URL}/account"
104  resp = requests.get(
105  api_url,
106  headers=HEADERS,
107  auth=(config[CONF_USERNAME], config[CONF_API_KEY]),
108  timeout=TIMEOUT,
109  )
110  return resp.status_code == HTTPStatus.OK
None send_message(self, str message="", **Any kwargs)
Definition: notify.py:69
bool _authenticate(ConfigType config)
Definition: notify.py:101
ClicksendNotificationService|None get_service(HomeAssistant hass, ConfigType config, DiscoveryInfoType|None discovery_info=None)
Definition: notify.py:51