core/homeassistant/components/notify/twitter.py

58 lines
2.2 KiB
Python
Raw Normal View History

2016-01-21 01:02:32 +00:00
"""
Twitter platform for notify component.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.twitter/
"""
import logging
2016-02-19 05:27:50 +00:00
from homeassistant.components.notify import DOMAIN, BaseNotificationService
2016-01-21 01:02:32 +00:00
from homeassistant.const import CONF_ACCESS_TOKEN
2016-02-19 05:27:50 +00:00
from homeassistant.helpers import validate_config
2016-01-21 01:02:32 +00:00
_LOGGER = logging.getLogger(__name__)
2016-08-29 20:16:10 +00:00
REQUIREMENTS = ['TwitterAPI==2.4.2']
2016-01-21 01:02:32 +00:00
CONF_CONSUMER_KEY = "consumer_key"
CONF_CONSUMER_SECRET = "consumer_secret"
CONF_ACCESS_TOKEN_SECRET = "access_token_secret"
def get_service(hass, config):
2016-03-08 10:46:32 +00:00
"""Get the Twitter notification service."""
2016-01-21 01:02:32 +00:00
if not validate_config({DOMAIN: config},
{DOMAIN: [CONF_CONSUMER_KEY, CONF_CONSUMER_SECRET,
CONF_ACCESS_TOKEN,
CONF_ACCESS_TOKEN_SECRET]},
_LOGGER):
return None
return TwitterNotificationService(config[CONF_CONSUMER_KEY],
config[CONF_CONSUMER_SECRET],
config[CONF_ACCESS_TOKEN],
config[CONF_ACCESS_TOKEN_SECRET])
# pylint: disable=too-few-public-methods
class TwitterNotificationService(BaseNotificationService):
2016-03-08 10:46:32 +00:00
"""Implement notification service for the Twitter service."""
2016-01-21 01:02:32 +00:00
def __init__(self, consumer_key, consumer_secret, access_token_key,
access_token_secret):
2016-03-08 10:46:32 +00:00
"""Initialize the service."""
2016-01-21 01:02:32 +00:00
from TwitterAPI import TwitterAPI
self.api = TwitterAPI(consumer_key, consumer_secret, access_token_key,
access_token_secret)
def send_message(self, message="", **kwargs):
2016-03-08 10:46:32 +00:00
"""Tweet some message."""
2016-01-21 01:02:32 +00:00
resp = self.api.request('statuses/update', {'status': message})
if resp.status_code != 200:
import json
obj = json.loads(resp.text)
error_message = obj['errors'][0]['message']
error_code = obj['errors'][0]['code']
_LOGGER.error("Error %s : %s (Code %s)", resp.status_code,
error_message,
error_code)