I don't need that anymore

This commit is contained in:
Zergling_man 2022-08-18 03:46:07 +10:00
parent 9dd3b82bf8
commit 667fb2bd4f
4 changed files with 49 additions and 48 deletions

View File

@ -13,35 +13,33 @@ tracing=False
def trace(*msg): def trace(*msg):
if tracing: print(datetime.datetime.now(),*msg) if tracing: print(datetime.datetime.now(),*msg)
class ChatClient(): event_queue=asyncio.Queue() #Contains Events. Everything in here must be an Event.
def __init__(self,homeserver,token): listeners=[] # These respond to events. They're executed by workers processing the event queue. They should all be Listeners
self.event_queue=asyncio.Queue() #Contains Events. Everything in here must be an Event. timers=[] # These just execute on a schedule. That schedule can be "as soon as it exits". Should all be Timers, which include the property of whether to wait for exit before starting the next call or not (rarely relevant, so defaults to "no").
self.listeners=[]
self.timers=[] def addlistener(name=None,match=None):
if isinstance(name,func) and match==None: match=name; name=None
def addlistener(self,name=None,match=None): def __wrap__(funky):
if isinstance(name,func) and match==None: match=name; name=None self.listeners.append(Listener(name,match,funky))
def __wrap__(funky): return funky
self.listeners.append(Listener(name,match,funky))
return funky def loop(timer=0):
def _loop(funky):
def loop(timer=0): @functools.wraps(funky)
def _loop(funky): async def _wrapper(*args,**kwargs):
@functools.wraps(funky) while True:
async def _wrapper(*args,**kwargs): try: await funky(*args,**kwargs)
while True: except Exception: open('error '+str(datetime.datetime.now()),'w').write(traceback.format_exc())
try: await funky(*args,**kwargs) await asyncio.sleep(timer)
except Exception: open('error '+str(datetime.datetime.now()),'w').write(traceback.format_exc()) timers.append(_wrapper)
await asyncio.sleep(timer) return _wrapper
self.timers.append(_wrapper) return _loop
return _wrapper
return _loop async def process_queue():
item=await event_queue.get():
async def process_queue(self): for listener in listeners:
item=await self.event_queue.get(): if listener==item:
for listener in self.listeners: await listener(item)
if listener==item:
await listener(item)
@dataclass @dataclass
class Event(): class Event():

View File

@ -7,4 +7,7 @@ The whole bot will be synchronous. However, all network/disk/DB/etc., basically
Raw events will not be exposed, only processed events. This is not a "you have full control" framework. This is a clean, unified, easy-to-use framework. Raw events will not be exposed, only processed events. This is not a "you have full control" framework. This is a clean, unified, easy-to-use framework.
https://spec.matrix.org https://spec.matrix.org
https://www.matrix.org/docs/develop/ https://www.matrix.org/docs/develop/
Main chat lib defines API - is NOT a class, the module itself is a singleton
Specific proto libs are classes, instansiate with the module + account info, it'll hook itself into the module. For convenience, if the module isn't provided they'll do it themselves, and provide a .run() wrapper. If that's used with a provided module (set a flag), they emit a warning.

View File

@ -1,5 +1,18 @@
async def request(self,endpoint='sync',method='GET', ver=0,headers={} *args,**kwargs): class MatrixLibHttp():
async with self.session.request(method, f'{self.baseurl}/r{ver}/{endpoint}', headers=headers|{'Authorization':f'Bearer {self.token}'}, *args,**kwargs) as fetched: def __init__(self,instance,token=None,username=None,password=None,chatlib=None):
if fetched.status_code!=200: raise Exception('fix ur shit') self.instance=instance
try: return await fetched.json() self.https=True
except JSONDecodeError: pass # TODO: Figure out what this is called self.token=token
if chatlib is None:
import chatlib
chatlib.addlistener() # TODO: probably should make that a decorator actually. Lol, it already is.
@property
def baseurl(self):
return 'http'+['','s'][self.https]+'://'+self.instance+'/_matrix/client'
async def request(self,endpoint='sync',method='GET', ver=0,headers={}, *args,**kwargs):
async with self.session.request(method, f'{self.baseurl}/r{ver}/{endpoint}', headers=headers|{'Authorization':f'Bearer {self.token}'}, *args,**kwargs) as fetched:
if fetched.status_code!=200: raise Exception('fix ur shit')
try: return await fetched.json()
except JSONDecodeError: pass # TODO: Figure out what this is called

View File

@ -1,13 +0,0 @@
from .chatlib import *
import .listeners
real_listeners=dict(filter(lambda x:isinstance(x,Listener),listeners.__dict__.items()))
class MatrixClient(MatrixClient):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.listeners=real_listeners
self.homeserver=homeserver
self.token=token # Deal with login stuff later
self.baseurl=f'https://{self.homeserver}/_matrix/client'
self.session=ah.ClientSession()
self.since=None