-
Notifications
You must be signed in to change notification settings - Fork 2
feat: AFK system #108
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
feat: AFK system #108
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
941032d
feat: add AFK system (#46)
BillChirico 0b5e476
fix: address PR #108 review feedback
BillChirico 57b425b
fix: resolve memory leak, non-atomic deletes, ping tracking, displayName
BillChirico 1c64126
fix: wrap auto-clear deletes in transaction for atomicity
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
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,37 @@ | ||
| /** | ||
| * Migration 006 — AFK system tables | ||
|
BillChirico marked this conversation as resolved.
|
||
| */ | ||
|
|
||
| 'use strict'; | ||
|
|
||
| exports.up = (pgm) => { | ||
| pgm.createTable( | ||
| 'afk_status', | ||
| { | ||
| id: { type: 'serial', primaryKey: true }, | ||
| guild_id: { type: 'text', notNull: true }, | ||
| user_id: { type: 'text', notNull: true }, | ||
| reason: { type: 'text', notNull: true, default: 'AFK' }, | ||
| set_at: { type: 'timestamptz', default: pgm.func('NOW()') }, | ||
| }, | ||
| { constraints: { unique: ['guild_id', 'user_id'] } }, | ||
| ); | ||
|
BillChirico marked this conversation as resolved.
|
||
|
|
||
| pgm.createTable('afk_pings', { | ||
| id: { type: 'serial', primaryKey: true }, | ||
| guild_id: { type: 'text', notNull: true }, | ||
| afk_user_id: { type: 'text', notNull: true }, | ||
| pinger_id: { type: 'text', notNull: true }, | ||
| channel_id: { type: 'text', notNull: true }, | ||
| message_preview: { type: 'text' }, | ||
| pinged_at: { type: 'timestamptz', default: pgm.func('NOW()') }, | ||
| }); | ||
|
|
||
| pgm.createIndex('afk_pings', ['guild_id', 'afk_user_id'], { name: 'idx_afk_pings_user' }); | ||
| }; | ||
|
|
||
| exports.down = (pgm) => { | ||
| pgm.dropIndex('afk_pings', ['guild_id', 'afk_user_id'], { name: 'idx_afk_pings_user' }); | ||
| pgm.dropTable('afk_pings'); | ||
|
BillChirico marked this conversation as resolved.
|
||
| pgm.dropTable('afk_status'); | ||
| }; | ||
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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,159 @@ | ||
| /** | ||
| * AFK Command | ||
| * Let members set an AFK status. When mentioned while away, the bot | ||
| * sends a notice. On return, the user receives a ping summary. | ||
| * | ||
| * @see https://github.com/VolvoxLLC/volvox-bot/issues/46 | ||
| */ | ||
|
|
||
| import { SlashCommandBuilder } from 'discord.js'; | ||
| import { getPool } from '../db.js'; | ||
| import { info, error as logError } from '../logger.js'; | ||
| import { getConfig } from '../modules/config.js'; | ||
| import { safeReply } from '../utils/safeSend.js'; | ||
|
|
||
| export const data = new SlashCommandBuilder() | ||
| .setName('afk') | ||
| .setDescription('Set or clear your AFK status') | ||
| .addSubcommand((sub) => | ||
| sub | ||
| .setName('set') | ||
| .setDescription('Mark yourself as AFK') | ||
| .addStringOption((opt) => | ||
| opt | ||
| .setName('reason') | ||
| .setDescription('Why are you AFK? (default: AFK)') | ||
| .setRequired(false) | ||
| .setMaxLength(200), | ||
| ), | ||
| ) | ||
| .addSubcommand((sub) => sub.setName('clear').setDescription('Clear your AFK status manually')); | ||
|
|
||
| // ── Subcommand handlers ──────────────────────────────────────────── | ||
|
|
||
| async function handleSet(interaction) { | ||
| const reason = interaction.options.getString('reason') || 'AFK'; | ||
| const pool = getPool(); | ||
|
|
||
| await pool.query( | ||
| `INSERT INTO afk_status (guild_id, user_id, reason, set_at) | ||
| VALUES ($1, $2, $3, NOW()) | ||
| ON CONFLICT (guild_id, user_id) DO UPDATE | ||
| SET reason = EXCLUDED.reason, set_at = NOW()`, | ||
| [interaction.guildId, interaction.user.id, reason], | ||
| ); | ||
|
|
||
| info('AFK set', { guildId: interaction.guildId, userId: interaction.user.id, reason }); | ||
|
|
||
| await safeReply(interaction, { | ||
| content: `💤 You are now AFK: *${reason}*`, | ||
| ephemeral: true, | ||
| }); | ||
| } | ||
|
|
||
| async function handleClear(interaction) { | ||
| const pool = getPool(); | ||
|
|
||
| const { rows: afkRows } = await pool.query( | ||
| 'SELECT * FROM afk_status WHERE guild_id = $1 AND user_id = $2', | ||
|
BillChirico marked this conversation as resolved.
|
||
| [interaction.guildId, interaction.user.id], | ||
|
BillChirico marked this conversation as resolved.
|
||
| ); | ||
|
BillChirico marked this conversation as resolved.
|
||
|
|
||
| if (afkRows.length === 0) { | ||
| return await safeReply(interaction, { | ||
| content: "ℹ️ You're not AFK right now.", | ||
| ephemeral: true, | ||
| }); | ||
| } | ||
|
|
||
| // Fetch ping summary before deleting | ||
| const { rows: pings } = await pool.query( | ||
| `SELECT pinger_id, channel_id, message_preview, pinged_at | ||
| FROM afk_pings | ||
| WHERE guild_id = $1 AND afk_user_id = $2 | ||
| ORDER BY pinged_at ASC`, | ||
| [interaction.guildId, interaction.user.id], | ||
| ); | ||
|
|
||
| // Delete AFK record and pings atomically | ||
| const client = await pool.connect(); | ||
| try { | ||
| await client.query('BEGIN'); | ||
| await client.query('DELETE FROM afk_status WHERE guild_id = $1 AND user_id = $2', [ | ||
| interaction.guildId, | ||
| interaction.user.id, | ||
| ]); | ||
| await client.query('DELETE FROM afk_pings WHERE guild_id = $1 AND afk_user_id = $2', [ | ||
| interaction.guildId, | ||
| interaction.user.id, | ||
| ]); | ||
| await client.query('COMMIT'); | ||
| } catch (err) { | ||
| await client.query('ROLLBACK'); | ||
| throw err; | ||
| } finally { | ||
| client.release(); | ||
| } | ||
|
|
||
| info('AFK cleared (manual)', { guildId: interaction.guildId, userId: interaction.user.id }); | ||
|
|
||
| const summary = buildPingSummary(pings); | ||
| await safeReply(interaction, { | ||
| content: `✅ AFK cleared!${summary}`, | ||
| ephemeral: true, | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Build a human-readable ping summary from ping rows. | ||
| * @param {Array} pings | ||
| * @returns {string} | ||
| */ | ||
|
BillChirico marked this conversation as resolved.
|
||
| export function buildPingSummary(pings) { | ||
| if (pings.length === 0) return '\n\nNo one pinged you while you were away.'; | ||
|
|
||
| const lines = pings.slice(0, 10).map((p) => { | ||
| const time = `<t:${Math.floor(new Date(p.pinged_at).getTime() / 1000)}:R>`; | ||
| const preview = p.message_preview ? ` — "${p.message_preview}"` : ''; | ||
| return `• <@${p.pinger_id}> in <#${p.channel_id}> ${time}${preview}`; | ||
| }); | ||
|
|
||
| const extra = pings.length > 10 ? `\n…and ${pings.length - 10} more.` : ''; | ||
| return `\n\n**Pings while AFK (${pings.length}):**\n${lines.join('\n')}${extra}`; | ||
| } | ||
|
|
||
| // ── Execute ──────────────────────────────────────────────────────── | ||
|
|
||
| /** | ||
| * Execute the afk command. | ||
| * @param {import('discord.js').ChatInputCommandInteraction} interaction | ||
| */ | ||
| export async function execute(interaction) { | ||
| const guildConfig = getConfig(interaction.guildId); | ||
|
|
||
| if (!guildConfig.afk?.enabled) { | ||
| return await safeReply(interaction, { | ||
| content: '❌ The AFK feature is not enabled on this server.', | ||
| ephemeral: true, | ||
| }); | ||
| } | ||
|
|
||
| const subcommand = interaction.options.getSubcommand(); | ||
|
|
||
| try { | ||
| switch (subcommand) { | ||
| case 'set': | ||
| await handleSet(interaction); | ||
| break; | ||
| case 'clear': | ||
| await handleClear(interaction); | ||
| break; | ||
| } | ||
| } catch (err) { | ||
| logError('AFK command failed', { error: err.message, stack: err.stack, subcommand }); | ||
| await safeReply(interaction, { | ||
| content: '❌ Failed to execute AFK command.', | ||
| ephemeral: true, | ||
| }); | ||
| } | ||
| } | ||
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.