Home Assistant Unofficial Reference 2024.12.1
notify.py
Go to the documentation of this file.
1 """clicksend_tts platform for notify component."""
2 
3 from __future__ import annotations
4 
5 from http import HTTPStatus
6 import json
7 import logging
8 
9 import requests
10 import voluptuous as vol
11 
13  PLATFORM_SCHEMA as NOTIFY_PLATFORM_SCHEMA,
14  BaseNotificationService,
15 )
16 from homeassistant.const import (
17  CONF_API_KEY,
18  CONF_NAME,
19  CONF_RECIPIENT,
20  CONF_USERNAME,
21  CONTENT_TYPE_JSON,
22 )
23 from homeassistant.core import HomeAssistant
25 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
26 
27 _LOGGER = logging.getLogger(__name__)
28 
29 BASE_API_URL = "https://rest.clicksend.com/v3"
30 
31 HEADERS = {"Content-Type": CONTENT_TYPE_JSON}
32 
33 CONF_LANGUAGE = "language"
34 CONF_VOICE = "voice"
35 
36 MALE_VOICE = "male"
37 FEMALE_VOICE = "female"
38 
39 DEFAULT_NAME = "clicksend_tts"
40 DEFAULT_LANGUAGE = "en-us"
41 DEFAULT_VOICE = FEMALE_VOICE
42 TIMEOUT = 5
43 
44 PLATFORM_SCHEMA = NOTIFY_PLATFORM_SCHEMA.extend(
45  {
46  vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
47  vol.Required(CONF_USERNAME): cv.string,
48  vol.Required(CONF_API_KEY): cv.string,
49  vol.Required(CONF_RECIPIENT): vol.All(
50  cv.string, vol.Match(r"^\+?[1-9]\d{1,14}$")
51  ),
52  vol.Optional(CONF_LANGUAGE, default=DEFAULT_LANGUAGE): cv.string,
53  vol.Optional(CONF_VOICE, default=DEFAULT_VOICE): vol.In(
54  [MALE_VOICE, FEMALE_VOICE]
55  ),
56  }
57 )
58 
59 
61  hass: HomeAssistant,
62  config: ConfigType,
63  discovery_info: DiscoveryInfoType | None = None,
64 ) -> ClicksendNotificationService | None:
65  """Get the ClickSend notification service."""
66  if not _authenticate(config):
67  _LOGGER.error("You are not authorized to access ClickSend")
68  return None
69 
70  return ClicksendNotificationService(config)
71 
72 
73 class ClicksendNotificationService(BaseNotificationService):
74  """Implementation of a notification service for the ClickSend service."""
75 
76  def __init__(self, config):
77  """Initialize the service."""
78  self.usernameusername = config[CONF_USERNAME]
79  self.api_keyapi_key = config[CONF_API_KEY]
80  self.recipientrecipient = config[CONF_RECIPIENT]
81  self.languagelanguage = config[CONF_LANGUAGE]
82  self.voicevoice = config[CONF_VOICE]
83 
84  def send_message(self, message="", **kwargs):
85  """Send a voice call to a user."""
86  data = {
87  "messages": [
88  {
89  "source": "hass.notify",
90  "to": self.recipientrecipient,
91  "body": message,
92  "lang": self.languagelanguage,
93  "voice": self.voicevoice,
94  }
95  ]
96  }
97  api_url = f"{BASE_API_URL}/voice/send"
98  resp = requests.post(
99  api_url,
100  data=json.dumps(data),
101  headers=HEADERS,
102  auth=(self.usernameusername, self.api_keyapi_key),
103  timeout=TIMEOUT,
104  )
105 
106  if resp.status_code == HTTPStatus.OK:
107  return
108  obj = json.loads(resp.text)
109  response_msg = obj["response_msg"]
110  response_code = obj["response_code"]
111  _LOGGER.error(
112  "Error %s : %s (Code %s)", resp.status_code, response_msg, response_code
113  )
114 
115 
116 def _authenticate(config):
117  """Authenticate with ClickSend."""
118  api_url = f"{BASE_API_URL}/account"
119  resp = requests.get(
120  api_url,
121  headers=HEADERS,
122  auth=(config.get(CONF_USERNAME), config.get(CONF_API_KEY)),
123  timeout=TIMEOUT,
124  )
125 
126  return resp.status_code == HTTPStatus.OK
ClicksendNotificationService|None get_service(HomeAssistant hass, ConfigType config, DiscoveryInfoType|None discovery_info=None)
Definition: notify.py:64