Allow multiple event types in the same handler

This commit is contained in:
Tulir Asokan 2023-06-29 15:44:46 +03:00
parent ed046bcbfe
commit 61f154876d
3 changed files with 11 additions and 7 deletions

View File

@ -72,7 +72,7 @@ class CommandHandler:
self.__mb_must_consume_args__: bool = True
self.__mb_arg_fallthrough__: bool = True
self.__mb_event_handler__: bool = True
self.__mb_event_type__: EventType = EventType.ROOM_MESSAGE
self.__mb_event_types__: set[EventType] = {EventType.ROOM_MESSAGE}
self.__mb_msgtypes__: Iterable[MessageType] = (MessageType.TEXT,)
self.__bound_copies__: Dict[Any, CommandHandler] = {}
self.__bound_instance__: Any = None
@ -95,7 +95,7 @@ class CommandHandler:
"must_consume_args",
"arg_fallthrough",
"event_handler",
"event_type",
"event_types",
"msgtypes",
]
for key in keys:
@ -315,7 +315,7 @@ def new(
func.__mb_require_subcommand__ = require_subcommand
func.__mb_arg_fallthrough__ = arg_fallthrough
func.__mb_must_consume_args__ = must_consume_args
func.__mb_event_type__ = event_type
func.__mb_event_types__ = {event_type}
if msgtypes:
func.__mb_msgtypes__ = msgtypes
return func

View File

@ -27,9 +27,12 @@ def on(var: EventType | InternalEventType | EventHandler) -> EventHandlerDecorat
def decorator(func: EventHandler) -> EventHandler:
func.__mb_event_handler__ = True
if isinstance(var, (EventType, InternalEventType)):
func.__mb_event_type__ = var
if hasattr(func, "__mb_event_types__"):
func.__mb_event_types__.add(var)
else:
func.__mb_event_types__ = {var}
else:
func.__mb_event_type__ = EventType.ALL
func.__mb_event_types__ = {EventType.ALL}
return func

View File

@ -76,8 +76,9 @@ class Plugin(ABC):
val = getattr(obj, key)
try:
if val.__mb_event_handler__:
self._handlers_at_startup.append((val, val.__mb_event_type__))
self.client.add_event_handler(val.__mb_event_type__, val)
for event_type in val.__mb_event_types__:
self._handlers_at_startup.append((val, event_type))
self.client.add_event_handler(event_type, val)
except AttributeError:
pass
try: