From 881d598098119e8130c9891d705e0af0adb71fbe Mon Sep 17 00:00:00 2001 From: mjk134 <57556877+mjk134@users.noreply.github.com> Date: Fri, 8 Jul 2022 21:55:05 +0000 Subject: Add `EventEmitter` + fix `User` constructor not being able to set key, values --- discord/utils/__init__.py | 1 + discord/utils/event_emitter.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 discord/utils/__init__.py create mode 100644 discord/utils/event_emitter.py (limited to 'discord/utils') 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)) -- cgit 1.4.1-2-gfad0