Skip to content

Commit

Permalink
Merge branch 'liyihao1110:main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
Qi-Cao authored Feb 19, 2025
2 parents ecb09fb + 974c61e commit 9d033dd
Show file tree
Hide file tree
Showing 7 changed files with 125 additions and 215 deletions.
57 changes: 57 additions & 0 deletions ncatbot/conn/connect.py
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()

65 changes: 0 additions & 65 deletions ncatbot/conn/gateway.py

This file was deleted.

103 changes: 0 additions & 103 deletions ncatbot/conn/http.py

This file was deleted.

55 changes: 55 additions & 0 deletions ncatbot/conn/wsroute.py
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())
12 changes: 7 additions & 5 deletions ncatbot/core/api.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os
from typing import Union

from ncatbot.conn.http import Route, WsRoute
from ncatbot.conn.wsroute import Route
from ncatbot.core.message import (
At,
CustomMusic,
Expand All @@ -25,7 +25,6 @@

_log = get_log()


def check_and_log(result):
if result["status"] == REQUEST_SUCCESS:
_log.debug(result)
Expand All @@ -35,11 +34,14 @@ def check_and_log(result):


class BotAPI:
def __init__(self, use_ws: bool):
self.__message = []
self._http = WsRoute() if use_ws else Route()
def __init__(self):
self._http = Route()

async def _construct_forward_message(self, messages):
"""
:param messages: 消息列表
:return: 转发消息
"""
def decode_summary(report):
def decode_single_message(message):
if message["type"] == "text":
Expand Down
26 changes: 5 additions & 21 deletions ncatbot/core/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
import urllib
import urllib.parse

from ncatbot.conn.gateway import Websocket
from ncatbot.conn.http import check_websocket
from ncatbot.conn.connect import Websocket
from ncatbot.conn.wsroute import check_websocket
from ncatbot.core.api import BotAPI
from ncatbot.core.launcher import start_qq
from ncatbot.core.message import GroupMessage, PrivateMessage
Expand All @@ -30,14 +30,14 @@


class BotClient:
def __init__(self, use_ws=True, plugins_path="plugins"):
def __init__(self, plugins_path="plugins"):
if not config._updated:
_log.warning("没有主动设置配置项, 配置项将使用默认值")
time.sleep(0.8)
_log.info(config)
time.sleep(1.6)

self.api = BotAPI(use_ws)
self.api = BotAPI()
self._group_event_handlers = []
self._private_event_handlers = []
self._notice_event_handlers = []
Expand Down Expand Up @@ -104,7 +104,7 @@ def request_event(self, func):
async def run_async(self):
websocket_server = Websocket(self)
await self.plugin_sys.load_plugin(self.api)
await websocket_server.ws_connect()
await websocket_server.on_connect()

def run(self, reload=False, debug=False):
"""
Expand Down Expand Up @@ -171,7 +171,6 @@ def run(self, reload=False, debug=False):
exit(1)

# WebUI配置和连接等待逻辑...
http_enable = False if config.hp_uri == "" else True
ws_enable = False if config.ws_uri == "" else True
if platform.system() == "Linux":
config_path = "/opt/QQ/resources/app/app_launcher/napcat/config"
Expand All @@ -182,21 +181,6 @@ def run(self, reload=False, debug=False):
os.chdir(os.path.join(NAPCAT_DIR, "config"))
expected_data = {
"network": {
"httpServers": [
{
"name": "httpServer",
"enable": http_enable,
"port": int(urllib.parse.urlparse(config.hp_uri).port),
"host": str(urllib.parse.urlparse(config.hp_uri).hostname),
"enableCors": True,
"enableWebsocket": True,
"messagePostFormat": "array",
"token": (
str(config.token) if config.token is not None else ""
),
"debug": False,
}
],
"websocketServers": [
{
"name": "WsServer",
Expand Down
Loading

0 comments on commit 9d033dd

Please sign in to comment.