Fix telegram webhooks (#7236)

* Always register the view if a webhook exists.
* Return True if platform is set up succesfully, False otherwise.
* Remove the webhook when home assistant stops. Webhooks and long
  polling are mutually excklusive. If a webhook is left after home
  assistant is stopped, a polling telegram bot is unable to be set up,
  on next start of home assistant.
This commit is contained in:
Martin Hjelmare authored and Paulus Schoutsen committed 2017-04-23 23:20:04 -07:00
1 parent 6a8a656fef
commit 0e662c4007
2 files changed
+18 -19

No files matched your search

@@ -11,9 +11,8 @@ from ipaddress import ip_network
import voluptuous as vol
from homeassistant.const import (
HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED)
EVENT_HOMEASSISTANT_STOP, HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED)
import homeassistant.helpers.config_validation as cv
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.telegram_bot import CONF_ALLOWED_CHAT_IDS, \
@@ -27,6 +26,7 @@ REQUIREMENTS = ['python-telegram-bot==5.3.0']
_LOGGER = logging.getLogger(__name__)
TELEGRAM_HANDLER_URL = '/api/telegram_webhooks'
REMOVE_HANDLER_URL = ''
CONF_TRUSTED_NETWORKS = 'trusted_networks'
DEFAULT_TRUSTED_NETWORKS = [
@@ -50,20 +50,21 @@ def setup_platform(hass, config, async_add_devices, discovery_info=None):
bot = telegram.Bot(config[CONF_API_KEY])
current_status = bot.getWebhookInfo()
handler_url = "{0}{1}".format(hass.config.api.base_url,
TELEGRAM_HANDLER_URL)
handler_url = '{0}{1}'.format(
hass.config.api.base_url, TELEGRAM_HANDLER_URL)
if current_status and current_status['url'] != handler_url:
if bot.setWebhook(handler_url):
_LOGGER.info("set new telegram webhook %s", handler_url)
hass.http.register_view(
BotPushReceiver(
hass,
config[CONF_ALLOWED_CHAT_IDS],
config[CONF_TRUSTED_NETWORKS]))
else:
_LOGGER.error("set telegram webhook failed %s", handler_url)
return False
hass.bus.listen_once(
EVENT_HOMEASSISTANT_STOP,
lambda event: bot.setWebhook(REMOVE_HANDLER_URL))
hass.http.register_view(BotPushReceiver(
hass, config[CONF_ALLOWED_CHAT_IDS], config[CONF_TRUSTED_NETWORKS]))
return True
class BotPushReceiver(HomeAssistantView, BaseTelegramBotEntity):
@@ -71,7 +72,7 @@ class BotPushReceiver(HomeAssistantView, BaseTelegramBotEntity):
requires_auth = False
url = TELEGRAM_HANDLER_URL
name = "telegram_webhooks"
name = 'telegram_webhooks'
def __init__(self, hass, allowed_chat_ids, trusted_networks):
"""Initialize the class."""