Skip to content

Leaderboard

A leaderboard shows a ranked list a page at a time: who is first, with what score. It is a paginated view that numbers its rows across pages and draws each page as one card.

Kael clicks the next-page arrow at the foot of the Arena Rankings card: the card shows ranks 6 to 10, and the indicator beside the arrow reads Page 2/2

import discord

from cascadeui import LeaderboardLayoutView, render_progress


class ArenaBoard(LeaderboardLayoutView):
    title = "Arena Rankings"
    entry_layout = "sections"  # (1)!
    nav_inside_container = True  # (2)!
    nav_divider = True

    def format_secondary(self, rank, user_id, stats):  # (3)!
        wins, games = stats["wins"], stats["games"]
        bar = render_progress(wins, games or 1, width=10)
        return f"{wins} wins · {games - wins} losses\n-# {bar}"

    def build_subtitle(self, page):  # (4)!
        entries = self.get_entries()
        games = sum(stats["games"] for _, stats in entries)
        return f"-# Season 3 · {len(entries)} players · {games} games"

    def build_footer(self, page):  # (5)!
        return "-# Ranked by wins"


scores = {user_id: {"wins": 20 - user_id, "games": 24} for user_id in range(1, 11)}  # (6)!


@bot.tree.command(description="Show the arena rankings")
async def rankings(interaction: discord.Interaction):
    rows = sorted(scores.items(), key=lambda row: row[1]["wins"], reverse=True)  # (7)!
    view = ArenaBoard(interaction=interaction, entries=rows, bot=interaction.client)
    await view.send()
  1. Each row gets the player's avatar beside it. The bot passed as bot= looks the avatars up.
  2. The page buttons sit inside the card, under a divider.
  3. The lines under each player's name: the record, then the win rate as a bar. Rows covers each part a row is built from.
  4. A grey line under the title, on every page.
  5. A line at the foot of the card.
  6. Ten players, each user id mapped to their stats. A real board reads these from the bot's own records.
  7. The board ranks entries in the order it gets them, so sort them first.

The panel is one card: the title, a grey line with the season's numbers, the first five players with their wins and losses over a win-rate bar (gold, silver, and bronze medals on the top three), and the footer line. With more than five players, the page arrows and the indicator sit at the foot of the card. A board that fits one page shows no buttons.

A leaderboard suits a ranking the bot already keeps: game results, points, activity. For a list that is not a ranking, use the paginated view it is built on.

Entries and Ranks

entries= takes (user_id, stats) pairs in rank order, each stats a dict the rows read from. A dict of {user_id: stats} works too, in its own order, as does any iterable of pairs. A Member given for an id stands for its id. A wrong entry is refused when the board is built, naming its place: ValueError for a row that is not two items, TypeError for anything else, such as stats that are not a dict.

leaderboard_top_n (default 10) is how many entries are ranked and leaderboard_per_page (default 5) how many sit on a page, so the default board is two pages of five. Ranks continue across pages: page two starts at 6. None for leaderboard_per_page puts every ranked entry on one page, and None for leaderboard_top_n ranks every entry.

The buttons are the paginator's. From five pages the row adds first-page and last-page buttons, and the indicator becomes a button that opens a "Go to Page" box (see Turning Pages).

For entries the board reads itself, override get_entries(). It returns the same pairs and may be async (see Keeping It Current).

Rows

Each row reads rank name -- stats. Four small hooks draw its parts, so an override replaces only the part it changes:

Hook Draws Default
format_rank(rank) The rank. A medal for ranks 1 to 3, **4.** from 4 on.
format_name(user_id, stats) The name. stats["display_name"] as written, else a mention of user_id.
format_stats(user_id, stats) The stats. 12W / 20G, from wins and games (0 when missing).
format_accessory(user_id, stats) A tag after the stats. Nothing.

format_entry(rank, user_id, stats) joins them, with entry_separator (default " -- ") between the name and the stats. Override it for a row of another shape. The four part hooks run inside it, so they are plain defs: an async def one is refused when the class is defined. format_entry itself may be async.

from cascadeui import LeaderboardLayoutView, render_progress


class MmrBoard(LeaderboardLayoutView):
    entry_separator = " | "

    def format_stats(self, user_id, stats):
        bar = render_progress(stats["wins"], stats["games"] or 1, width=6, show_percent=True)
        return f"`{stats['mmr']}` MMR {bar}"

podium_emojis holds the medals, keyed by rank. Change the dict to change them, or add ranks to it, without overriding format_rank. Its keys are numbers: a dict of other keys is refused when the class is defined.

A board mentions players without pinging them: its allowed_mentions is none, so the names show as mentions and nobody gets a notification.

Around the Rows

The parts of a leaderboard page, each labeled with what draws it: the header card above, then inside the rankings card the banner and title, the divider, the subtitle line, the rows, and the footer line, then a footer card below, and the page buttons last

The rankings card opens with its masthead: the banner image, then title as a heading. A divider follows, then the subtitle line, then the rows.

Attribute Default What it does
title "Leaderboard" The heading. None or "" shows none.
banner None An image above the title: a URL, a discord.File, or anything with a .url such as guild.icon.
banner_description None The banner's alt text, up to 1024 characters. None uses a discord.File banner's own description.
subtitle "Rankings" A line above the rows, as a small heading. None or "" leaves a gap in its place.
show_title_divider True The divider under the masthead. There is none when the masthead is empty.
card_color None The card's accent: a discord.Color or an int. None takes the theme's.

title=, subtitle=, banner=, and banner_description= set the same four for one board. A discord.File banner travels with the board: it is uploaded with every send and a return from another screen, with no send(files=...) to add. One sent with spoiler=True shows blurred. A value of the wrong kind for any attribute on this page raises when the class is defined, naming the class and the attribute.

Hooks draw the parts per page. Each takes page, counted from 0, so a part can show on some pages only:

  • build_title(page) replaces the masthead. [] shows none, and None, the default, shows banner and title. What it returns sits inside the rankings card, so a card there raises ValueError naming the hook.
  • build_subtitle(page) gives the subtitle line as markdown ("-# Updated hourly"). "" shows no line and no gap, and None uses subtitle.
  • build_header(page) adds content above the rankings card. A card shows as its own card, and text or another component shows above the card on its own.
  • build_footer(page) adds content below the rows. Text and components join the end of the rankings card, and a card shows as its own card below it.

The title, header, and footer hooks may return a component, a list of them, text, or None, and build_subtitle text or None. Anything else raises TypeError naming the hook.

ranked_entries holds the ranked entries, the first leaderboard_top_n, for a header or footer that counts or sums them. get_entries() returns every entry. A board draws its pages again only when its entries change, so a part that reads anything else shows a change after reload(force=True).

With nav_inside_container = True the page buttons move into the rankings card, after a footer line. A header, or a card from build_footer, keeps them below the card in their own row: the page is then a card beside other things, and a card cannot hold another.

Avatars

entry_layout = "sections" shows each row in two lines, the rank and name above the stats, with the player's avatar beside them.

Three boards side by side. Lines: one row of text per player. Sections with a bot: each row with an avatar beside it. Sections without a bot: each row in two lines of text with no avatar

format_primary(rank, user_id, stats) draws the first line, the rank and name by default, and format_secondary(rank, user_id, stats) the second, the stats. Either may be async. A second line that comes back empty is left out.

get_avatar_url(user_id, stats) gives each avatar. With bot= it finds the player in the bot's cache, or gives Discord's default avatar when they are not there. With no bot it gives None, and the row shows its two lines as text. A PersistentLeaderboardLayoutView gets its bot when it is sent.

An id given as a string of digits, as data read back from JSON is, finds the player it names, and an id that names no Discord user shows as text. Override the hook, plain or async, to read avatars from somewhere else.

A message holds 40 components. A row with an avatar costs four of them and a row of text one, so a page of avatars holds fewer rows: eight fit beside the default title and page buttons, fewer with a header. A page that does not fit raises ValueError when it is drawn, at send(), naming the rows and what to lower. Test a board of avatars with its bot: without one its rows cost one each.

Loading Avatars Later

Players missing from the bot's cache show Discord's default avatar. With avatar_backfill = True the board shows the page at once, then fetches the missing avatars and draws the page again once with them.

Kael opens the board: three rows show the default avatar. A moment later the board draws again with the real avatars, and one player whose account no longer exists keeps the default

The fetch runs once for each set of entries and needs a bot. A player it cannot fetch, such as a deleted account, keeps the default avatar.

resolve_avatar_urls(user_ids) does the fetching: it gets the ids that missed and returns {user_id: url} for the ones it found. The default fetches the players one at a time. A guild's member search finds them in one request:

class BigBoard(LeaderboardLayoutView):
    entry_layout = "sections"
    avatar_backfill = True

    async def resolve_avatar_urls(self, user_ids):
        guild = self.bot.get_guild(self.guild_id)
        if guild is None:
            return {}
        members = await guild.query_members(user_ids=user_ids, limit=len(user_ids))
        return {m.id: m.display_avatar.with_size(128).url for m in members}

An Empty Board

With no entries the board shows one card with leaderboard_empty_message ("No entries recorded yet.") under the masthead, colored by card_color. The header shows above it and the footer where it would on a page with entries, so the board looks the same either side of its first entry. The subtitle line is left out.

on_leaderboard_empty() returns what the card holds instead:

def on_leaderboard_empty(self):
    return "No games yet. Play one with `/duel` to take first place."

Text or components go into a card with the masthead. A card of your own keeps its color and gets the masthead added, except a card marked as a spoiler, which would hide the board's title, and a Container subclass, whose own behavior a copy would drop: those show as they are, below the masthead.

Two cards, or a card beside other components, show as they are, below the masthead. ranked_entries is empty here. Returning None raises TypeError.

Keeping It Current

Override get_entries() to read the ranking where it lives. A board that should follow a ranking kept in the store names the actions that change it in subscribed_actions, and redraws when one is dispatched:

from cascadeui import LeaderboardLayoutView, get_store


class DuelBoard(LeaderboardLayoutView):
    subscribed_actions = {"DUEL_FINISHED"}

    def get_entries(self):
        scores = get_store().get_scoped("guild", guild_id=self.guild_id) or {}
        return sorted(scores.items(), key=lambda row: row[1].get("wins", 0), reverse=True)

Each dispatch the board hears reads get_entries() once, and draws again only when the entries changed: the same players with the same stats, in the same order, skip the redraw.

get_entries() may be async, to query a database. It then runs on every action the board hears, so a board that hears many fetches at those moments instead: load in on_load(), keep the rows, and return them.

class GuildRankings(LeaderboardLayoutView):
    async def on_load(self):
        self.rows = await self.db.rankings(self.guild_id)
        await super().on_load()

    def get_entries(self):
        return getattr(self, "rows", [])

reload() then fetches again and redraws: call it from the code that changes the ranking. Reloads run one at a time, and with refresh_cooldown_ms set a burst of them makes one fetch (see Loading Data). Keep the rows on an attribute of your own, since the board keeps what it was given in entries= for itself.

A Board That Survives a Restart

PersistentLeaderboardLayoutView is a leaderboard posted once and kept: it comes back after the bot restarts. It takes a persistence_key=, and differs from the plain board in three defaults:

Attribute Leaderboard Persistent leaderboard
owner_only True False: everyone can turn its pages.
exit_policy "delete" "disable": closing it leaves it on screen, disabled.
timeout 180 seconds None: it never times out.
from cascadeui import PersistentLeaderboardLayoutView


class ServerBoard(PersistentLeaderboardLayoutView):
    title = "Server Rankings"
    subscribed_actions = {"DUEL_FINISHED"}
    persistent_slots = ("scoped",)  # (1)!

    def get_entries(self):
        scores = self.state_store.get_scoped("guild", guild_id=self.guild_id) or {}
        return sorted(scores.items(), key=lambda row: row[1].get("wins", 0), reverse=True)


await ServerBoard(context=ctx, persistence_key=f"board:{ctx.guild.id}").send()
  1. Saves the scoped data the board reads, so the ranking comes back with the board. See Saving Data.

Each time the board comes back it reads get_entries() and draws again. It gets the bot when it is sent and when it comes back, so avatars work without bot=. A discord.File banner is saved as the upload already on the message, with its description, and a board sent to a new message after a restart reads the image back from the old one. Setting up persistence is covered in Panels That Survive Restarts.