加入指令数据统计,指令看板内容

This commit is contained in:
liuwei
2025-03-18 17:40:59 +08:00
parent 21f8fffca8
commit 1d7ee9f953
23 changed files with 2407 additions and 1 deletions

View File

@@ -0,0 +1,7 @@
from plugins.stats_collector.main import StatsCollectorPlugin
def get_plugin():
"""获取插件实例"""
return StatsCollectorPlugin()
__all__ = ['StatsCollectorPlugin', 'get_plugin']

View File

@@ -0,0 +1,21 @@
# 统计收集器插件配置
name: stats_collector
description: 插件使用统计收集器
version: 1.0.0
author: Trae AI
enabled: true
# 统计设置
settings:
# 是否记录详细日志
debug_logging: false
# 统计保留天数
retention_days: 90
# 是否统计系统插件
include_system_plugins: true
# 排除的插件列表
excluded_plugins:
- stats_collector

View File

@@ -0,0 +1,75 @@
import functools
import traceback
from datetime import datetime
from typing import Callable, Dict, Any, Tuple
from event_system.event_manager import EventManager
from event_system.events.stats_events import PluginCallStartEvent, PluginCallEndEvent, PluginCallErrorEvent
def plugin_stats_decorator(plugin_name: str) -> Callable:
"""插件统计装饰器
Args:
plugin_name: 插件名称
Returns:
装饰器函数
"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(self, message: Dict[str, Any]) -> Tuple[bool, str]:
# 获取事件管理器
event_manager = EventManager.get_instance()
# 提取消息信息
content = message.get("content", "")
sender = message.get("sender", "")
roomid = message.get("roomid", "")
# 发布插件调用开始事件
start_time = datetime.now()
event_manager.publish(PluginCallStartEvent, {
"plugin_name": plugin_name,
"command": content,
"user_id": sender,
"group_id": roomid,
"start_time": start_time
})
try:
# 调用原始方法
success, response = func(self, message)
# 发布插件调用结束事件
end_time = datetime.now()
event_manager.publish(PluginCallEndEvent, {
"plugin_name": plugin_name,
"command": content,
"user_id": sender,
"group_id": roomid,
"start_time": start_time,
"end_time": end_time,
"success": success,
"response": response
})
return success, response
except Exception as e:
# 发布插件调用错误事件
event_manager.publish(PluginCallErrorEvent, {
"plugin_name": plugin_name,
"command": content,
"user_id": sender,
"group_id": roomid,
"start_time": start_time,
"error_message": str(e),
"stack_trace": traceback.format_exc()
})
# 重新抛出异常,让上层处理
raise
return wrapper
return decorator

View File

@@ -0,0 +1,136 @@
import logging
import time
from typing import Dict, Any, Tuple, Optional
from datetime import datetime
from plugin_common.plugin_interface import PluginInterface
from event_system.event_manager import EventManager
# 修正导入,使用与装饰器相同的事件类型
from event_system.events.plugin_events import PluginCallStartEvent, PluginCallEndEvent, PluginCallErrorEvent
from db.stats_db import StatsDBOperator
from db.db_manager import DBConnectionManager
from job_decorators import register_job_decorator
from .decorators import plugin_stats_decorator
class StatsCollectorPlugin(PluginInterface):
"""统计收集插件"""
def __init__(self):
self.name = "统计收集器"
self.version = "1.0.0"
self.description = "收集插件调用统计数据"
self.author = "Trae AI"
self.logger = logging.getLogger("StatsCollector")
# 默认配置
self.config = {
"enable": True,
"record_all_plugins": True, # 是否记录所有插件的调用
"excluded_plugins": [], # 排除的插件列表
}
self.event_manager = EventManager.get_instance()
# 修正获取数据库连接管理器的方式
self.db_manager = DBConnectionManager.get_instance()
self.stats_db = StatsDBOperator(self.db_manager)
# 用于临时存储插件调用开始时间的字典
self.plugin_call_start_times = {}
def initialize(self, config: Dict[str, Any]) -> bool:
"""初始化插件"""
if config:
self.config.update(config)
if not self.config["enable"]:
self.logger.info("统计收集插件已禁用")
return False
# 注册事件处理器
self.event_manager.register(PluginCallStartEvent, self.handle_plugin_call_start)
self.event_manager.register(PluginCallEndEvent, self.handle_plugin_call_end)
self.event_manager.register(PluginCallErrorEvent, self.handle_plugin_error)
self.logger.info("统计收集插件已初始化")
return True
def handle_plugin_call_start(self, event: PluginCallStartEvent) -> None:
"""处理插件调用开始事件"""
# 检查是否需要记录该插件
if not self._should_record_plugin(event.plugin_name):
return
# 记录开始时间和相关信息
# 注意plugin_events.py 中的事件结构与 stats_events.py 不同
self.logger.debug(f"记录插件调用开始: {event.plugin_name} - {event.command}")
def handle_plugin_call_end(self, event: PluginCallEndEvent) -> None:
"""处理插件调用结束事件"""
# 检查是否需要记录该插件
if not self._should_record_plugin(event.plugin_name):
return
# 记录统计数据
try:
self.stats_db.record_plugin_call(
plugin_name=event.plugin_name,
command=event.command,
user_id=event.user_id,
group_id=event.group_id,
success=event.process_result, # 注意字段名不同
process_time_ms=event.process_time # 注意字段名不同
)
self.logger.debug(f"记录插件调用结束: {event.plugin_name} - {event.command} - 成功: {event.process_result} - 处理时间: {event.process_time}ms")
except Exception as e:
self.logger.error(f"记录插件调用统计数据出错: {e}")
def handle_plugin_error(self, event: PluginCallErrorEvent) -> None:
"""处理插件调用错误事件"""
# 检查是否需要记录该插件
if not self._should_record_plugin(event.plugin_name):
return
# 记录错误信息
try:
self.stats_db.record_error(
plugin_name=event.plugin_name,
command=event.command,
user_id=event.user_id,
group_id=event.group_id,
error_message=event.error_message,
stack_trace=event.stack_trace
)
self.logger.debug(f"记录插件调用错误: {event.plugin_name} - {event.command} - {event.error_message}")
except Exception as e:
self.logger.error(f"记录插件错误信息出错: {e}")
def _should_record_plugin(self, plugin_name: str) -> bool:
"""检查是否应该记录该插件的调用"""
if not self.config["record_all_plugins"]:
return False
if plugin_name in self.config["excluded_plugins"]:
return False
return True
def match_command(self, content: str) -> bool:
"""匹配命令"""
# 该插件不处理用户消息
return False
def process_message(self, message: Dict[str, Any]) -> Tuple[bool, str]:
"""处理消息"""
# 该插件不处理用户消息
return False, ""
def shutdown(self) -> None:
"""关闭插件"""
# 取消注册事件处理器
self.event_manager.unregister(PluginCallStartEvent, self.handle_plugin_call_start)
self.event_manager.unregister(PluginCallEndEvent, self.handle_plugin_call_end)
self.event_manager.unregister(PluginCallErrorEvent, self.handle_plugin_error)
self.logger.info("统计收集插件已关闭")

View File

@@ -0,0 +1,7 @@
from .main import StatsDashboardPlugin
def get_plugin():
"""获取插件实例"""
return StatsDashboardPlugin()
__all__ = ['StatsDashboardPlugin', 'get_plugin']

View File

@@ -0,0 +1,138 @@
import logging
from typing import Dict, Any, Optional
import threading
import time
import os
from flask import Flask, render_template, request, jsonify, redirect, url_for, session, send_from_directory
from db.connection import DBConnectionManager
from db.stats_db import StatsDBOperator
class DashboardServer:
"""统计看板服务器"""
def __init__(self, host: str = "127.0.0.1", port: int = 8080,
username: str = "admin", password: str = "admin123"):
self.host = host
self.port = port
self.username = username
self.password = password
self.logger = logging.getLogger("DashboardServer")
# 修正:使用单例模式获取数据库连接
self.db_manager = DBConnectionManager()
self.stats_db = StatsDBOperator(self.db_manager)
self.app = self._create_app()
self._stop_event = threading.Event()
self._server = None # 添加:存储服务器实例
def _create_app(self) -> Flask:
"""创建Flask应用"""
app = Flask(__name__)
app.secret_key = "stats_dashboard_secret_key"
# 添加:实现基本的身份验证
def check_auth():
auth = request.authorization
if not auth or auth.username != self.username or auth.password != self.password:
return False
return True
# 静态文件目录
static_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')
@app.route('/static/<path:filename>')
def serve_static(filename):
return send_from_directory(static_folder, filename)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/plugins')
def plugins():
return render_template('plugins.html')
@app.route('/users')
def users_page():
return render_template('users.html')
@app.route('/groups')
def groups():
return render_template('groups.html')
@app.route('/api/plugin_stats')
def api_plugin_stats():
days = request.args.get('days', 7, type=int)
stats = self.stats_db.get_plugin_stats(days)
return jsonify({"success": True, "data": stats})
@app.route('/api/user_stats')
def api_user_stats():
days = request.args.get('days', 7, type=int)
limit = request.args.get('limit', 10, type=int)
stats = self.stats_db.get_user_stats(days, limit)
return jsonify({"success": True, "data": stats})
@app.route('/api/group_stats')
def api_group_stats():
days = request.args.get('days', 7, type=int)
limit = request.args.get('limit', 10, type=int)
stats = self.stats_db.get_group_stats(days, limit)
return jsonify({"success": True, "data": stats})
@app.route('/api/error_logs')
def api_error_logs():
days = request.args.get('days', 7, type=int)
limit = request.args.get('limit', 50, type=int)
logs = self.stats_db.get_error_logs(days, limit)
return jsonify({"success": True, "data": logs})
@app.route('/api/error_detail/<int:error_id>')
def api_error_detail(error_id):
detail = self.stats_db.get_error_detail(error_id)
return jsonify({"success": True, "data": detail})
# 修改添加错误处理的API路由示例
@app.route('/api/dashboard_summary')
def api_dashboard_summary():
try:
days = request.args.get('days', 7, type=int)
summary = self.stats_db.get_dashboard_summary(days)
return jsonify({"success": True, "data": summary})
except Exception as e:
self.logger.error(f"获取仪表盘摘要数据出错: {e}")
return jsonify({"success": False, "error": str(e)}), 500
@app.route('/api/plugin_trend')
def api_plugin_trend():
days = request.args.get('days', 7, type=int)
plugin_name = request.args.get('plugin_name', '')
trend = self.stats_db.get_plugin_trend(plugin_name, days)
return jsonify({"success": True, "data": trend})
return app
def run(self) -> None:
"""运行服务器"""
try:
self.logger.info(f"启动统计看板服务器,地址: {self.host}:{self.port}")
# 修改:使用线程安全的方式运行服务器
from werkzeug.serving import make_server
self._server = make_server(self.host, self.port, self.app)
self._server.serve_forever()
except Exception as e:
self.logger.error(f"运行统计看板服务器出错: {e}")
def stop(self) -> None:
"""停止服务器"""
try:
self._stop_event.set()
# 修改:使用更可靠的方式停止服务器
if self._server:
self._server.shutdown()
self.logger.info("统计看板服务器已停止")
except Exception as e:
self.logger.error(f"停止统计看板服务器出错: {e}")
raise

View File

@@ -0,0 +1,146 @@
import logging
import threading
from typing import Dict, Any, Tuple, Optional, List
from plugin_common.plugin_interface import PluginInterface
from .dashboard_server import DashboardServer
class StatsDashboardPlugin(PluginInterface):
"""统计看板插件"""
@property
def name(self) -> str:
return "统计看板"
@property
def version(self) -> str:
return "1.0.0"
@property
def description(self) -> str:
return "提供插件使用统计数据的可视化界面"
@property
def author(self) -> str:
return "Trae AI"
@property
def command_prefix(self) -> Optional[str]:
return "" # 不需要前缀,直接匹配命令
@property
def commands(self) -> List[str]:
return []
def __init__(self):
self.logger = logging.getLogger("StatsDashboard")
# 默认配置
self.config = {
"enable": True,
"host": "127.0.0.1",
"port": 8080,
"username": "admin",
"password": "admin123",
"auto_start": True
}
self.server = None
self.server_thread = None
def initialize(self, config: Dict[str, Any]) -> bool:
"""初始化插件"""
if config:
self.config.update(config)
if not self.config["enable"]:
self.logger.info("统计看板插件已禁用")
return False
# 创建看板服务器
self.server = DashboardServer(
host=self.config["host"],
port=self.config["port"],
username=self.config["username"],
password=self.config["password"]
)
# 如果配置为自动启动,则启动服务器
if self.config["auto_start"]:
self.start_server()
return True
def start_server(self) -> bool:
"""启动看板服务器"""
if self.server_thread and self.server_thread.is_alive():
self.logger.warning("服务器已经在运行中")
return False
try:
self.server_thread = threading.Thread(target=self.server.run, daemon=True)
self.server_thread.start()
self.logger.info(f"统计看板服务器已启动,访问地址: http://{self.config['host']}:{self.config['port']}")
return True
except Exception as e:
self.logger.error(f"启动统计看板服务器失败: {e}")
return False
def stop_server(self) -> bool:
"""停止看板服务器"""
if not self.server_thread or not self.server_thread.is_alive():
self.logger.warning("服务器未运行")
return False
try:
# 修改:添加超时处理和错误检查
self.server.stop()
# 等待线程结束,但设置超时
self.server_thread.join(timeout=5)
# 检查线程是否真的结束了
if self.server_thread.is_alive():
self.logger.warning("服务器停止超时,可能需要手动终止")
return False
self.logger.info("统计看板服务器已停止")
return True
except Exception as e:
self.logger.error(f"停止统计看板服务器失败: {e}")
return False
def match_command(self, content: str) -> bool:
"""匹配命令"""
return content.strip().startswith("/stats")
def process_message(self, message: Dict[str, Any]) -> Tuple[bool, str]:
"""处理消息"""
# 暂时不启用指令
return False, ""
# content = str(message.get("content", "")).strip()
# if content == "/stats start":
# if self.start_server():
# return True, "统计看板服务器已启动"
# else:
# return False, "启动统计看板服务器失败"
#
# elif content == "/stats stop":
# if self.stop_server():
# return True, "统计看板服务器已停止"
# else:
# return False, "停止统计看板服务器失败"
#
# elif content == "/stats status":
# if self.server_thread and self.server_thread.is_alive():
# return True, f"统计看板服务器正在运行,访问地址: http://{self.config['host']}:{self.config['port']}"
# else:
# return True, "统计看板服务器未运行"
#
# else:
# return True, f"统计看板命令格式错误,可用命令:\n/stats start - 启动服务器\n/stats stop - 停止服务器\n/stats status - 查看状态"
def shutdown(self) -> None:
"""关闭插件"""
if self.server:
self.stop_server()

View File

@@ -0,0 +1,162 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}机器人统计看板{% endblock %}</title>
<!-- Element UI CSS -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 图表库 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- Vue.js -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<!-- Element UI JS -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<!-- Axios -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<style>
body {
margin: 0;
padding: 0;
font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif;
}
.app-container {
height: 100vh;
display: flex;
flex-direction: column;
}
.header {
background-color: #409EFF;
color: white;
padding: 0 20px;
height: 60px;
display: flex;
align-items: center;
justify-content: space-between;
}
.main-container {
display: flex;
flex: 1;
overflow: hidden;
}
.sidebar {
width: 200px;
background-color: #545c64;
height: 100%;
overflow-y: auto;
}
.content {
flex: 1;
padding: 20px;
overflow-y: auto;
background-color: #f0f2f5;
}
.el-menu {
border-right: none;
}
.chart-container {
background-color: white;
padding: 20px;
border-radius: 4px;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
}
.stats-card {
margin-bottom: 20px;
}
</style>
{% block head %}{% endblock %}
</head>
<body>
<div id="app" class="app-container">
<header class="header">
<h2>机器人统计看板</h2>
</header>
<div class="main-container">
<!-- 左侧菜单 -->
<div class="sidebar">
<el-menu
:default-active="currentView"
class="el-menu-vertical-demo"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b"
@select="handleSelect"
router>
<el-menu-item index="1" route="/">
<i class="el-icon-s-home"></i>
<span slot="title">首页概览</span>
</el-menu-item>
<el-menu-item index="2" route="/plugins">
<i class="el-icon-s-grid"></i>
<span slot="title">插件统计</span>
</el-menu-item>
<el-menu-item index="3" route="/users">
<i class="el-icon-user"></i>
<span slot="title">用户统计</span>
</el-menu-item>
<el-menu-item index="4" route="/groups">
<i class="el-icon-s-cooperation"></i>
<span slot="title">群组统计</span>
</el-menu-item>
<el-menu-item index="5" route="/errors">
<i class="el-icon-warning"></i>
<span slot="title">错误日志</span>
</el-menu-item>
</el-menu>
</div>
<!-- 右侧内容区 -->
<div class="content">
<!-- 时间范围选择器 -->
<el-row :gutter="20" style="margin-bottom: 20px;">
<el-col :span="24">
<el-card shadow="hover">
<el-form :inline="true" size="small">
<el-form-item label="统计时间范围">
<el-select v-model="timeRange" @change="loadData">
<el-option label="最近7天" value="7"></el-option>
<el-option label="最近30天" value="30"></el-option>
<el-option label="最近90天" value="90"></el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="loadData">刷新数据</el-button>
</el-form-item>
</el-form>
</el-card>
</el-col>
</el-row>
<!-- 内容区域 -->
{% block content %}{% endblock %}
</div>
</div>
</div>
<!-- 基础 Vue 实例 -->
<script>
const baseApp = {
data() {
return {
currentView: '1',
timeRange: '7',
charts: {}
}
},
methods: {
handleSelect(key, keyPath) {
this.currentView = key;
this.loadData();
},
loadData() {
// 由子组件实现
}
}
};
</script>
{% block scripts %}{% endblock %}
</body>
</html>

View File

@@ -0,0 +1,129 @@
{% extends "base.html" %}
{% block title %}错误日志 - 机器人统计看板{% endblock %}
{% block content %}
<!-- 错误日志 -->
<div>
<el-row :gutter="20">
<el-col :span="24">
<el-card shadow="hover">
<div slot="header">
<span>错误日志</span>
</div>
<el-table :data="errorLogs" style="width: 100%" border>
<el-table-column prop="plugin_name" label="插件名称"></el-table-column>
<el-table-column prop="command" label="命令"></el-table-column>
<el-table-column prop="error_message" label="错误信息" :show-overflow-tooltip="true"></el-table-column>
<el-table-column prop="created_at" label="时间"></el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="mini" type="primary" @click="viewErrorDetail(scope.row)">查看详情</el-button>
</template>
</el-table-column>
</el-table>
<div class="pagination-container" style="margin-top: 20px; text-align: right;">
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 50, 100]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="totalErrors">
</el-pagination>
</div>
</el-card>
</el-col>
</el-row>
<!-- 错误详情对话框 -->
<el-dialog title="错误详情" :visible.sync="errorDetailVisible" width="70%">
<el-descriptions :column="1" border>
<el-descriptions-item label="插件名称">{{ errorDetail.plugin_name }}</el-descriptions-item>
<el-descriptions-item label="命令">{{ errorDetail.command }}</el-descriptions-item>
<el-descriptions-item label="用户ID">{{ errorDetail.user_id }}</el-descriptions-item>
<el-descriptions-item label="群组ID">{{ errorDetail.group_id || '私聊' }}</el-descriptions-item>
<el-descriptions-item label="错误信息">{{ errorDetail.error_message }}</el-descriptions-item>
<el-descriptions-item label="时间">{{ errorDetail.created_at }}</el-descriptions-item>
<el-descriptions-item label="堆栈跟踪">
<pre style="white-space: pre-wrap; word-wrap: break-word; max-height: 300px; overflow-y: auto;">{{ errorDetail.stack_trace }}</pre>
</el-descriptions-item>
</el-descriptions>
</el-dialog>
</div>
{% endblock %}
{% block scripts %}
<script>
new Vue({
el: '#app',
mixins: [baseApp],
data() {
return {
errorLogs: [],
errorDetail: {},
errorDetailVisible: false,
currentPage: 1,
pageSize: 20,
totalErrors: 0
}
},
mounted() {
this.currentView = '5';
this.loadData();
},
methods: {
loadData() {
const days = parseInt(this.timeRange);
this.loadErrorLogs(days);
},
loadErrorLogs(days) {
axios.get(`/api/error_logs?days=${days}&limit=${this.pageSize}&offset=${(this.currentPage - 1) * this.pageSize}`)
.then(response => {
if (response.data.success) {
this.errorLogs = response.data.data.logs || [];
this.totalErrors = response.data.data.total || 0;
}
})
.catch(error => {
console.error('加载错误日志出错:', error);
this.$message.error('加载错误日志出错');
});
},
viewErrorDetail(error) {
// 如果已有错误ID直接加载详情
if (error.id) {
this.loadErrorDetail(error.id);
} else {
// 否则直接显示当前行的数据
this.errorDetail = error;
this.errorDetailVisible = true;
}
},
loadErrorDetail(errorId) {
axios.get(`/api/error_detail/${errorId}`)
.then(response => {
if (response.data.success) {
this.errorDetail = response.data.data || {};
this.errorDetailVisible = true;
}
})
.catch(error => {
console.error('加载错误详情出错:', error);
this.$message.error('加载错误详情出错');
});
},
handleSizeChange(size) {
this.pageSize = size;
this.currentPage = 1; // 重置到第一页
this.loadData();
},
handleCurrentChange(page) {
this.currentPage = page;
this.loadData();
}
}
});
</script>
{% endblock %}

View File

@@ -0,0 +1,74 @@
{% extends "base.html" %}
{% block title %}群组统计 - 机器人统计看板{% endblock %}
{% block content %}
<!-- 群组统计 -->
<div>
<el-row :gutter="20">
<el-col :span="24">
<el-card shadow="hover">
<div slot="header">
<span>群组活跃度排行</span>
</div>
<el-table :data="groupStats" style="width: 100%" border>
<el-table-column prop="group_id" label="群组ID"></el-table-column>
<el-table-column prop="total_calls" label="调用次数" sortable></el-table-column>
<el-table-column prop="unique_users" label="唯一用户数" sortable></el-table-column>
<el-table-column prop="success_calls" label="成功次数" sortable></el-table-column>
<el-table-column prop="error_calls" label="失败次数" sortable></el-table-column>
<el-table-column label="成功率" sortable>
<template slot-scope="scope">
{{ (scope.row.success_calls / scope.row.total_calls * 100).toFixed(2) }}%
</template>
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="mini" type="primary" @click="viewGroupDetail(scope.row)">查看详情</el-button>
</template>
</el-table-column>
</el-table>
</el-card>
</el-col>
</el-row>
</div>
{% endblock %}
{% block scripts %}
<script>
new Vue({
el: '#app',
mixins: [baseApp],
data() {
return {
groupStats: []
}
},
mounted() {
this.currentView = '4';
this.loadData();
},
methods: {
loadData() {
const days = parseInt(this.timeRange);
this.loadGroupStats(days);
},
loadGroupStats(days) {
axios.get(`/api/group_stats?days=${days}&limit=20`)
.then(response => {
if (response.data.success) {
this.groupStats = response.data.data || [];
}
})
.catch(error => {
console.error('加载群组统计数据出错:', error);
this.$message.error('加载群组统计数据出错');
});
},
viewGroupDetail(group) {
this.$message.info('群组详情功能开发中');
}
}
});
</script>
{% endblock %}

View File

@@ -0,0 +1,285 @@
{% extends "base.html" %}
{% block title %}首页概览 - 机器人统计看板{% endblock %}
{% block content %}
<!-- 首页概览 -->
<div>
<el-row :gutter="20">
<el-col :span="6">
<el-card shadow="hover" class="stats-card">
<div slot="header">
<span>总调用次数</span>
</div>
<div style="font-size: 24px; text-align: center;">
{{ totalCalls }}
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover" class="stats-card">
<div slot="header">
<span>成功率</span>
</div>
<div style="font-size: 24px; text-align: center;">
{{ successRate }}%
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover" class="stats-card">
<div slot="header">
<span>活跃用户数</span>
</div>
<div style="font-size: 24px; text-align: center;">
{{ activeUsers }}
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover" class="stats-card">
<div slot="header">
<span>活跃群组数</span>
</div>
<div style="font-size: 24px; text-align: center;">
{{ activeGroups }}
</div>
</el-card>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="12">
<div class="chart-container">
<h3>插件使用排行</h3>
<canvas id="pluginChart" width="400" height="300"></canvas>
</div>
</el-col>
<el-col :span="12">
<div class="chart-container">
<h3>成功率分析</h3>
<canvas id="successRateChart" width="400" height="300"></canvas>
</div>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="24">
<div class="chart-container">
<h3>使用趋势</h3>
<canvas id="trendChart" width="800" height="300"></canvas>
</div>
</el-col>
</el-row>
</div>
{% endblock %}
{% block scripts %}
<script>
new Vue({
el: '#app',
mixins: [baseApp],
data() {
return {
totalCalls: 0,
successRate: 0,
activeUsers: 0,
activeGroups: 0,
pluginStats: []
}
},
mounted() {
this.currentView = '1';
this.loadData();
},
methods: {
loadData() {
const days = parseInt(this.timeRange);
this.loadDashboardSummary(days);
this.loadPluginStats(days);
this.loadPluginTrend(days);
},
loadDashboardSummary(days) {
axios.get(`/api/dashboard_summary?days=${days}`)
.then(response => {
if (response.data.success) {
const data = response.data.data;
this.totalCalls = data.total_calls || 0;
this.successRate = data.success_rate || 0;
this.activeUsers = data.active_users || 0;
this.activeGroups = data.active_groups || 0;
}
})
.catch(error => {
console.error('加载仪表盘摘要数据出错:', error);
this.$message.error('加载仪表盘摘要数据出错');
});
},
loadPluginStats(days) {
axios.get(`/api/plugin_stats?days=${days}`)
.then(response => {
if (response.data.success) {
this.pluginStats = response.data.data || [];
this.$nextTick(() => {
this.renderPluginChart();
this.renderSuccessRateChart();
});
}
})
.catch(error => {
console.error('加载插件统计数据出错:', error);
this.$message.error('加载插件统计数据出错');
});
},
loadPluginTrend(days) {
axios.get(`/api/plugin_trend?days=${days}`)
.then(response => {
if (response.data.success) {
const trendData = response.data.data || [];
this.$nextTick(() => {
this.renderTrendChart(trendData);
});
}
})
.catch(error => {
console.error('加载插件趋势数据出错:', error);
this.$message.error('加载插件趋势数据出错');
});
},
renderPluginChart() {
const ctx = document.getElementById('pluginChart').getContext('2d');
// 销毁旧图表
if (this.charts.pluginChart) {
this.charts.pluginChart.destroy();
}
// 准备数据
const sortedData = [...this.pluginStats].sort((a, b) => b.total_calls - a.total_calls).slice(0, 10);
const labels = sortedData.map(item => item.plugin_name);
const data = sortedData.map(item => item.total_calls);
// 创建新图表
this.charts.pluginChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: '调用次数',
data: data,
backgroundColor: 'rgba(54, 162, 235, 0.6)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
},
renderSuccessRateChart() {
const ctx = document.getElementById('successRateChart').getContext('2d');
// 销毁旧图表
if (this.charts.successRateChart) {
this.charts.successRateChart.destroy();
}
// 准备数据
const sortedData = [...this.pluginStats]
.filter(item => item.total_calls > 0)
.sort((a, b) => (b.success_calls / b.total_calls) - (a.success_calls / a.total_calls))
.slice(0, 10);
const labels = sortedData.map(item => item.plugin_name);
const data = sortedData.map(item => (item.success_calls / item.total_calls) * 100);
// 创建新图表
this.charts.successRateChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: '成功率 (%)',
data: data,
backgroundColor: 'rgba(75, 192, 192, 0.6)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true,
max: 100
}
}
}
});
},
renderTrendChart(trendData) {
const ctx = document.getElementById('trendChart').getContext('2d');
// 销毁旧图表
if (this.charts.trendChart) {
this.charts.trendChart.destroy();
}
// 准备数据
const labels = trendData.map(item => item.stat_date);
const totalData = trendData.map(item => item.total_calls);
const successData = trendData.map(item => item.success_calls);
const errorData = trendData.map(item => item.error_calls);
// 创建新图表
this.charts.trendChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [
{
label: '总调用',
data: totalData,
fill: false,
backgroundColor: 'rgba(54, 162, 235, 0.6)',
borderColor: 'rgba(54, 162, 235, 1)',
tension: 0.1
},
{
label: '成功调用',
data: successData,
fill: false,
backgroundColor: 'rgba(75, 192, 192, 0.6)',
borderColor: 'rgba(75, 192, 192, 1)',
tension: 0.1
},
{
label: '失败调用',
data: errorData,
fill: false,
backgroundColor: 'rgba(255, 99, 132, 0.6)',
borderColor: 'rgba(255, 99, 132, 1)',
tension: 0.1
}
]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
}
}
});
</script>
{% endblock %}

View File

@@ -0,0 +1,141 @@
{% extends "base.html" %}
{% block title %}插件统计 - 机器人统计看板{% endblock %}
{% block content %}
<!-- 插件统计 -->
<div>
<el-row :gutter="20">
<el-col :span="24">
<el-card shadow="hover">
<div slot="header">
<span>插件使用统计</span>
</div>
<el-table :data="pluginStats" style="width: 100%" border>
<el-table-column prop="plugin_name" label="插件名称"></el-table-column>
<el-table-column prop="total_calls" label="调用次数" sortable></el-table-column>
<el-table-column prop="success_calls" label="成功次数" sortable></el-table-column>
<el-table-column prop="error_calls" label="失败次数" sortable></el-table-column>
<el-table-column label="成功率" sortable>
<template slot-scope="scope">
{{ (scope.row.success_calls / scope.row.total_calls * 100).toFixed(2) }}%
</template>
</el-table-column>
<el-table-column label="平均响应时间" sortable>
<template slot-scope="scope">
{{ scope.row.avg_response_time.toFixed(2) }}ms
</template>
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="mini" type="primary" @click="viewPluginTrend(scope.row)">查看趋势</el-button>
</template>
</el-table-column>
</el-table>
</el-card>
</el-col>
</el-row>
<!-- 插件趋势对话框 -->
<el-dialog title="插件使用趋势" :visible.sync="pluginTrendVisible" width="70%">
<div class="chart-container">
<h3>{{ selectedPlugin ? selectedPlugin.plugin_name : '' }} 使用趋势</h3>
<canvas id="pluginTrendChart" width="800" height="400"></canvas>
</div>
</el-dialog>
</div>
{% endblock %}
{% block scripts %}
<script>
new Vue({
el: '#app',
mixins: [baseApp],
data() {
return {
pluginStats: [],
pluginTrendVisible: false,
selectedPlugin: null
}
},
mounted() {
this.currentView = '2';
this.loadData();
},
methods: {
loadData() {
const days = parseInt(this.timeRange);
this.loadPluginStats(days);
},
loadPluginStats(days) {
axios.get(`/api/plugin_stats?days=${days}`)
.then(response => {
if (response.data.success) {
this.pluginStats = response.data.data || [];
}
})
.catch(error => {
console.error('加载插件统计数据出错:', error);
this.$message.error('加载插件统计数据出错');
});
},
viewPluginTrend(plugin) {
this.selectedPlugin = plugin;
this.pluginTrendVisible = true;
// 加载插件趋势数据
const days = parseInt(this.timeRange);
axios.get(`/api/plugin_trend?days=${days}&plugin_name=${plugin.plugin_name}`)
.then(response => {
if (response.data.success) {
const trendData = response.data.data || [];
this.$nextTick(() => {
this.renderPluginTrendChart(trendData, plugin.plugin_name);
});
}
})
.catch(error => {
console.error('加载插件趋势数据出错:', error);
this.$message.error('加载插件趋势数据出错');
});
},
renderPluginTrendChart(trendData, pluginName) {
const ctx = document.getElementById('pluginTrendChart').getContext('2d');
// 销毁旧图表
if (this.charts.pluginTrendChart) {
this.charts.pluginTrendChart.destroy();
}
// 准备数据
const labels = trendData.map(item => item.stat_date);
const data = trendData.map(item => item.total_calls);
// 创建新图表
this.charts.pluginTrendChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: `${pluginName} 调用次数`,
data: data,
fill: false,
backgroundColor: 'rgba(153, 102, 255, 0.6)',
borderColor: 'rgba(153, 102, 255, 1)',
tension: 0.1
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
}
}
});
</script>
{% endblock %}

View File

@@ -0,0 +1,73 @@
{% extends "base.html" %}
{% block title %}用户统计 - 机器人统计看板{% endblock %}
{% block content %}
<!-- 用户统计 -->
<div>
<el-row :gutter="20">
<el-col :span="24">
<el-card shadow="hover">
<div slot="header">
<span>用户活跃度排行</span>
</div>
<el-table :data="userStats" style="width: 100%" border>
<el-table-column prop="user_id" label="用户ID"></el-table-column>
<el-table-column prop="total_calls" label="调用次数" sortable></el-table-column>
<el-table-column prop="success_calls" label="成功次数" sortable></el-table-column>
<el-table-column prop="error_calls" label="失败次数" sortable></el-table-column>
<el-table-column label="成功率" sortable>
<template slot-scope="scope">
{{ (scope.row.success_calls / scope.row.total_calls * 100).toFixed(2) }}%
</template>
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="mini" type="primary" @click="viewUserDetail(scope.row)">查看详情</el-button>
</template>
</el-table-column>
</el-table>
</el-card>
</el-col>
</el-row>
</div>
{% endblock %}
{% block scripts %}
<script>
new Vue({
el: '#app',
mixins: [baseApp],
data() {
return {
userStats: []
}
},
mounted() {
this.currentView = '3';
this.loadData();
},
methods: {
loadData() {
const days = parseInt(this.timeRange);
this.loadUserStats(days);
},
loadUserStats(days) {
axios.get(`/api/user_stats?days=${days}&limit=20`)
.then(response => {
if (response.data.success) {
this.userStats = response.data.data || [];
}
})
.catch(error => {
console.error('加载用户统计数据出错:', error);
this.$message.error('加载用户统计数据出错');
});
},
viewUserDetail(user) {
this.$message.info('用户详情功能开发中');
}
}
});
</script>
{% endblock %}