diff options
Diffstat (limited to 'discord/utils')
-rw-r--r-- | discord/utils/__init__.py | 1 | ||||
-rw-r--r-- | discord/utils/event_emitter.py | 29 |
2 files changed, 30 insertions, 0 deletions
diff --git a/discord/utils/__init__.py b/discord/utils/__init__.py new file mode 100644 index 0000000..7fdb52b --- /dev/null +++ b/discord/utils/__init__.py @@ -0,0 +1 @@ +from .event_emitter import * \ No newline at end of file diff --git a/discord/utils/event_emitter.py b/discord/utils/event_emitter.py new file mode 100644 index 0000000..77fff72 --- /dev/null +++ b/discord/utils/event_emitter.py @@ -0,0 +1,29 @@ +import asyncio +from types import NoneType +from typing import Coroutine + +class EventEmitter(): + def __init__(self): + self.listeners = {} + + def add_listener(self, event_name: str, func: Coroutine): + if not self.listeners.get(event_name, None): + self.listeners[event_name] = {func} + else: + self.listeners[event_name].add(func) + + def remove_listener(self, event_name: str, func: Coroutine): + self.listeners[event_name].remove(func) + if len(self.listeners[event_name]) == 0: + del self.listeners[event_name] + + def emit(self, event_name: str, args_required=False, *args, **kwargs): + listeners = self.listeners.get(event_name, []) + for func in listeners: + if args_required: + if len(args) == 0: + raise TypeError('event registered must have arguments') + else: + asyncio.create_task(func(*args, **kwargs)) + else: + asyncio.create_task(func(*args, **kwargs)) |