Spaces:
Paused
Paused
File size: 9,253 Bytes
2fd3032 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | // Discord Bot Web Dashboard - JavaScript
let ws = null;
let reconnectInterval = null;
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
initializeTabs();
connectWebSocket();
loadStats();
// 每30秒自动刷新统计数据
setInterval(loadStats, 30000);
});
// 初始化标签页切换
function initializeTabs() {
const navItems = document.querySelectorAll('.nav-item');
navItems.forEach(item => {
item.addEventListener('click', (e) => {
e.preventDefault();
// 移除所有活动状态
navItems.forEach(nav => nav.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
// 添加当前活动状态
item.classList.add('active');
const tabName = item.getAttribute('data-tab');
document.getElementById(`tab-${tabName}`).classList.add('active');
// 更新页面标题
const titles = {
'overview': '控制面板',
'tickets': '工单管理',
'levels': '等级排行榜',
'broadcast': '广播消息'
};
document.getElementById('page-title').textContent = titles[tabName];
// 加载对应数据
if (tabName === 'tickets') {
refreshTickets();
} else if (tabName === 'levels') {
refreshLevels();
}
});
});
}
// 连接 WebSocket
function connectWebSocket() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}/ws`;
ws = new WebSocket(wsUrl);
ws.onopen = () => {
console.log('WebSocket 连接成功');
updateConnectionStatus(true);
// 发送心跳
setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send('ping');
}
}, 30000);
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
handleWebSocketMessage(data);
};
ws.onclose = () => {
console.log('WebSocket 连接关闭');
updateConnectionStatus(false);
// 尝试重连
if (!reconnectInterval) {
reconnectInterval = setInterval(() => {
console.log('尝试重新连接...');
connectWebSocket();
}, 5000);
}
};
ws.onerror = (error) => {
console.error('WebSocket 错误:', error);
};
}
// 处理 WebSocket 消息
function handleWebSocketMessage(data) {
console.log('收到实时更新:', data);
// 可以根据消息类型更新不同的部分
if (data.type === 'stats_update') {
updateStatsDisplay(data.stats);
}
}
// 更新连接状态显示
function updateConnectionStatus(connected) {
const statusDot = document.getElementById('status-dot');
const statusText = document.getElementById('bot-status');
if (connected) {
statusDot.classList.add('connected');
statusText.textContent = '已连接';
clearInterval(reconnectInterval);
reconnectInterval = null;
} else {
statusDot.classList.remove('connected');
statusText.textContent = '断开连接';
}
}
// 加载统计数据
async function loadStats() {
try {
const response = await fetch('/api/stats');
const data = await response.json();
updateStatsDisplay(data);
} catch (error) {
console.error('加载统计数据失败:', error);
}
}
// 更新统计数据显示
function updateStatsDisplay(data) {
// 服务器统计
document.getElementById('guild-count').textContent = data.server_stats.total_guilds;
document.getElementById('user-count').textContent = data.server_stats.total_users.toLocaleString();
document.getElementById('channel-count').textContent = data.server_stats.total_channels;
// 性能统计
document.getElementById('latency').textContent = `${data.performance.latency_ms}ms`;
document.getElementById('commands-count').textContent = data.performance.commands_registered;
// 运行时间
document.getElementById('uptime').textContent = data.bot_info.uptime_formatted;
// 更新连接状态
updateConnectionStatus(true);
}
// 刷新生工单列表
async function refreshTickets() {
const tbody = document.getElementById('tickets-table-body');
tbody.innerHTML = '<tr><td colspan="5" class="loading">加载中...</td></tr>';
try {
const response = await fetch('/api/tickets');
const data = await response.json();
if (data.tickets.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" class="loading">暂无工单数据</td></tr>';
return;
}
tbody.innerHTML = data.tickets.map(ticket => `
<tr>
<td>#${ticket.ticket_id}</td>
<td>${ticket.type}</td>
<td>
<span style="color: ${ticket.status === 'open' ? '#3ba55d' : '#ed4245'}">
${ticket.status === 'open' ? '🟢 进行中' : '🔴 已关闭'}
</span>
</td>
<td>${formatDateTime(ticket.created_at)}</td>
<td>${ticket.closed_at ? formatDateTime(ticket.closed_at) : '-'}</td>
</tr>
`).join('');
} catch (error) {
console.error('加载工单列表失败:', error);
tbody.innerHTML = '<tr><td colspan="5" class="loading">加载失败</td></tr>';
}
}
// 刷新等级排行榜
async function refreshLevels() {
const tbody = document.getElementById('levels-table-body');
tbody.innerHTML = '<tr><td colspan="5" class="loading">加载中...</td></tr>';
try {
const response = await fetch('/api/levels');
const data = await response.json();
if (data.levels.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" class="loading">暂无等级数据</td></tr>';
return;
}
tbody.innerHTML = data.levels.map((level, index) => `
<tr>
<td>${getRankEmoji(index + 1)} ${index + 1}</td>
<td>${level.user_id}</td>
<td><strong>${level.level}</strong></td>
<td>${level.experience} XP</td>
<td>${level.messages_sent}</td>
</tr>
`).join('');
} catch (error) {
console.error('加载等级数据失败:', error);
tbody.innerHTML = '<tr><td colspan="5" class="loading">加载失败</td></tr>';
}
}
// 发送广播消息
async function sendBroadcast() {
const message = document.getElementById('broadcast-message').value.trim();
const resultSpan = document.getElementById('broadcast-result');
if (!message) {
alert('请输入要广播的消息!');
return;
}
if (!confirm(`确定要向所有服务器广播以下消息吗?\n\n"${message}"`)) {
return;
}
resultSpan.textContent = '发送中...';
try {
const response = await fetch('/api/broadcast', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ message })
});
const data = await response.json();
if (data.success) {
resultSpan.textContent = `✅ 成功发送到 ${data.sent_to} 个服务器`;
resultSpan.style.color = '#3ba55d';
document.getElementById('broadcast-message').value = '';
} else {
resultSpan.textContent = '❌ 发送失败';
resultSpan.style.color = '#ed4245';
}
} catch (error) {
console.error('广播消息失败:', error);
resultSpan.textContent = '❌ 发送失败: ' + error.message;
resultSpan.style.color = '#ed4245';
}
// 3秒后清除结果
setTimeout(() => {
resultSpan.textContent = '';
}, 3000);
}
// 辅助函数:格式化日期时间
function formatDateTime(datetime) {
if (!datetime) return '-';
const date = new Date(datetime);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}`;
}
// 辅助函数:获取排名表情
function getRankEmoji(rank) {
const emojis = ['🥇', '🥈', '🥉'];
return emojis[rank - 1] || '•';
}
|