Add Discord bot (moderation, filters, scheduling, roles, invites, site integration)

Standalone bot/ service (its own package.json/Dockerfile) managed entirely
through a new admin-only Discord Bot panel — token stored encrypted in the
DB and pushed to the bot process in-memory, never an env var. Built in
phases, each independently verified against a live Discord guild:

- Bot skeleton: gateway connection, internal shared-secret API, self-heals
  on its own restart by pulling config from the site
- Moderation core: /ban /kick /mute /warn /warnings + mod-log channel
- Word/invite/spam filtering with leetspeak-resistant normalization and a
  staff role/channel allowlist
- Scheduled messages: recurring (cron) and one-off channel posts
- Role assignment: button role menus, auto-role on join, temp roles,
  bulk role ops
- Auto-rotating primary invite with an audit log
- Site integration: news-publish -> Discord announce webhook, manual
  /announce, read-only /wiki search

Also fixes a pre-existing bug in both DB pools (server + bot): the mariadb
driver defaulted to timezone 'local', silently mis-serializing bound Date
params by the host's local offset instead of the DB's UTC session.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-04 15:54:41 -05:00
parent 0318d6fe9f
commit 7a21cc636c
77 changed files with 4800 additions and 3 deletions

View File

@@ -0,0 +1,49 @@
const { PermissionFlagsBits, ApplicationCommandOptionType } = require('discord.js')
const siteApiClient = require('../../site/siteApiClient')
const newsAnnounce = require('../newsAnnounce')
function siteOrigin() {
const base = process.env.SITE_PUBLIC_URL || 'http://localhost:3000/api/v1/public'
return new URL(base).origin
}
module.exports = {
data: {
name: 'announce',
description: 'Re-post or boost an existing news item.',
default_member_permissions: PermissionFlagsBits.ManageGuild.toString(),
options: [
{ name: 'post', description: 'News post id or slug', type: ApplicationCommandOptionType.String, required: true },
],
},
async execute(interaction) {
const idOrSlug = interaction.options.getString('post', true)
await interaction.deferReply({ ephemeral: true })
const result = await siteApiClient.getNewsPost(idOrSlug)
if (result.maintenance) {
await interaction.editReply({ content: `Can't reach the site right now: ${result.message || 'maintenance mode'}` })
return
}
if (!result.ok) {
await interaction.editReply({ content: `Couldn't find that news post ("${idOrSlug}").` })
return
}
const post = result.data
const origin = siteOrigin()
try {
await newsAnnounce.postAnnounce(interaction.client, interaction.guildId, {
title: post.title,
excerpt: post.excerpt,
url: `${origin}/site/news`,
// image_url is stored relative — Discord embeds require an absolute URL.
imageUrl: post.image_url ? new URL(post.image_url, origin).toString() : null,
})
await interaction.editReply({ content: `Posted "${post.title}" to the news channel.` })
} catch (err) {
await interaction.editReply({ content: `Couldn't post: ${err.message}` })
}
},
}

View File

@@ -0,0 +1,30 @@
const { PermissionFlagsBits, ApplicationCommandOptionType } = require('discord.js')
const guildConfig = require('../../model/guildConfig')
module.exports = {
data: {
name: 'autorole',
description: 'View or set the role automatically assigned to new members on join.',
default_member_permissions: PermissionFlagsBits.ManageGuild.toString(),
options: [
{
name: 'role',
description: 'Role to auto-assign on join. Omit to view the current setting.',
type: ApplicationCommandOptionType.Role,
required: false,
},
],
},
async execute(interaction) {
const role = interaction.options.getRole('role')
if (!role) {
const currentId = await guildConfig.getAutoRoleId(interaction.guildId)
const content = currentId ? `Auto-role is set to <@&${currentId}>.` : 'No auto-role is set yet.'
await interaction.reply({ content, ephemeral: true })
return
}
await guildConfig.setAutoRoleId(interaction.guildId, role.id)
await interaction.reply({ content: `Auto-role set to ${role}. New members will get this automatically.`, ephemeral: true })
},
}

View File

@@ -0,0 +1,34 @@
const { PermissionFlagsBits, ApplicationCommandOptionType } = require('discord.js')
const modLog = require('../modLog')
module.exports = {
data: {
name: 'ban',
description: 'Ban a member from the server.',
default_member_permissions: PermissionFlagsBits.BanMembers.toString(),
options: [
{ name: 'user', description: 'Member to ban', type: ApplicationCommandOptionType.User, required: true },
{ name: 'reason', description: 'Reason for the ban', type: ApplicationCommandOptionType.String, required: true },
],
},
async execute(interaction) {
const user = interaction.options.getUser('user', true)
const reason = interaction.options.getString('reason', true)
if (user.id === interaction.user.id) {
await interaction.reply({ content: "You can't ban yourself.", ephemeral: true })
return
}
const member = interaction.guild.members.cache.get(user.id)
if (member && !member.bannable) {
await interaction.reply({ content: "I don't have permission to ban that member (role hierarchy).", ephemeral: true })
return
}
await interaction.guild.members.ban(user, { reason })
await modLog.record({ client: interaction.client, guildId: interaction.guildId, actionType: 'ban', target: user, staffUser: interaction.user, reason })
await interaction.reply({ content: `Banned ${user.tag}.`, ephemeral: true })
},
}

View File

@@ -0,0 +1,73 @@
const { PermissionFlagsBits, ApplicationCommandOptionType } = require('discord.js')
const filterWords = require('../../model/filterWords')
const filterCache = require('../../filter/filterCache')
module.exports = {
data: {
name: 'filter',
description: 'Manage the banned-word filter.',
default_member_permissions: PermissionFlagsBits.ManageGuild.toString(),
options: [
{
name: 'add',
description: 'Add a word to the filter.',
type: ApplicationCommandOptionType.Subcommand,
options: [
{ name: 'word', description: 'Word or phrase to ban', type: ApplicationCommandOptionType.String, required: true },
{
name: 'severity',
description: 'Auto-action when triggered (default: delete)',
type: ApplicationCommandOptionType.String,
required: false,
choices: [
{ name: 'Delete only', value: 'delete' },
{ name: 'Delete + warn', value: 'warn' },
{ name: 'Delete + mute (10m)', value: 'mute' },
],
},
],
},
{
name: 'remove',
description: 'Remove a word from the filter.',
type: ApplicationCommandOptionType.Subcommand,
options: [
{ name: 'word', description: 'Word or phrase to remove', type: ApplicationCommandOptionType.String, required: true },
],
},
{
name: 'list',
description: 'List all filtered words.',
type: ApplicationCommandOptionType.Subcommand,
options: [],
},
],
},
async execute(interaction) {
const sub = interaction.options.getSubcommand()
if (sub === 'add') {
const word = interaction.options.getString('word', true)
const severity = interaction.options.getString('severity') || 'delete'
await filterWords.add({ guildId: interaction.guildId, word, severity, addedBy: interaction.user.id, addedByTag: interaction.user.tag })
await filterCache.refresh(interaction.guildId)
await interaction.reply({ content: `Added "${word}" to the filter (${severity}).`, ephemeral: true })
return
}
if (sub === 'remove') {
const word = interaction.options.getString('word', true)
const removed = await filterWords.remove(interaction.guildId, word)
await filterCache.refresh(interaction.guildId)
await interaction.reply({ content: removed ? `Removed "${word}" from the filter.` : `"${word}" wasn't in the filter.`, ephemeral: true })
return
}
if (sub === 'list') {
const words = await filterWords.list(interaction.guildId)
const content = words.length === 0 ? 'The filter list is empty.' : words.map((w) => `${w.word} (${w.severity})`).join('\n')
await interaction.reply({ content, ephemeral: true })
}
},
}

View File

@@ -0,0 +1,61 @@
const { PermissionFlagsBits, ApplicationCommandOptionType } = require('discord.js')
const filterAllowlist = require('../../model/filterAllowlist')
const filterCache = require('../../filter/filterCache')
module.exports = {
data: {
name: 'filterallow',
description: 'Manage roles/channels that bypass the filter entirely.',
default_member_permissions: PermissionFlagsBits.ManageGuild.toString(),
options: [
{
name: 'role',
description: 'Toggle a role in/out of the filter bypass list.',
type: ApplicationCommandOptionType.Subcommand,
options: [{ name: 'role', description: 'Role to toggle', type: ApplicationCommandOptionType.Role, required: true }],
},
{
name: 'channel',
description: 'Toggle a channel in/out of the filter bypass list.',
type: ApplicationCommandOptionType.Subcommand,
options: [{ name: 'channel', description: 'Channel to toggle', type: ApplicationCommandOptionType.Channel, required: true }],
},
{
name: 'list',
description: 'Show current filter bypass roles/channels.',
type: ApplicationCommandOptionType.Subcommand,
options: [],
},
],
},
async execute(interaction) {
const sub = interaction.options.getSubcommand()
if (sub === 'role') {
const role = interaction.options.getRole('role', true)
const nowAllowed = await filterAllowlist.toggleRole(interaction.guildId, role.id)
await filterCache.refresh(interaction.guildId)
await interaction.reply({ content: `${role} is ${nowAllowed ? 'now' : 'no longer'} bypassing the filter.`, ephemeral: true })
return
}
if (sub === 'channel') {
const channel = interaction.options.getChannel('channel', true)
const nowAllowed = await filterAllowlist.toggleChannel(interaction.guildId, channel.id)
await filterCache.refresh(interaction.guildId)
await interaction.reply({ content: `${channel} is ${nowAllowed ? 'now' : 'no longer'} bypassing the filter.`, ephemeral: true })
return
}
if (sub === 'list') {
const [roles, channels] = await Promise.all([
filterAllowlist.getRoles(interaction.guildId),
filterAllowlist.getChannels(interaction.guildId),
])
const roleText = roles.length ? roles.map((id) => `<@&${id}>`).join(', ') : 'none'
const channelText = channels.length ? channels.map((id) => `<#${id}>`).join(', ') : 'none'
await interaction.reply({ content: `Bypass roles: ${roleText}\nBypass channels: ${channelText}`, ephemeral: true })
}
},
}

View File

@@ -0,0 +1,31 @@
// Command registry. Each module exports { data, execute } — `data` is the
// slash-command definition pushed to Discord (registerCommands), `execute` is
// the interactionCreate handler (dispatch). Adding a new command is just
// adding a file here — discordManager.js never needs to change.
const commands = [
require('./ping.command'),
require('./modlog.command'),
require('./ban.command'),
require('./kick.command'),
require('./mute.command'),
require('./warn.command'),
require('./warnings.command'),
require('./filter.command'),
require('./filterallow.command'),
require('./schedule.command'),
require('./rolemenu.command'),
require('./autorole.command'),
require('./role.command'),
require('./roles.command'),
require('./invite.command'),
require('./news.command'),
require('./announce.command'),
require('./wiki.command'),
]
const byName = new Map(commands.map((c) => [c.data.name, c]))
module.exports = {
all: commands,
get: (name) => byName.get(name),
}

View File

@@ -0,0 +1,85 @@
const { PermissionFlagsBits, ApplicationCommandOptionType, ChannelType } = require('discord.js')
const guildConfig = require('../../model/guildConfig')
const inviteLog = require('../../model/inviteLog')
const inviteRotator = require('../../invites/inviteRotator')
module.exports = {
data: {
name: 'invite',
description: 'Manage the auto-rotating primary server invite.',
default_member_permissions: PermissionFlagsBits.ManageGuild.toString(),
options: [
{
name: 'channel',
description: 'View or set the channel new invites are created in.',
type: ApplicationCommandOptionType.Subcommand,
options: [
{
name: 'channel',
description: 'Channel to create invites in. Omit to view the current setting.',
type: ApplicationCommandOptionType.Channel,
channel_types: [ChannelType.GuildText],
required: false,
},
],
},
{
name: 'rotate',
description: 'Revoke the current invite and generate a new one now.',
type: ApplicationCommandOptionType.Subcommand,
options: [],
},
{
name: 'log',
description: 'Show recent invite rotation history.',
type: ApplicationCommandOptionType.Subcommand,
options: [],
},
],
},
async execute(interaction) {
const sub = interaction.options.getSubcommand()
if (sub === 'channel') {
const channel = interaction.options.getChannel('channel')
if (!channel) {
const currentId = await guildConfig.getInviteChannelId(interaction.guildId)
const content = currentId ? `Invites are created in <#${currentId}>.` : 'No invite channel is set yet.'
await interaction.reply({ content, ephemeral: true })
return
}
await guildConfig.setInviteChannelId(interaction.guildId, channel.id)
await interaction.reply({ content: `Invite channel set to ${channel}.`, ephemeral: true })
return
}
if (sub === 'rotate') {
await interaction.deferReply({ ephemeral: true })
try {
const invite = await inviteRotator.rotate(interaction.client, interaction.guildId, {
triggeredBy: interaction.user.id,
triggeredByTag: interaction.user.tag,
})
await interaction.editReply({ content: `New invite: https://discord.gg/${invite.code}` })
} catch (err) {
await interaction.editReply({ content: `Couldn't rotate the invite: ${err.message}` })
}
return
}
if (sub === 'log') {
const rows = await inviteLog.list(interaction.guildId, 10)
if (rows.length === 0) {
await interaction.reply({ content: 'No invite rotations logged yet.', ephemeral: true })
return
}
const lines = rows.map((r) => {
const who = r.triggered_by_tag || 'automatic (scheduled)'
const status = r.revoked_at ? `revoked ${new Date(r.revoked_at).toLocaleString()}` : 'active'
return `\`${r.invite_code}\` — by ${who} on ${new Date(r.created_at).toLocaleString()} (${status})`
})
await interaction.reply({ content: lines.join('\n'), ephemeral: true })
}
},
}

View File

@@ -0,0 +1,38 @@
const { PermissionFlagsBits, ApplicationCommandOptionType } = require('discord.js')
const modLog = require('../modLog')
module.exports = {
data: {
name: 'kick',
description: 'Kick a member from the server.',
default_member_permissions: PermissionFlagsBits.KickMembers.toString(),
options: [
{ name: 'user', description: 'Member to kick', type: ApplicationCommandOptionType.User, required: true },
{ name: 'reason', description: 'Reason for the kick', type: ApplicationCommandOptionType.String, required: true },
],
},
async execute(interaction) {
const user = interaction.options.getUser('user', true)
const reason = interaction.options.getString('reason', true)
if (user.id === interaction.user.id) {
await interaction.reply({ content: "You can't kick yourself.", ephemeral: true })
return
}
const member = interaction.guild.members.cache.get(user.id)
if (!member) {
await interaction.reply({ content: 'That user is not a member of this server.', ephemeral: true })
return
}
if (!member.kickable) {
await interaction.reply({ content: "I don't have permission to kick that member (role hierarchy).", ephemeral: true })
return
}
await member.kick(reason)
await modLog.record({ client: interaction.client, guildId: interaction.guildId, actionType: 'kick', target: user, staffUser: interaction.user, reason })
await interaction.reply({ content: `Kicked ${user.tag}.`, ephemeral: true })
},
}

View File

@@ -0,0 +1,33 @@
const { PermissionFlagsBits, ApplicationCommandOptionType, ChannelType } = require('discord.js')
const guildConfig = require('../../model/guildConfig')
module.exports = {
data: {
name: 'modlog',
description: 'View or set the mod-log channel (ban/kick/mute/warn actions post here).',
// Configuration, not a moderation action — gated to Manage Server rather
// than the ModerateMembers bit the action commands use.
default_member_permissions: PermissionFlagsBits.ManageGuild.toString(),
options: [
{
name: 'channel',
description: 'Channel to post mod-log entries to. Omit to view the current setting.',
type: ApplicationCommandOptionType.Channel,
channel_types: [ChannelType.GuildText],
required: false,
},
],
},
async execute(interaction) {
const channel = interaction.options.getChannel('channel')
if (!channel) {
const currentId = await guildConfig.getModLogChannelId(interaction.guildId)
const content = currentId ? `Mod-log channel is set to <#${currentId}>.` : 'No mod-log channel is set yet.'
await interaction.reply({ content, ephemeral: true })
return
}
await guildConfig.setModLogChannelId(interaction.guildId, channel.id)
await interaction.reply({ content: `Mod-log channel set to ${channel}.`, ephemeral: true })
},
}

View File

@@ -0,0 +1,49 @@
const { PermissionFlagsBits, ApplicationCommandOptionType } = require('discord.js')
const modLog = require('../modLog')
const { parseDuration, MAX_TIMEOUT_MS } = require('../../utils/duration')
module.exports = {
data: {
name: 'mute',
description: 'Timeout a member for a duration (e.g. 10m, 2h, 1d).',
default_member_permissions: PermissionFlagsBits.ModerateMembers.toString(),
options: [
{ name: 'user', description: 'Member to mute', type: ApplicationCommandOptionType.User, required: true },
{ name: 'duration', description: 'e.g. 30s, 10m, 2h, 1d (max 28d)', type: ApplicationCommandOptionType.String, required: true },
{ name: 'reason', description: 'Reason for the mute', type: ApplicationCommandOptionType.String, required: true },
],
},
async execute(interaction) {
const user = interaction.options.getUser('user', true)
const durationInput = interaction.options.getString('duration', true)
const reason = interaction.options.getString('reason', true)
if (user.id === interaction.user.id) {
await interaction.reply({ content: "You can't mute yourself.", ephemeral: true })
return
}
const ms = parseDuration(durationInput)
if (!ms) {
await interaction.reply({ content: 'Invalid duration — use a number plus s/m/h/d, e.g. `10m`, `2h`, `1d`.', ephemeral: true })
return
}
const clampedMs = Math.min(ms, MAX_TIMEOUT_MS)
const member = interaction.guild.members.cache.get(user.id)
if (!member) {
await interaction.reply({ content: 'That user is not a member of this server.', ephemeral: true })
return
}
if (!member.moderatable) {
await interaction.reply({ content: "I don't have permission to timeout that member (role hierarchy).", ephemeral: true })
return
}
await member.timeout(clampedMs, reason)
const durationSeconds = Math.round(clampedMs / 1000)
await modLog.record({ client: interaction.client, guildId: interaction.guildId, actionType: 'mute', target: user, staffUser: interaction.user, reason, durationSeconds })
await interaction.reply({ content: `Muted ${user.tag} for ${durationInput}.`, ephemeral: true })
},
}

View File

@@ -0,0 +1,31 @@
const { PermissionFlagsBits, ApplicationCommandOptionType, ChannelType } = require('discord.js')
const guildConfig = require('../../model/guildConfig')
module.exports = {
data: {
name: 'news',
description: 'View or set the channel news posts are announced to.',
default_member_permissions: PermissionFlagsBits.ManageGuild.toString(),
options: [
{
name: 'channel',
description: 'Channel for news announcements. Omit to view the current setting.',
type: ApplicationCommandOptionType.Channel,
channel_types: [ChannelType.GuildText],
required: false,
},
],
},
async execute(interaction) {
const channel = interaction.options.getChannel('channel')
if (!channel) {
const currentId = await guildConfig.getNewsChannelId(interaction.guildId)
const content = currentId ? `News channel is set to <#${currentId}>.` : 'No news channel is set yet.'
await interaction.reply({ content, ephemeral: true })
return
}
await guildConfig.setNewsChannelId(interaction.guildId, channel.id)
await interaction.reply({ content: `News channel set to ${channel}.`, ephemeral: true })
},
}

View File

@@ -0,0 +1,15 @@
const { PermissionFlagsBits } = require('discord.js')
module.exports = {
data: {
name: 'ping',
description: 'Health-check — replies pong if the bot is alive and staff-permitted.',
// Restricted by default to members with Moderate Members — proves slash
// commands can be permission-gated via Discord's own permission model,
// per the spec's "restrict staff commands via Discord's permission system".
default_member_permissions: PermissionFlagsBits.ModerateMembers.toString(),
},
async execute(interaction) {
await interaction.reply({ content: 'pong', ephemeral: true })
},
}

View File

@@ -0,0 +1,71 @@
const { PermissionFlagsBits, ApplicationCommandOptionType } = require('discord.js')
const tempRoles = require('../../model/tempRoles')
const { parseDuration } = require('../../utils/duration')
module.exports = {
data: {
name: 'role',
description: 'Assign or remove a role for a single member.',
default_member_permissions: PermissionFlagsBits.ManageRoles.toString(),
options: [
{
name: 'add',
description: 'Add a role to a member, optionally temporary.',
type: ApplicationCommandOptionType.Subcommand,
options: [
{ name: 'user', description: 'Member', type: ApplicationCommandOptionType.User, required: true },
{ name: 'role', description: 'Role to add', type: ApplicationCommandOptionType.Role, required: true },
{ name: 'duration', description: 'Optional — makes this temporary, e.g. 1h, 2d, 7d', type: ApplicationCommandOptionType.String, required: false },
],
},
{
name: 'remove',
description: 'Remove a role from a member.',
type: ApplicationCommandOptionType.Subcommand,
options: [
{ name: 'user', description: 'Member', type: ApplicationCommandOptionType.User, required: true },
{ name: 'role', description: 'Role to remove', type: ApplicationCommandOptionType.Role, required: true },
],
},
],
},
async execute(interaction) {
const sub = interaction.options.getSubcommand()
const user = interaction.options.getUser('user', true)
const role = interaction.options.getRole('role', true)
const member = interaction.guild.members.cache.get(user.id)
if (!member) {
await interaction.reply({ content: 'That user is not a member of this server.', ephemeral: true })
return
}
if (sub === 'add') {
await member.roles.add(role.id)
const durationInput = interaction.options.getString('duration')
if (!durationInput) {
await interaction.reply({ content: `Added ${role} to ${user.tag}.`, ephemeral: true })
return
}
const ms = parseDuration(durationInput)
if (!ms) {
await interaction.reply({
content: `Added ${role}, but "${durationInput}" isn't a valid duration so it won't expire automatically. Use e.g. 1h, 2d, 7d.`,
ephemeral: true,
})
return
}
const expiresAt = new Date(Date.now() + ms)
await tempRoles.add({ guildId: interaction.guildId, userId: user.id, roleId: role.id, expiresAt, createdBy: interaction.user.id })
await interaction.reply({ content: `Added ${role} to ${user.tag} until ${expiresAt.toLocaleString()}.`, ephemeral: true })
return
}
if (sub === 'remove') {
await member.roles.remove(role.id)
await tempRoles.remove(interaction.guildId, user.id, role.id)
await interaction.reply({ content: `Removed ${role} from ${user.tag}.`, ephemeral: true })
}
},
}

View File

@@ -0,0 +1,85 @@
const {
PermissionFlagsBits,
ApplicationCommandOptionType,
ChannelType,
EmbedBuilder,
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
} = require('discord.js')
const roleMenus = require('../../model/roleMenus')
// Capped at 5 roles per menu — a single Discord action row holds at most 5
// buttons, and one row keeps this a single simple slash command instead of
// needing a multi-step builder/modal flow.
const MAX_ROLES = 5
// role1/label1 are declared inline in `data` (ahead of the optional
// `description` option, per Discord's required-before-optional rule) — this
// generates the rest, all optional.
function roleOptions(from, to) {
const opts = []
for (let i = from; i <= to; i++) {
opts.push({ name: `role${i}`, description: `Role #${i}`, type: ApplicationCommandOptionType.Role, required: false })
opts.push({ name: `label${i}`, description: `Button label for role #${i} (default: role name)`, type: ApplicationCommandOptionType.String, required: false })
}
return opts
}
module.exports = {
data: {
name: 'rolemenu',
description: 'Post a button menu for self-assignable roles (up to 5).',
default_member_permissions: PermissionFlagsBits.ManageGuild.toString(),
// Discord requires all required options before any optional ones across
// the whole array — role1 (required) must come before description
// (optional), even though they read more naturally in the other order.
options: [
{ name: 'channel', description: 'Channel to post the menu in', type: ApplicationCommandOptionType.Channel, channel_types: [ChannelType.GuildText], required: true },
{ name: 'title', description: 'Menu title', type: ApplicationCommandOptionType.String, required: true },
{ name: 'role1', description: 'Role #1', type: ApplicationCommandOptionType.Role, required: true },
{ name: 'description', description: 'Menu description', type: ApplicationCommandOptionType.String, required: false },
{ name: 'label1', description: 'Button label for role #1 (default: role name)', type: ApplicationCommandOptionType.String, required: false },
...roleOptions(2, MAX_ROLES),
],
},
async execute(interaction) {
const channel = interaction.options.getChannel('channel', true)
const title = interaction.options.getString('title', true)
const description = interaction.options.getString('description') || undefined
const entries = []
for (let i = 1; i <= MAX_ROLES; i++) {
const role = interaction.options.getRole(`role${i}`)
if (!role) continue
const label = interaction.options.getString(`label${i}`) || role.name
entries.push({ roleId: role.id, label })
}
if (entries.length === 0) {
await interaction.reply({ content: 'Provide at least one role (role1).', ephemeral: true })
return
}
const embed = new EmbedBuilder().setTitle(title).setColor(0x6a8fc2)
if (description) embed.setDescription(description)
const row = new ActionRowBuilder().addComponents(
entries.map((e) =>
new ButtonBuilder().setCustomId(`rolemenu:${e.roleId}`).setLabel(e.label).setStyle(ButtonStyle.Secondary),
),
)
const message = await channel.send({ embeds: [embed], components: [row] })
await roleMenus.add({
guildId: interaction.guildId,
channelId: channel.id,
messageId: message.id,
mapping: entries,
createdBy: interaction.user.id,
})
await interaction.reply({ content: `Role menu posted in ${channel}.`, ephemeral: true })
},
}

View File

@@ -0,0 +1,68 @@
const { PermissionFlagsBits, ApplicationCommandOptionType } = require('discord.js')
// Bulk targeting is "by existing role" only — the spec also mentions an
// explicit list of members, but Discord slash commands have no multi-user
// picker, so that variant is deferred rather than faked with a handful of
// user1..user5 options that would feel arbitrary and cramped.
module.exports = {
data: {
name: 'roles',
description: 'Bulk role operations across members who share an existing role.',
default_member_permissions: PermissionFlagsBits.ManageRoles.toString(),
options: [
{
name: 'bulk-assign',
description: 'Add a role to every member who has another role.',
type: ApplicationCommandOptionType.Subcommand,
options: [
{ name: 'has-role', description: 'Members with this role are targeted', type: ApplicationCommandOptionType.Role, required: true },
{ name: 'add-role', description: 'Role to add to those members', type: ApplicationCommandOptionType.Role, required: true },
],
},
{
name: 'bulk-remove',
description: 'Remove a role from every member who has another role.',
type: ApplicationCommandOptionType.Subcommand,
options: [
{ name: 'has-role', description: 'Members with this role are targeted', type: ApplicationCommandOptionType.Role, required: true },
{ name: 'remove-role', description: 'Role to remove from those members', type: ApplicationCommandOptionType.Role, required: true },
],
},
],
},
async execute(interaction) {
const sub = interaction.options.getSubcommand()
// Fetching every member + looping role updates can easily exceed
// Discord's 3-second initial-response window.
await interaction.deferReply({ ephemeral: true })
const hasRole = interaction.options.getRole('has-role', true)
const members = await interaction.guild.members.fetch()
const targets = members.filter((m) => m.roles.cache.has(hasRole.id))
if (sub === 'bulk-assign') {
const addRole = interaction.options.getRole('add-role', true)
let count = 0
for (const member of targets.values()) {
if (!member.roles.cache.has(addRole.id)) {
await member.roles.add(addRole.id).catch(() => {})
count++
}
}
await interaction.editReply({ content: `Added ${addRole} to ${count} member(s) who have ${hasRole}.` })
return
}
if (sub === 'bulk-remove') {
const removeRole = interaction.options.getRole('remove-role', true)
let count = 0
for (const member of targets.values()) {
if (member.roles.cache.has(removeRole.id)) {
await member.roles.remove(removeRole.id).catch(() => {})
count++
}
}
await interaction.editReply({ content: `Removed ${removeRole} from ${count} member(s) who have ${hasRole}.` })
}
},
}

View File

@@ -0,0 +1,119 @@
const { PermissionFlagsBits, ApplicationCommandOptionType, ChannelType } = require('discord.js')
const cron = require('node-cron')
const scheduledMessages = require('../../model/scheduledMessages')
const scheduler = require('../../scheduler/scheduler')
const { parseDuration } = require('../../utils/duration')
module.exports = {
data: {
name: 'schedule',
description: 'Manage recurring and one-off scheduled channel messages.',
default_member_permissions: PermissionFlagsBits.ManageGuild.toString(),
options: [
{
name: 'recurring',
description: 'Schedule a recurring message on a cron schedule.',
type: ApplicationCommandOptionType.Subcommand,
options: [
{ name: 'channel', description: 'Channel to post in', type: ApplicationCommandOptionType.Channel, channel_types: [ChannelType.GuildText], required: true },
{ name: 'cron', description: 'Cron expression, e.g. "0 9 * * 5" (Fridays 9am)', type: ApplicationCommandOptionType.String, required: true },
{ name: 'message', description: 'Message content to post', type: ApplicationCommandOptionType.String, required: true },
],
},
{
name: 'once',
description: 'Schedule a one-off message for a future time.',
type: ApplicationCommandOptionType.Subcommand,
options: [
{ name: 'channel', description: 'Channel to post in', type: ApplicationCommandOptionType.Channel, channel_types: [ChannelType.GuildText], required: true },
{ name: 'in', description: 'When to post, e.g. 30m, 2h, 1d', type: ApplicationCommandOptionType.String, required: true },
{ name: 'message', description: 'Message content to post', type: ApplicationCommandOptionType.String, required: true },
],
},
{
name: 'remove',
description: 'Remove a scheduled message by id.',
type: ApplicationCommandOptionType.Subcommand,
options: [{ name: 'id', description: 'Scheduled message id (see /schedule list)', type: ApplicationCommandOptionType.Integer, required: true }],
},
{
name: 'list',
description: 'List all scheduled messages.',
type: ApplicationCommandOptionType.Subcommand,
options: [],
},
],
},
async execute(interaction) {
const sub = interaction.options.getSubcommand()
if (sub === 'recurring') {
const channel = interaction.options.getChannel('channel', true)
const cronExpr = interaction.options.getString('cron', true)
const message = interaction.options.getString('message', true)
if (!cron.validate(cronExpr)) {
await interaction.reply({ content: `"${cronExpr}" isn't a valid cron expression.`, ephemeral: true })
return
}
const id = await scheduledMessages.addRecurring({
guildId: interaction.guildId,
channelId: channel.id,
content: message,
cronExpression: cronExpr,
createdBy: interaction.user.id,
createdByTag: interaction.user.tag,
})
await scheduler.refresh()
await interaction.reply({ content: `Scheduled recurring message #${id} in ${channel} on \`${cronExpr}\`.`, ephemeral: true })
return
}
if (sub === 'once') {
const channel = interaction.options.getChannel('channel', true)
const inInput = interaction.options.getString('in', true)
const message = interaction.options.getString('message', true)
const ms = parseDuration(inInput)
if (!ms) {
await interaction.reply({ content: 'Invalid time — use a number plus s/m/h/d, e.g. `30m`, `2h`, `1d`.', ephemeral: true })
return
}
const runAt = new Date(Date.now() + ms)
const id = await scheduledMessages.addOnce({
guildId: interaction.guildId,
channelId: channel.id,
content: message,
runAt,
createdBy: interaction.user.id,
createdByTag: interaction.user.tag,
})
await interaction.reply({ content: `Scheduled one-off message #${id} in ${channel} for ${runAt.toLocaleString()}.`, ephemeral: true })
return
}
if (sub === 'remove') {
const id = interaction.options.getInteger('id', true)
const removed = await scheduledMessages.remove(interaction.guildId, id)
await scheduler.refresh()
await interaction.reply({ content: removed ? `Removed scheduled message #${id}.` : `No scheduled message #${id} found.`, ephemeral: true })
return
}
if (sub === 'list') {
const rows = await scheduledMessages.list(interaction.guildId)
if (rows.length === 0) {
await interaction.reply({ content: 'No scheduled messages.', ephemeral: true })
return
}
const lines = rows.map((r) => {
const kind = r.cron_expression
? `cron \`${r.cron_expression}\``
: r.sent_at
? `sent ${new Date(r.sent_at).toLocaleString()}`
: `due ${new Date(r.run_at).toLocaleString()}`
return `**#${r.id}** <#${r.channel_id}> — ${kind}${r.enabled ? '' : ' (disabled)'}`
})
await interaction.reply({ content: lines.join('\n'), ephemeral: true })
}
},
}

View File

@@ -0,0 +1,40 @@
const { PermissionFlagsBits, ApplicationCommandOptionType } = require('discord.js')
const modLog = require('../modLog')
const warnings = require('../../model/warnings')
// Escalation (e.g. "3 active warns -> auto-mute for X hours") and warning
// decay/expiry are in the original spec but deferred past this phase — this
// just records the warning and posts it to the mod-log, matching the
// "Suggested Build Order" step 2 scope (core moderation).
module.exports = {
data: {
name: 'warn',
description: 'Log a warning against a member.',
default_member_permissions: PermissionFlagsBits.ModerateMembers.toString(),
options: [
{ name: 'user', description: 'Member to warn', type: ApplicationCommandOptionType.User, required: true },
{ name: 'reason', description: 'Reason for the warning', type: ApplicationCommandOptionType.String, required: true },
],
},
async execute(interaction) {
const user = interaction.options.getUser('user', true)
const reason = interaction.options.getString('reason', true)
if (user.id === interaction.user.id) {
await interaction.reply({ content: "You can't warn yourself.", ephemeral: true })
return
}
await warnings.add({
guildId: interaction.guildId,
targetUserId: user.id,
targetTag: user.tag,
staffUserId: interaction.user.id,
staffTag: interaction.user.tag,
reason,
})
await modLog.record({ client: interaction.client, guildId: interaction.guildId, actionType: 'warn', target: user, staffUser: interaction.user, reason })
await interaction.reply({ content: `Warned ${user.tag}.`, ephemeral: true })
},
}

View File

@@ -0,0 +1,34 @@
const { PermissionFlagsBits, ApplicationCommandOptionType, EmbedBuilder } = require('discord.js')
const warnings = require('../../model/warnings')
module.exports = {
data: {
name: 'warnings',
description: "List a member's active warnings.",
default_member_permissions: PermissionFlagsBits.ModerateMembers.toString(),
options: [
{ name: 'user', description: 'Member to look up', type: ApplicationCommandOptionType.User, required: true },
],
},
async execute(interaction) {
const user = interaction.options.getUser('user', true)
const rows = await warnings.listActive(interaction.guildId, user.id)
if (rows.length === 0) {
await interaction.reply({ content: `${user.tag} has no active warnings.`, ephemeral: true })
return
}
const embed = new EmbedBuilder()
.setColor(0xe0b070)
.setTitle(`Warnings — ${user.tag}`)
.setDescription(
rows
.map((w, i) => `**${i + 1}.** ${w.reason || '(no reason given)'} — by ${w.staff_tag || 'unknown'} on ${new Date(w.created_at).toLocaleDateString()}`)
.join('\n'),
)
await interaction.reply({ embeds: [embed], ephemeral: true })
},
}

View File

@@ -0,0 +1,40 @@
const { ApplicationCommandOptionType } = require('discord.js')
const siteApiClient = require('../../site/siteApiClient')
// Public command — no default_member_permissions restriction. Read-only:
// searches wiki titles/content and links to the best match. Never posts to or
// edits the wiki. Category-scoped search (spec's optional "/wiki spells
// fireball") is deferred — the site's public search endpoint currently
// ignores category filters whenever a text query is given.
function siteOrigin() {
const base = process.env.SITE_PUBLIC_URL || 'http://localhost:3000/api/v1/public'
return new URL(base).origin
}
module.exports = {
data: {
name: 'wiki',
description: 'Search the wiki.',
options: [{ name: 'query', description: 'What to search for', type: ApplicationCommandOptionType.String, required: true }],
},
async execute(interaction) {
const query = interaction.options.getString('query', true)
await interaction.deferReply()
const result = await siteApiClient.searchWiki(query)
if (result.maintenance) {
await interaction.editReply({ content: `The wiki is unavailable right now: ${result.message || 'maintenance mode'}` })
return
}
if (!result.ok || !result.data || result.data.length === 0) {
await interaction.editReply({ content: `No wiki results for "${query}".` })
return
}
const best = result.data[0]
const url = `${siteOrigin()}/wiki/${best.slug}`
const content = best.excerpt ? `**${best.title}**\n${best.excerpt}\n${url}` : `**${best.title}**\n${url}`
await interaction.editReply({ content })
},
}