From a83b61ad58384c561865b03ff24704be6e71c153 Mon Sep 17 00:00:00 2001 From: Fabian Affolter Date: Mon, 23 Jan 2017 22:24:45 +0100 Subject: [PATCH] Allow direct messaging to user (#5521) --- homeassistant/components/notify/twitter.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/homeassistant/components/notify/twitter.py b/homeassistant/components/notify/twitter.py index 24128edd880..5672429b9c6 100644 --- a/homeassistant/components/notify/twitter.py +++ b/homeassistant/components/notify/twitter.py @@ -11,7 +11,7 @@ import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.notify import ( PLATFORM_SCHEMA, BaseNotificationService) -from homeassistant.const import CONF_ACCESS_TOKEN +from homeassistant.const import CONF_ACCESS_TOKEN, CONF_USERNAME REQUIREMENTS = ['TwitterAPI==2.4.3'] @@ -22,10 +22,11 @@ CONF_CONSUMER_SECRET = 'consumer_secret' CONF_ACCESS_TOKEN_SECRET = 'access_token_secret' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ - vol.Required(CONF_CONSUMER_KEY): cv.string, - vol.Required(CONF_CONSUMER_SECRET): cv.string, vol.Required(CONF_ACCESS_TOKEN): cv.string, vol.Required(CONF_ACCESS_TOKEN_SECRET): cv.string, + vol.Required(CONF_CONSUMER_KEY): cv.string, + vol.Required(CONF_CONSUMER_SECRET): cv.string, + vol.Optional(CONF_USERNAME): cv.string, }) @@ -33,7 +34,8 @@ def get_service(hass, config, discovery_info=None): """Get the Twitter notification service.""" return TwitterNotificationService( config[CONF_CONSUMER_KEY], config[CONF_CONSUMER_SECRET], - config[CONF_ACCESS_TOKEN], config[CONF_ACCESS_TOKEN_SECRET] + config[CONF_ACCESS_TOKEN], config[CONF_ACCESS_TOKEN_SECRET], + config.get(CONF_USERNAME) ) @@ -41,15 +43,21 @@ class TwitterNotificationService(BaseNotificationService): """Implementation of a notification service for the Twitter service.""" def __init__(self, consumer_key, consumer_secret, access_token_key, - access_token_secret): + access_token_secret, username): """Initialize the service.""" from TwitterAPI import TwitterAPI + self.user = username self.api = TwitterAPI(consumer_key, consumer_secret, access_token_key, access_token_secret) def send_message(self, message="", **kwargs): - """Tweet some message.""" - resp = self.api.request('statuses/update', {'status': message}) + """Tweet a message.""" + if self.user: + resp = self.api.request( + 'direct_messages/new', {'text': message, 'user': self.user}) + else: + resp = self.api.request('statuses/update', {'status': message}) + if resp.status_code != 200: import json obj = json.loads(resp.text)