86 lines
2.6 KiB
Python
Executable File
86 lines
2.6 KiB
Python
Executable File
import discord
|
|
from discord.ext import commands
|
|
from discord import app_commands
|
|
import sqlite3
|
|
|
|
class Leaderboard(commands.Cog):
|
|
def __init__(self, bot):
|
|
self.bot = bot
|
|
|
|
@app_commands.command(
|
|
name="leaderboard",
|
|
description="Best players by accuracy"
|
|
)
|
|
async def leaderboard(self, interaction: discord.Interaction):
|
|
conn = sqlite3.connect("Goonerdle.db")
|
|
cursor = conn.cursor()
|
|
|
|
try:
|
|
cursor.execute("""
|
|
SELECT
|
|
User_ID,
|
|
COUNT(*) as games_played,
|
|
SUM(Result) as total_correct
|
|
FROM Result
|
|
GROUP BY User_ID
|
|
""")
|
|
|
|
rows = cursor.fetchall()
|
|
|
|
if not rows:
|
|
await interaction.response.send_message("No data available.")
|
|
return
|
|
|
|
leaderboard_data = []
|
|
|
|
# Calculate accuracy
|
|
for user_id, games_played, total_correct in rows:
|
|
total_possible = games_played * 10
|
|
accuracy = (total_correct / total_possible) * 100
|
|
|
|
leaderboard_data.append((user_id, accuracy, games_played))
|
|
|
|
# Sort by accuracy descending
|
|
leaderboard_data.sort(key=lambda x: x[1], reverse=True)
|
|
|
|
# Build leaderboard text
|
|
lines = []
|
|
position = 1
|
|
|
|
for user_id, accuracy, games_played in leaderboard_data[:10]:
|
|
# Try cache first
|
|
user = self.bot.get_user(user_id)
|
|
|
|
# Fetch if not cached
|
|
if user is None:
|
|
try:
|
|
user = await self.bot.fetch_user(user_id)
|
|
except e:
|
|
user = None
|
|
|
|
# NO PINGS → use display name or username
|
|
if user:
|
|
name = user.display_name if hasattr(user, "display_name") else user.name
|
|
else:
|
|
name = f"User {user_id}"
|
|
|
|
line = f"{position}. {name} — **{accuracy:.2f}%** ({games_played} games)"
|
|
lines.append(line)
|
|
|
|
position += 1
|
|
|
|
msg = "🏆 **Accuracy Leaderboard** 🏆\n\n" + "\n".join(lines)
|
|
|
|
await interaction.response.send_message(msg)
|
|
|
|
except Exception as e:
|
|
print("Leaderboard error:", e)
|
|
await interaction.response.send_message("Error loading leaderboard.")
|
|
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
async def setup(bot):
|
|
await bot.add_cog(Leaderboard(bot))
|