Home Assistant Unofficial Reference 2024.12.1
notify.py
Go to the documentation of this file.
1 """Facebook 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  ATTR_DATA,
14  ATTR_TARGET,
15  PLATFORM_SCHEMA as NOTIFY_PLATFORM_SCHEMA,
16  BaseNotificationService,
17 )
18 from homeassistant.const import CONTENT_TYPE_JSON
19 from homeassistant.core import HomeAssistant
21 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 CONF_PAGE_ACCESS_TOKEN = "page_access_token"
26 BASE_URL = "https://graph.facebook.com/v2.6/me/messages"
27 
28 PLATFORM_SCHEMA = NOTIFY_PLATFORM_SCHEMA.extend(
29  {vol.Required(CONF_PAGE_ACCESS_TOKEN): cv.string}
30 )
31 
32 
34  hass: HomeAssistant,
35  config: ConfigType,
36  discovery_info: DiscoveryInfoType | None = None,
37 ) -> FacebookNotificationService:
38  """Get the Facebook notification service."""
39  return FacebookNotificationService(config[CONF_PAGE_ACCESS_TOKEN])
40 
41 
42 class FacebookNotificationService(BaseNotificationService):
43  """Implementation of a notification service for the Facebook service."""
44 
45  def __init__(self, access_token):
46  """Initialize the service."""
47  self.page_access_tokenpage_access_token = access_token
48 
49  def send_message(self, message="", **kwargs):
50  """Send some message."""
51  payload = {"access_token": self.page_access_tokenpage_access_token}
52  targets = kwargs.get(ATTR_TARGET)
53  data = kwargs.get(ATTR_DATA)
54 
55  body_message = {"text": message}
56 
57  if data is not None:
58  body_message.update(data)
59  # Only one of text or attachment can be specified
60  if "attachment" in body_message:
61  body_message.pop("text")
62 
63  if not targets:
64  _LOGGER.error("At least 1 target is required")
65  return
66 
67  for target in targets:
68  # If the target starts with a "+", it's a phone number,
69  # otherwise it's a user id.
70  if target.startswith("+"):
71  recipient = {"phone_number": target}
72  else:
73  recipient = {"id": target}
74 
75  body = {
76  "recipient": recipient,
77  "message": body_message,
78  "messaging_type": "MESSAGE_TAG",
79  "tag": "ACCOUNT_UPDATE",
80  }
81  resp = requests.post(
82  BASE_URL,
83  data=json.dumps(body),
84  params=payload,
85  headers={"Content-Type": CONTENT_TYPE_JSON},
86  timeout=10,
87  )
88  if resp.status_code != HTTPStatus.OK:
89  log_error(resp)
90 
91 
92 def log_error(response):
93  """Log error message."""
94  obj = response.json()
95  error_message = obj["error"]["message"]
96  error_code = obj["error"]["code"]
97 
98  _LOGGER.error(
99  "Error %s : %s (Code %s)", response.status_code, error_message, error_code
100  )
FacebookNotificationService get_service(HomeAssistant hass, ConfigType config, DiscoveryInfoType|None discovery_info=None)
Definition: notify.py:37