diff options
author | mjk134 <57556877+mjk134@users.noreply.github.com> | 2022-07-08 21:55:05 +0000 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-07-08 21:55:05 +0000 |
commit | 881d598098119e8130c9891d705e0af0adb71fbe (patch) | |
tree | da94d5b4f8900dd08f8cf0ff2bd6dd3e586ecd11 /discord/utils | |
parent | 39bdd5e8089bd337bf775ca2ca574f1934662ba2 (diff) | |
download | discobra-881d598098119e8130c9891d705e0af0adb71fbe.tar.gz |
Add `EventEmitter` + fix `User` constructor not being able to set key, values
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)) |