-
Notifications
You must be signed in to change notification settings - Fork 2
feat: role menu templates (#135) #216
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 14 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
1483318
feat: add role_menu_templates migration (#135)
BillChirico 5c85f8c
feat: add roleMenuTemplates module with built-ins, CRUD, and share (#β¦
BillChirico 10d30af
feat: add /rolemenu command with template CRUD, apply, share (#135)
BillChirico 4cdd3d2
feat: seed built-in role menu templates on startup (#135)
BillChirico f5fa6b4
test: add roleMenuTemplates tests β 36 passing (#135)
BillChirico f158bf4
test: add /rolemenu command tests β 19 passing (#135)
BillChirico 5ea09bc
fix: typo hasModeatorPerms β hasModeratorPerms
BillChirico 7ecc70e
perf: SQL-based conversation pagination + missing DB indexes (#221)
BillChirico fd9c39a
feat: channel-level quiet mode via bot mention (#173) (#213)
BillChirico 23650ca
Fix: unterminated string in rolemenu.js
b0016e6
Fix: lint issues and formatting
320f6e2
Merge main into feat/issue-135
098e4d6
fix: deterministic template lookup and correct roleId precedence
ecfe3a2
fix: test assertion matches comment intent
4450a9f
fix: filter empty roleIds and only enable when valid options exist
ffc2c5d
chore: remove unused _MAX_DESCRIPTION_LEN constant
64acf4d
fix: case-insensitive unique index for template names
2e3d6ce
fix(roleMenuTemplates): add type validation for roleId and description
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| /** | ||
| * Migration: Role Menu Templates | ||
| * | ||
| * Stores reusable role menu templates β both built-in (is_builtin=true) and | ||
| * custom guild-created templates. Shared templates (is_shared=true) are | ||
| * visible to every guild. | ||
| * | ||
| * @see https://github.com/VolvoxLLC/volvox-bot/issues/135 | ||
| */ | ||
|
|
||
| 'use strict'; | ||
|
|
||
| /** @param {import('node-pg-migrate').MigrationBuilder} pgm */ | ||
| exports.up = (pgm) => { | ||
| pgm.sql(` | ||
| CREATE TABLE IF NOT EXISTS role_menu_templates ( | ||
| id SERIAL PRIMARY KEY, | ||
| name TEXT NOT NULL, | ||
| description TEXT, | ||
| category TEXT NOT NULL DEFAULT 'custom', | ||
| created_by_guild_id TEXT, | ||
| is_builtin BOOLEAN NOT NULL DEFAULT FALSE, | ||
| is_shared BOOLEAN NOT NULL DEFAULT FALSE, | ||
| options JSONB NOT NULL DEFAULT '[]', | ||
| created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), | ||
| updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() | ||
| ) | ||
| `); | ||
|
|
||
| pgm.sql(` | ||
| CREATE UNIQUE INDEX IF NOT EXISTS idx_rmt_name_guild | ||
| ON role_menu_templates (name, COALESCE(created_by_guild_id, '__builtin__')) | ||
| `); | ||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| pgm.sql(` | ||
| CREATE INDEX IF NOT EXISTS idx_rmt_guild | ||
| ON role_menu_templates (created_by_guild_id) | ||
| `); | ||
|
|
||
| pgm.sql(` | ||
| CREATE INDEX IF NOT EXISTS idx_rmt_shared | ||
| ON role_menu_templates (is_shared) WHERE is_shared = TRUE | ||
| `); | ||
| }; | ||
|
|
||
| /** @param {import('node-pg-migrate').MigrationBuilder} pgm */ | ||
| exports.down = (pgm) => { | ||
| pgm.sql('DROP TABLE IF EXISTS role_menu_templates 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,347 @@ | ||
| /** | ||
| * Role Menu Command | ||
| * | ||
| * Manage reusable role menu templates. | ||
| * | ||
| * Subcommands (all under /rolemenu template): | ||
| * list β list available templates | ||
| * info <name> β show template details | ||
| * apply <name> [merge] β apply template to this guild's role menu config | ||
| * create <name> <options> β create a custom template (JSON options array) | ||
| * delete <name> β delete a custom template | ||
| * share <name> <enabled> β toggle sharing of a custom template with other guilds | ||
| * | ||
| * @see https://github.com/VolvoxLLC/volvox-bot/issues/135 | ||
| */ | ||
|
|
||
| import { EmbedBuilder, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; | ||
| import { info } from '../logger.js'; | ||
| import { getConfig, setConfigValue } from '../modules/config.js'; | ||
| import { | ||
| applyTemplateToOptions, | ||
| createTemplate, | ||
| deleteTemplate, | ||
| getTemplateByName, | ||
| listTemplates, | ||
| setTemplateShared, | ||
| validateTemplateName, | ||
| validateTemplateOptions, | ||
| } from '../modules/roleMenuTemplates.js'; | ||
| import { isModerator } from '../utils/permissions.js'; | ||
| import { safeEditReply } from '../utils/safeSend.js'; | ||
|
|
||
| export const adminOnly = true; | ||
|
|
||
| export const data = new SlashCommandBuilder() | ||
| .setName('rolemenu') | ||
| .setDescription('Manage role menu templates') | ||
| .addSubcommandGroup((group) => | ||
| group | ||
| .setName('template') | ||
| .setDescription('Role menu template operations') | ||
| .addSubcommand((sub) => | ||
| sub.setName('list').setDescription('List available role menu templates'), | ||
| ) | ||
| .addSubcommand((sub) => | ||
| sub | ||
| .setName('info') | ||
| .setDescription('Show details for a template') | ||
| .addStringOption((opt) => | ||
| opt.setName('name').setDescription('Template name').setRequired(true), | ||
| ), | ||
| ) | ||
| .addSubcommand((sub) => | ||
| sub | ||
| .setName('apply') | ||
| .setDescription("Apply a template to this guild's role menu config") | ||
| .addStringOption((opt) => | ||
| opt.setName('name').setDescription('Template name').setRequired(true), | ||
| ) | ||
| .addBooleanOption((opt) => | ||
| opt | ||
| .setName('merge') | ||
| .setDescription( | ||
| 'Merge with existing role menu options instead of replacing (default: replace)', | ||
| ) | ||
| .setRequired(false), | ||
| ), | ||
| ) | ||
| .addSubcommand((sub) => | ||
| sub | ||
| .setName('create') | ||
| .setDescription('Create a custom role menu template for this guild') | ||
| .addStringOption((opt) => | ||
| opt.setName('name').setDescription('Template name').setRequired(true), | ||
| ) | ||
| .addStringOption((opt) => | ||
| opt | ||
| .setName('options') | ||
| .setDescription( | ||
| 'JSON array: [{"label":"Red","description":"Red role","roleId":"123"}]', | ||
| ) | ||
| .setRequired(true), | ||
| ) | ||
| .addStringOption((opt) => | ||
| opt | ||
| .setName('description') | ||
| .setDescription('Short description of this template') | ||
| .setRequired(false), | ||
| ) | ||
| .addStringOption((opt) => | ||
| opt | ||
| .setName('category') | ||
| .setDescription('Category (e.g. colors, pronouns, notifications, custom)') | ||
| .setRequired(false), | ||
| ), | ||
| ) | ||
| .addSubcommand((sub) => | ||
| sub | ||
| .setName('delete') | ||
| .setDescription('Delete a custom template owned by this guild') | ||
| .addStringOption((opt) => | ||
| opt.setName('name').setDescription('Template name').setRequired(true), | ||
| ), | ||
| ) | ||
| .addSubcommand((sub) => | ||
| sub | ||
| .setName('share') | ||
| .setDescription('Toggle sharing of a guild-owned template with other guilds') | ||
| .addStringOption((opt) => | ||
| opt.setName('name').setDescription('Template name').setRequired(true), | ||
| ) | ||
| .addBooleanOption((opt) => | ||
| opt.setName('enabled').setDescription('Share this template?').setRequired(true), | ||
| ), | ||
| ), | ||
| ); | ||
|
|
||
| // ββ Permission guard ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | ||
|
|
||
| function hasModeratorPerms(interaction, guildConfig) { | ||
| return ( | ||
| interaction.member.permissions.has(PermissionFlagsBits.Administrator) || | ||
| isModerator(interaction.member, guildConfig) | ||
| ); | ||
| } | ||
|
|
||
| // ββ Subcommand handlers βββββββββββββββββββββββββββββββββββββββββββββββββββββββ | ||
|
|
||
| async function handleList(interaction) { | ||
| const templates = await listTemplates(interaction.guildId); | ||
| if (templates.length === 0) { | ||
| await safeEditReply(interaction, { | ||
| content: 'π No templates available. Use `/rolemenu template create` to make one.', | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| const byCategory = {}; | ||
| for (const tpl of templates) { | ||
| const cat = tpl.category || 'custom'; | ||
| byCategory[cat] = byCategory[cat] || []; | ||
| byCategory[cat].push(tpl); | ||
| } | ||
|
|
||
| const embed = new EmbedBuilder() | ||
| .setTitle('π Role Menu Templates') | ||
| .setColor(0x5865f2) | ||
| .setFooter({ text: `${templates.length} template(s) available` }); | ||
|
|
||
| for (const [cat, items] of Object.entries(byCategory)) { | ||
| const lines = items.map((t) => { | ||
| const badges = [t.is_builtin ? 'π§ built-in' : 'π custom', t.is_shared ? 'π shared' : null] | ||
| .filter(Boolean) | ||
| .join(' Β· '); | ||
| return `**${t.name}** β ${t.description || 'no description'} *(${badges})*`; | ||
| }); | ||
| const fieldValue = lines.join('\n').slice(0, 1020) + (lines.join('\n').length > 1020 ? '...' : ''); | ||
| embed.addFields({ name: `π ${cat}`, value: fieldValue, inline: false }); | ||
| } | ||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| await safeEditReply(interaction, { embeds: [embed] }); | ||
| } | ||
|
|
||
| async function handleInfo(interaction) { | ||
| const name = interaction.options.getString('name'); | ||
| const tpl = await getTemplateByName(interaction.guildId, name); | ||
| if (!tpl) { | ||
| await safeEditReply(interaction, { content: `β Template \`${name}\` not found.` }); | ||
| return; | ||
| } | ||
|
|
||
| const options = Array.isArray(tpl.options) ? tpl.options : []; | ||
| const optLines = | ||
| options | ||
| .map( | ||
| (opt, i) => | ||
| `${i + 1}. **${opt.label}**${opt.description ? ` β ${opt.description}` : ''}${opt.roleId ? ` <@&${opt.roleId}>` : ''}`, | ||
| ) | ||
| .join('\n') || '_No options_'; | ||
|
|
||
| const embed = new EmbedBuilder() | ||
| .setTitle(`π Template: ${tpl.name}`) | ||
| .setColor(0x57f287) | ||
| .setDescription(tpl.description || '_No description_') | ||
| .addFields( | ||
| { name: 'Category', value: tpl.category || 'custom', inline: true }, | ||
| { name: 'Type', value: tpl.is_builtin ? 'π§ Built-in' : 'π Custom', inline: true }, | ||
| { name: 'Shared', value: tpl.is_shared ? 'β Yes' : 'β No', inline: true }, | ||
| { name: `Options (${options.length})`, value: optLines.slice(0, 1024), inline: false }, | ||
| ) | ||
| .setFooter({ | ||
| text: `Created: ${tpl.created_at ? new Date(tpl.created_at).toDateString() : 'N/A'}`, | ||
| }); | ||
|
|
||
| await safeEditReply(interaction, { embeds: [embed] }); | ||
| } | ||
|
|
||
| async function handleApply(interaction) { | ||
| const name = interaction.options.getString('name'); | ||
| const merge = interaction.options.getBoolean('merge') ?? false; | ||
|
|
||
| const tpl = await getTemplateByName(interaction.guildId, name); | ||
| if (!tpl) { | ||
| await safeEditReply(interaction, { content: `β Template \`${name}\` not found.` }); | ||
| return; | ||
| } | ||
|
|
||
| const guildConfig = getConfig(interaction.guildId); | ||
| const existingOptions = merge ? (guildConfig?.welcome?.roleMenu?.options ?? []) : []; | ||
| const newOptions = applyTemplateToOptions(tpl, existingOptions); | ||
|
|
||
| await setConfigValue('welcome.roleMenu.enabled', true, interaction.guildId); | ||
| await setConfigValue('welcome.roleMenu.options', newOptions, interaction.guildId); | ||
|
|
||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| info('Role menu template applied', { | ||
| guildId: interaction.guildId, | ||
| template: tpl.name, | ||
| optionCount: newOptions.length, | ||
| merge, | ||
| userId: interaction.user.id, | ||
| }); | ||
|
|
||
| const builtinNote = tpl.is_builtin | ||
| ? '\n\n> β οΈ Built-in templates have no role IDs. Use the config editor to assign a **roleId** to each option before posting the role menu.' | ||
| : ''; | ||
|
|
||
| await safeEditReply(interaction, { | ||
| content: `β Applied template **${tpl.name}** to role menu config (${newOptions.length} option${newOptions.length !== 1 ? 's' : ''}).${merge ? ' Merged with existing options.' : ''}${builtinNote}\n\nRun \`/welcome setup\` to post the updated role menu.`, | ||
| }); | ||
| } | ||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| async function handleCreate(interaction) { | ||
| const name = interaction.options.getString('name'); | ||
| const optionsRaw = interaction.options.getString('options'); | ||
| const description = interaction.options.getString('description') ?? ''; | ||
| const category = interaction.options.getString('category') ?? 'custom'; | ||
|
|
||
BillChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| const nameErr = validateTemplateName(name); | ||
| if (nameErr) { | ||
| await safeEditReply(interaction, { content: `β ${nameErr}` }); | ||
| return; | ||
| } | ||
|
|
||
| let parsedOptions; | ||
| try { | ||
| parsedOptions = JSON.parse(optionsRaw); | ||
| } catch { | ||
| await safeEditReply(interaction, { | ||
| content: | ||
| 'β Options must be valid JSON. Example:\n```json\n[{"label":"Red","description":"Red role","roleId":"123456789"}]\n```', | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| const optErr = validateTemplateOptions(parsedOptions); | ||
| if (optErr) { | ||
| await safeEditReply(interaction, { content: `β ${optErr}` }); | ||
| return; | ||
| } | ||
|
|
||
| try { | ||
| const tpl = await createTemplate({ | ||
| guildId: interaction.guildId, | ||
| name, | ||
| description, | ||
| category, | ||
| options: parsedOptions, | ||
| }); | ||
| await safeEditReply(interaction, { | ||
| content: `β Template **${tpl.name}** created with ${parsedOptions.length} option(s). Use \`/rolemenu template apply ${tpl.name}\` to apply it.`, | ||
| }); | ||
| } catch (err) { | ||
| if (err.code === '23505') { | ||
| await safeEditReply(interaction, { | ||
| content: `β A template named **${name}** already exists for this guild.`, | ||
| }); | ||
| } else { | ||
| throw err; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| async function handleDelete(interaction) { | ||
| const name = interaction.options.getString('name'); | ||
| const deleted = await deleteTemplate(interaction.guildId, name); | ||
| if (!deleted) { | ||
| await safeEditReply(interaction, { | ||
| content: `β Template \`${name}\` not found or is a built-in (built-ins cannot be deleted).`, | ||
| }); | ||
| return; | ||
| } | ||
| await safeEditReply(interaction, { content: `β Template **${name}** deleted.` }); | ||
| } | ||
|
|
||
| async function handleShare(interaction) { | ||
| const name = interaction.options.getString('name'); | ||
| const enabled = interaction.options.getBoolean('enabled'); | ||
| const updated = await setTemplateShared(interaction.guildId, name, enabled); | ||
| if (!updated) { | ||
| await safeEditReply(interaction, { | ||
| content: `β Template \`${name}\` not found or not owned by this guild.`, | ||
| }); | ||
| return; | ||
| } | ||
| await safeEditReply(interaction, { | ||
| content: `β Template **${name}** is now ${enabled ? 'π shared with all guilds' : 'π private to this guild'}.`, | ||
| }); | ||
| } | ||
|
|
||
| // ββ Main execute ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | ||
|
|
||
| export async function execute(interaction) { | ||
| await interaction.deferReply({ ephemeral: true }); | ||
|
|
||
| const guildConfig = getConfig(interaction.guildId); | ||
| if (!hasModeratorPerms(interaction, guildConfig)) { | ||
| await safeEditReply(interaction, { | ||
| content: 'β You need moderator or administrator permissions to use this command.', | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| const sub = interaction.options.getSubcommand(); | ||
|
|
||
| switch (sub) { | ||
| case 'list': | ||
| await handleList(interaction); | ||
| break; | ||
| case 'info': | ||
| await handleInfo(interaction); | ||
| break; | ||
| case 'apply': | ||
| await handleApply(interaction); | ||
| break; | ||
| case 'create': | ||
| await handleCreate(interaction); | ||
| break; | ||
| case 'delete': | ||
| await handleDelete(interaction); | ||
| break; | ||
| case 'share': | ||
| await handleShare(interaction); | ||
| break; | ||
| default: | ||
| await safeEditReply(interaction, { content: 'β Unknown subcommand.' }); | ||
| } | ||
| } | ||
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.