2019-04-03 15:40:03 +00:00
|
|
|
"""Twilio Call platform for notify component."""
|
2017-01-26 23:32:01 +00:00
|
|
|
import logging
|
|
|
|
import urllib
|
|
|
|
|
2019-11-26 18:08:16 +00:00
|
|
|
from twilio.base.exceptions import TwilioRestException
|
2017-01-26 23:32:01 +00:00
|
|
|
import voluptuous as vol
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
from homeassistant.components.notify import (
|
|
|
|
ATTR_TARGET,
|
|
|
|
PLATFORM_SCHEMA,
|
|
|
|
BaseNotificationService,
|
|
|
|
)
|
2019-10-22 07:00:58 +00:00
|
|
|
from homeassistant.components.twilio import DATA_TWILIO
|
|
|
|
import homeassistant.helpers.config_validation as cv
|
2017-01-26 23:32:01 +00:00
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
CONF_FROM_NUMBER = "from_number"
|
2017-01-26 23:32:01 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
|
|
|
{
|
|
|
|
vol.Required(CONF_FROM_NUMBER): vol.All(
|
|
|
|
cv.string, vol.Match(r"^\+?[1-9]\d{1,14}$")
|
|
|
|
)
|
|
|
|
}
|
|
|
|
)
|
2017-01-26 23:32:01 +00:00
|
|
|
|
|
|
|
|
|
|
|
def get_service(hass, config, discovery_info=None):
|
|
|
|
"""Get the Twilio Call notification service."""
|
2017-05-02 16:18:47 +00:00
|
|
|
return TwilioCallNotificationService(
|
2019-07-31 19:25:30 +00:00
|
|
|
hass.data[DATA_TWILIO], config[CONF_FROM_NUMBER]
|
|
|
|
)
|
2017-01-26 23:32:01 +00:00
|
|
|
|
|
|
|
|
|
|
|
class TwilioCallNotificationService(BaseNotificationService):
|
|
|
|
"""Implement the notification service for the Twilio Call service."""
|
|
|
|
|
|
|
|
def __init__(self, twilio_client, from_number):
|
|
|
|
"""Initialize the service."""
|
|
|
|
self.client = twilio_client
|
|
|
|
self.from_number = from_number
|
|
|
|
|
|
|
|
def send_message(self, message="", **kwargs):
|
|
|
|
"""Call to specified target users."""
|
2017-01-28 00:35:54 +00:00
|
|
|
|
2017-01-26 23:32:01 +00:00
|
|
|
targets = kwargs.get(ATTR_TARGET)
|
|
|
|
|
|
|
|
if not targets:
|
|
|
|
_LOGGER.info("At least 1 target is required")
|
|
|
|
return
|
|
|
|
|
2017-01-28 20:46:34 +00:00
|
|
|
if message.startswith(("http://", "https://")):
|
2017-01-27 23:51:30 +00:00
|
|
|
twimlet_url = message
|
|
|
|
else:
|
2017-01-28 20:45:52 +00:00
|
|
|
twimlet_url = "http://twimlets.com/message?Message="
|
|
|
|
twimlet_url += urllib.parse.quote(message, safe="")
|
2017-01-27 23:51:30 +00:00
|
|
|
|
|
|
|
for target in targets:
|
2017-01-28 00:35:54 +00:00
|
|
|
try:
|
2017-05-02 16:18:47 +00:00
|
|
|
self.client.calls.create(
|
2019-07-31 19:25:30 +00:00
|
|
|
to=target, url=twimlet_url, from_=self.from_number
|
|
|
|
)
|
2017-01-28 00:35:54 +00:00
|
|
|
except TwilioRestException as exc:
|
|
|
|
_LOGGER.error(exc)
|