feat(api): 新增消息统计API端点
将原有的获取最近消息的API替换为功能更强大的消息统计API。 新的 `/messages/recent` 端点允许按天数和消息类型(发送、接收或全部)查询机器人的消息数量统计。 - 支持 `days` 和 `message_type` 查询参数。 - 实现统计逻辑,区分机器人发送和接收的消息。 - 增加异常处理,提高API的健壮性。
This commit is contained in:
@@ -1,13 +1,48 @@
|
|||||||
from fastapi import APIRouter
|
import time
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Query
|
||||||
|
|
||||||
|
from src.config.config import global_config
|
||||||
from src.plugin_system.apis import message_api
|
from src.plugin_system.apis import message_api
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
@router.get("/messages/recent")
|
@router.get("/messages/recent")
|
||||||
async def get_recent_messages(chat_id: str, limit: int = 10):
|
async def get_message_stats(
|
||||||
|
days: int = Query(1, ge=1, description="指定查询过去多少天的数据"),
|
||||||
|
message_type: Literal["all", "sent", "received"] = Query("all", description="筛选消息类型: 'sent' (BOT发送的), 'received' (BOT接收的), or 'all' (全部)")
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
获取最近的聊天记录
|
获取BOT在指定天数内的消息统计数据。
|
||||||
"""
|
"""
|
||||||
# 假设 message_api.get_recent_messages 是一个异步函数
|
try:
|
||||||
messages = await message_api.get_recent_messages(chat_id=chat_id, limit=limit)
|
end_time = time.time()
|
||||||
return {"chat_id": chat_id, "messages": messages}
|
start_time = end_time - (days * 24 * 3600)
|
||||||
|
|
||||||
|
messages = await message_api.get_messages_by_time(start_time, end_time)
|
||||||
|
|
||||||
|
sent_count = 0
|
||||||
|
received_count = 0
|
||||||
|
bot_qq = str(global_config.bot.qq_account)
|
||||||
|
|
||||||
|
for msg in messages:
|
||||||
|
if msg.get("user_id") == bot_qq:
|
||||||
|
sent_count += 1
|
||||||
|
else:
|
||||||
|
received_count += 1
|
||||||
|
if message_type == "sent":
|
||||||
|
return {"days": days, "message_type": message_type, "count": sent_count}
|
||||||
|
elif message_type == "received":
|
||||||
|
return {"days": days, "message_type": message_type, "count": received_count}
|
||||||
|
else:
|
||||||
|
return {
|
||||||
|
"days": days,
|
||||||
|
"message_type": message_type,
|
||||||
|
"sent_count": sent_count,
|
||||||
|
"received_count": received_count,
|
||||||
|
"total_count": len(messages)
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|||||||
Reference in New Issue
Block a user