Files

53 lines
2.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import discord
from discord import app_commands
from discord.ext import commands
import db
SIZE = 5 # 每個排行榜顯示的格數
EMPTY = "-----"
MEDALS = {1: "🥇 ", 2: "🥈 ", 3: "🥉 "}
def line(rank: int, user_id: int, points: int, currency: str) -> str:
return f"{MEDALS.get(rank, '')}第 {rank} 名|<@{user_id}>|{points} {currency}"
async def reply(interaction: discord.Interaction, text: str):
# 公開訊息,用 mention 顯示名字但不要 tag 到人
await interaction.response.send_message(text, allowed_mentions=discord.AllowedMentions.none())
@app_commands.guild_only()
class Leaderboard(commands.GroupCog, group_name="排行榜", group_description="簽到點數排行榜"):
@app_commands.command(name="伺服器", description="查看這個伺服器的前五名")
async def server(self, interaction: discord.Interaction):
currency = db.get_setting(interaction.guild_id, "currency_name")
lines = [line(*row, currency) for row in db.get_ranking(interaction.guild_id)[:SIZE]]
lines += [EMPTY] * (SIZE - len(lines))
await reply(interaction, "**🏆 伺服器排行榜**\n" + "\n".join(lines))
@app_commands.command(name="個人", description="查看自己的名次和前後各兩位")
async def personal(self, interaction: discord.Interaction):
user = interaction.user
ranking = db.get_ranking(interaction.guild_id)
index = next((i for i, row in enumerate(ranking) if row[1] == user.id), None)
if index is None:
await reply(interaction, f"{user.mention} 在這個伺服器還沒有簽到紀錄")
return
currency = db.get_setting(interaction.guild_id, "currency_name")
lines = []
for i in range(index - SIZE // 2, index + SIZE // 2 + 1):
if not 0 <= i < len(ranking):
lines.append(EMPTY)
elif i == index:
lines.append(f"**▶ {line(*ranking[i], currency)}**")
else:
lines.append(line(*ranking[i], currency))
await reply(interaction, f"**📊 {user.mention} 的排名**\n" + "\n".join(lines))
async def setup(bot: commands.Bot):
await bot.add_cog(Leaderboard())