Skip to content
This repository has been archived by the owner on Mar 4, 2023. It is now read-only.

Commit

Permalink
✨增加ws重连,增加ws操作指令
Browse files Browse the repository at this point in the history
  • Loading branch information
JustUndertaker committed Jan 24, 2022
1 parent 53dd1cf commit efbe91c
Show file tree
Hide file tree
Showing 4 changed files with 142 additions and 5 deletions.
69 changes: 67 additions & 2 deletions src/managers/server_manager/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,25 @@

from nonebot import get_driver
from nonebot.adapters.onebot.v11 import Bot
from nonebot.plugin import on
from nonebot.adapters.onebot.v11.event import PrivateMessageEvent
from nonebot.permission import SUPERUSER
from nonebot.plugin import on, on_regex
from src.utils.browser import browser
from src.utils.log import logger
from src.utils.utils import GroupList_Async
from tortoise import Tortoise

from . import data_source as source
from ._email import mail_client
from ._jx3_event import RecvEvent
from ._jx3_event import RecvEvent, WsClosed
from ._websocket import ws_client

driver = get_driver()

# ----------------------------------------------------------------
# bot服务的各种hook
# ----------------------------------------------------------------


@driver.on_bot_connect
async def _(bot: Bot):
Expand Down Expand Up @@ -78,11 +84,53 @@ async def _():
await ws_client.close()
logger.info("<g>ws链接关闭成功。</g>")

# ----------------------------------------------------------------
# server操作的几个mathcer
# ----------------------------------------------------------------
check_ws = on_regex(pattern=r"^查看连接$", permission=SUPERUSER, priority=5, block=True)
connect_ws = on_regex(pattern=r"^连接服务$", permission=SUPERUSER, priority=5, block=True)
close_ws = on_regex(pattern=r"^关闭连接$", permission=SUPERUSER, priority=5, block=True)


@check_ws.handle()
async def _(bot: Bot, event: PrivateMessageEvent):
'''查看连接'''
if ws_client.closed:
msg = "jx3api > ws连接已关闭!"
else:
msg = "jx3api > ws连接正常!"
await check_ws.finish(msg)


@connect_ws.handle()
async def _(bot: Bot, event: PrivateMessageEvent):
'''连接服务器'''
if ws_client.closed:
msg = "正在连接ws服务器……"
await connect_ws.send(msg)
flag, req = await ws_client.init()
if flag:
msg = "连接成功!ws服务器已连接。"
else:
msg = f"连接失败:{req}!"
await connect_ws.finish(msg)
else:
msg = "ws服务器当前已连接,不要重复连接!"
await connect_ws.finish(msg)


@close_ws.handle()
async def _(bot: Bot, event: PrivateMessageEvent):
'''关闭连接'''
await ws_client.close()
await close_ws.finish("ws连接已关闭!")

# ----------------------------------------------------------------
# ws消息事件处理
# ----------------------------------------------------------------

ws_recev = on(type="WsRecv", priority=4, block=True)
ws_closed = on(type="WsClosed", priority=4, block=True)


@ws_recev.handle()
Expand All @@ -105,3 +153,20 @@ async def _(bot: Bot, event: RecvEvent):
except Exception:
pass
await ws_recev.finish()


@ws_closed.handle()
async def _(bot: Bot, event: WsClosed):
'''ws关闭事件'''
superusers = list(bot.config.superusers)
msg = f"检测到ws链接关闭:{event.reason}\n正在重连……"
async for user_id in GroupList_Async(superusers):
await bot.send_private_msg(user_id=user_id, message=msg)
flag, req = await ws_client.init()
if flag:
msg = "ws重连成功!"
else:
msg = f"ws链接失败:{req}!"
async for user_id in GroupList_Async(superusers):
await bot.send_private_msg(user_id=user_id, message=msg)
await ws_closed.finish()
49 changes: 49 additions & 0 deletions src/managers/server_manager/_jx3_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,55 @@
from nonebot.utils import escape_tag


class WsClosed(BaseEvent):
'''ws被关闭事件'''
__event__ = "WsClosed"
post_type: str = "WsClosed"
reason: Optional[str]
'''关闭原因'''

def __init__(self, reason: str):
super().__init__()
self.reason = reason

@property
def log(self) -> str:
'''事件日志内容'''
return ""

@overrides(BaseEvent)
def get_type(self) -> str:
return self.post_type

@overrides(BaseEvent)
def get_event_name(self) -> str:
return self.post_type

@overrides(BaseEvent)
def get_event_description(self) -> str:
return escape_tag(str(self.dict()))

@overrides(BaseEvent)
def get_message(self) -> Message:
raise ValueError("Event has no message!")

@overrides(BaseEvent)
def get_plaintext(self) -> str:
raise ValueError("Event has no message!")

@overrides(BaseEvent)
def get_user_id(self) -> str:
raise ValueError("Event has no message!")

@overrides(BaseEvent)
def get_session_id(self) -> str:
raise ValueError("Event has no message!")

@overrides(BaseEvent)
def is_tome(self) -> bool:
return False


class RecvEvent(BaseEvent):
'''ws推送事件基类'''
__event__ = "WsRecv"
Expand Down
17 changes: 14 additions & 3 deletions src/managers/server_manager/_websocket.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import json
from typing import Tuple

import websockets
from nonebot import get_bots
Expand All @@ -9,7 +10,7 @@
from websockets.exceptions import ConnectionClosedOK
from websockets.legacy.client import WebSocketClientProtocol

from ._jx3_event import ws_event_factory
from ._jx3_event import WsClosed, ws_event_factory


class Jx3WebSocket(object):
Expand Down Expand Up @@ -51,6 +52,15 @@ async def _task(self):
except Exception as e:
logger.error(
f"<r>jx3api > ws链接被关闭:{str(e)}</r>")
await self._raise_closed(str(e))

async def _raise_closed(self, reason: str):
'''处理关闭事件'''
event = WsClosed(reason)
bots = get_bots()
for _, one_bot in bots.items():
await handle_event(one_bot, event)
break # 只发送一次

async def _handle_msg(self, message: str):
'''处理回复数据'''
Expand Down Expand Up @@ -82,7 +92,7 @@ def _to_bool(string: str) -> bool:
except Exception:
pass

async def init(self):
async def init(self) -> Tuple[bool, str]:
'''初始化'''
ws_path: str = config.jx3api['ws_path']
ws_token = config.jx3api['ws_token']
Expand All @@ -97,10 +107,11 @@ async def init(self):
ping_timeout=20,
close_timeout=10)
asyncio.create_task(self._task())

return True, ""
except Exception as e:
logger.error(
f"<r>链接到ws服务器时发生错误:{str(e)}</r>")
return False, str(e)

async def close(self):
'''关闭ws链接'''
Expand Down
12 changes: 12 additions & 0 deletions template/super_help.html
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,18 @@ <h4 class="text-center text-success">超级用户帮助</h2>
<td>全体广播 [<span class="text-danger">消息内容</span>]</td>
<td>发送全体广播</td>
</tr>
<tr>
<td>查看连接</td>
<td>查看当前ws连接状态</td>
</tr>
<tr>
<td>连接服务</td>
<td>主动连接ws服务器</td>
</tr>
<tr>
<td>关闭连接</td>
<td>主动关闭ws服务器</td>
</tr>

</tbody>
</table>
Expand Down

0 comments on commit efbe91c

Please sign in to comment.