Skip to content

Commit

Permalink
Fix ExceptionHandler handle() method as async for async telebot
Browse files Browse the repository at this point in the history
issue #2070
  • Loading branch information
oalexandere committed Nov 8, 2023
1 parent bb2d8d9 commit 4314ea3
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 30 deletions.
19 changes: 8 additions & 11 deletions examples/asynchronous_telebot/exception_handler.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,25 @@
import logging

import telebot
from telebot.async_telebot import AsyncTeleBot


import logging
from telebot.async_telebot import AsyncTeleBot, ExceptionHandler

logger = telebot.logger
telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console.
telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console.

class ExceptionHandler(telebot.ExceptionHandler):
def handle(self, exception):
logger.error(exception)

bot = AsyncTeleBot('TOKEN',exception_handler=ExceptionHandler())
class MyExceptionHandler(ExceptionHandler):
async def handle(self, exception):
logger.error(exception)


bot = AsyncTeleBot('TOKEN', exception_handler=MyExceptionHandler())


@bot.message_handler(commands=['photo'])
async def photo_send(message: telebot.types.Message):
await bot.send_message(message.chat.id, 'Hi, this is an example of exception handlers.')
raise Exception('test') # Exception goes to ExceptionHandler if it is set
raise Exception('test') # Exception goes to ExceptionHandler if it is set



import asyncio
asyncio.run(bot.polling())
35 changes: 16 additions & 19 deletions telebot/async_telebot.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class ExceptionHandler:
"""

# noinspection PyMethodMayBeStatic,PyUnusedLocal
def handle(self, exception):
async def handle(self, exception):
return False


Expand Down Expand Up @@ -368,6 +368,16 @@ async def infinity_polling(self, timeout: Optional[int]=20, skip_pending: Option
if logger_level and logger_level >= logging.INFO:
logger.error("Break infinity polling")

async def _handle_exception(self, exception: Exception) -> bool:
if self.exception_handler is None:
return False

if iscoroutinefunction(self.exception_handler.handle):
await self.exception_handler.handle(exception)
else:
self.exception_handler.handle(exception) # noqa
return True

async def _process_polling(self, non_stop: bool=False, interval: int=0, timeout: int=20,
request_timeout: int=None, allowed_updates: Optional[List[str]]=None):
"""
Expand Down Expand Up @@ -415,11 +425,7 @@ async def _process_polling(self, non_stop: bool=False, interval: int=0, timeout:
except asyncio.CancelledError:
return
except asyncio_helper.RequestTimeout as e:
handled = False
if self.exception_handler:
self.exception_handler.handle(e)
handled = True

handled = await self._handle_exception(e)
if not handled:
logger.error('Unhandled exception (full traceback for debug level): %s', str(e))
logger.debug(traceback.format_exc())
Expand All @@ -430,11 +436,7 @@ async def _process_polling(self, non_stop: bool=False, interval: int=0, timeout:
else:
return
except asyncio_helper.ApiException as e:
handled = False
if self.exception_handler:
self.exception_handler.handle(e)
handled = True

handled = await self._handle_exception(e)
if not handled:
logger.error('Unhandled exception (full traceback for debug level): %s', str(e))
logger.debug(traceback.format_exc())
Expand All @@ -444,11 +446,7 @@ async def _process_polling(self, non_stop: bool=False, interval: int=0, timeout:
else:
break
except Exception as e:
handled = False
if self.exception_handler:
self.exception_handler.handle(e)
handled = True

handled = await self._handle_exception(e)
if not handled:
logger.error('Unhandled exception (full traceback for debug level): %s', str(e))
logger.debug(traceback.format_exc())
Expand Down Expand Up @@ -545,9 +543,8 @@ async def _run_middlewares_and_handlers(self, message, handlers, middlewares, up
break
except Exception as e:
handler_error = e
if self.exception_handler:
self.exception_handler.handle(e)
else:
handled = await self._handle_exception(e)
if not handled:
logger.error(str(e))
logger.debug("Exception traceback:\n%s", traceback.format_exc())

Expand Down

0 comments on commit 4314ea3

Please sign in to comment.