From 6005fda2d4e52ec272c53d286b74bf7766363577 Mon Sep 17 00:00:00 2001 From: minecraft1024a Date: Sat, 4 Oct 2025 13:18:07 +0800 Subject: [PATCH] =?UTF-8?q?feat(api):=20=E6=96=B0=E5=A2=9E=E6=9C=BA?= =?UTF-8?q?=E5=99=A8=E4=BA=BA=E6=B6=88=E6=81=AF=E7=BB=9F=E8=AE=A1=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 `/messages/bot_stats_by_chat` 端点,用于统计机器人在指定天数内按聊天会话(群聊或私聊)发送的消息数量。 该接口支持以下功能: - 通过 `days` 参数指定查询的时间范围。 - 通过 `format` 参数选择是否在结果中包含会话名称,以提高可读性。 --- src/api/message_router.py | 47 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/api/message_router.py b/src/api/message_router.py index 17f04f33f..e0f8f7004 100644 --- a/src/api/message_router.py +++ b/src/api/message_router.py @@ -128,3 +128,50 @@ async def get_message_stats_by_chat( except Exception as e: raise HTTPException(status_code=500, detail=str(e)) + +@router.get("/messages/bot_stats_by_chat") +async def get_bot_message_stats_by_chat( + days: int = Query(1, ge=1, description="指定查询过去多少天的数据"), + format: bool = Query(False, description="是否格式化输出,包含群聊和用户信息"), +): + """ + 获取BOT在指定天数内按聊天流统计的已发送消息数据。 + """ + try: + end_time = time.time() + start_time = end_time - (days * 24 * 3600) + messages = await message_api.get_messages_by_time(start_time, end_time) + bot_qq = str(global_config.bot.qq_account) + + # 筛选出机器人发送的消息 + bot_messages = [msg for msg in messages if msg.get("user_id") == bot_qq] + + stats = {} + for msg in bot_messages: + chat_id = msg.get("chat_id", "unknown") + if chat_id not in stats: + stats[chat_id] = 0 + stats[chat_id] = 1 + + if format: + chat_manager = get_chat_manager() + formatted_stats = {} + for chat_id, count in stats.items(): + stream = chat_manager.streams.get(chat_id) + chat_name = f"未知会话 ({chat_id})" + if stream: + if stream.group_info and stream.group_info.group_name: + chat_name = stream.group_info.group_name + elif stream.user_info and stream.user_info.user_nickname: + chat_name = stream.user_info.user_nickname + + formatted_stats[chat_id] = { + "chat_name": chat_name, + "count": count + } + return formatted_stats + + return stats + + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) \ No newline at end of file