core/homeassistant/components/notify/telegram.py

63 lines
1.8 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 logging
import urllib
from homeassistant.components.notify import (
2016-02-19 05:27:50 +00:00
ATTR_TITLE, 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==4.2.0']
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)
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.")