Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error handlers #1240

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 48 additions & 11 deletions pyrogram/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
from pyrogram.handlers import (
CallbackQueryHandler, MessageHandler, EditedMessageHandler, DeletedMessagesHandler,
UserStatusHandler, RawUpdateHandler, InlineQueryHandler, PollHandler,
ChosenInlineResultHandler, ChatMemberUpdatedHandler, ChatJoinRequestHandler
ChosenInlineResultHandler, ChatMemberUpdatedHandler, ChatJoinRequestHandler,
ErrorHandler
)
from pyrogram.raw.types import (
UpdateNewMessage, UpdateNewChannelMessage, UpdateNewScheduledMessage,
Expand Down Expand Up @@ -62,6 +63,7 @@ def __init__(self, client: "pyrogram.Client"):

self.updates_queue = asyncio.Queue()
self.groups = OrderedDict()
self.error_handlers = []

async def message_parser(update, users, chats):
return (
Expand Down Expand Up @@ -163,6 +165,7 @@ async def stop(self):

self.handler_worker_tasks.clear()
self.groups.clear()
self.error_handlers.clear()

log.info("Stopped %s HandlerTasks", self.client.workers)

Expand All @@ -172,11 +175,15 @@ async def fn():
await lock.acquire()

try:
if group not in self.groups:
self.groups[group] = []
self.groups = OrderedDict(sorted(self.groups.items()))

self.groups[group].append(handler)
if isinstance(handler, ErrorHandler):
if handler not in self.error_handlers:
self.error_handlers.append(handler)
else:
if group not in self.groups:
self.groups[group] = []
self.groups = OrderedDict(sorted(self.groups.items()))

self.groups[group].append(handler)
finally:
for lock in self.locks_list:
lock.release()
Expand All @@ -189,10 +196,16 @@ async def fn():
await lock.acquire()

try:
if group not in self.groups:
raise ValueError(f"Group {group} does not exist. Handler was not removed.")
if isinstance(handler, ErrorHandler):
if handler not in self.error_handlers:
raise ValueError(f"Error handler {handler} does not exist. Handler was not removed.")

self.error_handlers.remove(handler)
else:
if group not in self.groups:
raise ValueError(f"Group {group} does not exist. Handler was not removed.")

self.groups[group].remove(handler)
self.groups[group].remove(handler)
finally:
for lock in self.locks_list:
lock.release()
Expand Down Expand Up @@ -250,8 +263,32 @@ async def handler_worker(self, lock):
except pyrogram.ContinuePropagation:
continue
except Exception as e:
log.exception(e)

handled_error = False
for error_handler in self.error_handlers:
try:
if await error_handler.check(self.client, e):
if inspect.iscoroutinefunction(error_handler.callback):
await error_handler.callback(self.client, e, *args)
else:
await self.loop.run_in_executor(
self.client.executor,
error_handler.callback,
self.client,
e,
*args
)
handled_error = True
break
except pyrogram.StopPropagation:
raise
except pyrogram.ContinuePropagation:
continue
except Exception as e:
log.exception(e)
continue

if not handled_error:
log.exception(e)
break
except pyrogram.StopPropagation:
pass
Expand Down
1 change: 1 addition & 0 deletions pyrogram/handlers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,4 @@
from .poll_handler import PollHandler
from .raw_update_handler import RawUpdateHandler
from .user_status_handler import UserStatusHandler
from .error_handler import ErrorHandler
64 changes: 64 additions & 0 deletions pyrogram/handlers/error_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from typing import Callable
import pyrogram
from .handler import Handler


class ErrorHandler(Handler):
"""The Error handler class. Used to handle errors.
It is intended to be used with :meth:`~pyrogram.Client.add_handler`

For a nicer way to register this handler, have a look at the
:meth:`~pyrogram.Client.on_message` decorator.

Parameters:
callback (``Callable``):
Pass a function that will be called when a new Error arrives. It takes *(client, error)*
as positional arguments (look at the section below for a detailed description).

errors (:obj:`Exception` | List of :obj:`Exception`):
Pass one or more exception classes to allow only a subset of errors to be passed
in your callback function.

Other parameters:
client (:obj:`~pyrogram.Client`):
The Client itself, useful when you want to call other API methods inside the message handler.

error (:obj:`~Exception`):
The error that was raised.

update (:obj:`~pyrogram.Update`):
The update that caused the error.
"""

def __init__(self, callback: Callable, errors=None):
if errors is None:
errors = [Exception]
else:
if not isinstance(errors, list):
errors = [errors]

self.errors = errors
super().__init__(callback)

async def check(self, client: "pyrogram.Client", error: Exception):
return any(isinstance(error, e) for e in self.errors)

def check_remove(self, error: Exception):
return self.errors == error or any(isinstance(error, e) for e in self.errors)
4 changes: 3 additions & 1 deletion pyrogram/methods/decorators/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from .on_poll import OnPoll
from .on_raw_update import OnRawUpdate
from .on_user_status import OnUserStatus
from .on_error import OnError


class Decorators(
Expand All @@ -42,6 +43,7 @@ class Decorators(
OnPoll,
OnChosenInlineResult,
OnChatMemberUpdated,
OnChatJoinRequest
OnChatJoinRequest,
OnError
):
pass
49 changes: 49 additions & 0 deletions pyrogram/methods/decorators/on_error.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.

from typing import Callable

import pyrogram
from pyrogram.filters import Filter


class OnError:
def on_error(self=None, errors=None) -> Callable:
"""Decorator for handling new errors.

This does the same thing as :meth:`~pyrogram.Client.add_handler` using the
:obj:`~pyrogram.handlers.MessageHandler`.

Parameters:
errors (:obj:`~Exception`, *optional*):
Pass one or more errors to allow only a subset of errors to be passed
in your function.
"""

def decorator(func: Callable) -> Callable:
if isinstance(self, pyrogram.Client):
self.add_handler(pyrogram.handlers.ErrorHandler(func, errors), 0)
elif isinstance(self, Filter) or self is None:
if not hasattr(func, "handlers"):
func.handlers = []

func.handlers.append((pyrogram.handlers.ErrorHandler(func, self), 0))

return func

return decorator
4 changes: 3 additions & 1 deletion pyrogram/methods/utilities/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,18 @@
from .start import Start
from .stop import Stop
from .stop_transmission import StopTransmission
from .remove_error_handler import RemoveErrorHandler


class Utilities(
AddHandler,
ExportSessionString,
RemoveHandler,
RemoveErrorHandler,
Restart,
Run,
Start,
Stop,
StopTransmission
StopTransmission,
):
pass
35 changes: 35 additions & 0 deletions pyrogram/methods/utilities/remove_error_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.

import pyrogram


class RemoveErrorHandler:
def remove_error_handler(
self: "pyrogram.Client",
error: "Exception | tuple[Exception]" = Exception
):
"""Remove a previously-registered error handler. (using exception classes)

Parameters:
error (``Exception``):
The error(s) for handlers to be removed.
"""
for handler in self.dispatcher.error_handlers:
if handler.check_remove(error):
self.dispatcher.error_handlers.remove(handler)