Home Assistant Unofficial Reference 2024.12.1
notify.py
Go to the documentation of this file.
1 """Microsoft Teams platform for notify component."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 import pymsteams
8 import voluptuous as vol
9 
11  ATTR_DATA,
12  ATTR_TITLE,
13  ATTR_TITLE_DEFAULT,
14  PLATFORM_SCHEMA as NOTIFY_PLATFORM_SCHEMA,
15  BaseNotificationService,
16 )
17 from homeassistant.const import CONF_URL
18 from homeassistant.core import HomeAssistant
20 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 ATTR_FILE_URL = "image_url"
25 
26 PLATFORM_SCHEMA = NOTIFY_PLATFORM_SCHEMA.extend({vol.Required(CONF_URL): cv.url})
27 
28 
30  hass: HomeAssistant,
31  config: ConfigType,
32  discovery_info: DiscoveryInfoType | None = None,
33 ) -> MSTeamsNotificationService | None:
34  """Get the Microsoft Teams notification service."""
35  webhook_url = config.get(CONF_URL)
36 
37  try:
38  return MSTeamsNotificationService(webhook_url)
39 
40  except RuntimeError:
41  _LOGGER.exception("Error in creating a new Microsoft Teams message")
42  return None
43 
44 
45 class MSTeamsNotificationService(BaseNotificationService):
46  """Implement the notification service for Microsoft Teams."""
47 
48  def __init__(self, webhook_url):
49  """Initialize the service."""
50  self._webhook_url_webhook_url = webhook_url
51 
52  def send_message(self, message=None, **kwargs):
53  """Send a message to the webhook."""
54 
55  teams_message = pymsteams.connectorcard(self._webhook_url_webhook_url)
56 
57  title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
58  data = kwargs.get(ATTR_DATA)
59 
60  teams_message.title(title)
61 
62  teams_message.text(message)
63 
64  if data is not None and (file_url := data.get(ATTR_FILE_URL)) is not None:
65  if not file_url.startswith("http"):
66  _LOGGER.error("URL should start with http or https")
67  return
68 
69  message_section = pymsteams.cardsection()
70  message_section.addImage(file_url)
71  teams_message.addSection(message_section)
72  try:
73  teams_message.send()
74  except RuntimeError as err:
75  _LOGGER.error("Could not send notification. Error: %s", err)
MSTeamsNotificationService|None get_service(HomeAssistant hass, ConfigType config, DiscoveryInfoType|None discovery_info=None)
Definition: notify.py:33