Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

A leaderboard can be implemented in Discord.py by using a database to store the scores and a command to display the leaderboard. Here's an example:

  1. Set up the database:
import sqlite3

# Connect to the database
conn = sqlite3.connect('leaderboard.db')

# Create a table to store the scores
conn.execute('''CREATE TABLE IF NOT EXISTS scores
             (user_id TEXT PRIMARY KEY,
              username TEXT,
              score INTEGER)''')
  1. Whenever a user earns points, update the database:
# Increment the user's score by 10
user_id = '123'
username = 'John'
conn.execute('INSERT OR REPLACE INTO scores (user_id, username, score) VALUES (?, ?, COALESCE((SELECT score FROM scores WHERE user_id = ?), 0) + ?)', (user_id, username, user_id, 10))
conn.commit()
  1. Create a leaderboard command:
import discord

@client.command()
async def leaderboard(ctx):
    embed = discord.Embed(title='Leaderboard')
    # Order the scores by descending order and limit to the top 10
    cursor = conn.execute('SELECT username, score FROM scores ORDER BY score DESC LIMIT 10')
    leaderboard = cursor.fetchall()
    for index, (username, score) in enumerate(leaderboard):
        embed.add_field(name=f'{index + 1}. {username}', value=f'Score: {score}', inline=False)
    await ctx.send(embed=embed)

This command will fetch the top 10 scores from the database, create an embed with the leaderboard, and send it to the channel where the command was used.