async def ws_event(self): from mirai.event.external.enums import ExternalEvents async with aiohttp.ClientSession() as session: async with session.ws_connect( f"{self.baseurl}/event?sessionKey={self.session_key}" ) as ws_connection: while True: try: received_data = await ws_connection.receive_json() except TypeError: continue if received_data: try: if hasattr(ExternalEvents, received_data['type']): received_data = \ ExternalEvents[received_data['type']] \ .value \ .parse_obj(received_data) else: raise exceptions.UnknownEvent( f"a unknown event has been received, it's '{received_data['type']}'") except pydantic.ValidationError: SessionLogger.error(f"parse failed: {received_data}") traceback.print_exc() else: await self.queue.put(InternalEvent( name=self.getEventCurrentName(type(received_data)), body=received_data ))
async def ws_message(self): async with aiohttp.ClientSession() as session: async with session.ws_connect( f"{self.baseurl}/message?sessionKey={self.session_key}" ) as ws_connection: while True: try: received_data = await ws_connection.receive_json() except TypeError: continue if received_data: NetworkLogger.debug("received", received_data) try: received_data[ 'messageChain'] = MessageChain.parse_obj( received_data['messageChain']) received_data = MessageTypes[ received_data['type']].parse_obj(received_data) except pydantic.ValidationError: SessionLogger.error( f"parse failed: {received_data}") traceback.print_exc() else: await self.queue.put( InternalEvent(name=self.getEventCurrentName( type(received_data)), body=received_data))
async def ws_event_receiver(self, exit_signal, queue): await self.checkWebsocket(force=True) async with aiohttp.ClientSession() as session: async with session.ws_connect( f"{self.baseurl}/all?sessionKey={self.session_key}" ) as ws_connection: while not exit_signal(): try: received_data = await ws_connection.receive_json() except TypeError: if not exit_signal(): continue else: break if received_data: try: if received_data['type'] in MessageTypes: if 'messageChain' in received_data: received_data['messageChain'] = \ MessageChain.parse_obj(received_data['messageChain']) received_data = \ MessageTypes[received_data['type']].parse_obj(received_data) elif hasattr(ExternalEvents, received_data['type']): # 判断当前项是否为 Event received_data = \ ExternalEvents[received_data['type']]\ .value\ .parse_obj(received_data) except pydantic.ValidationError: SessionLogger.error( f"parse failed: {received_data}") traceback.print_exc() else: await queue.put( InternalEvent(name=self.getEventCurrentName( type(received_data)), body=received_data))
async def main_entrance(self, run_body, event_context, queue): if isinstance(run_body, dict): callable_target = run_body['func'] for depend in run_body['dependencies']: if not inspect.isclass(depend.func): depend_func = depend.func elif hasattr(depend.func, "__call__"): depend_func = depend.func.__call__ else: raise TypeError("must be callable.") await self.main_entrance( { "func": depend_func, "middlewares": depend.middlewares, "dependencies": [] }, event_context, queue) else: if inspect.isclass(run_body): if hasattr(run_body, "__call__"): run_body = run_body.__call__ else: raise TypeError("must be callable.") else: callable_target = run_body translated_mapping = { **(await self.argument_compiler(callable_target, event_context)), **(await self.signature_checkout(callable_target, event_context, queue)) } try: if isinstance(run_body, dict): middlewares = run_body.get("middlewares") if middlewares: async_middlewares = [] normal_middlewares = [] for middleware in middlewares: if all([ hasattr(middleware, "__aenter__"), hasattr(middleware, "__aexit__") ]): async_middlewares.append(middleware) elif all([ hasattr(middleware, "__enter__"), hasattr(middleware, "__exit__") ]): normal_middlewares.append(middleware) else: SessionLogger.error( f"threw a exception by {event_context.name}, no currect context error." ) raise AttributeError( "no a currect context object.") async with contextlib.AsyncExitStack() as async_stack: for async_middleware in async_middlewares: SessionLogger.debug( f"a event called {event_context.name}, enter a currect async context." ) await async_stack.enter_async_context( async_middleware) with contextlib.ExitStack() as normal_stack: for normal_middleware in normal_middlewares: SessionLogger.debug( f"a event called {event_context.name}, enter a currect context." ) normal_stack.enter_context(normal_middleware) if inspect.iscoroutinefunction(callable_target): return await callable_target( **translated_mapping) else: return callable_target(**translated_mapping) else: if inspect.iscoroutinefunction(callable_target): return await callable_target(**translated_mapping) else: return callable_target(**translated_mapping) else: if inspect.iscoroutinefunction(callable_target): return await callable_target(**translated_mapping) else: return callable_target(**translated_mapping) except (NameError, TypeError) as e: EventLogger.error( f"threw a exception by {event_context.name}, it's about Annotations Checker, please report to developer." ) traceback.print_exc() except Exception as e: EventLogger.error( f"threw a exception by {event_context.name}, and it's {e}") await self.throw_exception_event(event_context, queue, e)