2022-01-28 13:34:16 +03:00
|
|
|
import abc
|
2022-01-28 16:12:32 +03:00
|
|
|
import functools
|
2018-09-22 13:51:58 +03:00
|
|
|
|
2022-01-28 22:21:15 +03:00
|
|
|
from .filters import Filter
|
|
|
|
|
2018-09-22 13:51:58 +03:00
|
|
|
|
2018-02-27 13:30:42 +03:00
|
|
|
class StopPropagation(Exception):
|
|
|
|
"""
|
2018-03-21 10:55:13 +03:00
|
|
|
If this exception is raised in any of the handlers for a given event,
|
|
|
|
it will stop the execution of all other registered event handlers.
|
|
|
|
It can be seen as the ``StopIteration`` in a for loop but for events.
|
2018-02-27 13:30:42 +03:00
|
|
|
|
|
|
|
Example usage:
|
2018-09-22 13:51:58 +03:00
|
|
|
|
2018-04-05 21:14:22 +03:00
|
|
|
>>> from telethon import TelegramClient, events
|
|
|
|
>>> client = TelegramClient(...)
|
|
|
|
>>>
|
2018-03-21 10:55:13 +03:00
|
|
|
>>> @client.on(events.NewMessage)
|
2018-07-08 16:11:10 +03:00
|
|
|
... async def delete(event):
|
|
|
|
... await event.delete()
|
2018-03-21 10:55:13 +03:00
|
|
|
... # No other event handler will have a chance to handle this event
|
|
|
|
... raise StopPropagation
|
|
|
|
...
|
|
|
|
>>> @client.on(events.NewMessage)
|
2018-07-08 16:11:10 +03:00
|
|
|
... async def _(event):
|
2018-03-21 10:55:13 +03:00
|
|
|
... # Will never be reached, because it is the second handler
|
|
|
|
... pass
|
2018-02-27 13:30:42 +03:00
|
|
|
"""
|
2018-03-21 10:55:13 +03:00
|
|
|
# For some reason Sphinx wants the silly >>> or
|
|
|
|
# it will show warnings and look bad when generated.
|
|
|
|
pass
|
2018-09-22 13:51:58 +03:00
|
|
|
|
|
|
|
|
2022-01-28 13:34:16 +03:00
|
|
|
class EventBuilder(abc.ABC):
|
|
|
|
@classmethod
|
|
|
|
@abc.abstractmethod
|
|
|
|
def _build(cls, update, others, self_id, entities, client):
|
|
|
|
"""
|
|
|
|
Builds an event for the given update if possible, or returns None.
|
2018-09-22 13:51:58 +03:00
|
|
|
|
2022-01-28 13:34:16 +03:00
|
|
|
`others` are the rest of updates that came in the same container
|
|
|
|
as the current `update`.
|
2018-09-22 13:51:58 +03:00
|
|
|
|
2022-01-28 13:34:16 +03:00
|
|
|
`self_id` should be the current user's ID, since it is required
|
|
|
|
for some events which lack this information but still need it.
|
|
|
|
"""
|
2022-01-28 16:12:32 +03:00
|
|
|
|
|
|
|
|
|
|
|
@functools.total_ordering
|
|
|
|
class EventHandler:
|
|
|
|
__slots__ = ('_event', '_callback', '_priority', '_filter')
|
|
|
|
|
2022-01-28 22:21:15 +03:00
|
|
|
def __init__(self, event: EventBuilder, callback: callable, priority: int, filter: Filter):
|
2022-01-28 16:12:32 +03:00
|
|
|
self._event = event
|
|
|
|
self._callback = callback
|
|
|
|
self._priority = priority
|
|
|
|
self._filter = filter
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
return self is other
|
|
|
|
|
|
|
|
def __lt__(self, other):
|
|
|
|
return self._priority < other._priority
|
|
|
|
|
|
|
|
def __call__(self, *args, **kwargs):
|
|
|
|
return self._callback(*args, **kwargs)
|