async def handle_websocket(websocket: WebSocket) -> None: await websocket.accept() botId = int(websocket.headers.get("x-self-id")) logger.info('Accepted client [{}] from [{}:{}]'.format( botId, websocket.client.host, websocket.client.port)) client_addr = "{}:{}".format(websocket.client.host, websocket.client.port) if not botId in drivers.keys(): alive_clients[client_addr] = botId driver_builder = app.driver_builder if driver_builder is None: driver_builder = pypbbot.driver.BaseDriver drivers[botId] = (websocket, driver_builder(botId)) else: _, dri = drivers[botId] drivers[botId] = (websocket, dri) while True: try: rawdata: bytes = await websocket.receive_bytes() frame = Frame() frame.ParseFromString(rawdata) await recv_frame(frame, botId) except WebSocketDisconnect: client_addr = "{}:{}".format(websocket.client.host, websocket.client.port) client_id: Union[str, int] = "UNKNOWN" if alive_clients[client_addr] != -1: client_id = alive_clients[client_addr] del drivers[client_id] logger.warning( 'Connection to [{}] has been closed, lost connection with [{}] ' .format(client_addr, client_id)) break
async def handle_shutdown(websocket: WebSocket) -> None: await websocket.accept() logger.warning("Being asked to shutdown by websocket trigger.") def self_terminate() -> None: asyncio.run(close()) time.sleep(1) parent = psutil.Process(psutil.Process(os.getpid()).ppid()) parent.kill() threading.Thread(target=self_terminate, daemon=True).start()
async def handle(self, event: Event) -> None: affair: BaseAffair if isinstance(event, PrivateMessageEvent) or isinstance( event, GroupMessageEvent): affair = ChatAffair(event) else: affair = BaseAffair(event) logger.warning('Handling [{}]'.format(affair)) for handler in _handlers.queue: affair_filter = handler._ftr if affair_filter(affair): await handler._func(affair)
def decorator( func: Callable[[BaseAffair], Coroutine[Any, Any, None]] ) -> Callable[[BaseAffair], Coroutine[Any, Any, None]]: # DO NOT USE LAMBDA EXPRESSION if not inspect.iscoroutinefunction(func): func = asyncify(func) logger.warning( "Function {} has been asyncified for being registered.".format( func.__name__)) _register(ftr, func, priority) @functools.wraps(func) def wrapper(affair: BaseAffair) -> Coroutine[Any, Any, None]: return func(affair) return wrapper
async def load_plugins(*plugin_dir: str) -> Dict[str, ModuleType]: for _dir in plugin_dir: _dir = os.path.abspath(_dir) if not os.path.exists(_dir): os.makedirs(_dir) for name in os.listdir(_dir): if name.endswith(".zip"): zippath = os.path.join(_dir, name) sys.path.append(zippath) module_names: set[str] = set() try: with zipfile.ZipFile(zippath) as zipmodule: for filename in zipmodule.namelist(): module_name = filename _pathsep = filename.find("/") if _pathsep != -1: module_name = filename[:_pathsep] module_names.add(module_name) except: logger.warning("Illegal zip file [{}]. Skipping ...", name) for module_name in module_names: logger.info('Loading module [{}] from [{}] ...'.format( module_name, name)) try: _loadedPlugins[name] = importlib.import_module( module_name) except: logger.warning( 'Failed to load [{}]. Possibly illegal module type.' .format(module_name)) for module_finder, name, _ in pkgutil.iter_modules(plugin_dir): logger.info('Loading module [{}] ...'.format(name)) if isinstance(module_finder, PathEntryFinder): # Hack for Type Check module = module_finder.find_module(name) elif isinstance(module_finder, MetaPathFinder): module = module_finder.find_module(name, None) # SourceFileLoader if module is not None: _loadedPlugins[name] = module.load_module(name) return _loadedPlugins