From 2ebab890af6a1d63a032fccbfd1ac4fe7e66725b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wuyi=E6=97=A0=E7=96=91?= <444835641@qq.com> Date: Sun, 16 Apr 2023 19:47:21 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20=E4=BC=98=E5=8C=96=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E7=A8=B3=E5=AE=9A=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- GenshinUID/__init__.py | 10 ++++++++-- GenshinUID/client.py | 23 ++++++++++++++++++++--- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/GenshinUID/__init__.py b/GenshinUID/__init__.py index ae653c21..b1239ba3 100644 --- a/GenshinUID/__init__.py +++ b/GenshinUID/__init__.py @@ -1,6 +1,7 @@ from typing import List, Literal, Optional from hoshino import priv +from websockets.exceptions import ConnectionClosed from hoshino.typing import CQEvent, HoshinoBot, NoticeSession from .client import GsClient @@ -15,14 +16,19 @@ async def connect(): global gsclient try: gsclient = await GsClient().async_connect() - await gsclient.start() except ConnectionRefusedError: logger.error('Core服务器连接失败...请稍后使用[启动core]命令启动...') async def get_gs_msg(ev): - if gsclient is None or not gsclient.is_alive: + if gsclient is None: return await connect() + + try: + await gsclient.ws.ping() + except ConnectionClosed: + return await connect() + # 通用字段获取 user_id = str(ev.user_id) msg_id = str(ev.message_id) diff --git a/GenshinUID/client.py b/GenshinUID/client.py index 1d8f9f0a..0094b834 100644 --- a/GenshinUID/client.py +++ b/GenshinUID/client.py @@ -17,6 +17,8 @@ bots: Dict[str, str] = {} class GsClient: + _instance = None + @classmethod async def async_connect( cls, IP: str = 'localhost', PORT: Union[str, int] = '8765' @@ -30,8 +32,16 @@ class GsClient: ) logger.info(f'与[gsuid-core]成功连接! Bot_ID: {BOT_ID}') cls.msg_list = asyncio.queues.Queue() + cls.pending = [] + await self.start() return self + def __new__(cls, *args, **kwargs): + # 判断sv是否已经被初始化 + if cls._instance is None: + cls._instance = super(GsClient, cls).__new__(cls, *args, **kwargs) + return cls._instance + async def recv_msg(self): try: global bots @@ -100,8 +110,17 @@ class GsClient: except RuntimeError: pass except ConnectionClosedError: + for task in self.pending: + task.cancel() logger.warning(f'与[gsuid-core]断开连接! Bot_ID: {BOT_ID}') self.is_alive = False + for _ in range(30): + await asyncio.sleep(5) + try: + await self.async_connect() + break + except: # noqa + logger.debug('自动连接core服务器失败...五秒后重新连接...') async def _input(self, msg: MessageReceive): await self.msg_list.put(msg) @@ -115,12 +134,10 @@ class GsClient: async def start(self): recv_task = asyncio.create_task(self.recv_msg()) send_task = asyncio.create_task(self.send_msg()) - _, pending = await asyncio.wait( + _, self.pending = await asyncio.wait( [recv_task, send_task], return_when=asyncio.FIRST_COMPLETED, ) - for task in pending: - task.cancel() def to_json(msg: str, name: str, uin: int):