Files
bot.js
package.json
Code
2 848
bot.js
require('dotenv').config();
const {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
ChannelType,
Client,
EmbedBuilder,
GatewayIntentBits,
PermissionFlagsBits,
SlashCommandBuilder
} = require('discord.js');
const Database = require('better-sqlite3');
if (!process.env.DISCORD_TOKEN) {
throw new Error('DISCORD_TOKEN is missing. Add it to your .env file.');
}
const db = new Database('fbi-management.sqlite');
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
db.exec(`
CREATE TABLE IF NOT EXISTS settings (guild_id TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (guild_id, key));
CREATE TABLE IF NOT EXISTS shifts (id INTEGER PRIMARY KEY AUTOINCREMENT, guild_id TEXT NOT NULL, user_id TEXT NOT NULL, started_at INTEGER NOT NULL, ended_at INTEGER, break_total INTEGER NOT NULL DEFAULT 0, break_started_at INTEGER, status TEXT NOT NULL DEFAULT 'active', ended_by TEXT);
CREATE TABLE IF NOT EXISTS promotions (id INTEGER PRIMARY KEY AUTOINCREMENT, guild_id TEXT NOT NULL, user_id TEXT NOT NULL, old_rank TEXT NOT NULL, new_rank TEXT NOT NULL, reason TEXT NOT NULL, actor_id TEXT NOT NULL, created_at INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'active');
CREATE TABLE IF NOT EXISTS infractions (id INTEGER PRIMARY KEY AUTOINCREMENT, guild_id TEXT NOT NULL, user_id TEXT NOT NULL, type TEXT NOT NULL, reason TEXT NOT NULL, actor_id TEXT NOT NULL, created_at INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'active', removed_by TEXT, removed_reason TEXT);
CREATE TABLE IF NOT EXISTS retirements (id INTEGER PRIMARY KEY AUTOINCREMENT, guild_id TEXT NOT NULL, user_id TEXT NOT NULL, rank TEXT NOT NULL, department TEXT NOT NULL, reason TEXT NOT NULL, status TEXT NOT NULL, submitted_at INTEGER NOT NULL, action_by TEXT, action_at INTEGER, action_reason TEXT);
CREATE TABLE IF NOT EXISTS warrants (id TEXT PRIMARY KEY, guild_id TEXT NOT NULL, suspect_id TEXT NOT NULL, suspect_name TEXT NOT NULL, reason TEXT NOT NULL, image_url TEXT NOT NULL, created_by TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'active', executed_by TEXT, channel_id TEXT, message_id TEXT);
CREATE TABLE IF NOT EXISTS departments (guild_id TEXT NOT NULL, name TEXT NOT NULL, role_id TEXT, PRIMARY KEY (guild_id, name));
CREATE TABLE IF NOT EXISTS department_members (guild_id TEXT NOT NULL, user_id TEXT NOT NULL, department TEXT NOT NULL, PRIMARY KEY (guild_id, user_id));
CREATE TABLE IF NOT EXISTS reports (id INTEGER PRIMARY KEY AUTOINCREMENT, guild_id TEXT NOT NULL, type TEXT NOT NULL, title TEXT NOT NULL, reporter_id TEXT NOT NULL, people TEXT NOT NULL, description TEXT NOT NULL, case_number TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'Open', created_at INTEGER NOT NULL);
`);
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const DAY = 24 * 60 * 60 * 1000;
const COLORS = { green: 0x2ecc71, red: 0xe74c3c, gold: 0xf1c40f, orange: 0xe67e22, purple: 0x8e44ad, blue: 0x3498db, gray: 0x7f8c8d };
const INFO_TOPICS = {
sop: ['FBI Standard Operating Procedures', 'Department procedures have not been configured. Ask an administrator to use `/info set`.'],
'10-codes': ['Radio 10-Codes', '10-codes have not been configured. Ask an administrator to use `/info set`.'],
'miranda-rights': ['Miranda Rights', 'Miranda rights information has not been configured. Ask an administrator to use `/info set`.'],
'fbi-ranks': ['FBI Ranks', 'The rank hierarchy has not been configured. Ask an administrator to use `/info set`.'],
'chain-of-command': ['Chain of Command', 'The chain of command has not been configured. Ask an administrator to use `/info set`.'],
'radio-codes': ['Radio Codes', 'Radio codes have not been configured. Ask an administrator to use `/info set`.'],
'fbi-rules': ['FBI Rules', 'Department rules have not been configured. Ask an administrator to use `/info set`.'],
'uniform-guide': ['Uniform Guide', 'Uniform requirements have not been configured. Ask an administrator to use `/info set`.'],
'training-info': ['Training Information', 'Training information has not been configured. Ask an administrator to use `/info set`.'],
'department-info': ['Department Information', 'Department details have not been configured.'],
'interview-info': ['Interview Information', 'Interview information has not been configured.'],
'recruitment-status': ['Recruitment Status', 'Recruitment is currently closed.']
};
function getSetting(guildId, key, fallback = '') {
return db.prepare('SELECT value FROM settings WHERE guild_id = ? AND key = ?').get(guildId, key)?.value ?? fallback;
}
function setSetting(guildId, key, value) {
db.prepare('INSERT INTO settings (guild_id, key, value) VALUES (?, ?, ?) ON CONFLICT(guild_id, key) DO UPDATE SET value = excluded.value').run(guildId, key, String(value));
}
function makeEmbed(title, description, color = COLORS.blue, member = null) {
const embed = new EmbedBuilder().setTitle(title).setDescription(description).setColor(color).setTimestamp();
if (member?.user) embed.setThumbnail(member.user.displayAvatarURL());
return embed;
}
function withBanner(guildId, kind, embed) {
const url = getSetting(guildId, `${kind}_banner`);
if (url) embed.setImage(url);
return embed;
}
function validImageUrl(value) {
try {
const url = new URL(value);
return url.protocol === 'https:' && /\.(png|jpe?g|gif|webp)(\?.*)?$/i.test(url.href);
} catch {
return false;
}
}
function formatDuration(ms) {
const minutes = Math.max(0, Math.floor(ms / 60000));
const days = Math.floor(minutes / 1440);
const hours = Math.floor((minutes % 1440) / 60);
const remainder = minutes % 60;
return `${days ? `${days}d ` : ''}${hours}h ${remainder}m`;
}
function hasRole(member, settingKey) {
const ids = getSetting(member.guild.id, settingKey).split(',').map(value => value.trim()).filter(Boolean);
return ids.some(id => member.roles.cache.has(id));
}
function isAdministrator(member) {
return member.permissions.has(PermissionFlagsBits.Administrator) || hasRole(member, 'administrator_role_ids');
}
function canManageStaff(member) {
return isAdministrator(member) || hasRole(member, 'management_role_ids') || hasRole(member, 'supervisor_role_ids');
}
function canUseWarrants(member) {
return isAdministrator(member) || hasRole(member, 'staff_role_ids') || hasRole(member, 'warrant_role_ids');
}
function command(name, description) {
return new SlashCommandBuilder().setName(name).setDescription(description);
}
const commands = [];
const shift = command('shift', 'Manage staff shifts')
.addSubcommand(s => s.setName('start').setDescription('Start your shift'))
.addSubcommand(s => s.setName('end').setDescription('End your shift'))
.addSubcommand(s => s.setName('status').setDescription('Check your shift status').addUserOption(o => o.setName('user').setDescription('Staff member')))
.addSubcommand(s => s.setName('stats').setDescription('View shift totals').addUserOption(o => o.setName('user').setDescription('Staff member')))
.addSubcommand(s => s.setName('history').setDescription('View recent shift history').addUserOption(o => o.setName('user').setDescription('Staff member')))
.addSubcommand(s => s.setName('leaderboard').setDescription('Rank staff by working time'))
.addSubcommand(s => s.setName('active').setDescription('List staff currently on shift'))
.addSubcommand(s => s.setName('break').setDescription('Pause your shift for a break'))
.addSubcommand(s => s.setName('resume').setDescription('Resume your shift'))
.addSubcommand(s => s.setName('force-end').setDescription('End another member shift').addUserOption(o => o.setName('user').setDescription('Staff member').setRequired(true)))
.addSubcommand(s => s.setName('reset').setDescription('Archive shift records for a member').addUserOption(o => o.setName('user').setDescription('Staff member').setRequired(true)).addBooleanOption(o => o.setName('confirm').setDescription('Confirm archiving records').setRequired(true)))
.addSubcommand(s => s.setName('report').setDescription('Generate the staff shift activity report'));
commands.push(shift);
const config = command('config', 'Configure channels, roles, and banners')
.addSubcommand(s => s.setName('channel').setDescription('Set a logging or output channel').addStringOption(o => o.setName('type').setDescription('Channel type').setRequired(true).addChoices(...['shift-logs', 'promotion-logs', 'infraction-logs', 'retirement-logs', 'audit-logs', 'reports', 'announcements', 'recruitment', 'warrant'].map(x => ({ name: x, value: x })))).addChannelOption(o => o.setName('channel').setDescription('Target text channel').setRequired(true).addChannelTypes(ChannelType.GuildText)))
.addSubcommand(s => s.setName('roles').setDescription('Configure authorized role IDs (comma-separated)').addStringOption(o => o.setName('type').setDescription('Permission group').setRequired(true).addChoices({ name: 'administrator', value: 'administrator_role_ids' }, { name: 'supervisor', value: 'supervisor_role_ids' }, { name: 'staff', value: 'staff_role_ids' }, { name: 'management', value: 'management_role_ids' }, { name: 'warrant', value: 'warrant_role_ids' }, { name: 'retired', value: 'retired_role_id' })).addStringOption(o => o.setName('role-ids').setDescription('Comma-separated IDs; blank clears').setRequired(true)))
.addSubcommand(s => s.setName('banner').setDescription('Set or clear a custom banner').addStringOption(o => o.setName('type').setDescription('Banner system').setRequired(true).addChoices({ name: 'promotion', value: 'promotion' }, { name: 'infraction', value: 'infraction' }, { name: 'retirement', value: 'retirement' }, { name: 'warrant', value: 'warrant' })).addStringOption(o => o.setName('url').setDescription('HTTPS image URL; omit to clear').setRequired(false)))
.addSubcommand(s => s.setName('rank-role').setDescription('Map a rank to a Discord role').addStringOption(o => o.setName('rank').setDescription('Rank name').setRequired(true)).addRoleOption(o => o.setName('role').setDescription('Role to assign').setRequired(true)));
commands.push(config);
commands.push(command('warrant', 'Issue a roleplay arrest warrant')
.addUserOption(o => o.setName('suspect').setDescription('Person named in the warrant').setRequired(true))
.addStringOption(o => o.setName('reason').setDescription('Reason for the warrant').setRequired(true).setMaxLength(1000))
.addStringOption(o => o.setName('image').setDescription('HTTPS evidence image URL').setRequired(true)));
commands.push(command('warrant-list', 'List active warrants'));
const promotion = command('promotion', 'Manage staff promotions')
.addSubcommand(s => s.setName('give').setDescription('Promote a member').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)).addStringOption(o => o.setName('rank').setDescription('New rank').setRequired(true)).addStringOption(o => o.setName('reason').setDescription('Reason').setRequired(true)))
.addSubcommand(s => s.setName('history').setDescription('View promotion history').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)))
.addSubcommand(s => s.setName('list').setDescription('List current rank records'))
.addSubcommand(s => s.setName('remove').setDescription('Revoke a promotion record').addIntegerOption(o => o.setName('id').setDescription('Promotion record ID').setRequired(true)).addStringOption(o => o.setName('reason').setDescription('Reason').setRequired(true)));
commands.push(promotion);
const infraction = command('infraction', 'Manage staff disciplinary records')
.addSubcommand(s => s.setName('issue').setDescription('Issue an infraction').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)).addStringOption(o => o.setName('type').setDescription('Infraction type').setRequired(true).addChoices(...['Verbal Warning', 'Written Warning', 'Staff Strike', 'Formal Infraction', 'Final Warning', 'Suspension'].map(x => ({ name: x, value: x })))).addStringOption(o => o.setName('reason').setDescription('Reason').setRequired(true)))
.addSubcommand(s => s.setName('history').setDescription('View infractions for a member').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)))
.addSubcommand(s => s.setName('list').setDescription('List active infractions'))
.addSubcommand(s => s.setName('remove').setDescription('Mark an infraction as removed').addIntegerOption(o => o.setName('id').setDescription('Infraction ID').setRequired(true)).addStringOption(o => o.setName('reason').setDescription('Removal reason').setRequired(true)))
.addSubcommand(s => s.setName('info').setDescription('View an infraction record').addIntegerOption(o => o.setName('id').setDescription('Infraction ID').setRequired(true)));
commands.push(infraction);
const retirement = command('retirement', 'Manage retirement requests')
.addSubcommand(s => s.setName('submit').setDescription('Submit your retirement request').addStringOption(o => o.setName('reason').setDescription('Reason').setRequired(true)))
.addSubcommand(s => s.setName('approve').setDescription('Approve a retirement').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)))
.addSubcommand(s => s.setName('deny').setDescription('Deny a pending retirement').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)).addStringOption(o => o.setName('reason').setDescription('Reason').setRequired(true)))
.addSubcommand(s => s.setName('history').setDescription('View retirement history').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)))
.addSubcommand(s => s.setName('list').setDescription('List pending retirement requests'))
.addSubcommand(s => s.setName('revoke').setDescription('Revoke a retirement').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)).addStringOption(o => o.setName('reason').setDescription('Reason').setRequired(true)));
commands.push(retirement);
const department = command('department', 'Manage departments and memberships')
.addSubcommand(s => s.setName('configure').setDescription('Create or update a department').addStringOption(o => o.setName('name').setDescription('Department name').setRequired(true)).addRoleOption(o => o.setName('role').setDescription('Optional department role')))
.addSubcommand(s => s.setName('assign').setDescription('Assign a member to a department').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)).addStringOption(o => o.setName('name').setDescription('Department').setRequired(true)))
.addSubcommand(s => s.setName('remove').setDescription('Remove a member from their department').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)))
.addSubcommand(s => s.setName('roster').setDescription('Show a department roster').addStringOption(o => o.setName('name').setDescription('Department').setRequired(true)))
.addSubcommand(s => s.setName('leadership').setDescription('Show department leadership and configured roles'))
.addSubcommand(s => s.setName('list').setDescription('List configured departments'));
commands.push(department);
const reportCommand = (name, description, type) => command(name, description)
.addStringOption(o => o.setName('title').setDescription('Report title').setRequired(true))
.addStringOption(o => o.setName('description').setDescription('Detailed report').setRequired(true).setMaxLength(3000))
.addStringOption(o => o.setName('people').setDescription('People involved').setRequired(true))
.addStringOption(o => o.setName('case-number').setDescription('Case/reference number').setRequired(true))
.setDMPermission(false);
for (const [name, description, type] of [
['arrest-report', 'Submit an arrest report', 'Arrest'], ['incident-report', 'Submit an incident report', 'Incident'],
['investigation-report', 'Submit an investigation report', 'Investigation'], ['evidence-log', 'Submit an evidence log', 'Evidence']
]) commands.push(reportCommand(name, description, type));
commands.push(command('case-status', 'Check a saved case').addStringOption(o => o.setName('case-number').setDescription('Case/reference number').setRequired(true)));
commands.push(command('warrant-info', 'Look up an active warrant').addStringOption(o => o.setName('id').setDescription('Warrant ID').setRequired(true)));
commands.push(command('suspect-info', 'Show saved roleplay reports for a member').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)));
commands.push(command('info', 'Set configurable FBI information')
.addSubcommand(s => s.setName('set').setDescription('Set information shown by a public information command').addStringOption(o => o.setName('topic').setDescription('Information topic').setRequired(true).addChoices(...Object.keys(INFO_TOPICS).map(x => ({ name: x, value: x })))).addStringOption(o => o.setName('text').setDescription('Information text').setRequired(true).setMaxLength(3500))));
for (const topic of Object.keys(INFO_TOPICS)) commands.push(command(topic, INFO_TOPICS[topic][0]));
commands.push(command('departments', 'List available departments'));
commands.push(command('department-roster', 'Show a department roster').addStringOption(o => o.setName('name').setDescription('Department name').setRequired(true)));
commands.push(command('department-leadership', 'Show department role configuration'));
commands.push(command('assign-department', 'Assign a department').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)).addStringOption(o => o.setName('name').setDescription('Department').setRequired(true)));
commands.push(command('remove-department', 'Remove a member department').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)));
commands.push(command('staff-profile', 'View a member career profile').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)));
commands.push(command('staff-list', 'List recorded staff members'));
commands.push(command('staff-info', 'Show staff member information').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)));
commands.push(command('promote', 'Promote a staff member').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)).addStringOption(o => o.setName('rank').setDescription('New rank').setRequired(true)).addStringOption(o => o.setName('reason').setDescription('Reason').setRequired(true)));
commands.push(command('demote', 'Record a staff demotion').addUserOption(o => o.setName('user').setDescription('Member').setRequired(true)).addStringOption(o => o.setName('rank').setDescription('New rank').setRequired(true)).addStringOption(o => o.setName('reason').setDescription('Reason').setRequired(true)));