// 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 = '加载中...'; try { const response = await fetch('/api/tickets'); const data = await response.json(); if (data.tickets.length === 0) { tbody.innerHTML = '暂无工单数据'; return; } tbody.innerHTML = data.tickets.map(ticket => ` #${ticket.ticket_id} ${ticket.type} ${ticket.status === 'open' ? '🟢 进行中' : '🔴 已关闭'} ${formatDateTime(ticket.created_at)} ${ticket.closed_at ? formatDateTime(ticket.closed_at) : '-'} `).join(''); } catch (error) { console.error('加载工单列表失败:', error); tbody.innerHTML = '加载失败'; } } // 刷新等级排行榜 async function refreshLevels() { const tbody = document.getElementById('levels-table-body'); tbody.innerHTML = '加载中...'; try { const response = await fetch('/api/levels'); const data = await response.json(); if (data.levels.length === 0) { tbody.innerHTML = '暂无等级数据'; return; } tbody.innerHTML = data.levels.map((level, index) => ` ${getRankEmoji(index + 1)} ${index + 1} ${level.user_id} ${level.level} ${level.experience} XP ${level.messages_sent} `).join(''); } catch (error) { console.error('加载等级数据失败:', error); tbody.innerHTML = '加载失败'; } } // 发送广播消息 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] || '•'; }