-
Notifications
You must be signed in to change notification settings - Fork 1
feat: daily coding challenge system (#52) #115
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 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
3dde38c
feat: daily coding challenge system (#52)
BillChirico cc8ef34
fix: resolve critical bugs in daily challenge system
BillChirico f07099b
fix(challenge): date-based solves, COUNT cast, bounds check, streak fix
BillChirico b330657
merge: resolve conflicts with main for PR #115
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
Some comments aren't visible on the classic Files Changed page.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| /** | ||
| * Migration 011 β Daily Coding Challenges | ||
| * Creates the challenge_solves table for tracking user solve history. | ||
| * | ||
| * @see https://github.com/VolvoxLLC/volvox-bot/issues/52 | ||
| */ | ||
|
|
||
| 'use strict'; | ||
|
|
||
| /** | ||
| * @param {import('pg').Pool} pool | ||
| */ | ||
| async function up(pool) { | ||
| await pool.query(` | ||
| CREATE TABLE IF NOT EXISTS challenge_solves ( | ||
| guild_id TEXT NOT NULL, | ||
| challenge_index INTEGER NOT NULL, | ||
| user_id TEXT NOT NULL, | ||
| solved_at TIMESTAMPTZ DEFAULT NOW(), | ||
| PRIMARY KEY (guild_id, challenge_index, user_id) | ||
BillChirico marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ); | ||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| `); | ||
|
|
||
| await pool.query(` | ||
| CREATE INDEX IF NOT EXISTS idx_challenge_solves_guild | ||
| ON challenge_solves(guild_id); | ||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| `); | ||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| module.exports = { up }; | ||
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,221 @@ | ||
| /** | ||
| * Challenge Command | ||
| * View today's coding challenge, check your streak, or see the leaderboard. | ||
| * | ||
| * @see https://github.com/VolvoxLLC/volvox-bot/issues/52 | ||
| */ | ||
|
|
||
| import { EmbedBuilder, SlashCommandBuilder } from 'discord.js'; | ||
| import { getPool } from '../db.js'; | ||
| import { info } from '../logger.js'; | ||
| import { | ||
| buildChallengeButtons, | ||
| buildChallengeEmbed, | ||
| selectTodaysChallenge, | ||
| } from '../modules/challengeScheduler.js'; | ||
| import { getConfig } from '../modules/config.js'; | ||
| import { safeEditReply } from '../utils/safeSend.js'; | ||
|
|
||
| export const data = new SlashCommandBuilder() | ||
| .setName('challenge') | ||
| .setDescription('Daily coding challenges') | ||
| .addSubcommand((sub) => sub.setName('today').setDescription("Show today's coding challenge")) | ||
| .addSubcommand((sub) => | ||
| sub.setName('streak').setDescription('Show your solve streak and total solves'), | ||
| ) | ||
| .addSubcommand((sub) => | ||
| sub.setName('leaderboard').setDescription('Top 10 solvers this week and all-time'), | ||
| ); | ||
|
|
||
| /** | ||
| * Execute the /challenge command. | ||
| * | ||
| * @param {import('discord.js').ChatInputCommandInteraction} interaction | ||
| */ | ||
| export async function execute(interaction) { | ||
| await interaction.deferReply({ ephemeral: false }); | ||
|
|
||
| const subcommand = interaction.options.getSubcommand(); | ||
| const config = getConfig(interaction.guildId); | ||
| const challengesCfg = config.challenges ?? {}; | ||
|
|
||
| if (!challengesCfg.enabled) { | ||
| await safeEditReply(interaction, { | ||
| content: 'β Daily coding challenges are not enabled on this server.', | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| if (subcommand === 'today') { | ||
| await handleToday(interaction, challengesCfg); | ||
| } else if (subcommand === 'streak') { | ||
| await handleStreak(interaction); | ||
| } else if (subcommand === 'leaderboard') { | ||
| await handleLeaderboard(interaction); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Handle /challenge today | ||
| * | ||
| * @param {import('discord.js').ChatInputCommandInteraction} interaction | ||
| * @param {Object} challengesCfg | ||
| */ | ||
| async function handleToday(interaction, challengesCfg) { | ||
| const pool = getPool(); | ||
| const timezone = challengesCfg.timezone ?? 'America/New_York'; | ||
| const now = new Date(); | ||
| const { challenge, index, dayNumber } = selectTodaysChallenge(now, timezone); | ||
|
|
||
| // Get current solve count | ||
| let solveCount = 0; | ||
| if (pool) { | ||
| const { rows } = await pool.query( | ||
| 'SELECT COUNT(*) AS total FROM challenge_solves WHERE guild_id = $1 AND challenge_index = $2', | ||
| [interaction.guildId, index], | ||
BillChirico marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ); | ||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| solveCount = Number.parseInt(rows[0].total, 10); | ||
| } | ||
|
|
||
| const embed = buildChallengeEmbed(challenge, dayNumber, solveCount); | ||
| const buttons = buildChallengeButtons(index); | ||
|
|
||
| await safeEditReply(interaction, { embeds: [embed], components: [buttons] }); | ||
|
|
||
| info('/challenge today used', { | ||
| userId: interaction.user.id, | ||
| guildId: interaction.guildId, | ||
| dayNumber, | ||
| challengeTitle: challenge.title, | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Handle /challenge streak | ||
| * | ||
| * @param {import('discord.js').ChatInputCommandInteraction} interaction | ||
| */ | ||
| async function handleStreak(interaction) { | ||
| const pool = getPool(); | ||
| if (!pool) { | ||
| await safeEditReply(interaction, { content: 'β Database unavailable.' }); | ||
| return; | ||
| } | ||
|
|
||
| const { guildId } = interaction; | ||
| const userId = interaction.user.id; | ||
|
|
||
| // Total solves | ||
| const { rows: totalRows } = await pool.query( | ||
| 'SELECT COUNT(*) AS total FROM challenge_solves WHERE guild_id = $1 AND user_id = $2', | ||
| [guildId, userId], | ||
| ); | ||
| const totalSolves = Number.parseInt(totalRows[0].total, 10); | ||
|
|
||
| // All solved challenge indices ordered by index to compute streak | ||
| const { rows: solvedRows } = await pool.query( | ||
| `SELECT challenge_index, solved_at | ||
| FROM challenge_solves | ||
| WHERE guild_id = $1 AND user_id = $2 | ||
BillChirico marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ORDER BY challenge_index DESC`, | ||
| [guildId, userId], | ||
| ); | ||
|
|
||
| // Compute streak: consecutive challenge indices ending at most-recent | ||
| let streak = 0; | ||
| if (solvedRows.length > 0) { | ||
| const indices = solvedRows.map((r) => r.challenge_index); | ||
| streak = 1; | ||
| for (let i = 0; i < indices.length - 1; i++) { | ||
| if (indices[i] - indices[i + 1] === 1) { | ||
BillChirico marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| streak++; | ||
| } else { | ||
| break; | ||
| } | ||
| } | ||
| } | ||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
BillChirico marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| const embed = new EmbedBuilder() | ||
| .setColor(0x5865f2) | ||
| .setTitle(`π Challenge Stats β ${interaction.user.displayName}`) | ||
| .setThumbnail(interaction.user.displayAvatarURL()) | ||
| .addFields( | ||
| { | ||
| name: 'π₯ Current Streak', | ||
| value: `**${streak}** challenge${streak !== 1 ? 's' : ''}`, | ||
| inline: true, | ||
| }, | ||
| { | ||
| name: 'β Total Solved', | ||
| value: `**${totalSolves}** challenge${totalSolves !== 1 ? 's' : ''}`, | ||
| inline: true, | ||
| }, | ||
| ) | ||
| .setFooter({ text: 'Keep solving to grow your streak!' }) | ||
| .setTimestamp(); | ||
|
|
||
| await safeEditReply(interaction, { embeds: [embed] }); | ||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| /** | ||
| * Handle /challenge leaderboard | ||
| * | ||
| * @param {import('discord.js').ChatInputCommandInteraction} interaction | ||
| */ | ||
| async function handleLeaderboard(interaction) { | ||
| const pool = getPool(); | ||
| if (!pool) { | ||
| await safeEditReply(interaction, { content: 'β Database unavailable.' }); | ||
| return; | ||
| } | ||
|
|
||
| const { guildId } = interaction; | ||
|
|
||
| // All-time top 10 | ||
| const { rows: allTimeRows } = await pool.query( | ||
| `SELECT user_id, COUNT(*) AS total | ||
| FROM challenge_solves | ||
| WHERE guild_id = $1 | ||
| GROUP BY user_id | ||
| ORDER BY total DESC | ||
| LIMIT 10`, | ||
| [guildId], | ||
| ); | ||
|
|
||
| // This week top 10 (last 7 days) | ||
| const { rows: weekRows } = await pool.query( | ||
| `SELECT user_id, COUNT(*) AS total | ||
| FROM challenge_solves | ||
| WHERE guild_id = $1 AND solved_at >= NOW() - INTERVAL '7 days' | ||
| GROUP BY user_id | ||
| ORDER BY total DESC | ||
| LIMIT 10`, | ||
| [guildId], | ||
| ); | ||
|
|
||
| const medals = ['π₯', 'π₯', 'π₯']; | ||
|
|
||
| const formatBoard = (rows) => { | ||
| if (rows.length === 0) return '_No solves yet β be the first!_'; | ||
| return rows | ||
| .map((row, i) => { | ||
| const prefix = medals[i] ?? `**${i + 1}.**`; | ||
| return `${prefix} <@${row.user_id}> β **${row.total}** solve${row.total !== 1 ? 's' : ''}`; | ||
BillChirico marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| }) | ||
| .join('\n'); | ||
| }; | ||
|
|
||
| const embed = new EmbedBuilder() | ||
| .setColor(0xfee75c) | ||
| .setTitle('π Challenge Leaderboard') | ||
| .addFields( | ||
| { name: 'π This Week', value: formatBoard(weekRows) }, | ||
| { name: 'π All-Time', value: formatBoard(allTimeRows) }, | ||
| ) | ||
| .setFooter({ text: 'Solve daily challenges to climb the ranks!' }) | ||
| .setTimestamp(); | ||
|
|
||
| await safeEditReply(interaction, { embeds: [embed] }); | ||
|
|
||
| info('/challenge leaderboard used', { userId: interaction.user.id, guildId }); | ||
| } | ||
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.
Uh oh!
There was an error while loading. Please reload this page.