core/homeassistant/components/notify/slack.py

59 lines
1.7 KiB
Python
Raw Normal View History

2015-07-31 20:45:41 +00:00
"""
Slack platform for notify component.
2015-10-13 20:45:36 +00:00
For more details about this platform, please refer to the documentation at
2015-11-09 17:33:11 +00:00
https://home-assistant.io/components/notify.slack/
2015-07-31 20:45:41 +00:00
"""
import logging
2015-11-09 06:15:34 +00:00
from homeassistant.components.notify import DOMAIN, BaseNotificationService
2015-07-31 20:45:41 +00:00
from homeassistant.const import CONF_API_KEY
2016-02-19 05:27:50 +00:00
from homeassistant.helpers import validate_config
2015-07-31 20:45:41 +00:00
REQUIREMENTS = ['slacker==0.6.8']
2015-07-31 20:45:41 +00:00
_LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-variable
def get_service(hass, config):
2016-03-08 10:46:32 +00:00
"""Get the Slack notification service."""
2015-11-09 06:15:34 +00:00
import slacker
2015-07-31 20:45:41 +00:00
2015-11-09 06:15:34 +00:00
if not validate_config({DOMAIN: config},
2015-07-31 20:45:41 +00:00
{DOMAIN: ['default_channel', CONF_API_KEY]},
_LOGGER):
return None
try:
return SlackNotificationService(
2015-11-09 06:15:34 +00:00
config['default_channel'],
config[CONF_API_KEY])
2015-07-31 20:45:41 +00:00
2015-11-09 06:15:34 +00:00
except slacker.Error:
_LOGGER.exception(
2015-07-31 20:45:41 +00:00
"Slack authentication failed")
2015-11-09 06:15:34 +00:00
return None
2015-07-31 20:45:41 +00:00
# pylint: disable=too-few-public-methods
class SlackNotificationService(BaseNotificationService):
2016-03-08 10:46:32 +00:00
"""Implement the notification service for Slack."""
2015-07-31 20:45:41 +00:00
def __init__(self, default_channel, api_token):
2016-03-08 10:46:32 +00:00
"""Initialize the service."""
2015-07-31 20:45:41 +00:00
from slacker import Slacker
self._default_channel = default_channel
self._api_token = api_token
self.slack = Slacker(self._api_token)
self.slack.auth.test()
def send_message(self, message="", **kwargs):
2016-03-08 10:46:32 +00:00
"""Send a message to a user."""
2015-11-09 06:15:34 +00:00
import slacker
2015-07-31 20:45:41 +00:00
channel = kwargs.get('channel', self._default_channel)
try:
self.slack.chat.post_message(channel, message)
2015-11-09 06:15:34 +00:00
except slacker.Error:
2015-07-31 20:45:41 +00:00
_LOGGER.exception("Could not send slack notification")