Spaces:
Paused
Paused
Download web/dashboard.py from QwertOs/DiscordBot: direct link, hf CLI and curl.
- Browser
- Download file 9.68 kB
-
https://huggingface.co/spaces/QwertOs/DiscordBot/resolve/main/web/dashboard.py
- Command line
-
hf download hf://spaces/QwertOs/DiscordBot/web/dashboard.py
-
curl -L -o dashboard.py https://huggingface.co/spaces/QwertOs/DiscordBot/resolve/main/web/dashboard.py
9.68 kB
| """ | |
| Discord Bot Web 控制台 - FastAPI 后端 | |
| 提供实时监控、统计数据和远程管理功能 | |
| """ | |
| from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect, HTTPException | |
| from fastapi.responses import HTMLResponse, JSONResponse | |
| from fastapi.templating import Jinja2Templates | |
| from fastapi.staticfiles import StaticFiles | |
| from pydantic import BaseModel | |
| from typing import Optional, List | |
| import asyncio | |
| import json | |
| from datetime import datetime | |
| import structlog | |
| logger = structlog.get_logger() | |
| class WebDashboard: | |
| """Web 控制台主类""" | |
| def __init__(self, bot): | |
| self.bot = bot | |
| self.app = FastAPI(title="Discord Bot Dashboard") | |
| self.templates = Jinja2Templates(directory="web/templates") | |
| self.connected_clients: List[WebSocket] = [] | |
| self.start_time = datetime.utcnow() | |
| # 注册路由 | |
| self._register_routes() | |
| def _register_routes(self): | |
| """注册所有路由""" | |
| async def dashboard(request: Request): | |
| """主控制面板页面""" | |
| return self.templates.TemplateResponse("dashboard.html", { | |
| "request": request, | |
| "bot_name": self.bot.user.name if self.bot.user else "Bot", | |
| "bot_id": self.bot.user.id if self.bot.user else 0 | |
| }) | |
| async def get_stats(): | |
| """获取 Bot 统计数据""" | |
| try: | |
| uptime = (datetime.utcnow() - self.start_time).total_seconds() | |
| stats = { | |
| "bot_info": { | |
| "name": self.bot.user.name if self.bot.user else "N/A", | |
| "id": str(self.bot.user.id) if self.bot.user else "N/A", | |
| "status": str(self.bot.status) if self.bot.status else "offline", | |
| "uptime_seconds": round(uptime), | |
| "uptime_formatted": self._format_uptime(uptime) | |
| }, | |
| "server_stats": { | |
| "total_guilds": len(self.bot.guilds), | |
| "total_users": sum(guild.member_count for guild in self.bot.guilds) if self.bot.guilds else 0, | |
| "total_channels": sum(len(guild.channels) for guild in self.bot.guilds) if self.bot.guilds else 0 | |
| }, | |
| "performance": { | |
| "latency_ms": round(self.bot.latency * 1000, 2) if self.bot.latency else 0, | |
| "commands_registered": len(self.bot.tree.get_commands()) | |
| } | |
| } | |
| return JSONResponse(content=stats) | |
| except Exception as e: | |
| logger.error(f"获取统计数据失败: {e}", exc_info=True) | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def get_tickets(): | |
| """获取工单列表""" | |
| try: | |
| conn = self.bot.pool | |
| if not conn: | |
| return JSONResponse(content={"tickets": [], "message": "数据库未连接"}) | |
| cursor = await conn.execute( | |
| """SELECT * FROM tickets | |
| ORDER BY created_at DESC | |
| LIMIT 50""" | |
| ) | |
| rows = await cursor.fetchall() | |
| tickets = [] | |
| for row in rows: | |
| tickets.append({ | |
| "ticket_id": row[0], | |
| "user_id": row[1], | |
| "channel_id": row[2], | |
| "type": row[3], | |
| "status": row[4], | |
| "created_at": row[5], | |
| "closed_at": row[6] | |
| }) | |
| return JSONResponse(content={"tickets": tickets}) | |
| except Exception as e: | |
| logger.error(f"获取工单列表失败: {e}", exc_info=True) | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def get_top_levels(): | |
| """获取等级排行榜""" | |
| try: | |
| conn = self.bot.pool | |
| if not conn: | |
| return JSONResponse(content={"levels": [], "message": "数据库未连接"}) | |
| cursor = await conn.execute( | |
| """SELECT user_id, level, experience, messages_sent | |
| FROM user_levels | |
| ORDER BY level DESC, experience DESC | |
| LIMIT 20""" | |
| ) | |
| rows = await cursor.fetchall() | |
| levels = [] | |
| for row in rows: | |
| levels.append({ | |
| "user_id": row[0], | |
| "level": row[1], | |
| "experience": row[2], | |
| "messages_sent": row[3] | |
| }) | |
| return JSONResponse(content={"levels": levels}) | |
| except Exception as e: | |
| logger.error(f"获取等级数据失败: {e}", exc_info=True) | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def websocket_endpoint(websocket: WebSocket): | |
| """WebSocket 实时数据推送""" | |
| await websocket.accept() | |
| self.connected_clients.append(websocket) | |
| try: | |
| while True: | |
| # 接收客户端消息(可选) | |
| data = await websocket.receive_text() | |
| # 可以处理客户端请求 | |
| if data == "ping": | |
| await websocket.send_text("pong") | |
| except WebSocketDisconnect: | |
| self.connected_clients.remove(websocket) | |
| logger.info("WebSocket 客户端断开连接") | |
| except Exception as e: | |
| logger.error(f"WebSocket 错误: {e}", exc_info=True) | |
| if websocket in self.connected_clients: | |
| self.connected_clients.remove(websocket) | |
| async def broadcast_message(request: Request): | |
| """广播消息到所有服务器""" | |
| try: | |
| data = await request.json() | |
| message = data.get("message", "") | |
| if not message: | |
| raise HTTPException(status_code=400, detail="消息不能为空") | |
| sent_count = 0 | |
| for guild in self.bot.guilds: | |
| for channel in guild.text_channels: | |
| if channel.permissions_for(guild.me).send_messages: | |
| try: | |
| await channel.send(message) | |
| sent_count += 1 | |
| break # 每个服务器只发送到一个频道 | |
| except: | |
| continue | |
| return JSONResponse(content={ | |
| "success": True, | |
| "sent_to": sent_count | |
| }) | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| logger.error(f"广播消息失败: {e}", exc_info=True) | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| def _format_uptime(self, seconds: float) -> str: | |
| """格式化运行时间""" | |
| days = int(seconds // 86400) | |
| hours = int((seconds % 86400) // 3600) | |
| minutes = int((seconds % 3600) // 60) | |
| secs = int(seconds % 60) | |
| if days > 0: | |
| return f"{days}天 {hours}小时 {minutes}分钟" | |
| elif hours > 0: | |
| return f"{hours}小时 {minutes}分钟 {secs}秒" | |
| elif minutes > 0: | |
| return f"{minutes}分钟 {secs}秒" | |
| else: | |
| return f"{secs}秒" | |
| async def broadcast_update(self, data: dict): | |
| """向所有连接的客户端广播更新""" | |
| if self.connected_clients: | |
| message = json.dumps(data) | |
| disconnected = [] | |
| for client in self.connected_clients: | |
| try: | |
| await client.send_text(message) | |
| except: | |
| disconnected.append(client) | |
| # 清理断开的连接 | |
| for client in disconnected: | |
| if client in self.connected_clients: | |
| self.connected_clients.remove(client) | |
| async def start(self, host: str = "0.0.0.0", port: int = 8080): | |
| """启动 Web 控制台""" | |
| import uvicorn | |
| config = uvicorn.Config( | |
| self.app, | |
| host=host, | |
| port=port, | |
| log_level="info" | |
| ) | |
| server = uvicorn.Server(config) | |
| logger.info(f"🌐 Web 控制台启动中... http://{host}:{port}") | |
| # 在后台运行服务器 | |
| asyncio.create_task(server.serve()) | |
| return server | |