webui主页和插件管理api更新

This commit is contained in:
HibiKier
2024-01-06 17:36:22 +08:00
parent c146df3d25
commit a5bb1f768e
19 changed files with 711 additions and 579 deletions
+122 -8
View File
@@ -7,21 +7,26 @@ import nonebot
from fastapi import APIRouter, WebSocket
from nonebot.utils import escape_tag
from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState
from tortoise.functions import Count
from websockets.exceptions import ConnectionClosedError, ConnectionClosedOK
from configs.config import NICKNAME
from models.chat_history import ChatHistory
from models.group_info import GroupInfo
from models.statistics import Statistics
from services.log import logger
from utils.manager import plugin_data_manager, plugins2settings_manager, plugins_manager
from utils.manager.models import PluginData, PluginType
from ....config import QueryDateType
from ....base_model import Result
from ....config import QueryDateType
from ....utils import authentication, get_system_status
from .data_source import bot_live
from .model import BaseInfo
from .model import ActiveGroup, BaseInfo, ChatHistoryCount, HotPlugin
AVA_URL = "http://q1.qlogo.cn/g?b=qq&nk={}&s=160"
GROUP_AVA_URL = "http://p.qlogo.cn/gh/{}/{}/640/"
run_time = time.time()
ws_router = APIRouter()
@@ -34,7 +39,7 @@ async def _(bot_id: Optional[str] = None) -> Result:
获取Bot基础信息
Args:
qq (Optional[str], optional): qq号. Defaults to None.
bot_id (Optional[str], optional): bot_id. Defaults to None.
Returns:
Result: 获取指定bot信息与bot列表
@@ -43,20 +48,22 @@ async def _(bot_id: Optional[str] = None) -> Result:
if bots := nonebot.get_bots():
select_bot: BaseInfo
for key, bot in bots.items():
login_info = await bot.get_login_info()
bot_list.append(
BaseInfo(
bot=bot, # type: ignore
self_id=bot.self_id,
nickname=NICKNAME,
nickname=login_info["nickname"],
ava_url=AVA_URL.format(bot.self_id),
)
)
# 获取指定qq号的bot信息,若无指定则获取第一个
# 获取指定qq号的bot信息,若无指定 则获取第一个
if _bl := [b for b in bot_list if b.self_id == bot_id]:
select_bot = _bl[0]
else:
select_bot = bot_list[0]
select_bot.is_select = True
select_bot.config = select_bot.bot.config
now = datetime.now()
# 今日累计接收消息
select_bot.received_messages = await ChatHistory.filter(
@@ -78,11 +85,43 @@ async def _(bot_id: Optional[str] = None) -> Result:
)
# 连接时间
select_bot.connect_time = bot_live.get(select_bot.self_id) or 0
if select_bot.connect_time:
connect_date = datetime.fromtimestamp(select_bot.connect_time)
select_bot.connect_date = connect_date.strftime("%Y-%m-%d %H:%M:%S")
return Result.ok(bot_list, "已获取操作列表")
return Result.ok(bot_list, "拿到信息啦!")
return Result.warning_("无Bot连接...")
@router.get(
"/get_all_ch_count", dependencies=[authentication()], description="获取接收消息数量"
)
async def _(bot_id: str) -> Result:
now = datetime.now()
all_count = await ChatHistory.filter(bot_id=bot_id).count()
day_count = await ChatHistory.filter(
bot_id=bot_id, create_time__gte=now - timedelta(hours=now.hour)
).count()
week_count = await ChatHistory.filter(
bot_id=bot_id, create_time__gte=now - timedelta(days=7)
).count()
month_count = await ChatHistory.filter(
bot_id=bot_id, create_time__gte=now - timedelta(days=30)
).count()
year_count = await ChatHistory.filter(
bot_id=bot_id, create_time__gte=now - timedelta(days=365)
).count()
return Result.ok(
ChatHistoryCount(
num=all_count,
day=day_count,
week=week_count,
month=month_count,
year=year_count,
)
)
@router.get("/get_ch_count", dependencies=[authentication()], description="获取接收消息数量")
async def _(bot_id: str, query_type: Optional[QueryDateType] = None) -> Result:
if bots := nonebot.get_bots():
@@ -135,6 +174,81 @@ async def _() -> Result:
return Result.ok(int(time.time() - run_time))
@router.get("/get_active_group", dependencies=[authentication()], description="获取活跃群聊")
async def _(date_type: Optional[QueryDateType] = None) -> Result:
query = ChatHistory
now = datetime.now()
if date_type == QueryDateType.DAY:
query = ChatHistory.filter(create_time__gte=now - timedelta(hours=now.hour))
if date_type == QueryDateType.WEEK:
query = ChatHistory.filter(create_time__gte=now - timedelta(days=7))
if date_type == QueryDateType.MONTH:
query = ChatHistory.filter(create_time__gte=now - timedelta(days=30))
if date_type == QueryDateType.YEAR:
query = ChatHistory.filter(create_time__gte=now - timedelta(days=365))
data_list = (
await query.annotate(count=Count("id"))
.group_by("group_id").order_by("-count").limit(5)
.values_list("group_id", "count")
)
active_group_list = []
id2name = {}
if data_list:
if info_list := await GroupInfo.filter(group_id__in=[x[0] for x in data_list]).all():
for group_info in info_list:
id2name[group_info.group_id] = group_info.group_name
for data in data_list:
active_group_list.append(
ActiveGroup(
group_id=data[0],
name=id2name.get(data[0]) or data[0],
chat_num=data[1],
ava_img=GROUP_AVA_URL.format(data[0], data[0]),
)
)
active_group_list = sorted(
active_group_list, key=lambda x: x.chat_num, reverse=True
)
if len(active_group_list) > 5:
active_group_list = active_group_list[:5]
return Result.ok(active_group_list)
@router.get("/get_hot_plugin", dependencies=[authentication()], description="获取热门插件")
async def _(date_type: Optional[QueryDateType] = None) -> Result:
query = Statistics
now = datetime.now()
if date_type == QueryDateType.DAY:
query = Statistics.filter(create_time__gte=now - timedelta(hours=now.hour))
if date_type == QueryDateType.WEEK:
query = Statistics.filter(create_time__gte=now - timedelta(days=7))
if date_type == QueryDateType.MONTH:
query = Statistics.filter(create_time__gte=now - timedelta(days=30))
if date_type == QueryDateType.YEAR:
query = Statistics.filter(create_time__gte=now - timedelta(days=365))
data_list = (
await query.annotate(count=Count("id"))
.group_by("plugin_name").order_by("-count").limit(5)
.values_list("plugin_name", "count")
)
hot_plugin_list = []
for data in data_list:
name = data[0]
if plugin_data := plugin_data_manager.get(data[0]):
name = plugin_data.name
hot_plugin_list.append(
HotPlugin(
module=data[0],
name=name,
count=data[1],
)
)
hot_plugin_list = sorted(hot_plugin_list, key=lambda x: x.count, reverse=True)
if len(hot_plugin_list) > 5:
hot_plugin_list = hot_plugin_list[:5]
return Result.ok(hot_plugin_list)
@ws_router.websocket("/system_status")
async def system_logs_realtime(websocket: WebSocket):
await websocket.accept()
@@ -144,6 +258,6 @@ async def system_logs_realtime(websocket: WebSocket):
system_status = await get_system_status()
await websocket.send_text(system_status.json())
await asyncio.sleep(5)
except WebSocketDisconnect:
except (WebSocketDisconnect, ConnectionClosedError, ConnectionClosedOK):
pass
return
+1 -1
View File
@@ -3,7 +3,7 @@ from typing import Optional
import nonebot
from nonebot import Driver
from nonebot.adapters.onebot.v12 import Bot
from nonebot.adapters.onebot.v11 import Bot
driver: Driver = nonebot.get_driver()
+54
View File
@@ -1,4 +1,8 @@
from datetime import datetime
from typing import Optional, Union
from nonebot.adapters.onebot.v11 import Bot
from nonebot.config import Config
from pydantic import BaseModel
@@ -41,6 +45,8 @@ class BaseInfo(BaseModel):
# """一年内累计接受消息"""
connect_time: int = 0
"""连接时间"""
connect_date: Optional[datetime] = None
"""连接日期"""
plugin_count: int = 0
"""加载插件数量"""
@@ -52,5 +58,53 @@ class BaseInfo(BaseModel):
is_select: bool = False
"""当前选择"""
config: Optional[Config] = None
"""nb配置"""
class Config:
arbitrary_types_allowed = True
class ChatHistoryCount(BaseModel):
"""
聊天记录数量
"""
num: int
"""总数"""
day: int
"""一天内"""
week: int
"""一周内"""
month: int
"""一月内"""
year: int
"""一年内"""
class ActiveGroup(BaseModel):
"""
活跃群聊数据
"""
group_id: Union[str, int]
"""群组id"""
name: str
"""群组名称"""
chat_num: int
"""发言数量"""
ava_img: str
"""群组头像"""
class HotPlugin(BaseModel):
"""
热门插件
"""
module: str
"""模块名"""
name: str
"""插件名称"""
count: int
"""调用次数"""