2019-04-03 15:40:03 +00:00
|
|
|
"""MessageBird platform for notify component."""
|
2016-03-15 17:09:19 +00:00
|
|
|
import logging
|
|
|
|
|
2019-10-21 07:48:25 +00:00
|
|
|
import messagebird
|
|
|
|
from messagebird.client import ErrorException
|
2016-09-05 05:07:31 +00:00
|
|
|
import voluptuous as vol
|
2016-03-15 17:09:19 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
from homeassistant.components.notify import (
|
|
|
|
ATTR_TARGET,
|
|
|
|
PLATFORM_SCHEMA,
|
|
|
|
BaseNotificationService,
|
|
|
|
)
|
2019-10-21 07:48:25 +00:00
|
|
|
from homeassistant.const import CONF_API_KEY, CONF_SENDER
|
|
|
|
import homeassistant.helpers.config_validation as cv
|
2016-03-15 17:09:19 +00:00
|
|
|
|
2016-10-29 16:12:43 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
2016-03-15 17:09:19 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
|
|
|
{
|
|
|
|
vol.Required(CONF_API_KEY): cv.string,
|
|
|
|
vol.Optional(CONF_SENDER, default="HA"): vol.All(
|
|
|
|
cv.string, vol.Match(r"^(\+?[1-9]\d{1,14}|\w{1,11})$")
|
|
|
|
),
|
|
|
|
}
|
|
|
|
)
|
2016-03-15 17:09:19 +00:00
|
|
|
|
|
|
|
|
2017-01-15 02:53:14 +00:00
|
|
|
def get_service(hass, config, discovery_info=None):
|
2016-03-15 17:09:19 +00:00
|
|
|
"""Get the MessageBird notification service."""
|
2016-03-16 09:32:02 +00:00
|
|
|
client = messagebird.Client(config[CONF_API_KEY])
|
|
|
|
try:
|
|
|
|
# validates the api key
|
|
|
|
client.balance()
|
|
|
|
except messagebird.client.ErrorException:
|
2017-05-02 16:18:47 +00:00
|
|
|
_LOGGER.error("The specified MessageBird API key is invalid")
|
2016-03-16 09:32:02 +00:00
|
|
|
return None
|
|
|
|
|
2016-09-05 05:07:31 +00:00
|
|
|
return MessageBirdNotificationService(config.get(CONF_SENDER), client)
|
2016-03-15 17:09:19 +00:00
|
|
|
|
|
|
|
|
|
|
|
class MessageBirdNotificationService(BaseNotificationService):
|
|
|
|
"""Implement the notification service for MessageBird."""
|
|
|
|
|
|
|
|
def __init__(self, sender, client):
|
|
|
|
"""Initialize the service."""
|
|
|
|
self.sender = sender
|
|
|
|
self.client = client
|
|
|
|
|
|
|
|
def send_message(self, message=None, **kwargs):
|
|
|
|
"""Send a message to a specified target."""
|
|
|
|
targets = kwargs.get(ATTR_TARGET)
|
|
|
|
if not targets:
|
2017-05-02 16:18:47 +00:00
|
|
|
_LOGGER.error("No target specified")
|
2016-03-15 17:09:19 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
for target in targets:
|
|
|
|
try:
|
2017-05-02 16:18:47 +00:00
|
|
|
self.client.message_create(
|
2019-07-31 19:25:30 +00:00
|
|
|
self.sender, target, message, {"reference": "HA"}
|
|
|
|
)
|
2016-03-15 17:09:19 +00:00
|
|
|
except ErrorException as exception:
|
2017-05-02 16:18:47 +00:00
|
|
|
_LOGGER.error("Failed to notify %s: %s", target, exception)
|
2016-03-15 17:09:19 +00:00
|
|
|
continue
|