Skip to main content

Overview

The /leaderboard command displays the top 10 users in the server ranked by their experience points (XP). This allows you to see who the most active and engaged members are.

Parameters

This command takes no parameters.

Usage

/leaderboard

Response

The bot will respond with an embed message titled “Leaderboard” showing:
  • Rank (1-10)
  • Discord username
  • Total XP for each user

Example Response

Leaderboard

1. @johndoe - 5000 XP
2. @janedoe - 4750 XP
3. @student123 - 4200 XP
4. @alice - 3800 XP
5. @bob - 3500 XP
6. @charlie - 3200 XP
7. @david - 2900 XP
8. @emma - 2700 XP
9. @frank - 2500 XP
10. @grace - 2300 XP

Implementation Details

The command queries the database to retrieve the top 10 users by XP:
let users = sqlx::query_as::<sqlx::Postgres, structs::UserXP>(
    "SELECT * FROM user_xp ORDER BY user_xp DESC LIMIT 10",
)
.fetch_all(pool)
.await
.map_err(Error::Database)?;

let mut leaderboard = String::new();
for (i, user) in users.iter().enumerate() {
    let user_discord = serenity::UserId(user.user_id as u64)
        .to_user(&ctx.serenity_context())
        .await
        .map_err(Error::Serenity)?;
    leaderboard.push_str(&format!(
        "{}. {} - {} XP\n",
        i + 1,
        // pomelo-fy affected users (replace #0000 discriminator with empty string and prefix username with an @)
        user_discord.tag().replace("#0000", ""),
        user.user_xp
    ));
}

Username Formatting

The command handles Discord’s username system changes (“Pomelo” update):
  • Users with the legacy discriminator #0000 have it removed from display
  • Usernames are shown in their tag format

Localization

This command supports multiple languages:
LanguageCommand NameDescription
English/leaderboardShow the Top 10 users by XP
German/leaderboardZeige die besten 10 Nutzer anhand ihrer XP
Japanese/leaderboard(Uses English as fallback)

Database Schema

The command queries the user_xp table:
SELECT * FROM user_xp ORDER BY user_xp DESC LIMIT 10
Table structure:
  • user_id: Discord user ID (bigint)
  • user_xp: Total experience points (integer)
  • user_level: Current level (integer)

Permissions

  • No guild restriction: This command can be used in servers or DMs
  • No special permissions required for users to run this command

Performance Considerations

The leaderboard command:
  • Fetches only the top 10 users (not the entire database)
  • Uses efficient SQL ordering with ORDER BY user_xp DESC LIMIT 10
  • Makes individual Discord API calls to fetch user information for each of the 10 users
  • /xp - View your own XP and level

Notes

  • The leaderboard shows active users who have earned XP through server participation
  • If fewer than 10 users have earned XP, the leaderboard will show only those users
  • XP is earned through various activities in the server (see the /xp command documentation for more details)

Build docs developers (and LLMs) love