core/homeassistant/components/notify/telegram.py

115 lines
3.7 KiB
Python
Raw Normal View History

2015-10-09 12:04:29 +00:00
"""
Telegram platform for notify component.
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.telegram/
2015-10-09 12:04:29 +00:00
"""
import io
2015-10-09 12:04:29 +00:00
import logging
import urllib
import requests
from requests.auth import HTTPBasicAuth
2015-10-09 12:04:29 +00:00
from homeassistant.components.notify import (
ATTR_TITLE, ATTR_DATA, DOMAIN, BaseNotificationService)
2015-10-09 12:04:29 +00:00
from homeassistant.const import CONF_API_KEY
2016-02-19 05:27:50 +00:00
from homeassistant.helpers import validate_config
2015-10-09 12:04:29 +00:00
_LOGGER = logging.getLogger(__name__)
2015-10-26 20:11:24 +00:00
REQUIREMENTS = ['python-telegram-bot==5.0.0']
2015-10-09 12:04:29 +00:00
ATTR_PHOTO = "photo"
ATTR_FILE = "file"
ATTR_URL = "url"
ATTR_CAPTION = "caption"
ATTR_USERNAME = "username"
ATTR_PASSWORD = "password"
2015-10-09 12:04:29 +00:00
def get_service(hass, config):
2016-03-08 10:46:32 +00:00
"""Get the Telegram notification service."""
2015-11-09 06:15:34 +00:00
import telegram
2015-10-09 12:04:29 +00:00
2015-11-09 06:15:34 +00:00
if not validate_config({DOMAIN: config},
2015-10-09 12:04:29 +00:00
{DOMAIN: [CONF_API_KEY, 'chat_id']},
_LOGGER):
return None
try:
2015-11-09 06:15:34 +00:00
bot = telegram.Bot(token=config[CONF_API_KEY])
2015-10-09 12:04:29 +00:00
username = bot.getMe()['username']
2015-10-26 20:11:24 +00:00
_LOGGER.info("Telegram bot is '%s'.", username)
2015-10-09 12:04:29 +00:00
except urllib.error.HTTPError:
_LOGGER.error("Please check your access token.")
return None
2015-11-09 06:15:34 +00:00
return TelegramNotificationService(config[CONF_API_KEY], config['chat_id'])
2015-10-09 12:04:29 +00:00
# pylint: disable=too-few-public-methods
class TelegramNotificationService(BaseNotificationService):
2016-03-08 10:46:32 +00:00
"""Implement the notification service for Telegram."""
2015-10-09 12:04:29 +00:00
def __init__(self, api_key, chat_id):
2016-03-08 10:46:32 +00:00
"""Initialize the service."""
2015-11-09 06:15:34 +00:00
import telegram
2015-10-09 12:04:29 +00:00
self._api_key = api_key
self._chat_id = chat_id
self.bot = telegram.Bot(token=self._api_key)
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 telegram
2015-10-09 12:04:29 +00:00
title = kwargs.get(ATTR_TITLE)
data = kwargs.get(ATTR_DATA, {})
2015-10-09 12:04:29 +00:00
# send message
2015-10-26 20:11:24 +00:00
try:
self.bot.sendMessage(chat_id=self._chat_id,
text=title + " " + message)
except telegram.error.TelegramError:
2015-11-09 06:15:34 +00:00
_LOGGER.exception("Error sending message.")
return
# send photo
if ATTR_PHOTO in data:
# if not a list
if not isinstance(data[ATTR_PHOTO], list):
photos = [data[ATTR_PHOTO]]
else:
photos = data[ATTR_PHOTO]
try:
for photo_data in photos:
caption = photo_data.get(ATTR_CAPTION, None)
# file is a url
if ATTR_URL in photo_data:
# use http authenticate
if ATTR_USERNAME in photo_data and\
ATTR_PASSWORD in photo_data:
req = requests.get(
photo_data[ATTR_URL],
auth=HTTPBasicAuth(photo_data[ATTR_USERNAME],
photo_data[ATTR_PASSWORD])
)
else:
req = requests.get(photo_data[ATTR_URL])
file_id = io.BytesIO(req.content)
elif ATTR_FILE in photo_data:
file_id = open(photo_data[ATTR_FILE], "rb")
else:
_LOGGER.error("No url or path is set for photo!")
continue
self.bot.sendPhoto(chat_id=self._chat_id,
photo=file_id, caption=caption)
except (OSError, IOError, telegram.error.TelegramError,
urllib.error.HTTPError):
_LOGGER.exception("Error sending photo.")
return