-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'liyihao1110:main' into main
- Loading branch information
Showing
7 changed files
with
125 additions
and
215 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
import asyncio | ||
import json | ||
|
||
import websockets | ||
|
||
from ncatbot.utils.config import config | ||
from ncatbot.utils.logger import get_log | ||
|
||
_log = get_log() | ||
|
||
|
||
class Websocket: | ||
def __init__(self, client): | ||
self.client = client | ||
self._websocket_uri = config.ws_uri + "/event" | ||
self._header = {"Content-Type": "application/json","Authorization": f"Bearer {config.token}"} if config.token else {"Content-Type": "application/json"} | ||
|
||
async def on_message(self, message: dict): | ||
if message["post_type"] == "message" or message["post_type"] == "message_sent": | ||
if message["message_type"] == "group": | ||
asyncio.create_task(self.client.handle_group_event(message)) | ||
elif message["message_type"] == "private": | ||
asyncio.create_task(self.client.handle_private_event(message)) | ||
else: | ||
_log.error("Unknown error: Unrecognized message type!Please check log info!") and _log.debug(message) | ||
elif message["post_type"] == "notice": | ||
asyncio.create_task(self.client.handle_notice_event(message)) | ||
elif message["post_type"] == "request": | ||
asyncio.create_task(self.client.handle_request_event(message)) | ||
elif message["post_type"] == "meta_event": | ||
if message["meta_event_type"] == "lifecycle": | ||
_log.info(f"机器人 {message.get('self_id')} 成功启动") | ||
else: | ||
_log.debug(message) | ||
else: | ||
_log.error("Unknown error: Unrecognized message type!Please check log info!") and _log.debug(message) | ||
|
||
async def on_error(self, error): | ||
_log.error(f"WebSocket 连接错误: {error}") | ||
|
||
async def on_close(self): | ||
_log.info("WebSocket 连接已关闭") | ||
|
||
async def on_connect(self): | ||
async with websockets.connect(uri=self._websocket_uri, extra_headers=self._header) as ws: | ||
# 我发现你们在client.py中已经进行了websocket连接的测试,故删除了此处不必要的错误处理。 | ||
while True: | ||
try: | ||
message = await ws.recv() | ||
message = json.loads(message) | ||
await self.on_message(message) | ||
# 这里的错误处理没有进行细分,我觉得没有很大的必要,报错的可能性不大,如果你对websocket了解很深,请完善此部分。 | ||
except Exception as e: | ||
await self.on_error(e) | ||
break | ||
await self.on_close() | ||
|
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import datetime | ||
import json as j | ||
|
||
import websockets | ||
|
||
from ncatbot.utils.config import config | ||
from ncatbot.utils.logger import get_log | ||
|
||
_log = get_log() | ||
|
||
async def check_websocket(uri): | ||
""" | ||
检查指定的 WebSocket uri 是否可用。 | ||
:return: 如果可用返回 True,否则返回 False | ||
""" | ||
try: | ||
async with websockets.connect(f"{uri}", extra_headers={"Content-Type": "application/json","Authorization": f"Bearer {config.token}"} if config.token else {"Content-Type": "application/json"}): | ||
_log.info(f"WebSocket {uri} 可用.") | ||
return True | ||
except Exception as e: | ||
_log.error(f"检查 WebSocket 端口时发生错误: {e}") | ||
return False | ||
|
||
class Route: | ||
""" | ||
路由类,用于处理 WebSocket 连接。 | ||
""" | ||
def __init__(self): | ||
self.url = config.ws_uri + "/api" | ||
self.headers = {"Content-Type": "application/json","Authorization": f"Bearer {config.token}"} if config.token else {"Content-Type": "application/json"} | ||
|
||
async def post(self, path, params=None, json=None): | ||
async with websockets.connect(self.url, extra_headers=self.headers) as ws: | ||
if params: | ||
await ws.send( | ||
j.dumps( | ||
{ | ||
"action": path.replace("/", ""), | ||
"params": params, | ||
"echo": int(datetime.datetime.now().timestamp()), | ||
} | ||
) | ||
) | ||
elif json: | ||
await ws.send( | ||
j.dumps( | ||
{ | ||
"action": path.replace("/", ""), | ||
"params": json, | ||
"echo": int(datetime.datetime.now().timestamp()), | ||
} | ||
) | ||
) | ||
return j.loads(await ws.recv()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.