DiscordBot / diagnose.py
QwertOs's picture
2
2fd3032 verified
Raw History Blame Contribute Delete
6.03 kB
"""
Bot 诊断工具 - 检查常见问题
"""
import asyncio
import aiohttp
import sys
from config import settings
async def check_internet():
"""检查网络连接"""
print("🔍 检查网络连接...")
try:
async with aiohttp.ClientSession() as session:
async with session.get('https://discord.com/api/v10/gateway', timeout=5) as resp:
if resp.status == 200:
print("✅ 网络连接正常")
return True
except Exception as e:
print(f"❌ 网络连接失败: {e}")
return False
async def check_discord_api():
"""检查 Discord API"""
print("\n🔍 检查 Discord API...")
try:
headers = {
'Authorization': f'Bot {settings.BOT_TOKEN}'
}
async with aiohttp.ClientSession() as session:
async with session.get(
'https://discord.com/api/v10/users/@me',
headers=headers,
timeout=5
) as resp:
if resp.status == 200:
data = await resp.json()
print(f"✅ Discord API 正常")
print(f" Bot: {data['username']}")
return True
elif resp.status == 401:
print("❌ Bot Token 无效")
return False
except Exception as e:
print(f"❌ Discord API 检查失败: {e}")
return False
def check_ports():
"""检查端口占用"""
print("\n🔍 检查端口状态...")
import socket
ports_to_check = [8000, 8080] # 使用标准端口
for port in ports_to_check:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('localhost', port))
if result == 0:
print(f"✅ 端口 {port} 正在使用(Bot 运行中)")
else:
print(f"⚠️ 端口 {port} 未使用(Bot 可能未启动)")
sock.close()
def check_env():
"""检查环境变量"""
print("\n🔍 检查配置...")
if not settings.BOT_TOKEN or settings.BOT_TOKEN == "your_discord_bot_token_here":
print("❌ BOT_TOKEN 未配置或使用默认值")
return False
print(f"✅ BOT_TOKEN 已配置 (长度: {len(settings.BOT_TOKEN)})")
print(f"✅ LOG_LEVEL: {settings.LOG_LEVEL}")
return True
async def check_web_dashboard():
"""检查 Web 控制台"""
print("\n🔍 检查 Web 控制台...")
try:
async with aiohttp.ClientSession() as session:
async with session.get('http://localhost:8080/', timeout=3) as resp:
if resp.status == 200:
print("✅ Web 控制台可访问 (http://localhost:8080)")
return True
except Exception as e:
print(f"⚠️ Web 控制台无法访问: {e}")
print(" 提示:如果刚启动,可能需要等待几秒")
return False
async def check_health_endpoint():
"""检查健康检查端点"""
print("\n🔍 检查健康检查端点...")
try:
async with aiohttp.ClientSession() as session:
async with session.get('http://localhost:8000/health', timeout=3) as resp:
if resp.status == 200:
data = await resp.json()
print(f"✅ 健康检查正常")
print(f" 状态: {data.get('status', 'unknown')}")
print(f" 延迟: {data.get('latency', 'N/A')}ms")
print(f" 服务器数: {data.get('guilds', 0)}")
return True
except Exception as e:
print(f"⚠️ 健康检查端点无法访问: {e}")
return False
async def main():
print("=" * 60)
print(" Discord Bot 诊断工具")
print("=" * 60)
print()
results = []
# 检查配置
results.append(("配置检查", check_env()))
# 检查端口
check_ports()
# 检查网络
results.append(("网络连接", await check_internet()))
# 检查 Discord API
results.append(("Discord API", await check_discord_api()))
# 检查 Web 控制台
results.append(("Web 控制台", await check_web_dashboard()))
# 检查健康检查
results.append(("健康检查", await check_health_endpoint()))
# 总结
print("\n" + "=" * 60)
print(" 诊断结果总结")
print("=" * 60)
all_passed = True
for name, passed in results:
status = "✅ 通过" if passed else "❌ 失败"
print(f" {name}: {status}")
if not passed:
all_passed = False
print()
if all_passed:
print("🎉 所有检查通过!")
print()
print("如果 Bot 仍然反应超时,可能的原因:")
print(" 1. Discord API 临时延迟(稍后重试)")
print(" 2. 命令执行时间过长(检查代码逻辑)")
print(" 3. 数据库查询慢(优化查询或添加索引)")
print(" 4. 网络波动(检查网络稳定性)")
print()
print("建议:")
print(" - 查看日志文件: logs/bot.log")
print(" - 查看错误日志: logs/error.log")
print(" - 检查 Discord 状态: https://discordstatus.com")
else:
print("⚠️ 部分检查失败,请修复上述问题。")
print()
print("常见解决方案:")
print(" 1. 配置问题 → 检查 .env 文件")
print(" 2. 网络问题 → 检查防火墙和代理")
print(" 3. Token 问题 → 重置 Bot Token")
print(" 4. 端口问题 → 杀死占用进程或更改端口")
return all_passed
if __name__ == "__main__":
result = asyncio.run(main())
input("\n按回车键退出...")