18 Commits
Author SHA1 Message Date
nxbat 27481e6e04 Fix additional conflicts manually. 2026-10-20 16:30:59 +00:00
nxbat c3a831f198 Merge initial changes. 2026-10-20 16:25:09 +00:00
nxbat 5f7ad1921f oops :derp: 2026-10-14 18:19:12 +08:00
nxbat 687b647ca8 (buttons): Type-checking & linting. 2026-10-14 12:57:09 +08:00
nxbat 6c7fe40f54 (buttons): Bug-testing round 1. 2026-10-14 12:53:37 +08:00
nxbat 71e2d1c088 (buttons): Hook up buttons. Pre-testing. 2026-10-14 12:18:35 +08:00
nxbat 12cdba21b5 (buttons): Implement unclaim-ticket button. 2026-10-14 12:04:59 +08:00
nxbat 5a5a82f890 (buttons): Implement role-button button. 2026-10-14 12:04:38 +08:00
nxbat f92a650536 (buttons): Implement role-button button. 2026-10-14 11:58:27 +08:00
nxbat e87be791eb (buttons): Implement records-next & records-previous buttons. 2026-10-14 11:46:48 +08:00
nxbat 9d2b2e6a9e (buttons): Implement private-help button. 2026-10-14 11:41:51 +08:00
nxbat 2a96359d8d (buttons): Implement open-ticket-for-reported-message button. 2026-10-14 11:26:43 +08:00
nxbat e0aa68874d (buttons): Implement note-next & note-previous buttons. 2026-10-14 10:44:03 +08:00
nxbat 2f14da099d (buttons): Implement dev-watch button. 2026-10-14 10:37:25 +08:00
nxbat 8e88b2c83a (buttons): Implement close-ticket button. 2026-10-14 10:28:54 +08:00
nxbat 0d2e4403f7 (buttons): Implement close-mod-ticket button & fix claim-ticket. 2026-10-14 10:23:00 +08:00
nxbat f4f0044dc3 (buttons): Implement claim-ticket button. 2026-10-14 10:09:35 +08:00
nxbat 1d58c9692c (buttons): Add Button<Context> interface. 2026-10-14 10:07:07 +08:00
44 changed files with 546 additions and 504 deletions
+4 -8
View File
@@ -1,9 +1,5 @@
# Directories node_modules
certs/ dist
data/ data/*
dist/
node_modules/
# Files
.DS_Store
.env .env
certs/*
@@ -1,9 +0,0 @@
--------------------------------------------------------------------------------
-- Up
--------------------------------------------------------------------------------
ALTER TABLE settings DROP COLUMN devwatch_role_id;
--------------------------------------------------------------------------------
-- Down
--------------------------------------------------------------------------------
ALTER TABLE settings ADD devwatch_role_id TEXT;
+9 -11
View File
@@ -1,6 +1,6 @@
import { ActionRowBuilder, ButtonBuilder, ButtonInteraction, ButtonStyle, ChannelType, Client, MessageFlags, PermissionFlagsBits } from 'discord.js'; import { ActionRowBuilder, ButtonBuilder, ButtonInteraction, ButtonStyle, ChannelType, Client, MessageFlags } from 'discord.js';
import { Database } from '../shared/Database';
import { Button } from '../types'; import { Button } from '../types';
import { SetSeverity } from '../utils';
class ClaimTicketButton implements Button<Client> { class ClaimTicketButton implements Button<Client> {
id = 'claim-ticket'; id = 'claim-ticket';
@@ -16,7 +16,12 @@ class ClaimTicketButton implements Button<Client> {
if (!channel.isThread() || channel.type != ChannelType.PrivateThread) throw new Error('This interaction was not run in a ticket thread.'); if (!channel.isThread() || channel.type != ChannelType.PrivateThread) throw new Error('This interaction was not run in a ticket thread.');
if (!channel.isSendable()) throw new Error("I don't have permission to send messages in this channel."); if (!channel.isSendable()) throw new Error("I don't have permission to send messages in this channel.");
if (!interaction.memberPermissions.has(PermissionFlagsBits.ManageMessages)) throw new Error("You don't have permission to claim tickets."); const settings = await Database.getOrCreateSettings(interaction.guildId);
if (!settings.private_help_role_id) throw new Error("`private_help_role_id` hasn't been configured. Please report this error to staff.");
const guild = await context.guilds.fetch(interaction.guildId);
const member = await guild.members.fetch(interaction.user.id);
if (!member.roles.cache.has(settings.private_help_role_id)) throw new Error("You don't have permission to claim tickets.");
const closeButton = new ButtonBuilder() const closeButton = new ButtonBuilder()
.setCustomId('close-ticket') .setCustomId('close-ticket')
@@ -35,14 +40,7 @@ class ClaimTicketButton implements Button<Client> {
components: [row] components: [row]
}); });
await channel.send({ await interaction.editReply({ content: `Ticket claimed by ${interaction.user}.` });
embeds: [{
...SetSeverity('success'),
description: `This ticket has been claimed by ${interaction.user}.`
}],
});
await interaction.editReply({ content: "You've claimed this ticket." });
} catch (error: Error | any) { } catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {}); await interaction.editReply({ content: error.message }).catch(() => {});
} }
+4 -1
View File
@@ -16,7 +16,10 @@ class CloseTicketButton implements Button<Client> {
if (!channel.isThread() || channel.type != ChannelType.PrivateThread) throw new Error('This interaction was not run in a ticket thread.'); if (!channel.isThread() || channel.type != ChannelType.PrivateThread) throw new Error('This interaction was not run in a ticket thread.');
if (!channel.isSendable()) throw new Error("I don't have permission to send messages in this channel."); if (!channel.isSendable()) throw new Error("I don't have permission to send messages in this channel.");
await interaction.editReply({ content: 'Closing, please wait...' }); await interaction.reply({
content: 'Closing, please wait...',
flags: MessageFlags.Ephemeral
});
await interaction.message.edit({ await interaction.message.edit({
content: interaction.message.content, content: interaction.message.content,
+25 -8
View File
@@ -1,20 +1,37 @@
import { ButtonInteraction, Client, MessageFlags } from 'discord.js'; import { ButtonInteraction, Client, MessageFlags } from 'discord.js';
import { Database } from '../shared/Database';
import { Button } from '../types'; import { Button } from '../types';
import { SetSeverity } from '../utils';
class DevWatchButton implements Button<Client> { class DevWatchButton implements Button<Client> {
id = 'dev-watch'; id = 'dev-watch';
async execute(context: Client<boolean>, interaction: ButtonInteraction): Promise<void> { async execute(context: Client<boolean>, interaction: ButtonInteraction): Promise<void> {
if (!interaction.inGuild()) return; if (!interaction.inGuild()) return;
await interaction.reply({ await interaction.deferReply({ flags: MessageFlags.Ephemeral });
embeds: [{
...SetSeverity('warning'),
description: 'DevWatch roles have been deprecated in favour of the `/role-buttons create` command. Please notify an administrator to setup a new role-button.'
}],
flags: MessageFlags.Ephemeral, try {
}); const settings = await Database.getOrCreateSettings(interaction.guildId);
if (!settings.devwatch_role_id) throw new Error('`devwatch_role_id` was not configured. Please configure a role then try again.');
const guild = await context.guilds.fetch(interaction.guildId);
const member = await guild.members.fetch(interaction.user.id);
if (!member) throw new Error('Unable to fetch the member executing this command.');
const bot = await guild.members.fetchMe();
const role = await guild.roles.fetch(settings.devwatch_role_id);
if (!role) throw new Error('The configured `devwatch_role_id` does not exist.');
if (role.position > bot.roles.highest.position) throw new Error('The configured `devwatch_role_id` is higher than my highest role.');
if (member.roles.cache.has(settings.devwatch_role_id)) {
await member.roles.remove(settings.devwatch_role_id);
await interaction.editReply({ content: 'Removed role.' });
} else {
await member.roles.add(settings.devwatch_role_id);
await interaction.editReply({ content: 'Added role.' });
}
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
} }
} }
+9 -11
View File
@@ -1,6 +1,6 @@
import { ActionRowBuilder, ButtonBuilder, ButtonInteraction, ButtonStyle, ChannelType, Client, MessageFlags, PermissionFlagsBits } from 'discord.js'; import { ActionRowBuilder, ButtonBuilder, ButtonInteraction, ButtonStyle, ChannelType, Client, MessageFlags } from 'discord.js';
import { Database } from '../shared/Database';
import { Button } from '../types'; import { Button } from '../types';
import { SetSeverity } from '../utils';
class UnclaimTicketButton implements Button<Client> { class UnclaimTicketButton implements Button<Client> {
id = 'unclaim-ticket'; id = 'unclaim-ticket';
@@ -16,9 +16,14 @@ class UnclaimTicketButton implements Button<Client> {
if (!channel.isThread() || channel.type != ChannelType.PrivateThread) throw new Error('This interaction was not run in a ticket thread.'); if (!channel.isThread() || channel.type != ChannelType.PrivateThread) throw new Error('This interaction was not run in a ticket thread.');
if (!channel.isSendable()) throw new Error("I don't have permission to send messages in this channel."); if (!channel.isSendable()) throw new Error("I don't have permission to send messages in this channel.");
if (!interaction.memberPermissions.has(PermissionFlagsBits.ManageMessages)) throw new Error("You don't have permission to unclaim tickets."); const settings = await Database.getOrCreateSettings(interaction.guildId);
if (!settings.private_help_role_id) throw new Error("`private_help_role_id` hasn't been configured. Please report this error to staff.");
if (!interaction.message.content.split('\n').at(-1)!.includes(`<@${interaction.user.id}>`)) throw new Error("You haven't claimed this ticket."); const guild = await context.guilds.fetch(interaction.guildId);
const member = await guild.members.fetch(interaction.user.id);
if (!member.roles.cache.has(settings.private_help_role_id)) throw new Error("You don't have permission to claim tickets.");
if (!interaction.message.content.split('\n').at(-1)!.includes(`<@${interaction.user.id}>`)) throw new Error('You haven\'t claimed this ticket.');
const closeButton = new ButtonBuilder() const closeButton = new ButtonBuilder()
.setCustomId('close-ticket') .setCustomId('close-ticket')
@@ -37,13 +42,6 @@ class UnclaimTicketButton implements Button<Client> {
components: [row] components: [row]
}); });
await channel.send({
embeds: [{
...SetSeverity('warning'),
description: 'This ticket has been unclaimed.'
}],
});
await interaction.editReply({ content: 'Ticket unclaimed.' }); await interaction.editReply({ content: 'Ticket unclaimed.' });
} catch (error: Error | any) { } catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {}); await interaction.editReply({ content: error.message }).catch(() => {});
+42
View File
@@ -0,0 +1,42 @@
import { ActionRowBuilder, ApplicationIntegrationType, ButtonBuilder, ButtonStyle, ChatInputCommandInteraction, Client, InteractionContextType, MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
export default {
name: 'devwatch',
data: new SlashCommandBuilder()
.setName('devwatch')
.setDescription('Sends a dev watch role toggle button.')
.setIntegrationTypes(ApplicationIntegrationType.GuildInstall)
.setContexts(InteractionContextType.Guild)
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.addStringOption(option =>
option
.setName('content')
.setDescription('The content of the message.')
.setRequired(false)
)
.addStringOption(option =>
option
.setName('button-label')
.setDescription('The button label.')
.setRequired(false)
),
handler: async function (client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.channel || !interaction.channel.isSendable())
return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Missing permissions to send to channel.' });
const content = interaction.options.getString('content') ?? '';
const label = interaction.options.getString('button-label') ?? 'Toggle DevWatch Role';
const button = new ButtonBuilder()
.setCustomId('dev-watch')
.setStyle(ButtonStyle.Primary)
.setLabel(label);
const row = new ActionRowBuilder<ButtonBuilder>()
.addComponents(button);
await interaction.channel.send({ components: [row], content });
interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Sent.' });
}
};
+31 -66
View File
@@ -1,61 +1,6 @@
import { ApplicationIntegrationType, ChatInputCommandInteraction, Client, InteractionContextType, MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { ApplicationIntegrationType, ChatInputCommandInteraction, Client, InteractionContextType, MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { Database } from '../shared/Database'; import { Database } from '../shared/Database';
import { getIdFromInput, SetSeverity } from '../utils'; import { getIdFromInput } from '../utils';
const userRegex = new RegExp(/^\d{16,20}$/);
async function addUserMapping(interaction: ChatInputCommandInteraction) {
const githubUsername = interaction.options.getString('github-name', true);
const discordId = getIdFromInput(interaction.options.getString('discord-user', true));
if (!userRegex.test(discordId)) throw new Error('The provided Discord user ID is invalid.');
const existingMappingId = await Database.getGithubFromDiscordId(discordId);
const existingMappingName = await Database.getDiscordIdFromGithub(githubUsername);
if (existingMappingId) throw new Error(`<@${discordId}> (${discordId}) is already mapped to \`${existingMappingId}\``);
if (existingMappingName) throw new Error(`\`${githubUsername}\` is already mapped to <@${existingMappingName}> (${existingMappingName})`);
await Database.putGithubUserMapping(discordId, githubUsername);
await interaction.editReply({
embeds: [{
...SetSeverity('success'),
title: 'GitHub/Discord Mapping | Add',
description: `\`${githubUsername}\` has been linked to <@${discordId}>`,
}],
});
}
async function removeUserMapping(interaction: ChatInputCommandInteraction) {
const discordId = getIdFromInput(interaction.options.getString('discord-user', true));
if (!userRegex.test(discordId)) throw new Error('The provided Discord user ID is invalid.');
if (!await Database.removeGithubUserMapping(discordId)) throw new Error('No existing GitHub mapping was found.');
await interaction.editReply({
embeds: [{
...SetSeverity('success'),
title: 'GitHub/Discord Mapping | Remove',
description: `<@${discordId}> is no longer linked.`,
}],
});
}
async function listUserMapping(interaction: ChatInputCommandInteraction) {
const allMappings = await Database.getAllGithubUserMappings();
if (allMappings.length < 1) throw new Error('No GitHub mappings have been configured.');
await interaction.editReply({
embeds: [{
...SetSeverity('success'),
title: 'GitHub/Discord Mapping | List',
description: allMappings.map(m => `- <@${m.discord_id}> (${m.discord_id}) - ${m.github_username}`).join('\n'),
}]
});
}
export default { export default {
name: 'github-mapping', name: 'github-mapping',
@@ -99,17 +44,37 @@ export default {
.setDescription('List all github-discord mappings.') .setDescription('List all github-discord mappings.')
), ),
handler: async function (client: Client, interaction: ChatInputCommandInteraction) { handler: async function (client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.inGuild()) return; await interaction.deferReply({ flags: [MessageFlags.Ephemeral] });
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
try { const subcommand = await interaction.options.getSubcommand(true);
switch (interaction.options.getSubcommand(true)) {
case 'add': return await addUserMapping(interaction); if (subcommand == 'add') {
case 'remove': return await removeUserMapping(interaction); const discordUserInput = interaction.options.getString('discord-user', true);
case 'list': return await listUserMapping(interaction);
} const idToUse = getIdFromInput(discordUserInput);
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {}); const githubName = interaction.options.getString('github-name', true);
const existingMappingId = await Database.getGithubFromDiscordId(idToUse);
const existingMappingName = await Database.getDiscordIdFromGithub(githubName);
if (existingMappingId) return interaction.editReply(`Discord user id is already mapped to ${existingMappingId}`);
if (existingMappingName) return interaction.editReply(`Github username is already mapped to <@${existingMappingName}> (${existingMappingName})`);
Database.putGithubUserMapping(idToUse, githubName);
return interaction.editReply('Mapping added.');
} else if (subcommand == 'remove') {
const discordUserInput = interaction.options.getString('discord-user', true);
const idToUse = getIdFromInput(discordUserInput);
Database.removeGithubUserMapping(idToUse);
return interaction.editReply('Mapping removed.');
} else if (subcommand == 'list') {
const allMappings = await Database.getAllGithubUserMappings();
return interaction.editReply(allMappings.map(m => `- <@${m.discord_id}> (${m.discord_id}) - ${m.github_username}`).join('\n'));
} }
} }
}; };
+12 -1
View File
@@ -75,7 +75,12 @@ export default {
.setDescription('Set the private helper role.') .setDescription('Set the private helper role.')
.setRequired(false) .setRequired(false)
) )
.addRoleOption(option =>
option
.setName('devwatch-role')
.setDescription('Set the DevWatch role.')
.setRequired(false)
)
.addChannelOption(option => .addChannelOption(option =>
option option
.setName('add-staff-category') .setName('add-staff-category')
@@ -199,6 +204,12 @@ export default {
response.push(`**private_help_role_id** has been set to: ${privateHelperRole}.`); response.push(`**private_help_role_id** has been set to: ${privateHelperRole}.`);
} }
const devWatchRole = interaction.options.getRole('devwatch-role');
if (devWatchRole) {
await Database.updateSettings(interaction.guildId, 'devwatch_role_id', devWatchRole.id);
response.push(`**devwatch_role_id** has been set to ${devWatchRole}.`);
}
const addCategory = interaction.options.getChannel('add-staff-category'); const addCategory = interaction.options.getChannel('add-staff-category');
if (addCategory) { if (addCategory) {
if (addCategory.type == ChannelType.GuildCategory) { if (addCategory.type == ChannelType.GuildCategory) {
+16 -4
View File
@@ -1,4 +1,5 @@
import { ApplicationCommandType, ApplicationIntegrationType, CheckboxBuilder, Client, ContextMenuCommandBuilder, InteractionContextType, LabelBuilder, MessageContextMenuCommandInteraction, MessageFlags, ModalBuilder, TextInputBuilder, TextInputStyle } from 'discord.js'; import { ApplicationCommandType, ApplicationIntegrationType, Client, ContextMenuCommandBuilder, InteractionContextType, LabelBuilder, MessageContextMenuCommandInteraction, MessageFlags, ModalBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';
import { Database } from '../shared/Database'; import { Database } from '../shared/Database';
export default { export default {
@@ -27,13 +28,24 @@ export default {
.setDescription('Any additional information? This will help staff understand your report. 1000 characters maximum.') .setDescription('Any additional information? This will help staff understand your report. 1000 characters maximum.')
.setTextInputComponent(additionalInfoInput); .setTextInputComponent(additionalInfoInput);
const createTicketCheckbox = new CheckboxBuilder() const yesNoMenu = new StringSelectMenuBuilder()
.setCustomId('create-private-help-ticket'); .setCustomId('create-private-help-ticket')
.setRequired(false)
.addOptions(
new StringSelectMenuOptionBuilder()
.setLabel('No')
.setDefault(true)
.setValue('no'),
new StringSelectMenuOptionBuilder()
.setLabel('Yes')
.setDefault(false)
.setValue('yes')
);
const createPrivateTicket = new LabelBuilder() const createPrivateTicket = new LabelBuilder()
.setLabel('Create Private Help Ticket') .setLabel('Create Private Help Ticket')
.setDescription('Should a private help ticket be opened with this report? (Does not bypass ticket restrictions)') .setDescription('Should a private help ticket be opened with this report? (Does not bypass ticket restrictions)')
.setCheckboxComponent(createTicketCheckbox); .setStringSelectMenuComponent(yesNoMenu);
modal.addLabelComponents(additionalInfoLabel, createPrivateTicket); modal.addLabelComponents(additionalInfoLabel, createPrivateTicket);
-6
View File
@@ -1,5 +1,4 @@
import { Client, Guild } from 'discord.js'; import { Client, Guild } from 'discord.js';
import { config } from '../../config';
import { Database } from '../../shared/Database'; import { Database } from '../../shared/Database';
import { Event } from '../../types'; import { Event } from '../../types';
@@ -7,11 +6,6 @@ class GuildCreateEvent implements Event<Client, 'guildCreate'> {
event = 'guildCreate' as const; event = 'guildCreate' as const;
async execute(context: Client<boolean>, guild: Guild): Promise<void> { async execute(context: Client<boolean>, guild: Guild): Promise<void> {
if (guild.id != config.DISCORD_GUILD_ID) {
await guild.leave();
return;
}
await Database.getOrCreateSettings(guild.id); await Database.getOrCreateSettings(guild.id);
} }
} }
+8 -11
View File
@@ -1,8 +1,7 @@
import { ButtonInteraction, Client, GatewayIntentBits, MessageFlags, ModalSubmitInteraction, Partials } from 'discord.js'; import { ButtonInteraction, Client, GatewayIntentBits, MessageFlags, Partials } from 'discord.js';
import buttons from './buttons'; import buttons from './buttons';
import { config } from './config'; import { config } from './config';
import events from './events'; import events from './events';
import modals from './modals';
import { Database } from './shared/Database'; import { Database } from './shared/Database';
import { openRedisClient } from './shared/RedisClient'; import { openRedisClient } from './shared/RedisClient';
import { Handler } from './types'; import { Handler } from './types';
@@ -39,6 +38,7 @@ const client = new Client({
const commands: Handler[] = []; const commands: Handler[] = [];
const contextMenus: Handler[] = []; const contextMenus: Handler[] = [];
const modals: Handler[] = [];
const menus: Handler[] = []; const menus: Handler[] = [];
// Due to their reliance on each other, these two events (interactionCreate, and ready) have to stay here. // Due to their reliance on each other, these two events (interactionCreate, and ready) have to stay here.
@@ -104,11 +104,10 @@ client.on('interactionCreate', async (interaction) => {
const id = interaction.customId.split('_')[0]; const id = interaction.customId.split('_')[0];
for (const modal of modals) { for (const modal of modals) {
if (id != modal.id) continue; if (id == modal.name) {
modal.handler(client, interaction, ...interaction.customId.split('_').slice(1));
Promise.resolve((modal.execute as (context: Client, interaction: ModalSubmitInteraction, ...args: unknown[]) => Promise<void>)(client, interaction, ...interaction.customId.split('_').slice(1)) return;
.catch(e => console.error('An error occurred while handling a modal interaction: ', e))); }
return;
} }
} else if (interaction.isAnySelectMenu()) { } else if (interaction.isAnySelectMenu()) {
// Handle menu selections. // Handle menu selections.
@@ -126,17 +125,15 @@ client.on('interactionCreate', async (interaction) => {
client.on('clientReady', async () => { client.on('clientReady', async () => {
console.log(`Logged in as ${client.user!.tag}!`); console.log(`Logged in as ${client.user!.tag}!`);
for (const guild of client.guilds.cache.values()) {
if (guild.id != config.DISCORD_GUILD_ID) await guild.leave();
}
await loadHandlersFrom('commands', commands); await loadHandlersFrom('commands', commands);
await loadHandlersFrom('context-menus', contextMenus); await loadHandlersFrom('context-menus', contextMenus);
await loadHandlersFrom('modals', modals);
await loadHandlersFrom('menus', menus); await loadHandlersFrom('menus', menus);
await refreshCommands(client); await refreshCommands(client);
await initIfNecessary(client, commands); await initIfNecessary(client, commands);
await initIfNecessary(client, modals);
await initIfNecessary(client, menus); await initIfNecessary(client, menus);
Encrypter.initialize(config.DATABASE_SECRET!); Encrypter.initialize(config.DATABASE_SECRET!);
@@ -0,0 +1,49 @@
import { Client, MessageFlags, ModalSubmitInteraction } from 'discord.js';
import { Database } from '../shared/Database';
import { deferInteraction, logCustomEvent } from '../utils';
export default {
name: 'add-knowledgebase-item-modal',
handler: async function (client: Client, interaction: ModalSubmitInteraction) {
if (!interaction.guild) return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Must be ran in guild.' });
await deferInteraction(interaction);
const name = interaction.fields.getTextInputValue('name');
const content = interaction.fields.getTextInputValue('content');
if (content.length > 2000) return interaction.editReply('Content cannot be over 2000 characters long.');
const existingItem = await Database.getFromKnowledgebaseByName(interaction.guild.id, name);
if (existingItem) return interaction.editReply(`Knowledgebase item ${name} already exists!`);
logCustomEvent(interaction.guild!, {
title: 'Knowledgebase Item Added',
description: null,
color: 0x00FF00,
timestamp: new Date(),
fields: [
{
name: 'User',
value: `<@${interaction.user.id}>\n${interaction.user.username}`,
inline: true
},
{
name: 'Name',
value: name,
inline: true
},
{
name: 'Content',
value: content,
inline: true
}
]
});
await Database.addToKnowledgebase(interaction.guild.id, name, content);
return interaction.editReply(`Entry \`${name}\` added to knowledgebase.`);
}
};
+40
View File
@@ -0,0 +1,40 @@
import { Client, MessageFlags, ModalSubmitInteraction } from 'discord.js';
import { Database } from '../shared/Database';
import { logCustomEvent } from '../utils';
export default {
name: 'add-note-modal',
handler: async function (client: Client, interaction: ModalSubmitInteraction, id: string) {
const message = interaction.fields.getTextInputValue('note-message');
const user = await client.users.fetch(id);
logCustomEvent(interaction.guild!, {
title: 'Note Added',
description: null,
color: 0x00FF00,
timestamp: new Date(),
fields: [
{
name: 'Moderator',
value: `<@${interaction.user.id}>\n${interaction.user.username}`,
inline: true
},
{
name: 'User',
value: `<@${id}>\n${user.username}`,
inline: true
},
{
name: 'Note',
value: message,
inline: true
}
]
});
await Database.putNote(id, message, interaction.user.id);
interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Note added' });
}
};
-41
View File
@@ -1,41 +0,0 @@
import { Client, ModalSubmitInteraction } from 'discord.js';
import { Database } from '../shared/Database';
import { Modal } from '../types';
import { deferInteraction, logCustomEvent } from '../utils';
class AddKnowledgebaseItemModal implements Modal<Client> {
id = 'add-knowledgebase-item-modal';
async execute(context: Client<boolean>, interaction: ModalSubmitInteraction): Promise<void> {
if (!interaction.inGuild()) return;
await deferInteraction(interaction);
try {
const name = interaction.fields.getTextInputValue('name');
const content = interaction.fields.getTextInputValue('content');
if (content.length > 2000) throw new Error('Content cannot be longer than 2000 characters.');
const existing = await Database.getFromKnowledgebaseByName(interaction.guildId, name);
if (existing) throw new Error(`A knowledgebase item under \`${name}\` already exists.`);
await logCustomEvent(interaction.guild!, {
title: 'Knowledgebase Item Added',
description: null,
color: 0x00FF00,
timestamp: new Date(),
fields: [
{ name: 'User', value: `${interaction.user} (${interaction.user.id})`, inline: false },
{ name: 'Name', value: name, inline: false },
{ name: 'Content', value: content, inline: false },
],
});
await Database.addToKnowledgebase(interaction.guildId, name, content);
await interaction.editReply({ content: `\`${name}\` has been added to the knowledgebase.` });
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
}
}
export default new AddKnowledgebaseItemModal();
-38
View File
@@ -1,38 +0,0 @@
import { Client, ModalSubmitInteraction } from 'discord.js';
import { Database } from '../shared/Database';
import { deferInteraction, logCustomEvent } from '../utils';
import { Modal } from '../types';
class AddNoteModal implements Modal<Client> {
id = 'add-note-modal';
async execute(context: Client<boolean>, interaction: ModalSubmitInteraction, id: string): Promise<void> {
if (!interaction.inGuild()) return;
await deferInteraction(interaction);
try {
const message = interaction.fields.getTextInputValue('note-message');
const guild = await context.guilds.fetch(interaction.guildId);
const user = await context.users.fetch(id);
await logCustomEvent(guild, {
title: 'Note Added',
description: null,
color: 0x00FF00,
timestamp: new Date(),
fields: [
{ name: 'Moderator', value: `${interaction.user} (${interaction.user.id})`, inline: false },
{ name: 'User', value: `${user.username} (${user.id})`, inline: false },
{ name: 'Note', value: message, inline: false },
],
});
await Database.putNote(id, message, interaction.user.id);
await interaction.editReply({ content: 'Note added.' });
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
}
}
export default new AddNoteModal();
@@ -0,0 +1,54 @@
import { Client, MessageFlags, ModalSubmitInteraction } from 'discord.js';
import { Database } from '../shared/Database';
import { deferInteraction, logCustomEvent } from '../utils';
export default {
name: 'edit-knowledgebase-item-modal',
handler: async function (client: Client, interaction: ModalSubmitInteraction, idString: string) {
if (!interaction.guild) return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Must be ran in guild.' });
await deferInteraction(interaction);
const id = parseInt(idString);
const content = interaction.fields.getTextInputValue('content');
const existingItem = await Database.getFromKnowledgebase(id);
if (!existingItem) return interaction.editReply('Knowledgebase item not found.');
if (content.length > 2000) return interaction.editReply('Content cannot be over 2000 characters long.');
logCustomEvent(interaction.guild!, {
title: 'Knowledgebase Item Edited',
description: null,
color: 0xFFFF00,
timestamp: new Date(),
fields: [
{
name: 'User',
value: `<@${interaction.user.id}>\n${interaction.user.username}`,
inline: true
},
{
name: 'Name',
value: existingItem.name,
inline: true
},
{
name: 'Old Content',
value: existingItem.content,
inline: true
},
{
name: 'New Content',
value: content,
inline: true
}
]
});
await Database.editKnowledgebaseItem(id, content);
return interaction.editReply(`Edited knowledgebase entry \`${existingItem.name}\`.`);
}
};
-43
View File
@@ -1,43 +0,0 @@
import { Client, ModalSubmitInteraction } from 'discord.js';
import { Database } from '../shared/Database';
import { deferInteraction, logCustomEvent } from '../utils';
import { Modal } from '../types';
class EditKnowledgebaseItemModal implements Modal<Client> {
id = 'edit-knowledgebase-item-modal';
async execute(context: Client<boolean>, interaction: ModalSubmitInteraction, idString: string): Promise<void> {
if (!interaction.inGuild()) return;
await deferInteraction(interaction);
try {
const id = parseInt(idString);
const existing = await Database.getFromKnowledgebase(id);
if (!existing) throw new Error("A knowledgebase item with that ID doesn't exist.");
const content = interaction.fields.getTextInputValue('content');
if (content.length > 2000) throw new Error('Content cannot be longer than 2000 characters.');
const guild = await context.guilds.fetch(interaction.guildId);
await logCustomEvent(guild, {
title: 'Knowledgebase Item Edited',
description: null,
color: 0xFFFF00,
timestamp: new Date(),
fields: [
{ name: 'User', value: `${interaction.user} (${interaction.user.id})`, inline: false },
{ name: 'Name', value: existing.name, inline: false },
{ name: 'Old Content', value: existing.content, inline: false },
{ name: 'New Content', value: content, inline: false },
],
});
await Database.editKnowledgebaseItem(id, content);
await interaction.editReply({ content: `\`${existing.name}\` has been edited.` });
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
}
}
export default new EditKnowledgebaseItemModal();
-17
View File
@@ -1,17 +0,0 @@
import addKnowledgebaseItemModal from './addKnowledgebaseItemModal';
import addNoteModal from './addNoteModal';
import editKnowledgebaseItemModal from './editKnowledgebaseItemModal';
import openModTicket from './openModTicket';
import openTicketModal from './openTicketModal';
import reportMessage from './reportMessage';
import syncNameModal from './syncNameModal';
export default [
addKnowledgebaseItemModal,
addNoteModal,
editKnowledgebaseItemModal,
openModTicket,
openTicketModal,
reportMessage,
syncNameModal
];
+31
View File
@@ -0,0 +1,31 @@
import { Client, MessageFlags, ModalSubmitInteraction } from 'discord.js';
import { Database } from '../shared/Database';
import { createPrivateHelpTicketThread } from '../utils';
const warning = '\n\n\nLeaving this thread without acknowledgement may result in punishment. Staff will close the thread when they deem your response acceptable.';
export default {
name: 'open-mod-ticket',
handler: async function (client: Client, interaction: ModalSubmitInteraction, userId: string) {
const guild = await client.guilds.fetch(interaction.guildId!);
const member = await guild.members.fetch(userId);
const guildSettings = await Database.getOrCreateSettings(guild.id);
if (!guildSettings || !guildSettings.private_help_channel_id)
return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Failed to create ticket. Please report this to a developer.' });
const title = interaction.fields.getTextInputValue('title') ? interaction.fields.getTextInputValue('title') : `Mod Ticket For ${member.displayName}`;
const reason = interaction.fields.getTextInputValue('initial-message') + warning;
const autoJoin = interaction.fields.getStringSelectValues('auto-join-thread')[0] == 'yes';
const membersToAdd = [userId];
if (autoJoin) membersToAdd.push(interaction.user.id);
const thread = await createPrivateHelpTicketThread(client, guild, null, reason, title, membersToAdd);
if (thread) interaction.reply({ flags: [MessageFlags.Ephemeral], content: `Mod ticket created: ${thread}.${!autoJoin ? "You've selected not to auto join the thread. You will not be notified of messages sent there. You will have to check the thread periodically for user response." : ''}` });
else interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Failed to create ticket. Please report this to a developer.' });
}
};
+23
View File
@@ -0,0 +1,23 @@
import { Client, MessageFlags, ModalSubmitInteraction } from 'discord.js';
import { Database } from '../shared/Database';
import { createPrivateHelpTicketThread } from '../utils';
export default {
name: 'open-ticket-modal',
handler: async function (client: Client, interaction: ModalSubmitInteraction) {
const guild = await client.guilds.fetch(interaction.guildId!);
const member = await guild.members.fetch(interaction.user.id);
const guildSettings = await Database.getOrCreateSettings(guild.id);
if (!guildSettings || !guildSettings.private_help_role_id)
return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Failed to create ticket. Please report this to a staff member.' });
const reason = interaction.fields.getTextInputValue('ticket-message');
const thread = await createPrivateHelpTicketThread(client, guild, member, reason);
if (thread) interaction.reply({ flags: [MessageFlags.Ephemeral], content: `Your ticket has been created: ${thread}` });
else interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Failed to create ticket. Please report this to a staff member.' });
}
};
-39
View File
@@ -1,39 +0,0 @@
import { Client, MessageFlags, ModalSubmitInteraction } from 'discord.js';
import { Database } from '../shared/Database';
import { Modal } from '../types';
import { createPrivateHelpTicketThread } from '../utils';
const warning = '\n\n\nLeaving this thread without acknowledgement may result in punishment. Staff will close the thread when they deem your response acceptable.';
class OpenModTicketModal implements Modal<Client> {
id = 'open-mod-ticket';
async execute(context: Client<boolean>, interaction: ModalSubmitInteraction, userId: string): Promise<void> {
if (!interaction.inGuild()) return;
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
try {
const settings = await Database.getOrCreateSettings(interaction.guildId);
if (!settings.private_help_channel_id) throw new Error("`private_help_channel_id` hasn't been configured. Please report this error to staff.");
const guild = await context.guilds.fetch(interaction.guildId);
const member = await guild.members.fetch(userId);
const title = interaction.fields.getTextInputValue('title') ? interaction.fields.getTextInputValue('title') : `Mod Ticket For ${member.displayName}`;
const reason = interaction.fields.getTextInputValue('initial-message') + warning;
const autoJoin = interaction.fields.getCheckbox('auto-join-thread');
const membersToAdd = [userId];
if (autoJoin) membersToAdd.push(interaction.user.id);
const thread = await createPrivateHelpTicketThread(context, guild, null, reason, title, membersToAdd);
if (!thread) throw new Error('Failed to create a ticket thread. Please report this to a developer.');
await interaction.editReply({ content: `Mod ticket created: ${thread}. ${!autoJoin ? "You've selected not to auto join the thread. You will not be notified of messages sent there. You will have to check the thread periodically for user response." : ''}` });
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
}
}
export default new OpenModTicketModal();
-31
View File
@@ -1,31 +0,0 @@
import { Client, MessageFlags, ModalSubmitInteraction } from 'discord.js';
import { Database } from '../shared/Database';
import { Modal } from '../types';
import { createPrivateHelpTicketThread } from '../utils';
class OpenTicketModal implements Modal<Client> {
id = 'open-ticket-modal';
async execute(context: Client<boolean>, interaction: ModalSubmitInteraction): Promise<void> {
if (!interaction.inGuild()) return;
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
try {
const guild = await context.guilds.fetch(interaction.guildId);
const member = await guild.members.fetch(interaction.user.id);
const settings = await Database.getOrCreateSettings(interaction.guildId);
if (!settings.private_help_role_id) throw new Error("`private_help_role_id` hasn't been configured. Please report this error to staff.");
const reason = interaction.fields.getTextInputValue('ticket-message');
const thread = await createPrivateHelpTicketThread(context, guild, member, reason);
if (!thread) throw new Error('Failed to create ticket. Please report this to a staff member.');
await interaction.editReply({ content: `Your ticket has been created: ${thread}` });
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
}
}
export default new OpenTicketModal();
+118
View File
@@ -0,0 +1,118 @@
import { ActionRowBuilder, AttachmentBuilder, ButtonBuilder, ButtonStyle, Client, EmbedBuilder, GuildTextBasedChannel, MessageFlags, ModalSubmitInteraction } from 'discord.js';
import { Database } from '../shared/Database';
import { canOpenPrivateHelpTicket, createPrivateHelpTicketThread } from '../utils';
export default {
name: 'report-message',
handler: async function (client: Client, interaction: ModalSubmitInteraction, channelId: string, messageId: string) {
await interaction.deferReply({ flags: [MessageFlags.Ephemeral] });
const guild = await client.guilds.fetch(interaction.guildId!);
const member = await guild.members.fetch(interaction.user.id);
const reportedMessageChannel = await guild.channels.fetch(channelId) as GuildTextBasedChannel;
const reportedMessage = await reportedMessageChannel?.messages.fetch(messageId);
const additionalInfo = interaction.fields.getTextInputValue('additional-info');
const createPrivateHelpTicket = interaction.fields.getStringSelectValues('create-private-help-ticket')[0] == 'yes';
if (!reportedMessageChannel || !reportedMessage)
return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Failed to submit report. Please report this to a staff member.' });
const guildSettings = await Database.getOrCreateSettings(interaction.guildId!);
if (!guildSettings || !guildSettings.moderator_channel_id)
return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Report channel missing. Unable to submit report.' });
const reportsChannel = await interaction.guild!.channels.fetch(guildSettings.moderator_channel_id);
if (!reportsChannel || !reportsChannel.isSendable())
return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Report channel missing. Unable to submit report.' });
const embed = new EmbedBuilder()
.setTitle('New Message Report!')
.setColor(0xFF0000)
.addFields(
{
name: 'Message',
value: reportedMessage.url,
inline: false
},
{
name: 'Message Author',
value: reportedMessage.author.toString(),
inline: false
},
{
name: 'Reporter',
value: member.toString(),
inline: false
});
if (additionalInfo) {
embed.addFields(
{
name: 'Additional Information',
value: additionalInfo,
inline: false
}
);
}
let replyContent = "Thanks for making a report! I've notified the moderators who can take further action.";
const wantsTicketButCantOpen = createPrivateHelpTicket && !await canOpenPrivateHelpTicket(member.id);
if (wantsTicketButCantOpen) {
embed.addFields(
{
name: 'User Requested Private Ticket',
value: 'The user requested a private ticket be opened, but already has an open ticket. If additional information is needed, press the button below to open a ticket with the user.',
inline: false
}
);
replyContent += " Could not open private help ticket since you already have one open. Staff have been notified that you'd like to have a ticket opened, and can make one for you if they deem it necessary.";
}
const openTicketButton = new ButtonBuilder()
.setCustomId('open-ticket-for-reported-message')
.setLabel('Open Private Ticket')
.setStyle(ButtonStyle.Primary);
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(openTicketButton);
const reportMessage = await reportsChannel.send({
embeds: [embed],
components: createPrivateHelpTicket && !wantsTicketButCantOpen ? [] : [row]
});
await reportsChannel.send({ files: [new AttachmentBuilder(Buffer.from(reportedMessage.content), { name: 'message-content.txt' })] });
if (createPrivateHelpTicket && !wantsTicketButCantOpen) {
if (!guildSettings.private_help_channel_id) {
replyContent += ' Could not open private help ticket. Private help channel not set. Please report this to a staff member.';
} else {
const thread = await createPrivateHelpTicketThread(client, guild, member, `Ticket created with message report (${reportMessage.url}). ${member}, use this channel to talk with staff privately about the reported message (${reportedMessage.url}). ${additionalInfo ? `\n\nAdditional information provided in report:\n${additionalInfo.split('\n').map(c => `> ${c}`).join('\n')}` : ''}`);
if (thread) {
replyContent += ` Private help ticket created: ${thread}.`;
embed.addFields({
name: 'Private Help Ticket',
value: thread.url,
inline: false
});
await reportMessage.edit({ embeds: [embed] });
} else {
replyContent += ' There was an issue opening a private help ticket, please report this to a staff member.';
await reportMessage.edit({
embeds: [embed],
components: [row]
});
}
}
}
await interaction.editReply(replyContent);
}
};
-96
View File
@@ -1,96 +0,0 @@
import { ActionRowBuilder, AttachmentBuilder, ButtonBuilder, ButtonStyle, Client, EmbedBuilder, GuildTextBasedChannel, MessageFlags, ModalSubmitInteraction } from 'discord.js';
import { Database } from '../shared/Database';
import { Modal } from '../types';
import { canOpenPrivateHelpTicket, createPrivateHelpTicketThread } from '../utils';
class ReportMessageModal implements Modal<Client> {
id = 'report-message';
async execute(context: Client<boolean>, interaction: ModalSubmitInteraction, channelId: string, messageId: string): Promise<void> {
if (!interaction.inGuild()) return;
await interaction.deferReply({ flags: [MessageFlags.Ephemeral] });
try {
const guild = await context.guilds.fetch(interaction.guildId);
const member = await guild.members.fetch(interaction.user.id);
const reportedMessageChannel = await guild.channels.fetch(channelId) as GuildTextBasedChannel;
const reportedMessage = await reportedMessageChannel?.messages.fetch(messageId);
const additionalInfo = interaction.fields.getTextInputValue('additional-info');
const createPrivateHelpTicket = interaction.fields.getCheckbox('create-private-help-ticket');
if (!reportedMessageChannel || !reportedMessage) throw new Error('Failed to submit report. Please report this to a staff member.');
const settings = await Database.getOrCreateSettings(interaction.guildId);
if (!settings.moderator_channel_id) throw new Error('Report channel missing. Unable to submit report.');
const reportsChannel = await interaction.guild!.channels.fetch(settings.moderator_channel_id);
if (!reportsChannel || !reportsChannel.isSendable()) throw new Error('Report channel missing. Unable to submit report.');
const embed = new EmbedBuilder()
.setTitle('New Message Report!')
.setColor(0xFF0000)
.addFields(
{ name: 'Message', value: reportedMessage.url, inline: false },
{ name: 'Author', value: reportedMessage.author.toString(), inline: false },
{ name: 'Reporter', value: member.toString(), inline: false }
);
if (additionalInfo) embed.addFields({ name: 'Additional Information', value: additionalInfo, inline: false });
let replyContent = "Thanks for making a report! I've notified the moderators who can take further action.";
const wantsTicketButCantOpen = createPrivateHelpTicket && !await canOpenPrivateHelpTicket(member.id);
if (wantsTicketButCantOpen) {
embed.addFields({
name: 'User Requested Private Ticket',
value: 'The user requested a private ticket be opened, but already has an open ticket. If additional information is needed, press the button below to open a ticket with the user.',
inline: false
});
replyContent += " Could not open private help ticket since you already have one open. Staff have been notified that you'd like to have a ticket opened, and can make one for you if they deem it necessary.";
}
const openTicketButton = new ButtonBuilder()
.setCustomId('open-ticket-for-reported-message')
.setLabel('Open Private Ticket')
.setStyle(ButtonStyle.Primary);
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(openTicketButton);
const reportMessage = await reportsChannel.send({
embeds: [embed],
components: createPrivateHelpTicket && !wantsTicketButCantOpen ? [] : [row]
});
await reportsChannel.send({ files: [new AttachmentBuilder(Buffer.from(reportedMessage.content), { name: 'message-content.txt' })] });
if (createPrivateHelpTicket && !wantsTicketButCantOpen) {
if (!settings.private_help_channel_id) {
replyContent += ' Could not open private help ticket. Private help channel not set. Please report this to a staff member.';
} else {
const thread = await createPrivateHelpTicketThread(context, guild, member, `Ticket created with message report (${reportMessage.url}). ${member}, use this channel to talk with staff privately about the reported message (${reportedMessage.url}). ${additionalInfo ? `\n\nAdditional information provided in report:\n${additionalInfo.split('\n').map(c => `> ${c}`).join('\n')}` : ''}`);
if (thread) {
replyContent += ` Private help ticket created: ${thread}.`;
embed.addFields({ name: 'Private Help Ticket', value: thread.url, inline: false });
await reportMessage.edit({ embeds: [embed] });
} else {
replyContent += ' There was an issue opening a private help ticket, please report this to a staff member.';
await reportMessage.edit({
embeds: [embed],
components: [row]
});
}
}
}
await interaction.editReply(replyContent);
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
}
}
export default new ReportMessageModal();
+32
View File
@@ -0,0 +1,32 @@
import { Client, ModalSubmitInteraction } from 'discord.js';
import { config } from '../config';
import { deferInteraction, syncName } from '../utils';
export default {
name: 'sync-name-modal',
handler: async function (client: Client, interaction: ModalSubmitInteraction, id: string) {
await deferInteraction(interaction);
const e621Id = Number(interaction.fields.getTextInputValue('id') ?? 0);
if (isNaN(e621Id)) return await interaction.editReply('Provided id is not a number');
const member = await interaction.guild?.members.fetch(id);
if (!member) {
return interaction.editReply('An error has occurred. Please try again later.');
}
const guild = await interaction.client.guilds.fetch(config.DISCORD_GUILD_ID!);
if (!guild) {
return interaction.editReply('An error has occurred. Please try again later.');
}
if (!guild.members.me) {
return interaction.editReply('An error has occurred. Please try again later.');
}
await syncName(interaction, member, e621Id);
}
};
-27
View File
@@ -1,27 +0,0 @@
import { Client, ModalSubmitInteraction } from 'discord.js';
import { Modal } from '../types';
import { deferInteraction, syncName } from '../utils';
class SyncNameModal implements Modal<Client> {
id = 'sync-name-modal';
async execute(context: Client<boolean>, interaction: ModalSubmitInteraction, id: string): Promise<void> {
if (!interaction.inGuild()) return;
await deferInteraction(interaction);
try {
const e621Id = Number(interaction.fields.getTextInputValue('id') ?? 0);
if (isNaN(e621Id)) throw new Error('Provided id is not a number.');
const guild = await context.guilds.fetch(interaction.guildId);
const member = await guild.members.fetch(id);
if (!member) throw new Error('Unable to fetch the target member.');
await syncName(interaction, member, e621Id);
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
}
}
export default new SyncNameModal();
+2 -3
View File
@@ -364,9 +364,8 @@ export class Database {
}); });
} }
static async removeGithubUserMapping(discordId: string): Promise<boolean> { static async removeGithubUserMapping(discordId: string) {
const result = await Database.db.run('DELETE FROM github_user_mapping WHERE discord_id_hash = ?', Encrypter.hash(discordId)); await Database.db.run('DELETE from github_user_mapping WHERE discord_id_hash = ?', Encrypter.encrypt(discordId));
return (result.changes ?? 0) > 0;
} }
//#endregion //#endregion
+1
View File
@@ -22,6 +22,7 @@ export type GuildSettings = {
voice_logs_channel_id?: string voice_logs_channel_id?: string
admin_role_id?: string admin_role_id?: string
private_help_role_id?: string private_help_role_id?: string
devwatch_role_id?: string
staff_categories?: string staff_categories?: string
safe_channels?: string safe_channels?: string
link_skip_channels?: string link_skip_channels?: string
-1
View File
@@ -5,5 +5,4 @@ export * from './event.d';
export * from './e621-types.d'; export * from './e621-types.d';
export * from './handler.d'; export * from './handler.d';
export * from './helper-types.d'; export * from './helper-types.d';
export * from './modal.d';
export * from './task.d'; export * from './task.d';
-6
View File
@@ -1,6 +0,0 @@
import { ModalSubmitInteraction } from 'discord.js';
export interface Modal<Context> {
id: string;
execute(context: Context, interaction: ModalSubmitInteraction, ...args: any): Promise<void>;
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { ChatInputCommandInteraction, ContextMenuCommandInteraction, GuildBasedChannel, MessageFlags, ModalSubmitInteraction } from 'discord.js'; import { ChatInputCommandInteraction, ContextMenuCommandInteraction, GuildBasedChannel, MessageFlags, ModalSubmitInteraction } from 'discord.js';
import { channelIsInStaffCategory } from '.'; import { channelIsInStaffCategory } from './channel-utils';
export async function deferInteraction(interaction: ChatInputCommandInteraction | ContextMenuCommandInteraction | ModalSubmitInteraction) { export async function deferInteraction(interaction: ChatInputCommandInteraction | ContextMenuCommandInteraction | ModalSubmitInteraction) {
const isStaffChannel = await channelIsInStaffCategory(interaction.channel as GuildBasedChannel); const isStaffChannel = await channelIsInStaffCategory(interaction.channel as GuildBasedChannel);
+14 -5
View File
@@ -1,4 +1,4 @@
import { CheckboxBuilder, LabelBuilder, TextInputBuilder, TextInputStyle } from 'discord.js'; import { LabelBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';
export function createTextInput(customId: string, labelTitle: string, description: string | null, required: boolean, style: TextInputStyle, maxLength: number | null, minLength: number | null): LabelBuilder { export function createTextInput(customId: string, labelTitle: string, description: string | null, required: boolean, style: TextInputStyle, maxLength: number | null, minLength: number | null): LabelBuilder {
const input = new TextInputBuilder() const input = new TextInputBuilder()
@@ -19,14 +19,23 @@ export function createTextInput(customId: string, labelTitle: string, descriptio
return label; return label;
} }
export function createCheckbox(customId: string, labelTitle: string, description: string | null, defaultYes: boolean): LabelBuilder { export function createYesNoMenu(customId: string, labelTitle: string, description: string | null, defaultYes: boolean): LabelBuilder {
const component = new CheckboxBuilder() const yesNoMenu = new StringSelectMenuBuilder()
.setCustomId(customId) .setCustomId(customId)
.setDefault(defaultYes); .addOptions(
new StringSelectMenuOptionBuilder()
.setLabel('Yes')
.setDefault(defaultYes)
.setValue('yes'),
new StringSelectMenuOptionBuilder()
.setLabel('No')
.setDefault(!defaultYes)
.setValue('no')
);
const yesNoLabel = new LabelBuilder() const yesNoLabel = new LabelBuilder()
.setLabel(labelTitle) .setLabel(labelTitle)
.setCheckboxComponent(component); .setStringSelectMenuComponent(yesNoMenu);
if (description !== null) yesNoLabel.setDescription(description); if (description !== null) yesNoLabel.setDescription(description);
+3 -2
View File
@@ -1,6 +1,6 @@
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelType, ChatInputCommandInteraction, Client, Guild, GuildMember, ModalBuilder, PrivateThreadChannel, TextChannel, TextInputStyle, ThreadAutoArchiveDuration, ThreadChannel, UserContextMenuCommandInteraction } from 'discord.js'; import { ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelType, ChatInputCommandInteraction, Client, Guild, GuildMember, ModalBuilder, PrivateThreadChannel, TextChannel, TextInputStyle, ThreadAutoArchiveDuration, ThreadChannel, UserContextMenuCommandInteraction } from 'discord.js';
import { Database } from '../shared/Database'; import { Database } from '../shared/Database';
import { CreateDefaultEmbed, createTextInput, createCheckbox, SetSeverity } from '.'; import { CreateDefaultEmbed, createTextInput, createYesNoMenu, SetSeverity } from '.';
export async function closeOldTickets(client: Client) { export async function closeOldTickets(client: Client) {
for (const ticket of await Database.getAllOpenPrivateHelpTickets()) { for (const ticket of await Database.getAllOpenPrivateHelpTickets()) {
@@ -121,8 +121,9 @@ export async function openModTicketModal(interaction: UserContextMenuCommandInte
const titleLabel = createTextInput('title', 'Title', `The name of the thread. Defaults to "Mod Ticket For ${member.displayName}" if left empty`, false, TextInputStyle.Short, 100, null); const titleLabel = createTextInput('title', 'Title', `The name of the thread. Defaults to "Mod Ticket For ${member.displayName}" if left empty`, false, TextInputStyle.Short, 100, null);
const initialMessageLabel = createTextInput('initial-message', 'Inital Message', 'The inital message sent in the thread', false, TextInputStyle.Paragraph, 1800, null); const initialMessageLabel = createTextInput('initial-message', 'Inital Message', 'The inital message sent in the thread', false, TextInputStyle.Paragraph, 1800, null);
const autoJoinLabel = createCheckbox('auto-join-thread', 'Auto Join Thread', 'Whether or not to automatically add you to the thread.', true); const autoJoinLabel = createYesNoMenu('auto-join-thread', 'Auto Join Thread', 'Whether or not to join you to the thread. Selecting no will not notify you of messages sent!', true);
modal.addLabelComponents(titleLabel, initialMessageLabel, autoJoinLabel); modal.addLabelComponents(titleLabel, initialMessageLabel, autoJoinLabel);
interaction.showModal(modal); interaction.showModal(modal);
} }