Home Assistant Unofficial Reference 2024.12.1
polling.py
Go to the documentation of this file.
1 """Support for Telegram bot using polling."""
2 
3 import logging
4 
5 from telegram import Update
6 from telegram.error import NetworkError, RetryAfter, TelegramError, TimedOut
7 from telegram.ext import ApplicationBuilder, CallbackContext, TypeHandler
8 
9 from homeassistant.const import EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP
10 
11 from . import BaseTelegramBotEntity
12 
13 _LOGGER = logging.getLogger(__name__)
14 
15 
16 async def async_setup_platform(hass, bot, config):
17  """Set up the Telegram polling platform."""
18  pollbot = PollBot(hass, bot, config)
19 
20  hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, pollbot.start_polling)
21  hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, pollbot.stop_polling)
22 
23  return True
24 
25 
26 async def process_error(update: Update, context: CallbackContext) -> None:
27  """Telegram bot error handler."""
28  if context.error:
29  error_callback(context.error, update)
30 
31 
32 def error_callback(error: Exception, update: Update | None = None) -> None:
33  """Log the error."""
34  try:
35  raise error
36  except (TimedOut, NetworkError, RetryAfter):
37  # Long polling timeout or connection problem. Nothing serious.
38  pass
39  except TelegramError:
40  if update is not None:
41  _LOGGER.error('Update "%s" caused error: "%s"', update, error)
42  else:
43  _LOGGER.error("%s: %s", error.__class__.__name__, error)
44 
45 
46 class PollBot(BaseTelegramBotEntity):
47  """Controls the Application object that holds the bot and an updater.
48 
49  The application is set up to pass telegram updates to `self.handle_update`
50  """
51 
52  def __init__(self, hass, bot, config):
53  """Create Application to poll for updates."""
54  super().__init__(hass, config)
55  self.botbot = bot
56  self.applicationapplication = ApplicationBuilder().bot(self.botbot).build()
57  self.applicationapplication.add_handler(TypeHandler(Update, self.handle_update))
58  self.applicationapplication.add_error_handler(process_error)
59 
60  async def start_polling(self, event=None):
61  """Start the polling task."""
62  _LOGGER.debug("Starting polling")
63  await self.applicationapplication.initialize()
64  await self.applicationapplication.updater.start_polling(error_callback=error_callback)
65  await self.applicationapplication.start()
66 
67  async def stop_polling(self, event=None):
68  """Stop the polling task."""
69  _LOGGER.debug("Stopping polling")
70  await self.applicationapplication.updater.stop()
71  await self.applicationapplication.stop()
72  await self.applicationapplication.shutdown()
None process_error(Update update, CallbackContext context)
Definition: polling.py:26
None error_callback(Exception error, Update|None update=None)
Definition: polling.py:32
def async_setup_platform(hass, bot, config)
Definition: polling.py:16