10 Commits
74 changed files with 1497 additions and 2181 deletions
+8 -4
View File
@@ -1,5 +1,9 @@
node_modules
dist
data/*
# Directories
certs/
data/
dist/
node_modules/
# Files
.DS_Store
.env
certs/*
+23 -948
View File
File diff suppressed because it is too large Load Diff
+6 -7
View File
@@ -1,11 +1,8 @@
{
"name": "discordbot-ng",
"devDependencies": {
"@eslint/js": "9.39.5",
"@stylistic/eslint-plugin": "5.2.1",
"@types/express": "5.0.2",
"@types/express-session": "1.18.1",
"copyfiles": "2.4.1",
"eslint": "9.39.5",
"rimraf": "6.0.1",
@@ -15,12 +12,10 @@
},
"dependencies": {
"@clynamic/dmark": "0.0.11",
"@hono/node-server": "2.1.1",
"@redis/client": "5.1.0",
"body-parser": "2.3.0",
"discord.js": "14.27.0",
"express": "5.1.0",
"express-session": "1.19.0",
"memorystore": "1.6.7",
"hono": "4.13.10",
"sqlite": "5.1.1",
"sqlite3": "6.0.1"
},
@@ -34,5 +29,9 @@
"copyfiles": "copyfiles -u 1 \"./src/**/*.html\" ./dist",
"encrypt": "node --env-file=.env ./scripts/encrypt-data.js",
"add-author-hash": "node --env-file=.env ./scripts/add-author-id-hash.js"
},
"allowScripts": {
"esbuild@0.28.1": true,
"sqlite3@6.0.1": true
}
}
@@ -0,0 +1,9 @@
--------------------------------------------------------------------------------
-- Up
--------------------------------------------------------------------------------
ALTER TABLE settings DROP COLUMN devwatch_role_id;
--------------------------------------------------------------------------------
-- Down
--------------------------------------------------------------------------------
ALTER TABLE settings ADD devwatch_role_id TEXT;
-40
View File
@@ -1,40 +0,0 @@
import { ActionRowBuilder, ButtonBuilder, ButtonInteraction, ButtonStyle, ChannelType, Client, MessageFlags, PermissionFlagsBits } from 'discord.js';
import { Database } from '../shared/Database';
export default {
name: 'claim-ticket',
handler: async function (client: Client, interaction: ButtonInteraction) {
const channel = await interaction.channel?.fetch();
if (!channel || !channel.isThread() || !channel.isSendable() || channel.type != ChannelType.PrivateThread)
return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Oops. Something went wrong.' });
if (!interaction.memberPermissions) return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'An error has occurred.' });
if (!interaction.memberPermissions.has(PermissionFlagsBits.ManageMessages)) return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'You do not have permission to claim tickets.' });
const guild = await client.guilds.fetch(interaction.guildId!);
const settings = await Database.getOrCreateSettings(guild.id);
if (!settings.private_help_role_id) return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Failed to claim ticket.' });
const closeButton = new ButtonBuilder()
.setCustomId('close-ticket')
.setLabel('Click here if you no longer need help')
.setStyle(ButtonStyle.Danger);
const unclaimButton = new ButtonBuilder()
.setCustomId('unclaim-ticket')
.setLabel('Unclaim ticket')
.setStyle(ButtonStyle.Primary);
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(closeButton, unclaimButton);
await interaction.message.edit({
content: `${interaction.message.content}\n\nClaimed by: ${interaction.user}`,
components: [row]
});
await interaction.reply({ content: `Ticket claimed by ${interaction.user}.` });
}
};
+52
View File
@@ -0,0 +1,52 @@
import { ActionRowBuilder, ButtonBuilder, ButtonInteraction, ButtonStyle, ChannelType, Client, MessageFlags, PermissionFlagsBits } from 'discord.js';
import { Button } from '../types';
import { SetSeverity } from '../utils';
class ClaimTicketButton implements Button<Client> {
id = 'claim-ticket';
async execute(context: Client<boolean>, interaction: ButtonInteraction): Promise<void> {
if (!interaction.inGuild()) return;
await interaction.deferReply({ flags: [MessageFlags.Ephemeral] });
try {
const channel = await context.channels.fetch(interaction.channelId);
if (!channel) throw new Error("The interaction channel couldn't be fetched.");
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 (!interaction.memberPermissions.has(PermissionFlagsBits.ManageMessages)) throw new Error("You don't have permission to claim tickets.");
const closeButton = new ButtonBuilder()
.setCustomId('close-ticket')
.setLabel('Click here if you no longer need help')
.setStyle(ButtonStyle.Danger);
const unclaimButton = new ButtonBuilder()
.setCustomId('unclaim-ticket')
.setLabel('Unclaim ticket')
.setStyle(ButtonStyle.Primary);
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(closeButton, unclaimButton);
await interaction.message.edit({
content: `${interaction.message.content}\n\nClaimed by: ${interaction.user}`,
components: [row]
});
await channel.send({
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) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
}
}
export default new ClaimTicketButton();
-31
View File
@@ -1,31 +0,0 @@
import { ButtonInteraction, Client, MessageFlags, ChannelType, PermissionFlagsBits } from 'discord.js';
export default {
name: 'close-mod-ticket',
handler: async function (client: Client, interaction: ButtonInteraction) {
await interaction.deferReply({ flags: [MessageFlags.Ephemeral] });
const channel = await interaction.channel?.fetch();
const guild = await interaction.guild?.fetch();
const member = await guild?.members.fetch(interaction.user.id);
if (!channel || !channel.isThread() || !channel.isSendable() || channel.type != ChannelType.PrivateThread || !member)
return interaction.editReply({ content: 'Oops. Something went wrong. Please report this to a staff member.' });
if (!member.permissions.has(PermissionFlagsBits.KickMembers))
return interaction.editReply({ content: 'Only staff members may close mod tickets.' });
await interaction.message.edit({
content: interaction.message.content,
components: []
});
await channel.send('This ticket has been closed by staff.');
await interaction.editReply({ content: 'Ticket closed.' });
channel.edit({
archived: true,
locked: true
});
}
};
-28
View File
@@ -1,28 +0,0 @@
import { ButtonInteraction, Client, MessageFlags, ChannelType } from 'discord.js';
import { Database } from '../shared/Database';
export default {
name: 'close-ticket',
handler: async function (client: Client, interaction: ButtonInteraction) {
const channel = await interaction.channel?.fetch();
if (!channel || !channel.isThread() || !channel.isSendable() || channel.type != ChannelType.PrivateThread)
return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Oops. Something went wrong. Please report this to a staff member.' });
await interaction.message.edit({
content: interaction.message.content,
components: []
});
await Database.closePrivateHelpTicket(channel.id);
await channel.send(`This ticket has been closed by ${interaction.user}`);
await interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Ticket closed.' });
channel.edit({
archived: true,
locked: true
});
}
};
+38
View File
@@ -0,0 +1,38 @@
import { ButtonInteraction, Client, MessageFlags, ChannelType } from 'discord.js';
import { Button } from '../types';
import { closeTicket } from '../utils';
class CloseModTicketButton implements Button<Client> {
id = 'close-mod-ticket';
async execute(context: Client<boolean>, interaction: ButtonInteraction): Promise<void> {
if (!interaction.inGuild()) return;
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
try {
const channel = await context.channels.fetch(interaction.channelId);
if (!channel) throw new Error("The interaction channel couldn't be fetched.");
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 (!interaction.memberPermissions.has('KickMembers')) throw new Error("You don't have permission to close this ticket.");
await interaction.message.edit({
content: interaction.message.content,
components: []
});
if (!await closeTicket(context, channel, 'This ticket has been closed by staff.')) {
await interaction.editReply({ content: 'An error occurred while trying to close this ticket.' });
return;
}
await interaction.editReply({ content: 'Ticket closed.' });
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
}
}
export default new CloseModTicketButton();
+38
View File
@@ -0,0 +1,38 @@
import { ButtonInteraction, Client, MessageFlags, ChannelType } from 'discord.js';
import { Button } from '../types';
import { closeTicket } from '../utils';
class CloseTicketButton implements Button<Client> {
id = 'close-ticket';
async execute(context: Client<boolean>, interaction: ButtonInteraction): Promise<void> {
if (!interaction.inGuild()) return;
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
try {
const channel = await context.channels.fetch(interaction.channelId);
if (!channel) throw new Error("The interaction channel couldn't be fetched.");
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.");
await interaction.editReply({ content: 'Closing, please wait...' });
await interaction.message.edit({
content: interaction.message.content,
components: []
});
if (!await closeTicket(context, channel, `This ticket has been closed by ${interaction.user}`)) {
await interaction.editReply({ content: 'An error occurred while trying to close this ticket.' });
return;
}
await interaction.editReply({ content: 'Ticket closed.' });
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
}
}
export default new CloseTicketButton();
-32
View File
@@ -1,32 +0,0 @@
import { ButtonInteraction, Client, MessageFlags } from 'discord.js';
import { Database } from '../shared/Database';
export default {
name: 'dev-watch',
handler: async function (client: Client, interaction: ButtonInteraction) {
try {
if (!interaction.guild) throw new Error('This action must be run in a guild.');
const settings = await Database.getOrCreateSettings(interaction.guild.id);
if (!settings.devwatch_role_id) throw new Error('`devwatch_role_id` was not configured. Please configure a role then try again.');
const member = await interaction.guild.members.fetch(interaction.user.id);
if (!member) throw new Error('Unable to retreive the member executing this command.');
const bot = await interaction.guild.members.fetchMe();
const role = await interaction.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.reply({ flags: [MessageFlags.Ephemeral], content: 'Removed role.' });
} else {
await member.roles.add(settings.devwatch_role_id);
await interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Added role.' });
}
} catch (error: Error | any) {
await interaction.reply({ flags: [MessageFlags.Ephemeral], content: error.message });
}
}
};
+21
View File
@@ -0,0 +1,21 @@
import { ButtonInteraction, Client, MessageFlags } from 'discord.js';
import { Button } from '../types';
import { SetSeverity } from '../utils';
class DevWatchButton implements Button<Client> {
id = 'dev-watch';
async execute(context: Client<boolean>, interaction: ButtonInteraction): Promise<void> {
if (!interaction.inGuild()) return;
await interaction.reply({
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,
});
}
}
export default new DevWatchButton();
+27
View File
@@ -0,0 +1,27 @@
import claimTicket from './claimTicket';
import closeModTicket from './closeModTicket';
import closeTicket from './closeTicket';
import devWatch from './devWatch';
import noteNext from './noteNext';
import notePrevious from './notePrevious';
import openTicketForReportedMessage from './openTicketForReportedMessage';
import privateHelp from './privateHelp';
import recordsNext from './recordsNext';
import recordsPrevious from './recordsPrevious';
import roleButton from './roleButton';
import unclaimTicket from './unclaimTicket';
export default [
claimTicket,
closeModTicket,
closeTicket,
devWatch,
noteNext,
notePrevious,
openTicketForReportedMessage,
privateHelp,
recordsNext,
recordsPrevious,
roleButton,
unclaimTicket
];
-15
View File
@@ -1,15 +0,0 @@
import { ButtonInteraction, Client } from 'discord.js';
import { getNoteMessage } from '../utils';
export default {
name: 'note-next',
handler: async function (client: Client, interaction: ButtonInteraction, userId: string, page: string) {
await interaction.deferUpdate();
const message = await getNoteMessage(userId, parseInt(page) + 1);
if (!message) return;
interaction.editReply(message);
}
};
-15
View File
@@ -1,15 +0,0 @@
import { ButtonInteraction, Client} from 'discord.js';
import { getNoteMessage } from '../utils';
export default {
name: 'note-previous',
handler: async function (client: Client, interaction: ButtonInteraction, userId: string, page: string) {
await interaction.deferUpdate();
const message = await getNoteMessage(userId, parseInt(page) - 1);
if (!message) return;
interaction.editReply(message);
}
};
+18
View File
@@ -0,0 +1,18 @@
import { ButtonInteraction, Client } from 'discord.js';
import { Button } from '../types';
import { getNoteMessage } from '../utils';
class NoteNextButton implements Button<Client> {
id = 'note-next';
async execute(context: Client<boolean>, interaction: ButtonInteraction, userId: string, page: string): Promise<void> {
await interaction.deferUpdate();
const message = await getNoteMessage(userId, parseInt(page) + 1);
if (!message) return;
await interaction.editReply(message);
}
}
export default new NoteNextButton();
+18
View File
@@ -0,0 +1,18 @@
import { ButtonInteraction, Client } from 'discord.js';
import { Button } from '../types';
import { getNoteMessage } from '../utils';
class NotePreviousButton implements Button<Client> {
id = 'note-previous';
async execute(context: Client<boolean>, interaction: ButtonInteraction, userId: string, page: string): Promise<void> {
await interaction.deferUpdate();
const message = await getNoteMessage(userId, parseInt(page) - 1);
if (!message) return;
await interaction.editReply(message);
}
}
export default new NotePreviousButton();
@@ -1,40 +0,0 @@
import { ButtonInteraction, Client, MessageFlags, MessageMentions } from 'discord.js';
import { createPrivateHelpTicketThread } from '../utils';
export default {
name: 'open-ticket-for-reported-message',
handler: async function (client: Client, interaction: ButtonInteraction) {
const message = await interaction.message.fetch();
const guild = await interaction.guild!.fetch();
const reportEmbed = message.embeds[0]!;
const regex = new RegExp(MessageMentions.UsersPattern);
const reportedMessageUrl = reportEmbed.fields[0].value;
const reporterId = regex.exec(reportEmbed.fields[2].value)!.groups!.id;
const additionalInfo = reportEmbed.fields[3]?.name == 'Additional Information' ? reportEmbed.fields[3].value : '';
const reporter = await guild.members.fetch(reporterId) ?? await client.users.fetch(reporterId);
const thread = await createPrivateHelpTicketThread(client, guild, null, `Ticket creted by staff in response to message report: ${message.url}. Reported message: ${reportedMessageUrl}. ${additionalInfo ? `\n\nAdditional information provided in report:\n${additionalInfo.split('\n').map(c => `> ${c}`).join('\n')}` : ''}`, `Ticket: Message Report From ${reporter.displayName}`, [reporterId, interaction.user.id]);
if (thread) {
await interaction.reply({
flags: [MessageFlags.Ephemeral],
content: `Ticket created: ${thread}`
});
const requestIndex = reportEmbed.fields.findIndex(f => f.name == 'User Requested Private Ticket');
if (requestIndex != -1) reportEmbed.fields.splice(requestIndex, 1);
reportEmbed.fields.push({
name: 'Private Help Ticket',
value: thread.url,
inline: false
});
await message.edit({ embeds: [reportEmbed], components: [] });
}
}
};
@@ -0,0 +1,45 @@
import { ButtonInteraction, Client, MessageFlags, MessageMentions } from 'discord.js';
import { Button } from '../types';
import { createPrivateHelpTicketThread } from '../utils';
class OpenTicketForReportedMessageButton implements Button<Client> {
id = 'open-ticket-for-reported-message';
async execute(context: Client<boolean>, interaction: ButtonInteraction): Promise<void> {
if (!interaction.inGuild()) return;
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
try {
const guild = await context.guilds.fetch(interaction.guildId);
const message = await interaction.message.fetch();
const reportEmbed = message.embeds[0]!;
const regex = new RegExp(MessageMentions.UsersPattern);
const reportedMessageUrl = reportEmbed.fields[0].value;
const reporterId = regex.exec(reportEmbed.fields[2].value)!.groups!.id;
const additionalInfo = reportEmbed.fields[3]?.name == 'Additional Information' ? reportEmbed.fields[3].value : '';
const reporter = await guild.members.fetch(reporterId) ?? await context.users.fetch(reporterId);
const thread = await createPrivateHelpTicketThread(context, guild, null, `Ticket creted by staff in response to message report: ${message.url}. Reported message: ${reportedMessageUrl}. ${additionalInfo ? `\n\nAdditional information provided in report:\n${additionalInfo.split('\n').map(c => `> ${c}`).join('\n')}` : ''}`, `Ticket: Message Report From ${reporter.displayName}`, [reporterId, interaction.user.id]);
if (!thread) throw new Error('An error occured and a thread was not created.');
await interaction.editReply({ content: `Ticket Created: ${thread}` });
const requestIndex = reportEmbed.fields.findIndex(f => f.name == 'User Requested Private Ticket');
if (requestIndex != -1) reportEmbed.fields.splice(requestIndex, 1);
reportEmbed.fields.push({
name: 'Private Help Ticket',
value: thread.url,
inline: false
});
await message.edit({ embeds: [reportEmbed], components: [] });
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
}
}
export default new OpenTicketForReportedMessageButton();
-20
View File
@@ -1,20 +0,0 @@
import { ButtonInteraction, Client, ModalBuilder, TextInputStyle, MessageFlags } from 'discord.js';
import { canOpenPrivateHelpTicket, createTextInput } from '../utils';
export default {
name: 'private-help',
handler: async function (client: Client, interaction: ButtonInteraction) {
if (!(await canOpenPrivateHelpTicket(interaction.user.id)))
return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'You can only have one open ticket at a time that is less than a day old.' });
const modal = new ModalBuilder()
.setCustomId('open-ticket-modal')
.setTitle('Get in contact');
const label = createTextInput('ticket-message', 'What is the reason for your ticket?', null, true, TextInputStyle.Paragraph, 1500, 10);
modal.addLabelComponents(label);
await interaction.showModal(modal);
}
};
+30
View File
@@ -0,0 +1,30 @@
import { ButtonInteraction, Client, ModalBuilder, TextInputStyle, MessageFlags } from 'discord.js';
import { Button } from '../types';
import { canOpenPrivateHelpTicket, createTextInput } from '../utils';
class PrivateHelpButton implements Button<Client> {
id = 'private-help';
async execute(context: Client<boolean>, interaction: ButtonInteraction): Promise<void> {
try {
if (!await canOpenPrivateHelpTicket(interaction.user.id))
throw new Error('You can only have one open ticket at a time that is less than a day old.');
const modal = new ModalBuilder()
.setCustomId('open-ticket-modal')
.setTitle('Get in contact');
const label = createTextInput('ticket-message', 'What is the reason for your ticket?', null, true, TextInputStyle.Paragraph, 1500, 10);
modal.addLabelComponents(label);
await interaction.showModal(modal);
} catch (error: Error | any) {
await interaction.reply({
content: error.message,
flags: MessageFlags.Ephemeral,
}).catch(() => {});
}
}
}
export default new PrivateHelpButton();
-15
View File
@@ -1,15 +0,0 @@
import { ButtonInteraction, Client } from 'discord.js';
import { getRecordMessageFromDiscordId } from '../utils';
export default {
name: 'records-next',
handler: async function (client: Client, interaction: ButtonInteraction, userId: string, page: string) {
await interaction.deferUpdate();
const message = await getRecordMessageFromDiscordId(userId, parseInt(page) + 1, interaction.guild!);
if (!message) return;
interaction.editReply(message);
}
};
-15
View File
@@ -1,15 +0,0 @@
import { ButtonInteraction, Client} from 'discord.js';
import { getRecordMessageFromDiscordId } from '../utils';
export default {
name: 'records-previous',
handler: async function (client: Client, interaction: ButtonInteraction, userId: string, page: string) {
await interaction.deferUpdate();
const message = await getRecordMessageFromDiscordId(userId, parseInt(page) - 1, interaction.guild!);
if (!message) return;
interaction.editReply(message);
}
};
+18
View File
@@ -0,0 +1,18 @@
import { ButtonInteraction, Client } from 'discord.js';
import { Button } from '../types';
import { getRecordMessageFromDiscordId } from '../utils';
class RecordsNextButton implements Button<Client> {
id = 'records-next';
async execute(context: Client<boolean>, interaction: ButtonInteraction, userId: string, page: string): Promise<void> {
await interaction.deferUpdate();
const message = await getRecordMessageFromDiscordId(userId, parseInt(page) + 1, interaction.guild!);
if (!message) return;
await interaction.editReply(message);
}
}
export default new RecordsNextButton();
+18
View File
@@ -0,0 +1,18 @@
import { ButtonInteraction, Client } from 'discord.js';
import { Button } from '../types';
import { getRecordMessageFromDiscordId } from '../utils';
class RecordsPreviousButton implements Button<Client> {
id = 'records-previous';
async execute(context: Client<boolean>, interaction: ButtonInteraction, userId: string, page: string): Promise<void> {
await interaction.deferUpdate();
const message = await getRecordMessageFromDiscordId(userId, parseInt(page) - 1, interaction.guild!);
if (!message) return;
await interaction.editReply(message);
}
}
export default new RecordsPreviousButton();
-32
View File
@@ -1,32 +0,0 @@
import { ButtonInteraction, Client, MessageFlags } from 'discord.js';
import { Database } from '../shared/Database';
export default {
name: 'role-button',
handler: async function (client: Client, interaction: ButtonInteraction) {
await interaction.deferReply({ flags: [MessageFlags.Ephemeral] });
const roleId = await Database.getRoleFromButton(interaction.message.id);
if (!roleId) await interaction.editReply({ content: 'Could not find role button.' });
const guild = await interaction.guild?.fetch();
const member = await guild?.members.fetch(interaction.user.id);
if (!member) return interaction.editReply({ content: 'Member not found.' });
try {
if (member.roles.cache.has(roleId!)) {
await member.roles.remove(roleId!);
interaction.editReply({ content: 'Role removed.' });
} else {
await member.roles.add(roleId!);
interaction.editReply({ content: 'Role added.' });
}
} catch (e) {
console.error(e);
interaction.editReply({ content: 'Could not add role. Is it higher than mine?' });
}
}
};
+38
View File
@@ -0,0 +1,38 @@
import { ButtonInteraction, Client, MessageFlags } from 'discord.js';
import { Database } from '../shared/Database';
import { Button } from '../types';
class RoleButtonButton implements Button<Client> {
id = 'role-button';
async execute(context: Client<boolean>, interaction: ButtonInteraction): Promise<void> {
if (!interaction.inGuild()) return;
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
try {
const roleId = await Database.getRoleFromButton(interaction.message.id);
if (!roleId) throw new Error("I couldn't find an associated role ID with this button.");
const guild = await context.guilds.fetch(interaction.guildId);
const member = await guild.members.fetch(interaction.user.id);
if (!member) throw new Error('I was unable to fetch you as a member.');
const bot = await guild.members.fetchMe();
const role = await guild.roles.fetch(roleId);
if (!role) throw new Error("The configured role for this button doesn't exist.");
if (role.position > bot.roles.highest.position) throw new Error(`The configured role (\`${role.name}\`) is higher than my highest role.`);
if (member.roles.cache.has(roleId)) {
await member.roles.remove(roleId);
await interaction.editReply({ content: 'Role removed.' });
} else {
await member.roles.add(roleId);
await interaction.editReply({ content: 'Role Added' });
}
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
}
}
export default new RoleButtonButton();
-42
View File
@@ -1,42 +0,0 @@
import { ActionRowBuilder, ButtonBuilder, ButtonInteraction, ButtonStyle, ChannelType, Client, MessageFlags, PermissionFlagsBits } from 'discord.js';
import { Database } from '../shared/Database';
export default {
name: 'unclaim-ticket',
handler: async function (client: Client, interaction: ButtonInteraction) {
const channel = await interaction.channel?.fetch();
if (!channel || !channel.isThread() || !channel.isSendable() || channel.type != ChannelType.PrivateThread)
return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Oops. Something went wrong.' });
if (!interaction.memberPermissions) return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'An error has occurred.' });
if (!interaction.memberPermissions.has(PermissionFlagsBits.ManageMessages)) return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'You do not have permission to unclaim this ticket.' });
if (!interaction.message.content.split('\n').at(-1)!.includes(`<@${interaction.user.id}>`)) return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'You did not claim this ticket.' });
const guild = await client.guilds.fetch(interaction.guildId!);
const settings = await Database.getOrCreateSettings(guild.id);
if (!settings.private_help_role_id) return interaction.reply({ flags: [MessageFlags.Ephemeral], content: 'Failed to unclaim ticket.' });
const closeButton = new ButtonBuilder()
.setCustomId('close-ticket')
.setLabel('Click here if you no longer need help')
.setStyle(ButtonStyle.Danger);
const claimButton = new ButtonBuilder()
.setCustomId('claim-ticket')
.setLabel('Claim ticket')
.setStyle(ButtonStyle.Primary);
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(closeButton, claimButton);
await interaction.message.edit({
content: interaction.message.content.split('\n').slice(0, -1).join('\n').trim(),
components: [row]
});
await interaction.reply({ content: 'Ticket unclaimed.', flags: [MessageFlags.Ephemeral] });
}
};
+54
View File
@@ -0,0 +1,54 @@
import { ActionRowBuilder, ButtonBuilder, ButtonInteraction, ButtonStyle, ChannelType, Client, MessageFlags, PermissionFlagsBits } from 'discord.js';
import { Button } from '../types';
import { SetSeverity } from '../utils';
class UnclaimTicketButton implements Button<Client> {
id = 'unclaim-ticket';
async execute(context: Client<boolean>, interaction: ButtonInteraction): Promise<void> {
if (!interaction.inGuild()) return;
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
try {
const channel = await context.channels.fetch(interaction.channelId);
if (!channel) throw new Error("The interaction channel couldn't be fetched.");
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 (!interaction.memberPermissions.has(PermissionFlagsBits.ManageMessages)) throw new Error("You don't have permission to unclaim 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()
.setCustomId('close-ticket')
.setLabel('Click here if you no longer need help')
.setStyle(ButtonStyle.Danger);
const claimButton = new ButtonBuilder()
.setCustomId('claim-ticket')
.setLabel('Claim ticket')
.setStyle(ButtonStyle.Primary);
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(closeButton, claimButton);
await interaction.message.edit({
content: interaction.message.content.split('\n').slice(0, -1).join('\n').trim(),
components: [row]
});
await channel.send({
embeds: [{
...SetSeverity('warning'),
description: 'This ticket has been unclaimed.'
}],
});
await interaction.editReply({ content: 'Ticket unclaimed.' });
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
}
}
export default new UnclaimTicketButton();
-42
View File
@@ -1,42 +0,0 @@
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.' });
}
};
+66 -31
View File
@@ -1,6 +1,61 @@
import { ApplicationIntegrationType, ChatInputCommandInteraction, Client, InteractionContextType, MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { Database } from '../shared/Database';
import { getIdFromInput } from '../utils';
import { getIdFromInput, SetSeverity } 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 {
name: 'github-mapping',
@@ -44,37 +99,17 @@ export default {
.setDescription('List all github-discord mappings.')
),
handler: async function (client: Client, interaction: ChatInputCommandInteraction) {
await interaction.deferReply({ flags: [MessageFlags.Ephemeral] });
if (!interaction.inGuild()) return;
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const subcommand = await interaction.options.getSubcommand(true);
if (subcommand == 'add') {
const discordUserInput = interaction.options.getString('discord-user', true);
const idToUse = getIdFromInput(discordUserInput);
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'));
try {
switch (interaction.options.getSubcommand(true)) {
case 'add': return await addUserMapping(interaction);
case 'remove': return await removeUserMapping(interaction);
case 'list': return await listUserMapping(interaction);
}
} catch (error: Error | any) {
await interaction.editReply({ content: error.message }).catch(() => {});
}
}
};
+2 -13
View File
@@ -75,12 +75,7 @@ export default {
.setDescription('Set the private helper role.')
.setRequired(false)
)
.addRoleOption(option =>
option
.setName('devwatch-role')
.setDescription('Set the DevWatch role.')
.setRequired(false)
)
.addChannelOption(option =>
option
.setName('add-staff-category')
@@ -189,7 +184,7 @@ export default {
const moderatorChannel = interaction.options.getChannel('moderator-channel');
if (moderatorChannel) {
await Database.updateSettings(interaction.guildId, 'moderator_channel_id', moderatorChannel.id);
response.push(`**moderator_channel_id** has been set to": ${moderatorChannel}.`);
response.push(`**moderator_channel_id** has been set to: ${moderatorChannel}.`);
}
const adminRole = interaction.options.getRole('admin-role');
@@ -204,12 +199,6 @@ export default {
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');
if (addCategory) {
if (addCategory.type == ChannelType.GuildCategory) {
+4 -16
View File
@@ -1,5 +1,4 @@
import { ApplicationCommandType, ApplicationIntegrationType, Client, ContextMenuCommandBuilder, InteractionContextType, LabelBuilder, MessageContextMenuCommandInteraction, MessageFlags, ModalBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';
import { ApplicationCommandType, ApplicationIntegrationType, CheckboxBuilder, Client, ContextMenuCommandBuilder, InteractionContextType, LabelBuilder, MessageContextMenuCommandInteraction, MessageFlags, ModalBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';
import { Database } from '../shared/Database';
export default {
@@ -28,24 +27,13 @@ export default {
.setDescription('Any additional information? This will help staff understand your report. 1000 characters maximum.')
.setTextInputComponent(additionalInfoInput);
const yesNoMenu = new StringSelectMenuBuilder()
.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 createTicketCheckbox = new CheckboxBuilder()
.setCustomId('create-private-help-ticket');
const createPrivateTicket = new LabelBuilder()
.setLabel('Create Private Help Ticket')
.setDescription('Should a private help ticket be opened with this report? (Does not bypass ticket restrictions)')
.setStringSelectMenuComponent(yesNoMenu);
.setCheckboxComponent(createTicketCheckbox);
modal.addLabelComponents(additionalInfoLabel, createPrivateTicket);
+8 -5
View File
@@ -1,5 +1,6 @@
import { APIEmbedField, APIRole, AuditLogEvent, Guild, GuildAuditLogsEntry, RoleFlags, SnowflakeUtil } from 'discord.js';
import { APIEmbedField, APIRole, AuditLogEvent, Client, Guild, GuildAuditLogsEntry, RoleFlags, SnowflakeUtil } from 'discord.js';
import { Database } from '../../shared/Database';
import { Event } from '../../types';
import { CreateDefaultEmbed, formatChanges, formatExtras, formatSnowflake, getTargetType } from '../../utils';
const IGNORED_ACTIONS = [
@@ -33,10 +34,10 @@ async function shouldLogRoleChanges(entry: GuildAuditLogsEntry<AuditLogEvent.Mem
return false;
}
export default {
event: 'guildAuditLogEntryCreate',
class GuildAuditLogEntryCreateEvent implements Event<Client, 'guildAuditLogEntryCreate'> {
event = 'guildAuditLogEntryCreate' as const;
handler: async (entry: GuildAuditLogsEntry, guild: Guild) => {
async execute(context: Client, entry: GuildAuditLogsEntry, guild: Guild): Promise<void> {
if (!await shouldLog(entry, guild)) return;
const settings = await Database.getOrCreateSettings(guild.id);
@@ -95,4 +96,6 @@ export default {
}]
});
}
};
}
export default new GuildAuditLogEntryCreateEvent();
+8 -5
View File
@@ -1,10 +1,13 @@
import { GuildBan } from 'discord.js';
import { Client, GuildBan } from 'discord.js';
import { Database } from '../../shared/Database';
import { Event } from '../../types';
export default {
event: 'guildBanRemove',
class GuildBanRemoveEvent implements Event<Client, 'guildBanRemove'> {
event = 'guildBanRemove' as const;
handler: async (ban: GuildBan) => {
async execute(context: Client<boolean>, ban: GuildBan): Promise<void> {
await Database.removeBan(ban.user.id);
}
};
}
export default new GuildBanRemoveEvent();
+14 -5
View File
@@ -1,10 +1,19 @@
import { Guild } from 'discord.js';
import { Client, Guild } from 'discord.js';
import { config } from '../../config';
import { Database } from '../../shared/Database';
import { Event } from '../../types';
export default {
event: 'guildCreate',
class GuildCreateEvent implements Event<Client, 'guildCreate'> {
event = 'guildCreate' as const;
async execute(context: Client<boolean>, guild: Guild): Promise<void> {
if (guild.id != config.DISCORD_GUILD_ID) {
await guild.leave();
return;
}
handler: async (guild: Guild) => {
await Database.getOrCreateSettings(guild.id);
}
};
}
export default new GuildCreateEvent();
+16 -17
View File
@@ -1,27 +1,26 @@
import { GuildMember, GuildTextBasedChannel } from 'discord.js';
import { Client, GuildMember, GuildTextBasedChannel } from 'discord.js';
import { Database } from '../../shared/Database';
import { Event } from '../../types';
import { getE621Alts } from '../../utils';
export default {
event: 'guildMemberAdd',
class GuildMemberAddEvent implements Event<Client, 'guildMemberAdd'> {
event = 'guildMemberAdd' as const;
handler: async (member: GuildMember) => {
async execute(context: Client<boolean>, member: GuildMember): Promise<void> {
const settings = await Database.getOrCreateSettings(member.guild.id);
if (!settings.new_member_channel_id) return;
if (settings.new_member_channel_id) {
const channel = await member.guild.channels.fetch(settings.new_member_channel_id) as GuildTextBasedChannel;
const channel = await member.guild.channels.fetch(settings.new_member_channel_id) as GuildTextBasedChannel;
if (!channel) return;
if (channel) {
const content = `${member.toString()}'s (${member.id}) e621 and discord account(s):\n${await getE621Alts(member.id, member.guild)}`;
const content = `${member.toString()}'s (${member.id}) e621 and discord account(s):\n${await getE621Alts(member.id, member.guild)}`;
channel.send(content).catch(console.error);
channel.send(content).catch(console.error);
if (settings.moderator_channel_id && content.includes('[BANNED]')) {
const modChannel = await member.guild.channels.fetch(settings.moderator_channel_id) as GuildTextBasedChannel;
if (modChannel) modChannel.send(`Member joined with banned alts:\n${content}`).catch(console.error);
}
}
if (settings.moderator_channel_id && content.includes('[BANNED]')) {
const modChannel = await member.guild.channels.fetch(settings.moderator_channel_id) as GuildTextBasedChannel;
if (modChannel) modChannel.send(`Member joined with banned alts:\n${content}`).catch(console.error);
}
}
};
}
export default new GuildMemberAddEvent();
+8 -4
View File
@@ -1,11 +1,13 @@
import { Client } from 'discord.js';
import { config } from '../../config';
import { Database } from '../../shared/Database';
import { Event } from '../../types';
import { ALLOWED_MIMETYPES, blacklistIfNecessary, calculateMD5FromURL, getE621PostByMd5, getPostUrl, md5Regex, Message, regexTesters, uniqueRegexMatches } from '../../utils';
export default {
event: 'messageCreate',
class MessageCreateEvent implements Event<Client, 'messageCreate'> {
event = 'messageCreate' as const;
handler: async (message: Message) => {
async execute(context: Client<boolean>, message: Message): Promise<void> {
if (message.author.bot) return;
if (message.inGuild()) await Database.putMessage(message);
@@ -66,4 +68,6 @@ export default {
await message.reply(responses.join('\n'));
}
}
};
}
export default new MessageCreateEvent();
+8 -5
View File
@@ -1,11 +1,12 @@
import { Message, PartialMessage } from 'discord.js';
import { Client, Message, PartialMessage } from 'discord.js';
import { Database } from '../../shared/Database';
import { Event } from '../../types';
import { logDeletion } from '../../utils';
export default {
event: 'messageDelete',
class MessageDeleteEvent implements Event<Client, 'messageDelete'> {
event = 'messageDelete' as const;
handler: async (message: Message | PartialMessage) => {
async execute(context: Client<boolean>, message: Message | PartialMessage): Promise<void> {
const loggedMessage = await Database.getMessageWithRetry(message.id);
if (!loggedMessage) return;
@@ -13,4 +14,6 @@ export default {
if (message.inGuild()) await logDeletion(loggedMessage, message);
}
};
}
export default new MessageDeleteEvent();
+8 -6
View File
@@ -1,18 +1,20 @@
import { GuildTextBasedChannel, Message, OmitPartialGroupDMChannel, PartialMessage, ReadonlyCollection } from 'discord.js';
import { Client, GuildTextBasedChannel, Message, OmitPartialGroupDMChannel, PartialMessage, ReadonlyCollection } from 'discord.js';
import { Database } from '../../shared/Database';
import { Event } from '../../types';
import { logDeletion } from '../../utils';
export default {
event: 'messageDeleteBulk',
class MessageDeleteBulkEvent implements Event<Client, 'messageDeleteBulk'> {
event = 'messageDeleteBulk' as const;
handler: async (messages: ReadonlyCollection<string, Message | OmitPartialGroupDMChannel<PartialMessage>>, channel: GuildTextBasedChannel) => {
async execute(context: Client<boolean>, messages: ReadonlyCollection<string, Message | OmitPartialGroupDMChannel<PartialMessage>>, channel: GuildTextBasedChannel): Promise<void> {
for (const message of messages.values()) {
const loggedMessage = await Database.getMessageWithRetry(message.id);
if (!loggedMessage) continue;
await Database.removeMessge(message.id);
if (message.inGuild()) await logDeletion(loggedMessage, message);
}
}
};
}
export default new MessageDeleteBulkEvent();
+25 -28
View File
@@ -1,12 +1,13 @@
import { PartialMessage } from 'discord.js';
import { Client, PartialMessage } from 'discord.js';
import { config } from '../../config';
import { Database } from '../../shared/Database';
import { Event } from '../../types';
import { isEdited, logEdit, Message, regexTesters, uniqueRegexMatches } from '../../utils';
export default {
event: 'messageUpdate',
class MessageUpdateEvent implements Event<Client, 'messageUpdate'> {
event = 'messageUpdate' as const;
handler: async (oldMessage: Message | PartialMessage, newMessage: Message) => {
async execute(context: Client<boolean>, oldMessage: Message | PartialMessage, newMessage: Message): Promise<void> {
if (newMessage.author.bot) return;
const loggedMessage = await Database.getMessageWithRetry(newMessage.id);
@@ -31,39 +32,35 @@ export default {
const hasMatches = test.regex.test(newMessage.content);
test.regex.lastIndex = 0;
if (hasMatches) {
const oldMatches: RegExpExecArray[] = [];
const newMatches: RegExpExecArray[] = [];
let match: RegExpExecArray | null;
if (!hasMatches) continue;
while ((match = test.regex.exec(newMessage.content)) != null) {
newMatches.push(match);
}
test.regex.lastIndex = 0;
const oldMatches: RegExpExecArray[] = [];
const newMatches: RegExpExecArray[] = [];
let match: RegExpExecArray | null;
while ((match = test.regex.exec(loggedMessage.content)) != null) {
oldMatches.push(match);
}
test.regex.lastIndex = 0;
while ((match = test.regex.exec(newMessage.content)) != null) newMatches.push(match);
test.regex.lastIndex = 0;
const properMatches: RegExpExecArray[] = [];
while ((match = test.regex.exec(loggedMessage.content)) != null) oldMatches.push(match);
test.regex.lastIndex = 0;
for (const newMatch of newMatches) {
if (!oldMatches.find(m => m[1] == newMatch[1])) properMatches.push(newMatch);
}
const properMatches: RegExpExecArray[] = [];
if (properMatches.length == 0) continue;
const response = await test.handler(newMessage, properMatches.filter(uniqueRegexMatches));
if (response === false) return;
if (response !== true) responses.push(response as string);
for (const newMatch of newMatches) {
if (!oldMatches.find(m => m[1] == newMatch[1])) properMatches.push(newMatch);
}
if (properMatches.length == 0) continue;
const response = await test.handler(newMessage, properMatches.filter(uniqueRegexMatches));
if (response === false) return;
if (response !== true) responses.push(response as string);
}
if (responses.length > 0) {
await newMessage.reply(responses.join('\n'));
}
}
};
}
export default new MessageUpdateEvent();
+8 -5
View File
@@ -1,13 +1,16 @@
import { AnyThreadChannel } from 'discord.js';
import { AnyThreadChannel, Client } from 'discord.js';
import { Event } from '../../types';
export default {
event: 'threadCreate',
class ThreadCreateEvent implements Event<Client, 'threadCreate'> {
event = 'threadCreate' as const;
handler: async (thread: AnyThreadChannel, newlyCreated: boolean) => {
async execute(context: Client<boolean>, thread: AnyThreadChannel, _newlyCreated: boolean) {
try {
await thread.join();
} catch (e) {
console.error(`Failed to join thread: ${thread.name} (${thread.id})`, e);
}
}
};
}
export default new ThreadCreateEvent();
+8 -7
View File
@@ -1,5 +1,6 @@
import { Guild, GuildTextBasedChannel, VoiceState } from 'discord.js';
import { Client, Guild, GuildTextBasedChannel, VoiceState } from 'discord.js';
import { Database } from '../../shared/Database';
import { Event } from '../../types';
import { CreateDefaultEmbed, SetSeverity } from '../../utils';
async function getVoiceLogsChannel(guild: Guild): Promise<GuildTextBasedChannel | undefined> {
@@ -22,7 +23,6 @@ async function memberJoinedChannel(_: VoiceState, state: VoiceState) {
...SetSeverity('success'),
title: 'Joined Voice Channel',
fields: [
{ name: 'Member', value: `<@${state.member?.id}>`, inline: false },
{ name: 'Channel', value: `${state.channel?.name} (${state.channelId})`, inline: true },
@@ -61,7 +61,6 @@ async function memberMovedChannel(oldState: VoiceState, newState: VoiceState) {
...SetSeverity('warning'),
title: 'Moved Voice Channel',
fields: [
{ name: 'Member', value: `<@${newState.member?.id}>`, inline: false },
{ name: 'Channel', value: `<#${oldState.channelId}> -> <#${newState.channelId}>`, inline: false },
@@ -70,10 +69,10 @@ async function memberMovedChannel(oldState: VoiceState, newState: VoiceState) {
});
}
export default {
event: 'voiceStateUpdate',
class VoiceStateUpdateEvent implements Event<Client, 'voiceStateUpdate'> {
event = 'voiceStateUpdate' as const;
handler: async (oldState: VoiceState, newState: VoiceState) => {
async execute(context: Client<boolean>, oldState: VoiceState, newState: VoiceState): Promise<void> {
// Ignore non-movement voiceStateUpdate events.
if (oldState.channelId === newState.channelId) return;
@@ -84,4 +83,6 @@ export default {
else if (newState.channelId == null && oldState.channelId != null)
await memberLeftChannel(oldState, newState);
}
};
}
export default new VoiceStateUpdateEvent();
+25 -20
View File
@@ -1,6 +1,8 @@
import { Client as DiscordClient, GatewayIntentBits, MessageFlags, Partials } from 'discord.js';
import { ButtonInteraction, Client, GatewayIntentBits, MessageFlags, ModalSubmitInteraction, Partials } from 'discord.js';
import buttons from './buttons';
import { config } from './config';
import events from './events';
import modals from './modals';
import { Database } from './shared/Database';
import { openRedisClient } from './shared/RedisClient';
import { Handler } from './types';
@@ -14,7 +16,7 @@ let ready = false;
console.log('Starting...');
const client = new DiscordClient({
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
@@ -24,17 +26,19 @@ const client = new DiscordClient({
GatewayIntentBits.MessageContent
],
partials: [Partials.Message, Partials.GuildMember, Partials.User, Partials.Channel],
rest: { timeout: 30000 },
rest: {
version: '10'
},
allowedMentions: {
parse: [],
repliedUser: false
}
},
});
const commands: Handler[] = [];
const contextMenus: Handler[] = [];
const buttons: Handler[] = [];
const modals: Handler[] = [];
const menus: Handler[] = [];
// Due to their reliance on each other, these two events (interactionCreate, and ready) have to stay here.
@@ -89,20 +93,22 @@ client.on('interactionCreate', async (interaction) => {
const id = interaction.customId.split('_')[0];
for (const button of buttons) {
if (id == button.name) {
button.handler(client, interaction, ...interaction.customId.split('_').slice(1));
return;
}
if (button.id != id) continue;
Promise.resolve((button.execute as (context: Client, interaction: ButtonInteraction, ...args: unknown[]) => Promise<void>)(client, interaction, ...interaction.customId.split('_').slice(1))
.catch(e => console.error('An error occurred while handling a button interaction: ', e)));
return;
}
} else if (interaction.isModalSubmit()) {
// Handle modal submissions.
const id = interaction.customId.split('_')[0];
for (const modal of modals) {
if (id == modal.name) {
modal.handler(client, interaction, ...interaction.customId.split('_').slice(1));
return;
}
if (id != modal.id) continue;
Promise.resolve((modal.execute as (context: Client, interaction: ModalSubmitInteraction, ...args: unknown[]) => Promise<void>)(client, interaction, ...interaction.customId.split('_').slice(1))
.catch(e => console.error('An error occurred while handling a modal interaction: ', e)));
return;
}
} else if (interaction.isAnySelectMenu()) {
// Handle menu selections.
@@ -120,17 +126,17 @@ client.on('interactionCreate', async (interaction) => {
client.on('clientReady', async () => {
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('context-menus', contextMenus);
await loadHandlersFrom('buttons', buttons);
await loadHandlersFrom('modals', modals);
await loadHandlersFrom('menus', menus);
await refreshCommands(client);
await initIfNecessary(client, commands);
await initIfNecessary(client, buttons);
await initIfNecessary(client, modals);
await initIfNecessary(client, menus);
Encrypter.initialize(config.DATABASE_SECRET!);
@@ -151,7 +157,7 @@ client.on('clientReady', async () => {
events.forEach(event =>
client.on(event.event, (...args) =>
Promise.resolve((event.handler as (...args: unknown[]) => Promise<void>)(...args))
Promise.resolve((event.execute as (context: Client, ...args: unknown[]) => Promise<void>)(client, ...args))
.catch(e => console.error(`Error in ${event.event} handler:`, e))
)
);
@@ -160,7 +166,6 @@ client.on('clientReady', async () => {
console.log('Ready');
});
client.on('error', console.error);
process.on('uncaughtException', console.error);
@@ -1,49 +0,0 @@
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
@@ -1,40 +0,0 @@
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
@@ -0,0 +1,41 @@
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
@@ -0,0 +1,38 @@
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();
@@ -1,54 +0,0 @@
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
@@ -0,0 +1,43 @@
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
@@ -0,0 +1,17 @@
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
@@ -1,31 +0,0 @@
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
@@ -1,23 +0,0 @@
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
@@ -0,0 +1,39 @@
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
@@ -0,0 +1,31 @@
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
@@ -1,118 +0,0 @@
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
@@ -0,0 +1,96 @@
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
@@ -1,32 +0,0 @@
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
@@ -0,0 +1,27 @@
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();
+3 -2
View File
@@ -364,8 +364,9 @@ export class Database {
});
}
static async removeGithubUserMapping(discordId: string) {
await Database.db.run('DELETE from github_user_mapping WHERE discord_id_hash = ?', Encrypter.encrypt(discordId));
static async removeGithubUserMapping(discordId: string): Promise<boolean> {
const result = await Database.db.run('DELETE FROM github_user_mapping WHERE discord_id_hash = ?', Encrypter.hash(discordId));
return (result.changes ?? 0) > 0;
}
//#endregion
+6
View File
@@ -0,0 +1,6 @@
import { ButtonInteraction } from 'discord.js';
export interface Button<Context> {
id: string;
execute(context: Context, interaction: ButtonInteraction, ...args: any): Promise<void>;
}
-1
View File
@@ -22,7 +22,6 @@ export type GuildSettings = {
voice_logs_channel_id?: string
admin_role_id?: string
private_help_role_id?: string
devwatch_role_id?: string
staff_categories?: string
safe_channels?: string
link_skip_channels?: string
+6
View File
@@ -0,0 +1,6 @@
import { ClientEvents } from 'discord.js';
export interface Event<Context, E extends keyof ClientEvents> {
readonly event: E;
execute(context: Context, ...args: ClientEvents[E]): Promise<void>;
}
+3
View File
@@ -1,6 +1,9 @@
export * from './button.d';
export * from './command.d';
export * from './database-types.d';
export * from './event.d';
export * from './e621-types.d';
export * from './handler.d';
export * from './helper-types.d';
export * from './modal.d';
export * from './task.d';
+6
View File
@@ -0,0 +1,6 @@
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 { channelIsInStaffCategory } from './channel-utils';
import { channelIsInStaffCategory } from '.';
export async function deferInteraction(interaction: ChatInputCommandInteraction | ContextMenuCommandInteraction | ModalSubmitInteraction) {
const isStaffChannel = await channelIsInStaffCategory(interaction.channel as GuildBasedChannel);
+5 -14
View File
@@ -1,4 +1,4 @@
import { LabelBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';
import { CheckboxBuilder, LabelBuilder, 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 {
const input = new TextInputBuilder()
@@ -19,23 +19,14 @@ export function createTextInput(customId: string, labelTitle: string, descriptio
return label;
}
export function createYesNoMenu(customId: string, labelTitle: string, description: string | null, defaultYes: boolean): LabelBuilder {
const yesNoMenu = new StringSelectMenuBuilder()
export function createCheckbox(customId: string, labelTitle: string, description: string | null, defaultYes: boolean): LabelBuilder {
const component = new CheckboxBuilder()
.setCustomId(customId)
.addOptions(
new StringSelectMenuOptionBuilder()
.setLabel('Yes')
.setDefault(defaultYes)
.setValue('yes'),
new StringSelectMenuOptionBuilder()
.setLabel('No')
.setDefault(!defaultYes)
.setValue('no')
);
.setDefault(defaultYes);
const yesNoLabel = new LabelBuilder()
.setLabel(labelTitle)
.setStringSelectMenuComponent(yesNoMenu);
.setCheckboxComponent(component);
if (description !== null) yesNoLabel.setDescription(description);
+46 -18
View File
@@ -1,35 +1,64 @@
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 { createTextInput, createYesNoMenu } from './modal-utils';
import { CreateDefaultEmbed, createTextInput, createCheckbox, SetSeverity } from '.';
export async function closeOldTickets(client: Client) {
for (const ticket of await Database.getAllOpenPrivateHelpTickets()) {
try {
const thread = await client.channels.fetch(ticket.thread_id) as ThreadChannel;
const latestMessage = (await thread.messages.fetch({ limit: 1 })).at(0);
if (latestMessage && latestMessage.createdTimestamp <= Date.now() - 432e6) {
await Database.closePrivateHelpTicket(thread.id);
await thread.send('This ticket has been closed due to inactivity.');
// Only process stale tickets. (Tickets with 5 days since the last message.)
if (latestMessage && latestMessage.createdTimestamp > Date.now() - 432e6) continue;
thread.edit({
archived: true,
locked: true
});
}
await closeTicket(client, thread, 'This ticket has been closed due to inactivity.');
} catch (e) {
console.error('Error closing ticket due to inactivity:');
console.error(e);
console.error('Error closing ticket due to inactivity:', e);
}
}
}
export async function closeTicket(context: Client, thread: ThreadChannel, reason: string): Promise<boolean> {
try {
await Database.closePrivateHelpTicket(thread.id);
await thread.send({
embeds: [{
...CreateDefaultEmbed(context),
...SetSeverity('info'),
title: 'Ticket Closed',
description: reason,
}],
});
await thread.edit({
name: `[CLOSED] ${thread.name}`.slice(0, 100),
archived: true,
locked: true,
});
return true;
} catch (error) {
console.error('An error occured while trying to close the ticket:', error);
await thread.send({
embeds: [{
...SetSeverity('error'),
description: 'I encountered an error while trying to close this ticket.',
}],
}).catch(() => {});
return false;
}
}
export async function createPrivateHelpTicketThread(client: Client, guild: Guild, creator: GuildMember | null, reason: string, customTitle: string = '', additionalMembersToAdd: string[] = []): Promise<PrivateThreadChannel | null> {
const guildSettings = await Database.getOrCreateSettings(guild.id);
const settings = await Database.getOrCreateSettings(guild.id);
if (!guildSettings || !guildSettings.private_help_channel_id || !guildSettings.private_help_role_id) return null;
if (!settings.private_help_channel_id || !settings.private_help_role_id) return null;
const channel = await client.channels.fetch(guildSettings.private_help_channel_id) as TextChannel;
const channel = await client.channels.fetch(settings.private_help_channel_id) as TextChannel;
const thread = await channel.threads.create({
name: customTitle ? customTitle : (creator ? `${creator.displayName}'s Ticket` : 'Mod Ticket'),
@@ -54,11 +83,11 @@ export async function createPrivateHelpTicketThread(client: Client, guild: Guild
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(closeButton, claimButton);
await thread.send({
content: `${creator} feel free to direct your questions at any <@&${guildSettings.private_help_role_id}>. Only you and staff members can see this channel.\n\n**Reason for contact:**\n${reason}\n\n-# Tickets will automatically close after 5 days of inactivity.`,
content: `${creator} feel free to direct your questions at any <@&${settings.private_help_role_id}>. Only you and staff members can see this channel.\n\n**Reason for contact:**\n${reason}\n\n-# Tickets will automatically close after 5 days of inactivity.`,
components: [row],
allowedMentions: {
users: [creator.id],
roles: [guildSettings.private_help_role_id]
roles: [settings.private_help_role_id]
}
});
} else {
@@ -92,9 +121,8 @@ 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 initialMessageLabel = createTextInput('initial-message', 'Inital Message', 'The inital message sent in the thread', false, TextInputStyle.Paragraph, 1800, null);
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);
const autoJoinLabel = createCheckbox('auto-join-thread', 'Auto Join Thread', 'Whether or not to automatically add you to the thread.', true);
modal.addLabelComponents(titleLabel, initialMessageLabel, autoJoinLabel);
interaction.showModal(modal);
}
+3 -5
View File
@@ -1,4 +1,4 @@
import { Client, REST, RESTPostAPIApplicationCommandsJSONBody, Routes } from 'discord.js';
import { Client, RESTPostAPIApplicationCommandsJSONBody, Routes } from 'discord.js';
import fs from 'fs';
import path from 'path';
import { config } from '../config';
@@ -6,8 +6,6 @@ import { Command } from '../types';
const ROOT_DIR = path.resolve(__dirname, '..');
const rest = new REST({ version: '10' }).setToken(config.DISCORD_TOKEN!);
export async function refreshCommands(client: Client) {
try {
const commands: RESTPostAPIApplicationCommandsJSONBody[] = [];
@@ -49,14 +47,14 @@ export async function refreshCommands(client: Client) {
console.log('Started refreshing application (/) commands.');
console.log('Global commands: ' + commands.length);
await rest.put(
await client.rest.put(
Routes.applicationCommands(config.DISCORD_CLIENT_ID!),
{ body: commands }
);
for (const guild in guildCommands) {
console.log('Guild commands: ' + guildCommands[guild].length + ' (' + guild + ')');
await rest.put(
await client.rest.put(
Routes.applicationGuildCommands(config.DISCORD_CLIENT_ID!, guild),
{ body: guildCommands[guild] }
);
+12 -294
View File
@@ -1,302 +1,20 @@
import bodyParser from 'body-parser';
import crypto from 'crypto';
import { Client } from 'discord.js';
import express, { Request, Response } from 'express';
import session from 'express-session';
import fs from 'fs';
import MemoryStore from 'memorystore';
import path from 'path';
import { serve } from '@hono/node-server';
import { Hono } from 'hono';
import { config } from '../config';
import { Database } from '../shared/Database';
import { AltData, comprehensiveAltLookupFromE621, DiscordOAuth2 } from '../utils';
import { logDebug } from '../utils/debug-utils';
import { fixPings, removeIssueLinks } from '../utils/github-user-utils';
declare module 'express-session' {
interface SessionData {
username: string;
userId: string;
oauthState: string;
}
}
const GITHUB_REPO_ID = 169334303;
const DEV_BASE_URL = `http://localhost:${config.PORT}`;
const PROD_BASE_URL = 'https://discord.e621.net';
const OAUTH_SCOPES = ['identify', 'guilds.join'];
const PAGE_TEMPLATE = fs.readFileSync(path.join(__dirname, 'templates', 'page.html'), { encoding: 'utf-8' });
const oauth = new DiscordOAuth2({
clientId: config.DISCORD_CLIENT_ID!,
clientSecret: config.DISCORD_CLIENT_SECRET!,
redirectUri: `${config.DEV_MODE ? DEV_BASE_URL : PROD_BASE_URL}/callback`,
clientToken: config.DISCORD_TOKEN!,
credentials: Buffer.from(`${config.DISCORD_CLIENT_ID!}:${config.DISCORD_CLIENT_SECRET!}`).toString('base64')
});
const enum JoinResponse {
Success = 1,
Error = 2,
Banned = 3,
Underage = 4
};
async function joinGuild(code: string, userId: string, username: string): Promise<JoinResponse> {
let tokenResponse;
try {
if (Number.isNaN(userId)) return JoinResponse.Error;
if (!username) return JoinResponse.Error;
const id = Number(userId);
tokenResponse = await oauth.getAccessToken(code, OAUTH_SCOPES);
const user = await oauth.getUser(tokenResponse.access_token);
if (!user.id || !user.username) {
console.error(`Error joining user (${userId}) to discord. User object missing id or username.`);
console.error(user);
return JoinResponse.Error;
}
await Database.putUser(id, user);
const alts = await comprehensiveAltLookupFromE621(id, null);
if (await checkAltsForFullBans([alts])) return JoinResponse.Banned;
const response = await oauth.addMember({
accessToken: tokenResponse.access_token,
guildId: config.DISCORD_GUILD_ID!,
userId: user.id,
nickname: username
});
if (config.DEBUG) console.log(response);
if (!response) return JoinResponse.Error;
} catch (e: any) {
if (e.code == 40007) return JoinResponse.Banned;
else if (e.code == 20024) return JoinResponse.Underage;
console.error(`Error joining user (${userId}) to discord:`);
console.error(e);
return JoinResponse.Error;
} finally {
if (tokenResponse) await oauth.revokeToken(tokenResponse.access_token);
}
return JoinResponse.Success;
}
async function handleInitial(req: Request, res: Response): Promise<any> {
const { username, user_id, time, hash } = req.query;
if (!username || !user_id || !time || !hash) {
return sendBadRequest(res, 'Missing parameters');
}
if (Number.isNaN(time) || Date.now() / 1000 > Number(time)) {
return render(res, 403, 'You took too long to authorize the request. Please try again.');
}
const authString = `${username} ${user_id} ${time} ${config.LINK_SECRET}`;
const digest = crypto.createHash('sha256').update(authString).digest('hex');
if (hash !== digest) {
console.error(`Bad auth: ${hash} ${digest}`);
return sendForbidden(res, 'Bad auth');
}
const oauthState = crypto.randomBytes(16).toString('hex');
const oauthUrl = await oauth.generateOauth2Url({
state: oauthState,
scope: OAUTH_SCOPES,
type: 'code'
});
req.session.username = username as string;
req.session.userId = user_id as string;
req.session.oauthState = oauthState;
req.session.save((e) => {
if (e) {
console.error('Error saving session:');
console.error(e);
return sendInteralServerError(res);
}
res.redirect(oauthUrl);
});
}
async function handleCallback(req: Request, res: Response): Promise<any> {
if (!req.session.userId || !req.session.username || !req.session.oauthState) {
return sendForbidden(res, 'Session details missing');
}
const state = req.query.state as string;
if (state != req.session.oauthState) {
console.error('OAuth state mismatch on discord joining');
return sendForbidden(res, 'OAuth state mismatch');
}
const code = req.query.code as string;
const userId = req.session.userId;
const username = req.session.username;
req.session.destroy((e) => {
if (e) console.error(e);
});
try {
const response = await joinGuild(code, userId, username);
if (response == JoinResponse.Error) {
console.error(`Error joining user: ${username} (${userId})`);
return sendInteralServerError(res, 'Unable to join user to guild. Retry later. If issue persists, please contact staff.');
} else if (response == JoinResponse.Banned) {
return sendForbidden(res, 'User is banned.');
} else if (response == JoinResponse.Underage) {
return sendForbidden(res, 'Discord account flagged as underage by discord.');
}
} catch (e) {
console.error(e);
return sendInteralServerError(res);
}
render(res, 200, 'Success', `You have been added to the server. <a href="https://discord.com/channels/${config.DISCORD_GUILD_ID}">See you there.</a>`);
}
function sendInteralServerError(res: Response, message: string = '') {
render(res, 500, 'Internal Server Error', message);
}
function sendForbidden(res: Response, message: string = '') {
render(res, 403, 'Forbidden', message);
}
function sendBadRequest(res: Response, message: string = '') {
render(res, 400, 'Bad Request', message);
}
function render(res: Response, code: number, title: string = '', message: string = '') {
res.status(code).setHeader('Content-Type', 'text/html').send(PAGE_TEMPLATE.replaceAll('{{ title }}', title).replaceAll('{{ message }}', message));
}
async function handleGithubRelease(client: Client, req: Request, res: Response): Promise<any> {
logDebug('Received github release webhook');
const signature = (req.headers['x-hub-signature-256'] as string).split('=')[1];
const computedSignature = crypto.createHmac('sha256', config.RELEASE_SECRET!).update(req.body).digest('hex');
if (signature !== computedSignature) {
console.error('Github release webhook signature mismatch');
return res.sendStatus(401);
}
res.sendStatus(200);
const data = JSON.parse(req.body);
logDebug(`Release webhook data:\n${JSON.stringify(data, null, 4)}`);
if (data.action != 'published' || data.repository.id != GITHUB_REPO_ID) return;
const settings = await Database.getOrCreateSettings(config.DISCORD_GUILD_ID!);
if (!settings || !settings.github_release_channel) return;
const channel = await client.channels.fetch(settings.github_release_channel);
if (!channel || !channel.isSendable()) {
console.error(`Github release channel ${channel ? 'sendable' : 'found'}`);
return;
}
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const date = new Date();
let message = `## [${months[date.getUTCMonth()]} ${date.getUTCDate()}, ${date.getUTCFullYear()}](<${data.release.html_url}>)\n\n${settings.site_breaker_role_id ? `<@&${settings.site_breaker_role_id}>\n` : ''}${await fixPings(removeIssueLinks(data.release.body))}`;
logDebug('Sending github release message');
const MAX_MESSAGE_LENGTH = 2000;
const ADDITIONAL_PART = '...\n\nYou may view the full changelog on github.';
if (message.length > MAX_MESSAGE_LENGTH) {
const splitMessage = message.split('\n');
message = '';
for (const part of splitMessage) {
if (message.length + part.length + 1 >= MAX_MESSAGE_LENGTH - ADDITIONAL_PART.length) break;
message += `${part}\n`;
}
message += ADDITIONAL_PART;
}
const sentMessage = await channel.send(message);
await sentMessage.startThread({ name: data.release.tag_name });
logDebug('Github webhook processed');
}
async function checkAltsForFullBans(altData: AltData[]): Promise<boolean> {
for (const data of altData) {
if (data.type == 'discord') {
try {
const banData = await Database.getBan(data.thisId as string);
if (banData?.full_ban) return true;
} catch (e) {
console.error(e);
}
}
if (await checkAltsForFullBans(data.alts)) return true;
}
return false;
}
import routes from './routes';
export function initializeWebserver(client: Client) {
const app = express();
const app = new Hono();
const Store = MemoryStore(session);
routes.forEach(route => app.route(route.route, route.builder(client)));
app.set('trust proxy', 1);
app.use(session({
secret: config.DISCORD_CLIENT_SECRET!,
cookie: {
secure: !config.DEV_MODE,
httpOnly: !config.DEV_MODE,
sameSite: false,
maxAge: 300000
},
store: new Store({
checkPeriod: 600000,
}),
resave: false,
saveUninitialized: false
}));
app.get('/', handleInitial);
app.get('/callback', handleCallback);
app.use(bodyParser.raw({ type: 'application/json' }));
app.post('/release', handleGithubRelease.bind(null, client));
app.listen(config.PORT, (error) => {
if (error) {
throw error;
}
console.log(`Listening on port ${config.PORT}`);
const server = serve({
fetch: app.fetch,
port: config.PORT
}, (info) => {
console.log(`Listening on port ${info.port}`);
});
return server;
}
+273
View File
@@ -0,0 +1,273 @@
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import { Hono, type Context } from 'hono';
import { getCookie, setCookie, deleteCookie } from 'hono/cookie';
import { ContentfulStatusCode } from 'hono/utils/http-status';
import { config } from '../../config';
import { Database } from '../../shared/Database';
import { AltData, comprehensiveAltLookupFromE621, DiscordOAuth2 } from '../../utils';
const DEV_BASE_URL = `http://localhost:${config.PORT}`;
const PROD_BASE_URL = 'https://discord.e621.net';
const OAUTH_SCOPES = ['identify', 'guilds.join'];
const PAGE_TEMPLATE = fs.readFileSync(path.join(__dirname, '..', 'templates', 'page.html'), { encoding: 'utf-8' });
const SESSION_COOKIE = 'discord_oauth_session';
const SESSION_MAX_AGE = 300;
interface SessionData {
username?: string;
userId?: string;
oauthState?: string;
expiresAt: number;
}
const sessions = new Map<string, SessionData>();
const oauth = new DiscordOAuth2({
clientId: config.DISCORD_CLIENT_ID!,
clientSecret: config.DISCORD_CLIENT_SECRET!,
redirectUri: `${config.DEV_MODE ? DEV_BASE_URL : PROD_BASE_URL}/callback`,
clientToken: config.DISCORD_TOKEN!,
credentials: Buffer
.from(`${config.DISCORD_CLIENT_ID!}:${config.DISCORD_CLIENT_SECRET!}`)
.toString('base64')
});
const enum JoinResponse {
Success = 1,
Error = 2,
Banned = 3,
Underage = 4
};
// Cleanup expired sessions.
function cleanupSessions(): void {
const now = Date.now();
for (const [id, session] of sessions) {
if (session.expiresAt <= now) sessions.delete(id);
}
}
setInterval(cleanupSessions, 600_000).unref();
function getSession(c: Context): SessionData | undefined {
const sessionId = getCookie(c, SESSION_COOKIE);
if (!sessionId) return undefined;
const session = sessions.get(sessionId);
if (!session) return undefined;
if (session.expiresAt <= Date.now()) {
sessions.delete(sessionId);
return undefined;
}
return session;
}
function createSession(c: Context, data: Omit<SessionData, 'expiresAt'>): void {
const sessionId = crypto.randomBytes(32).toString('hex');
sessions.set(sessionId, {
...data,
expiresAt: Date.now() + SESSION_MAX_AGE * 1000
});
setCookie(c, SESSION_COOKIE, sessionId, {
maxAge: SESSION_MAX_AGE,
httpOnly: !config.DEV_MODE,
secure: !config.DEV_MODE,
sameSite: 'Lax',
path: '/'
});
}
function destroySession(c: Context): void {
const sessionId = getCookie(c, SESSION_COOKIE);
if (sessionId)
sessions.delete(sessionId);
deleteCookie(c, SESSION_COOKIE, {
path: '/'
});
}
async function joinGuild(code: string, userId: string, username: string): Promise<JoinResponse> {
let tokenResponse;
try {
if (Number.isNaN(Number(userId)) || !username) return JoinResponse.Error;
tokenResponse = await oauth.getAccessToken(code, OAUTH_SCOPES);
const user = await oauth.getUser(tokenResponse.access_token);
if (!user.id || !user.username) {
console.error(`Error joining user (${userId}) to discord. User object missing id or username.`, user);
return JoinResponse.Error;
}
const id = Number(userId);
await Database.putUser(id, user);
const alts = await comprehensiveAltLookupFromE621(id, null);
if (await checkAltsForFullBans([alts])) return JoinResponse.Banned;
const response = await oauth.addMember({
accessToken: tokenResponse.access_token,
guildId: config.DISCORD_GUILD_ID!,
userId: user.id,
nickname: username
});
if (config.DEBUG) console.log(response);
if (!response) return JoinResponse.Error;
} catch (e: any) {
switch (e.code) {
case 40007:
return JoinResponse.Banned;
case 20024:
return JoinResponse.Underage;
}
console.error(`Error joining user (${userId}) to discord:`, e);
return JoinResponse.Error;
} finally {
if (tokenResponse)
await oauth.revokeToken(tokenResponse.access_token);
}
return JoinResponse.Success;
}
async function handleInitial(c: Context): Promise<Response> {
const query = c.req.query();
const username = query.username;
const userId = query.user_id;
const time = query.time;
const hash = query.hash;
if (!username || !userId || !time || !hash)
return sendBadRequest(c, 'Missing parameters');
const timestamp = Number(time);
if (Number.isNaN(timestamp) || Date.now() / 1000 > timestamp)
return render(c, 403, 'You took too long to authorize the request. Please try again.');
const authString = `${username} ${userId} ${time} ${config.LINK_SECRET}`;
const digest = crypto.createHash('sha256').update(authString).digest('hex');
if (hash !== digest) {
console.error(`Bad auth: ${hash} ${digest}`);
return sendForbidden(c, 'Bad auth');
}
const oauthState = crypto.randomBytes(16).toString('hex');
const oauthUrl = oauth.generateOauth2Url({
state: oauthState,
scope: OAUTH_SCOPES,
type: 'code'
});
createSession(c, { username, userId, oauthState });
return c.redirect(oauthUrl);
}
async function handleCallback(c: Context): Promise<Response> {
const session = getSession(c);
if (!session?.userId || !session.username || !session.oauthState)
return sendForbidden(c, 'Session details missing');
const query = c.req.query();
const state = query.state;
if (state !== session.oauthState) {
console.error('OAuth state mismatch on discord joining');
return sendForbidden(c, 'OAuth state mismatch');
}
const code = query.code;
if (!code)
return sendBadRequest(c, 'Missing OAuth code');
const userId = session.userId;
const username = session.username;
destroySession(c);
try {
const response = await joinGuild(code, userId, username);
switch (response) {
case JoinResponse.Error:
console.error(`Error joining user: ${username} (${userId})`);
return sendInternalServerError(c, 'Unable to join user to guild. Retry later. If issue persists, please contact staff.');
case JoinResponse.Banned:
return sendForbidden(c, 'User is banned.');
case JoinResponse.Underage:
return sendForbidden(c, 'Discord account flagged as underage by discord.');
}
} catch (e) {
console.error(e);
return sendInternalServerError(c);
}
return render(c, 200, 'Success', `You have been added to the server. <a href="https://discord.com/channels/${config.DISCORD_GUILD_ID}">See you there.</a>`);
}
function sendInternalServerError(c: Context, message: string = ''): Response {
return render(c, 500, 'Internal Server Error', message);
}
function sendForbidden(c: Context, message: string = ''): Response {
return render(c, 403, 'Forbidden', message);
}
function sendBadRequest(c: Context, message: string = ''): Response {
return render(c, 400, 'Bad Request', message);
}
function render(c: Context, code: ContentfulStatusCode, title: string = '', message: string = ''): Response {
const html = PAGE_TEMPLATE
.replaceAll('{{ title }}', title)
.replaceAll('{{ message }}', message);
return c.html(html, code);
}
async function checkAltsForFullBans(altData: AltData[]): Promise<boolean> {
for (const data of altData) {
if (data.type === 'discord') {
try {
const banData = await Database.getBan(data.thisId as string);
if (banData?.full_ban) return true;
} catch (e) {
console.error(e);
}
}
if (await checkAltsForFullBans(data.alts)) return true;
}
return false;
}
export default {
route: '/',
builder: (): Hono => {
const app = new Hono();
app.get('/', c => handleInitial(c));
app.get('/callback', c => handleCallback(c));
return app;
}
};
+122
View File
@@ -0,0 +1,122 @@
import crypto from 'crypto';
import { Client } from 'discord.js';
import { Hono, type Context } from 'hono';
import { config } from '../../config';
import { Database } from '../../shared/Database';
import { fixPings, logDebug, removeIssueLinks } from '../../utils';
const GITHUB_REPO_ID = 169334303;
async function handleGithubRelease(client: Client, c: Context): Promise<Response> {
logDebug('Received github release webhook');
/*
Intentionally read the raw request body here.
GitHub signs the raw bytes, so parsing the body first
would potentially invalidate the signature.
*/
const rawBody = await c.req.raw.arrayBuffer();
const signatureHeader = c.req.header('x-hub-signature-256');
if (!signatureHeader) {
console.error('Github release webhook signature missing');
return c.body(null, 401);
}
const signature = signatureHeader.split('=')[1];
if (!signature) {
console.error('Github release webhook signature malformed');
return c.body(null, 401);
}
const computedSignature = crypto.createHmac('sha256', config.RELEASE_SECRET!)
.update(Buffer.from(rawBody)).digest('hex');
// Use timingSafeEqual rather than a normal string comparison for the HMAC.
const providedBuffer = Buffer.from(signature, 'hex');
const computedBuffer = Buffer.from(computedSignature, 'hex');
if (providedBuffer.length !== computedBuffer.length || !crypto.timingSafeEqual(providedBuffer, computedBuffer)) {
console.error('Github release webhook signature mismatch');
return c.body(null, 401);
}
void processGithubRelease(client, Buffer.from(rawBody));
return c.body(null, 200);
}
async function processGithubRelease(client: Client, rawBody: Buffer): Promise<void> {
try {
const data = JSON.parse(rawBody.toString('utf-8'));
logDebug(`Release webhook data:\n${JSON.stringify(data, null, 4)}`);
if (data.action !== 'published' || data.repository.id !== GITHUB_REPO_ID) return;
const settings = await Database.getOrCreateSettings(config.DISCORD_GUILD_ID!);
if (!settings.github_release_channel) return;
const channel = await client.channels.fetch(settings.github_release_channel);
if (!channel || !channel.isSendable()) {
console.error(`Github release channel not ${channel ? 'sendable' : 'found'}`);
return;
}
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
const date = new Date();
let message = `## [${months[date.getUTCMonth()]} ${date.getUTCDate()}, ${date.getUTCFullYear()}](<${data.release.html_url}>)\n\n${settings.site_breaker_role_id ? `<@&${settings.site_breaker_role_id}>\n` : ''}${await fixPings(removeIssueLinks(data.release.body))}`;
logDebug('Sending github release message');
const MAX_MESSAGE_LENGTH = 2000;
const ADDITIONAL_PART = '...\n\nYou may view the full changelog on github.';
if (message.length > MAX_MESSAGE_LENGTH) {
const splitMessage = message.split('\n');
message = '';
for (const part of splitMessage) {
if (message.length + part.length + 1 >= MAX_MESSAGE_LENGTH - ADDITIONAL_PART.length) break;
message += `${part}\n`;
}
message += ADDITIONAL_PART;
}
const sentMessage = await channel.send(message);
await sentMessage.startThread({
name: data.release.tag_name
});
logDebug('Github webhook processed');
} catch (e) {
console.error('Error processing Github release webhook:', e);
}
}
export default {
route: '/',
builder: (client: Client): Hono => {
const app = new Hono();
app.post('/release', c => handleGithubRelease(client, c));
return app;
}
};
+4
View File
@@ -0,0 +1,4 @@
import discord from './discord';
import github from './github';
export default [discord, github];