-
Notifications
You must be signed in to change notification settings - Fork 2
feat(reputation): add XP/leveling system with rank and leaderboard #109
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
5691ebb
feat(reputation): add XP/leveling system with rank and leaderboard co…
BillChirico 567e73a
refactor: extract shared reputation defaults, add full dashboard UI f…
BillChirico aeb249a
fix: remove stale DEFAULT_THRESHOLDS ref, add try/catch to rank and l…
BillChirico 584479a
fix(reputation): address PR review — crashes, guards, schema, tests
BillChirico 30beaca
fix: static logger imports, remove v13 displayAvatarURL option, guild…
BillChirico 95f4c9b
test(rank): add max-level and displayName fallback branch coverage
BillChirico 4673195
fix(reputation): address review — cooldown sweep, batch fetch, test c…
BillChirico 3a674d5
fix(config): remove duplicate 'afk' entry from SAFE_CONFIG_KEYS allow…
BillChirico f49a056
fix(reputation): sweep export, guild guard, error handling, UI valida…
BillChirico 79c82a9
docs: add reputation config reference to README
BillChirico File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| /** | ||
| * Add reputation table for XP/leveling system. | ||
| * | ||
| * @see https://github.com/VolvoxLLC/volvox-bot/issues/45 | ||
| */ | ||
|
|
||
| /** @param {import('node-pg-migrate').MigrationBuilder} pgm */ | ||
| exports.up = (pgm) => { | ||
| pgm.sql(` | ||
| CREATE TABLE IF NOT EXISTS reputation ( | ||
| id SERIAL PRIMARY KEY, | ||
| guild_id TEXT NOT NULL, | ||
| user_id TEXT NOT NULL, | ||
| xp INTEGER NOT NULL DEFAULT 0, | ||
| level INTEGER NOT NULL DEFAULT 0, | ||
| messages_count INTEGER NOT NULL DEFAULT 0, | ||
| voice_minutes INTEGER NOT NULL DEFAULT 0, | ||
| helps_given INTEGER NOT NULL DEFAULT 0, | ||
| last_xp_gain TIMESTAMPTZ, | ||
| created_at TIMESTAMPTZ DEFAULT NOW(), | ||
| UNIQUE(guild_id, user_id) | ||
| ) | ||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| `); | ||
|
|
||
| pgm.sql('CREATE INDEX IF NOT EXISTS idx_reputation_guild_xp ON reputation(guild_id, xp DESC)'); | ||
| }; | ||
|
|
||
| /** @param {import('node-pg-migrate').MigrationBuilder} pgm */ | ||
| exports.down = (pgm) => { | ||
| pgm.sql('DROP TABLE IF EXISTS reputation CASCADE'); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||
|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,79 @@ | ||||||||
| /** | ||||||||
| * Leaderboard Command | ||||||||
| * Show the top 10 users by XP in this server. | ||||||||
| * | ||||||||
| * @see https://github.com/VolvoxLLC/volvox-bot/issues/45 | ||||||||
| */ | ||||||||
|
|
||||||||
| import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; | ||||||||
| import { getPool } from '../db.js'; | ||||||||
| import { error as logError } from '../logger.js'; | ||||||||
| import { getConfig } from '../modules/config.js'; | ||||||||
| import { safeEditReply } from '../utils/safeSend.js'; | ||||||||
|
|
||||||||
| export const data = new SlashCommandBuilder() | ||||||||
| .setName('leaderboard') | ||||||||
| .setDescription('Show the top 10 members by XP in this server'); | ||||||||
|
|
||||||||
| /** | ||||||||
| * Execute the /leaderboard command. | ||||||||
| * | ||||||||
| * @param {import('discord.js').ChatInputCommandInteraction} interaction | ||||||||
| */ | ||||||||
| export async function execute(interaction) { | ||||||||
| await interaction.deferReply(); | ||||||||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||
|
|
||||||||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||
| const cfg = getConfig(interaction.guildId); | ||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Warning: Missing guild-context guard
Suggested change
|
||||||||
| if (!cfg?.reputation?.enabled) { | ||||||||
| return safeEditReply(interaction, { content: 'Reputation system is not enabled.' }); | ||||||||
| } | ||||||||
|
|
||||||||
| try { | ||||||||
| const pool = getPool(); | ||||||||
| const { rows } = await pool.query( | ||||||||
| `SELECT user_id, xp, level | ||||||||
| FROM reputation | ||||||||
| WHERE guild_id = $1 | ||||||||
| ORDER BY xp DESC | ||||||||
| LIMIT 10`, | ||||||||
| [interaction.guildId], | ||||||||
| ); | ||||||||
|
|
||||||||
| if (rows.length === 0) { | ||||||||
| await safeEditReply(interaction, { | ||||||||
| content: '📭 No one has earned XP yet. Start chatting!', | ||||||||
| }); | ||||||||
| return; | ||||||||
| } | ||||||||
|
|
||||||||
| // Batch-fetch all members in a single API call | ||||||||
| const memberMap = new Map(); | ||||||||
| try { | ||||||||
| const members = await interaction.guild.members.fetch({ user: rows.map((r) => r.user_id) }); | ||||||||
| for (const [id, member] of members) memberMap.set(id, member.displayName); | ||||||||
| } catch { | ||||||||
| // Fall back — entries will use mention format | ||||||||
| } | ||||||||
|
|
||||||||
| // Resolve display names | ||||||||
| const lines = rows.map((row, i) => { | ||||||||
| const displayName = memberMap.get(row.user_id) ?? `<@${row.user_id}>`; | ||||||||
| const medal = i === 0 ? '🥇' : i === 1 ? '🥈' : i === 2 ? '🥉' : `**${i + 1}.**`; | ||||||||
| return `${medal} ${displayName} — Level ${row.level} • ${row.xp} XP`; | ||||||||
| }); | ||||||||
|
|
||||||||
| const embed = new EmbedBuilder() | ||||||||
| .setColor(0xfee75c) | ||||||||
| .setTitle('🏆 XP Leaderboard') | ||||||||
| .setDescription(lines.join('\n')) | ||||||||
| .setFooter({ text: `Top ${rows.length} members` }) | ||||||||
| .setTimestamp(); | ||||||||
|
|
||||||||
| await safeEditReply(interaction, { embeds: [embed] }); | ||||||||
| } catch (err) { | ||||||||
| logError('Leaderboard command failed', { error: err.message, stack: err.stack }); | ||||||||
| await safeEditReply(interaction, { | ||||||||
| content: '❌ Something went wrong fetching the leaderboard.', | ||||||||
| }); | ||||||||
| } | ||||||||
| } | ||||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| /** | ||
| * Rank Command | ||
| * Show a user's level, XP, and progress bar. | ||
| * | ||
| * @see https://github.com/VolvoxLLC/volvox-bot/issues/45 | ||
| */ | ||
|
|
||
| import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; | ||
| import { getPool } from '../db.js'; | ||
| import { error as logError } from '../logger.js'; | ||
| import { getConfig } from '../modules/config.js'; | ||
| import { buildProgressBar, computeLevel } from '../modules/reputation.js'; | ||
| import { REPUTATION_DEFAULTS } from '../modules/reputationDefaults.js'; | ||
| import { safeEditReply } from '../utils/safeSend.js'; | ||
|
|
||
| export const data = new SlashCommandBuilder() | ||
| .setName('rank') | ||
| .setDescription("Show your (or another user's) level and XP") | ||
| .addUserOption((opt) => | ||
| opt.setName('user').setDescription('User to look up (defaults to you)').setRequired(false), | ||
| ); | ||
|
|
||
| /** | ||
| * Execute the /rank command. | ||
| * | ||
| * @param {import('discord.js').ChatInputCommandInteraction} interaction | ||
| */ | ||
| export async function execute(interaction) { | ||
| await interaction.deferReply(); | ||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if (!interaction.guildId) { | ||
| return safeEditReply(interaction, { content: '❌ This command can only be used in a server.' }); | ||
| } | ||
|
|
||
| const cfg = getConfig(interaction.guildId); | ||
| if (!cfg?.reputation?.enabled) { | ||
| return safeEditReply(interaction, { content: 'Reputation system is not enabled.' }); | ||
| } | ||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| try { | ||
| const pool = getPool(); | ||
| const target = interaction.options.getUser('user') ?? interaction.user; | ||
| const repCfg = { ...REPUTATION_DEFAULTS, ...cfg.reputation }; | ||
| const thresholds = repCfg.levelThresholds; | ||
|
|
||
| // Fetch reputation row | ||
| const { rows } = await pool.query( | ||
| 'SELECT xp, level, messages_count FROM reputation WHERE guild_id = $1 AND user_id = $2', | ||
| [interaction.guildId, target.id], | ||
| ); | ||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| const xp = rows[0]?.xp ?? 0; | ||
| const level = computeLevel(xp, thresholds); | ||
| const messagesCount = rows[0]?.messages_count ?? 0; | ||
|
|
||
| // XP within current level and needed for next | ||
| const currentThreshold = level > 0 ? thresholds[level - 1] : 0; | ||
| const nextThreshold = thresholds[level] ?? null; // null = max level | ||
|
|
||
| const xpInLevel = xp - currentThreshold; | ||
| const xpNeeded = nextThreshold !== null ? nextThreshold - currentThreshold : 0; | ||
| const progressBar = | ||
| nextThreshold !== null ? buildProgressBar(xpInLevel, xpNeeded) : `${'▓'.repeat(10)} MAX`; | ||
|
|
||
| // Rank position in guild | ||
| const rankRow = await pool.query( | ||
| `SELECT COUNT(*) + 1 AS rank | ||
| FROM reputation | ||
| WHERE guild_id = $1 AND xp > $2`, | ||
| [interaction.guildId, xp], | ||
| ); | ||
| const rank = Number(rankRow.rows[0]?.rank ?? 1); | ||
|
|
||
| const levelLabel = `Level ${level}`; | ||
| const xpLabel = nextThreshold !== null ? `${xp} / ${nextThreshold} XP` : `${xp} XP (Max Level)`; | ||
|
|
||
| const embed = new EmbedBuilder() | ||
| .setColor(0x5865f2) | ||
| .setAuthor({ | ||
| name: target.displayName ?? target.username, | ||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| iconURL: target.displayAvatarURL(), | ||
| }) | ||
| .setTitle(`🏆 ${levelLabel}`) | ||
| .addFields( | ||
| { name: 'XP', value: xpLabel, inline: true }, | ||
| { name: 'Server Rank', value: `#${rank}`, inline: true }, | ||
| { name: 'Messages', value: String(messagesCount), inline: true }, | ||
| { | ||
| name: nextThreshold !== null ? `Progress to Level ${level + 1}` : 'Progress', | ||
| value: progressBar, | ||
| inline: false, | ||
| }, | ||
| ) | ||
| .setThumbnail(target.displayAvatarURL()) | ||
| .setTimestamp(); | ||
|
|
||
| await safeEditReply(interaction, { embeds: [embed] }); | ||
| } catch (err) { | ||
| logError('Rank command failed', { error: err.message, stack: err.stack }); | ||
| await safeEditReply(interaction, { content: '❌ Something went wrong fetching your rank.' }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Warning: Documentation says "null = DM user" but implementation skips announcements
The description for
announceChannelIdsays(null = DM user), but the actual implementation inreputation.js:164-190simply skips the announcement whenannounceChannelIdis null — it never DMs the user. Either implement DM functionality or fix the docs: