85 lines
3.0 KiB
Python
85 lines
3.0 KiB
Python
from datetime import datetime, time
|
|
|
|
import discord
|
|
from discord import app_commands
|
|
from discord.ext import commands, tasks
|
|
|
|
import db
|
|
from config import TZ
|
|
|
|
SERVER_TOP = 10
|
|
GLOBAL_TOP = 20
|
|
COLUMNS = {"signin": "total_signin", "exp": "exp"}
|
|
|
|
|
|
class Rank(commands.Cog):
|
|
def __init__(self, bot: commands.Bot):
|
|
self.bot = bot
|
|
self.global_cache: dict[str, list] = {}
|
|
self.global_updated: datetime | None = None
|
|
|
|
async def cog_load(self):
|
|
self.refresh_global()
|
|
self.daily_refresh.start()
|
|
|
|
async def cog_unload(self):
|
|
self.daily_refresh.cancel()
|
|
|
|
# 全國排行榜每日 00:00 更新
|
|
@tasks.loop(time=time(0, 0, tzinfo=TZ))
|
|
async def daily_refresh(self):
|
|
self.refresh_global()
|
|
|
|
def refresh_global(self):
|
|
for key, col in COLUMNS.items():
|
|
self.global_cache[key] = db.conn.execute(
|
|
f"SELECT id, {col} AS value FROM users WHERE {col} > 0 ORDER BY {col} DESC LIMIT ?",
|
|
(GLOBAL_TOP,),
|
|
).fetchall()
|
|
self.global_updated = datetime.now(TZ)
|
|
|
|
def server_rank(self, guild: discord.Guild, col: str) -> list[tuple[str, int]]:
|
|
rows = db.conn.execute(f"SELECT id, {col} AS value FROM users WHERE {col} > 0 ORDER BY {col} DESC")
|
|
result = []
|
|
for row in rows:
|
|
member = guild.get_member(row["id"])
|
|
if member:
|
|
result.append((member.display_name, row["value"]))
|
|
if len(result) >= SERVER_TOP:
|
|
break
|
|
return result
|
|
|
|
def global_rank(self, key: str) -> list[tuple[str, int]]:
|
|
result = []
|
|
for row in self.global_cache[key]:
|
|
user = self.bot.get_user(row["id"])
|
|
result.append((user.name if user else f"(ID:{row['id']})", row["value"]))
|
|
return result
|
|
|
|
@app_commands.command(name="排行榜", description="查看排行榜")
|
|
@app_commands.describe(類型="選擇排行榜類型")
|
|
@app_commands.choices(類型=[
|
|
app_commands.Choice(name="簽到-本伺服器", value="signin_server"),
|
|
app_commands.Choice(name="簽到-全國", value="signin_all"),
|
|
app_commands.Choice(name="經驗-本伺服器", value="exp_server"),
|
|
app_commands.Choice(name="經驗-全國", value="exp_all"),
|
|
])
|
|
@app_commands.guild_only()
|
|
async def rank(self, interaction: discord.Interaction, 類型: app_commands.Choice[str]):
|
|
key, scope = 類型.value.split("_")
|
|
if scope == "server":
|
|
data = self.server_rank(interaction.guild, COLUMNS[key])
|
|
footer = ""
|
|
else:
|
|
data = self.global_rank(key)
|
|
footer = f"\n更新時間:{self.global_updated:%Y-%m-%d %H:%M}(每日 00:00 更新)"
|
|
|
|
body = "\n".join(f"{i}. {name} - {value}" for i, (name, value) in enumerate(data, start=1))
|
|
await interaction.response.send_message(
|
|
f"**{類型.name} 排行榜**\n```{body or '(目前沒有資料)'}```{footer}"
|
|
)
|
|
|
|
|
|
async def setup(bot: commands.Bot):
|
|
await bot.add_cog(Rank(bot))
|