2022-02-24 16:27:55 +11:00
|
|
|
from dataclasses import dataclass, field, _MISSING_TYPE as mt
|
2022-08-09 20:36:16 +10:00
|
|
|
from asyncio import iscoroutinefunction
|
2022-02-24 16:27:55 +11:00
|
|
|
|
2022-08-09 20:36:16 +10:00
|
|
|
@dataclass
|
2022-02-24 16:27:55 +11:00
|
|
|
class Event():
|
2022-08-09 20:36:16 +10:00
|
|
|
event_type:str
|
|
|
|
data:Object=None
|
|
|
|
raw_data:dict=None
|
|
|
|
outbound:bool=False
|
2022-02-24 16:27:55 +11:00
|
|
|
|
|
|
|
class Listener():
|
2022-08-09 20:36:16 +10:00
|
|
|
def __init__(self,name,match,function):
|
2022-02-24 16:27:55 +11:00
|
|
|
self.name=name or function.__name__
|
|
|
|
self.match=match
|
|
|
|
self._matchstr=isinstance(match,str)
|
|
|
|
self.function=function
|
2022-08-09 20:36:16 +10:00
|
|
|
self._async=iscoroutinefunction(function)
|
2022-02-24 16:27:55 +11:00
|
|
|
|
2022-08-09 20:36:16 +10:00
|
|
|
async def __call__(self,*args,**kwargs):
|
|
|
|
if not self._async: return self.function(*args,**kwargs)
|
|
|
|
return await self.function(*args,**kwargs)
|
2022-02-24 16:27:55 +11:00
|
|
|
|
|
|
|
def __eq__(self,other):
|
2022-08-09 20:36:16 +10:00
|
|
|
if isinstance(other,Event):
|
|
|
|
if self._matchstr: return self.match==other.event_type
|
2022-02-24 16:27:55 +11:00
|
|
|
return self.match(other) # If it's not a string, assume it's a callable.
|
|
|
|
else: return super.__eq__(self,other)
|
|
|
|
def __str__(self): return self.name
|
|
|
|
|
|
|
|
def get_or_create(needle,haystack,default):
|
|
|
|
"""
|
|
|
|
This is a wrapper for filter that can add stuff. Nothing special. Needle is a function, default isn't. Haystack is a list. I might fix that later.
|
|
|
|
"""
|
|
|
|
f=filter(needle,haystack)
|
|
|
|
try: return next(f)
|
|
|
|
except StopIteration: pass
|
|
|
|
haystack.append(default)
|
|
|
|
return default
|