Files
zhenxun_bot/zhenxun/builtin_plugins/statistics/statistics_hook.py
T

107 lines
3.5 KiB
Python
Raw Normal View History

2026-04-26 15:50:15 +08:00
import asyncio
2024-05-27 16:09:24 +08:00
from datetime import datetime
2026-04-26 15:50:15 +08:00
from nonebot import get_driver
2024-10-03 23:56:17 +08:00
from nonebot.adapters import Bot, Event
from nonebot.adapters.onebot.v11 import PokeNotifyEvent
from nonebot.matcher import Matcher
2024-10-03 23:56:17 +08:00
from nonebot.message import run_postprocessor
from nonebot.plugin import PluginMetadata
2024-10-04 00:14:36 +08:00
from nonebot_plugin_apscheduler import scheduler
from nonebot_plugin_uninfo import Uninfo
2024-05-27 16:09:24 +08:00
from zhenxun.configs.utils import PluginExtraData
from zhenxun.models.statistics import Statistics
2026-02-01 14:28:51 +08:00
from zhenxun.services.cache.runtime_cache import PluginInfoMemoryCache
from zhenxun.services.log import logger
from zhenxun.services.message_load import should_pause_tasks
from zhenxun.utils.enum import PluginType
from zhenxun.utils.utils import get_entity_ids
2024-05-27 16:09:24 +08:00
__plugin_meta__ = PluginMetadata(
name="功能调用统计",
description="功能调用统计",
usage="""""".strip(),
extra=PluginExtraData(
author="HibiKier", version="0.1", plugin_type=PluginType.HIDDEN
).to_dict(),
2024-05-27 16:09:24 +08:00
)
2026-04-26 15:50:15 +08:00
STATS_BUFFER_FLUSH_SIZE = 5000
STATS_BUFFER_MAX_RETAIN = 10000
TEMP_LIST: list[Statistics] = []
_STATS_FLUSH_LOCK = asyncio.Lock()
driver = get_driver()
async def _flush_statistics_buffer(reason: str) -> int:
async with _STATS_FLUSH_LOCK:
call_list = TEMP_LIST.copy()
TEMP_LIST.clear()
if not call_list:
return 0
try:
await Statistics.bulk_create(call_list)
except Exception as e:
logger.error(f"{reason}批量添加调用记录失败", "定时任务", e=e)
retain_count = max(STATS_BUFFER_MAX_RETAIN - len(TEMP_LIST), 0)
if retain_count:
TEMP_LIST[:0] = call_list[-retain_count:]
return 0
logger.debug(f"{reason}批量添加调用记录 {len(call_list)} 条", "定时任务")
return len(call_list)
async def _append_statistics(record: Statistics) -> None:
TEMP_LIST.append(record)
if len(TEMP_LIST) >= STATS_BUFFER_FLUSH_SIZE and not _STATS_FLUSH_LOCK.locked():
await _flush_statistics_buffer("缓冲区触发")
2024-10-04 00:14:36 +08:00
2024-05-27 16:09:24 +08:00
@run_postprocessor
async def _(
2024-08-13 22:37:44 +08:00
matcher: Matcher,
exception: Exception | None,
bot: Bot,
session: Uninfo,
2024-08-13 22:37:44 +08:00
event: Event,
2024-05-27 16:09:24 +08:00
):
2024-08-13 22:37:44 +08:00
if matcher.type == "notice" and not isinstance(event, PokeNotifyEvent):
"""过滤除poke外的notice"""
return
if matcher.plugin:
2026-02-01 14:28:51 +08:00
plugin = PluginInfoMemoryCache.get_by_module_path(matcher.plugin.module_name)
if not plugin:
2026-04-18 23:42:10 +08:00
# cache miss 时不查数据库,直接跳过统计,避免阻塞
return
2026-04-18 23:42:10 +08:00
if plugin.ignore_statistics:
return
plugin_type = plugin.plugin_type
2024-10-03 23:56:17 +08:00
if plugin_type == PluginType.NORMAL:
2026-04-18 23:42:10 +08:00
entity = get_entity_ids(session)
2024-10-03 23:56:17 +08:00
logger.debug(f"提交调用记录: {matcher.plugin_name}...", session=session)
2026-04-26 15:50:15 +08:00
await _append_statistics(
2024-10-04 00:14:36 +08:00
Statistics(
user_id=entity.user_id,
group_id=entity.group_id,
2024-10-04 00:14:36 +08:00
plugin_name=matcher.plugin_name,
create_time=datetime.now(),
bot_id=bot.self_id,
)
2024-08-10 12:10:53 +08:00
)
2024-10-04 00:14:36 +08:00
@scheduler.scheduled_job("interval", minutes=30, max_instances=1, coalesce=True)
2024-10-04 00:14:36 +08:00
async def _():
try:
if should_pause_tasks():
return
2026-04-26 15:50:15 +08:00
await _flush_statistics_buffer("定时")
2024-10-04 00:14:36 +08:00
except Exception as e:
logger.error("定时批量添加调用记录", "定时任务", e=e)
2026-04-26 15:50:15 +08:00
@driver.on_shutdown
async def _flush_statistics_on_shutdown():
await _flush_statistics_buffer("关闭")