数据库中所有user_qq改名以及user_id和group_id改为字符串

This commit is contained in:
HibiKier
2023-05-22 20:56:42 +08:00
parent 0d3c6d8684
commit 848de7f4fe
68 changed files with 1103 additions and 645 deletions
+75
View File
@@ -0,0 +1,75 @@
from datetime import datetime, timedelta
from typing import List, Optional
import nonebot
from fastapi import APIRouter
from configs.config import Config
from models.chat_history import ChatHistory
from services.log import logger
from utils.manager import plugin_data_manager, plugins2settings_manager, plugins_manager
from utils.manager.models import PluginData, PluginType
from ..models.model import BotInfo, Result
from ..models.params import UpdateConfig, UpdatePlugin
from ..utils import authentication
AVA_URL = "http://q1.qlogo.cn/g?b=qq&nk={}&s=160"
router = APIRouter()
@router.get("/get_bot_info", dependencies=[authentication()])
async def _(self_id: Optional[str] = None) -> Result:
"""
获取Bot基础信息
Args:
qq (Optional[str], optional): qq号. Defaults to None.
Returns:
Result: 获取指定bot信息与bot列表
"""
bot_list: List[BotInfo] = []
if bots := nonebot.get_bots():
select_bot: BotInfo
for key, bot in bots.items():
bot_list.append(
BotInfo(
bot=bot, # type: ignore
self_id=bot.self_id,
nickname="可爱的小真寻",
ava_url=AVA_URL.format(bot.self_id),
)
)
if _bl := [b for b in bot_list if b.self_id == self_id]:
select_bot = _bl[0]
else:
select_bot = bot_list[0]
select_bot.is_select = True
now = datetime.now()
select_bot.received_messages = await ChatHistory.filter(
bot_id=int(select_bot.self_id)
).count()
select_bot.received_messages_day = await ChatHistory.filter(
bot_id=int(select_bot.self_id),
create_time__gte=now - timedelta(hours=now.hour),
).count()
select_bot.received_messages_week = await ChatHistory.filter(
bot_id=int(select_bot.self_id),
create_time__gte=now - timedelta(days=7),
).count()
select_bot.group_count = len(await select_bot.bot.get_group_list())
select_bot.friend_count = len(await select_bot.bot.get_friend_list())
for bot in bot_list:
bot.bot = None # type: ignore
# 插件加载数量
select_bot.plugin_count = len(plugins2settings_manager)
pm_data = plugins_manager.get_data()
select_bot.fail_plugin_count = len([pd for pd in pm_data if pm_data[pd].error])
select_bot.success_plugin_count = (
select_bot.plugin_count - select_bot.fail_plugin_count
)
return Result.ok(bot_list, "已获取操作列表")
return Result.fail("无Bot连接")
+1
View File
@@ -0,0 +1 @@
from .logs import *
+45
View File
@@ -0,0 +1,45 @@
import asyncio
import re
from typing import Awaitable, Callable, ClassVar, Dict, Generic, List, Set, TypeVar
from urllib.parse import urlparse
PATTERN = r"\x1b(\[.*?[@-~]|\].*?(\x07|\x1b\\))"
_T = TypeVar("_T")
LogListener = Callable[[_T], Awaitable[None]]
class LogStorage(Generic[_T]):
def __init__(self, rotation: float = 5 * 60):
self.count, self.rotation = 0, rotation
self.logs: Dict[int, str] = {}
self.listeners: Set[LogListener[str]] = set()
async def add(self, log: str):
log = re.sub(PATTERN, "", log)
log_split = log.split()
time = log_split[0] + " " + log_split[1]
level = log_split[2]
main = log_split[3]
type_ = None
log_ = " ".join(log_split[3:])
if "Calling API" in log_:
sp = log_.split("|")
type_ = sp[1]
log_ = "|".join(log_[1:])
data = {"time": time, "level": level, "main": main, "type": type_, "log": log_}
seq = self.count = self.count + 1
self.logs[seq] = log
asyncio.get_running_loop().call_later(self.rotation, self.remove, seq)
await asyncio.gather(
*map(lambda listener: listener(log), self.listeners),
return_exceptions=True,
)
return seq
def remove(self, seq: int):
del self.logs[seq]
return
LOG_STORAGE = LogStorage[str]()
+37
View File
@@ -0,0 +1,37 @@
from typing import List
from fastapi import APIRouter, WebSocket
from loguru import logger
from nonebot.utils import escape_tag, run_sync
from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState
from .log_manager import LOG_STORAGE
router = APIRouter()
@router.get("/logs", response_model=List[str])
async def system_logs_history(reverse: bool = False):
return LOG_STORAGE.list(reverse=reverse)
@router.websocket("/logs")
async def system_logs_realtime(websocket: WebSocket):
await websocket.accept()
async def log_listener(log: str):
await websocket.send_text(log)
LOG_STORAGE.listeners.add(log_listener)
try:
while websocket.client_state == WebSocketState.CONNECTED:
recv = await websocket.receive()
logger.trace(
f"{system_logs_realtime.__name__!r} received "
f"<e>{escape_tag(repr(recv))}</e>"
)
except WebSocketDisconnect:
pass
finally:
LOG_STORAGE.listeners.remove(log_listener)
return