2019-02-13 20:21:14 +00:00
|
|
|
"""Support for Telegram bots using webhooks."""
|
2017-05-10 04:42:17 +00:00
|
|
|
import datetime as dt
|
2021-09-22 18:59:52 +00:00
|
|
|
from http import HTTPStatus
|
2020-08-11 20:57:50 +00:00
|
|
|
from ipaddress import ip_address
|
2017-04-12 04:10:56 +00:00
|
|
|
import logging
|
|
|
|
|
2019-10-18 00:19:34 +00:00
|
|
|
from telegram.error import TimedOut
|
|
|
|
|
2017-04-12 04:10:56 +00:00
|
|
|
from homeassistant.components.http import HomeAssistantView
|
2021-09-22 18:59:52 +00:00
|
|
|
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
|
2020-05-08 19:53:28 +00:00
|
|
|
from homeassistant.helpers.network import get_url
|
2019-07-31 19:25:30 +00:00
|
|
|
|
|
|
|
from . import (
|
|
|
|
CONF_ALLOWED_CHAT_IDS,
|
|
|
|
CONF_TRUSTED_NETWORKS,
|
|
|
|
CONF_URL,
|
|
|
|
BaseTelegramBotEntity,
|
|
|
|
initialize_bot,
|
|
|
|
)
|
2019-03-21 05:56:46 +00:00
|
|
|
|
2017-04-12 04:10:56 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
TELEGRAM_HANDLER_URL = "/api/telegram_webhooks"
|
|
|
|
REMOVE_HANDLER_URL = ""
|
2017-04-12 04:10:56 +00:00
|
|
|
|
|
|
|
|
2018-10-01 06:56:50 +00:00
|
|
|
async def async_setup_platform(hass, config):
|
2017-05-02 16:18:47 +00:00
|
|
|
"""Set up the Telegram webhooks platform."""
|
2019-07-31 19:25:30 +00:00
|
|
|
|
2018-03-07 11:44:07 +00:00
|
|
|
bot = initialize_bot(config)
|
2017-04-12 04:10:56 +00:00
|
|
|
|
2020-10-16 11:29:28 +00:00
|
|
|
current_status = await hass.async_add_executor_job(bot.getWebhookInfo)
|
2021-09-02 17:17:33 +00:00
|
|
|
if not (base_url := config.get(CONF_URL)):
|
|
|
|
base_url = get_url(hass, require_ssl=True, allow_internal=False)
|
2017-05-10 04:42:17 +00:00
|
|
|
|
|
|
|
# Some logging of Bot current status:
|
2019-07-31 19:25:30 +00:00
|
|
|
last_error_date = getattr(current_status, "last_error_date", None)
|
2017-05-10 04:42:17 +00:00
|
|
|
if (last_error_date is not None) and (isinstance(last_error_date, int)):
|
|
|
|
last_error_date = dt.datetime.fromtimestamp(last_error_date)
|
2019-07-31 19:25:30 +00:00
|
|
|
_LOGGER.info(
|
2021-03-19 14:26:36 +00:00
|
|
|
"Telegram webhook last_error_date: %s. Status: %s",
|
2019-07-31 19:25:30 +00:00
|
|
|
last_error_date,
|
|
|
|
current_status,
|
|
|
|
)
|
2017-05-10 04:42:17 +00:00
|
|
|
else:
|
|
|
|
_LOGGER.debug("telegram webhook Status: %s", current_status)
|
2017-05-30 04:55:06 +00:00
|
|
|
|
2019-09-03 19:12:51 +00:00
|
|
|
handler_url = f"{base_url}{TELEGRAM_HANDLER_URL}"
|
2019-07-31 19:25:30 +00:00
|
|
|
if not handler_url.startswith("https"):
|
2017-05-23 17:16:54 +00:00
|
|
|
_LOGGER.error("Invalid telegram webhook %s must be https", handler_url)
|
|
|
|
return False
|
|
|
|
|
2017-07-30 09:14:28 +00:00
|
|
|
def _try_to_set_webhook():
|
|
|
|
retry_num = 0
|
|
|
|
while retry_num < 3:
|
|
|
|
try:
|
|
|
|
return bot.setWebhook(handler_url, timeout=5)
|
2019-10-18 00:19:34 +00:00
|
|
|
except TimedOut:
|
2017-07-30 09:14:28 +00:00
|
|
|
retry_num += 1
|
2019-07-31 19:25:30 +00:00
|
|
|
_LOGGER.warning("Timeout trying to set webhook (retry #%d)", retry_num)
|
2017-07-30 09:14:28 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
if current_status and current_status["url"] != handler_url:
|
2020-10-16 11:29:28 +00:00
|
|
|
result = await hass.async_add_executor_job(_try_to_set_webhook)
|
2017-05-10 04:42:17 +00:00
|
|
|
if result:
|
2017-05-02 16:18:47 +00:00
|
|
|
_LOGGER.info("Set new telegram webhook %s", handler_url)
|
2017-04-12 04:10:56 +00:00
|
|
|
else:
|
2017-05-02 16:18:47 +00:00
|
|
|
_LOGGER.error("Set telegram webhook failed %s", handler_url)
|
2017-04-24 06:20:04 +00:00
|
|
|
return False
|
|
|
|
|
2017-05-10 04:42:17 +00:00
|
|
|
hass.bus.async_listen_once(
|
2019-07-31 19:25:30 +00:00
|
|
|
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]
|
|
|
|
)
|
|
|
|
)
|
2017-04-24 06:20:04 +00:00
|
|
|
return True
|
2017-04-12 04:10:56 +00:00
|
|
|
|
|
|
|
|
|
|
|
class BotPushReceiver(HomeAssistantView, BaseTelegramBotEntity):
|
2017-05-02 20:47:20 +00:00
|
|
|
"""Handle pushes from Telegram."""
|
2017-04-12 04:10:56 +00:00
|
|
|
|
|
|
|
requires_auth = False
|
|
|
|
url = TELEGRAM_HANDLER_URL
|
2019-07-31 19:25:30 +00:00
|
|
|
name = "telegram_webhooks"
|
2017-04-12 04:10:56 +00:00
|
|
|
|
|
|
|
def __init__(self, hass, allowed_chat_ids, trusted_networks):
|
|
|
|
"""Initialize the class."""
|
|
|
|
BaseTelegramBotEntity.__init__(self, hass, allowed_chat_ids)
|
|
|
|
self.trusted_networks = trusted_networks
|
|
|
|
|
2018-10-01 06:56:50 +00:00
|
|
|
async def post(self, request):
|
2017-04-12 04:10:56 +00:00
|
|
|
"""Accept the POST from telegram."""
|
2020-08-11 20:57:50 +00:00
|
|
|
real_ip = ip_address(request.remote)
|
2017-04-12 04:10:56 +00:00
|
|
|
if not any(real_ip in net for net in self.trusted_networks):
|
|
|
|
_LOGGER.warning("Access denied from %s", real_ip)
|
2021-09-22 18:59:52 +00:00
|
|
|
return self.json_message("Access denied", HTTPStatus.UNAUTHORIZED)
|
2017-04-12 04:10:56 +00:00
|
|
|
|
|
|
|
try:
|
2018-10-01 06:56:50 +00:00
|
|
|
data = await request.json()
|
2017-04-12 04:10:56 +00:00
|
|
|
except ValueError:
|
2021-09-22 18:59:52 +00:00
|
|
|
return self.json_message("Invalid JSON", HTTPStatus.BAD_REQUEST)
|
2017-04-12 04:10:56 +00:00
|
|
|
|
|
|
|
if not self.process_message(data):
|
2021-09-22 18:59:52 +00:00
|
|
|
return self.json_message("Invalid message", HTTPStatus.BAD_REQUEST)
|
2018-10-28 18:39:23 +00:00
|
|
|
return None
|