Home Assistant Unofficial Reference 2024.12.1
notify.py
Go to the documentation of this file.
1 """Flock platform for notify component."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from http import HTTPStatus
7 import logging
8 
9 import voluptuous as vol
10 
12  PLATFORM_SCHEMA as NOTIFY_PLATFORM_SCHEMA,
13  BaseNotificationService,
14 )
15 from homeassistant.const import CONF_ACCESS_TOKEN
16 from homeassistant.core import HomeAssistant
17 from homeassistant.helpers.aiohttp_client import async_get_clientsession
19 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
20 
21 _LOGGER = logging.getLogger(__name__)
22 _RESOURCE = "https://api.flock.com/hooks/sendMessage/"
23 
24 PLATFORM_SCHEMA = NOTIFY_PLATFORM_SCHEMA.extend(
25  {vol.Required(CONF_ACCESS_TOKEN): cv.string}
26 )
27 
28 
30  hass: HomeAssistant,
31  config: ConfigType,
32  discovery_info: DiscoveryInfoType | None = None,
33 ) -> FlockNotificationService:
34  """Get the Flock notification service."""
35  access_token = config.get(CONF_ACCESS_TOKEN)
36  url = f"{_RESOURCE}{access_token}"
37  session = async_get_clientsession(hass)
38 
39  return FlockNotificationService(url, session)
40 
41 
42 class FlockNotificationService(BaseNotificationService):
43  """Implement the notification service for Flock."""
44 
45  def __init__(self, url, session):
46  """Initialize the Flock notification service."""
47  self._url_url = url
48  self._session_session = session
49 
50  async def async_send_message(self, message, **kwargs):
51  """Send the message to the user."""
52  payload = {"text": message}
53 
54  _LOGGER.debug("Attempting to call Flock at %s", self._url_url)
55 
56  try:
57  async with asyncio.timeout(10):
58  response = await self._session_session.post(self._url_url, json=payload)
59  result = await response.json()
60 
61  if response.status != HTTPStatus.OK or "error" in result:
62  _LOGGER.error(
63  "Flock service returned HTTP status %d, response %s",
64  response.status,
65  result,
66  )
67  except TimeoutError:
68  _LOGGER.error("Timeout accessing Flock at %s", self._url_url)
web.Response post(self, web.Request request, str config_key)
Definition: view.py:101
FlockNotificationService async_get_service(HomeAssistant hass, ConfigType config, DiscoveryInfoType|None discovery_info=None)
Definition: notify.py:33
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)