lint, reformat, make the github action work (#24)
diff --git a/.prettierignore b/.prettierignore
index 7575e2d..6deb598 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -2,11 +2,14 @@
.history/
node_modules/
src/config/*
+
+!src/config/*.d.ts
!src/config/format.ts
-!src/config/default.json
+!src/config/default.ts
!src/config/emojis.json
-!src/config/main.ts
+src/config/main.ts
.vscode/
+.vim/
yarn-error.log
yarn.lock
src/utils/temp/*.png
@@ -15,4 +18,6 @@
src/utils/temp/*.jpg
ClicksMigratingProblems/oldData/
-ClicksMigratingProblems/oldData copy/
\ No newline at end of file
+ClicksMigratingProblems/oldData copy/
+
+.direnv/
diff --git a/package.json b/package.json
index 153e81e..2f63ea6 100644
--- a/package.json
+++ b/package.json
@@ -36,7 +36,7 @@
"lint": "echo 'Style checking...'; prettier --check .; echo 'Linting...'; eslint src; echo 'To auto-fix everything possible, please run `yarn lint-fix`'; true",
"lint-fix": "echo 'Fixing eslint issues...'; eslint src --fix; echo 'Reformatting...'; prettier --write --loglevel warn --cache .; true",
"lint-list": "echo 'Style checking...'; prettier --check .; echo 'Linting...'; eslint src; echo 'To view errors in more detail, please run `yarn lint`'; true",
- "lint-ci" : "echo 'Style checking...' && prettier --check . && echo 'Linting...' && eslint src",
+ "lint-ci": "echo 'Style checking...' && prettier --check . && echo 'Linting...' && eslint src",
"setup": "node Installer.js",
"win-force-build": "clear | rm -r dist | tsc-suppress"
},
diff --git a/src/Unfinished/all.ts b/src/Unfinished/all.ts
index eea33f5..b5b7d89 100644
--- a/src/Unfinished/all.ts
+++ b/src/Unfinished/all.ts
@@ -16,9 +16,7 @@
import client from "../utils/client.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
- builder
- .setName("all")
- .setDescription("Gives or removes a role from everyone");
+ builder.setName("all").setDescription("Gives or removes a role from everyone");
class Filter {
name: string;
@@ -244,13 +242,17 @@
.setLabel("Apply")
.setStyle(ButtonStyle.Primary)
.setCustomId("apply")
- .setEmoji(client.emojis.cache.get(getEmojiByName("CONTROL.TICK", "id"))! as APIMessageComponentEmoji)
+ .setEmoji(
+ client.emojis.cache.get(getEmojiByName("CONTROL.TICK", "id"))! as APIMessageComponentEmoji
+ )
.setDisabled(affected.length === 0),
new ButtonBuilder()
.setLabel("Add filter")
.setStyle(ButtonStyle.Primary)
.setCustomId("add")
- .setEmoji(client.emojis.cache.get(getEmojiByName("ICONS.FILTER", "id"))! as APIMessageComponentEmoji)
+ .setEmoji(
+ client.emojis.cache.get(getEmojiByName("ICONS.FILTER", "id"))! as APIMessageComponentEmoji
+ )
.setDisabled(filters.length >= 25)
])
]
diff --git a/src/Unfinished/categorizationTest.ts b/src/Unfinished/categorizationTest.ts
index ff2d66b..763669c 100644
--- a/src/Unfinished/categorizationTest.ts
+++ b/src/Unfinished/categorizationTest.ts
@@ -1,5 +1,14 @@
import { LoadingEmbed } from "../utils/defaults.js";
-import { CommandInteraction, GuildChannel, ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelType, StringSelectMenuBuilder, APIMessageComponentEmoji } from "discord.js";
+import {
+ CommandInteraction,
+ GuildChannel,
+ ActionRowBuilder,
+ ButtonBuilder,
+ ButtonStyle,
+ ChannelType,
+ StringSelectMenuBuilder,
+ APIMessageComponentEmoji
+} from "discord.js";
import { SlashCommandBuilder } from "discord.js";
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
import client from "../utils/client.js";
@@ -24,7 +33,7 @@
staff: ["staff", "mod", "admin", "helper", "train"],
spam: ["spam", "count"],
logs: ["log"],
- other: ["random", "starboard"],
+ other: ["random", "starboard"]
};
for (const c of channels.values()) {
for (const type in types) {
@@ -75,12 +84,16 @@
.setCustomId("accept")
.setStyle(ButtonStyle.Success)
.setDisabled(predicted[channel].length === 0)
- .setEmoji(client.emojis.cache.get(getEmojiByName("ICONS.TICK", "id")) as APIMessageComponentEmoji),
+ .setEmoji(
+ client.emojis.cache.get(getEmojiByName("ICONS.TICK", "id")) as APIMessageComponentEmoji
+ ),
new ButtonBuilder()
.setLabel('Use "Other"')
.setCustomId("reject")
.setStyle(ButtonStyle.Secondary)
- .setEmoji(client.emojis.cache.get(getEmojiByName("ICONS.CROSS", "id")) as APIMessageComponentEmoji)
+ .setEmoji(
+ client.emojis.cache.get(getEmojiByName("ICONS.CROSS", "id")) as APIMessageComponentEmoji
+ )
])
]
});
@@ -88,7 +101,13 @@
try {
i = await m.awaitMessageComponent({
time: 300000,
- filter: (i) => { return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.message.id === m.id}
+ filter: (i) => {
+ return (
+ i.user.id === interaction.user.id &&
+ i.channel!.id === interaction.channel!.id &&
+ i.message.id === m.id
+ );
+ }
});
} catch (e) {
return await interaction.editReply({
diff --git a/src/actions/createModActionTicket.ts b/src/actions/createModActionTicket.ts
index d86c14a..ea85255 100644
--- a/src/actions/createModActionTicket.ts
+++ b/src/actions/createModActionTicket.ts
@@ -1,4 +1,4 @@
-import { getCommandMentionByName } from './../utils/getCommandDataByName.js';
+import { getCommandMentionByName } from "./../utils/getCommandDataByName.js";
import Discord, { ActionRowBuilder, ButtonBuilder, OverwriteType, ChannelType, ButtonStyle } from "discord.js";
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
import getEmojiByName from "../utils/getEmojiByName.js";
@@ -13,11 +13,13 @@
) {
const config = await client.database.guilds.read(guild.id);
const { log, NucleusColors, entry, renderUser, renderChannel, renderDelta } = client.logger;
- const overwrites = [{
- id: user,
- allow: ["ViewChannel", "SendMessages", "AttachFiles", "AddReactions", "ReadMessageHistory"],
- type: OverwriteType.Member
- }] as unknown as Discord.OverwriteResolvable[];
+ const overwrites = [
+ {
+ id: user,
+ allow: ["ViewChannel", "SendMessages", "AttachFiles", "AddReactions", "ReadMessageHistory"],
+ type: OverwriteType.Member
+ }
+ ] as unknown as Discord.OverwriteResolvable[];
overwrites.push({
id: guild.roles.everyone,
deny: ["ViewChannel"],
@@ -30,7 +32,9 @@
type: OverwriteType.Role
});
}
- const targetChannel: Discord.CategoryChannel | Discord.TextChannel = (await guild.channels.fetch(config.tickets.category!))! as Discord.CategoryChannel | Discord.TextChannel;
+ const targetChannel: Discord.CategoryChannel | Discord.TextChannel = (await guild.channels.fetch(
+ config.tickets.category!
+ ))! as Discord.CategoryChannel | Discord.TextChannel;
let c: Discord.TextChannel | Discord.PrivateThreadChannel;
if (targetChannel.type === Discord.ChannelType.GuildCategory) {
@@ -83,10 +87,10 @@
.setTitle("New Ticket")
.setDescription(
"Ticket created by a Moderator\n" +
- `**Support type:** ${customReason ? customReason : "Appeal submission"}\n` +
- (reason !== null ? `**Reason:**\n> ${reason}\n` : "") +
- `**Ticket ID:** \`${c.id}\`\n` +
- `Type ${getCommandMentionByName("ticket/close")} to close this ticket.`
+ `**Support type:** ${customReason ? customReason : "Appeal submission"}\n` +
+ (reason !== null ? `**Reason:**\n> ${reason}\n` : "") +
+ `**Ticket ID:** \`${c.id}\`\n` +
+ `Type ${getCommandMentionByName("ticket/close")} to close this ticket.`
)
.setStatus("Success")
.setEmoji("GUILD.TICKET.OPEN")
@@ -105,11 +109,12 @@
return null;
}
} else {
- c = await targetChannel.threads.create({name: `${user.username} - ${user.id} - Active`,
- autoArchiveDuration: 60 * 24 * 7,
- type: Discord.ChannelType.PrivateThread,
- reason: "Creating ticket"
- }) as Discord.PrivateThreadChannel;
+ c = (await targetChannel.threads.create({
+ name: `${user.username} - ${user.id} - Active`,
+ autoArchiveDuration: 60 * 24 * 7,
+ type: Discord.ChannelType.PrivateThread,
+ reason: "Creating ticket"
+ })) as Discord.PrivateThreadChannel;
c.members.add(user.id);
c.members.add(createdBy.id);
try {
@@ -128,10 +133,10 @@
.setTitle("New Ticket")
.setDescription(
"Ticket created by a Moderator\n" +
- `**Support type:** ${customReason ? customReason : "Appeal submission"}\n` +
- (reason !== null ? `**Reason:**\n> ${reason}\n` : "") +
- `**Ticket ID:** \`${c.id}\`\n` +
- `Type ${getCommandMentionByName("ticket/close")} to close this ticket.`
+ `**Support type:** ${customReason ? customReason : "Appeal submission"}\n` +
+ (reason !== null ? `**Reason:**\n> ${reason}\n` : "") +
+ `**Ticket ID:** \`${c.id}\`\n` +
+ `Type ${getCommandMentionByName("ticket/close")} to close this ticket.`
)
.setStatus("Success")
.setEmoji("GUILD.TICKET.OPEN")
@@ -162,7 +167,7 @@
list: {
ticketFor: entry(user.id, renderUser(user)),
createdBy: entry(createdBy.id, renderUser(createdBy)),
- created: entry((Date.now()).toString(), renderDelta(Date.now())),
+ created: entry(Date.now().toString(), renderDelta(Date.now())),
ticketChannel: entry(c.id, renderChannel(c))
},
hidden: {
diff --git a/src/actions/roleMenu.ts b/src/actions/roleMenu.ts
index be58d99..8b15539 100644
--- a/src/actions/roleMenu.ts
+++ b/src/actions/roleMenu.ts
@@ -1,4 +1,4 @@
-import { unknownServerIcon } from './../utils/defaults.js';
+import { unknownServerIcon } from "./../utils/defaults.js";
import {
ButtonBuilder,
CommandInteraction,
@@ -16,9 +16,9 @@
import client from "../utils/client.js";
import { LoadingEmbed } from "../utils/defaults.js";
import type { GuildConfig } from "../utils/database.js";
-import { roleException } from '../utils/createTemporaryStorage.js';
-import addPlural from '../utils/plurals.js';
-import createPageIndicator from '../utils/createPageIndicator.js';
+import { roleException } from "../utils/createTemporaryStorage.js";
+import addPlural from "../utils/plurals.js";
+import createPageIndicator from "../utils/createPageIndicator.js";
export interface RoleMenuSchema {
guild: string;
@@ -42,23 +42,29 @@
}[];
}
-export const configToDropdown = (placeholder: string, currentPageData: ObjectSchema, selectedRoles?: string[]): ActionRowBuilder<StringSelectMenuBuilder> => {
+export const configToDropdown = (
+ placeholder: string,
+ currentPageData: ObjectSchema,
+ selectedRoles?: string[]
+): ActionRowBuilder<StringSelectMenuBuilder> => {
return new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
new StringSelectMenuBuilder()
.setCustomId("roles")
.setPlaceholder(placeholder)
.setMinValues(currentPageData.min)
.setMaxValues(currentPageData.max)
- .addOptions(currentPageData.options.map((option: {name: string; description: string | null; role: string;}) => {
- const builder = new StringSelectMenuOptionBuilder()
- .setLabel(option.name)
- .setValue(option.role)
- .setDefault(selectedRoles ? selectedRoles.includes(option.role) : false);
- if (option.description) builder.setDescription(option.description);
- return builder;
- }))
- )
-}
+ .addOptions(
+ currentPageData.options.map((option: { name: string; description: string | null; role: string }) => {
+ const builder = new StringSelectMenuOptionBuilder()
+ .setLabel(option.name)
+ .setValue(option.role)
+ .setDefault(selectedRoles ? selectedRoles.includes(option.role) : false);
+ if (option.description) builder.setDescription(option.description);
+ return builder;
+ })
+ )
+ );
+};
export async function callback(interaction: CommandInteraction | ButtonInteraction) {
if (!interaction.member) return;
@@ -69,7 +75,9 @@
embeds: [
new EmojiEmbed()
.setTitle("Roles")
- .setDescription("Self roles are currently disabled. Please contact a staff member or try again later.")
+ .setDescription(
+ "Self roles are currently disabled. Please contact a staff member or try again later."
+ )
.setStatus("Danger")
.setEmoji("GUILD.GREEN")
],
@@ -80,21 +88,24 @@
embeds: [
new EmojiEmbed()
.setTitle("Roles")
- .setDescription("There are no roles available. Please contact a staff member if you believe this is a mistake.")
+ .setDescription(
+ "There are no roles available. Please contact a staff member if you believe this is a mistake."
+ )
.setStatus("Danger")
.setEmoji("GUILD.GREEN")
],
ephemeral: true
});
const m = await interaction.reply({ embeds: LoadingEmbed, ephemeral: true, fetchReply: true });
- if (config.roleMenu.allowWebUI) { // TODO: Make rolemenu web ui
- const loginMethods: {webUI: boolean} = {
+ if (config.roleMenu.allowWebUI) {
+ // TODO: Make rolemenu web ui
+ const loginMethods: { webUI: boolean } = {
webUI: false
- }
+ };
try {
const status = await fetch(client.config.baseUrl).then((res) => res.status);
if (status !== 200) loginMethods.webUI = false;
- } catch(e) {
+ } catch (e) {
loginMethods.webUI = false;
}
if (Object.values(loginMethods).some((i) => i)) {
@@ -105,7 +116,7 @@
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let valid = false;
while (!valid) {
- itt ++;
+ itt++;
code = "";
for (let i = 0; i < length; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
@@ -113,7 +124,7 @@
if (code in client.roleMenu) continue;
if (itt > 1000) {
itt = 0;
- length ++;
+ length++;
continue;
}
valid = true;
@@ -143,10 +154,7 @@
.setStyle(ButtonStyle.Link)
.setDisabled(!loginMethods.webUI)
.setURL(`${client.config.baseUrl}nucleus/rolemenu?code=${code}`),
- new ButtonBuilder()
- .setLabel("In Discord")
- .setStyle(ButtonStyle.Primary)
- .setCustomId("discord")
+ new ButtonBuilder().setLabel("In Discord").setStyle(ButtonStyle.Primary).setCustomId("discord")
])
]
});
@@ -154,7 +162,13 @@
try {
component = await m.awaitMessageComponent({
time: 300000,
- filter: (i) => { return i.user.id === interaction.user.id && i.channelId === interaction.channelId && i.message.id === m.id}
+ filter: (i) => {
+ return (
+ i.user.id === interaction.user.id &&
+ i.channelId === interaction.channelId &&
+ i.message.id === m.id
+ );
+ }
});
} catch (e) {
console.log(e);
@@ -168,22 +182,26 @@
const selectedRoles: string[][] = [];
const maxPage = options.length;
const completedPages: boolean[] = options.map((option) => option.min === 0);
- for (let i = 0; i < maxPage; i++) { selectedRoles.push([]); }
+ for (let i = 0; i < maxPage; i++) {
+ selectedRoles.push([]);
+ }
let page = 0;
let complete = completedPages.every((page) => page);
let done = false;
while (!(complete && done)) {
- const currentPageData = options[page]!
+ const currentPageData = options[page]!;
const embed = new EmojiEmbed()
.setTitle("Roles")
.setDescription(
`**${currentPageData.name}**\n` +
- `> ${currentPageData.description}\n\n` +
- (currentPageData.min === currentPageData.max ? `Select ${addPlural(currentPageData.min, "role")}` :
- `Select between ${currentPageData.min} and ${currentPageData.max} roles then press next`) + "\n\n" +
- createPageIndicator(maxPage, page)
+ `> ${currentPageData.description}\n\n` +
+ (currentPageData.min === currentPageData.max
+ ? `Select ${addPlural(currentPageData.min, "role")}`
+ : `Select between ${currentPageData.min} and ${currentPageData.max} roles then press next`) +
+ "\n\n" +
+ createPageIndicator(maxPage, page)
)
.setStatus("Success")
.setEmoji("GUILD.GREEN");
@@ -215,7 +233,13 @@
try {
component = await m.awaitMessageComponent({
time: 300000,
- filter: (i) => { return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.message.id === m.id}
+ filter: (i) => {
+ return (
+ i.user.id === interaction.user.id &&
+ i.channel!.id === interaction.channel!.id &&
+ i.message.id === m.id
+ );
+ }
});
} catch (e) {
console.log(e);
@@ -230,7 +254,7 @@
done = true;
} else if (component.customId === "roles" && component.isStringSelectMenu()) {
selectedRoles[page] = component.values;
- completedPages[page] = true
+ completedPages[page] = true;
page = Math.min(maxPage - 1, page + 1);
}
complete = completedPages.every((page) => page);
@@ -238,14 +262,15 @@
const fullRoleList: string[] = selectedRoles.flat();
- const memberRoles = (interaction.member.roles as GuildMemberRoleManager).cache.map((r) => r.id); // IDs
- let rolesToRemove = config.roleMenu.options.map((o) => o.options.map((o) => o.role)).flat(); // IDs
- rolesToRemove = rolesToRemove.filter((r) => memberRoles.includes(r)).filter((r) => !fullRoleList.includes(r)) // IDs
- let roleObjectsToAdd = fullRoleList.map((r) => interaction.guild!.roles.cache.get(r)) // Role objects
+ const memberRoles = (interaction.member.roles as GuildMemberRoleManager).cache.map((r) => r.id); // IDs
+ let rolesToRemove = config.roleMenu.options.map((o) => o.options.map((o) => o.role)).flat(); // IDs
+ rolesToRemove = rolesToRemove.filter((r) => memberRoles.includes(r)).filter((r) => !fullRoleList.includes(r)); // IDs
+ let roleObjectsToAdd = fullRoleList
+ .map((r) => interaction.guild!.roles.cache.get(r)) // Role objects
.filter((r) => r !== undefined) as Role[];
- roleObjectsToAdd = roleObjectsToAdd.filter((r) => !memberRoles.includes(r.id)); // Role objects
+ roleObjectsToAdd = roleObjectsToAdd.filter((r) => !memberRoles.includes(r.id)); // Role objects
try {
- roleException(interaction.guild.id, interaction.user.id)
+ roleException(interaction.guild.id, interaction.user.id);
await (interaction.member.roles as GuildMemberRoleManager).remove(rolesToRemove);
await (interaction.member.roles as GuildMemberRoleManager).add(roleObjectsToAdd);
} catch (e) {
diff --git a/src/actions/tickets/create.ts b/src/actions/tickets/create.ts
index 237790e..26236d8 100644
--- a/src/actions/tickets/create.ts
+++ b/src/actions/tickets/create.ts
@@ -1,4 +1,10 @@
-import Discord, { ActionRowBuilder, ButtonBuilder, ButtonStyle, CommandInteraction, ButtonInteraction } from "discord.js";
+import Discord, {
+ ActionRowBuilder,
+ ButtonBuilder,
+ ButtonStyle,
+ CommandInteraction,
+ ButtonInteraction
+} from "discord.js";
import { tickets, toHexArray } from "../../utils/calculate.js";
import client from "../../utils/client.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
@@ -32,14 +38,18 @@
});
}
let count = 0;
- const targetChannel: Discord.CategoryChannel | Discord.TextChannel = (await interaction.guild.channels.fetch(config.tickets.category))! as Discord.CategoryChannel | Discord.TextChannel;
+ const targetChannel: Discord.CategoryChannel | Discord.TextChannel = (await interaction.guild.channels.fetch(
+ config.tickets.category
+ ))! as Discord.CategoryChannel | Discord.TextChannel;
if (targetChannel.type === Discord.ChannelType.GuildCategory) {
// For channels, the topic is the user ID, then the word Active
const category = targetChannel as Discord.CategoryChannel;
category.children.cache.forEach((element) => {
if (!(element.type === Discord.ChannelType.GuildText)) return;
if (((element as Discord.TextChannel).topic ?? "").includes(`${interaction.member!.user.id}`)) {
- if (((element as Discord.TextChannel).topic ?? "").endsWith("Active")) { count++; }
+ if (((element as Discord.TextChannel).topic ?? "").endsWith("Active")) {
+ count++;
+ }
}
});
} else {
@@ -47,7 +57,9 @@
const channel = targetChannel as Discord.TextChannel;
channel.threads.cache.forEach((element: Discord.ThreadChannel) => {
if (element.name.includes(`${interaction.member!.user.id}`)) {
- if (element.name.endsWith("Active")) { count++; }
+ if (element.name.endsWith("Active")) {
+ count++;
+ }
}
});
}
@@ -88,7 +100,9 @@
}
});
for (let i = 0; i < formattedTicketTypes.length; i += 5) {
- splitFormattedTicketTypes.push(new ActionRowBuilder<ButtonBuilder>().addComponents(formattedTicketTypes.slice(i, i + 5)));
+ splitFormattedTicketTypes.push(
+ new ActionRowBuilder<ButtonBuilder>().addComponents(formattedTicketTypes.slice(i, i + 5))
+ );
}
const m = await interaction.reply({
embeds: [
@@ -106,7 +120,13 @@
try {
component = await m.awaitMessageComponent({
time: 300000,
- filter: (i) => { return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.message.id === m.id }
+ filter: (i) => {
+ return (
+ i.user.id === interaction.user.id &&
+ i.channel!.id === interaction.channel!.id &&
+ i.message.id === m.id
+ );
+ }
});
} catch (e) {
return;
@@ -131,7 +151,9 @@
}
});
for (let i = 0; i < formattedTicketTypes.length; i += 5) {
- splitFormattedTicketTypes.push(new ActionRowBuilder<ButtonBuilder>().addComponents(formattedTicketTypes.slice(i, i + 5)));
+ splitFormattedTicketTypes.push(
+ new ActionRowBuilder<ButtonBuilder>().addComponents(formattedTicketTypes.slice(i, i + 5))
+ );
}
component.update({
embeds: [
@@ -252,11 +274,12 @@
});
}
} else {
- c = await targetChannel.threads.create({name: `${interaction.member!.user.username} - ${interaction.member!.user.id} - Active`,
- autoArchiveDuration: 60 * 24 * 7,
- type: Discord.ChannelType.PrivateThread,
- reason: "Creating ticket"
- }) as Discord.PrivateThreadChannel;
+ c = (await targetChannel.threads.create({
+ name: `${interaction.member!.user.username} - ${interaction.member!.user.id} - Active`,
+ autoArchiveDuration: 60 * 24 * 7,
+ type: Discord.ChannelType.PrivateThread,
+ reason: "Creating ticket"
+ })) as Discord.PrivateThreadChannel;
c.members.add(interaction.member!.user.id);
try {
await c.send({
diff --git a/src/actions/tickets/delete.ts b/src/actions/tickets/delete.ts
index 990b360..1c1e464 100644
--- a/src/actions/tickets/delete.ts
+++ b/src/actions/tickets/delete.ts
@@ -1,10 +1,18 @@
-import { getCommandMentionByName } from '../../utils/getCommandDataByName.js';
-import Discord, { ActionRowBuilder, ButtonBuilder, ButtonInteraction, PrivateThreadChannel, TextChannel, ButtonStyle, CategoryChannel } from "discord.js";
+import { getCommandMentionByName } from "../../utils/getCommandDataByName.js";
+import Discord, {
+ ActionRowBuilder,
+ ButtonBuilder,
+ ButtonInteraction,
+ PrivateThreadChannel,
+ TextChannel,
+ ButtonStyle,
+ CategoryChannel
+} from "discord.js";
import client from "../../utils/client.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import getEmojiByName from "../../utils/getEmojiByName.js";
-import { preloadPage } from '../../utils/createTemporaryStorage.js';
-import { LoadingEmbed } from '../../utils/defaults.js';
+import { preloadPage } from "../../utils/createTemporaryStorage.js";
+import { LoadingEmbed } from "../../utils/defaults.js";
export default async function (interaction: Discord.CommandInteraction | ButtonInteraction) {
if (!interaction.guild) return;
@@ -19,7 +27,8 @@
.setDescription("This channel isn't a ticket, so you can't delete it.")
.setStatus("Danger")
.setEmoji("CONTROL.BLOCKCROSS")
- ], ephemeral: true
+ ],
+ ephemeral: true
});
} else if (interaction.channel!.parent!.id !== ticketChannel) {
return await interaction.reply({
@@ -29,16 +38,23 @@
.setDescription("This channel isn't a ticket, so you can't delete it.")
.setStatus("Danger")
.setEmoji("CONTROL.BLOCKCROSS")
- ], ephemeral: true
+ ],
+ ephemeral: true
});
}
const channel: PrivateThreadChannel | TextChannel = interaction.channel as PrivateThreadChannel | TextChannel;
- let status: string | null = ("topic" in interaction.channel) ? interaction.channel!.topic : interaction.channel.name;
+ let status: string | null = "topic" in interaction.channel ? interaction.channel!.topic : interaction.channel.name;
status = status ?? "";
- if (status.endsWith("Archived")) { status = "Archived"; }
- else { status = "Active"; }
+ if (status.endsWith("Archived")) {
+ status = "Archived";
+ } else {
+ status = "Active";
+ }
- const uID = channel.type === Discord.ChannelType.PrivateThread ? channel.name.split(" - ")[1] : channel.topic!.split(" ")[0];
+ const uID =
+ channel.type === Discord.ChannelType.PrivateThread
+ ? channel.name.split(" - ")[1]
+ : channel.topic!.split(" ")[0];
if (status === "Archived") {
// Delete the ticket
@@ -53,10 +69,7 @@
timestamp: Date.now()
},
list: {
- ticketFor: entry(
- uID!,
- renderUser((await interaction.guild.members.fetch(uID!)).user)
- ),
+ ticketFor: entry(uID!, renderUser((await interaction.guild.members.fetch(uID!)).user)),
closedBy: entry(interaction.member!.user.id, renderUser(interaction.member!.user as Discord.User)),
closed: entry(Date.now(), renderDelta(Date.now())),
ticketChannel: entry(channel.id, channel.name)
@@ -69,26 +82,33 @@
await channel.delete();
} else if (status === "Active") {
- await interaction.reply({embeds: LoadingEmbed, fetchReply: true});
+ await interaction.reply({ embeds: LoadingEmbed, fetchReply: true });
// Archive the ticket
- await interaction.channel.fetch()
+ await interaction.channel.fetch();
if (channel.isThread()) {
channel.setName(`${channel.name.replace("Active", "Archived")}`);
channel.members.remove(channel.name.split(" - ")[1]!);
} else {
channel.setTopic(`${(channel.topic ?? "").replace("Active", "Archived")}`);
- if (!channel.topic!.includes("Archived")) { channel.setTopic("0 Archived"); }
+ if (!channel.topic!.includes("Archived")) {
+ channel.setTopic("0 Archived");
+ }
await channel.permissionOverwrites.delete(channel.topic!.split(" ")[0]!);
}
- preloadPage(interaction.channel.id, "privacy", "2")
+ preloadPage(interaction.channel.id, "privacy", "2");
const hasPremium = await client.database.premium.hasPremium(interaction.guild.id);
await interaction.editReply({
embeds: [
new EmojiEmbed()
.setTitle("Archived Ticket")
- .setDescription(`This ticket has been Archived. Type ${getCommandMentionByName("ticket/close")} to delete it.\n` +
- hasPremium ? ("Creating a transcript will delete all messages in this ticket" +
- `\n\nFor more info on transcripts, check ${getCommandMentionByName("privacy")}`): "")
+ .setDescription(
+ `This ticket has been Archived. Type ${getCommandMentionByName(
+ "ticket/close"
+ )} to delete it.\n` + hasPremium
+ ? "Creating a transcript will delete all messages in this ticket" +
+ `\n\nFor more info on transcripts, check ${getCommandMentionByName("privacy")}`
+ : ""
+ )
.setStatus("Warning")
.setEmoji("GUILD.TICKET.ARCHIVED")
],
@@ -103,12 +123,12 @@
].concat(
hasPremium
? [
- new ButtonBuilder()
- .setLabel("Create Transcript and Delete")
- .setStyle(ButtonStyle.Primary)
- .setCustomId("createtranscript")
- .setEmoji(getEmojiByName("CONTROL.DOWNLOAD", "id"))
- ]
+ new ButtonBuilder()
+ .setLabel("Create Transcript and Delete")
+ .setStyle(ButtonStyle.Primary)
+ .setCustomId("createtranscript")
+ .setEmoji(getEmojiByName("CONTROL.DOWNLOAD", "id"))
+ ]
: []
)
)
@@ -124,10 +144,7 @@
timestamp: Date.now()
},
list: {
- ticketFor: entry(
- uID!,
- renderUser((await interaction.guild.members.fetch(uID!)).user)
- ),
+ ticketFor: entry(uID!, renderUser((await interaction.guild.members.fetch(uID!)).user)),
archivedBy: entry(interaction.member!.user.id, renderUser(interaction.member!.user as Discord.User)),
archived: entry(Date.now(), renderDelta(Date.now())),
ticketChannel: entry(channel.id, renderChannel(channel))
@@ -141,12 +158,13 @@
return;
}
-
async function purgeByUser(member: string, guild: string) {
const config = await client.database.guilds.read(guild);
const fetchedGuild = await client.guilds.fetch(guild);
if (!config.tickets.category) return;
- const tickets: CategoryChannel | TextChannel | undefined = fetchedGuild.channels.cache.get(config.tickets.category) as CategoryChannel | TextChannel | undefined;
+ const tickets: CategoryChannel | TextChannel | undefined = fetchedGuild.channels.cache.get(
+ config.tickets.category
+ ) as CategoryChannel | TextChannel | undefined;
if (!tickets) return;
let deleted = 0;
if (tickets.type === Discord.ChannelType.GuildCategory) {
@@ -154,7 +172,7 @@
const category = tickets as Discord.CategoryChannel;
category.children.cache.forEach((element) => {
if (!(element.type === Discord.ChannelType.GuildText)) return;
- if (!(((element as Discord.TextChannel).topic ?? "").includes(member))) return;
+ if (!((element as Discord.TextChannel).topic ?? "").includes(member)) return;
try {
element.delete();
deleted++;
@@ -175,7 +193,7 @@
}
});
}
- if (!deleted) return
+ if (!deleted) return;
const { log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
const data = {
meta: {
diff --git a/src/api/index.ts b/src/api/index.ts
index 8d57f3d..f8873f0 100644
--- a/src/api/index.ts
+++ b/src/api/index.ts
@@ -1,5 +1,5 @@
-import type { Guild, GuildMember } from 'discord.js';
-import type { NucleusClient } from '../utils/client.js';
+import type { Guild, GuildMember } from "discord.js";
+import type { NucleusClient } from "../utils/client.js";
//@ts-expect-error
import express from "express";
//@ts-expect-error
@@ -21,11 +21,11 @@
const code = req.params.code;
const secret = req.body.secret;
if (secret === client.config.verifySecret) {
- const guild = await client.guilds.fetch(client.verify[code]!.gID) as Guild | null;
+ const guild = (await client.guilds.fetch(client.verify[code]!.gID)) as Guild | null;
if (!guild) {
return res.status(404);
}
- const member = await guild.members.fetch(client.verify[code]!.uID) as GuildMember | null;
+ const member = (await guild.members.fetch(client.verify[code]!.uID)) as GuildMember | null;
if (!member) {
return res.status(404);
}
@@ -47,7 +47,9 @@
});
client.verify = Object.keys(client.verify)
.filter((k) => k !== code)
- .reduce((obj, key) => {return { ...obj, [key]: client.verify[key]}}, {});
+ .reduce((obj, key) => {
+ return { ...obj, [key]: client.verify[key] };
+ }, {});
const { log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
try {
const data = {
@@ -108,11 +110,11 @@
const code = req.params.code;
const secret = req.body.secret;
if (secret === client.config.verifySecret) {
- const guild = await client.guilds.fetch(client.roleMenu[code]!.guild) as Guild | null;
+ const guild = (await client.guilds.fetch(client.roleMenu[code]!.guild)) as Guild | null;
if (!guild) {
return res.status(404);
}
- const member = await guild.members.fetch(client.roleMenu[code]!.user) as GuildMember | null;
+ const member = (await guild.members.fetch(client.roleMenu[code]!.user)) as GuildMember | null;
if (!member) {
return res.status(404);
}
@@ -187,7 +189,7 @@
try {
user = await client.users.fetch(id);
} catch (e) {
- console.log(e)
+ console.log(e);
return res.status(404).send("Could not find a user by that id");
}
return res.status(200).send(user.username);
diff --git a/src/commands/help.ts b/src/commands/help.ts
index 90ef133..fe829b9 100644
--- a/src/commands/help.ts
+++ b/src/commands/help.ts
@@ -22,163 +22,216 @@
import { getCommandByName, getCommandMentionByName } from "../utils/getCommandDataByName.js";
import getEmojiByName from "../utils/getEmojiByName.js";
-const command = new SlashCommandBuilder()
- .setName("help")
- .setDescription("Shows help for commands");
+const command = new SlashCommandBuilder().setName("help").setDescription("Shows help for commands");
-const styles: Record<string, {emoji: string}> = {
- "help": {emoji: "NUCLEUS.LOGO"},
- "mod": {emoji: "PUNISH.BAN.RED"},
- "nucleus": {emoji: "NUCLEUS.LOGO"},
- "privacy": {emoji: "NUCLEUS.LOGO"},
- "role": {emoji: "GUILD.ROLES.DELETE"},
- "rolemenu": {emoji: "GUILD.ROLES.DELETE"},
- "server": {emoji: "GUILD.RED"},
- "settings": {emoji: "GUILD.SETTINGS.RED"},
- "tag": {emoji: "PUNISH.NICKNAME.RED"},
- "tags": {emoji: "PUNISH.NICKNAME.RED"},
- "ticket": {emoji: "GUILD.TICKET.CLOSE"},
- "user": {emoji: "MEMBER.LEAVE"},
- "verify": {emoji: "CONTROL.REDTICK"}
-}
+const styles: Record<string, { emoji: string }> = {
+ help: { emoji: "NUCLEUS.LOGO" },
+ mod: { emoji: "PUNISH.BAN.RED" },
+ nucleus: { emoji: "NUCLEUS.LOGO" },
+ privacy: { emoji: "NUCLEUS.LOGO" },
+ role: { emoji: "GUILD.ROLES.DELETE" },
+ rolemenu: { emoji: "GUILD.ROLES.DELETE" },
+ server: { emoji: "GUILD.RED" },
+ settings: { emoji: "GUILD.SETTINGS.RED" },
+ tag: { emoji: "PUNISH.NICKNAME.RED" },
+ tags: { emoji: "PUNISH.NICKNAME.RED" },
+ ticket: { emoji: "GUILD.TICKET.CLOSE" },
+ user: { emoji: "MEMBER.LEAVE" },
+ verify: { emoji: "CONTROL.REDTICK" }
+};
const callback = async (interaction: CommandInteraction): Promise<void> => {
const m = await interaction.reply({ embeds: LoadingEmbed, ephemeral: true, fetchReply: true });
const commands = client.fetchedCommands;
let closed = false;
- let currentPath: [string, string, string] = ["", "", ""]
+ let currentPath: [string, string, string] = ["", "", ""];
do {
- const commandRow = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("commandRow")
- .setPlaceholder("Select a command")
- .addOptions(
- ...commands.filter(command => command.type === ApplicationCommandType.ChatInput).map((command) => {
+ const commandRow = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setCustomId("commandRow")
+ .setPlaceholder("Select a command")
+ .addOptions(
+ ...commands
+ .filter((command) => command.type === ApplicationCommandType.ChatInput)
+ .map((command) => {
const builder = new StringSelectMenuOptionBuilder()
.setLabel(capitalize(command.name))
.setValue(command.name)
.setDescription(command.description)
- .setDefault(currentPath[0] === command.name)
- if (styles[command.name]) builder.setEmoji(getEmojiByName(styles[command.name]!.emoji, "id") as APIMessageComponentEmoji)
- return builder
+ .setDefault(currentPath[0] === command.name);
+ if (styles[command.name])
+ builder.setEmoji(
+ getEmojiByName(styles[command.name]!.emoji, "id") as APIMessageComponentEmoji
+ );
+ return builder;
})
- )
+ )
);
- const subcommandGroupRow = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("subcommandGroupRow")
- );
- const subcommandRow = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("subcommandRow")
- );
- const embed = new EmojiEmbed()
- .setTitle("Help")
- .setStatus("Danger")
- .setEmoji("NUCLEUS.LOGO")
+ const subcommandGroupRow = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder().setCustomId("subcommandGroupRow")
+ );
+ const subcommandRow = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder().setCustomId("subcommandRow")
+ );
+ const embed = new EmojiEmbed().setTitle("Help").setStatus("Danger").setEmoji("NUCLEUS.LOGO");
- if(currentPath[0] === "" || currentPath[0] === "help") {
+ if (currentPath[0] === "" || currentPath[0] === "help") {
embed.setDescription(
`Welcome to Nucleus\n\n` +
- `Select a command to get started${
- (interaction.member?.permissions as PermissionsBitField).has("ManageGuild") ?
- `, or run ${getCommandMentionByName("nucleus/guide")} for commands to set up your server` : ``
+ `Select a command to get started${
+ (interaction.member?.permissions as PermissionsBitField).has("ManageGuild")
+ ? `, or run ${getCommandMentionByName("nucleus/guide")} for commands to set up your server`
+ : ``
}\n\n\n` +
- `Nucleus is fully [open source](https://github.com/clicksminuteper/Nucleus), and all currently free features will remain free forever.\n\n` +
- `You can invite Nucleus to your server using ${getCommandMentionByName("nucleus/invite")}`
- )
+ `Nucleus is fully [open source](https://github.com/clicksminuteper/Nucleus), and all currently free features will remain free forever.\n\n` +
+ `You can invite Nucleus to your server using ${getCommandMentionByName("nucleus/invite")}`
+ );
} else {
- const currentData = getCommandByName(currentPath.filter(value => value !== "" && value !== "none").join('/'));
+ const currentData = getCommandByName(
+ currentPath.filter((value) => value !== "" && value !== "none").join("/")
+ );
const current = commands.find((command) => command.name === currentPath[0])!;
- let optionString = ``
+ let optionString = ``;
let options: (ApplicationCommandOption & {
nameLocalized?: string;
descriptionLocalized?: string;
})[] = [];
//options
- if(currentPath[1] !== "" && currentPath[1] !== "none" && currentPath[2] !== "" && currentPath[2] !== "none") {
- const Op = current.options.find(option => option.name === currentPath[1])! as ApplicationCommandSubGroup
- const Op2 = Op.options!.find(option => option.name === currentPath[2])!
- options = Op2.options ?? []
- } else if(currentPath[1] !== "" && currentPath[1] !== "none") {
- let Op = current.options.find(option => option.name === currentPath[1])!
- if(Op.type === ApplicationCommandOptionType.SubcommandGroup) {
- options = []
+ if (
+ currentPath[1] !== "" &&
+ currentPath[1] !== "none" &&
+ currentPath[2] !== "" &&
+ currentPath[2] !== "none"
+ ) {
+ const Op = current.options.find(
+ (option) => option.name === currentPath[1]
+ )! as ApplicationCommandSubGroup;
+ const Op2 = Op.options!.find((option) => option.name === currentPath[2])!;
+ options = Op2.options ?? [];
+ } else if (currentPath[1] !== "" && currentPath[1] !== "none") {
+ let Op = current.options.find((option) => option.name === currentPath[1])!;
+ if (Op.type === ApplicationCommandOptionType.SubcommandGroup) {
+ options = [];
} else {
- Op = Op as ApplicationCommandSubCommand
- options = Op.options ?? []
+ Op = Op as ApplicationCommandSubCommand;
+ options = Op.options ?? [];
}
} else {
- options = current.options.filter(option => (option.type !== ApplicationCommandOptionType.SubcommandGroup) && (option.type !== ApplicationCommandOptionType.Subcommand));
+ options = current.options.filter(
+ (option) =>
+ option.type !== ApplicationCommandOptionType.SubcommandGroup &&
+ option.type !== ApplicationCommandOptionType.Subcommand
+ );
}
- for(const option of options) {
- optionString += `> ${option.name} (${ApplicationCommandOptionType[option.type]})- ${option.description}\n`
+ for (const option of options) {
+ optionString += `> ${option.name} (${ApplicationCommandOptionType[option.type]})- ${
+ option.description
+ }\n`;
}
- const APICommand = client.commands["commands/" + currentPath.filter(value => value !== "" && value !== "none").join("/")]![0]
+ const APICommand =
+ client.commands[
+ "commands/" + currentPath.filter((value) => value !== "" && value !== "none").join("/")
+ ]![0];
let allowedToRun = true;
- if(APICommand?.check) {
- allowedToRun = await APICommand.check(interaction as Interaction, true)
+ if (APICommand?.check) {
+ allowedToRun = await APICommand.check(interaction as Interaction, true);
}
embed.setDescription(
- `${getEmojiByName(styles[currentPath[0]]!.emoji)} **${capitalize(currentData.name)}**\n> ${currentData.mention}\n\n` +
- `> ${currentData.description}\n\n` +
- (APICommand ? (`${getEmojiByName(allowedToRun ? "CONTROL.TICK" : "CONTROL.CROSS")} You ${allowedToRun ? "" : "don't "}` +
- `have permission to use this command\n\n`) : "") +
- ((optionString.length > 0) ? "**Options:**\n" + optionString : "")
- )
- const subcommands = current.options.filter((option) => option.type === ApplicationCommandOptionType.Subcommand);
- const subcommandGroups = current.options.filter((option) => option.type === ApplicationCommandOptionType.SubcommandGroup);
+ `${getEmojiByName(styles[currentPath[0]]!.emoji)} **${capitalize(currentData.name)}**\n> ${
+ currentData.mention
+ }\n\n` +
+ `> ${currentData.description}\n\n` +
+ (APICommand
+ ? `${getEmojiByName(allowedToRun ? "CONTROL.TICK" : "CONTROL.CROSS")} You ${
+ allowedToRun ? "" : "don't "
+ }` + `have permission to use this command\n\n`
+ : "") +
+ (optionString.length > 0 ? "**Options:**\n" + optionString : "")
+ );
+ const subcommands = current.options.filter(
+ (option) => option.type === ApplicationCommandOptionType.Subcommand
+ );
+ const subcommandGroups = current.options.filter(
+ (option) => option.type === ApplicationCommandOptionType.SubcommandGroup
+ );
- if(subcommandGroups.length > 0) {
- subcommandGroupRow.components[0]!
- .addOptions(
- new StringSelectMenuOptionBuilder().setLabel("Select a subcommand").setValue("none").setDefault(currentPath[1] === "none"),
- ...subcommandGroups.map((option) => new StringSelectMenuOptionBuilder().setLabel(capitalize(option.name)).setValue(option.name).setDefault(currentPath[1] === option.name))
+ if (subcommandGroups.length > 0) {
+ subcommandGroupRow.components[0]!.addOptions(
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Select a subcommand")
+ .setValue("none")
+ .setDefault(currentPath[1] === "none"),
+ ...subcommandGroups.map((option) =>
+ new StringSelectMenuOptionBuilder()
+ .setLabel(capitalize(option.name))
+ .setValue(option.name)
+ .setDefault(currentPath[1] === option.name)
)
- if(subcommandGroupRow.components[0]!.options.find((option) => option.data.default && option.data.value !== "none")) {
- const subsubcommands = (subcommandGroups.find((option) => option.name === currentPath[1])! as ApplicationCommandSubGroup).options ?? [];
- subcommandRow.components[0]!
- .addOptions(
- new StringSelectMenuOptionBuilder().setLabel("Select a subcommand").setValue("none").setDefault(currentPath[2] === "none"),
- ...subsubcommands.map((option) => new StringSelectMenuOptionBuilder().setLabel(capitalize(option.name)).setValue(option.name).setDefault(currentPath[2] === option.name))
+ );
+ if (
+ subcommandGroupRow.components[0]!.options.find(
+ (option) => option.data.default && option.data.value !== "none"
+ )
+ ) {
+ const subsubcommands =
+ (
+ subcommandGroups.find(
+ (option) => option.name === currentPath[1]
+ )! as ApplicationCommandSubGroup
+ ).options ?? [];
+ subcommandRow.components[0]!.addOptions(
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Select a subcommand")
+ .setValue("none")
+ .setDefault(currentPath[2] === "none"),
+ ...subsubcommands.map((option) =>
+ new StringSelectMenuOptionBuilder()
+ .setLabel(capitalize(option.name))
+ .setValue(option.name)
+ .setDefault(currentPath[2] === option.name)
)
+ );
}
}
- if(subcommands.length > 0) {
- subcommandGroupRow.components[0]!
- .addOptions(
- ...subcommands.map((option) => new StringSelectMenuOptionBuilder().setLabel(capitalize(option.name)).setValue(option.name).setDefault(currentPath[1] === option.name))
+ if (subcommands.length > 0) {
+ subcommandGroupRow.components[0]!.addOptions(
+ ...subcommands.map((option) =>
+ new StringSelectMenuOptionBuilder()
+ .setLabel(capitalize(option.name))
+ .setValue(option.name)
+ .setDefault(currentPath[1] === option.name)
)
+ );
}
}
const cmps = [commandRow];
- if(subcommandGroupRow.components[0]!.options.length > 0) cmps.push(subcommandGroupRow);
- if(subcommandRow.components[0]!.options.length > 0) cmps.push(subcommandRow);
+ if (subcommandGroupRow.components[0]!.options.length > 0) cmps.push(subcommandGroupRow);
+ if (subcommandRow.components[0]!.options.length > 0) cmps.push(subcommandRow);
await interaction.editReply({ embeds: [embed], components: cmps });
let i: StringSelectMenuInteraction;
try {
- i = await m.awaitMessageComponent<ComponentType.StringSelect>({filter: (newInteraction) => interaction.user.id === newInteraction.user.id,time: 300000})
+ i = await m.awaitMessageComponent<ComponentType.StringSelect>({
+ filter: (newInteraction) => interaction.user.id === newInteraction.user.id,
+ time: 300000
+ });
} catch (e) {
closed = true;
continue;
}
await i.deferUpdate();
const value = i.values[0]!;
- switch(i.customId) {
+ switch (i.customId) {
case "commandRow": {
currentPath = [value, "", ""];
break;
}
case "subcommandGroupRow": {
- currentPath = [currentPath[0], value , ""];
+ currentPath = [currentPath[0], value, ""];
break;
}
case "subcommandRow": {
@@ -186,10 +239,8 @@
break;
}
}
-
} while (!closed);
};
-
export { command as command };
export { callback };
diff --git a/src/commands/mod/_meta.ts b/src/commands/mod/_meta.ts
index c5fcca5..af8006c 100644
--- a/src/commands/mod/_meta.ts
+++ b/src/commands/mod/_meta.ts
@@ -5,4 +5,4 @@
const subcommand = await command(name, description, `mod`);
-export { name, description, subcommand as command };
\ No newline at end of file
+export { name, description, subcommand as command };
diff --git a/src/commands/mod/about.ts b/src/commands/mod/about.ts
index 0a9d962..8736054 100644
--- a/src/commands/mod/about.ts
+++ b/src/commands/mod/about.ts
@@ -1,4 +1,4 @@
-import { LoadingEmbed } from '../../utils/defaults.js';
+import { LoadingEmbed } from "../../utils/defaults.js";
import type { HistorySchema } from "../../utils/database.js";
import Discord, {
CommandInteraction,
@@ -104,10 +104,7 @@
let history, current: TimelineSection;
history = await client.database.history.read(member.guild.id, member.id, currentYear);
history = history
- .sort(
- (a: { occurredAt: Date }, b: { occurredAt: Date }) =>
- b.occurredAt.getTime() - a.occurredAt.getTime()
- )
+ .sort((a: { occurredAt: Date }, b: { occurredAt: Date }) => b.occurredAt.getTime() - a.occurredAt.getTime())
.reverse();
let m: Message;
let refresh = false;
@@ -154,59 +151,62 @@
}
}
if (pageIndex === null) pageIndex = 0;
- let components: (ActionRowBuilder<Discord.StringSelectMenuBuilder> | ActionRowBuilder<ButtonBuilder>)[] = []
- if (openFilterPane) components = components.concat([
- new ActionRowBuilder<Discord.StringSelectMenuBuilder>().addComponents(
- new Discord.StringSelectMenuBuilder()
- .setMinValues(1)
- .setMaxValues(Object.keys(types).length)
- .setCustomId("filter")
- .setPlaceholder("Select events to show")
- .setOptions(...Object.entries(types).map(([key, value]) => new Discord.StringSelectMenuOptionBuilder()
- .setLabel(value.text)
- .setValue(key)
- .setDefault(filteredTypes.includes(key))
- .setEmoji(getEmojiByName(value.emoji, "id") as APIMessageComponentEmoji)
- )))
+ let components: (ActionRowBuilder<Discord.StringSelectMenuBuilder> | ActionRowBuilder<ButtonBuilder>)[] = [];
+ if (openFilterPane)
+ components = components.concat([
+ new ActionRowBuilder<Discord.StringSelectMenuBuilder>().addComponents(
+ new Discord.StringSelectMenuBuilder()
+ .setMinValues(1)
+ .setMaxValues(Object.keys(types).length)
+ .setCustomId("filter")
+ .setPlaceholder("Select events to show")
+ .setOptions(
+ ...Object.entries(types).map(([key, value]) =>
+ new Discord.StringSelectMenuOptionBuilder()
+ .setLabel(value.text)
+ .setValue(key)
+ .setDefault(filteredTypes.includes(key))
+ .setEmoji(getEmojiByName(value.emoji, "id") as APIMessageComponentEmoji)
+ )
+ )
+ )
+ ]);
+ components = components.concat([
+ new ActionRowBuilder<Discord.ButtonBuilder>().addComponents([
+ new ButtonBuilder()
+ .setCustomId("prevYear")
+ .setLabel((currentYear - 1).toString())
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id"))
+ .setStyle(ButtonStyle.Secondary),
+ new ButtonBuilder().setCustomId("prevPage").setLabel("Previous page").setStyle(ButtonStyle.Primary),
+ new ButtonBuilder().setCustomId("today").setLabel("Today").setStyle(ButtonStyle.Primary),
+ new ButtonBuilder()
+ .setCustomId("nextPage")
+ .setLabel("Next page")
+ .setStyle(ButtonStyle.Primary)
+ .setDisabled(pageIndex >= groups.length - 1 && currentYear === new Date().getFullYear()),
+ new ButtonBuilder()
+ .setCustomId("nextYear")
+ .setLabel((currentYear + 1).toString())
+ .setEmoji(getEmojiByName("CONTROL.RIGHT", "id"))
+ .setStyle(ButtonStyle.Secondary)
+ .setDisabled(currentYear === new Date().getFullYear())
+ ])
]);
- components = components.concat([new ActionRowBuilder<Discord.ButtonBuilder>().addComponents([
- new ButtonBuilder()
- .setCustomId("prevYear")
- .setLabel((currentYear - 1).toString())
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id"))
- .setStyle(ButtonStyle.Secondary),
- new ButtonBuilder()
- .setCustomId("prevPage")
- .setLabel("Previous page")
- .setStyle(ButtonStyle.Primary),
- new ButtonBuilder()
- .setCustomId("today")
- .setLabel("Today")
- .setStyle(ButtonStyle.Primary),
- new ButtonBuilder()
- .setCustomId("nextPage")
- .setLabel("Next page")
- .setStyle(ButtonStyle.Primary)
- .setDisabled(pageIndex >= groups.length - 1 && currentYear === new Date().getFullYear()),
- new ButtonBuilder()
- .setCustomId("nextYear")
- .setLabel((currentYear + 1).toString())
- .setEmoji(getEmojiByName("CONTROL.RIGHT", "id"))
- .setStyle(ButtonStyle.Secondary)
- .setDisabled(currentYear === new Date().getFullYear())
- ])])
- components = components.concat([new ActionRowBuilder<Discord.ButtonBuilder>().addComponents([
- new ButtonBuilder()
- .setLabel("Mod notes")
- .setCustomId("modNotes")
- .setStyle(ButtonStyle.Primary)
- .setEmoji(getEmojiByName("ICONS.EDIT", "id")),
- new ButtonBuilder()
- .setLabel("Filter")
- .setCustomId("openFilter")
- .setStyle(openFilterPane ? ButtonStyle.Success : ButtonStyle.Primary)
- .setEmoji(getEmojiByName("ICONS.FILTER", "id"))
- ])])
+ components = components.concat([
+ new ActionRowBuilder<Discord.ButtonBuilder>().addComponents([
+ new ButtonBuilder()
+ .setLabel("Mod notes")
+ .setCustomId("modNotes")
+ .setStyle(ButtonStyle.Primary)
+ .setEmoji(getEmojiByName("ICONS.EDIT", "id")),
+ new ButtonBuilder()
+ .setLabel("Filter")
+ .setCustomId("openFilter")
+ .setStyle(openFilterPane ? ButtonStyle.Success : ButtonStyle.Primary)
+ .setEmoji(getEmojiByName("ICONS.FILTER", "id"))
+ ])
+ ]);
const end =
"\n\nJanuary " +
@@ -227,7 +227,10 @@
)
.setStatus("Success")
.setFooter({
- text: openFilterPane && filteredTypes.length ? "Filters are currently enabled" : "No filters selected"
+ text:
+ openFilterPane && filteredTypes.length
+ ? "Filters are currently enabled"
+ : "No filters selected"
})
],
components: components
@@ -241,17 +244,26 @@
.setDescription(`**${currentYear}**\n\n*No events*`)
.setStatus("Success")
.setFooter({
- text: openFilterPane && filteredTypes.length ? "Filters are currently enabled" : "No filters selected"
+ text:
+ openFilterPane && filteredTypes.length
+ ? "Filters are currently enabled"
+ : "No filters selected"
})
],
components: components
- })
+ });
}
let i: MessageComponentInteraction;
try {
i = await m.awaitMessageComponent({
time: 300000,
- filter: (i) => { return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.message.id === m.id }
+ filter: (i) => {
+ return (
+ i.user.id === interaction.user.id &&
+ i.channel!.id === interaction.channel!.id &&
+ i.message.id === m.id
+ );
+ }
});
} catch (e) {
interaction.editReply({
@@ -328,7 +340,9 @@
let timedOut = false;
while (!timedOut) {
note = await client.database.notes.read(member.guild.id, member.id);
- if (firstLoad && !note) { await showHistory(member, interaction); }
+ if (firstLoad && !note) {
+ await showHistory(member, interaction);
+ }
firstLoad = false;
m = (await interaction.editReply({
embeds: [
@@ -357,7 +371,13 @@
try {
i = await m.awaitMessageComponent({
time: 300000,
- filter: (i) => { return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.message.id === m.id }
+ filter: (i) => {
+ return (
+ i.user.id === interaction.user.id &&
+ i.channel!.id === interaction.channel!.id &&
+ i.message.id === m.id
+ );
+ }
});
} catch (e) {
timedOut = true;
@@ -424,13 +444,13 @@
const check = (interaction: CommandInteraction) => {
const member = interaction.member as GuildMember;
- if (!member.permissions.has("ModerateMembers"))
- return "You do not have the *Moderate Members* permission";
+ if (!member.permissions.has("ModerateMembers")) return "You do not have the *Moderate Members* permission";
return true;
};
export { command, callback, check };
export const metadata = {
- longDescription: "Shows the moderation history (all previous bans, kicks, warns etc.), and moderator notes for a user.",
- premiumOnly: true,
-}
+ longDescription:
+ "Shows the moderation history (all previous bans, kicks, warns etc.), and moderator notes for a user.",
+ premiumOnly: true
+};
diff --git a/src/commands/mod/ban.ts b/src/commands/mod/ban.ts
index e8309fb..628b607 100644
--- a/src/commands/mod/ban.ts
+++ b/src/commands/mod/ban.ts
@@ -1,4 +1,12 @@
-import Discord, { CommandInteraction, GuildMember, ActionRowBuilder, ButtonBuilder, User, ButtonStyle, SlashCommandSubcommandBuilder } from "discord.js";
+import Discord, {
+ CommandInteraction,
+ GuildMember,
+ ActionRowBuilder,
+ ButtonBuilder,
+ User,
+ ButtonStyle,
+ SlashCommandSubcommandBuilder
+} from "discord.js";
import confirmationMessage from "../../utils/confirmationMessage.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import keyValueList from "../../utils/generateKeyValueList.js";
@@ -7,7 +15,6 @@
import { LinkWarningFooter } from "../../utils/defaults.js";
import getEmojiByName from "../../utils/getEmojiByName.js";
-
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
.setName("ban")
@@ -22,7 +29,6 @@
.setRequired(false)
);
-
const callback = async (interaction: CommandInteraction): Promise<void> => {
if (!interaction.guild) return;
const { renderUser } = client.logger;
@@ -39,12 +45,13 @@
.setDescription(
keyValueList({
user: renderUser(interaction.options.getUser("user")!),
- reason: reason ? "\n> " + (reason).replaceAll("\n", "\n> ") : "*No reason provided*"
+ reason: reason ? "\n> " + reason.replaceAll("\n", "\n> ") : "*No reason provided*"
}) +
`The user **will${notify ? "" : " not"}** be notified\n` +
`${addPlurals(
- (interaction.options.get("delete")?.value as number | null) ?? 0, "day")
- } of messages will be deleted\n\n` +
+ (interaction.options.get("delete")?.value as number | null) ?? 0,
+ "day"
+ )} of messages will be deleted\n\n` +
`Are you sure you want to ban <@!${(interaction.options.getMember("user") as GuildMember).id}>?`
)
.addCustomBoolean(
@@ -66,15 +73,20 @@
else if (confirmation.success !== undefined) chosen = true;
else if (confirmation.newReason) reason = confirmation.newReason;
else if (confirmation.components) notify = confirmation.components["notify"]!.active;
- } while (!timedOut && !chosen)
+ } while (!timedOut && !chosen);
if (timedOut || !confirmation.success) return;
- reason = reason.length ? reason : null
+ reason = reason.length ? reason : null;
let dmSent = false;
let dmMessage;
const config = await client.database.guilds.read(interaction.guild.id);
try {
if (notify) {
- if (reason) { reason = reason.split("\n").map((line) => "> " + line).join("\n") }
+ if (reason) {
+ reason = reason
+ .split("\n")
+ .map((line) => "> " + line)
+ .join("\n");
+ }
const messageData: {
embeds: EmojiEmbed[];
components: ActionRowBuilder<ButtonBuilder>[];
@@ -92,14 +104,20 @@
components: []
};
if (config.moderation.ban.text && config.moderation.ban.link) {
- messageData.embeds[0]!.setFooter(LinkWarningFooter)
- messageData.components.push(new ActionRowBuilder<Discord.ButtonBuilder>()
- .addComponents(new ButtonBuilder()
+ messageData.embeds[0]!.setFooter(LinkWarningFooter);
+ messageData.components.push(
+ new ActionRowBuilder<Discord.ButtonBuilder>().addComponents(
+ new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setLabel(config.moderation.ban.text)
- .setURL(config.moderation.ban.link.replaceAll("{id}", (interaction.options.getMember("user") as GuildMember).id))
- )
- )
+ .setURL(
+ config.moderation.ban.link.replaceAll(
+ "{id}",
+ (interaction.options.getMember("user") as GuildMember).id
+ )
+ )
+ )
+ );
}
dmMessage = await (interaction.options.getMember("user") as GuildMember).send(messageData);
dmSent = true;
@@ -109,7 +127,7 @@
}
try {
const member = interaction.options.getMember("user") as GuildMember;
- const days: number = interaction.options.get("delete")?.value as number | null ?? 0;
+ const days: number = (interaction.options.get("delete")?.value as number | null) ?? 0;
member.ban({
deleteMessageSeconds: days * 24 * 60 * 60,
reason: reason ?? "*No reason provided*"
@@ -135,7 +153,9 @@
serverMemberCount: interaction.guild.memberCount
},
separate: {
- end: getEmojiByName("ICONS.NOTIFY." + (notify ? "ON" : "OFF")) + ` The user was ${notify ? "" : "not "}notified`
+ end:
+ getEmojiByName("ICONS.NOTIFY." + (notify ? "ON" : "OFF")) +
+ ` The user was ${notify ? "" : "not "}notified`
},
hidden: {
guild: interaction.guild.id
@@ -174,17 +194,17 @@
const member = interaction.member as GuildMember;
// Check if the user has ban_members permission
if (!member.permissions.has("BanMembers")) return "You do not have the *Ban Members* permission";
- if(partial) return true;
+ if (partial) return true;
const me = interaction.guild.members.me!;
let apply = interaction.options.getUser("user") as User | GuildMember;
const memberPos = member.roles.cache.size > 1 ? member.roles.highest.position : 0;
const mePos = me.roles.cache.size > 1 ? me.roles.highest.position : 0;
- let applyPos = 0
+ let applyPos = 0;
try {
- apply = await interaction.guild.members.fetch(apply.id) as GuildMember
+ apply = (await interaction.guild.members.fetch(apply.id)) as GuildMember;
applyPos = apply.roles.cache.size > 1 ? apply.roles.highest.position : 0;
} catch {
- apply = apply as User
+ apply = apply as User;
}
// Do not allow banning the owner
if (member.id === interaction.guild.ownerId) return "You cannot ban the owner of the server";
@@ -204,6 +224,7 @@
export { command, callback, check };
export const metadata = {
- longDescription: "Removes a member from the server - this will prevent them from rejoining until they are unbanned, and will delete a specified number of days of messages from them.",
- premiumOnly: true,
-}
+ longDescription:
+ "Removes a member from the server - this will prevent them from rejoining until they are unbanned, and will delete a specified number of days of messages from them.",
+ premiumOnly: true
+};
diff --git a/src/commands/mod/kick.ts b/src/commands/mod/kick.ts
index 059bdb2..c4f1867 100644
--- a/src/commands/mod/kick.ts
+++ b/src/commands/mod/kick.ts
@@ -1,5 +1,12 @@
-import { LinkWarningFooter } from '../../utils/defaults.js';
-import { CommandInteraction, GuildMember, ActionRowBuilder, ButtonBuilder, ButtonStyle, SlashCommandSubcommandBuilder } from "discord.js";
+import { LinkWarningFooter } from "../../utils/defaults.js";
+import {
+ CommandInteraction,
+ GuildMember,
+ ActionRowBuilder,
+ ButtonBuilder,
+ ButtonStyle,
+ SlashCommandSubcommandBuilder
+} from "discord.js";
// @ts-expect-error
import humanizeDuration from "humanize-duration";
import type Discord from "discord.js";
@@ -31,9 +38,8 @@
.setDescription(
keyValueList({
user: renderUser(interaction.options.getUser("user")!),
- reason: reason ? "\n> " + (reason).replaceAll("\n", "\n> ") : "*No reason provided*"
- }) +
- `Are you sure you want to kick <@!${(interaction.options.getMember("user") as GuildMember).id}>?`
+ reason: reason ? "\n> " + reason.replaceAll("\n", "\n> ") : "*No reason provided*"
+ }) + `Are you sure you want to kick <@!${(interaction.options.getMember("user") as GuildMember).id}>?`
)
.setColor("Danger")
.addCustomBoolean(
@@ -56,14 +62,19 @@
else if (confirmation.components) {
notify = confirmation.components["notify"]!.active;
}
- } while (!timedOut && !success)
+ } while (!timedOut && !success);
if (timedOut || !confirmation.success) return;
let dmSent = false;
let dmMessage;
const config = await client.database.guilds.read(interaction.guild.id);
try {
if (notify) {
- if (reason) { reason = reason.split("\n").map((line) => "> " + line).join("\n") }
+ if (reason) {
+ reason = reason
+ .split("\n")
+ .map((line) => "> " + line)
+ .join("\n");
+ }
const messageData: {
embeds: EmojiEmbed[];
components: ActionRowBuilder<ButtonBuilder>[];
@@ -81,14 +92,20 @@
components: []
};
if (config.moderation.kick.text && config.moderation.kick.link) {
- messageData.embeds[0]!.setFooter(LinkWarningFooter)
- messageData.components.push(new ActionRowBuilder<Discord.ButtonBuilder>()
- .addComponents(new ButtonBuilder()
+ messageData.embeds[0]!.setFooter(LinkWarningFooter);
+ messageData.components.push(
+ new ActionRowBuilder<Discord.ButtonBuilder>().addComponents(
+ new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setLabel(config.moderation.kick.text)
- .setURL(config.moderation.kick.link.replaceAll("{id}", (interaction.options.getMember("user") as GuildMember).id))
- )
- )
+ .setURL(
+ config.moderation.kick.link.replaceAll(
+ "{id}",
+ (interaction.options.getMember("user") as GuildMember).id
+ )
+ )
+ )
+ );
}
dmMessage = await (interaction.options.getMember("user") as GuildMember).send(messageData);
dmSent = true;
@@ -101,12 +118,14 @@
const member = interaction.options.getMember("user") as GuildMember;
await client.database.history.create("kick", interaction.guild.id, member.user, interaction.user, reason);
const { log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
- const timeInServer = member.joinedTimestamp ? entry(
- (Date.now() - member.joinedTimestamp).toString(),
- humanizeDuration(Date.now() - member.joinedTimestamp, {
- round: true
- })
- ) : entry(null, "*Unknown*")
+ const timeInServer = member.joinedTimestamp
+ ? entry(
+ (Date.now() - member.joinedTimestamp).toString(),
+ humanizeDuration(Date.now() - member.joinedTimestamp, {
+ round: true
+ })
+ )
+ : entry(null, "*Unknown*");
const data = {
meta: {
type: "memberKick",
@@ -119,7 +138,7 @@
list: {
memberId: entry(member.id, `\`${member.id}\``),
name: entry(member.id, renderUser(member.user)),
- joined: undefined as (unknown | typeof entry),
+ joined: undefined as unknown | typeof entry,
kicked: entry(Date.now().toString(), renderDelta(Date.now())),
kickedBy: entry(interaction.user.id, renderUser(interaction.user)),
reason: entry(reason, reason ? `\n> ${reason}` : "*No reason provided.*"),
@@ -127,22 +146,18 @@
serverMemberCount: member.guild.memberCount
},
separate: {
- end: getEmojiByName("ICONS.NOTIFY." + (notify ? "ON" : "OFF")) + ` The user was ${notify ? "" : "not "}notified`
+ end:
+ getEmojiByName("ICONS.NOTIFY." + (notify ? "ON" : "OFF")) +
+ ` The user was ${notify ? "" : "not "}notified`
},
hidden: {
guild: member.guild.id
}
};
if (member.joinedTimestamp) {
- data.list.joined = entry(member.joinedTimestamp.toString(), renderDelta(member.joinedTimestamp))
+ data.list.joined = entry(member.joinedTimestamp.toString(), renderDelta(member.joinedTimestamp));
}
- await client.database.history.create(
- "kick",
- interaction.guild.id,
- member.user,
- interaction.user,
- reason
- )
+ await client.database.history.create("kick", interaction.guild.id, member.user, interaction.user, reason);
log(data);
} catch {
await interaction.editReply({
@@ -203,5 +218,5 @@
export { command, callback, check };
export const metadata = {
longDescription: "Removes a member from the server. They will be able to rejoin if they have an invite link.",
- premiumOnly: true,
-}
+ premiumOnly: true
+};
diff --git a/src/commands/mod/mute.ts b/src/commands/mod/mute.ts
index c795456..39c9e5e 100644
--- a/src/commands/mod/mute.ts
+++ b/src/commands/mod/mute.ts
@@ -49,12 +49,11 @@
.setRequired(false)
);
-
const callback = async (interaction: CommandInteraction): Promise<unknown> => {
if (!interaction.guild) return;
const { log, NucleusColors, renderUser, entry, renderDelta } = client.logger;
const member = interaction.options.getMember("user") as GuildMember;
- const time: {days: number, hours: number, minutes: number, seconds: number} = {
+ const time: { days: number; hours: number; minutes: number; seconds: number } = {
days: (interaction.options.get("days")?.value as number | null) ?? 0,
hours: (interaction.options.get("hours")?.value as number | null) ?? 0,
minutes: (interaction.options.get("minutes")?.value as number | null) ?? 0,
@@ -79,8 +78,14 @@
components: [
new ActionRowBuilder<ButtonBuilder>().addComponents([
new Discord.ButtonBuilder().setCustomId("1m").setLabel("1 Minute").setStyle(ButtonStyle.Secondary),
- new Discord.ButtonBuilder().setCustomId("10m").setLabel("10 Minutes").setStyle(ButtonStyle.Secondary),
- new Discord.ButtonBuilder().setCustomId("30m").setLabel("30 Minutes").setStyle(ButtonStyle.Secondary),
+ new Discord.ButtonBuilder()
+ .setCustomId("10m")
+ .setLabel("10 Minutes")
+ .setStyle(ButtonStyle.Secondary),
+ new Discord.ButtonBuilder()
+ .setCustomId("30m")
+ .setLabel("30 Minutes")
+ .setStyle(ButtonStyle.Secondary),
new Discord.ButtonBuilder().setCustomId("1h").setLabel("1 Hour").setStyle(ButtonStyle.Secondary)
]),
new ActionRowBuilder<ButtonBuilder>().addComponents([
@@ -103,7 +108,9 @@
let component;
try {
component = await m.awaitMessageComponent({
- filter: (i) => {return i.user.id === interaction.user.id && i.channelId === interaction.channelId},
+ filter: (i) => {
+ return i.user.id === interaction.user.id && i.channelId === interaction.channelId;
+ },
time: 300000
});
} catch {
@@ -178,7 +185,7 @@
time: `${humanizeDuration(muteTime * 1000, {
round: true
})}`,
- reason: reason ? "\n> " + (reason).replaceAll("\n", "\n> ") : "*No reason provided*"
+ reason: reason ? "\n> " + reason.replaceAll("\n", "\n> ") : "*No reason provided*"
}) +
"The user will be " +
serverSettingsDescription +
@@ -190,7 +197,8 @@
"appeal",
"Create appeal ticket",
!(await areTicketsEnabled(interaction.guild.id)),
- async () => await create(interaction.guild!, interaction.options.getUser("user")!, interaction.user, reason),
+ async () =>
+ await create(interaction.guild!, interaction.options.getUser("user")!, interaction.user, reason),
"An appeal ticket will be created when Confirm is clicked",
null,
"CONTROL.TICKET",
@@ -217,13 +225,22 @@
notify = confirmation.components["notify"]!.active;
createAppealTicket = confirmation.components["appeal"]!.active;
}
- } while (!timedOut && !success)
+ } while (!timedOut && !success);
if (timedOut || !confirmation.success) return;
- const status: {timeout: boolean | null, role: boolean | null, dm: boolean | null} = {timeout: null, role: null, dm: null};
+ const status: { timeout: boolean | null; role: boolean | null; dm: boolean | null } = {
+ timeout: null,
+ role: null,
+ dm: null
+ };
let dmMessage;
try {
if (notify) {
- if (reason) { reason = reason.split("\n").map((line) => "> " + line).join("\n") }
+ if (reason) {
+ reason = reason
+ .split("\n")
+ .map((line) => "> " + line)
+ .join("\n");
+ }
const messageData: {
embeds: EmojiEmbed[];
components: ActionRowBuilder<ButtonBuilder>[];
@@ -234,28 +251,39 @@
.setTitle("Muted")
.setDescription(
`You have been muted in ${interaction.guild.name}` +
- (reason ? ` for:\n${reason}` : ".\n*No reason was provided*") + "\n\n" +
- `You will be unmuted at: <t:${Math.round(Date.now() / 1000) + muteTime}:D> at ` +
- `<t:${Math.round(Date.now() / 1000) + muteTime}:T> (<t:${Math.round(Date.now() / 1000) + muteTime
- }:R>)` + "\n\n" +
- (createAppealTicket
- ? `You can appeal this in the ticket created in <#${confirmation.components!["appeal"]!.response}>`
- : "")
+ (reason ? ` for:\n${reason}` : ".\n*No reason was provided*") +
+ "\n\n" +
+ `You will be unmuted at: <t:${Math.round(Date.now() / 1000) + muteTime}:D> at ` +
+ `<t:${Math.round(Date.now() / 1000) + muteTime}:T> (<t:${
+ Math.round(Date.now() / 1000) + muteTime
+ }:R>)` +
+ "\n\n" +
+ (createAppealTicket
+ ? `You can appeal this in the ticket created in <#${
+ confirmation.components!["appeal"]!.response
+ }>`
+ : "")
)
.setStatus("Danger")
],
components: []
- }
+ };
if (config.moderation.mute.text && config.moderation.mute.link) {
messageData.embeds[0]!.setFooter(LinkWarningFooter);
- messageData.components.push(new ActionRowBuilder<Discord.ButtonBuilder>()
- .addComponents(new ButtonBuilder()
- .setStyle(ButtonStyle.Link)
- .setLabel(config.moderation.mute.text)
- .setURL(config.moderation.mute.link.replaceAll("{id}", (interaction.options.getMember("user") as GuildMember).id))
+ messageData.components.push(
+ new ActionRowBuilder<Discord.ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setStyle(ButtonStyle.Link)
+ .setLabel(config.moderation.mute.text)
+ .setURL(
+ config.moderation.mute.link.replaceAll(
+ "{id}",
+ (interaction.options.getMember("user") as GuildMember).id
+ )
+ )
)
- )
- };
+ );
+ }
dmMessage = await member.send(messageData);
status.dm = true;
}
@@ -267,11 +295,15 @@
await member.timeout(muteTime * 1000, reason || "*No reason provided*");
if (config.moderation.mute.role !== null) {
await member.roles.add(config.moderation.mute.role);
- await client.database.eventScheduler.schedule("naturalUnmute", (Date.now() + muteTime * 1000).toString(), {
- guild: interaction.guild.id,
- user: member.id,
- expires: Date.now() + muteTime * 1000
- });
+ await client.database.eventScheduler.schedule(
+ "naturalUnmute",
+ (Date.now() + muteTime * 1000).toString(),
+ {
+ guild: interaction.guild.id,
+ user: member.id,
+ expires: Date.now() + muteTime * 1000
+ }
+ );
}
} else {
status.timeout = true;
@@ -293,7 +325,7 @@
} catch {
status.role = false;
}
- const countTrue = (items: (boolean | null)[]) => items.filter(item => item === true).length;
+ const countTrue = (items: (boolean | null)[]) => items.filter((item) => item === true).length;
const requiredPunishments = countTrue([config.moderation.mute.timeout, config.moderation.mute.role !== null]);
const actualPunishments = countTrue([status.timeout, status.role]);
@@ -301,7 +333,8 @@
if (requiredPunishments !== actualPunishments) {
const messages = [];
if (config.moderation.mute.timeout) messages.push(`The member was ${status.timeout ? "" : "not "}timed out`);
- if (config.moderation.mute.role !== null) messages.push(`The member was ${status.role ? "" : "not "}given the mute role`);
+ if (config.moderation.mute.role !== null)
+ messages.push(`The member was ${status.role ? "" : "not "}given the mute role`);
messages.push(`The member was not sent a DM`);
if (dmMessage && actualPunishments === 0) await dmMessage.delete();
await interaction.editReply({
@@ -310,8 +343,10 @@
.setEmoji("PUNISH.MUTE." + (actualPunishments > 0 ? "YELLOW" : "RED"))
.setTitle("Mute")
.setDescription(
- "Mute " + (actualPunishments > 0 ? "partially" : "failed") + ":\n" +
- messages.map(message => `> ${message}`).join("\n")
+ "Mute " +
+ (actualPunishments > 0 ? "partially" : "failed") +
+ ":\n" +
+ messages.map((message) => `> ${message}`).join("\n")
)
.setStatus(actualPunishments > 0 ? "Warning" : "Danger")
],
@@ -330,16 +365,15 @@
list: {
memberId: entry(member.user.id, `\`${member.user.id}\``),
name: entry(member.user.id, renderUser(member.user)),
- mutedUntil: entry(
- (Date.now() + muteTime * 1000).toString(),
- renderDelta(Date.now() + muteTime * 1000)
- ),
+ mutedUntil: entry((Date.now() + muteTime * 1000).toString(), renderDelta(Date.now() + muteTime * 1000)),
muted: entry(new Date().getTime.toString(), renderDelta(Date.now() - 1000)),
mutedBy: entry(interaction.member!.user.id, renderUser(interaction.member!.user as Discord.User)),
reason: entry(reason, reason ? reason : "*No reason provided*")
},
separate: {
- end: getEmojiByName("ICONS.NOTIFY." + (notify ? "ON" : "OFF")) + ` The user was ${notify ? "" : "not "}notified`
+ end:
+ getEmojiByName("ICONS.NOTIFY." + (notify ? "ON" : "OFF")) +
+ ` The user was ${notify ? "" : "not "}notified`
},
hidden: {
guild: interaction.guild.id
@@ -353,10 +387,11 @@
.setEmoji(`PUNISH.MUTE.${failed ? "YELLOW" : "GREEN"}`)
.setTitle("Mute")
.setDescription(
- "The member was muted" + (failed ? ", but could not be notified" : "") +
- (createAppealTicket
- ? ` and an appeal ticket was opened in <#${confirmation.components!["appeal"]!.response}>`
- : "")
+ "The member was muted" +
+ (failed ? ", but could not be notified" : "") +
+ (createAppealTicket
+ ? ` and an appeal ticket was opened in <#${confirmation.components!["appeal"]!.response}>`
+ : "")
)
.setStatus(failed ? "Warning" : "Success")
],
@@ -393,6 +428,7 @@
export { command, callback, check };
export const metadata = {
- longDescription: "Stops a member from being able to send messages or join voice channels for a specified amount of time.",
- premiumOnly: true,
-}
+ longDescription:
+ "Stops a member from being able to send messages or join voice channels for a specified amount of time.",
+ premiumOnly: true
+};
diff --git a/src/commands/mod/nick.ts b/src/commands/mod/nick.ts
index 5511d19..8b33551 100644
--- a/src/commands/mod/nick.ts
+++ b/src/commands/mod/nick.ts
@@ -1,4 +1,4 @@
-import { LinkWarningFooter } from './../../utils/defaults.js';
+import { LinkWarningFooter } from "./../../utils/defaults.js";
import { ActionRowBuilder, ButtonBuilder, CommandInteraction, GuildMember, ButtonStyle, Message } from "discord.js";
import type { SlashCommandSubcommandBuilder } from "discord.js";
import confirmationMessage from "../../utils/confirmationMessage.js";
@@ -8,15 +8,14 @@
import { areTicketsEnabled, create } from "../../actions/createModActionTicket.js";
import getEmojiByName from "../../utils/getEmojiByName.js";
-
-const command = (builder: SlashCommandSubcommandBuilder) => builder
- .setName("nick")
- .setDescription("Changes a users nickname")
- .addUserOption((option) => option.setName("user").setDescription("The user to change").setRequired(true))
- .addStringOption((option) =>
- option.setName("name").setDescription("The name to set | Leave blank to clear").setRequired(false)
- );
-
+const command = (builder: SlashCommandSubcommandBuilder) =>
+ builder
+ .setName("nick")
+ .setDescription("Changes a users nickname")
+ .addUserOption((option) => option.setName("user").setDescription("The user to change").setRequired(true))
+ .addStringOption((option) =>
+ option.setName("name").setDescription("The name to set | Leave blank to clear").setRequired(false)
+ );
const callback = async (interaction: CommandInteraction): Promise<unknown> => {
const { log, NucleusColors, entry, renderDelta, renderUser } = client.logger;
@@ -35,19 +34,27 @@
keyValueList({
user: renderUser(interaction.options.getUser("user")!),
"new nickname": `${
- interaction.options.get("name")?.value as string ? interaction.options.get("name")?.value as string : "*No nickname*"
+ (interaction.options.get("name")?.value as string)
+ ? (interaction.options.get("name")?.value as string)
+ : "*No nickname*"
}`
}) +
- `Are you sure you want to ${interaction.options.get("name")?.value as string ? "change" : "clear"} <@!${
- (interaction.options.getMember("user") as GuildMember).id
- }>'s nickname?`
+ `Are you sure you want to ${
+ (interaction.options.get("name")?.value as string) ? "change" : "clear"
+ } <@!${(interaction.options.getMember("user") as GuildMember).id}>'s nickname?`
)
.setColor("Danger")
.addCustomBoolean(
"appeal",
"Create appeal ticket",
!(await areTicketsEnabled(interaction.guild!.id)),
- async () => await create(interaction.guild!, interaction.options.getUser("user")!, interaction.user, "Nickname changed"),
+ async () =>
+ await create(
+ interaction.guild!,
+ interaction.options.getUser("user")!,
+ interaction.user,
+ "Nickname changed"
+ ),
"An appeal ticket will be created",
null,
"CONTROL.TICKET",
@@ -69,7 +76,7 @@
if (confirmation.cancelled) timedOut = true;
else if (confirmation.success !== undefined) success = true;
else if (confirmation.components) {
- notify = confirmation.components['notify']!.active;
+ notify = confirmation.components["notify"]!.active;
createAppealTicket = confirmation.components["appeal"]!.active;
}
} while (!timedOut && !success);
@@ -88,29 +95,38 @@
.setEmoji("PUNISH.NICKNAME.RED")
.setTitle("Nickname changed")
.setDescription(
- `Your nickname was ${interaction.options.get("name")?.value as string ? "changed" : "cleared"} in ${
- interaction.guild!.name
- }.` +
- (interaction.options.get("name")?.value as string
+ `Your nickname was ${
+ (interaction.options.get("name")?.value as string) ? "changed" : "cleared"
+ } in ${interaction.guild!.name}.` +
+ ((interaction.options.get("name")?.value as string)
? `\nIt is now: ${interaction.options.get("name")?.value as string}`
: "") +
"\n\n" +
(createAppealTicket
- ? `You can appeal this in the ticket created in <#${confirmation.components!["appeal"]!.response}>`
+ ? `You can appeal this in the ticket created in <#${
+ confirmation.components!["appeal"]!.response
+ }>`
: "")
)
.setStatus("Danger")
- ], components: []
+ ],
+ components: []
};
if (config.moderation.nick.text && config.moderation.nick.link) {
- messageData.embeds[0]!.setFooter(LinkWarningFooter)
- messageData.components.push(new ActionRowBuilder<ButtonBuilder>()
- .addComponents(new ButtonBuilder()
+ messageData.embeds[0]!.setFooter(LinkWarningFooter);
+ messageData.components.push(
+ new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setLabel(config.moderation.nick.text)
- .setURL(config.moderation.nick.link.replaceAll("{id}", (interaction.options.getMember("user") as GuildMember).id))
- )
- )
+ .setURL(
+ config.moderation.nick.link.replaceAll(
+ "{id}",
+ (interaction.options.getMember("user") as GuildMember).id
+ )
+ )
+ )
+ );
}
dmMessage = await (interaction.options.getMember("user") as GuildMember).send(messageData);
dmSent = true;
@@ -166,7 +182,9 @@
updatedBy: entry(interaction.user.id, renderUser(interaction.user))
},
separate: {
- end: getEmojiByName("ICONS.NOTIFY." + (notify ? "ON" : "OFF")) + ` The user was ${notify ? "" : "not "}notified`
+ end:
+ getEmojiByName("ICONS.NOTIFY." + (notify ? "ON" : "OFF")) +
+ ` The user was ${notify ? "" : "not "}notified`
},
hidden: {
guild: interaction.guild!.id
@@ -221,6 +239,7 @@
export { command, callback, check };
export const metadata = {
- longDescription: "Changes the nickname of a member. This is the name that shows in the member list and on messages.",
- premiumOnly: true,
-}
+ longDescription:
+ "Changes the nickname of a member. This is the name that shows in the member list and on messages.",
+ premiumOnly: true
+};
diff --git a/src/commands/mod/purge.ts b/src/commands/mod/purge.ts
index a1b094e..2c8129e 100644
--- a/src/commands/mod/purge.ts
+++ b/src/commands/mod/purge.ts
@@ -1,4 +1,12 @@
-import Discord, { CommandInteraction, GuildChannel, GuildMember, TextChannel, ButtonStyle, ButtonBuilder, Message } from "discord.js";
+import Discord, {
+ CommandInteraction,
+ GuildChannel,
+ GuildMember,
+ TextChannel,
+ ButtonStyle,
+ ButtonBuilder,
+ Message
+} from "discord.js";
import type { SlashCommandSubcommandBuilder } from "discord.js";
import confirmationMessage from "../../utils/confirmationMessage.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
@@ -27,7 +35,7 @@
const callback = async (interaction: CommandInteraction): Promise<unknown> => {
if (!interaction.guild) return;
- const user = (interaction.options.getMember("user") as GuildMember | null);
+ const user = interaction.options.getMember("user") as GuildMember | null;
const channel = interaction.channel as GuildChannel;
if (!channel.isTextBased()) {
return await interaction.reply({
@@ -93,7 +101,8 @@
let component;
try {
component = m.awaitMessageComponent({
- filter: (i) => i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.id === m.id,
+ filter: (i) =>
+ i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.id === m.id,
time: 300000
});
} catch (e) {
@@ -112,7 +121,7 @@
if (user) {
ms = ms.filter((m) => m.author.id === user.id);
}
- messages = (await (channel as TextChannel).bulkDelete(ms, true)).map(m => m as Discord.Message);
+ messages = (await (channel as TextChannel).bulkDelete(ms, true)).map((m) => m as Discord.Message);
});
deleted = deleted.concat(messages);
}
@@ -133,7 +142,7 @@
interaction.guild.id,
user.user,
interaction.user,
- (interaction.options.get("reason")?.value as (string | null)) ?? "*No reason provided*",
+ (interaction.options.get("reason")?.value as string | null) ?? "*No reason provided*",
null,
null,
deleted.length.toString()
@@ -160,7 +169,11 @@
}
};
log(data);
- const newOut = await client.database.transcripts.createTranscript(deleted, interaction, interaction.member as GuildMember);
+ const newOut = await client.database.transcripts.createTranscript(
+ deleted,
+ interaction,
+ interaction.member as GuildMember
+ );
const transcript = client.database.transcripts.toHumanReadable(newOut);
const attachmentObject = {
attachment: Buffer.from(transcript),
@@ -188,7 +201,8 @@
let component;
try {
component = await m.awaitMessageComponent({
- filter: (i) => i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.id === m.id,
+ filter: (i) =>
+ i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.id === m.id,
time: 300000
});
} catch {
@@ -227,7 +241,11 @@
keyValueList({
channel: `<#${channel.id}>`,
amount: (interaction.options.get("amount")?.value as number).toString(),
- reason: `\n> ${interaction.options.get("reason")?.value ? interaction.options.get("reason")?.value : "*No reason provided*"}`
+ reason: `\n> ${
+ interaction.options.get("reason")?.value
+ ? interaction.options.get("reason")?.value
+ : "*No reason provided*"
+ }`
})
)
.setColor("Danger")
@@ -282,7 +300,7 @@
interaction.guild.id,
user.user,
interaction.user,
- (interaction.options.get("reason")?.value as (string | null)) ?? "*No reason provided*",
+ (interaction.options.get("reason")?.value as string | null) ?? "*No reason provided*",
null,
null,
messages.size.toString()
@@ -309,14 +327,19 @@
}
};
log(data);
- const messageArray: Message[] = messages.filter(message => !(
- message!.components.some(
- component => component.components.some(
- child => child.customId?.includes("transcript") ?? false
- )
+ const messageArray: Message[] = messages
+ .filter(
+ (message) =>
+ !message!.components.some((component) =>
+ component.components.some((child) => child.customId?.includes("transcript") ?? false)
+ )
)
- )).map(message => message as Message);
- const newOut = await client.database.transcripts.createTranscript(messageArray, interaction, interaction.member as GuildMember);
+ .map((message) => message as Message);
+ const newOut = await client.database.transcripts.createTranscript(
+ messageArray,
+ interaction,
+ interaction.member as GuildMember
+ );
const [code, key, iv] = await client.database.transcripts.create(newOut);
@@ -330,8 +353,11 @@
],
components: [
new Discord.ActionRowBuilder<ButtonBuilder>().addComponents([
- new ButtonBuilder().setLabel("View").setStyle(ButtonStyle.Link).setURL(`https://clicks.codes/nucleus/transcript/${code}?key=${key}&iv=${iv}`).setDisabled(!code),
-
+ new ButtonBuilder()
+ .setLabel("View")
+ .setStyle(ButtonStyle.Link)
+ .setURL(`https://clicks.codes/nucleus/transcript/${code}?key=${key}&iv=${iv}`)
+ .setDisabled(!code)
])
]
});
@@ -355,6 +381,7 @@
export { command, callback, check };
export const metadata = {
- longDescription: "Deletes a specified amount of messages from a channel, optionally from a specific user. Without an amount, you can repeatedly choose a number of messages to delete.",
- premiumOnly: true,
-}
+ longDescription:
+ "Deletes a specified amount of messages from a channel, optionally from a specific user. Without an amount, you can repeatedly choose a number of messages to delete.",
+ premiumOnly: true
+};
diff --git a/src/commands/mod/slowmode.ts b/src/commands/mod/slowmode.ts
index f282e82..ba88c00 100644
--- a/src/commands/mod/slowmode.ts
+++ b/src/commands/mod/slowmode.ts
@@ -16,25 +16,25 @@
.setDescription("The delay between messages")
.setRequired(false)
.addChoices(
- {name: "Off", value: "0"},
- {name: "5 seconds", value: "5"},
- {name: "10 seconds", value: "10"},
- {name: "15 seconds", value: "15"},
- {name: "30 seconds", value: "30"},
- {name: "1 minute", value: "60"},
- {name: "2 minutes", value: "120"},
- {name: "5 minutes", value: "300"},
- {name: "10 minutes", value: "600"},
- {name: "15 minutes", value: "900"},
- {name: "30 minutes", value: "1800"},
- {name: "1 hour", value: "3600"},
- {name: "2 hours", value: "7200"},
- {name: "6 hours", value: "21600"}
+ { name: "Off", value: "0" },
+ { name: "5 seconds", value: "5" },
+ { name: "10 seconds", value: "10" },
+ { name: "15 seconds", value: "15" },
+ { name: "30 seconds", value: "30" },
+ { name: "1 minute", value: "60" },
+ { name: "2 minutes", value: "120" },
+ { name: "5 minutes", value: "300" },
+ { name: "10 minutes", value: "600" },
+ { name: "15 minutes", value: "900" },
+ { name: "30 minutes", value: "1800" },
+ { name: "1 hour", value: "3600" },
+ { name: "2 hours", value: "7200" },
+ { name: "6 hours", value: "21600" }
)
);
const callback = async (interaction: CommandInteraction): Promise<void> => {
- let time = parseInt(interaction.options.get("time")?.value as string || "0");
+ let time = parseInt((interaction.options.get("time")?.value as string) || "0");
if (time === 0 && (interaction.channel as TextChannel).rateLimitPerUser === 0) {
time = 10;
}
@@ -82,13 +82,15 @@
if (!member.permissions.has("ManageChannels")) return "You do not have the *Manage Channels* permission";
if (partial) return true;
// Check if Nucleus can set the slowmode
- if (!interaction.guild!.members.me!.permissions.has("ManageChannels")) return "I do not have the *Manage Channels* permission";
+ if (!interaction.guild!.members.me!.permissions.has("ManageChannels"))
+ return "I do not have the *Manage Channels* permission";
// Allow slowmode
return true;
};
export { command, callback, check };
export const metadata = {
- longDescription: "Stops members from being able to send messages without waiting a certain amount of time between messages.",
- premiumOnly: true,
-}
+ longDescription:
+ "Stops members from being able to send messages without waiting a certain amount of time between messages.",
+ premiumOnly: true
+};
diff --git a/src/commands/mod/softban.ts b/src/commands/mod/softban.ts
index 1b404c9..cd03d1a 100644
--- a/src/commands/mod/softban.ts
+++ b/src/commands/mod/softban.ts
@@ -1,4 +1,11 @@
-import Discord, { CommandInteraction, GuildMember, ActionRowBuilder, ButtonBuilder, User, ButtonStyle } from "discord.js";
+import Discord, {
+ CommandInteraction,
+ GuildMember,
+ ActionRowBuilder,
+ ButtonBuilder,
+ User,
+ ButtonStyle
+} from "discord.js";
import type { SlashCommandSubcommandBuilder } from "discord.js";
import confirmationMessage from "../../utils/confirmationMessage.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
@@ -8,7 +15,6 @@
import { LinkWarningFooter } from "../../utils/defaults.js";
import getEmojiByName from "../../utils/getEmojiByName.js";
-
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
.setName("softban")
@@ -23,7 +29,6 @@
.setRequired(false)
);
-
const callback = async (interaction: CommandInteraction): Promise<void> => {
if (!interaction.guild) return;
const { renderUser } = client.logger;
@@ -40,12 +45,13 @@
.setDescription(
keyValueList({
user: renderUser(interaction.options.getUser("user")!),
- reason: reason ? "\n> " + (reason).replaceAll("\n", "\n> ") : "*No reason provided*"
+ reason: reason ? "\n> " + reason.replaceAll("\n", "\n> ") : "*No reason provided*"
}) +
`The user **will${notify ? "" : " not"}** be notified\n` +
`${addPlurals(
- (interaction.options.get("delete")?.value as number | null) ?? 0, "day")
- } of messages will be deleted\n\n` +
+ (interaction.options.get("delete")?.value as number | null) ?? 0,
+ "day"
+ )} of messages will be deleted\n\n` +
`Are you sure you want to softban <@!${(interaction.options.getMember("user") as GuildMember).id}>?`
)
.addCustomBoolean(
@@ -67,15 +73,20 @@
else if (confirmation.success !== undefined) chosen = true;
else if (confirmation.newReason) reason = confirmation.newReason;
else if (confirmation.components) notify = confirmation.components["notify"]!.active;
- } while (!timedOut && !chosen)
+ } while (!timedOut && !chosen);
if (timedOut || !confirmation.success) return;
- reason = reason.length ? reason : null
+ reason = reason.length ? reason : null;
let dmSent = false;
let dmMessage;
const config = await client.database.guilds.read(interaction.guild.id);
try {
if (notify) {
- if (reason) { reason = reason.split("\n").map((line) => "> " + line).join("\n") }
+ if (reason) {
+ reason = reason
+ .split("\n")
+ .map((line) => "> " + line)
+ .join("\n");
+ }
const messageData: {
embeds: EmojiEmbed[];
components: ActionRowBuilder<ButtonBuilder>[];
@@ -93,14 +104,20 @@
components: []
};
if (config.moderation.softban.text && config.moderation.softban.link) {
- messageData.embeds[0]!.setFooter(LinkWarningFooter)
- messageData.components.push(new ActionRowBuilder<Discord.ButtonBuilder>()
- .addComponents(new ButtonBuilder()
+ messageData.embeds[0]!.setFooter(LinkWarningFooter);
+ messageData.components.push(
+ new ActionRowBuilder<Discord.ButtonBuilder>().addComponents(
+ new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setLabel(config.moderation.softban.text)
- .setURL(config.moderation.softban.link.replaceAll("{id}", (interaction.options.getMember("user") as GuildMember).id))
- )
- )
+ .setURL(
+ config.moderation.softban.link.replaceAll(
+ "{id}",
+ (interaction.options.getMember("user") as GuildMember).id
+ )
+ )
+ )
+ );
}
dmMessage = await (interaction.options.getMember("user") as GuildMember).send(messageData);
dmSent = true;
@@ -110,7 +127,7 @@
}
try {
const member = interaction.options.getMember("user") as GuildMember;
- const days: number = interaction.options.get("delete")?.value as number | null ?? 0;
+ const days: number = (interaction.options.get("delete")?.value as number | null) ?? 0;
member.ban({
deleteMessageSeconds: days * 24 * 60 * 60,
reason: reason ?? "*No reason provided*"
@@ -137,7 +154,9 @@
serverMemberCount: interaction.guild.memberCount
},
separate: {
- end: getEmojiByName("ICONS.NOTIFY." + (notify ? "ON" : "OFF")) + ` The user was ${notify ? "" : "not "}notified`
+ end:
+ getEmojiByName("ICONS.NOTIFY." + (notify ? "ON" : "OFF")) +
+ ` The user was ${notify ? "" : "not "}notified`
},
hidden: {
guild: interaction.guild.id
@@ -181,12 +200,12 @@
let apply = interaction.options.getUser("user") as User | GuildMember;
const memberPos = member.roles.cache.size > 1 ? member.roles.highest.position : 0;
const mePos = me.roles.cache.size > 1 ? me.roles.highest.position : 0;
- let applyPos = 0
+ let applyPos = 0;
try {
- apply = await interaction.guild.members.fetch(apply.id) as GuildMember
+ apply = (await interaction.guild.members.fetch(apply.id)) as GuildMember;
applyPos = apply.roles.cache.size > 1 ? apply.roles.highest.position : 0;
} catch {
- apply = apply as User
+ apply = apply as User;
}
// Do not allow banning the owner
if (member.id === interaction.guild.ownerId) return "You cannot softban the owner of the server";
diff --git a/src/commands/mod/unban.ts b/src/commands/mod/unban.ts
index 40f4504..7397414 100644
--- a/src/commands/mod/unban.ts
+++ b/src/commands/mod/unban.ts
@@ -48,7 +48,13 @@
try {
await interaction.guild.members.unban(resolved.user as User, "Unban");
const member = resolved.user as User;
- await client.database.history.create("unban", interaction.guild.id, member, interaction.user, "No reason provided");
+ await client.database.history.create(
+ "unban",
+ interaction.guild.id,
+ member,
+ interaction.user,
+ "No reason provided"
+ );
const { log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
const data = {
meta: {
diff --git a/src/commands/mod/unmute.ts b/src/commands/mod/unmute.ts
index 8562c4c..f248a3b 100644
--- a/src/commands/mod/unmute.ts
+++ b/src/commands/mod/unmute.ts
@@ -29,8 +29,7 @@
keyValueList({
user: renderUser(interaction.options.getUser("user")!),
reason: `\n> ${reason ? reason : "*No reason provided*"}`
- }) +
- `Are you sure you want to unmute <@!${(interaction.options.getMember("user") as GuildMember).id}>?`
+ }) + `Are you sure you want to unmute <@!${(interaction.options.getMember("user") as GuildMember).id}>?`
)
.setColor("Danger")
.addCustomBoolean(
@@ -115,7 +114,9 @@
unmutedBy: entry(interaction.user.id, renderUser(interaction.user))
},
separate: {
- end: getEmojiByName("ICONS.NOTIFY." + (notify ? "ON" : "OFF")) + ` The user was ${notify ? "" : "not "}notified`
+ end:
+ getEmojiByName("ICONS.NOTIFY." + (notify ? "ON" : "OFF")) +
+ ` The user was ${notify ? "" : "not "}notified`
},
hidden: {
guild: interaction.guild.id
@@ -139,8 +140,7 @@
if (!interaction.guild) return;
const member = interaction.member as GuildMember;
// Check if the user has moderate_members permission
- if (!member.permissions.has("ModerateMembers"))
- return "You do not have the *Moderate Members* permission";
+ if (!member.permissions.has("ModerateMembers")) return "You do not have the *Moderate Members* permission";
if (partial) return true;
const me = interaction.guild.members.me!;
const apply = interaction.options.getMember("user") as GuildMember;
diff --git a/src/commands/mod/viewas.ts b/src/commands/mod/viewas.ts
index ef62816..41f34b9 100644
--- a/src/commands/mod/viewas.ts
+++ b/src/commands/mod/viewas.ts
@@ -1,4 +1,4 @@
-import { LoadingEmbed } from './../../utils/defaults.js';
+import { LoadingEmbed } from "./../../utils/defaults.js";
import Discord, {
CommandInteraction,
GuildMember,
@@ -23,20 +23,19 @@
.addUserOption((option) => option.setName("member").setDescription("The member to view as").setRequired(true));
const callback = async (interaction: CommandInteraction): Promise<void> => {
+ const m = await interaction.reply({ embeds: LoadingEmbed, ephemeral: true, fetchReply: true });
- const m = await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true})
-
- let channels: Record<string, GuildBasedChannel[]> = {"": []};
+ let channels: Record<string, GuildBasedChannel[]> = { "": [] };
const channelCollection = await interaction.guild!.channels.fetch();
- channelCollection.forEach(channel => {
+ channelCollection.forEach((channel) => {
if (!channel) return; // if no channel
if (channel.type === Discord.ChannelType.GuildCategory) {
- if(!channels[channel!.id]) channels[channel!.id] = [];
+ if (!channels[channel!.id]) channels[channel!.id] = [];
} else if (channel.parent) {
if (!channels[channel.parent.id]) channels[channel.parent.id] = [channel];
- else (channels[channel.parent.id as string])!.push(channel);
+ else channels[channel.parent.id as string]!.push(channel);
} else {
channels[""]!.push(channel);
}
@@ -47,7 +46,11 @@
for (const category in channels) {
channels[category] = channels[category]!.sort((a: GuildBasedChannel, b: GuildBasedChannel) => {
- const disallowedTypes = [Discord.ChannelType.PublicThread, Discord.ChannelType.PrivateThread, Discord.ChannelType.AnnouncementThread];
+ const disallowedTypes = [
+ Discord.ChannelType.PublicThread,
+ Discord.ChannelType.PrivateThread,
+ Discord.ChannelType.AnnouncementThread
+ ];
if (disallowedTypes.includes(a.type) || disallowedTypes.includes(b.type)) return 0;
a = a as NonThreadGuildBasedChannel;
b = b as NonThreadGuildBasedChannel;
@@ -64,7 +67,11 @@
}
for (const category in channels) {
channels[category] = channels[category]!.filter((c) => {
- return !(c.type === Discord.ChannelType.PublicThread || c.type === Discord.ChannelType.PrivateThread || c.type === Discord.ChannelType.AnnouncementThread)
+ return !(
+ c.type === Discord.ChannelType.PublicThread ||
+ c.type === Discord.ChannelType.PrivateThread ||
+ c.type === Discord.ChannelType.AnnouncementThread
+ );
});
}
channels = Object.fromEntries(Object.entries(channels).filter(([_, v]) => v.length > 0));
@@ -81,12 +88,12 @@
if (last25.length > 0) categoryNames25.push(last25);
const channelTypeEmoji: Record<number, string> = {
- 0: "GUILD_TEXT", // Text channel
- 2: "GUILD_VOICE", // Voice channel
- 5: "GUILD_NEWS", // Announcement channel
- 13: "GUILD_STAGE_VOICE", // Stage channel
- 15: "FORUM", // Forum channel
- 99: "RULES" // Rules channel
+ 0: "GUILD_TEXT", // Text channel
+ 2: "GUILD_VOICE", // Voice channel
+ 5: "GUILD_NEWS", // Announcement channel
+ 13: "GUILD_STAGE_VOICE", // Stage channel
+ 15: "FORUM", // Forum channel
+ 99: "RULES" // Rules channel
};
const NSFWAvailable: number[] = [0, 2, 5, 13];
const rulesChannel = interaction.guild!.rulesChannel?.id;
@@ -94,12 +101,12 @@
async function nameFromChannel(channel: GuildBasedChannel): Promise<string> {
let channelType: Discord.ChannelType | 99 = channel.type;
if (channelType === Discord.ChannelType.GuildCategory) return "";
- if (channel.id === rulesChannel) channelType = 99
+ if (channel.id === rulesChannel) channelType = 99;
let threads: Discord.ThreadChannel[] = [];
if ("threads" in channel) {
threads = channel.threads.cache.toJSON().map((t) => t as Discord.ThreadChannel);
}
- const nsfw = ("nsfw" in channel ? channel.nsfw : false) && NSFWAvailable.includes(channelType)
+ const nsfw = ("nsfw" in channel ? channel.nsfw : false) && NSFWAvailable.includes(channelType);
const emojiName = channelTypeEmoji[channelType.valueOf()] + (nsfw ? "_NSFW" : "");
const emoji = getEmojiByName("ICONS.CHANNEL." + (threads.length ? "THREAD_CHANNEL" : emojiName));
let current = `${emoji} ${channel.name}`;
@@ -118,46 +125,59 @@
description += `${await nameFromChannel(channel)}\n`;
}
- const parsedCategorySelectMenu: ActionRowBuilder<StringSelectMenuBuilder | ButtonBuilder>[] = categoryNames25.map(
- (categories, set) => { return new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(new StringSelectMenuBuilder()
- .setCustomId("category")
- .setMinValues(1)
- .setMaxValues(1)
- .setOptions(categories.map((c, i) => {
- return new StringSelectMenuOptionBuilder()
- .setLabel(c)
- .setValue((set * 25 + i).toString())
- .setEmoji(getEmojiByName("ICONS.CHANNEL.CATEGORY", "id") as APIMessageComponentEmoji) // Again, this is valid but TS doesn't think so
- .setDefault((set * 25 + i) === page)
- }))
- )}
+ const parsedCategorySelectMenu: ActionRowBuilder<StringSelectMenuBuilder | ButtonBuilder>[] =
+ categoryNames25.map((categories, set) => {
+ return new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setCustomId("category")
+ .setMinValues(1)
+ .setMaxValues(1)
+ .setOptions(
+ categories.map((c, i) => {
+ return new StringSelectMenuOptionBuilder()
+ .setLabel(c)
+ .setValue((set * 25 + i).toString())
+ .setEmoji(
+ getEmojiByName("ICONS.CHANNEL.CATEGORY", "id") as APIMessageComponentEmoji
+ ) // Again, this is valid but TS doesn't think so
+ .setDefault(set * 25 + i === page);
+ })
+ )
+ );
+ });
+
+ const components: ActionRowBuilder<ButtonBuilder | StringSelectMenuBuilder>[] = parsedCategorySelectMenu;
+ components.push(
+ new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setStyle(ButtonStyle.Secondary)
+ .setDisabled(page === 0)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id")),
+ new ButtonBuilder()
+ .setCustomId("right")
+ .setStyle(ButtonStyle.Secondary)
+ .setDisabled(page === categoryIDs.length - 1)
+ .setEmoji(getEmojiByName("CONTROL.RIGHT", "id"))
+ )
);
- const components: ActionRowBuilder<ButtonBuilder | StringSelectMenuBuilder>[] = parsedCategorySelectMenu
- components.push(new ActionRowBuilder<ButtonBuilder>().addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setStyle(ButtonStyle.Secondary)
- .setDisabled(page === 0)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id")),
- new ButtonBuilder()
- .setCustomId("right")
- .setStyle(ButtonStyle.Secondary)
- .setDisabled(page === categoryIDs.length - 1)
- .setEmoji(getEmojiByName("CONTROL.RIGHT", "id"))
- ));
-
await interaction.editReply({
- embeds: [new EmojiEmbed()
- .setEmoji("MEMBER.JOIN")
- .setTitle("Viewing as " + member.displayName)
- .setStatus("Success")
- .setDescription(description + "\n" + pageIndicator(categoryIDs.length, page))
- ], components: components
+ embeds: [
+ new EmojiEmbed()
+ .setEmoji("MEMBER.JOIN")
+ .setTitle("Viewing as " + member.displayName)
+ .setStatus("Success")
+ .setDescription(description + "\n" + pageIndicator(categoryIDs.length, page))
+ ],
+ components: components
});
let i;
try {
- i = await m.awaitMessageComponent({filter: (i) => i.user.id === interaction.user.id && i.message.id === m.id, time: 30000});
+ i = await m.awaitMessageComponent({
+ filter: (i) => i.user.id === interaction.user.id && i.message.id === m.id,
+ time: 30000
+ });
} catch (e) {
closed = true;
continue;
diff --git a/src/commands/mod/warn.ts b/src/commands/mod/warn.ts
index ea4f084..5d1bd94 100644
--- a/src/commands/mod/warn.ts
+++ b/src/commands/mod/warn.ts
@@ -32,15 +32,15 @@
keyValueList({
user: renderUser(interaction.options.getUser("user")!),
reason: reason ? "\n> " + reason.replaceAll("\n", "\n> ") : "*No reason provided*"
- }) +
- `Are you sure you want to warn <@!${(interaction.options.getMember("user") as GuildMember).id}>?`
+ }) + `Are you sure you want to warn <@!${(interaction.options.getMember("user") as GuildMember).id}>?`
)
.setColor("Danger")
.addCustomBoolean(
"appeal",
"Create appeal ticket",
!(await areTicketsEnabled(interaction.guild.id)),
- async () => await create(interaction.guild!, interaction.options.getUser("user")!, interaction.user, reason),
+ async () =>
+ await create(interaction.guild!, interaction.options.getUser("user")!, interaction.user, reason),
"An appeal ticket will be created",
null,
"CONTROL.TICKET",
@@ -67,13 +67,18 @@
notify = confirmation.components["notify"]!.active;
createAppealTicket = confirmation.components["appeal"]!.active;
}
- } while (!timedOut && !success)
+ } while (!timedOut && !success);
if (timedOut || !success) return;
let dmSent = false;
const config = await client.database.guilds.read(interaction.guild.id);
try {
if (notify) {
- if (reason) { reason = reason.split("\n").map((line) => "> " + line).join("\n") }
+ if (reason) {
+ reason = reason
+ .split("\n")
+ .map((line) => "> " + line)
+ .join("\n");
+ }
const messageData: {
embeds: EmojiEmbed[];
components: ActionRowBuilder<ButtonBuilder>[];
@@ -87,7 +92,9 @@
(reason ? ` for:\n${reason}` : ".\n*No reason was provided*") +
"\n\n" +
(createAppealTicket
- ? `You can appeal this in the ticket created in <#${confirmation.components!["appeal"]!.response}>`
+ ? `You can appeal this in the ticket created in <#${
+ confirmation.components!["appeal"]!.response
+ }>`
: "")
)
.setStatus("Danger")
@@ -95,14 +102,20 @@
components: []
};
if (config.moderation.warn.text && config.moderation.warn.link) {
- messageData.embeds[0]!.setFooter(LinkWarningFooter)
- messageData.components.push(new ActionRowBuilder<Discord.ButtonBuilder>()
- .addComponents(new ButtonBuilder()
+ messageData.embeds[0]!.setFooter(LinkWarningFooter);
+ messageData.components.push(
+ new ActionRowBuilder<Discord.ButtonBuilder>().addComponents(
+ new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setLabel(config.moderation.warn.text)
- .setURL(config.moderation.warn.link.replaceAll("{id}", (interaction.options.getMember("user") as GuildMember).id))
- )
- )
+ .setURL(
+ config.moderation.warn.link.replaceAll(
+ "{id}",
+ (interaction.options.getMember("user") as GuildMember).id
+ )
+ )
+ )
+ );
}
await (interaction.options.getMember("user") as GuildMember).send(messageData);
dmSent = true;
@@ -128,7 +141,9 @@
reason: reason ? reason : "*No reason provided*"
},
separate: {
- end: getEmojiByName("ICONS.NOTIFY." + (notify ? "ON" : "OFF")) + ` The user was ${notify ? "" : "not "}notified`
+ end:
+ getEmojiByName("ICONS.NOTIFY." + (notify ? "ON" : "OFF")) +
+ ` The user was ${notify ? "" : "not "}notified`
},
hidden: {
guild: interaction.guild.id
@@ -152,7 +167,9 @@
.setDescription(
"The user was warned" +
(createAppealTicket
- ? ` and an appeal ticket was opened in <#${confirmation.components!["appeal"]!.response}>`
+ ? ` and an appeal ticket was opened in <#${
+ confirmation.components!["appeal"]!.response
+ }>`
: "")
)
.setStatus("Success")
@@ -173,7 +190,10 @@
],
components: [
new ActionRowBuilder<Discord.ButtonBuilder>().addComponents(
- new Discord.ButtonBuilder().setCustomId("log").setLabel("Ignore and log").setStyle(ButtonStyle.Secondary),
+ new Discord.ButtonBuilder()
+ .setCustomId("log")
+ .setLabel("Ignore and log")
+ .setStyle(ButtonStyle.Secondary),
new Discord.ButtonBuilder()
.setCustomId("here")
.setLabel("Warn here")
@@ -190,7 +210,8 @@
let component;
try {
component = await m.awaitMessageComponent({
- filter: (i) => i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.id === m.id,
+ filter: (i) =>
+ i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.id === m.id,
time: 300000
});
} catch (e) {
@@ -227,7 +248,9 @@
.setDescription(
"The user was warned" +
(createAppealTicket
- ? ` and an appeal ticket was opened in <#${confirmation.components!["appeal"]!.response}>`
+ ? ` and an appeal ticket was opened in <#${
+ confirmation.components!["appeal"]!.response
+ }>`
: "")
)
.setStatus("Success")
@@ -282,9 +305,8 @@
const check = (interaction: CommandInteraction, partial: boolean = false) => {
if (!interaction.guild) return;
const member = interaction.member as GuildMember;
- if (!member.permissions.has("ModerateMembers"))
- return "You do not have the *Moderate Members* permission";
- if(partial) return true;
+ if (!member.permissions.has("ModerateMembers")) return "You do not have the *Moderate Members* permission";
+ if (partial) return true;
const apply = interaction.options.getMember("user") as GuildMember | null;
if (apply === null) return "That member is not in the server";
const memberPos = member.roles.cache.size ? member.roles.highest.position : 0;
diff --git a/src/commands/nucleus/guide.ts b/src/commands/nucleus/guide.ts
index 270ee62..d05e265 100644
--- a/src/commands/nucleus/guide.ts
+++ b/src/commands/nucleus/guide.ts
@@ -1,4 +1,4 @@
-import type { CommandInteraction } from 'discord.js';
+import type { CommandInteraction } from "discord.js";
import type { SlashCommandSubcommandBuilder } from "discord.js";
import guide from "../../reflex/guide.js";
diff --git a/src/commands/nucleus/invite.ts b/src/commands/nucleus/invite.ts
index b89425a..6805adb 100644
--- a/src/commands/nucleus/invite.ts
+++ b/src/commands/nucleus/invite.ts
@@ -21,7 +21,9 @@
.setLabel("Invite")
.setStyle(ButtonStyle.Link)
.setURL(
- `https://discord.com/api/oauth2/authorize?client_id=${client.user!.id}&permissions=295157886134&scope=bot%20applications.commands`
+ `https://discord.com/api/oauth2/authorize?client_id=${
+ client.user!.id
+ }&permissions=295157886134&scope=bot%20applications.commands`
)
])
],
diff --git a/src/commands/nucleus/ping.ts b/src/commands/nucleus/ping.ts
index 3e02a8f..62988bb 100644
--- a/src/commands/nucleus/ping.ts
+++ b/src/commands/nucleus/ping.ts
@@ -19,8 +19,8 @@
.setTitle("Ping")
.setDescription(
`**Ping:** \`${ping}ms\`\n` +
- `**To Discord:** \`${client.ws.ping}ms\`\n` +
- `**From Expected:** \`±${Math.abs(ping / 2 - client.ws.ping)}ms\``
+ `**To Discord:** \`${client.ws.ping}ms\`\n` +
+ `**From Expected:** \`±${Math.abs(ping / 2 - client.ws.ping)}ms\``
)
.setEmoji("CHANNEL.SLOWMODE.OFF")
.setStatus("Danger")
diff --git a/src/commands/nucleus/premium.ts b/src/commands/nucleus/premium.ts
index c431c8e..721bc5c 100644
--- a/src/commands/nucleus/premium.ts
+++ b/src/commands/nucleus/premium.ts
@@ -1,4 +1,14 @@
-import { ActionRowBuilder, ButtonBuilder, ButtonInteraction, ButtonStyle, CommandInteraction, ComponentType, Message, StringSelectMenuBuilder, StringSelectMenuInteraction } from "discord.js";
+import {
+ ActionRowBuilder,
+ ButtonBuilder,
+ ButtonInteraction,
+ ButtonStyle,
+ CommandInteraction,
+ ComponentType,
+ Message,
+ StringSelectMenuBuilder,
+ StringSelectMenuInteraction
+} from "discord.js";
import type { SlashCommandSubcommandBuilder } from "discord.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import client from "../../utils/client.js";
@@ -13,53 +23,54 @@
let closed = false;
do {
const dbUser = await client.database.premium.fetchUser(interaction.user.id);
- if(!dbUser) {
- await interaction.editReply({embeds: [
- new EmojiEmbed()
- .setTitle("Premium")
- .setDescription(`*You do not have premium! You can't activate premium on any servers.*` + firstDescription)
- .setEmoji("NUCLEUS.LOGO")
- .setStatus("Danger")
- ]});
+ if (!dbUser) {
+ await interaction.editReply({
+ embeds: [
+ new EmojiEmbed()
+ .setTitle("Premium")
+ .setDescription(
+ `*You do not have premium! You can't activate premium on any servers.*` + firstDescription
+ )
+ .setEmoji("NUCLEUS.LOGO")
+ .setStatus("Danger")
+ ]
+ });
return;
}
const premiumGuilds = dbUser.appliesTo.map((guildID) => {
const guild = client.guilds.cache.get(guildID);
- if(!guild) return undefined;
+ if (!guild) return undefined;
return guild.name;
});
const options = premiumGuilds.filter((guild) => guild !== undefined) as string[];
- const removeRow = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("currentPremium")
- .setPlaceholder("Select a server to remove premium from")
- .setDisabled(premiumGuilds.length === 0)
- .addOptions(options.slice(0, Math.min(options.length, 24)).map((guild) => {
- return {label: guild, value: guild}
- }))
- );
- const cancel = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("cancel")
- .setLabel("Close")
- .setStyle(ButtonStyle.Danger)
- );
+ const removeRow = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setCustomId("currentPremium")
+ .setPlaceholder("Select a server to remove premium from")
+ .setDisabled(premiumGuilds.length === 0)
+ .addOptions(
+ options.slice(0, Math.min(options.length, 24)).map((guild) => {
+ return { label: guild, value: guild };
+ })
+ )
+ );
+ const cancel = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder().setCustomId("cancel").setLabel("Close").setStyle(ButtonStyle.Danger)
+ );
const components: ActionRowBuilder<StringSelectMenuBuilder | ButtonBuilder>[] = [cancel];
- if(options.length > 0) components.unshift(removeRow);
- await interaction.editReply(
- {
+ if (options.length > 0) components.unshift(removeRow);
+ await interaction.editReply({
embeds: [
new EmojiEmbed()
.setTitle("Premium")
.setDescription(
`*You have premium on the following servers:*\n\n` +
- (options.length > 0 ? options.join(', ') : `You have not activated premium in any guilds`) +
- firstDescription)
+ (options.length > 0 ? options.join(", ") : `You have not activated premium in any guilds`) +
+ firstDescription
+ )
.setEmoji("NUCLEUS.LOGO")
.setStatus("Success")
],
@@ -69,43 +80,66 @@
let i: StringSelectMenuInteraction | ButtonInteraction;
try {
const filter = (i: StringSelectMenuInteraction | ButtonInteraction) => i.user.id === interaction.user.id;
- i = await msg.awaitMessageComponent<ComponentType.StringSelect | ComponentType.Button>({time: 300000, filter})
+ i = await msg.awaitMessageComponent<ComponentType.StringSelect | ComponentType.Button>({
+ time: 300000,
+ filter
+ });
} catch (e) {
await interaction.deleteReply();
closed = true;
break;
}
await i.deferUpdate();
- if(i.isButton()) {
+ if (i.isButton()) {
closed = true;
} else {
const response = client.database.premium.removePremium(interaction.user.id, i.values[0]!);
- console.log(response)
+ console.log(response);
}
} while (!closed);
await interaction.deleteReply();
-}
+};
const callback = async (interaction: CommandInteraction): Promise<void> => {
if (interaction.guild) client.database.premium.hasPremium(interaction.guild.id).finally(() => {});
- const m = await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true})
- const member = await (await interaction.client.guilds.fetch("684492926528651336")).members.fetch(interaction.user.id).catch(() => {
- interaction.editReply({ embeds: [
- new EmojiEmbed()
- .setTitle("Premium")
- .setDescription(`*You are not currently in the Clicks Server. To gain access to premium please join.*` + firstDescription)
- .setEmoji("NUCLEUS.LOGO")
- .setStatus("Danger")
- ], components: [new ActionRowBuilder<ButtonBuilder>().addComponents(new ButtonBuilder().setStyle(ButtonStyle.Link).setLabel("Join").setURL("https://discord.gg/bPaNnxe"))] });
- })
+ const m = await interaction.reply({ embeds: LoadingEmbed, ephemeral: true, fetchReply: true });
+ const member = await (await interaction.client.guilds.fetch("684492926528651336")).members
+ .fetch(interaction.user.id)
+ .catch(() => {
+ interaction.editReply({
+ embeds: [
+ new EmojiEmbed()
+ .setTitle("Premium")
+ .setDescription(
+ `*You are not currently in the Clicks Server. To gain access to premium please join.*` +
+ firstDescription
+ )
+ .setEmoji("NUCLEUS.LOGO")
+ .setStatus("Danger")
+ ],
+ components: [
+ new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setStyle(ButtonStyle.Link)
+ .setLabel("Join")
+ .setURL("https://discord.gg/bPaNnxe")
+ )
+ ]
+ });
+ });
if (!member) return;
- const firstDescription = "\n\nPremium allows servers of your choice to get access to extra features for a fixed price per month.\nThis includes:\n" +
- `${getEmojiByName("MOD.IMAGES.TOOSMALL")} Attachment logs - Stores attachments so they can be viewed after a message is deleted.\n` +
- `${getEmojiByName("GUILD.TICKET.ARCHIVED")} Ticket Transcripts - Gives a link to view the history of a ticket after it has been closed.\n`
- const dbMember = await client.database.premium.fetchUser(interaction.user.id)
+ const firstDescription =
+ "\n\nPremium allows servers of your choice to get access to extra features for a fixed price per month.\nThis includes:\n" +
+ `${getEmojiByName(
+ "MOD.IMAGES.TOOSMALL"
+ )} Attachment logs - Stores attachments so they can be viewed after a message is deleted.\n` +
+ `${getEmojiByName(
+ "GUILD.TICKET.ARCHIVED"
+ )} Ticket Transcripts - Gives a link to view the history of a ticket after it has been closed.\n`;
+ const dbMember = await client.database.premium.fetchUser(interaction.user.id);
let premium = `You do not have premium! You can't activate premium on any servers.`;
let count = 0;
- const {level, appliesTo} = dbMember ?? {level: 0, appliesTo: []}
+ const { level, appliesTo } = dbMember ?? { level: 0, appliesTo: [] };
if (level === 99) {
premium = `You have Infinite Premium! You have been gifted this by the developers as a thank you. You can give premium to any and all servers you are in.`;
count = 200;
@@ -116,51 +150,53 @@
premium = `You have Premium tier 2! You can give premium to ${3 - appliesTo.length} more server(s).`;
count = 3;
} else if (level === 3) {
- premium = `You have Premium Mod! You can give premium to ${3 - appliesTo.length} more server(s), as well as automatically giving premium to all servers you have a "manage" permission in.`
+ premium = `You have Premium Mod! You can give premium to ${
+ 3 - appliesTo.length
+ } more server(s), as well as automatically giving premium to all servers you have a "manage" permission in.`;
count = 3;
}
if (dbMember?.expiresAt) {
- premium = `**You can't give servers premium anymore because your subscription ended or was cancelled.** To get premium again please subscribe in the Clicks server`
+ premium = `**You can't give servers premium anymore because your subscription ended or was cancelled.** To get premium again please subscribe in the Clicks server`;
count = 0;
}
- if(!interaction.guild) return await dmcallback(interaction, firstDescription, m);
+ if (!interaction.guild) return await dmcallback(interaction, firstDescription, m);
const hasPremium = await client.database.premium.hasPremium(interaction.guild!.id);
- let premiumGuild = ""
+ let premiumGuild = "";
if (hasPremium) {
- premiumGuild = `**This server has premium! It was ${hasPremium[2] === 3 && hasPremium[3] ? `automatically applied by <@${hasPremium[1]}>` : `given by <@${hasPremium[1]}>`}**\n\n`
+ premiumGuild = `**This server has premium! It was ${
+ hasPremium[2] === 3 && hasPremium[3]
+ ? `automatically applied by <@${hasPremium[1]}>`
+ : `given by <@${hasPremium[1]}>`
+ }**\n\n`;
}
- const components: ActionRowBuilder<ButtonBuilder>[] = []
+ const components: ActionRowBuilder<ButtonBuilder>[] = [];
if (level === 0 || dbMember?.expiresAt) {
components.push(
- new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
+ new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setLabel("Join Clicks")
.setURL("https://discord.gg/bPaNnxe")
- )
- )
+ )
+ );
} else {
components.push(
- new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setStyle(premiumGuild.length > 0 ? ButtonStyle.Secondary : ButtonStyle.Success)
- .setLabel(premiumGuild.length > 0 ? "This server has premium" : "Activate premium here")
- .setCustomId("premiumActivate")
- .setDisabled(count <= 0 || (hasPremium ? hasPremium[0] : false))
- )
- )
+ new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setStyle(premiumGuild.length > 0 ? ButtonStyle.Secondary : ButtonStyle.Success)
+ .setLabel(premiumGuild.length > 0 ? "This server has premium" : "Activate premium here")
+ .setCustomId("premiumActivate")
+ .setDisabled(count <= 0 || (hasPremium ? hasPremium[0] : false))
+ )
+ );
}
interaction.editReply({
embeds: [
new EmojiEmbed()
.setTitle("Premium")
- .setDescription(
- premiumGuild + premium + firstDescription
- )
+ .setDescription(premiumGuild + premium + firstDescription)
.setEmoji("NUCLEUS.LOGO")
.setStatus("Danger")
.setImage("https://assets.clicks.codes/ads/ads/nucleus-premium.png")
@@ -196,9 +232,7 @@
embeds: [
new EmojiEmbed()
.setTitle("Premium")
- .setDescription(
- `You have activated premium on this server!` + firstDescription
- )
+ .setDescription(`You have activated premium on this server!` + firstDescription)
.setEmoji("NUCLEUS.LOGO")
.setStatus("Danger")
],
diff --git a/src/commands/nucleus/suggest.ts b/src/commands/nucleus/suggest.ts
index 6ba3445..79a0673 100644
--- a/src/commands/nucleus/suggest.ts
+++ b/src/commands/nucleus/suggest.ts
@@ -1,11 +1,11 @@
-import { LoadingEmbed } from '../../utils/defaults.js';
+import { LoadingEmbed } from "../../utils/defaults.js";
import { ButtonStyle, CommandInteraction } from "discord.js";
import Discord from "discord.js";
import type { SlashCommandSubcommandBuilder } from "discord.js";
import confirmationMessage from "../../utils/confirmationMessage.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import client from "../../utils/client.js";
-import getEmojiByName from '../../utils/getEmojiByName.js';
+import getEmojiByName from "../../utils/getEmojiByName.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
@@ -16,10 +16,10 @@
);
const callback = async (interaction: CommandInteraction): Promise<void> => {
- await interaction.guild?.members.fetch(interaction.member!.user.id)
+ await interaction.guild?.members.fetch(interaction.member!.user.id);
const { renderUser } = client.logger;
const suggestion = interaction.options.get("suggestion")?.value as string;
- await interaction.reply({embeds: LoadingEmbed, ephemeral: true})
+ await interaction.reply({ embeds: LoadingEmbed, ephemeral: true });
const confirmation = await new confirmationMessage(interaction)
.setEmoji("ICONS.OPP.ADD")
.setTitle("Suggest")
@@ -37,22 +37,27 @@
new EmojiEmbed()
.setTitle("Suggestion")
.setDescription(
- `**From:** ${renderUser(interaction.member!.user as Discord.User)}\n**Suggestion:**\n> ${suggestion}\n\n` +
- `**Server:** ${interaction.guild!.name} (${interaction.guild!.id})\n`,
+ `**From:** ${renderUser(
+ interaction.member!.user as Discord.User
+ )}\n**Suggestion:**\n> ${suggestion}\n\n` +
+ `**Server:** ${interaction.guild!.name} (${interaction.guild!.id})\n`
)
.setStatus("Warning")
- ], components: [new Discord.ActionRowBuilder<Discord.ButtonBuilder>().addComponents(
- new Discord.ButtonBuilder()
- .setCustomId("suggestionAccept")
- .setLabel("Accept")
- .setStyle(ButtonStyle.Secondary)
- .setEmoji(getEmojiByName("ICONS.ADD", "id")),
- new Discord.ButtonBuilder()
- .setCustomId("suggestionDeny")
- .setLabel("Delete")
- .setStyle(ButtonStyle.Secondary)
- .setEmoji(getEmojiByName("ICONS.REMOVE", "id"))
- )]
+ ],
+ components: [
+ new Discord.ActionRowBuilder<Discord.ButtonBuilder>().addComponents(
+ new Discord.ButtonBuilder()
+ .setCustomId("suggestionAccept")
+ .setLabel("Accept")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("ICONS.ADD", "id")),
+ new Discord.ButtonBuilder()
+ .setCustomId("suggestionDeny")
+ .setLabel("Delete")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("ICONS.REMOVE", "id"))
+ )
+ ]
});
await interaction.editReply({
embeds: [
diff --git a/src/commands/privacy.ts b/src/commands/privacy.ts
index 69c8980..1b0c6bb 100644
--- a/src/commands/privacy.ts
+++ b/src/commands/privacy.ts
@@ -1,5 +1,14 @@
import { LoadingEmbed } from "../utils/defaults.js";
-import Discord, { SlashCommandBuilder, CommandInteraction, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuOptionBuilder, SelectMenuOptionBuilder, StringSelectMenuBuilder } from "discord.js";
+import Discord, {
+ SlashCommandBuilder,
+ CommandInteraction,
+ ActionRowBuilder,
+ ButtonBuilder,
+ ButtonStyle,
+ StringSelectMenuOptionBuilder,
+ SelectMenuOptionBuilder,
+ StringSelectMenuBuilder
+} from "discord.js";
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
import getEmojiByName from "../utils/getEmojiByName.js";
import createPageIndicator from "../utils/createPageIndicator.js";
@@ -11,7 +20,6 @@
.setName("privacy")
.setDescription("Information and options for you and your server's settings");
-
const callback = async (interaction: CommandInteraction): Promise<void> => {
const pages = [
new Embed()
@@ -48,7 +56,7 @@
new EmojiEmbed()
.setTitle("Link scanning and Transcripts")
.setDescription(
- "Transcripts allow you to store all messages sent in a channel. Transcripts are stored in our database along with the rest of the server's settings but is accessible by anyone with the link, so a leaked link could show all messages sent in the channel.\n"
+ "Transcripts allow you to store all messages sent in a channel. Transcripts are stored in our database along with the rest of the server's settings but is accessible by anyone with the link, so a leaked link could show all messages sent in the channel.\n"
)
.setEmoji("NUCLEUS.LOGO")
.setStatus("Danger")
@@ -59,26 +67,26 @@
].concat(
(interaction.member as Discord.GuildMember).permissions.has("Administrator")
? [
- new Embed()
- .setEmbed(
- new EmojiEmbed()
- .setTitle("Options")
- .setDescription("Below are buttons for controlling this servers privacy settings")
- .setEmoji("NUCLEUS.LOGO")
- .setStatus("Danger")
- )
- .setTitle("Options")
- .setDescription("Options")
- .setPageId(3)
- .setComponents([
- new ActionRowBuilder<ButtonBuilder>().addComponents([
- new ButtonBuilder()
- .setLabel("Clear all data")
- .setCustomId("clear-all-data")
- .setStyle(ButtonStyle.Danger)
- ])
- ])
- ]
+ new Embed()
+ .setEmbed(
+ new EmojiEmbed()
+ .setTitle("Options")
+ .setDescription("Below are buttons for controlling this servers privacy settings")
+ .setEmoji("NUCLEUS.LOGO")
+ .setStatus("Danger")
+ )
+ .setTitle("Options")
+ .setDescription("Options")
+ .setPageId(3)
+ .setComponents([
+ new ActionRowBuilder<ButtonBuilder>().addComponents([
+ new ButtonBuilder()
+ .setLabel("Clear all data")
+ .setCustomId("clear-all-data")
+ .setStyle(ButtonStyle.Danger)
+ ])
+ ])
+ ]
: []
);
const m = await interaction.reply({
@@ -86,7 +94,9 @@
fetchReply: true,
ephemeral: true
});
- let page = parseInt(client.preloadPage[interaction.channel!.id] ? client.preloadPage[interaction.channel!.id]?.argument! : "0");
+ let page = parseInt(
+ client.preloadPage[interaction.channel!.id] ? client.preloadPage[interaction.channel!.id]?.argument! : "0"
+ );
let selectPaneOpen = false;
let nextFooter = null;
@@ -146,7 +156,13 @@
try {
i = await m.awaitMessageComponent({
time: 300000,
- filter: (i) => { return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.message.id === m.id }
+ filter: (i) => {
+ return (
+ i.user.id === interaction.user.id &&
+ i.channel!.id === interaction.channel!.id &&
+ i.message.id === m.id
+ );
+ }
});
} catch (e) {
timedOut = true;
@@ -206,6 +222,5 @@
});
};
-
export { command };
export { callback };
diff --git a/src/commands/server/about.ts b/src/commands/server/about.ts
index 4c88365..815b9e6 100644
--- a/src/commands/server/about.ts
+++ b/src/commands/server/about.ts
@@ -8,27 +8,26 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder.setName("about").setDescription("Shows info about the server");
-
const verificationTypes = {
0: "None - Unrestricted",
1: "Low - Must have a verified email",
2: "Medium - Must be registered for 5 minutes",
3: "High - Must be a member for 10 minutes",
4: "Highest - Must have a verified phone"
-}
+};
const premiumTiers = {
0: "None",
1: "Tier 1",
2: "Tier 2",
3: "Tier 3"
-}
+};
const filterLevels = {
0: "Disabled",
1: "Members without roles",
2: "All members"
-}
+};
const callback = async (interaction: CommandInteraction): Promise<void> => {
const guild = interaction.guild!;
@@ -49,10 +48,10 @@
`${guild.emojis.cache.size}` +
(guild.emojis.cache.size > 1
? `\n> ${guild.emojis.cache
- .first(10)
- .map((emoji) => `<${emoji.animated ? "a" : ""}:${emoji.name}:${emoji.id}>`)
- .join(" ")}` +
- (guild.emojis.cache.size > 10 ? ` and ${guild.emojis.cache.size - 10} more` : "")
+ .first(10)
+ .map((emoji) => `<${emoji.animated ? "a" : ""}:${emoji.name}:${emoji.id}>`)
+ .join(" ")}` +
+ (guild.emojis.cache.size > 10 ? ` and ${guild.emojis.cache.size - 10} more` : "")
: ""),
icon: `[Discord](${guild.iconURL()})`,
"2 factor authentication": `${
diff --git a/src/commands/server/buttons.ts b/src/commands/server/buttons.ts
index 3297616..3ba9c25 100644
--- a/src/commands/server/buttons.ts
+++ b/src/commands/server/buttons.ts
@@ -1,4 +1,19 @@
-import { ActionRowBuilder, APIMessageComponentEmoji, ButtonBuilder, ButtonStyle, ChannelSelectMenuBuilder, ChannelType, CommandInteraction, MessageCreateOptions, ModalBuilder, SlashCommandSubcommandBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, TextInputBuilder, TextInputStyle } from "discord.js";
+import {
+ ActionRowBuilder,
+ APIMessageComponentEmoji,
+ ButtonBuilder,
+ ButtonStyle,
+ ChannelSelectMenuBuilder,
+ ChannelType,
+ CommandInteraction,
+ MessageCreateOptions,
+ ModalBuilder,
+ SlashCommandSubcommandBuilder,
+ StringSelectMenuBuilder,
+ StringSelectMenuOptionBuilder,
+ TextInputBuilder,
+ TextInputStyle
+} from "discord.js";
import type Discord from "discord.js";
import { LoadingEmbed } from "../../utils/defaults.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
@@ -11,32 +26,31 @@
.setDescription("Create clickable buttons for verifying, role menus etc.");
interface Data {
- buttons: string[],
- title: string | null,
- description: string | null,
- color: number,
- channel: string | null
+ buttons: string[];
+ title: string | null;
+ description: string | null;
+ color: number;
+ channel: string | null;
}
-const colors: Record<string, number> = {
- RED: 0xF27878,
- ORANGE: 0xE5AB71,
- YELLOW: 0xF2D478,
- GREEN: 0x65CC76,
- BLUE: 0x72AEF5,
- PURPLE: 0xA358B2,
- PINK: 0xD46899,
- GRAY: 0x999999,
-}
+const colors: Record<string, number> = {
+ RED: 0xf27878,
+ ORANGE: 0xe5ab71,
+ YELLOW: 0xf2d478,
+ GREEN: 0x65cc76,
+ BLUE: 0x72aef5,
+ PURPLE: 0xa358b2,
+ PINK: 0xd46899,
+ GRAY: 0x999999
+};
const buttonNames: Record<string, string> = {
verifybutton: "Verify",
rolemenu: "Role Menu",
createticket: "Create Ticket"
-}
+};
export const callback = async (interaction: CommandInteraction): Promise<void> => {
-
const m = await interaction.reply({
embeds: LoadingEmbed,
fetchReply: true,
@@ -50,81 +64,76 @@
description: null,
color: colors["RED"]!,
channel: interaction.channelId
- }
+ };
do {
+ const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder().setCustomId("edit").setLabel("Edit Embed").setStyle(ButtonStyle.Secondary),
+ new ButtonBuilder()
+ .setCustomId("send")
+ .setLabel("Send")
+ .setStyle(ButtonStyle.Primary)
+ .setDisabled(!data.channel)
+ );
- const buttons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("edit")
- .setLabel("Edit Embed")
- .setStyle(ButtonStyle.Secondary),
- new ButtonBuilder()
- .setCustomId("send")
- .setLabel("Send")
- .setStyle(ButtonStyle.Primary)
- .setDisabled(!data.channel)
- );
+ const colorSelect = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setCustomId("color")
+ .setPlaceholder("Select a color")
+ .setMinValues(1)
+ .addOptions(
+ Object.keys(colors).map((color: string) => {
+ return new StringSelectMenuOptionBuilder()
+ .setLabel(lodash.capitalize(color))
+ .setValue(color)
+ .setEmoji(getEmojiByName("COLORS." + color, "id") as APIMessageComponentEmoji)
+ .setDefault(data.color === colors[color]);
+ })
+ )
+ );
- const colorSelect = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("color")
- .setPlaceholder("Select a color")
- .setMinValues(1)
- .addOptions(
- Object.keys(colors).map((color: string) => {
- return new StringSelectMenuOptionBuilder()
- .setLabel(lodash.capitalize(color))
- .setValue(color)
- .setEmoji(getEmojiByName("COLORS." + color, "id") as APIMessageComponentEmoji)
- .setDefault(data.color === colors[color])
- }
- )
- )
- );
+ const buttonSelect = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setCustomId("button")
+ .setPlaceholder("Select buttons to add")
+ .setMinValues(1)
+ .setMaxValues(3)
+ .addOptions(
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Verify")
+ .setValue("verifybutton")
+ .setDescription("Click to get verified in the server")
+ .setDefault(data.buttons.includes("verifybutton")),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Role Menu")
+ .setValue("rolemenu")
+ .setDescription("Click to customize your roles")
+ .setDefault(data.buttons.includes("rolemenu")),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Ticket")
+ .setValue("createticket")
+ .setDescription("Click to create a support ticket")
+ .setDefault(data.buttons.includes("createticket"))
+ )
+ );
- const buttonSelect = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("button")
- .setPlaceholder("Select buttons to add")
- .setMinValues(1)
- .setMaxValues(3)
- .addOptions(
- new StringSelectMenuOptionBuilder()
- .setLabel("Verify")
- .setValue("verifybutton")
- .setDescription("Click to get verified in the server")
- .setDefault(data.buttons.includes("verifybutton")),
- new StringSelectMenuOptionBuilder()
- .setLabel("Role Menu")
- .setValue("rolemenu")
- .setDescription("Click to customize your roles")
- .setDefault(data.buttons.includes("rolemenu")),
- new StringSelectMenuOptionBuilder()
- .setLabel("Ticket")
- .setValue("createticket")
- .setDescription("Click to create a support ticket")
- .setDefault(data.buttons.includes("createticket"))
- )
- )
-
- const channelMenu = new ActionRowBuilder<ChannelSelectMenuBuilder>()
- .addComponents(
- new ChannelSelectMenuBuilder()
- .setCustomId("channel")
- .setPlaceholder("Select a channel")
- .setChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement, ChannelType.PublicThread, ChannelType.AnnouncementThread)
- )
+ const channelMenu = new ActionRowBuilder<ChannelSelectMenuBuilder>().addComponents(
+ new ChannelSelectMenuBuilder()
+ .setCustomId("channel")
+ .setPlaceholder("Select a channel")
+ .setChannelTypes(
+ ChannelType.GuildText,
+ ChannelType.GuildAnnouncement,
+ ChannelType.PublicThread,
+ ChannelType.AnnouncementThread
+ )
+ );
let channelName = interaction.guild!.channels.cache.get(data.channel!)?.name;
if (data.channel === interaction.channelId) channelName = "this channel";
const embed = new EmojiEmbed()
.setTitle(data.title ?? "No title set")
.setDescription(data.description ?? "*No description set*")
.setColor(data.color)
- .setFooter({text: `Click the button below to edit the embed | The embed will be sent in ${channelName}`});
-
+ .setFooter({ text: `Click the button below to edit the embed | The embed will be sent in ${channelName}` });
await interaction.editReply({
embeds: [embed],
@@ -133,16 +142,19 @@
let i: Discord.ButtonInteraction | Discord.ChannelSelectMenuInteraction | Discord.StringSelectMenuInteraction;
try {
- i = await interaction.channel!.awaitMessageComponent({
+ i = (await interaction.channel!.awaitMessageComponent({
filter: (i: Discord.Interaction) => i.user.id === interaction.user.id,
time: 300000
- }) as Discord.ButtonInteraction | Discord.ChannelSelectMenuInteraction | Discord.StringSelectMenuInteraction;
+ })) as
+ | Discord.ButtonInteraction
+ | Discord.ChannelSelectMenuInteraction
+ | Discord.StringSelectMenuInteraction;
} catch (e) {
closed = true;
break;
}
- if(i.isButton()) {
- switch(i.customId) {
+ if (i.isButton()) {
+ switch (i.customId) {
case "edit": {
await i.showModal(
new ModalBuilder()
@@ -189,43 +201,56 @@
});
let out: Discord.ModalSubmitInteraction | null;
try {
- out = await modalInteractionCollector(m, interaction.user) as Discord.ModalSubmitInteraction | null;
+ out = (await modalInteractionCollector(
+ m,
+ interaction.user
+ )) as Discord.ModalSubmitInteraction | null;
} catch (e) {
closed = true;
continue;
}
- if (!out || out.isButton()) continue
- data.title = out.fields.getTextInputValue("title").length === 0 ? null : out.fields.getTextInputValue("title");
- data.description = out.fields.getTextInputValue("description").length === 0 ? null : out.fields.getTextInputValue("description");
+ if (!out || out.isButton()) continue;
+ data.title =
+ out.fields.getTextInputValue("title").length === 0
+ ? null
+ : out.fields.getTextInputValue("title");
+ data.description =
+ out.fields.getTextInputValue("description").length === 0
+ ? null
+ : out.fields.getTextInputValue("description");
break;
}
case "send": {
await i.deferUpdate();
const channel = interaction.guild!.channels.cache.get(data.channel!) as Discord.TextChannel;
const components = new ActionRowBuilder<ButtonBuilder>();
- for(const button of data.buttons) {
+ for (const button of data.buttons) {
components.addComponents(
new ButtonBuilder()
- .setCustomId(button)
- .setLabel(buttonNames[button]!)
- .setStyle(ButtonStyle.Primary)
- );
- }
- const messageData: MessageCreateOptions = {components: [components]}
+ .setCustomId(button)
+ .setLabel(buttonNames[button]!)
+ .setStyle(ButtonStyle.Primary)
+ );
+ }
+ const messageData: MessageCreateOptions = { components: [components] };
if (data.title || data.description) {
- const e = new EmojiEmbed()
- if(data.title) e.setTitle(data.title);
- if(data.description) e.setDescription(data.description);
- if(data.color) e.setColor(data.color);
+ const e = new EmojiEmbed();
+ if (data.title) e.setTitle(data.title);
+ if (data.description) e.setDescription(data.description);
+ if (data.color) e.setColor(data.color);
messageData.embeds = [e];
}
await channel.send(messageData);
break;
}
}
- } else if(i.isStringSelectMenu()) {
- try {await i.deferUpdate();} catch (err) {console.log(err)}
- switch(i.customId) {
+ } else if (i.isStringSelectMenu()) {
+ try {
+ await i.deferUpdate();
+ } catch (err) {
+ console.log(err);
+ }
+ switch (i.customId) {
case "color": {
data.color = colors[i.values[0]!]!;
break;
@@ -239,10 +264,9 @@
await i.deferUpdate();
data.channel = i.values[0]!;
}
-
} while (!closed);
await interaction.deleteReply();
-}
+};
export const check = (interaction: CommandInteraction, _partial: boolean = false) => {
const member = interaction.member as Discord.GuildMember;
diff --git a/src/commands/settings/_meta.ts b/src/commands/settings/_meta.ts
index 666dbf4..1acc511 100644
--- a/src/commands/settings/_meta.ts
+++ b/src/commands/settings/_meta.ts
@@ -3,9 +3,6 @@
const name = "settings";
const description = "Change bot settings";
+const subcommand = await command(name, description, "settings", undefined, undefined, undefined, ["ManageGuild"]);
-const subcommand = await command(name, description, "settings", undefined, undefined, undefined, [
- "ManageGuild"
-])
-
-export { name, description, subcommand as command};
+export { name, description, subcommand as command };
diff --git a/src/commands/settings/automod.ts b/src/commands/settings/automod.ts
index ff9e0b2..9d59520 100644
--- a/src/commands/settings/automod.ts
+++ b/src/commands/settings/automod.ts
@@ -1,5 +1,6 @@
import type Discord from "discord.js";
-import { ActionRowBuilder,
+import {
+ ActionRowBuilder,
AnySelectMenuInteraction,
APIMessageComponentEmoji,
ButtonBuilder,
@@ -28,49 +29,77 @@
import { modalInteractionCollector } from "../../utils/dualCollector.js";
import listToAndMore from "../../utils/listToAndMore.js";
-
const command = (builder: SlashCommandSubcommandBuilder) =>
builder.setName("automod").setDescription("Setting for automatic moderation features");
+const emojiFromBoolean = (bool: boolean, id?: string) =>
+ bool ? getEmojiByName("CONTROL.TICK", id) : getEmojiByName("CONTROL.CROSS", id);
-const emojiFromBoolean = (bool: boolean, id?: string) => bool ? getEmojiByName("CONTROL.TICK", id) : getEmojiByName("CONTROL.CROSS", id);
-
-const toSelectMenu = async (interaction: StringSelectMenuInteraction, m: Message, ids: string[], type: "member" | "role" | "channel", title: string): Promise<string[]> => {
-
- const back = new ActionRowBuilder<ButtonBuilder>().addComponents(new ButtonBuilder().setCustomId("back").setLabel("Back").setStyle(ButtonStyle.Secondary).setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji));
+const toSelectMenu = async (
+ interaction: StringSelectMenuInteraction,
+ m: Message,
+ ids: string[],
+ type: "member" | "role" | "channel",
+ title: string
+): Promise<string[]> => {
+ const back = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setLabel("Back")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
+ );
let closed;
do {
- let render: string[] = []
+ let render: string[] = [];
let mapped: string[] = [];
let menu: UserSelectMenuBuilder | RoleSelectMenuBuilder | ChannelSelectMenuBuilder;
- switch(type) {
+ switch (type) {
case "member": {
menu = new UserSelectMenuBuilder().setCustomId("user").setPlaceholder("Select users").setMaxValues(25);
- mapped = await Promise.all(ids.map(async (id) => { return (await client.users.fetch(id).then(user => user.tag)) || "Unknown User" }));
- render = ids.map(id => client.logger.renderUser(id))
+ mapped = await Promise.all(
+ ids.map(async (id) => {
+ return (await client.users.fetch(id).then((user) => user.tag)) || "Unknown User";
+ })
+ );
+ render = ids.map((id) => client.logger.renderUser(id));
break;
}
case "role": {
menu = new RoleSelectMenuBuilder().setCustomId("role").setPlaceholder("Select roles").setMaxValues(25);
- mapped = await Promise.all(ids.map(async (id) => { return (await interaction.guild!.roles.fetch(id).then(role => role?.name ?? "Unknown Role"))}));
- render = ids.map(id => client.logger.renderRole(id, interaction.guild!))
+ mapped = await Promise.all(
+ ids.map(async (id) => {
+ return await interaction.guild!.roles.fetch(id).then((role) => role?.name ?? "Unknown Role");
+ })
+ );
+ render = ids.map((id) => client.logger.renderRole(id, interaction.guild!));
break;
}
case "channel": {
- menu = new ChannelSelectMenuBuilder().setCustomId("channel").setPlaceholder("Select channels").setMaxValues(25);
- mapped = await Promise.all(ids.map(async (id) => { return (await interaction.guild!.channels.fetch(id).then(channel => channel?.name ?? "Unknown Role")) }));
- render = ids.map(id => client.logger.renderChannel(id))
+ menu = new ChannelSelectMenuBuilder()
+ .setCustomId("channel")
+ .setPlaceholder("Select channels")
+ .setMaxValues(25);
+ mapped = await Promise.all(
+ ids.map(async (id) => {
+ return await interaction
+ .guild!.channels.fetch(id)
+ .then((channel) => channel?.name ?? "Unknown Role");
+ })
+ );
+ render = ids.map((id) => client.logger.renderChannel(id));
break;
}
}
- const removeOptions = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("remove")
- .setPlaceholder("Remove")
- .addOptions(mapped.map((name, i) => new StringSelectMenuOptionBuilder().setLabel(name).setValue(ids[i]!)))
- .setDisabled(ids.length === 0)
- );
+ const removeOptions = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setCustomId("remove")
+ .setPlaceholder("Remove")
+ .addOptions(
+ mapped.map((name, i) => new StringSelectMenuOptionBuilder().setLabel(name).setValue(ids[i]!))
+ )
+ .setDisabled(ids.length === 0)
+ );
const embed = new EmojiEmbed()
.setTitle(title)
@@ -78,96 +107,100 @@
.setDescription(`Select ${type}s:\n\nCurrent:\n` + (render.length > 0 ? render.join("\n") : "None"))
.setStatus("Success");
const components: ActionRowBuilder<
- StringSelectMenuBuilder |
- ButtonBuilder |
- ChannelSelectMenuBuilder |
- UserSelectMenuBuilder |
- RoleSelectMenuBuilder
- >[] = [new ActionRowBuilder<typeof menu>().addComponents(menu)]
- if(ids.length > 0) components.push(removeOptions);
+ | StringSelectMenuBuilder
+ | ButtonBuilder
+ | ChannelSelectMenuBuilder
+ | UserSelectMenuBuilder
+ | RoleSelectMenuBuilder
+ >[] = [new ActionRowBuilder<typeof menu>().addComponents(menu)];
+ if (ids.length > 0) components.push(removeOptions);
components.push(back);
- await interaction.editReply({embeds: [embed], components: components})
+ await interaction.editReply({ embeds: [embed], components: components });
let i: AnySelectMenuInteraction | ButtonInteraction;
try {
- i = await m.awaitMessageComponent({filter: i => i.user.id === interaction.user.id, time: 300000});
- } catch(e) {
+ i = await m.awaitMessageComponent({ filter: (i) => i.user.id === interaction.user.id, time: 300000 });
+ } catch (e) {
closed = true;
continue;
}
- if(i.isButton()) {
+ if (i.isButton()) {
await i.deferUpdate();
- if(i.customId === "back") {
+ if (i.customId === "back") {
closed = true;
break;
}
- } else if(i.isStringSelectMenu()) {
+ } else if (i.isStringSelectMenu()) {
await i.deferUpdate();
- if(i.customId === "remove") {
- ids = ids.filter(id => id !== (i as StringSelectMenuInteraction).values[0]);
- if(ids.length === 0) {
+ if (i.customId === "remove") {
+ ids = ids.filter((id) => id !== (i as StringSelectMenuInteraction).values[0]);
+ if (ids.length === 0) {
menu.data.disabled = true;
}
}
} else {
await i.deferUpdate();
- if(i.customId === "user") {
+ if (i.customId === "user") {
ids = ids.concat((i as UserSelectMenuInteraction).values);
- } else if(i.customId === "role") {
+ } else if (i.customId === "role") {
ids = ids.concat((i as RoleSelectMenuInteraction).values);
- } else if(i.customId === "channel") {
+ } else if (i.customId === "channel") {
ids = ids.concat((i as ChannelSelectMenuInteraction).values);
}
}
-
- } while(!closed)
+ } while (!closed);
return ids;
-}
+};
-const imageMenu = async (interaction: StringSelectMenuInteraction, m: Message, current: {
- NSFW: boolean,
- size: boolean
-}): Promise<{NSFW: boolean, size: boolean}> => {
+const imageMenu = async (
+ interaction: StringSelectMenuInteraction,
+ m: Message,
+ current: {
+ NSFW: boolean;
+ size: boolean;
+ }
+): Promise<{ NSFW: boolean; size: boolean }> => {
let closed = false;
do {
- const options = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setLabel("Back")
- .setStyle(ButtonStyle.Secondary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("nsfw")
- .setLabel("NSFW")
- .setStyle(current.NSFW ? ButtonStyle.Success : ButtonStyle.Danger)
- .setEmoji(emojiFromBoolean(current.NSFW, "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("size")
- .setLabel("Size")
- .setStyle(current.size ? ButtonStyle.Success : ButtonStyle.Danger)
- .setEmoji(emojiFromBoolean(current.size, "id") as APIMessageComponentEmoji)
- )
+ const options = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setLabel("Back")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji),
+ new ButtonBuilder()
+ .setCustomId("nsfw")
+ .setLabel("NSFW")
+ .setStyle(current.NSFW ? ButtonStyle.Success : ButtonStyle.Danger)
+ .setEmoji(emojiFromBoolean(current.NSFW, "id") as APIMessageComponentEmoji),
+ new ButtonBuilder()
+ .setCustomId("size")
+ .setLabel("Size")
+ .setStyle(current.size ? ButtonStyle.Success : ButtonStyle.Danger)
+ .setEmoji(emojiFromBoolean(current.size, "id") as APIMessageComponentEmoji)
+ );
const embed = new EmojiEmbed()
.setTitle("Image Settings")
.setDescription(
- `${emojiFromBoolean(current.NSFW)} **NSFW**\n` +
- `${emojiFromBoolean(current.size)} **Size**\n`
- )
+ `${emojiFromBoolean(current.NSFW)} **NSFW**\n` + `${emojiFromBoolean(current.size)} **Size**\n`
+ );
- await interaction.editReply({embeds: [embed], components: [options]});
+ await interaction.editReply({ embeds: [embed], components: [options] });
let i: ButtonInteraction;
try {
- i = await m.awaitMessageComponent({filter: (i) => interaction.user.id === i.user.id && i.message.id === m.id, time: 300000}) as ButtonInteraction;
+ i = (await m.awaitMessageComponent({
+ filter: (i) => interaction.user.id === i.user.id && i.message.id === m.id,
+ time: 300000
+ })) as ButtonInteraction;
} catch (e) {
return current;
}
await i.deferUpdate();
- switch(i.customId) {
+ switch (i.customId) {
case "back": {
closed = true;
break;
@@ -181,87 +214,106 @@
break;
}
}
- } while(!closed);
+ } while (!closed);
return current;
-}
+};
-const wordMenu = async (interaction: StringSelectMenuInteraction, m: Message, current: {
- enabled: boolean,
- words: {strict: string[], loose: string[]},
- allowed: {users: string[], roles: string[], channels: string[]}
-}): Promise<{
- enabled: boolean,
- words: {strict: string[], loose: string[]},
- allowed: {users: string[], roles: string[], channels: string[]}
+const wordMenu = async (
+ interaction: StringSelectMenuInteraction,
+ m: Message,
+ current: {
+ enabled: boolean;
+ words: { strict: string[]; loose: string[] };
+ allowed: { users: string[]; roles: string[]; channels: string[] };
+ }
+): Promise<{
+ enabled: boolean;
+ words: { strict: string[]; loose: string[] };
+ allowed: { users: string[]; roles: string[]; channels: string[] };
}> => {
let closed = false;
do {
- const buttons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setLabel("Back")
- .setStyle(ButtonStyle.Secondary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("enabled")
- .setLabel("Enabled")
- .setStyle(current.enabled ? ButtonStyle.Success : ButtonStyle.Danger)
- .setEmoji(emojiFromBoolean(current.enabled, "id") as APIMessageComponentEmoji),
- );
+ const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setLabel("Back")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji),
+ new ButtonBuilder()
+ .setCustomId("enabled")
+ .setLabel("Enabled")
+ .setStyle(current.enabled ? ButtonStyle.Success : ButtonStyle.Danger)
+ .setEmoji(emojiFromBoolean(current.enabled, "id") as APIMessageComponentEmoji)
+ );
- const selectMenu = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("edit")
- .setPlaceholder("Edit... ")
- .addOptions(
- new StringSelectMenuOptionBuilder()
- .setLabel("Words")
- .setDescription("Edit your list of words to filter")
- .setValue("words"),
- new StringSelectMenuOptionBuilder()
- .setLabel("Allowed Users")
- .setDescription("Users who will be unaffected by the word filter")
- .setValue("allowedUsers"),
- new StringSelectMenuOptionBuilder()
- .setLabel("Allowed Roles")
- .setDescription("Roles that will be unaffected by the word filter")
- .setValue("allowedRoles"),
- new StringSelectMenuOptionBuilder()
- .setLabel("Allowed Channels")
- .setDescription("Channels where the word filter will not apply")
- .setValue("allowedChannels")
- )
- .setDisabled(!current.enabled)
- );
+ const selectMenu = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setCustomId("edit")
+ .setPlaceholder("Edit... ")
+ .addOptions(
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Words")
+ .setDescription("Edit your list of words to filter")
+ .setValue("words"),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Allowed Users")
+ .setDescription("Users who will be unaffected by the word filter")
+ .setValue("allowedUsers"),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Allowed Roles")
+ .setDescription("Roles that will be unaffected by the word filter")
+ .setValue("allowedRoles"),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Allowed Channels")
+ .setDescription("Channels where the word filter will not apply")
+ .setValue("allowedChannels")
+ )
+ .setDisabled(!current.enabled)
+ );
const embed = new EmojiEmbed()
.setTitle("Word Filters")
.setDescription(
`${emojiFromBoolean(current.enabled)} **Enabled**\n` +
- `**Strict Words:** ${listToAndMore(current.words.strict, 5)}\n` +
- `**Loose Words:** ${listToAndMore(current.words.loose, 5)}\n\n` +
- `**Users:** ` + listToAndMore(current.allowed.users.map(user => `<@${user}>`), 5) + `\n` +
- `**Roles:** ` + listToAndMore(current.allowed.roles.map(role => `<@&${role}>`), 5) + `\n` +
- `**Channels:** ` + listToAndMore(current.allowed.channels.map(channel => `<#${channel}>`), 5)
+ `**Strict Words:** ${listToAndMore(current.words.strict, 5)}\n` +
+ `**Loose Words:** ${listToAndMore(current.words.loose, 5)}\n\n` +
+ `**Users:** ` +
+ listToAndMore(
+ current.allowed.users.map((user) => `<@${user}>`),
+ 5
+ ) +
+ `\n` +
+ `**Roles:** ` +
+ listToAndMore(
+ current.allowed.roles.map((role) => `<@&${role}>`),
+ 5
+ ) +
+ `\n` +
+ `**Channels:** ` +
+ listToAndMore(
+ current.allowed.channels.map((channel) => `<#${channel}>`),
+ 5
+ )
)
.setStatus("Success")
- .setEmoji("GUILD.SETTINGS.GREEN")
+ .setEmoji("GUILD.SETTINGS.GREEN");
- await interaction.editReply({embeds: [embed], components: [selectMenu, buttons]});
+ await interaction.editReply({ embeds: [embed], components: [selectMenu, buttons] });
let i: ButtonInteraction | StringSelectMenuInteraction;
try {
- i = await m.awaitMessageComponent({filter: (i) => interaction.user.id === i.user.id && i.message.id === m.id, time: 300000}) as ButtonInteraction | StringSelectMenuInteraction;
+ i = (await m.awaitMessageComponent({
+ filter: (i) => interaction.user.id === i.user.id && i.message.id === m.id,
+ time: 300000
+ })) as ButtonInteraction | StringSelectMenuInteraction;
} catch (e) {
closed = true;
break;
}
- if(i.isButton()) {
+ if (i.isButton()) {
await i.deferUpdate();
- switch(i.customId) {
+ switch (i.customId) {
case "back": {
closed = true;
break;
@@ -272,44 +324,53 @@
}
}
} else {
- switch(i.values[0]) {
+ switch (i.values[0]) {
case "words": {
- await interaction.editReply({embeds: [new EmojiEmbed()
- .setTitle("Word Filter")
- .setDescription("Modal opened. If you can't see it, click back and try again.")
- .setStatus("Success")
- .setEmoji("GUILD.SETTINGS.GREEN")
- ], components: [new ActionRowBuilder<ButtonBuilder>().addComponents(new ButtonBuilder()
- .setLabel("Back")
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id"))
- .setStyle(ButtonStyle.Primary)
- .setCustomId("back")
- )]})
+ await interaction.editReply({
+ embeds: [
+ new EmojiEmbed()
+ .setTitle("Word Filter")
+ .setDescription("Modal opened. If you can't see it, click back and try again.")
+ .setStatus("Success")
+ .setEmoji("GUILD.SETTINGS.GREEN")
+ ],
+ components: [
+ new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setLabel("Back")
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id"))
+ .setStyle(ButtonStyle.Primary)
+ .setCustomId("back")
+ )
+ ]
+ });
const modal = new ModalBuilder()
.setTitle("Word Filter")
.setCustomId("wordFilter")
.addComponents(
- new ActionRowBuilder<TextInputBuilder>()
- .addComponents(
- new TextInputBuilder()
- .setCustomId("wordStrict")
- .setLabel("Strict Words")
- .setPlaceholder("Matches anywhere in the message, including surrounded by other characters")
- .setValue(current.words.strict.join(", "))
- .setStyle(TextInputStyle.Paragraph)
- .setRequired(false)
- ),
- new ActionRowBuilder<TextInputBuilder>()
- .addComponents(
- new TextInputBuilder()
- .setCustomId("wordLoose")
- .setLabel("Loose Words")
- .setPlaceholder("Matches only if the word is by itself, surrounded by spaces or punctuation")
- .setValue(current.words.loose.join(", "))
- .setStyle(TextInputStyle.Paragraph)
- .setRequired(false)
- )
- )
+ new ActionRowBuilder<TextInputBuilder>().addComponents(
+ new TextInputBuilder()
+ .setCustomId("wordStrict")
+ .setLabel("Strict Words")
+ .setPlaceholder(
+ "Matches anywhere in the message, including surrounded by other characters"
+ )
+ .setValue(current.words.strict.join(", "))
+ .setStyle(TextInputStyle.Paragraph)
+ .setRequired(false)
+ ),
+ new ActionRowBuilder<TextInputBuilder>().addComponents(
+ new TextInputBuilder()
+ .setCustomId("wordLoose")
+ .setLabel("Loose Words")
+ .setPlaceholder(
+ "Matches only if the word is by itself, surrounded by spaces or punctuation"
+ )
+ .setValue(current.words.loose.join(", "))
+ .setStyle(TextInputStyle.Paragraph)
+ .setRequired(false)
+ )
+ );
await i.showModal(modal);
let out;
@@ -319,103 +380,146 @@
break;
}
if (!out) break;
- if(out.isButton()) break;
- current.words.strict = out.fields.getTextInputValue("wordStrict")
- .split(",").map(s => s.trim()).filter(s => s.length > 0);
- current.words.loose = out.fields.getTextInputValue("wordLoose")
- .split(",").map(s => s.trim()).filter(s => s.length > 0);
+ if (out.isButton()) break;
+ current.words.strict = out.fields
+ .getTextInputValue("wordStrict")
+ .split(",")
+ .map((s) => s.trim())
+ .filter((s) => s.length > 0);
+ current.words.loose = out.fields
+ .getTextInputValue("wordLoose")
+ .split(",")
+ .map((s) => s.trim())
+ .filter((s) => s.length > 0);
break;
}
case "allowedUsers": {
await i.deferUpdate();
- current.allowed.users = await toSelectMenu(interaction, m, current.allowed.users, "member", "Word Filter");
+ current.allowed.users = await toSelectMenu(
+ interaction,
+ m,
+ current.allowed.users,
+ "member",
+ "Word Filter"
+ );
break;
}
case "allowedRoles": {
await i.deferUpdate();
- current.allowed.roles = await toSelectMenu(interaction, m, current.allowed.roles, "role", "Word Filter");
+ current.allowed.roles = await toSelectMenu(
+ interaction,
+ m,
+ current.allowed.roles,
+ "role",
+ "Word Filter"
+ );
break;
}
case "allowedChannels": {
await i.deferUpdate();
- current.allowed.channels = await toSelectMenu(interaction, m, current.allowed.channels, "channel", "Word Filter");
+ current.allowed.channels = await toSelectMenu(
+ interaction,
+ m,
+ current.allowed.channels,
+ "channel",
+ "Word Filter"
+ );
break;
}
}
}
- } while(!closed);
+ } while (!closed);
return current;
-}
+};
-const inviteMenu = async (interaction: StringSelectMenuInteraction, m: Message, current: {
- enabled: boolean,
- allowed: {users: string[], roles: string[], channels: string[]}
-}): Promise<{
- enabled: boolean,
- allowed: {users: string[], roles: string[], channels: string[]}
+const inviteMenu = async (
+ interaction: StringSelectMenuInteraction,
+ m: Message,
+ current: {
+ enabled: boolean;
+ allowed: { users: string[]; roles: string[]; channels: string[] };
+ }
+): Promise<{
+ enabled: boolean;
+ allowed: { users: string[]; roles: string[]; channels: string[] };
}> => {
-
let closed = false;
do {
- const buttons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setLabel("Back")
- .setStyle(ButtonStyle.Secondary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("enabled")
- .setLabel(current.enabled ? "Enabled" : "Disabled")
- .setStyle(current.enabled ? ButtonStyle.Success : ButtonStyle.Danger)
- .setEmoji(emojiFromBoolean(current.enabled, "id") as APIMessageComponentEmoji)
- );
- const menu = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("toEdit")
- .setPlaceholder("Edit your allow list")
- .addOptions(
- new StringSelectMenuOptionBuilder()
- .setLabel("Users")
- .setDescription("Users that are allowed to send invites")
- .setValue("users"),
- new StringSelectMenuOptionBuilder()
- .setLabel("Roles")
- .setDescription("Roles that are allowed to send invites")
- .setValue("roles"),
- new StringSelectMenuOptionBuilder()
- .setLabel("Channels")
- .setDescription("Channels that anyone is allowed to send invites in")
- .setValue("channels")
- ).setDisabled(!current.enabled)
+ const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setLabel("Back")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji),
+ new ButtonBuilder()
+ .setCustomId("enabled")
+ .setLabel(current.enabled ? "Enabled" : "Disabled")
+ .setStyle(current.enabled ? ButtonStyle.Success : ButtonStyle.Danger)
+ .setEmoji(emojiFromBoolean(current.enabled, "id") as APIMessageComponentEmoji)
+ );
+ const menu = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setCustomId("toEdit")
+ .setPlaceholder("Edit your allow list")
+ .addOptions(
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Users")
+ .setDescription("Users that are allowed to send invites")
+ .setValue("users"),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Roles")
+ .setDescription("Roles that are allowed to send invites")
+ .setValue("roles"),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Channels")
+ .setDescription("Channels that anyone is allowed to send invites in")
+ .setValue("channels")
)
+ .setDisabled(!current.enabled)
+ );
const embed = new EmojiEmbed()
.setTitle("Invite Settings")
.setDescription(
- "Automatically deletes invites sent by users (outside of staff members and self promotion channels)" + `\n\n` +
- `${emojiFromBoolean(current.enabled)} **${current.enabled ? "Enabled" : "Disabled"}**\n\n` +
- `**Users:** ` + listToAndMore(current.allowed.users.map(user => `<@${user}>`), 5) + `\n` +
- `**Roles:** ` + listToAndMore(current.allowed.roles.map(role => `<@&${role}>`), 5) + `\n` +
- `**Channels:** ` + listToAndMore(current.allowed.channels.map(channel => `<#${channel}>`), 5)
+ "Automatically deletes invites sent by users (outside of staff members and self promotion channels)" +
+ `\n\n` +
+ `${emojiFromBoolean(current.enabled)} **${current.enabled ? "Enabled" : "Disabled"}**\n\n` +
+ `**Users:** ` +
+ listToAndMore(
+ current.allowed.users.map((user) => `<@${user}>`),
+ 5
+ ) +
+ `\n` +
+ `**Roles:** ` +
+ listToAndMore(
+ current.allowed.roles.map((role) => `<@&${role}>`),
+ 5
+ ) +
+ `\n` +
+ `**Channels:** ` +
+ listToAndMore(
+ current.allowed.channels.map((channel) => `<#${channel}>`),
+ 5
+ )
)
.setStatus("Success")
- .setEmoji("GUILD.SETTINGS.GREEN")
+ .setEmoji("GUILD.SETTINGS.GREEN");
-
- await interaction.editReply({embeds: [embed], components: [menu, buttons]});
+ await interaction.editReply({ embeds: [embed], components: [menu, buttons] });
let i: ButtonInteraction | StringSelectMenuInteraction;
try {
- i = await m.awaitMessageComponent({filter: (i) => interaction.user.id === i.user.id && i.message.id === m.id, time: 300000}) as ButtonInteraction | StringSelectMenuInteraction;
+ i = (await m.awaitMessageComponent({
+ filter: (i) => interaction.user.id === i.user.id && i.message.id === m.id,
+ time: 300000
+ })) as ButtonInteraction | StringSelectMenuInteraction;
} catch (e) {
return current;
}
- if(i.isButton()) {
+ if (i.isButton()) {
await i.deferUpdate();
- switch(i.customId) {
+ switch (i.customId) {
case "back": {
closed = true;
break;
@@ -427,135 +531,181 @@
}
} else {
await i.deferUpdate();
- switch(i.values[0]) {
+ switch (i.values[0]) {
case "users": {
- current.allowed.users = await toSelectMenu(interaction, m, current.allowed.users, "member", "Invite Settings");
+ current.allowed.users = await toSelectMenu(
+ interaction,
+ m,
+ current.allowed.users,
+ "member",
+ "Invite Settings"
+ );
break;
}
case "roles": {
- current.allowed.roles = await toSelectMenu(interaction, m, current.allowed.roles, "role", "Invite Settings");
+ current.allowed.roles = await toSelectMenu(
+ interaction,
+ m,
+ current.allowed.roles,
+ "role",
+ "Invite Settings"
+ );
break;
}
case "channels": {
- current.allowed.channels = await toSelectMenu(interaction, m, current.allowed.channels, "channel", "Invite Settings");
+ current.allowed.channels = await toSelectMenu(
+ interaction,
+ m,
+ current.allowed.channels,
+ "channel",
+ "Invite Settings"
+ );
break;
}
}
}
-
- } while(!closed);
+ } while (!closed);
return current;
-}
+};
-const mentionMenu = async (interaction: StringSelectMenuInteraction, m: Message, current: {
- mass: number,
- everyone: boolean,
- roles: boolean,
- allowed: {
- roles: string[],
- rolesToMention: string[],
- users: string[],
- channels: string[]
+const mentionMenu = async (
+ interaction: StringSelectMenuInteraction,
+ m: Message,
+ current: {
+ mass: number;
+ everyone: boolean;
+ roles: boolean;
+ allowed: {
+ roles: string[];
+ rolesToMention: string[];
+ users: string[];
+ channels: string[];
+ };
}
-}): Promise<{
- mass: number,
- everyone: boolean,
- roles: boolean,
+): Promise<{
+ mass: number;
+ everyone: boolean;
+ roles: boolean;
allowed: {
- roles: string[],
- rolesToMention: string[],
- users: string[],
- channels: string[]
- }
+ roles: string[];
+ rolesToMention: string[];
+ users: string[];
+ channels: string[];
+ };
}> => {
let closed = false;
do {
+ const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setLabel("Back")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji),
+ new ButtonBuilder()
+ .setCustomId("everyone")
+ .setLabel(current.everyone ? "Everyone" : "No one")
+ .setStyle(current.everyone ? ButtonStyle.Success : ButtonStyle.Danger)
+ .setEmoji(emojiFromBoolean(current.everyone, "id") as APIMessageComponentEmoji),
+ new ButtonBuilder()
+ .setCustomId("roles")
+ .setLabel(current.roles ? "Roles" : "No roles")
+ .setStyle(current.roles ? ButtonStyle.Success : ButtonStyle.Danger)
+ .setEmoji(emojiFromBoolean(current.roles, "id") as APIMessageComponentEmoji)
+ );
+ const menu = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setCustomId("toEdit")
+ .setPlaceholder("Edit mention settings")
+ .addOptions(
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Mass Mention Amount")
+ .setDescription("The amount of mentions before the bot will delete the message")
+ .setValue("mass"),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Roles")
+ .setDescription("Roles that are able to be mentioned")
+ .setValue("roles")
+ )
+ );
- const buttons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setLabel("Back")
- .setStyle(ButtonStyle.Secondary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("everyone")
- .setLabel(current.everyone ? "Everyone" : "No one")
- .setStyle(current.everyone ? ButtonStyle.Success : ButtonStyle.Danger)
- .setEmoji(emojiFromBoolean(current.everyone, "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("roles")
- .setLabel(current.roles ? "Roles" : "No roles")
- .setStyle(current.roles ? ButtonStyle.Success : ButtonStyle.Danger)
- .setEmoji(emojiFromBoolean(current.roles, "id") as APIMessageComponentEmoji)
- );
- const menu = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("toEdit")
- .setPlaceholder("Edit mention settings")
- .addOptions(
- new StringSelectMenuOptionBuilder()
- .setLabel("Mass Mention Amount")
- .setDescription("The amount of mentions before the bot will delete the message")
- .setValue("mass"),
- new StringSelectMenuOptionBuilder()
- .setLabel("Roles")
- .setDescription("Roles that are able to be mentioned")
- .setValue("roles"),
- )
- )
-
- const allowedMenu = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("allowed")
- .setPlaceholder("Edit exceptions")
- .addOptions(
- new StringSelectMenuOptionBuilder()
- .setLabel("Users")
- .setDescription("Users that are unaffected by the mention filter")
- .setValue("users"),
- new StringSelectMenuOptionBuilder()
- .setLabel("Roles")
- .setDescription("Roles that are unaffected by the mention filter")
- .setValue("roles"),
- new StringSelectMenuOptionBuilder()
- .setLabel("Channels")
- .setDescription("Channels where anyone is unaffected by the mention filter")
- .setValue("channels")
- )
- )
+ const allowedMenu = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setCustomId("allowed")
+ .setPlaceholder("Edit exceptions")
+ .addOptions(
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Users")
+ .setDescription("Users that are unaffected by the mention filter")
+ .setValue("users"),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Roles")
+ .setDescription("Roles that are unaffected by the mention filter")
+ .setValue("roles"),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Channels")
+ .setDescription("Channels where anyone is unaffected by the mention filter")
+ .setValue("channels")
+ )
+ );
const embed = new EmojiEmbed()
.setTitle("Mention Settings")
.setDescription(
`Log when members mention:\n` +
- `${emojiFromBoolean(true)} **${current.mass}+ members** in one message\n` +
- `${emojiFromBoolean(current.everyone)} **Everyone**\n` +
- `${emojiFromBoolean(current.roles)} **Roles**\n` +
- (current.allowed.rolesToMention.length > 0 ? `> *Except for ${listToAndMore(current.allowed.rolesToMention.map(r => `<@&${r}>`), 3)}*\n` : "") +
- "\n" +
- `Except if...\n` +
- `> ${current.allowed.users.length > 0 ? `Member is: ${listToAndMore(current.allowed.users.map(u => `<@${u}>`), 3)}\n` : ""}` +
- `> ${current.allowed.roles.length > 0 ? `Member has role: ${listToAndMore(current.allowed.roles.map(r => `<@&${r}>`), 3)}\n` : ""}` +
- `> ${current.allowed.channels.length > 0 ? `In channel: ${listToAndMore(current.allowed.channels.map(c => `<#${c}>`), 3)}\n` : ""}`
+ `${emojiFromBoolean(true)} **${current.mass}+ members** in one message\n` +
+ `${emojiFromBoolean(current.everyone)} **Everyone**\n` +
+ `${emojiFromBoolean(current.roles)} **Roles**\n` +
+ (current.allowed.rolesToMention.length > 0
+ ? `> *Except for ${listToAndMore(
+ current.allowed.rolesToMention.map((r) => `<@&${r}>`),
+ 3
+ )}*\n`
+ : "") +
+ "\n" +
+ `Except if...\n` +
+ `> ${
+ current.allowed.users.length > 0
+ ? `Member is: ${listToAndMore(
+ current.allowed.users.map((u) => `<@${u}>`),
+ 3
+ )}\n`
+ : ""
+ }` +
+ `> ${
+ current.allowed.roles.length > 0
+ ? `Member has role: ${listToAndMore(
+ current.allowed.roles.map((r) => `<@&${r}>`),
+ 3
+ )}\n`
+ : ""
+ }` +
+ `> ${
+ current.allowed.channels.length > 0
+ ? `In channel: ${listToAndMore(
+ current.allowed.channels.map((c) => `<#${c}>`),
+ 3
+ )}\n`
+ : ""
+ }`
)
.setStatus("Success")
- .setEmoji("GUILD.SETTINGS.GREEN")
+ .setEmoji("GUILD.SETTINGS.GREEN");
- await interaction.editReply({embeds: [embed], components: [menu, allowedMenu, buttons]});
+ await interaction.editReply({ embeds: [embed], components: [menu, allowedMenu, buttons] });
let i: ButtonInteraction | StringSelectMenuInteraction;
try {
- i = await m.awaitMessageComponent({filter: (i) => interaction.user.id === i.user.id && i.message.id === m.id, time: 300000}) as ButtonInteraction | StringSelectMenuInteraction;
+ i = (await m.awaitMessageComponent({
+ filter: (i) => interaction.user.id === i.user.id && i.message.id === m.id,
+ time: 300000
+ })) as ButtonInteraction | StringSelectMenuInteraction;
} catch (e) {
closed = true;
break;
}
- if(i.isButton()) {
+ if (i.isButton()) {
await i.deferUpdate();
switch (i.customId) {
case "back": {
@@ -576,31 +726,37 @@
case "toEdit": {
switch (i.values[0]) {
case "mass": {
- await interaction.editReply({embeds: [new EmojiEmbed()
- .setTitle("Word Filter")
- .setDescription("Modal opened. If you can't see it, click back and try again.")
- .setStatus("Success")
- .setEmoji("GUILD.SETTINGS.GREEN")
- ], components: [new ActionRowBuilder<ButtonBuilder>().addComponents(new ButtonBuilder()
- .setLabel("Back")
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id"))
- .setStyle(ButtonStyle.Primary)
- .setCustomId("back")
- )]})
+ await interaction.editReply({
+ embeds: [
+ new EmojiEmbed()
+ .setTitle("Word Filter")
+ .setDescription("Modal opened. If you can't see it, click back and try again.")
+ .setStatus("Success")
+ .setEmoji("GUILD.SETTINGS.GREEN")
+ ],
+ components: [
+ new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setLabel("Back")
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id"))
+ .setStyle(ButtonStyle.Primary)
+ .setCustomId("back")
+ )
+ ]
+ });
const modal = new ModalBuilder()
.setTitle("Mass Mention Amount")
.setCustomId("mass")
.addComponents(
- new ActionRowBuilder<TextInputBuilder>()
- .addComponents(
- new TextInputBuilder()
- .setCustomId("mass")
- .setPlaceholder("Amount")
- .setMinLength(1)
- .setMaxLength(3)
- .setStyle(TextInputStyle.Short)
- )
- )
+ new ActionRowBuilder<TextInputBuilder>().addComponents(
+ new TextInputBuilder()
+ .setCustomId("mass")
+ .setPlaceholder("Amount")
+ .setMinLength(1)
+ .setMaxLength(3)
+ .setStyle(TextInputStyle.Short)
+ )
+ );
await i.showModal(modal);
let out;
try {
@@ -609,13 +765,19 @@
break;
}
if (!out) break;
- if(out.isButton()) break;
+ if (out.isButton()) break;
current.mass = parseInt(out.fields.getTextInputValue("mass"));
break;
}
case "roles": {
await i.deferUpdate();
- current.allowed.rolesToMention = await toSelectMenu(interaction, m, current.allowed.rolesToMention, "role", "Mention Settings");
+ current.allowed.rolesToMention = await toSelectMenu(
+ interaction,
+ m,
+ current.allowed.rolesToMention,
+ "role",
+ "Mention Settings"
+ );
break;
}
}
@@ -625,15 +787,33 @@
await i.deferUpdate();
switch (i.values[0]) {
case "users": {
- current.allowed.users = await toSelectMenu(interaction, m, current.allowed.users, "member", "Mention Settings");
+ current.allowed.users = await toSelectMenu(
+ interaction,
+ m,
+ current.allowed.users,
+ "member",
+ "Mention Settings"
+ );
break;
}
case "roles": {
- current.allowed.roles = await toSelectMenu(interaction, m, current.allowed.roles, "role", "Mention Settings");
+ current.allowed.roles = await toSelectMenu(
+ interaction,
+ m,
+ current.allowed.roles,
+ "role",
+ "Mention Settings"
+ );
break;
}
case "channels": {
- current.allowed.channels = await toSelectMenu(interaction, m, current.allowed.channels, "channel", "Mention Settings");
+ current.allowed.channels = await toSelectMenu(
+ interaction,
+ m,
+ current.allowed.channels,
+ "channel",
+ "Mention Settings"
+ );
break;
}
}
@@ -641,85 +821,91 @@
}
}
}
+ } while (!closed);
+ return current;
+};
- } while(!closed);
- return current
-}
-
-const cleanMenu = async (interaction: StringSelectMenuInteraction, m: Message, current?: {
- channels?: string[],
- allowed?: {
- roles: string[],
- users: string[]
+const cleanMenu = async (
+ interaction: StringSelectMenuInteraction,
+ m: Message,
+ current?: {
+ channels?: string[];
+ allowed?: {
+ roles: string[];
+ users: string[];
+ };
}
-}): Promise<{
- channels: string[],
+): Promise<{
+ channels: string[];
allowed: {
- roles: string[],
- users: string[]
- }
+ roles: string[];
+ users: string[];
+ };
}> => {
let closed = false;
- if(!current) current = {channels: [], allowed: {roles: [], users: []}};
- if(!current.channels) current.channels = [];
- if(!current.allowed) current.allowed = {roles: [], users: []};
+ if (!current) current = { channels: [], allowed: { roles: [], users: [] } };
+ if (!current.channels) current.channels = [];
+ if (!current.allowed) current.allowed = { roles: [], users: [] };
- const channelMenu = new ActionRowBuilder<ChannelSelectMenuBuilder>()
- .addComponents(
- new ChannelSelectMenuBuilder()
- .setCustomId("toAdd")
- .setPlaceholder("Select a channel")
- )
+ const channelMenu = new ActionRowBuilder<ChannelSelectMenuBuilder>().addComponents(
+ new ChannelSelectMenuBuilder().setCustomId("toAdd").setPlaceholder("Select a channel")
+ );
- const allowedMenu = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("allowed")
- .setPlaceholder("Edit exceptions")
- .addOptions(
- new StringSelectMenuOptionBuilder()
- .setLabel("Users")
- .setDescription("Users that are unaffected by the mention filter")
- .setValue("users"),
- new StringSelectMenuOptionBuilder()
- .setLabel("Roles")
- .setDescription("Roles that are unaffected by the mention filter")
- .setValue("roles")
- )
- )
+ const allowedMenu = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setCustomId("allowed")
+ .setPlaceholder("Edit exceptions")
+ .addOptions(
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Users")
+ .setDescription("Users that are unaffected by the mention filter")
+ .setValue("users"),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Roles")
+ .setDescription("Roles that are unaffected by the mention filter")
+ .setValue("roles")
+ )
+ );
do {
-
- const buttons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setLabel("Back")
- .setStyle(ButtonStyle.Primary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id"))
- )
+ const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setLabel("Back")
+ .setStyle(ButtonStyle.Primary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id"))
+ );
const embed = new EmojiEmbed()
.setTitle("Clean Settings")
.setEmoji("GUILD.SETTINGS.GREEN")
.setDescription(
`Current clean channels:\n\n` +
- `${current.channels.length > 0 ? listToAndMore(current.channels.map(c => `<#${c}>`), 10) : "None"}\n\n`
+ `${
+ current.channels.length > 0
+ ? listToAndMore(
+ current.channels.map((c) => `<#${c}>`),
+ 10
+ )
+ : "None"
+ }\n\n`
)
- .setStatus("Success")
+ .setStatus("Success");
-
- await interaction.editReply({embeds: [embed], components: [channelMenu, allowedMenu, buttons]});
+ await interaction.editReply({ embeds: [embed], components: [channelMenu, allowedMenu, buttons] });
let i: ButtonInteraction | ChannelSelectMenuInteraction;
try {
- i = await m.awaitMessageComponent({filter: (i) => interaction.user.id === i.user.id && i.message.id === m.id, time: 300000}) as ButtonInteraction | ChannelSelectMenuInteraction;
+ i = (await m.awaitMessageComponent({
+ filter: (i) => interaction.user.id === i.user.id && i.message.id === m.id,
+ time: 300000
+ })) as ButtonInteraction | ChannelSelectMenuInteraction;
} catch (e) {
closed = true;
break;
}
await i.deferUpdate();
- if(i.isButton()) {
+ if (i.isButton()) {
switch (i.customId) {
case "back": {
closed = true;
@@ -733,24 +919,28 @@
.setTitle("Clean Settings")
.setDescription(`Editing <#${i.values[0]}>`)
.setEmoji("GUILD.SETTINGS.GREEN")
- .setStatus("Success")
- const channelButtons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setLabel("Back")
- .setStyle(ButtonStyle.Primary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id")),
- new ButtonBuilder()
- .setCustomId("switch")
- .setLabel(current.channels.includes(i.values[0]!) ? "Remove" : "Add")
- .setStyle(current.channels.includes(i.values[0]!) ? ButtonStyle.Danger : ButtonStyle.Success)
- )
+ .setStatus("Success");
+ const channelButtons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setLabel("Back")
+ .setStyle(ButtonStyle.Primary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id")),
+ new ButtonBuilder()
+ .setCustomId("switch")
+ .setLabel(current.channels.includes(i.values[0]!) ? "Remove" : "Add")
+ .setStyle(
+ current.channels.includes(i.values[0]!) ? ButtonStyle.Danger : ButtonStyle.Success
+ )
+ );
- await i.editReply({embeds: [channelEmbed], components: [channelButtons]});
+ await i.editReply({ embeds: [channelEmbed], components: [channelButtons] });
let j: ButtonInteraction;
try {
- j = await m.awaitMessageComponent({filter: (i) => interaction.user.id === i.user.id && i.message.id === m.id, time: 300000}) as ButtonInteraction;
+ j = (await m.awaitMessageComponent({
+ filter: (i) => interaction.user.id === i.user.id && i.message.id === m.id,
+ time: 300000
+ })) as ButtonInteraction;
} catch (e) {
closed = true;
break;
@@ -761,7 +951,7 @@
break;
}
case "switch": {
- if(current.channels.includes(i.values[0]!)) {
+ if (current.channels.includes(i.values[0]!)) {
current.channels.splice(current.channels.indexOf(i.values[0]!), 1);
} else {
current.channels.push(i.values[0]!);
@@ -773,11 +963,23 @@
case "allowed": {
switch (i.values[0]) {
case "users": {
- current.allowed.users = await toSelectMenu(interaction, m, current.allowed.users, "member", "Mention Settings");
+ current.allowed.users = await toSelectMenu(
+ interaction,
+ m,
+ current.allowed.users,
+ "member",
+ "Mention Settings"
+ );
break;
}
case "roles": {
- current.allowed.roles = await toSelectMenu(interaction, m, current.allowed.roles, "role", "Mention Settings");
+ current.allowed.roles = await toSelectMenu(
+ interaction,
+ m,
+ current.allowed.roles,
+ "role",
+ "Mention Settings"
+ );
break;
}
}
@@ -785,98 +987,94 @@
}
}
}
-
- } while(!closed);
+ } while (!closed);
return current as {
- channels: string[],
+ channels: string[];
allowed: {
- roles: string[],
- users: string[]
- }
+ roles: string[];
+ users: string[];
+ };
};
-
-}
+};
const callback = async (interaction: CommandInteraction): Promise<void> => {
if (!interaction.guild) return;
- const m = await interaction.reply({embeds: LoadingEmbed, fetchReply: true, ephemeral: true});
+ const m = await interaction.reply({ embeds: LoadingEmbed, fetchReply: true, ephemeral: true });
const config = (await client.database.guilds.read(interaction.guild.id)).filters;
let closed = false;
- const button = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("save")
- .setLabel("Save")
- .setStyle(ButtonStyle.Success)
- )
+ const button = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder().setCustomId("save").setLabel("Save").setStyle(ButtonStyle.Success)
+ );
do {
-
- const selectMenu = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("filter")
- .setPlaceholder("Select a filter to edit")
- .addOptions(
- new StringSelectMenuOptionBuilder()
- .setLabel("Invites")
- .setDescription("Automatically delete messages containing server invites")
- .setValue("invites"),
- new StringSelectMenuOptionBuilder()
- .setLabel("Mentions")
- .setDescription("Deletes messages with excessive mentions")
- .setValue("mentions"),
- new StringSelectMenuOptionBuilder()
- .setLabel("Words")
- .setDescription("Delete messages containing filtered words")
- .setValue("words"),
- new StringSelectMenuOptionBuilder()
- .setLabel("Malware")
- .setDescription("Automatically delete files and links containing malware")
- .setValue("malware"),
- new StringSelectMenuOptionBuilder()
- .setLabel("Images")
- .setDescription("Checks performed on images (NSFW, size checking, etc.)")
- .setValue("images"),
- new StringSelectMenuOptionBuilder()
- .setLabel("Clean")
- .setDescription("Automatically delete new messages in specific channels")
- .setValue("clean")
- )
- );
+ const selectMenu = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setCustomId("filter")
+ .setPlaceholder("Select a filter to edit")
+ .addOptions(
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Invites")
+ .setDescription("Automatically delete messages containing server invites")
+ .setValue("invites"),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Mentions")
+ .setDescription("Deletes messages with excessive mentions")
+ .setValue("mentions"),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Words")
+ .setDescription("Delete messages containing filtered words")
+ .setValue("words"),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Malware")
+ .setDescription("Automatically delete files and links containing malware")
+ .setValue("malware"),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Images")
+ .setDescription("Checks performed on images (NSFW, size checking, etc.)")
+ .setValue("images"),
+ new StringSelectMenuOptionBuilder()
+ .setLabel("Clean")
+ .setDescription("Automatically delete new messages in specific channels")
+ .setValue("clean")
+ )
+ );
const embed = new EmojiEmbed()
.setTitle("Automod Settings")
.setDescription(
`${emojiFromBoolean(config.invite.enabled)} **Invites**\n` +
- `${emojiFromBoolean(config.pings.everyone || config.pings.mass > 0 || config.pings.roles)} **Mentions**\n` +
- `${emojiFromBoolean(config.wordFilter.enabled)} **Words**\n` +
- `${emojiFromBoolean(config.malware)} **Malware**\n` +
- `${emojiFromBoolean(config.images.NSFW || config.images.size)} **Images**\n` +
- `${emojiFromBoolean(config.clean.channels.length > 0)} **Clean**\n`
+ `${emojiFromBoolean(
+ config.pings.everyone || config.pings.mass > 0 || config.pings.roles
+ )} **Mentions**\n` +
+ `${emojiFromBoolean(config.wordFilter.enabled)} **Words**\n` +
+ `${emojiFromBoolean(config.malware)} **Malware**\n` +
+ `${emojiFromBoolean(config.images.NSFW || config.images.size)} **Images**\n` +
+ `${emojiFromBoolean(config.clean.channels.length > 0)} **Clean**\n`
)
.setStatus("Success")
- .setEmoji("GUILD.SETTINGS.GREEN")
+ .setEmoji("GUILD.SETTINGS.GREEN");
-
- await interaction.editReply({embeds: [embed], components: [selectMenu, button]});
+ await interaction.editReply({ embeds: [embed], components: [selectMenu, button] });
let i: StringSelectMenuInteraction | ButtonInteraction;
try {
- i = await m.awaitMessageComponent({filter: (i) => i.user.id === interaction.user.id && i.message.id === m.id, time: 300000}) as StringSelectMenuInteraction | ButtonInteraction;
+ i = (await m.awaitMessageComponent({
+ filter: (i) => i.user.id === interaction.user.id && i.message.id === m.id,
+ time: 300000
+ })) as StringSelectMenuInteraction | ButtonInteraction;
} catch (e) {
closed = true;
continue;
}
await i.deferUpdate();
- if(i.isButton()) {
- await client.database.guilds.write(interaction.guild.id, {filters: config});
+ if (i.isButton()) {
+ await client.database.guilds.write(interaction.guild.id, { filters: config });
await client.memory.forceUpdate(interaction.guild.id);
} else {
- switch(i.values[0]) {
+ switch (i.values[0]) {
case "invites": {
config.invite = await inviteMenu(i, m, config.invite);
break;
@@ -905,10 +1103,8 @@
}
}
}
-
- } while(!closed);
- await interaction.deleteReply()
-
+ } while (!closed);
+ await interaction.deleteReply();
};
const check = (interaction: CommandInteraction, _partial: boolean = false) => {
diff --git a/src/commands/settings/autopublish.ts b/src/commands/settings/autopublish.ts
index 27d01bd..afc4e7d 100644
--- a/src/commands/settings/autopublish.ts
+++ b/src/commands/settings/autopublish.ts
@@ -1,4 +1,13 @@
-import { ActionRowBuilder, APIMessageComponentEmoji, ButtonBuilder, ButtonStyle, ChannelSelectMenuBuilder, ChannelType, CommandInteraction, SlashCommandSubcommandBuilder } from "discord.js";
+import {
+ ActionRowBuilder,
+ APIMessageComponentEmoji,
+ ButtonBuilder,
+ ButtonStyle,
+ ChannelSelectMenuBuilder,
+ ChannelType,
+ CommandInteraction,
+ SlashCommandSubcommandBuilder
+} from "discord.js";
import type Discord from "discord.js";
import client from "../../utils/client.js";
import { LoadingEmbed } from "../../utils/defaults.js";
@@ -21,62 +30,62 @@
let config = await client.database.guilds.read(interaction.guild!.id);
let data = _.cloneDeep(config.autoPublish);
do {
- const buttons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("switch")
- .setLabel(data.enabled ? "Enabled" : "Disabled")
- .setStyle(data.enabled ? ButtonStyle.Success : ButtonStyle.Danger)
- .setEmoji(getEmojiByName("CONTROL." + (data.enabled ? "TICK" : "CROSS"), "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("save")
- .setLabel("Save")
- .setStyle(ButtonStyle.Success)
- .setEmoji(getEmojiByName("ICONS.SAVE", "id") as APIMessageComponentEmoji)
- .setDisabled(_.isEqual(data, config.autoPublish))
- );
+ const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("switch")
+ .setLabel(data.enabled ? "Enabled" : "Disabled")
+ .setStyle(data.enabled ? ButtonStyle.Success : ButtonStyle.Danger)
+ .setEmoji(
+ getEmojiByName("CONTROL." + (data.enabled ? "TICK" : "CROSS"), "id") as APIMessageComponentEmoji
+ ),
+ new ButtonBuilder()
+ .setCustomId("save")
+ .setLabel("Save")
+ .setStyle(ButtonStyle.Success)
+ .setEmoji(getEmojiByName("ICONS.SAVE", "id") as APIMessageComponentEmoji)
+ .setDisabled(_.isEqual(data, config.autoPublish))
+ );
- const channelSelect = new ActionRowBuilder<ChannelSelectMenuBuilder>()
- .addComponents(
- new ChannelSelectMenuBuilder()
- .setCustomId("channel")
- .setPlaceholder("Select a channel")
- .setMinValues(1)
- .setChannelTypes(ChannelType.GuildAnnouncement, ChannelType.AnnouncementThread)
- );
+ const channelSelect = new ActionRowBuilder<ChannelSelectMenuBuilder>().addComponents(
+ new ChannelSelectMenuBuilder()
+ .setCustomId("channel")
+ .setPlaceholder("Select a channel")
+ .setMinValues(1)
+ .setChannelTypes(ChannelType.GuildAnnouncement, ChannelType.AnnouncementThread)
+ );
const current = data.channels.map((c) => `> <#${c}>`).join("\n") || "*None set*";
const embed = new EmojiEmbed()
.setTitle("Auto Publish")
.setDescription("Currently enabled in:\n" + current)
- .setStatus('Success')
- .setEmoji("ICONS.PUBLISH")
+ .setStatus("Success")
+ .setEmoji("ICONS.PUBLISH");
- await interaction.editReply({
+ await interaction.editReply({
embeds: [embed],
components: [channelSelect, buttons]
});
let i: Discord.ButtonInteraction | Discord.ChannelSelectMenuInteraction;
try {
- i = await interaction.channel!.awaitMessageComponent({
+ i = (await interaction.channel!.awaitMessageComponent({
filter: (i: Discord.Interaction) => i.user.id === interaction.user.id,
time: 300000
- }) as Discord.ButtonInteraction | Discord.ChannelSelectMenuInteraction;
+ })) as Discord.ButtonInteraction | Discord.ChannelSelectMenuInteraction;
} catch (e) {
closed = true;
continue;
}
await i.deferUpdate();
- if(i.isButton()) {
- switch(i.customId) {
+ if (i.isButton()) {
+ switch (i.customId) {
case "switch": {
data.enabled = !data.enabled;
break;
}
case "save": {
- await client.database.guilds.write(interaction.guild!.id, { "autoPublish": data });
+ await client.database.guilds.write(interaction.guild!.id, { autoPublish: data });
config = await client.database.guilds.read(interaction.guild!.id);
data = _.cloneDeep(config.autoPublish);
await client.memory.forceUpdate(interaction.guild!.id);
@@ -84,16 +93,17 @@
}
}
} else {
- await interaction.editReply({embeds: LoadingEmbed, components: []})
- for(const channel of i.values) {
- data.channels.includes(channel) ? data.channels.splice(data.channels.indexOf(channel), 1) : data.channels.push(channel);
+ await interaction.editReply({ embeds: LoadingEmbed, components: [] });
+ for (const channel of i.values) {
+ data.channels.includes(channel)
+ ? data.channels.splice(data.channels.indexOf(channel), 1)
+ : data.channels.push(channel);
}
}
-
} while (!closed);
await interaction.deleteReply();
-}
+};
export const check = (interaction: CommandInteraction, _partial: boolean = false) => {
const member = interaction.member as Discord.GuildMember;
diff --git a/src/commands/settings/logs/_meta.ts b/src/commands/settings/logs/_meta.ts
index 24a1e54..b1fe78e 100644
--- a/src/commands/settings/logs/_meta.ts
+++ b/src/commands/settings/logs/_meta.ts
@@ -3,6 +3,6 @@
const name = "logs";
const description = "Settings for logging";
-const subcommand = await group(name, description, `settings/logs`)
+const subcommand = await group(name, description, `settings/logs`);
-export { name, description, subcommand as command};
+export { name, description, subcommand as command };
diff --git a/src/commands/settings/logs/attachment.ts b/src/commands/settings/logs/attachment.ts
index 8f0b257..3ee7675 100644
--- a/src/commands/settings/logs/attachment.ts
+++ b/src/commands/settings/logs/attachment.ts
@@ -1,5 +1,12 @@
import { LoadingEmbed } from "../../../utils/defaults.js";
-import Discord, { CommandInteraction, ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelSelectMenuBuilder, ChannelType } from "discord.js";
+import Discord, {
+ CommandInteraction,
+ ActionRowBuilder,
+ ButtonBuilder,
+ ButtonStyle,
+ ChannelSelectMenuBuilder,
+ ChannelType
+} from "discord.js";
import EmojiEmbed from "../../../utils/generateEmojiEmbed.js";
import getEmojiByName from "../../../utils/getEmojiByName.js";
import type { SlashCommandSubcommandBuilder } from "discord.js";
@@ -7,9 +14,7 @@
import { getCommandMentionByName } from "../../../utils/getCommandDataByName.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
- builder
- .setName("attachments")
- .setDescription("Where attachments should be logged to (Premium only)")
+ builder.setName("attachments").setDescription("Where attachments should be logged to (Premium only)");
const callback = async (interaction: CommandInteraction): Promise<unknown> => {
if (interaction.guild) client.database.premium.hasPremium(interaction.guild.id).finally(() => {});
@@ -17,54 +22,55 @@
embeds: LoadingEmbed,
ephemeral: true,
fetchReply: true
- })
-
- if(!await client.database.premium.hasPremium(interaction.guild!.id)) return interaction.editReply({
- embeds: [
- new EmojiEmbed()
- .setTitle("Premium Required")
- .setDescription(`This feature is exclusive to ${getCommandMentionByName("nucleus/premium")} servers.`)
- .setStatus("Danger")
- .setEmoji("NUCLEUS.PREMIUM")
- ]
});
+ if (!(await client.database.premium.hasPremium(interaction.guild!.id)))
+ return interaction.editReply({
+ embeds: [
+ new EmojiEmbed()
+ .setTitle("Premium Required")
+ .setDescription(
+ `This feature is exclusive to ${getCommandMentionByName("nucleus/premium")} servers.`
+ )
+ .setStatus("Danger")
+ .setEmoji("NUCLEUS.PREMIUM")
+ ]
+ });
+
let data = await client.database.guilds.read(interaction.guild!.id);
let channel = data.logging.staff.channel;
let closed = false;
do {
- const channelMenu = new ActionRowBuilder<ChannelSelectMenuBuilder>()
- .addComponents(
- new ChannelSelectMenuBuilder()
- .setCustomId("channel")
- .setPlaceholder("Select a channel")
- .setChannelTypes(ChannelType.GuildText)
- );
- const buttons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("clear")
- .setLabel("Clear")
- .setStyle(ButtonStyle.Danger)
- .setEmoji(getEmojiByName("CONTROL.CROSS", "id") as Discord.APIMessageComponentEmoji)
- .setDisabled(!channel),
- new ButtonBuilder()
- .setCustomId("save")
- .setLabel("Save")
- .setStyle(ButtonStyle.Success)
- .setEmoji(getEmojiByName("ICONS.SAVE", "id") as Discord.APIMessageComponentEmoji)
- .setDisabled(channel === data.logging.staff.channel)
- );
+ const channelMenu = new ActionRowBuilder<ChannelSelectMenuBuilder>().addComponents(
+ new ChannelSelectMenuBuilder()
+ .setCustomId("channel")
+ .setPlaceholder("Select a channel")
+ .setChannelTypes(ChannelType.GuildText)
+ );
+ const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("clear")
+ .setLabel("Clear")
+ .setStyle(ButtonStyle.Danger)
+ .setEmoji(getEmojiByName("CONTROL.CROSS", "id") as Discord.APIMessageComponentEmoji)
+ .setDisabled(!channel),
+ new ButtonBuilder()
+ .setCustomId("save")
+ .setLabel("Save")
+ .setStyle(ButtonStyle.Success)
+ .setEmoji(getEmojiByName("ICONS.SAVE", "id") as Discord.APIMessageComponentEmoji)
+ .setDisabled(channel === data.logging.staff.channel)
+ );
const embed = new EmojiEmbed()
.setTitle("Attachments")
.setDescription(
`The channel to send all attachments from the server, allowing you to check them if they are deleted\n` +
- `**Channel:** ${channel ? `<#${channel}>` : "*None*"}\n`
+ `**Channel:** ${channel ? `<#${channel}>` : "*None*"}\n`
)
.setStatus("Success")
- .setEmoji("CHANNEL.TEXT.CREATE")
+ .setEmoji("CHANNEL.TEXT.CREATE");
await interaction.editReply({
embeds: [embed],
@@ -82,7 +88,7 @@
continue;
}
await i.deferUpdate();
- if(i.isButton()) {
+ if (i.isButton()) {
switch (i.customId) {
case "clear": {
channel = null;
@@ -100,9 +106,8 @@
} else {
channel = i.values[0]!;
}
-
} while (!closed);
- await interaction.deleteReply()
+ await interaction.deleteReply();
};
const check = (interaction: CommandInteraction, _partial: boolean = false) => {
diff --git a/src/commands/settings/logs/events.ts b/src/commands/settings/logs/events.ts
index 05d6928..4cffab7 100644
--- a/src/commands/settings/logs/events.ts
+++ b/src/commands/settings/logs/events.ts
@@ -1,5 +1,18 @@
import { LoadingEmbed } from "../../../utils/defaults.js";
-import Discord, { CommandInteraction, ActionRowBuilder, ChannelSelectMenuBuilder, ChannelType, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, ButtonInteraction, StringSelectMenuInteraction, ChannelSelectMenuInteraction, APIMessageComponentEmoji } from "discord.js";
+import Discord, {
+ CommandInteraction,
+ ActionRowBuilder,
+ ChannelSelectMenuBuilder,
+ ChannelType,
+ ButtonBuilder,
+ ButtonStyle,
+ StringSelectMenuBuilder,
+ StringSelectMenuOptionBuilder,
+ ButtonInteraction,
+ StringSelectMenuInteraction,
+ ChannelSelectMenuInteraction,
+ APIMessageComponentEmoji
+} from "discord.js";
import type { SlashCommandSubcommandBuilder } from "discord.js";
import client from "../../../utils/client.js";
import compare from "lodash";
@@ -26,14 +39,12 @@
webhookUpdate: "Webhooks created or deleted",
guildMemberVerify: "Member runs verify",
autoModeratorDeleted: "Messages auto deleted by Nucleus",
- ticketUpdate: "Tickets created or deleted",
+ ticketUpdate: "Tickets created or deleted"
//nucleusSettingsUpdated: "Nucleus' settings updated by a moderator" // TODO
};
const command = (builder: SlashCommandSubcommandBuilder) =>
- builder
- .setName("events")
- .setDescription("The general log channel for the server, and setting what events to show")
+ builder.setName("events").setDescription("The general log channel for the server, and setting what events to show");
const callback = async (interaction: CommandInteraction): Promise<void> => {
const m = (await interaction.reply({
@@ -47,52 +58,45 @@
let closed = false;
let show = false;
do {
- const channelMenu = new ActionRowBuilder<ChannelSelectMenuBuilder>()
- .addComponents(
- new ChannelSelectMenuBuilder()
- .setCustomId("channel")
- .setPlaceholder("Select a channel")
- .setChannelTypes(ChannelType.GuildText)
- )
- const buttons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("switch")
- .setLabel(data.enabled ? "Enabled" : "Disabled")
- .setStyle(data.enabled ? ButtonStyle.Success : ButtonStyle.Danger)
- .setEmoji(getEmojiByName((data.enabled ? "CONTROL.TICK" : "CONTROL.CROSS"), "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("remove")
- .setLabel("Remove")
- .setStyle(ButtonStyle.Danger)
- .setDisabled(!data.channel),
- new ButtonBuilder()
- .setCustomId("show")
- .setLabel("Manage Events")
- .setStyle(ButtonStyle.Primary),
- new ButtonBuilder()
- .setCustomId("save")
- .setLabel("Save")
- .setStyle(ButtonStyle.Success)
- .setDisabled(compare.isEqual(data, config.logging.logs))
- )
+ const channelMenu = new ActionRowBuilder<ChannelSelectMenuBuilder>().addComponents(
+ new ChannelSelectMenuBuilder()
+ .setCustomId("channel")
+ .setPlaceholder("Select a channel")
+ .setChannelTypes(ChannelType.GuildText)
+ );
+ const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("switch")
+ .setLabel(data.enabled ? "Enabled" : "Disabled")
+ .setStyle(data.enabled ? ButtonStyle.Success : ButtonStyle.Danger)
+ .setEmoji(
+ getEmojiByName(data.enabled ? "CONTROL.TICK" : "CONTROL.CROSS", "id") as APIMessageComponentEmoji
+ ),
+ new ButtonBuilder()
+ .setCustomId("remove")
+ .setLabel("Remove")
+ .setStyle(ButtonStyle.Danger)
+ .setDisabled(!data.channel),
+ new ButtonBuilder().setCustomId("show").setLabel("Manage Events").setStyle(ButtonStyle.Primary),
+ new ButtonBuilder()
+ .setCustomId("save")
+ .setLabel("Save")
+ .setStyle(ButtonStyle.Success)
+ .setDisabled(compare.isEqual(data, config.logging.logs))
+ );
const converted = toHexArray(data.toLog);
- const toLogMenu = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setPlaceholder("Set events to log")
- .setMaxValues(Object.keys(logs).length)
- .setCustomId("logs")
- .setMinValues(0)
- )
+ const toLogMenu = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setPlaceholder("Set events to log")
+ .setMaxValues(Object.keys(logs).length)
+ .setCustomId("logs")
+ .setMinValues(0)
+ );
Object.keys(logs).map((e) => {
toLogMenu.components[0]!.addOptions(
- new StringSelectMenuOptionBuilder()
- .setLabel(logs[e]!)
- .setValue(e)
- .setDefault(converted.includes(e))
- )
+ new StringSelectMenuOptionBuilder().setLabel(logs[e]!).setValue(e).setDefault(converted.includes(e))
+ );
});
const embed = new EmojiEmbed()
@@ -101,11 +105,14 @@
.setEmoji("CHANNEL.TEXT.CREATE")
.setDescription(
`This is the channel that all events you set to be logged will be stored\n` +
- `**Channel:** ${data.channel ? `<#${data.channel}>` : "None"}\n`
- )
+ `**Channel:** ${data.channel ? `<#${data.channel}>` : "None"}\n`
+ );
- const components: ActionRowBuilder<ButtonBuilder | ChannelSelectMenuBuilder | StringSelectMenuBuilder>[] = [channelMenu, buttons];
- if(show) components.push(toLogMenu);
+ const components: ActionRowBuilder<ButtonBuilder | ChannelSelectMenuBuilder | StringSelectMenuBuilder>[] = [
+ channelMenu,
+ buttons
+ ];
+ if (show) components.push(toLogMenu);
await interaction.editReply({
embeds: [embed],
@@ -114,10 +121,10 @@
let i: ButtonInteraction | StringSelectMenuInteraction | ChannelSelectMenuInteraction;
try {
- i = await m.awaitMessageComponent({
+ i = (await m.awaitMessageComponent({
filter: (i) => i.user.id === interaction.user.id,
time: 300000
- }) as ButtonInteraction | StringSelectMenuInteraction | ChannelSelectMenuInteraction;
+ })) as ButtonInteraction | StringSelectMenuInteraction | ChannelSelectMenuInteraction;
} catch (e) {
closed = true;
continue;
@@ -125,8 +132,8 @@
await i.deferUpdate();
- if(i.isButton()) {
- switch(i.customId) {
+ if (i.isButton()) {
+ switch (i.customId) {
case "show": {
show = !show;
break;
@@ -136,10 +143,10 @@
break;
}
case "save": {
- await client.database.guilds.write(interaction.guild!.id, {"logging.logs": data});
+ await client.database.guilds.write(interaction.guild!.id, { "logging.logs": data });
config = await client.database.guilds.read(interaction.guild!.id);
data = Object.assign({}, config.logging.logs);
- await client.memory.forceUpdate(interaction.guild!.id)
+ await client.memory.forceUpdate(interaction.guild!.id);
break;
}
case "remove": {
@@ -147,15 +154,14 @@
break;
}
}
- } else if(i.isStringSelectMenu()) {
+ } else if (i.isStringSelectMenu()) {
const hex = toHexInteger(i.values);
data.toLog = hex;
- } else if(i.isChannelSelectMenu()) {
+ } else if (i.isChannelSelectMenu()) {
data.channel = i.values[0]!;
}
-
} while (!closed);
- await interaction.deleteReply()
+ await interaction.deleteReply();
};
const check = (interaction: CommandInteraction, _partial: boolean = false) => {
diff --git a/src/commands/settings/logs/warnings.ts b/src/commands/settings/logs/warnings.ts
index 4d9a3fa..38b645a 100644
--- a/src/commands/settings/logs/warnings.ts
+++ b/src/commands/settings/logs/warnings.ts
@@ -1,14 +1,19 @@
import { LoadingEmbed } from "../../../utils/defaults.js";
-import Discord, { CommandInteraction, ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelSelectMenuBuilder, ChannelType } from "discord.js";
+import Discord, {
+ CommandInteraction,
+ ActionRowBuilder,
+ ButtonBuilder,
+ ButtonStyle,
+ ChannelSelectMenuBuilder,
+ ChannelType
+} from "discord.js";
import EmojiEmbed from "../../../utils/generateEmojiEmbed.js";
import getEmojiByName from "../../../utils/getEmojiByName.js";
import type { SlashCommandSubcommandBuilder } from "discord.js";
import client from "../../../utils/client.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
- builder
- .setName("warnings")
- .setDescription("Settings for the staff notifications channel")
+ builder.setName("warnings").setDescription("Settings for the staff notifications channel");
const callback = async (interaction: CommandInteraction): Promise<unknown> => {
if (!interaction.guild) return;
@@ -16,34 +21,32 @@
embeds: LoadingEmbed,
ephemeral: true,
fetchReply: true
- })
+ });
let data = await client.database.guilds.read(interaction.guild.id);
let channel = data.logging.staff.channel;
let closed = false;
do {
- const channelMenu = new ActionRowBuilder<ChannelSelectMenuBuilder>()
- .addComponents(
+ const channelMenu = new ActionRowBuilder<ChannelSelectMenuBuilder>().addComponents(
new ChannelSelectMenuBuilder()
.setCustomId("channel")
.setPlaceholder("Select a channel")
.setChannelTypes(ChannelType.GuildText)
);
- const buttons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("clear")
- .setLabel("Clear")
- .setStyle(ButtonStyle.Danger)
- .setEmoji(getEmojiByName("CONTROL.CROSS", "id") as Discord.APIMessageComponentEmoji)
- .setDisabled(!channel),
- new ButtonBuilder()
- .setCustomId("save")
- .setLabel("Save")
- .setStyle(ButtonStyle.Success)
- .setEmoji(getEmojiByName("ICONS.SAVE", "id") as Discord.APIMessageComponentEmoji)
- .setDisabled(channel === data.logging.staff.channel)
- );
+ const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("clear")
+ .setLabel("Clear")
+ .setStyle(ButtonStyle.Danger)
+ .setEmoji(getEmojiByName("CONTROL.CROSS", "id") as Discord.APIMessageComponentEmoji)
+ .setDisabled(!channel),
+ new ButtonBuilder()
+ .setCustomId("save")
+ .setLabel("Save")
+ .setStyle(ButtonStyle.Success)
+ .setEmoji(getEmojiByName("ICONS.SAVE", "id") as Discord.APIMessageComponentEmoji)
+ .setDisabled(channel === data.logging.staff.channel)
+ );
const embed = new EmojiEmbed()
.setTitle("Staff Notifications Channel")
@@ -51,8 +54,8 @@
.setEmoji("CHANNEL.TEXT.CREATE")
.setDescription(
`Logs which require an action from a moderator or administrator will be sent to this channel.\n` +
- `**Channel:** ${channel ? `<#${channel}>` : "*None*"}\n`
- )
+ `**Channel:** ${channel ? `<#${channel}>` : "*None*"}\n`
+ );
await interaction.editReply({
embeds: [embed],
@@ -70,7 +73,7 @@
continue;
}
await i.deferUpdate();
- if(i.isButton()) {
+ if (i.isButton()) {
switch (i.customId) {
case "clear": {
channel = null;
@@ -90,7 +93,7 @@
}
} while (!closed);
- await interaction.deleteReply()
+ await interaction.deleteReply();
};
const check = (interaction: CommandInteraction, _partial: boolean = false) => {
diff --git a/src/commands/settings/moderation.ts b/src/commands/settings/moderation.ts
index 336e53a..6ee6e1e 100644
--- a/src/commands/settings/moderation.ts
+++ b/src/commands/settings/moderation.ts
@@ -1,5 +1,13 @@
import { LoadingEmbed } from "../../utils/defaults.js";
-import Discord, { CommandInteraction, ActionRowBuilder, ButtonBuilder, ButtonStyle, ButtonComponent, TextInputBuilder, RoleSelectMenuBuilder } from "discord.js";
+import Discord, {
+ CommandInteraction,
+ ActionRowBuilder,
+ ButtonBuilder,
+ ButtonStyle,
+ ButtonComponent,
+ TextInputBuilder,
+ RoleSelectMenuBuilder
+} from "discord.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import getEmojiByName from "../../utils/getEmojiByName.js";
import type { SlashCommandSubcommandBuilder } from "discord.js";
@@ -9,7 +17,7 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
.setName("moderation")
- .setDescription("Links and text shown to a user after a moderator action is performed")
+ .setDescription("Links and text shown to a user after a moderator action is performed");
const callback = async (interaction: CommandInteraction): Promise<void> => {
const m = await interaction.reply({
@@ -21,7 +29,7 @@
while (!timedOut) {
const config = await client.database.guilds.read(interaction.guild!.id);
const moderation = config.moderation;
- console.log(moderation)
+ console.log(moderation);
await interaction.editReply({
embeds: [
new EmojiEmbed()
@@ -30,7 +38,8 @@
.setStatus("Success")
.setDescription(
"These links are shown below the message sent in a user's DM when they are punished.\n\n" +
- "**Mute Role:** " + (moderation.mute.role ? `<@&${moderation.mute.role}>` : "*None set*")
+ "**Mute Role:** " +
+ (moderation.mute.role ? `<@&${moderation.mute.role}>` : "*None set*")
)
],
components: [
@@ -76,9 +85,7 @@
.setEmoji(getEmojiByName("CONTROL." + (moderation.mute.timeout ? "TICK" : "CROSS"), "id"))
]),
new ActionRowBuilder<RoleSelectMenuBuilder>().addComponents(
- new RoleSelectMenuBuilder()
- .setCustomId("muteRole")
- .setPlaceholder("Select a new mute role")
+ new RoleSelectMenuBuilder().setCustomId("muteRole").setPlaceholder("Select a new mute role")
)
]
});
@@ -86,7 +93,13 @@
try {
i = await m.awaitMessageComponent({
time: 300000,
- filter: (i) => { return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.message.id === m.id }
+ filter: (i) => {
+ return (
+ i.user.id === interaction.user.id &&
+ i.channel!.id === interaction.channel!.id &&
+ i.message.id === m.id
+ );
+ }
});
} catch (e) {
timedOut = true;
@@ -112,24 +125,28 @@
.setCustomId("modal")
.setTitle(`Options for ${i.customId}`)
.addComponents(
- new ActionRowBuilder<TextInputBuilder>().addComponents(
- new TextInputBuilder()
- .setCustomId("name")
- .setLabel("Button text")
- .setMaxLength(100)
- .setRequired(false)
- .setStyle(Discord.TextInputStyle.Short)
- .setValue(chosen.text ?? "")
- ).toJSON(),
- new ActionRowBuilder<TextInputBuilder>().addComponents(
- new TextInputBuilder()
- .setCustomId("url")
- .setLabel("URL - Type {id} to insert the user's ID")
- .setMaxLength(2000)
- .setRequired(false)
- .setStyle(Discord.TextInputStyle.Short)
- .setValue(chosen.link ?? "")
- ).toJSON()
+ new ActionRowBuilder<TextInputBuilder>()
+ .addComponents(
+ new TextInputBuilder()
+ .setCustomId("name")
+ .setLabel("Button text")
+ .setMaxLength(100)
+ .setRequired(false)
+ .setStyle(Discord.TextInputStyle.Short)
+ .setValue(chosen.text ?? "")
+ )
+ .toJSON(),
+ new ActionRowBuilder<TextInputBuilder>()
+ .addComponents(
+ new TextInputBuilder()
+ .setCustomId("url")
+ .setLabel("URL - Type {id} to insert the user's ID")
+ .setMaxLength(2000)
+ .setRequired(false)
+ .setStyle(Discord.TextInputStyle.Short)
+ .setValue(chosen.link ?? "")
+ )
+ .toJSON()
)
);
await interaction.editReply({
@@ -152,11 +169,11 @@
});
let out: Discord.ModalSubmitInteraction | null;
try {
- out = await modalInteractionCollector(m, interaction.user) as Discord.ModalSubmitInteraction | null;
+ out = (await modalInteractionCollector(m, interaction.user)) as Discord.ModalSubmitInteraction | null;
} catch (e) {
continue;
}
- if (!out || out.isButton()) continue
+ if (!out || out.isButton()) continue;
const buttonText = out.fields.getTextInputValue("name");
const buttonLink = out.fields.getTextInputValue("url").replace(/{id}/gi, "{id}");
const current = chosen;
@@ -171,7 +188,7 @@
}
}
}
- await interaction.deleteReply()
+ await interaction.deleteReply();
};
const check = (interaction: CommandInteraction, _partial: boolean = false) => {
diff --git a/src/commands/settings/rolemenu.ts b/src/commands/settings/rolemenu.ts
index ae174b3..11c6b67 100644
--- a/src/commands/settings/rolemenu.ts
+++ b/src/commands/settings/rolemenu.ts
@@ -1,5 +1,21 @@
import type Discord from "discord.js";
-import { ActionRowBuilder, APIMessageComponentEmoji, ButtonBuilder, ButtonInteraction, ButtonStyle, CommandInteraction, Message, ModalBuilder, RoleSelectMenuBuilder, RoleSelectMenuInteraction, StringSelectMenuBuilder, StringSelectMenuInteraction, StringSelectMenuOptionBuilder, TextInputBuilder, TextInputStyle } from "discord.js";
+import {
+ ActionRowBuilder,
+ APIMessageComponentEmoji,
+ ButtonBuilder,
+ ButtonInteraction,
+ ButtonStyle,
+ CommandInteraction,
+ Message,
+ ModalBuilder,
+ RoleSelectMenuBuilder,
+ RoleSelectMenuInteraction,
+ StringSelectMenuBuilder,
+ StringSelectMenuInteraction,
+ StringSelectMenuOptionBuilder,
+ TextInputBuilder,
+ TextInputStyle
+} from "discord.js";
import type { SlashCommandSubcommandBuilder } from "discord.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import { LoadingEmbed } from "../../utils/defaults.js";
@@ -9,14 +25,11 @@
import { configToDropdown } from "../../actions/roleMenu.js";
import { modalInteractionCollector } from "../../utils/dualCollector.js";
import ellipsis from "../../utils/ellipsis.js";
-import lodash from 'lodash';
+import lodash from "lodash";
const isEqual = lodash.isEqual;
-const command = (builder: SlashCommandSubcommandBuilder) =>
- builder
- .setName("rolemenu")
- .setDescription("rolemenu")
+const command = (builder: SlashCommandSubcommandBuilder) => builder.setName("rolemenu").setDescription("rolemenu");
interface ObjectSchema {
name: string;
@@ -35,34 +48,27 @@
description: "A new role menu page",
min: 0,
max: 0,
- options: [
- {name: "Role 1", description: null, role: "No role set"}
- ]
-}
+ options: [{ name: "Role 1", description: null, role: "No role set" }]
+};
const reorderRoleMenuPages = async (interaction: CommandInteraction, m: Message, currentObj: ObjectSchema[]) => {
- const reorderRow = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("reorder")
- .setPlaceholder("Select all pages in the order you want them to appear.")
- .setMinValues(currentObj.length)
- .setMaxValues(currentObj.length)
- .addOptions(
- currentObj.map((o, i) => new StringSelectMenuOptionBuilder()
- .setLabel(o.name)
- .setValue(i.toString())
- )
- )
- );
- const buttonRow = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setLabel("Back")
- .setStyle(ButtonStyle.Secondary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
- )
+ const reorderRow = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setCustomId("reorder")
+ .setPlaceholder("Select all pages in the order you want them to appear.")
+ .setMinValues(currentObj.length)
+ .setMaxValues(currentObj.length)
+ .addOptions(
+ currentObj.map((o, i) => new StringSelectMenuOptionBuilder().setLabel(o.name).setValue(i.toString()))
+ )
+ );
+ const buttonRow = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setLabel("Back")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
+ );
await interaction.editReply({
embeds: [
new EmojiEmbed()
@@ -74,64 +80,65 @@
});
let out: StringSelectMenuInteraction | ButtonInteraction | null;
try {
- out = await m.awaitMessageComponent({
+ out = (await m.awaitMessageComponent({
filter: (i) => i.channel!.id === interaction.channel!.id,
time: 300000
- }) as StringSelectMenuInteraction | ButtonInteraction | null;
+ })) as StringSelectMenuInteraction | ButtonInteraction | null;
} catch (e) {
console.error(e);
out = null;
}
- if(!out) return;
+ if (!out) return;
out.deferUpdate();
if (out.isButton()) return;
const values = out.values;
const newOrder: ObjectSchema[] = currentObj.map((_, i) => {
- const index = values.findIndex(v => v === i.toString());
+ const index = values.findIndex((v) => v === i.toString());
return currentObj[index];
}) as ObjectSchema[];
return newOrder;
-}
+};
-const editNameDescription = async (i: ButtonInteraction, interaction: StringSelectMenuInteraction | ButtonInteraction, m: Message, data: {name?: string, description?: string}) => {
-
- let {name, description} = data;
+const editNameDescription = async (
+ i: ButtonInteraction,
+ interaction: StringSelectMenuInteraction | ButtonInteraction,
+ m: Message,
+ data: { name?: string; description?: string }
+) => {
+ let { name, description } = data;
const modal = new ModalBuilder()
.setTitle("Edit Name and Description")
.setCustomId("editNameDescription")
.addComponents(
- new ActionRowBuilder<TextInputBuilder>()
- .addComponents(
- new TextInputBuilder()
- .setLabel("Name")
- .setCustomId("name")
- .setPlaceholder("The name of the role (e.g. Programmer)")
- .setStyle(TextInputStyle.Short)
- .setValue(name ?? "")
- .setRequired(true)
- ),
- new ActionRowBuilder<TextInputBuilder>()
- .addComponents(
- new TextInputBuilder()
- .setLabel("Description")
- .setCustomId("description")
- .setPlaceholder("A short description of the role (e.g. A role for people who code)")
- .setStyle(TextInputStyle.Short)
- .setValue(description ?? "")
- )
- )
- const button = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setLabel("Back")
- .setStyle(ButtonStyle.Secondary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
- )
+ new ActionRowBuilder<TextInputBuilder>().addComponents(
+ new TextInputBuilder()
+ .setLabel("Name")
+ .setCustomId("name")
+ .setPlaceholder("The name of the role (e.g. Programmer)")
+ .setStyle(TextInputStyle.Short)
+ .setValue(name ?? "")
+ .setRequired(true)
+ ),
+ new ActionRowBuilder<TextInputBuilder>().addComponents(
+ new TextInputBuilder()
+ .setLabel("Description")
+ .setCustomId("description")
+ .setPlaceholder("A short description of the role (e.g. A role for people who code)")
+ .setStyle(TextInputStyle.Short)
+ .setValue(description ?? "")
+ )
+ );
+ const button = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setLabel("Back")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
+ );
- await i.showModal(modal)
+ await i.showModal(modal);
await interaction.editReply({
embeds: [
new EmojiEmbed()
@@ -144,76 +151,93 @@
let out: Discord.ModalSubmitInteraction | null;
try {
- out = await modalInteractionCollector(m, interaction.user) as Discord.ModalSubmitInteraction | null;
+ out = (await modalInteractionCollector(m, interaction.user)) as Discord.ModalSubmitInteraction | null;
} catch (e) {
console.error(e);
out = null;
}
- if(!out) return [name, description];
+ if (!out) return [name, description];
if (out.isButton()) return [name, description];
name = out.fields.fields.find((f) => f.customId === "name")?.value ?? name;
description = out.fields.fields.find((f) => f.customId === "description")?.value ?? description;
- return [name, description]
+ return [name, description];
+};
-}
+const editRoleMenuPage = async (
+ interaction: StringSelectMenuInteraction | ButtonInteraction,
+ m: Message,
+ data?: ObjectSchema
+): Promise<ObjectSchema | null> => {
+ if (!data)
+ data = {
+ name: "Role Menu Page",
+ description: "A new role menu page",
+ min: 0,
+ max: 0,
+ options: []
+ };
+ const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setLabel("Back")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji),
+ new ButtonBuilder()
+ .setCustomId("edit")
+ .setLabel("Edit")
+ .setStyle(ButtonStyle.Primary)
+ .setEmoji(getEmojiByName("ICONS.EDIT", "id") as APIMessageComponentEmoji),
+ new ButtonBuilder()
+ .setCustomId("addRole")
+ .setLabel("Add Role")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("TICKETS.SUGGESTION", "id") as APIMessageComponentEmoji)
+ );
-const editRoleMenuPage = async (interaction: StringSelectMenuInteraction | ButtonInteraction, m: Message, data?: ObjectSchema): Promise<ObjectSchema | null> => {
- if (!data) data = {
- name: "Role Menu Page",
- description: "A new role menu page",
- min: 0,
- max: 0,
- options: []
- };
- const buttons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setLabel("Back")
- .setStyle(ButtonStyle.Secondary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("edit")
- .setLabel("Edit")
- .setStyle(ButtonStyle.Primary)
- .setEmoji(getEmojiByName("ICONS.EDIT", "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("addRole")
- .setLabel("Add Role")
- .setStyle(ButtonStyle.Secondary)
- .setEmoji(getEmojiByName("TICKETS.SUGGESTION", "id") as APIMessageComponentEmoji)
- );
-
- let back = false
- if(data.options.length === 0) {
- data.options = [
- {name: "Role 1", description: null, role: "No role set"}
- ]
+ let back = false;
+ if (data.options.length === 0) {
+ data.options = [{ name: "Role 1", description: null, role: "No role set" }];
}
do {
- const previewSelect = configToDropdown("Edit Roles", {name: data.name, description: data.description, min: 1, max: 1, options: data.options});
+ const previewSelect = configToDropdown("Edit Roles", {
+ name: data.name,
+ description: data.description,
+ min: 1,
+ max: 1,
+ options: data.options
+ });
const embed = new EmojiEmbed()
.setTitle(`${data.name}`)
.setStatus("Success")
.setDescription(
`**Description:**\n> ${data.description}\n\n` +
- `**Min:** ${data.min}` + (data.min === 0 ? " (Members will be given a skip button)" : "") + "\n" +
- `**Max:** ${data.max}\n`
- )
+ `**Min:** ${data.min}` +
+ (data.min === 0 ? " (Members will be given a skip button)" : "") +
+ "\n" +
+ `**Max:** ${data.max}\n`
+ );
- interaction.editReply({embeds: [embed], components: [previewSelect, buttons]});
+ interaction.editReply({ embeds: [embed], components: [previewSelect, buttons] });
let i: StringSelectMenuInteraction | ButtonInteraction;
try {
- i = await m.awaitMessageComponent({ time: 300000, filter: (i) => i.user.id === interaction.user.id && i.message.id === m.id && i.channelId === interaction.channelId}) as ButtonInteraction | StringSelectMenuInteraction;
+ i = (await m.awaitMessageComponent({
+ time: 300000,
+ filter: (i) =>
+ i.user.id === interaction.user.id && i.message.id === m.id && i.channelId === interaction.channelId
+ })) as ButtonInteraction | StringSelectMenuInteraction;
} catch (e) {
back = true;
break;
}
if (i.isStringSelectMenu()) {
- if(i.customId === "roles") {
+ if (i.customId === "roles") {
await i.deferUpdate();
- await createRoleMenuOptionPage(interaction, m, data.options.find((o) => o.role === (i as StringSelectMenuInteraction).values[0]));
+ await createRoleMenuOptionPage(
+ interaction,
+ m,
+ data.options.find((o) => o.role === (i as StringSelectMenuInteraction).values[0])
+ );
}
} else if (i.isButton()) {
switch (i.customId) {
@@ -235,55 +259,69 @@
}
}
}
-
} while (!back);
- if(isEqual(data, defaultRolePageConfig)) return null;
+ if (isEqual(data, defaultRolePageConfig)) return null;
return data;
-}
+};
-const createRoleMenuOptionPage = async (interaction: StringSelectMenuInteraction | ButtonInteraction, m: Message, data?: {name: string; description: string | null; role: string}) => {
- const { renderRole} = client.logger;
- if (!data) data = {
- name: "New role Menu Option",
- description: null,
- role: ""
- };
+const createRoleMenuOptionPage = async (
+ interaction: StringSelectMenuInteraction | ButtonInteraction,
+ m: Message,
+ data?: { name: string; description: string | null; role: string }
+) => {
+ const { renderRole } = client.logger;
+ if (!data)
+ data = {
+ name: "New role Menu Option",
+ description: null,
+ role: ""
+ };
let back = false;
- const buttons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setLabel("Back")
- .setStyle(ButtonStyle.Secondary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("edit")
- .setLabel("Edit Details")
- .setStyle(ButtonStyle.Primary)
- .setEmoji(getEmojiByName("ICONS.EDIT", "id") as APIMessageComponentEmoji)
- );
+ const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setLabel("Back")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji),
+ new ButtonBuilder()
+ .setCustomId("edit")
+ .setLabel("Edit Details")
+ .setStyle(ButtonStyle.Primary)
+ .setEmoji(getEmojiByName("ICONS.EDIT", "id") as APIMessageComponentEmoji)
+ );
do {
- const roleSelect = new RoleSelectMenuBuilder().setCustomId("role").setPlaceholder(data.role ? "Set role to" : "Set the role");
+ const roleSelect = new RoleSelectMenuBuilder()
+ .setCustomId("role")
+ .setPlaceholder(data.role ? "Set role to" : "Set the role");
const embed = new EmojiEmbed()
.setTitle(`${data.name}`)
.setStatus("Success")
.setDescription(
`**Description:**\n> ${data.description ?? "No description set"}\n\n` +
- `**Role:** ${data.role ? renderRole((await interaction.guild!.roles.fetch(data.role))!) : "No role set"}\n`
- )
+ `**Role:** ${
+ data.role ? renderRole((await interaction.guild!.roles.fetch(data.role))!) : "No role set"
+ }\n`
+ );
- interaction.editReply({embeds: [embed], components: [new ActionRowBuilder<RoleSelectMenuBuilder>().addComponents(roleSelect), buttons]});
+ interaction.editReply({
+ embeds: [embed],
+ components: [new ActionRowBuilder<RoleSelectMenuBuilder>().addComponents(roleSelect), buttons]
+ });
let i: RoleSelectMenuInteraction | ButtonInteraction;
try {
- i = await m.awaitMessageComponent({ time: 300000, filter: (i) => i.user.id === interaction.user.id && i.message.id === m.id && i.channelId === interaction.channelId}) as ButtonInteraction | RoleSelectMenuInteraction;
+ i = (await m.awaitMessageComponent({
+ time: 300000,
+ filter: (i) =>
+ i.user.id === interaction.user.id && i.message.id === m.id && i.channelId === interaction.channelId
+ })) as ButtonInteraction | RoleSelectMenuInteraction;
} catch (e) {
back = true;
break;
}
if (i.isRoleSelectMenu()) {
- if(i.customId === "role") {
+ if (i.customId === "role") {
await i.deferUpdate();
data.role = (i as RoleSelectMenuInteraction).values[0]!;
}
@@ -296,7 +334,12 @@
}
case "edit": {
await i.deferUpdate();
- const [name, description] = await editNameDescription(i, interaction, m, data as {name: string; description: string});
+ const [name, description] = await editNameDescription(
+ i,
+ interaction,
+ m,
+ data as { name: string; description: string }
+ );
data.name = name ? name : data.name;
data.description = description ? description : data.description;
break;
@@ -305,11 +348,11 @@
}
} while (!back);
return data;
-}
+};
const callback = async (interaction: CommandInteraction): Promise<void> => {
if (!interaction.guild) return;
- const m = await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true});
+ const m = await interaction.reply({ embeds: LoadingEmbed, ephemeral: true, fetchReply: true });
let page = 0;
let closed = false;
@@ -317,10 +360,7 @@
let currentObject: ObjectSchema[] = config.roleMenu.options;
let modified = false;
do {
- const embed = new EmojiEmbed()
- .setTitle("Role Menu")
- .setEmoji("GUILD.GREEN")
- .setStatus("Success");
+ const embed = new EmojiEmbed().setTitle("Role Menu").setEmoji("GUILD.GREEN").setStatus("Success");
const noRoleMenus = currentObject.length === 0;
let current: ObjectSchema;
@@ -341,54 +381,52 @@
.setDescription("Delete this page")
.setValue("delete")
.setEmoji(getEmojiByName("TICKETS.ISSUE", "id") as APIMessageComponentEmoji)
- );
- const buttonRow = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setStyle(ButtonStyle.Primary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
- .setDisabled(page === 0),
- new ButtonBuilder()
- .setCustomId("next")
- .setEmoji(getEmojiByName("CONTROL.RIGHT", "id") as APIMessageComponentEmoji)
- .setStyle(ButtonStyle.Primary)
- .setDisabled(page === Object.keys(currentObject).length - 1),
- new ButtonBuilder()
- .setCustomId("add")
- .setLabel("New Page")
- .setEmoji(getEmojiByName("TICKETS.SUGGESTION", "id") as APIMessageComponentEmoji)
- .setStyle(ButtonStyle.Secondary)
- .setDisabled(Object.keys(currentObject).length >= 24),
- new ButtonBuilder()
- .setCustomId("reorder")
- .setLabel("Reorder Pages")
- .setEmoji(getEmojiByName("ICONS.REORDER", "id") as APIMessageComponentEmoji)
- .setStyle(ButtonStyle.Secondary)
- .setDisabled(Object.keys(currentObject).length <= 1),
- new ButtonBuilder()
- .setCustomId("save")
- .setLabel("Save")
- .setEmoji(getEmojiByName("ICONS.SAVE", "id") as APIMessageComponentEmoji)
- .setStyle(ButtonStyle.Success)
- .setDisabled(!modified),
);
- if(noRoleMenus) {
- embed.setDescription("No role menu pages have been set up yet. Use the button below to add one.\n\n" +
- createPageIndicator(1, 1, undefined, true)
+ const buttonRow = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setStyle(ButtonStyle.Primary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
+ .setDisabled(page === 0),
+ new ButtonBuilder()
+ .setCustomId("next")
+ .setEmoji(getEmojiByName("CONTROL.RIGHT", "id") as APIMessageComponentEmoji)
+ .setStyle(ButtonStyle.Primary)
+ .setDisabled(page === Object.keys(currentObject).length - 1),
+ new ButtonBuilder()
+ .setCustomId("add")
+ .setLabel("New Page")
+ .setEmoji(getEmojiByName("TICKETS.SUGGESTION", "id") as APIMessageComponentEmoji)
+ .setStyle(ButtonStyle.Secondary)
+ .setDisabled(Object.keys(currentObject).length >= 24),
+ new ButtonBuilder()
+ .setCustomId("reorder")
+ .setLabel("Reorder Pages")
+ .setEmoji(getEmojiByName("ICONS.REORDER", "id") as APIMessageComponentEmoji)
+ .setStyle(ButtonStyle.Secondary)
+ .setDisabled(Object.keys(currentObject).length <= 1),
+ new ButtonBuilder()
+ .setCustomId("save")
+ .setLabel("Save")
+ .setEmoji(getEmojiByName("ICONS.SAVE", "id") as APIMessageComponentEmoji)
+ .setStyle(ButtonStyle.Success)
+ .setDisabled(!modified)
+ );
+ if (noRoleMenus) {
+ embed.setDescription(
+ "No role menu pages have been set up yet. Use the button below to add one.\n\n" +
+ createPageIndicator(1, 1, undefined, true)
);
pageSelect.setDisabled(true);
actionSelect.setDisabled(true);
- pageSelect.addOptions(new StringSelectMenuOptionBuilder()
- .setLabel("No role menu pages")
- .setValue("none")
- );
+ pageSelect.addOptions(new StringSelectMenuOptionBuilder().setLabel("No role menu pages").setValue("none"));
} else {
page = Math.min(page, Object.keys(currentObject).length - 1);
current = currentObject[page]!;
- embed.setDescription(`**Currently Editing:** ${current.name}\n\n` +
- `**Description:**\n> ${current.description}\n` +
- `\n\n${createPageIndicator(Object.keys(config.roleMenu.options).length, page)}`
+ embed.setDescription(
+ `**Currently Editing:** ${current.name}\n\n` +
+ `**Description:**\n> ${current.description}\n` +
+ `\n\n${createPageIndicator(Object.keys(config.roleMenu.options).length, page)}`
);
pageSelect.addOptions(
@@ -399,13 +437,23 @@
.setValue(index.toString());
})
);
-
}
- await interaction.editReply({embeds: [embed], components: [new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(actionSelect), new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(pageSelect), buttonRow]});
+ await interaction.editReply({
+ embeds: [embed],
+ components: [
+ new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(actionSelect),
+ new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(pageSelect),
+ buttonRow
+ ]
+ });
let i: StringSelectMenuInteraction | ButtonInteraction;
try {
- i = await m.awaitMessageComponent({ time: 300000, filter: (i) => i.user.id === interaction.user.id && i.message.id === m.id && i.channelId === interaction.channelId}) as ButtonInteraction | StringSelectMenuInteraction;
+ i = (await m.awaitMessageComponent({
+ time: 300000,
+ filter: (i) =>
+ i.user.id === interaction.user.id && i.message.id === m.id && i.channelId === interaction.channelId
+ })) as ButtonInteraction | StringSelectMenuInteraction;
} catch (e) {
closed = true;
continue;
@@ -423,20 +471,20 @@
break;
}
case "add": {
- const newPage = await editRoleMenuPage(i, m)
- if(!newPage) break;
+ const newPage = await editRoleMenuPage(i, m);
+ if (!newPage) break;
currentObject.push();
page = currentObject.length - 1;
break;
}
case "reorder": {
const reordered = await reorderRoleMenuPages(interaction, m, currentObject);
- if(!reordered) break;
+ if (!reordered) break;
currentObject = reordered;
break;
}
case "save": {
- await client.database.guilds.write(interaction.guild.id, {"roleMenu.options": currentObject});
+ await client.database.guilds.write(interaction.guild.id, { "roleMenu.options": currentObject });
modified = false;
await client.memory.forceUpdate(interaction.guild.id);
break;
@@ -445,16 +493,16 @@
} else if (i.isStringSelectMenu()) {
switch (i.customId) {
case "action": {
- switch(i.values[0]) {
+ switch (i.values[0]) {
case "edit": {
const edited = await editRoleMenuPage(i, m, current!);
- if(!edited) break;
+ if (!edited) break;
currentObject[page] = edited;
modified = true;
break;
}
case "delete": {
- if(page === 0 && currentObject.keys.length - 1 > 0) page++;
+ if (page === 0 && currentObject.keys.length - 1 > 0) page++;
else page--;
currentObject.splice(page, 1);
break;
@@ -468,9 +516,8 @@
}
}
}
-
} while (!closed);
- await interaction.deleteReply()
+ await interaction.deleteReply();
};
const check = (interaction: CommandInteraction, _partial: boolean = false) => {
diff --git a/src/commands/settings/stats.ts b/src/commands/settings/stats.ts
index ecab612..d4e4439 100644
--- a/src/commands/settings/stats.ts
+++ b/src/commands/settings/stats.ts
@@ -1,5 +1,21 @@
import { LoadingEmbed } from "../../utils/defaults.js";
-import Discord, { CommandInteraction, Message, ActionRowBuilder, StringSelectMenuBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuOptionBuilder, APIMessageComponentEmoji, TextInputBuilder, StringSelectMenuInteraction, ButtonInteraction, MessageComponentInteraction, ChannelSelectMenuBuilder, ChannelSelectMenuInteraction, ModalBuilder } from "discord.js";
+import Discord, {
+ CommandInteraction,
+ Message,
+ ActionRowBuilder,
+ StringSelectMenuBuilder,
+ ButtonBuilder,
+ ButtonStyle,
+ StringSelectMenuOptionBuilder,
+ APIMessageComponentEmoji,
+ TextInputBuilder,
+ StringSelectMenuInteraction,
+ ButtonInteraction,
+ MessageComponentInteraction,
+ ChannelSelectMenuBuilder,
+ ChannelSelectMenuInteraction,
+ ModalBuilder
+} from "discord.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import type { SlashCommandSubcommandBuilder } from "discord.js";
import client from "../../utils/client.js";
@@ -9,14 +25,10 @@
import createPageIndicator from "../../utils/createPageIndicator.js";
import { modalInteractionCollector } from "../../utils/dualCollector.js";
-
const command = (builder: SlashCommandSubcommandBuilder) =>
- builder
- .setName("stats")
- .setDescription("Controls channels which update when someone joins or leaves the server")
+ builder.setName("stats").setDescription("Controls channels which update when someone joins or leaves the server");
-
-const showModal = async (interaction: MessageComponentInteraction, current: { enabled: boolean; name: string; }) => {
+const showModal = async (interaction: MessageComponentInteraction, current: { enabled: boolean; name: string }) => {
await interaction.showModal(
new ModalBuilder()
.setCustomId("modal")
@@ -28,7 +40,7 @@
.setLabel("Server Info (1/3)")
.setPlaceholder(
`{serverName} - This server's name\n\n` +
- `These placeholders will be replaced with the server's name, etc..`
+ `These placeholders will be replaced with the server's name, etc..`
)
.setMaxLength(1)
.setRequired(false)
@@ -40,8 +52,8 @@
.setLabel("Member Counts (2/3) - {MemberCount:...}")
.setPlaceholder(
`{:all} - Total member count\n` +
- `{:humans} - Total non-bot users\n` +
- `{:bots} - Number of bots\n`
+ `{:humans} - Total non-bot users\n` +
+ `{:bots} - Number of bots\n`
)
.setMaxLength(1)
.setRequired(false)
@@ -51,9 +63,7 @@
new TextInputBuilder()
.setCustomId("ex3")
.setLabel("Latest Member (3/3) - {member:...}")
- .setPlaceholder(
- `{:name} - The members name\n`
- )
+ .setPlaceholder(`{:name} - The members name\n`)
.setMaxLength(1)
.setRequired(false)
.setStyle(Discord.TextInputStyle.Paragraph)
@@ -69,35 +79,46 @@
)
)
);
-}
+};
-type ObjectSchema = Record<string, {name: string, enabled: boolean}>
+type ObjectSchema = Record<string, { name: string; enabled: boolean }>;
-
-const addStatsChannel = async (interaction: CommandInteraction, m: Message, currentObject: ObjectSchema): Promise<ObjectSchema> => {
+const addStatsChannel = async (
+ interaction: CommandInteraction,
+ m: Message,
+ currentObject: ObjectSchema
+): Promise<ObjectSchema> => {
let closed = false;
let cancelled = false;
- const originalObject = Object.fromEntries(Object.entries(currentObject).map(([k, v]) => [k, {...v}]));
+ const originalObject = Object.fromEntries(Object.entries(currentObject).map(([k, v]) => [k, { ...v }]));
let newChannel: string | undefined;
let newChannelName: string = "{memberCount:all}-members";
let newChannelEnabled: boolean = true;
do {
m = await interaction.editReply({
- embeds: [new EmojiEmbed()
- .setTitle("Stats Channel")
- .setDescription(
- `New stats channel` + (newChannel ? ` in <#${newChannel}>` : "") + "\n\n" +
- `**Name:** \`${newChannelName}\`\n` +
- `**Preview:** ${await convertCurlyBracketString(newChannelName, interaction.user!.id, interaction.user.username, interaction.guild!.name, interaction.guild!.members)}\n` +
- `**Enabled:** ${newChannelEnabled ? "Yes" : "No"}\n\n`
- )
- .setEmoji("SETTINGS.STATS.GREEN")
- .setStatus("Success")
- ], components: [
+ embeds: [
+ new EmojiEmbed()
+ .setTitle("Stats Channel")
+ .setDescription(
+ `New stats channel` +
+ (newChannel ? ` in <#${newChannel}>` : "") +
+ "\n\n" +
+ `**Name:** \`${newChannelName}\`\n` +
+ `**Preview:** ${await convertCurlyBracketString(
+ newChannelName,
+ interaction.user!.id,
+ interaction.user.username,
+ interaction.guild!.name,
+ interaction.guild!.members
+ )}\n` +
+ `**Enabled:** ${newChannelEnabled ? "Yes" : "No"}\n\n`
+ )
+ .setEmoji("SETTINGS.STATS.GREEN")
+ .setStatus("Success")
+ ],
+ components: [
new ActionRowBuilder<ChannelSelectMenuBuilder>().addComponents(
- new ChannelSelectMenuBuilder()
- .setCustomId("channel")
- .setPlaceholder("Select a channel to use")
+ new ChannelSelectMenuBuilder().setCustomId("channel").setPlaceholder("Select a channel to use")
),
new ActionRowBuilder<ButtonBuilder>().addComponents(
new ButtonBuilder()
@@ -125,9 +146,16 @@
});
let i: ButtonInteraction | ChannelSelectMenuInteraction;
try {
- i = await m.awaitMessageComponent({ time: 300000, filter: (i) => {
- return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.message.id === m.id;
- }}) as ButtonInteraction | ChannelSelectMenuInteraction;
+ i = (await m.awaitMessageComponent({
+ time: 300000,
+ filter: (i) => {
+ return (
+ i.user.id === interaction.user.id &&
+ i.channel!.id === interaction.channel!.id &&
+ i.message.id === m.id
+ );
+ }
+ })) as ButtonInteraction | ChannelSelectMenuInteraction;
} catch (e) {
closed = true;
cancelled = true;
@@ -146,18 +174,19 @@
currentObject[newChannel] = {
name: newChannelName,
enabled: newChannelEnabled
- }
+ };
}
closed = true;
break;
}
case "editName": {
await interaction.editReply({
- embeds: [new EmojiEmbed()
- .setTitle("Stats Channel")
- .setDescription("Modal opened. If you can't see it, click back and try again.")
- .setStatus("Success")
- .setEmoji("SETTINGS.STATS.GREEN")
+ embeds: [
+ new EmojiEmbed()
+ .setTitle("Stats Channel")
+ .setDescription("Modal opened. If you can't see it, click back and try again.")
+ .setStatus("Success")
+ .setEmoji("SETTINGS.STATS.GREEN")
],
components: [
new ActionRowBuilder<ButtonBuilder>().addComponents(
@@ -169,9 +198,10 @@
)
]
});
- showModal(i, {name: newChannelName, enabled: newChannelEnabled})
+ showModal(i, { name: newChannelName, enabled: newChannelEnabled });
- const out: Discord.ModalSubmitInteraction | ButtonInteraction| null = await modalInteractionCollector(m, interaction.user);
+ const out: Discord.ModalSubmitInteraction | ButtonInteraction | null =
+ await modalInteractionCollector(m, interaction.user);
if (!out) continue;
if (out.isButton()) continue;
newChannelName = out.fields.getTextInputValue("text");
@@ -189,11 +219,11 @@
newChannel = i.values[0];
}
}
- } while (!closed)
+ } while (!closed);
if (cancelled) return originalObject;
if (!(newChannel && newChannelName && newChannelEnabled)) return originalObject;
return currentObject;
-}
+};
const callback = async (interaction: CommandInteraction) => {
if (!interaction.guild) return;
const { renderChannel } = client.logger;
@@ -204,12 +234,9 @@
let currentObject: ObjectSchema = config.stats;
let modified = false;
do {
- const embed = new EmojiEmbed()
- .setTitle("Stats Settings")
- .setEmoji("SETTINGS.STATS.GREEN")
- .setStatus("Success");
+ const embed = new EmojiEmbed().setTitle("Stats Settings").setEmoji("SETTINGS.STATS.GREEN").setStatus("Success");
const noStatsChannels = Object.keys(currentObject).length === 0;
- let current: { enabled: boolean; name: string; };
+ let current: { enabled: boolean; name: string };
const pageSelect = new StringSelectMenuBuilder()
.setCustomId("page")
@@ -228,83 +255,109 @@
.setDescription("Delete the stats channel")
.setValue("delete")
.setEmoji(getEmojiByName("TICKETS.ISSUE", "id") as APIMessageComponentEmoji)
- );
- const buttonRow = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setStyle(ButtonStyle.Primary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
- .setDisabled(page === 0),
- new ButtonBuilder()
- .setCustomId("next")
- .setEmoji(getEmojiByName("CONTROL.RIGHT", "id") as APIMessageComponentEmoji)
- .setStyle(ButtonStyle.Primary)
- .setDisabled(page === Object.keys(currentObject).length - 1),
- new ButtonBuilder()
- .setCustomId("add")
- .setLabel("Create new")
- .setEmoji(getEmojiByName("TICKETS.SUGGESTION", "id") as APIMessageComponentEmoji)
- .setStyle(ButtonStyle.Secondary)
- .setDisabled(Object.keys(currentObject).length >= 24),
- new ButtonBuilder()
- .setCustomId("save")
- .setLabel("Save")
- .setEmoji(getEmojiByName("ICONS.SAVE", "id") as APIMessageComponentEmoji)
- .setStyle(ButtonStyle.Success)
- .setDisabled(modified),
);
+ const buttonRow = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setStyle(ButtonStyle.Primary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
+ .setDisabled(page === 0),
+ new ButtonBuilder()
+ .setCustomId("next")
+ .setEmoji(getEmojiByName("CONTROL.RIGHT", "id") as APIMessageComponentEmoji)
+ .setStyle(ButtonStyle.Primary)
+ .setDisabled(page === Object.keys(currentObject).length - 1),
+ new ButtonBuilder()
+ .setCustomId("add")
+ .setLabel("Create new")
+ .setEmoji(getEmojiByName("TICKETS.SUGGESTION", "id") as APIMessageComponentEmoji)
+ .setStyle(ButtonStyle.Secondary)
+ .setDisabled(Object.keys(currentObject).length >= 24),
+ new ButtonBuilder()
+ .setCustomId("save")
+ .setLabel("Save")
+ .setEmoji(getEmojiByName("ICONS.SAVE", "id") as APIMessageComponentEmoji)
+ .setStyle(ButtonStyle.Success)
+ .setDisabled(modified)
+ );
if (noStatsChannels) {
- embed.setDescription("No stats channels have been set up yet. Use the button below to add one.\n\n" +
- createPageIndicator(1, 1, undefined, true)
+ embed.setDescription(
+ "No stats channels have been set up yet. Use the button below to add one.\n\n" +
+ createPageIndicator(1, 1, undefined, true)
);
pageSelect.setDisabled(true);
actionSelect.setDisabled(true);
- pageSelect.addOptions(new StringSelectMenuOptionBuilder()
- .setLabel("No stats channels")
- .setValue("none")
- );
+ pageSelect.addOptions(new StringSelectMenuOptionBuilder().setLabel("No stats channels").setValue("none"));
} else {
page = Math.min(page, Object.keys(currentObject).length - 1);
- current = currentObject[Object.keys(config.stats)[page]!]!
- actionSelect.addOptions(new StringSelectMenuOptionBuilder()
- .setLabel(current.enabled ? "Disable" : "Enable")
- .setValue("toggleEnabled")
- .setDescription(`Currently ${current.enabled ? "Enabled" : "Disabled"}, click to ${current.enabled ? "disable" : "enable"} this channel`)
- .setEmoji(getEmojiByName(current.enabled ? "CONTROL.TICK" : "CONTROL.CROSS", "id") as APIMessageComponentEmoji)
+ current = currentObject[Object.keys(config.stats)[page]!]!;
+ actionSelect.addOptions(
+ new StringSelectMenuOptionBuilder()
+ .setLabel(current.enabled ? "Disable" : "Enable")
+ .setValue("toggleEnabled")
+ .setDescription(
+ `Currently ${current.enabled ? "Enabled" : "Disabled"}, click to ${
+ current.enabled ? "disable" : "enable"
+ } this channel`
+ )
+ .setEmoji(
+ getEmojiByName(
+ current.enabled ? "CONTROL.TICK" : "CONTROL.CROSS",
+ "id"
+ ) as APIMessageComponentEmoji
+ )
);
- embed.setDescription(`**Currently Editing:** ${renderChannel(Object.keys(currentObject)[page]!)}\n\n` +
- `${getEmojiByName(current.enabled ? "CONTROL.TICK" : "CONTROL.CROSS")} Currently ${current.enabled ? "Enabled" : "Disabled"}\n` +
- `**Name:** \`${current.name}\`\n` +
- `**Preview:** ${await convertCurlyBracketString(current.name, interaction.user.id, interaction.user.username, interaction.guild.name, interaction.guild.members)}` + '\n\n' +
- createPageIndicator(Object.keys(config.stats).length, page)
+ embed.setDescription(
+ `**Currently Editing:** ${renderChannel(Object.keys(currentObject)[page]!)}\n\n` +
+ `${getEmojiByName(current.enabled ? "CONTROL.TICK" : "CONTROL.CROSS")} Currently ${
+ current.enabled ? "Enabled" : "Disabled"
+ }\n` +
+ `**Name:** \`${current.name}\`\n` +
+ `**Preview:** ${await convertCurlyBracketString(
+ current.name,
+ interaction.user.id,
+ interaction.user.username,
+ interaction.guild.name,
+ interaction.guild.members
+ )}` +
+ "\n\n" +
+ createPageIndicator(Object.keys(config.stats).length, page)
);
for (const [id, { name, enabled }] of Object.entries(currentObject)) {
- pageSelect.addOptions(new StringSelectMenuOptionBuilder()
- .setLabel(`${name} (${renderChannel(id)})`)
- .setEmoji(getEmojiByName(enabled ? "CONTROL.TICK" : "CONTROL.CROSS", "id") as APIMessageComponentEmoji)
- .setDescription(`${enabled ? "Enabled" : "Disabled"}`)
- .setValue(id)
+ pageSelect.addOptions(
+ new StringSelectMenuOptionBuilder()
+ .setLabel(`${name} (${renderChannel(id)})`)
+ .setEmoji(
+ getEmojiByName(enabled ? "CONTROL.TICK" : "CONTROL.CROSS", "id") as APIMessageComponentEmoji
+ )
+ .setDescription(`${enabled ? "Enabled" : "Disabled"}`)
+ .setValue(id)
);
}
}
- interaction.editReply({embeds: [embed], components: [
- new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(pageSelect),
- new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(actionSelect),
- buttonRow
- ]});
+ interaction.editReply({
+ embeds: [embed],
+ components: [
+ new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(pageSelect),
+ new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(actionSelect),
+ buttonRow
+ ]
+ });
let i: StringSelectMenuInteraction | ButtonInteraction;
try {
- i = await m.awaitMessageComponent({ filter: (interaction) => interaction.user.id === interaction.user.id, time: 60000 }) as StringSelectMenuInteraction | ButtonInteraction;
+ i = (await m.awaitMessageComponent({
+ filter: (interaction) => interaction.user.id === interaction.user.id,
+ time: 60000
+ })) as StringSelectMenuInteraction | ButtonInteraction;
} catch (e) {
closed = true;
continue;
}
- if(i.isStringSelectMenu()) {
- switch(i.customId) {
+ if (i.isStringSelectMenu()) {
+ switch (i.customId) {
case "page": {
await i.deferUpdate();
page = Object.keys(currentObject).indexOf(i.values[0]!);
@@ -312,9 +365,9 @@
}
case "action": {
modified = true;
- switch(i.values[0]!) {
+ switch (i.values[0]!) {
case "edit": {
- showModal(i, current!)
+ showModal(i, current!);
await interaction.editReply({
embeds: [
new EmojiEmbed()
@@ -335,24 +388,31 @@
});
let out: Discord.ModalSubmitInteraction | null;
try {
- out = await modalInteractionCollector(m, interaction.user) as Discord.ModalSubmitInteraction | null;
+ out = (await modalInteractionCollector(
+ m,
+ interaction.user
+ )) as Discord.ModalSubmitInteraction | null;
} catch (e) {
continue;
}
- if (!out) continue
+ if (!out) continue;
if (out.isButton()) continue;
- currentObject[Object.keys(currentObject)[page]!]!.name = out.fields.getTextInputValue("text");
+ currentObject[Object.keys(currentObject)[page]!]!.name =
+ out.fields.getTextInputValue("text");
break;
}
case "toggleEnabled": {
await i.deferUpdate();
- currentObject[Object.keys(currentObject)[page]!]!.enabled = !currentObject[Object.keys(currentObject)[page]!]!.enabled;
+ currentObject[Object.keys(currentObject)[page]!]!.enabled =
+ !currentObject[Object.keys(currentObject)[page]!]!.enabled;
modified = true;
break;
}
case "delete": {
await i.deferUpdate();
- currentObject = Object.fromEntries(Object.entries(currentObject).filter(([k]) => k !== Object.keys(currentObject)[page]!));
+ currentObject = Object.fromEntries(
+ Object.entries(currentObject).filter(([k]) => k !== Object.keys(currentObject)[page]!)
+ );
page = Math.min(page, Object.keys(currentObject).length - 1);
modified = true;
break;
@@ -363,7 +423,7 @@
}
} else {
await i.deferUpdate();
- switch(i.customId) {
+ switch (i.customId) {
case "back": {
page--;
break;
@@ -378,7 +438,7 @@
break;
}
case "save": {
- await client.database.guilds.write(interaction.guild.id, {stats: currentObject});
+ await client.database.guilds.write(interaction.guild.id, { stats: currentObject });
singleNotify("statsChannelDeleted", interaction.guild.id, true);
modified = false;
await client.memory.forceUpdate(interaction.guild.id);
@@ -386,9 +446,8 @@
}
}
}
-
} while (!closed);
- await interaction.deleteReply()
+ await interaction.deleteReply();
};
const check = (interaction: CommandInteraction, _partial: boolean = false) => {
@@ -398,7 +457,6 @@
return true;
};
-
export { command };
export { callback };
export { check };
diff --git a/src/commands/settings/tickets.ts b/src/commands/settings/tickets.ts
index 838defb..c0025d8 100644
--- a/src/commands/settings/tickets.ts
+++ b/src/commands/settings/tickets.ts
@@ -30,9 +30,7 @@
import { LinkWarningFooter } from "../../utils/defaults.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
- builder
- .setName("tickets")
- .setDescription("Shows settings for tickets")
+ builder.setName("tickets").setDescription("Shows settings for tickets");
const callback = async (interaction: CommandInteraction): Promise<unknown> => {
if (!interaction.guild) return;
@@ -45,7 +43,7 @@
data.tickets.customTypes = (data.tickets.customTypes ?? []).filter(
(value: string, index: number, array: string[]) => array.indexOf(value) === index
);
- let ticketData = (await client.database.guilds.read(interaction.guild.id)).tickets
+ let ticketData = (await client.database.guilds.read(interaction.guild.id)).tickets;
let changesMade = false;
let timedOut = false;
let errorMessage = "";
@@ -54,23 +52,28 @@
.setTitle("Tickets")
.setDescription(
`${ticketData.enabled ? "" : getEmojiByName("TICKETS.REPORT")} **Enabled:** ${
- ticketData.enabled ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`
+ ticketData.enabled
+ ? `${getEmojiByName("CONTROL.TICK")} Yes`
+ : `${getEmojiByName("CONTROL.CROSS")} No`
}\n` +
`${ticketData.category ? "" : getEmojiByName("TICKETS.REPORT")}` +
- ((await interaction.guild.channels.fetch(ticketData.category!))!.type === ChannelType.GuildCategory ?
- `**Category:** ` : `**Channel:** `) + // TODO: Notify if permissions are wrong
+ ((await interaction.guild.channels.fetch(ticketData.category!))!.type === ChannelType.GuildCategory
+ ? `**Category:** `
+ : `**Channel:** `) + // TODO: Notify if permissions are wrong
`${ticketData.category ? `<#${ticketData.category}>` : "*None set*"}\n` +
`**Max Tickets:** ${ticketData.maxTickets ? ticketData.maxTickets : "*No limit*"}\n` +
`**Support Ping:** ${ticketData.supportRole ? `<@&${ticketData.supportRole}>` : "*None set*"}\n\n` +
- (ticketData.useCustom && ticketData.customTypes === null ? `${getEmojiByName("TICKETS.REPORT")} ` : "") +
+ (ticketData.useCustom && ticketData.customTypes === null
+ ? `${getEmojiByName("TICKETS.REPORT")} `
+ : "") +
`${ticketData.useCustom ? "Custom" : "Default"} types in use` +
"\n\n" +
`${getEmojiByName("TICKETS.REPORT")} *Indicates a setting stopping tickets from being used*`
)
.setStatus("Success")
.setEmoji("GUILD.TICKET.OPEN");
- if (errorMessage) embed.setFooter({text: errorMessage, iconURL: LinkWarningFooter.iconURL});
- m = (await interaction.editReply({
+ if (errorMessage) embed.setFooter({ text: errorMessage, iconURL: LinkWarningFooter.iconURL });
+ m = await interaction.editReply({
embeds: [embed],
components: [
new ActionRowBuilder<ButtonBuilder>().addComponents(
@@ -111,12 +114,18 @@
.setDisabled(!ticketData.enabled)
)
]
- }));
+ });
let i: RoleSelectMenuInteraction | ButtonInteraction | ChannelSelectMenuInteraction;
try {
i = await m.awaitMessageComponent<2 | 6 | 8>({
time: 300000,
- filter: (i) => { return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.message.id === m.id }
+ filter: (i) => {
+ return (
+ i.user.id === interaction.user.id &&
+ i.channel!.id === interaction.channel!.id &&
+ i.message.id === m.id
+ );
+ }
});
} catch (e) {
timedOut = true;
@@ -130,7 +139,7 @@
await i.deferUpdate();
ticketData.category = i.values[0] ?? null;
} else {
- switch(i.customId) {
+ switch (i.customId) {
case "save": {
await i.deferUpdate();
await client.database.guilds.write(interaction.guild.id, { tickets: ticketData });
@@ -161,7 +170,7 @@
.setStyle(TextInputStyle.Short)
)
)
- )
+ );
await i.editReply({
embeds: [
new EmojiEmbed()
@@ -189,7 +198,7 @@
if (!out || out.isButton()) continue;
out = out as ModalSubmitInteraction;
const toAdd = out.fields.getTextInputValue("maxTickets");
- if(isNaN(parseInt(toAdd))) {
+ if (isNaN(parseInt(toAdd))) {
errorMessage = "You entered an invalid number - No changes were made";
break;
}
@@ -204,11 +213,9 @@
}
}
}
- await interaction.deleteReply()
+ await interaction.deleteReply();
};
-
-
async function manageTypes(interaction: CommandInteraction, data: GuildConfig["tickets"], m: Message) {
let timedOut = false;
let backPressed = false;
@@ -278,7 +285,9 @@
new StringSelectMenuOptionBuilder({
label: capitalize(type),
value: type,
- emoji: client.emojis.cache.get(getEmojiByName(`TICKETS.${type.toUpperCase()}`, "id")) as APIMessageComponentEmoji,
+ emoji: client.emojis.cache.get(
+ getEmojiByName(`TICKETS.${type.toUpperCase()}`, "id")
+ ) as APIMessageComponentEmoji,
default: inUse.includes(type)
})
);
@@ -325,7 +334,13 @@
try {
i = await m.awaitMessageComponent({
time: 300000,
- filter: (i) => { return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.message.id === m.id }
+ filter: (i) => {
+ return (
+ i.user.id === interaction.user.id &&
+ i.channel!.id === interaction.channel!.id &&
+ i.message.id === m.id
+ );
+ }
});
} catch (e) {
timedOut = true;
@@ -394,7 +409,7 @@
}
toAdd = toAdd.substring(0, 80);
try {
- if(!data.customTypes) data.customTypes = [];
+ if (!data.customTypes) data.customTypes = [];
data.customTypes.push(toAdd);
} catch {
continue;
diff --git a/src/commands/settings/tracks.ts b/src/commands/settings/tracks.ts
index 39efede..20972f4 100644
--- a/src/commands/settings/tracks.ts
+++ b/src/commands/settings/tracks.ts
@@ -1,4 +1,26 @@
-import { ActionRowBuilder, APIMessageComponentEmoji, ButtonBuilder, ButtonInteraction, ButtonStyle, Collection, CommandInteraction, GuildMember, Message, ModalBuilder, ModalSubmitInteraction, PermissionsBitField, Role, RoleSelectMenuBuilder, RoleSelectMenuInteraction, SlashCommandSubcommandBuilder, StringSelectMenuBuilder, StringSelectMenuInteraction, StringSelectMenuOptionBuilder, TextInputBuilder, TextInputStyle } from "discord.js";
+import {
+ ActionRowBuilder,
+ APIMessageComponentEmoji,
+ ButtonBuilder,
+ ButtonInteraction,
+ ButtonStyle,
+ Collection,
+ CommandInteraction,
+ GuildMember,
+ Message,
+ ModalBuilder,
+ ModalSubmitInteraction,
+ PermissionsBitField,
+ Role,
+ RoleSelectMenuBuilder,
+ RoleSelectMenuInteraction,
+ SlashCommandSubcommandBuilder,
+ StringSelectMenuBuilder,
+ StringSelectMenuInteraction,
+ StringSelectMenuOptionBuilder,
+ TextInputBuilder,
+ TextInputStyle
+} from "discord.js";
import client from "../../utils/client.js";
import createPageIndicator, { createVerticalTrack } from "../../utils/createPageIndicator.js";
import { LoadingEmbed } from "../../utils/defaults.js";
@@ -7,12 +29,10 @@
import ellipsis from "../../utils/ellipsis.js";
import { modalInteractionCollector } from "../../utils/dualCollector.js";
-const { renderRole } = client.logger
+const { renderRole } = client.logger;
const command = (builder: SlashCommandSubcommandBuilder) =>
- builder
- .setName("tracks")
- .setDescription("Manage the tracks for the server")
+ builder.setName("tracks").setDescription("Manage the tracks for the server");
interface ObjectSchema {
name: string;
@@ -22,35 +42,36 @@
manageableBy: string[];
}
-
-const editName = async (i: ButtonInteraction, interaction: StringSelectMenuInteraction | ButtonInteraction, m: Message, current?: string) => {
-
+const editName = async (
+ i: ButtonInteraction,
+ interaction: StringSelectMenuInteraction | ButtonInteraction,
+ m: Message,
+ current?: string
+) => {
let name = current ?? "";
const modal = new ModalBuilder()
.setTitle("Edit Name and Description")
.setCustomId("editNameDescription")
.addComponents(
- new ActionRowBuilder<TextInputBuilder>()
- .addComponents(
- new TextInputBuilder()
- .setLabel("Name")
- .setCustomId("name")
- .setPlaceholder("The name of the track (e.g. Moderators)")
- .setStyle(TextInputStyle.Short)
- .setValue(name)
- .setRequired(true)
- )
- )
- const button = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setLabel("Back")
- .setStyle(ButtonStyle.Secondary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
- )
+ new ActionRowBuilder<TextInputBuilder>().addComponents(
+ new TextInputBuilder()
+ .setLabel("Name")
+ .setCustomId("name")
+ .setPlaceholder("The name of the track (e.g. Moderators)")
+ .setStyle(TextInputStyle.Short)
+ .setValue(name)
+ .setRequired(true)
+ )
+ );
+ const button = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setLabel("Back")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
+ );
- await i.showModal(modal)
+ await i.showModal(modal);
await interaction.editReply({
embeds: [
new EmojiEmbed()
@@ -63,41 +84,42 @@
let out: ModalSubmitInteraction | null;
try {
- out = await modalInteractionCollector(m, interaction.user) as ModalSubmitInteraction | null;
+ out = (await modalInteractionCollector(m, interaction.user)) as ModalSubmitInteraction | null;
} catch (e) {
console.error(e);
out = null;
}
- if(!out) return name;
+ if (!out) return name;
if (out.isButton()) return name;
name = out.fields.fields.find((f) => f.customId === "name")?.value ?? name;
- return name
+ return name;
+};
-}
-
-const reorderTracks = async (interaction: ButtonInteraction, m: Message, roles: Collection<string, Role>, currentObj: string[]) => {
- const reorderRow = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("reorder")
- .setPlaceholder("Select all roles in the order you want users to gain them (Lowest to highest rank).")
- .setMinValues(currentObj.length)
- .setMaxValues(currentObj.length)
- .addOptions(
- currentObj.map((o, i) => new StringSelectMenuOptionBuilder()
- .setLabel(roles.get(o)!.name)
- .setValue(i.toString())
- )
+const reorderTracks = async (
+ interaction: ButtonInteraction,
+ m: Message,
+ roles: Collection<string, Role>,
+ currentObj: string[]
+) => {
+ const reorderRow = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setCustomId("reorder")
+ .setPlaceholder("Select all roles in the order you want users to gain them (Lowest to highest rank).")
+ .setMinValues(currentObj.length)
+ .setMaxValues(currentObj.length)
+ .addOptions(
+ currentObj.map((o, i) =>
+ new StringSelectMenuOptionBuilder().setLabel(roles.get(o)!.name).setValue(i.toString())
)
- );
- const buttonRow = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setLabel("Back")
- .setStyle(ButtonStyle.Secondary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
- )
+ )
+ );
+ const buttonRow = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setLabel("Back")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
+ );
await interaction.editReply({
embeds: [
new EmojiEmbed()
@@ -109,134 +131,154 @@
});
let out: StringSelectMenuInteraction | ButtonInteraction | null;
try {
- out = await m.awaitMessageComponent({
+ out = (await m.awaitMessageComponent({
filter: (i) => i.channel!.id === interaction.channel!.id,
time: 300000
- }) as StringSelectMenuInteraction | ButtonInteraction | null;
+ })) as StringSelectMenuInteraction | ButtonInteraction | null;
} catch (e) {
console.error(e);
out = null;
}
- if(!out) return;
+ if (!out) return;
out.deferUpdate();
if (out.isButton()) return;
const values = out.values;
const newOrder: string[] = currentObj.map((_, i) => {
- const index = values.findIndex(v => v === i.toString());
+ const index = values.findIndex((v) => v === i.toString());
return currentObj[index];
}) as string[];
return newOrder;
-}
+};
-const editTrack = async (interaction: ButtonInteraction | StringSelectMenuInteraction, message: Message, roles: Collection<string, Role>, current?: ObjectSchema) => {
+const editTrack = async (
+ interaction: ButtonInteraction | StringSelectMenuInteraction,
+ message: Message,
+ roles: Collection<string, Role>,
+ current?: ObjectSchema
+) => {
const isAdmin = (interaction.member!.permissions as PermissionsBitField).has("Administrator");
- if(!current) {
+ if (!current) {
current = {
name: "",
retainPrevious: false,
nullable: false,
track: [],
manageableBy: []
- }
+ };
}
- const roleSelect = new ActionRowBuilder<RoleSelectMenuBuilder>()
- .addComponents(
- new RoleSelectMenuBuilder()
- .setCustomId("addRole")
- .setPlaceholder("Select a role to add")
- .setDisabled(!isAdmin)
- );
+ const roleSelect = new ActionRowBuilder<RoleSelectMenuBuilder>().addComponents(
+ new RoleSelectMenuBuilder().setCustomId("addRole").setPlaceholder("Select a role to add").setDisabled(!isAdmin)
+ );
let closed = false;
do {
- const editableRoles: string[] = current.track.map((r) => {
- if(!(roles.get(r)!.position >= (interaction.member as GuildMember).roles.highest.position) || interaction.user.id === interaction.guild?.ownerId) return roles.get(r)!.name;
- }).filter(v => v !== undefined) as string[];
- const selectMenu = new ActionRowBuilder<StringSelectMenuBuilder>()
- .addComponents(
- new StringSelectMenuBuilder()
- .setCustomId("removeRole")
- .setPlaceholder("Select a role to remove")
- .setDisabled(!isAdmin)
- .addOptions(
- editableRoles.map((r, i) => {
- return new StringSelectMenuOptionBuilder()
- .setLabel(r)
- .setValue(i.toString())}
- )
- )
- );
- const buttons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setLabel("Back")
- .setStyle(ButtonStyle.Secondary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("edit")
- .setLabel("Edit Name")
- .setStyle(ButtonStyle.Primary)
- .setEmoji(getEmojiByName("ICONS.EDIT", "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("reorder")
- .setLabel("Reorder")
- .setDisabled(!isAdmin)
- .setStyle(ButtonStyle.Primary)
- .setEmoji(getEmojiByName("ICONS.REORDER", "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("retainPrevious")
- .setLabel("Retain Previous")
- .setStyle(current.retainPrevious ? ButtonStyle.Success : ButtonStyle.Danger)
- .setEmoji(getEmojiByName("CONTROL." + (current.retainPrevious ? "TICK" : "CROSS"), "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("nullable")
- .setLabel(`Role ${current.nullable ? "Not " : ""}Required`)
- .setStyle(current.nullable ? ButtonStyle.Success : ButtonStyle.Danger)
- .setEmoji(getEmojiByName("CONTROL." + (current.nullable ? "TICK" : "CROSS"), "id") as APIMessageComponentEmoji)
+ const editableRoles: string[] = current.track
+ .map((r) => {
+ if (
+ !(roles.get(r)!.position >= (interaction.member as GuildMember).roles.highest.position) ||
+ interaction.user.id === interaction.guild?.ownerId
+ )
+ return roles.get(r)!.name;
+ })
+ .filter((v) => v !== undefined) as string[];
+ const selectMenu = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
+ new StringSelectMenuBuilder()
+ .setCustomId("removeRole")
+ .setPlaceholder("Select a role to remove")
+ .setDisabled(!isAdmin)
+ .addOptions(
+ editableRoles.map((r, i) => {
+ return new StringSelectMenuOptionBuilder().setLabel(r).setValue(i.toString());
+ })
+ )
+ );
+ const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setLabel("Back")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji),
+ new ButtonBuilder()
+ .setCustomId("edit")
+ .setLabel("Edit Name")
+ .setStyle(ButtonStyle.Primary)
+ .setEmoji(getEmojiByName("ICONS.EDIT", "id") as APIMessageComponentEmoji),
+ new ButtonBuilder()
+ .setCustomId("reorder")
+ .setLabel("Reorder")
+ .setDisabled(!isAdmin)
+ .setStyle(ButtonStyle.Primary)
+ .setEmoji(getEmojiByName("ICONS.REORDER", "id") as APIMessageComponentEmoji),
+ new ButtonBuilder()
+ .setCustomId("retainPrevious")
+ .setLabel("Retain Previous")
+ .setStyle(current.retainPrevious ? ButtonStyle.Success : ButtonStyle.Danger)
+ .setEmoji(
+ getEmojiByName(
+ "CONTROL." + (current.retainPrevious ? "TICK" : "CROSS"),
+ "id"
+ ) as APIMessageComponentEmoji
+ ),
+ new ButtonBuilder()
+ .setCustomId("nullable")
+ .setLabel(`Role ${current.nullable ? "Not " : ""}Required`)
+ .setStyle(current.nullable ? ButtonStyle.Success : ButtonStyle.Danger)
+ .setEmoji(
+ getEmojiByName("CONTROL." + (current.nullable ? "TICK" : "CROSS"), "id") as APIMessageComponentEmoji
+ )
);
const allowed: boolean[] = [];
for (const role of current.track) {
const disabled: boolean =
roles.get(role)!.position >= (interaction.member as GuildMember).roles.highest.position;
- allowed.push(disabled)
+ allowed.push(disabled);
}
- const mapped = current.track.map(role => roles.find(aRole => aRole.id === role)!);
+ const mapped = current.track.map((role) => roles.find((aRole) => aRole.id === role)!);
const embed = new EmojiEmbed()
.setTitle("Tracks")
.setDescription(
`**Currently Editing:** ${current.name}\n\n` +
- `${getEmojiByName("CONTROL." + (current.nullable ? "CROSS" : "TICK"))} Members ${current.nullable ? "don't " : ""}need a role in this track\n` +
- `${getEmojiByName("CONTROL." + (current.retainPrevious ? "TICK" : "CROSS"))} Members ${current.retainPrevious ? "" : "don't "}keep all roles below their current highest\n\n` +
- createVerticalTrack(
- mapped.map(role => renderRole(role)), new Array(current.track.length).fill(false), allowed)
+ `${getEmojiByName("CONTROL." + (current.nullable ? "CROSS" : "TICK"))} Members ${
+ current.nullable ? "don't " : ""
+ }need a role in this track\n` +
+ `${getEmojiByName("CONTROL." + (current.retainPrevious ? "TICK" : "CROSS"))} Members ${
+ current.retainPrevious ? "" : "don't "
+ }keep all roles below their current highest\n\n` +
+ createVerticalTrack(
+ mapped.map((role) => renderRole(role)),
+ new Array(current.track.length).fill(false),
+ allowed
+ )
)
- .setStatus("Success")
+ .setStatus("Success");
- const comps: ActionRowBuilder<RoleSelectMenuBuilder | ButtonBuilder | StringSelectMenuBuilder>[] = [roleSelect, buttons];
- if(current.track.length >= 1) comps.splice(1, 0, selectMenu);
+ const comps: ActionRowBuilder<RoleSelectMenuBuilder | ButtonBuilder | StringSelectMenuBuilder>[] = [
+ roleSelect,
+ buttons
+ ];
+ if (current.track.length >= 1) comps.splice(1, 0, selectMenu);
- interaction.editReply({embeds: [embed], components: comps});
+ interaction.editReply({ embeds: [embed], components: comps });
let out: ButtonInteraction | RoleSelectMenuInteraction | StringSelectMenuInteraction | null;
try {
- out = await message.awaitMessageComponent({
+ out = (await message.awaitMessageComponent({
filter: (i) => i.channel!.id === interaction.channel!.id,
time: 300000
- }) as ButtonInteraction | RoleSelectMenuInteraction | StringSelectMenuInteraction | null;
+ })) as ButtonInteraction | RoleSelectMenuInteraction | StringSelectMenuInteraction | null;
} catch (e) {
console.error(e);
out = null;
}
- if(!out) return;
+ if (!out) return;
if (out.isButton()) {
- switch(out.customId) {
+ switch (out.customId) {
case "back": {
out.deferUpdate();
closed = true;
@@ -264,34 +306,34 @@
}
} else if (out.isStringSelectMenu()) {
out.deferUpdate();
- switch(out.customId) {
+ switch (out.customId) {
case "removeRole": {
- const index = current.track.findIndex(v => v === editableRoles[parseInt((out! as StringSelectMenuInteraction).values![0]!)]);
+ const index = current.track.findIndex(
+ (v) => v === editableRoles[parseInt((out! as StringSelectMenuInteraction).values![0]!)]
+ );
current.track.splice(index, 1);
break;
}
}
} else {
- switch(out.customId) {
+ switch (out.customId) {
case "addRole": {
const role = out.values![0]!;
- if(!current.track.includes(role)) {
+ if (!current.track.includes(role)) {
current.track.push(role);
} else {
- out.reply({content: "That role is already on this track", ephemeral: true})
+ out.reply({ content: "That role is already on this track", ephemeral: true });
}
break;
}
}
}
-
- } while(!closed);
+ } while (!closed);
return current;
-}
+};
const callback = async (interaction: CommandInteraction) => {
-
- const m = await interaction.reply({embeds: LoadingEmbed, fetchReply: true, ephemeral: true})
+ const m = await interaction.reply({ embeds: LoadingEmbed, fetchReply: true, ephemeral: true });
const config = await client.database.guilds.read(interaction.guild!.id);
const tracks: ObjectSchema[] = config.tracks;
const roles = await interaction.guild!.roles.fetch();
@@ -301,16 +343,11 @@
let modified = false;
do {
- const embed = new EmojiEmbed()
- .setTitle("Track Settings")
- .setEmoji("TRACKS.ICON")
- .setStatus("Success");
+ const embed = new EmojiEmbed().setTitle("Track Settings").setEmoji("TRACKS.ICON").setStatus("Success");
const noTracks = config.tracks.length === 0;
let current: ObjectSchema;
- const pageSelect = new StringSelectMenuBuilder()
- .setCustomId("page")
- .setPlaceholder("Select a track to manage");
+ const pageSelect = new StringSelectMenuBuilder().setCustomId("page").setPlaceholder("Select a track to manage");
const actionSelect = new StringSelectMenuBuilder()
.setCustomId("action")
.setPlaceholder("Perform an action")
@@ -325,51 +362,56 @@
.setDescription("Delete this track")
.setValue("delete")
.setEmoji(getEmojiByName("TICKETS.ISSUE", "id") as APIMessageComponentEmoji)
- );
- const buttonRow = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setStyle(ButtonStyle.Primary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
- .setDisabled(page === 0),
- new ButtonBuilder()
- .setCustomId("next")
- .setEmoji(getEmojiByName("CONTROL.RIGHT", "id") as APIMessageComponentEmoji)
- .setStyle(ButtonStyle.Primary)
- .setDisabled(page === tracks.length - 1),
- new ButtonBuilder()
- .setCustomId("add")
- .setLabel("New Track")
- .setEmoji(getEmojiByName("TICKETS.SUGGESTION", "id") as APIMessageComponentEmoji)
- .setStyle(ButtonStyle.Secondary)
- .setDisabled(Object.keys(tracks).length >= 24),
- new ButtonBuilder()
- .setCustomId("save")
- .setLabel("Save")
- .setEmoji(getEmojiByName("ICONS.SAVE", "id") as APIMessageComponentEmoji)
- .setStyle(ButtonStyle.Success)
- .setDisabled(!modified),
);
- if(noTracks) {
- embed.setDescription("No tracks have been set up yet. Use the button below to add one.\n\n" +
- createPageIndicator(1, 1, undefined, true)
+ const buttonRow = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setStyle(ButtonStyle.Primary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
+ .setDisabled(page === 0),
+ new ButtonBuilder()
+ .setCustomId("next")
+ .setEmoji(getEmojiByName("CONTROL.RIGHT", "id") as APIMessageComponentEmoji)
+ .setStyle(ButtonStyle.Primary)
+ .setDisabled(page === tracks.length - 1),
+ new ButtonBuilder()
+ .setCustomId("add")
+ .setLabel("New Track")
+ .setEmoji(getEmojiByName("TICKETS.SUGGESTION", "id") as APIMessageComponentEmoji)
+ .setStyle(ButtonStyle.Secondary)
+ .setDisabled(Object.keys(tracks).length >= 24),
+ new ButtonBuilder()
+ .setCustomId("save")
+ .setLabel("Save")
+ .setEmoji(getEmojiByName("ICONS.SAVE", "id") as APIMessageComponentEmoji)
+ .setStyle(ButtonStyle.Success)
+ .setDisabled(!modified)
+ );
+ if (noTracks) {
+ embed.setDescription(
+ "No tracks have been set up yet. Use the button below to add one.\n\n" +
+ createPageIndicator(1, 1, undefined, true)
);
pageSelect.setDisabled(true);
actionSelect.setDisabled(true);
- pageSelect.addOptions(new StringSelectMenuOptionBuilder()
- .setLabel("No tracks")
- .setValue("none")
- );
+ pageSelect.addOptions(new StringSelectMenuOptionBuilder().setLabel("No tracks").setValue("none"));
} else {
page = Math.min(page, Object.keys(tracks).length - 1);
current = tracks[page]!;
- const mapped = current.track.map(role => roles.find(aRole => aRole.id === role)!);
- embed.setDescription(`**Currently Editing:** ${current.name}\n\n` +
- `${getEmojiByName("CONTROL." + (current.nullable ? "CROSS" : "TICK"))} Members ${current.nullable ? "don't " : ""}need a role in this track\n` +
- `${getEmojiByName("CONTROL." + (current.retainPrevious ? "TICK" : "CROSS"))} Members ${current.retainPrevious ? "" : "don't "}keep all roles below their current highest\n\n` +
- createVerticalTrack(mapped.map(role => renderRole(role)), new Array(current.track.length).fill(false)) +
- `\n${createPageIndicator(config.tracks.length, page)}`
+ const mapped = current.track.map((role) => roles.find((aRole) => aRole.id === role)!);
+ embed.setDescription(
+ `**Currently Editing:** ${current.name}\n\n` +
+ `${getEmojiByName("CONTROL." + (current.nullable ? "CROSS" : "TICK"))} Members ${
+ current.nullable ? "don't " : ""
+ }need a role in this track\n` +
+ `${getEmojiByName("CONTROL." + (current.retainPrevious ? "TICK" : "CROSS"))} Members ${
+ current.retainPrevious ? "" : "don't "
+ }keep all roles below their current highest\n\n` +
+ createVerticalTrack(
+ mapped.map((role) => renderRole(role)),
+ new Array(current.track.length).fill(false)
+ ) +
+ `\n${createPageIndicator(config.tracks.length, page)}`
);
pageSelect.addOptions(
@@ -380,13 +422,23 @@
.setValue(index.toString());
})
);
-
}
- await interaction.editReply({embeds: [embed], components: [new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(actionSelect), new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(pageSelect), buttonRow]});
+ await interaction.editReply({
+ embeds: [embed],
+ components: [
+ new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(actionSelect),
+ new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(pageSelect),
+ buttonRow
+ ]
+ });
let i: StringSelectMenuInteraction | ButtonInteraction;
try {
- i = await m.awaitMessageComponent({ time: 300000, filter: (i) => i.user.id === interaction.user.id && i.message.id === m.id && i.channelId === interaction.channelId}) as ButtonInteraction | StringSelectMenuInteraction;
+ i = (await m.awaitMessageComponent({
+ time: 300000,
+ filter: (i) =>
+ i.user.id === interaction.user.id && i.message.id === m.id && i.channelId === interaction.channelId
+ })) as ButtonInteraction | StringSelectMenuInteraction;
} catch (e) {
closed = true;
continue;
@@ -404,14 +456,14 @@
break;
}
case "add": {
- const newPage = await editTrack(i, m, roles)
- if(!newPage) break;
+ const newPage = await editTrack(i, m, roles);
+ if (!newPage) break;
tracks.push();
page = tracks.length - 1;
break;
}
case "save": {
- client.database.guilds.write(interaction.guild!.id, {tracks: tracks});
+ client.database.guilds.write(interaction.guild!.id, { tracks: tracks });
modified = false;
await client.memory.forceUpdate(interaction.guild!.id);
break;
@@ -420,16 +472,16 @@
} else if (i.isStringSelectMenu()) {
switch (i.customId) {
case "action": {
- switch(i.values[0]) {
+ switch (i.values[0]) {
case "edit": {
const edited = await editTrack(i, m, roles, current!);
- if(!edited) break;
+ if (!edited) break;
tracks[page] = edited;
modified = true;
break;
}
case "delete": {
- if(page === 0 && tracks.keys.length - 1 > 0) page++;
+ if (page === 0 && tracks.keys.length - 1 > 0) page++;
else page--;
tracks.splice(page, 1);
break;
@@ -443,10 +495,9 @@
}
}
}
-
} while (!closed);
- await interaction.deleteReply()
-}
+ await interaction.deleteReply();
+};
const check = (interaction: CommandInteraction, _partial: boolean = false) => {
const member = interaction.member as GuildMember;
diff --git a/src/commands/settings/verify.ts b/src/commands/settings/verify.ts
index 9c091a1..e2318fc 100644
--- a/src/commands/settings/verify.ts
+++ b/src/commands/settings/verify.ts
@@ -16,10 +16,7 @@
import lodash from "lodash";
const command = (builder: SlashCommandSubcommandBuilder) =>
- builder
- .setName("verify")
- .setDescription("Manage the role given after a user runs /verify")
-
+ builder.setName("verify").setDescription("Manage the role given after a user runs /verify");
const callback = async (interaction: CommandInteraction): Promise<unknown> => {
if (!interaction.guild) return;
@@ -33,33 +30,31 @@
let config = await client.database.guilds.read(interaction.guild.id);
let data = Object.assign({}, config.verify);
do {
- const selectMenu = new ActionRowBuilder<RoleSelectMenuBuilder>()
- .addComponents(
- new RoleSelectMenuBuilder()
- .setCustomId("role")
- .setPlaceholder("Select a role")
+ const selectMenu = new ActionRowBuilder<RoleSelectMenuBuilder>().addComponents(
+ new RoleSelectMenuBuilder().setCustomId("role").setPlaceholder("Select a role")
);
- const buttons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("switch")
- .setLabel(data.enabled ? "Enabled" : "Disabled")
- .setStyle(data.enabled ? ButtonStyle.Success : ButtonStyle.Danger)
- .setEmoji(getEmojiByName(data.enabled ? "CONTROL.TICK" : "CONTROL.CROSS", "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("save")
- .setLabel("Save")
- .setStyle(ButtonStyle.Success)
- .setEmoji(getEmojiByName("ICONS.SAVE", "id") as APIMessageComponentEmoji)
- .setDisabled(lodash.isEqual(config.verify, data))
- );
+ const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("switch")
+ .setLabel(data.enabled ? "Enabled" : "Disabled")
+ .setStyle(data.enabled ? ButtonStyle.Success : ButtonStyle.Danger)
+ .setEmoji(
+ getEmojiByName(data.enabled ? "CONTROL.TICK" : "CONTROL.CROSS", "id") as APIMessageComponentEmoji
+ ),
+ new ButtonBuilder()
+ .setCustomId("save")
+ .setLabel("Save")
+ .setStyle(ButtonStyle.Success)
+ .setEmoji(getEmojiByName("ICONS.SAVE", "id") as APIMessageComponentEmoji)
+ .setDisabled(lodash.isEqual(config.verify, data))
+ );
const embed = new EmojiEmbed()
.setTitle("Verify Role")
.setDescription(
`Select a role to be given to users after they run ${getCommandMentionByName("verify")}` +
- `\n\nCurrent role: ${config.verify.role ? `<@&${config.verify.role}>` : "None"}`
+ `\n\nCurrent role: ${config.verify.role ? `<@&${config.verify.role}>` : "None"}`
)
.setStatus("Success")
.setEmoji("CHANNEL.TEXT.CREATE");
@@ -73,7 +68,9 @@
try {
i = await m.awaitMessageComponent({
time: 300000,
- filter: (i) => { return i.user.id === interaction.user.id }
+ filter: (i) => {
+ return i.user.id === interaction.user.id;
+ }
});
} catch (e) {
closed = true;
@@ -82,26 +79,25 @@
await i.deferUpdate();
- if(i.isButton()) {
+ if (i.isButton()) {
switch (i.customId) {
case "save": {
- client.database.guilds.write(interaction.guild.id, {"verify": data} )
+ client.database.guilds.write(interaction.guild.id, { verify: data });
config = await client.database.guilds.read(interaction.guild.id);
data = Object.assign({}, config.verify);
await client.memory.forceUpdate(interaction.guild.id);
- break
+ break;
}
case "switch": {
data.enabled = !data.enabled;
- break
+ break;
}
}
} else {
data.role = i.values[0]!;
}
-
} while (!closed);
- await interaction.deleteReply()
+ await interaction.deleteReply();
};
const check = (interaction: CommandInteraction, _partial: boolean = false) => {
diff --git a/src/commands/settings/welcome.ts b/src/commands/settings/welcome.ts
index b2d484c..bf52dd1 100644
--- a/src/commands/settings/welcome.ts
+++ b/src/commands/settings/welcome.ts
@@ -14,7 +14,7 @@
ModalBuilder,
TextInputBuilder,
TextInputStyle,
- ModalSubmitInteraction,
+ ModalSubmitInteraction
} from "discord.js";
import type { SlashCommandSubcommandBuilder } from "discord.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
@@ -24,9 +24,7 @@
import { modalInteractionCollector } from "../../utils/dualCollector.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
- builder
- .setName("welcome")
- .setDescription("Messages and roles sent or given when someone joins the server")
+ builder.setName("welcome").setDescription("Messages and roles sent or given when someone joins the server");
const callback = async (interaction: CommandInteraction): Promise<void> => {
const { renderChannel } = client.logger;
@@ -39,80 +37,87 @@
let config = await client.database.guilds.read(interaction.guild!.id);
let data = Object.assign({}, config.welcome);
do {
- const buttons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("switch")
- .setLabel(data.enabled ? "Enabled" : "Disabled")
- .setStyle(data.enabled ? ButtonStyle.Success : ButtonStyle.Danger)
- .setEmoji(getEmojiByName(data.enabled ? "CONTROL.TICK" : "CONTROL.CROSS", "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("message")
- .setLabel((data.message ? "Change" : "Set") + "Message")
- .setStyle(ButtonStyle.Primary)
- .setEmoji(getEmojiByName("ICONS.EDIT", "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("channelDM")
- .setLabel("Send in DMs")
- .setStyle(ButtonStyle.Primary)
- .setDisabled(data.channel === "dm"),
- new ButtonBuilder()
- .setCustomId("role")
- .setLabel("Clear Role")
- .setStyle(ButtonStyle.Danger)
- .setEmoji(getEmojiByName("CONTROL.CROSS", "id") as APIMessageComponentEmoji),
- new ButtonBuilder()
- .setCustomId("save")
- .setLabel("Save")
- .setStyle(ButtonStyle.Success)
- .setEmoji(getEmojiByName("ICONS.SAVE", "id") as APIMessageComponentEmoji)
- .setDisabled(
- data.enabled === config.welcome.enabled &&
+ const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("switch")
+ .setLabel(data.enabled ? "Enabled" : "Disabled")
+ .setStyle(data.enabled ? ButtonStyle.Success : ButtonStyle.Danger)
+ .setEmoji(
+ getEmojiByName(data.enabled ? "CONTROL.TICK" : "CONTROL.CROSS", "id") as APIMessageComponentEmoji
+ ),
+ new ButtonBuilder()
+ .setCustomId("message")
+ .setLabel((data.message ? "Change" : "Set") + "Message")
+ .setStyle(ButtonStyle.Primary)
+ .setEmoji(getEmojiByName("ICONS.EDIT", "id") as APIMessageComponentEmoji),
+ new ButtonBuilder()
+ .setCustomId("channelDM")
+ .setLabel("Send in DMs")
+ .setStyle(ButtonStyle.Primary)
+ .setDisabled(data.channel === "dm"),
+ new ButtonBuilder()
+ .setCustomId("role")
+ .setLabel("Clear Role")
+ .setStyle(ButtonStyle.Danger)
+ .setEmoji(getEmojiByName("CONTROL.CROSS", "id") as APIMessageComponentEmoji),
+ new ButtonBuilder()
+ .setCustomId("save")
+ .setLabel("Save")
+ .setStyle(ButtonStyle.Success)
+ .setEmoji(getEmojiByName("ICONS.SAVE", "id") as APIMessageComponentEmoji)
+ .setDisabled(
+ data.enabled === config.welcome.enabled &&
data.message === config.welcome.message &&
data.role === config.welcome.role &&
data.ping === config.welcome.ping &&
data.channel === config.welcome.channel
- )
- );
+ )
+ );
- const channelMenu = new ActionRowBuilder<ChannelSelectMenuBuilder>()
- .addComponents(
- new ChannelSelectMenuBuilder()
- .setCustomId("channel")
- .setPlaceholder("Select a channel to send welcome messages to")
- );
- const roleMenu = new ActionRowBuilder<RoleSelectMenuBuilder>()
- .addComponents(
- new RoleSelectMenuBuilder()
- .setCustomId("roleToGive")
- .setPlaceholder("Select a role to give to the member when they join the server")
- );
- const pingMenu = new ActionRowBuilder<RoleSelectMenuBuilder>()
- .addComponents(
- new RoleSelectMenuBuilder()
- .setCustomId("roleToPing")
- .setPlaceholder("Select a role to ping when a member joins the server")
- );
+ const channelMenu = new ActionRowBuilder<ChannelSelectMenuBuilder>().addComponents(
+ new ChannelSelectMenuBuilder()
+ .setCustomId("channel")
+ .setPlaceholder("Select a channel to send welcome messages to")
+ );
+ const roleMenu = new ActionRowBuilder<RoleSelectMenuBuilder>().addComponents(
+ new RoleSelectMenuBuilder()
+ .setCustomId("roleToGive")
+ .setPlaceholder("Select a role to give to the member when they join the server")
+ );
+ const pingMenu = new ActionRowBuilder<RoleSelectMenuBuilder>().addComponents(
+ new RoleSelectMenuBuilder()
+ .setCustomId("roleToPing")
+ .setPlaceholder("Select a role to ping when a member joins the server")
+ );
const embed = new EmojiEmbed()
.setTitle("Welcome Settings")
.setStatus("Success")
.setDescription(
- `${getEmojiByName(data.enabled ? "CONTROL.TICK" : "CONTROL.CROSS")} Welcome messages and roles are ${data.enabled ? "enabled" : "disabled"}\n` +
- `**Welcome message:** ${data.message ?
- `\n> ` +
- await convertCurlyBracketString(
- data.message,
- interaction.user.id,
- interaction.user.username,
- interaction.guild!.name,
- interaction.guild!.members
- )
- : "*None*"}\n` +
- `**Send message in:** ` + (data.channel ? (data.channel == "dm" ? "DMs" : renderChannel(data.channel)) : `*None set*`) + `\n` +
- `**Role to ping:** ` + (data.ping ? `<@&${data.ping}>` : `*None set*`) + `\n` +
- `**Role given on join:** ` + (data.role ? `<@&${data.role}>` : `*None set*`)
- )
+ `${getEmojiByName(data.enabled ? "CONTROL.TICK" : "CONTROL.CROSS")} Welcome messages and roles are ${
+ data.enabled ? "enabled" : "disabled"
+ }\n` +
+ `**Welcome message:** ${
+ data.message
+ ? `\n> ` +
+ (await convertCurlyBracketString(
+ data.message,
+ interaction.user.id,
+ interaction.user.username,
+ interaction.guild!.name,
+ interaction.guild!.members
+ ))
+ : "*None*"
+ }\n` +
+ `**Send message in:** ` +
+ (data.channel ? (data.channel == "dm" ? "DMs" : renderChannel(data.channel)) : `*None set*`) +
+ `\n` +
+ `**Role to ping:** ` +
+ (data.ping ? `<@&${data.ping}>` : `*None set*`) +
+ `\n` +
+ `**Role given on join:** ` +
+ (data.role ? `<@&${data.role}>` : `*None set*`)
+ );
await interaction.editReply({
embeds: [embed],
@@ -121,17 +126,17 @@
let i: RoleSelectMenuInteraction | ChannelSelectMenuInteraction | ButtonInteraction;
try {
- i = await m.awaitMessageComponent({
+ i = (await m.awaitMessageComponent({
filter: (interaction) => interaction.user.id === interaction.user.id,
time: 300000
- }) as RoleSelectMenuInteraction | ChannelSelectMenuInteraction | ButtonInteraction;
+ })) as RoleSelectMenuInteraction | ChannelSelectMenuInteraction | ButtonInteraction;
} catch (e) {
closed = true;
continue;
}
- if(i.isButton()) {
- switch(i.customId) {
+ if (i.isButton()) {
+ switch (i.customId) {
case "switch": {
await i.deferUpdate();
data.enabled = !data.enabled;
@@ -148,7 +153,7 @@
.setLabel("Server Info (1/3)")
.setPlaceholder(
`{serverName} - This server's name\n\n` +
- `These placeholders will be replaced with the server's name, etc..`
+ `These placeholders will be replaced with the server's name, etc..`
)
.setMaxLength(1)
.setRequired(false)
@@ -160,8 +165,8 @@
.setLabel("Member Counts (2/3) - {MemberCount:...}")
.setPlaceholder(
`{:all} - Total member count\n` +
- `{:humans} - Total non-bot users\n` +
- `{:bots} - Number of bots\n`
+ `{:humans} - Total non-bot users\n` +
+ `{:bots} - Number of bots\n`
)
.setMaxLength(1)
.setRequired(false)
@@ -171,32 +176,28 @@
new TextInputBuilder()
.setCustomId("ex3")
.setLabel("Member who joined (3/3) - {member:...}")
- .setPlaceholder(
- `{:name} - The members name\n`
- )
+ .setPlaceholder(`{:name} - The members name\n`)
.setMaxLength(1)
.setRequired(false)
.setStyle(TextInputStyle.Paragraph)
),
- new ActionRowBuilder<TextInputBuilder>()
- .addComponents(
- new TextInputBuilder()
- .setCustomId("message")
- .setPlaceholder("Enter a message to send when someone joins the server")
- .setValue(data.message ?? "")
- .setLabel("Message")
- .setStyle(TextInputStyle.Paragraph)
- )
- )
- const button = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("back")
- .setLabel("Back")
- .setStyle(ButtonStyle.Secondary)
- .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
- )
- await i.showModal(modal)
+ new ActionRowBuilder<TextInputBuilder>().addComponents(
+ new TextInputBuilder()
+ .setCustomId("message")
+ .setPlaceholder("Enter a message to send when someone joins the server")
+ .setValue(data.message ?? "")
+ .setLabel("Message")
+ .setStyle(TextInputStyle.Paragraph)
+ )
+ );
+ const button = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("back")
+ .setLabel("Back")
+ .setStyle(ButtonStyle.Secondary)
+ .setEmoji(getEmojiByName("CONTROL.LEFT", "id") as APIMessageComponentEmoji)
+ );
+ await i.showModal(modal);
await i.editReply({
embeds: [
new EmojiEmbed()
@@ -209,21 +210,21 @@
let out: ModalSubmitInteraction | null;
try {
- out = await modalInteractionCollector(m, interaction.user) as ModalSubmitInteraction | null;
+ out = (await modalInteractionCollector(m, interaction.user)) as ModalSubmitInteraction | null;
} catch (e) {
console.error(e);
out = null;
}
- if(!out) break;
+ if (!out) break;
data.message = out.fields.getTextInputValue("message");
break;
}
case "save": {
await i.deferUpdate();
- await client.database.guilds.write(interaction.guild!.id, {"welcome": data});
+ await client.database.guilds.write(interaction.guild!.id, { welcome: data });
config = await client.database.guilds.read(interaction.guild!.id);
data = Object.assign({}, config.welcome);
- await client.memory.forceUpdate(interaction.guild!.id)
+ await client.memory.forceUpdate(interaction.guild!.id);
break;
}
case "channelDM": {
@@ -239,23 +240,22 @@
}
} else if (i.isRoleSelectMenu()) {
await i.deferUpdate();
- switch(i.customId) {
+ switch (i.customId) {
case "roleToGive": {
data.role = i.values[0]!;
- break
+ break;
}
case "roleToPing": {
data.ping = i.values[0]!;
- break
+ break;
}
}
} else {
await i.deferUpdate();
data.channel = i.values[0]!;
}
-
} while (!closed);
- await interaction.deleteReply()
+ await interaction.deleteReply();
};
const check = (interaction: CommandInteraction, _partial: boolean = false) => {
@@ -266,16 +266,16 @@
};
const autocomplete = async (interaction: AutocompleteInteraction): Promise<string[]> => {
- const validReplacements = ["serverName", "memberCount:all", "memberCount:bots", "memberCount:humans"]
+ const validReplacements = ["serverName", "memberCount:all", "memberCount:bots", "memberCount:humans"];
if (!interaction.guild) return [];
const prompt = interaction.options.getString("message");
const autocompletions = [];
- if ( prompt === null ) {
+ if (prompt === null) {
for (const replacement of validReplacements) {
autocompletions.push(`{${replacement}}`);
- };
+ }
return autocompletions;
- };
+ }
const beforeLastOpenBracket = prompt.match(/(.*){[^{}]{0,15}$/);
const afterLastOpenBracket = prompt.match(/{[^{}]{0,15}$/);
if (beforeLastOpenBracket !== null) {
diff --git a/src/commands/tag.ts b/src/commands/tag.ts
index 6ffecca..428a1f3 100644
--- a/src/commands/tag.ts
+++ b/src/commands/tag.ts
@@ -1,4 +1,11 @@
-import { AutocompleteInteraction, CommandInteraction, ActionRowBuilder, ButtonBuilder, ButtonStyle, SlashCommandBuilder } from "discord.js";
+import {
+ AutocompleteInteraction,
+ CommandInteraction,
+ ActionRowBuilder,
+ ButtonBuilder,
+ ButtonStyle,
+ SlashCommandBuilder
+} from "discord.js";
import client from "../utils/client.js";
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
import { capitalize } from "../utils/generateKeyValueList.js";
@@ -32,14 +39,13 @@
if (tag.match(/^(http|https):\/\/[^ "]+$/)) {
url = tag;
components = [
- new ActionRowBuilder<ButtonBuilder>().addComponents([new ButtonBuilder().setLabel("Open").setURL(url).setStyle(ButtonStyle.Link)])
+ new ActionRowBuilder<ButtonBuilder>().addComponents([
+ new ButtonBuilder().setLabel("Open").setURL(url).setStyle(ButtonStyle.Link)
+ ])
];
}
- const em = new EmojiEmbed()
- .setTitle(capitalize(search))
- .setEmoji("PUNISH.NICKNAME.GREEN")
- .setStatus("Success")
- if (url) em.setImage(url)
+ const em = new EmojiEmbed().setTitle(capitalize(search)).setEmoji("PUNISH.NICKNAME.GREEN").setStatus("Success");
+ if (url) em.setImage(url);
else em.setDescription(tag);
await interaction.reply({
diff --git a/src/commands/tags/edit.ts b/src/commands/tags/edit.ts
index 7e297c8..04c68b5 100644
--- a/src/commands/tags/edit.ts
+++ b/src/commands/tags/edit.ts
@@ -100,7 +100,11 @@
toUnset.push(`tags.${name}`);
toSet[`tags.${newname}`] = data.tags[name]!;
}
- await client.database.guilds.write(interaction.guild.id, Object.keys(toSet).length === 0 ? null : toSet, toUnset);
+ await client.database.guilds.write(
+ interaction.guild.id,
+ Object.keys(toSet).length === 0 ? null : toSet,
+ toUnset
+ );
await client.memory.forceUpdate(interaction.guild!.id);
} catch (e) {
return await interaction.editReply({
diff --git a/src/commands/tags/list.ts b/src/commands/tags/list.ts
index dbb1200..ef365f9 100644
--- a/src/commands/tags/list.ts
+++ b/src/commands/tags/list.ts
@@ -15,8 +15,11 @@
import client from "../../utils/client.js";
import getEmojiByName from "../../utils/getEmojiByName.js";
import createPageIndicator from "../../utils/createPageIndicator.js";
-interface MessageSelectOptionData { label: string; value: string; description?: string; }
-
+interface MessageSelectOptionData {
+ label: string;
+ value: string;
+ description?: string;
+}
class Embed {
embed: Discord.EmbedBuilder = new EmbedBuilder();
@@ -139,7 +142,13 @@
try {
i = await m.awaitMessageComponent({
time: 300000,
- filter: (i) => { return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.message.id === m.id }
+ filter: (i) => {
+ return (
+ i.user.id === interaction.user.id &&
+ i.channel!.id === interaction.channel!.id &&
+ i.message.id === m.id
+ );
+ }
});
} catch (e) {
timedOut = true;
@@ -163,7 +172,9 @@
}
const em = new Discord.EmbedBuilder(pages[page]!.embed.data);
if (timedOut) {
- em.setDescription(em.data.description + "\n\n" + createPageIndicator(pages.length, page) + " | Message timed out");
+ em.setDescription(
+ em.data.description + "\n\n" + createPageIndicator(pages.length, page) + " | Message timed out"
+ );
} else {
em.setDescription(em.data.description + "\n\n" + createPageIndicator(pages.length, page) + " | Message closed");
}
@@ -173,6 +184,5 @@
});
};
-
export { command };
export { callback };
diff --git a/src/commands/ticket/create.ts b/src/commands/ticket/create.ts
index 2f3ddc6..b9a0dc6 100644
--- a/src/commands/ticket/create.ts
+++ b/src/commands/ticket/create.ts
@@ -14,6 +14,5 @@
await create(interaction);
};
-
export { command };
export { callback };
diff --git a/src/commands/user/about.ts b/src/commands/user/about.ts
index 0eb8580..7e2902e 100644
--- a/src/commands/user/about.ts
+++ b/src/commands/user/about.ts
@@ -29,11 +29,15 @@
const guild = interaction.guild!;
const member = (interaction.options.getMember("user") ?? interaction.member) as Discord.GuildMember;
await userAbout(guild, member, interaction);
-}
+};
-async function userAbout(guild: Discord.Guild, member: Discord.GuildMember, interaction: Discord.CommandInteraction | Discord.ContextMenuCommandInteraction) {
- await member.user.fetch()
- await member.fetch()
+async function userAbout(
+ guild: Discord.Guild,
+ member: Discord.GuildMember,
+ interaction: Discord.CommandInteraction | Discord.ContextMenuCommandInteraction
+) {
+ await member.user.fetch();
+ await member.fetch();
await interaction.reply({
embeds: LoadingEmbed,
fetchReply: true,
@@ -59,10 +63,18 @@
) {
flags.push("CLICKSDEVELOPER");
}
- if (member.user.flags) { member.user.flags.toArray().map((flag) => { flags.push(flag.toString()); }); }
- if (member.user.bot) { flags.push("BOT"); }
+ if (member.user.flags) {
+ member.user.flags.toArray().map((flag) => {
+ flags.push(flag.toString());
+ });
+ }
+ if (member.user.bot) {
+ flags.push("BOT");
+ }
// Check if they are boosting the server
- if (member.premiumSince) { flags.push("BOOSTER"); }
+ if (member.premiumSince) {
+ flags.push("BOOSTER");
+ }
const nameReplacements: Record<string, string> = {
NUCLEUSDEVELOPER: "**Nucleus Developer**",
CLICKSDEVELOPER: "Clicks Developer",
@@ -79,7 +91,8 @@
Staff: "Discord Staff",
VerifiedDeveloper: "Verified Bot Developer",
ActiveDeveloper: "Active Developer",
- Quarantined: "Quarantined [[What does this mean?]](https://support.discord.com/hc/en-us/articles/6461420677527)",
+ Quarantined:
+ "Quarantined [[What does this mean?]](https://support.discord.com/hc/en-us/articles/6461420677527)",
Spammer: "Likely Spammer"
// CertifiedModerator
// VerifiedBot
@@ -139,24 +152,27 @@
.setStatus("Success")
.setEmoji("MEMBER.JOIN")
.setDescription(
- flags.map((flag) => {
- if (nameReplacements[flag]) {
- const emoji = getEmojiByName(`BADGES.${flag}`)
- if (emoji) return (emoji + " " + nameReplacements[flag] + "\n");
- else return nameReplacements[flag] + "\n";
- }
- }).join("") + "\n" +
- generateKeyValueList({
- member: renderUser(member.user),
- nickname: member.nickname ?? "*None set*",
- id: `\`${member.id}\``,
- "joined the server": renderDelta(member.joinedTimestamp!),
- "joined discord": renderDelta(member.user.createdTimestamp),
- "boost status": member.premiumSince
- ? `Started boosting ${renderDelta(member.premiumSinceTimestamp!)}`
- : "*Not boosting*",
- "join position": `${joinPos + 1}`
- })
+ flags
+ .map((flag) => {
+ if (nameReplacements[flag]) {
+ const emoji = getEmojiByName(`BADGES.${flag}`);
+ if (emoji) return emoji + " " + nameReplacements[flag] + "\n";
+ else return nameReplacements[flag] + "\n";
+ }
+ })
+ .join("") +
+ "\n" +
+ generateKeyValueList({
+ member: renderUser(member.user),
+ nickname: member.nickname ?? "*None set*",
+ id: `\`${member.id}\``,
+ "joined the server": renderDelta(member.joinedTimestamp!),
+ "joined discord": renderDelta(member.user.createdTimestamp),
+ "boost status": member.premiumSince
+ ? `Started boosting ${renderDelta(member.premiumSinceTimestamp!)}`
+ : "*Not boosting*",
+ "join position": `${joinPos + 1}`
+ })
)
.setThumbnail(member.user.displayAvatarURL())
)
@@ -174,7 +190,10 @@
member: renderUser(member.user),
id: `\`${member.id}\``,
roles: `${member.roles.cache.size - 1}`
- }) + "\n" + (s.length > 0 ? s : "*None*") + "\n"
+ }) +
+ "\n" +
+ (s.length > 0 ? s : "*None*") +
+ "\n"
)
)
.setTitle("Roles")
@@ -199,7 +218,9 @@
.setDescription("Key permissions the user has")
.setPageId(2)
];
- if (member.user.bannerURL() ) { embeds[0]!.embed.setImage(member.user.bannerURL()!); }
+ if (member.user.bannerURL()) {
+ embeds[0]!.embed.setImage(member.user.bannerURL()!);
+ }
let page = 0;
let timedOut = false;
for (const embed of embeds) {
@@ -255,7 +276,13 @@
try {
i = await m.awaitMessageComponent({
time: 300000,
- filter: (i) => { return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.message.id === m.id }
+ filter: (i) => {
+ return (
+ i.user.id === interaction.user.id &&
+ i.channel!.id === interaction.channel!.id &&
+ i.message.id === m.id
+ );
+ }
});
} catch {
timedOut = true;
@@ -281,8 +308,8 @@
embeds: [em],
components: []
});
-};
+}
export { command };
export { callback };
-export { userAbout };
\ No newline at end of file
+export { userAbout };
diff --git a/src/commands/user/avatar.ts b/src/commands/user/avatar.ts
index da33f51..6804695 100644
--- a/src/commands/user/avatar.ts
+++ b/src/commands/user/avatar.ts
@@ -35,6 +35,5 @@
});
};
-
export { command };
export { callback };
diff --git a/src/commands/user/role.ts b/src/commands/user/role.ts
index 41820ac..74b6c41 100644
--- a/src/commands/user/role.ts
+++ b/src/commands/user/role.ts
@@ -1,17 +1,29 @@
-import { ActionRowBuilder, APIMessageComponentEmoji, ButtonBuilder, ButtonInteraction, ButtonStyle, CommandInteraction, GuildMember, Role, RoleSelectMenuBuilder, RoleSelectMenuInteraction, UserSelectMenuBuilder, UserSelectMenuInteraction } from "discord.js";
+import {
+ ActionRowBuilder,
+ APIMessageComponentEmoji,
+ ButtonBuilder,
+ ButtonInteraction,
+ ButtonStyle,
+ CommandInteraction,
+ GuildMember,
+ Role,
+ RoleSelectMenuBuilder,
+ RoleSelectMenuInteraction,
+ UserSelectMenuBuilder,
+ UserSelectMenuInteraction
+} from "discord.js";
import type { SlashCommandSubcommandBuilder } from "discord.js";
import client from "../../utils/client.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import { LoadingEmbed } from "../../utils/defaults.js";
import getEmojiByName from "../../utils/getEmojiByName.js";
-import listToAndMore from "../../utils/listToAndMore.js"
+import listToAndMore from "../../utils/listToAndMore.js";
const { renderUser } = client.logger;
const canEdit = (role: Role, member: GuildMember, me: GuildMember): [string, boolean] => {
- if(role.position >= me.roles.highest.position ||
- role.position >= member.roles.highest.position
- ) return [`~~<@&${role.id}>~~`, false];
+ if (role.position >= me.roles.highest.position || role.position >= member.roles.highest.position)
+ return [`~~<@&${role.id}>~~`, false];
return [`<@&${role.id}>`, true];
};
@@ -19,103 +31,116 @@
builder
.setName("role")
.setDescription("Gives or removes a role from someone")
- .addUserOption((option) => option.setName("user").setDescription("The user to give or remove the role from"))
+ .addUserOption((option) => option.setName("user").setDescription("The user to give or remove the role from"));
const callback = async (interaction: CommandInteraction): Promise<unknown> => {
const m = await interaction.reply({ embeds: LoadingEmbed, fetchReply: true, ephemeral: true });
let member = interaction.options.getMember("user") as GuildMember | null;
- if(!member) {
+ if (!member) {
const memberEmbed = new EmojiEmbed()
.setTitle("Role")
.setDescription(`Please choose a member to edit the roles of.`)
.setEmoji("GUILD.ROLES.CREATE")
.setStatus("Success");
const memberChooser = new ActionRowBuilder<UserSelectMenuBuilder>().addComponents(
- new UserSelectMenuBuilder()
- .setCustomId("memberChooser")
- .setPlaceholder("Select a member")
+ new UserSelectMenuBuilder().setCustomId("memberChooser").setPlaceholder("Select a member")
);
- await interaction.editReply({embeds: [memberEmbed], components: [memberChooser]});
+ await interaction.editReply({ embeds: [memberEmbed], components: [memberChooser] });
- const filter = (i: UserSelectMenuInteraction) => i.customId === "memberChooser" && i.user.id === interaction.user.id;
+ const filter = (i: UserSelectMenuInteraction) =>
+ i.customId === "memberChooser" && i.user.id === interaction.user.id;
let i: UserSelectMenuInteraction | null;
try {
- i = await m.awaitMessageComponent<5>({ filter, time: 300000});
+ i = await m.awaitMessageComponent<5>({ filter, time: 300000 });
} catch (e) {
return;
}
memberEmbed.setDescription(`Editing roles for ${renderUser(i.values[0]!)}`);
await i.deferUpdate();
- await interaction.editReply({ embeds: LoadingEmbed, components: [] })
+ await interaction.editReply({ embeds: LoadingEmbed, components: [] });
member = await interaction.guild?.members.fetch(i.values[0]!)!;
-
}
let closed = false;
let rolesToChange: string[] = [];
- const roleAdd = new ActionRowBuilder<RoleSelectMenuBuilder>()
- .addComponents(
- new RoleSelectMenuBuilder()
- .setCustomId("roleAdd")
- .setPlaceholder("Select a role to add")
- .setMaxValues(25)
- );
+ const roleAdd = new ActionRowBuilder<RoleSelectMenuBuilder>().addComponents(
+ new RoleSelectMenuBuilder().setCustomId("roleAdd").setPlaceholder("Select a role to add").setMaxValues(25)
+ );
do {
-
- const removing = rolesToChange.filter((r) => member!.roles.cache.has(r)).map((r) => canEdit(interaction.guild?.roles.cache.get(r)!, interaction.member as GuildMember, interaction.guild?.members.me!)[0])
- const adding = rolesToChange.filter((r) => !member!.roles.cache.has(r)).map((r) => canEdit(interaction.guild?.roles.cache.get(r)!, interaction.member as GuildMember, interaction.guild?.members.me!)[0])
- const embed = new EmojiEmbed()
- .setTitle("Role")
- .setDescription(
- `${getEmojiByName("ICONS.EDIT")} Editing roles for <@${member.id}>\n\n` +
- `Adding:\n` +
- `${listToAndMore(adding.length > 0 ? adding : ["None"], 5)}\n` +
- `Removing:\n` +
- `${listToAndMore(removing.length > 0 ? removing : ["None"], 5)}\n`
- )
- .setEmoji("GUILD.ROLES.CREATE")
- .setStatus("Success");
-
- const buttons = new ActionRowBuilder<ButtonBuilder>()
- .addComponents(
- new ButtonBuilder()
- .setCustomId("roleSave")
- .setLabel("Apply")
- .setEmoji(getEmojiByName("ICONS.SAVE", "id") as APIMessageComponentEmoji)
- .setStyle(ButtonStyle.Success),
- new ButtonBuilder()
- .setCustomId("roleDiscard")
- .setLabel("Reset")
- .setEmoji(getEmojiByName("CONTROL.CROSS", "id") as APIMessageComponentEmoji)
- .setStyle(ButtonStyle.Danger)
+ const removing = rolesToChange
+ .filter((r) => member!.roles.cache.has(r))
+ .map(
+ (r) =>
+ canEdit(
+ interaction.guild?.roles.cache.get(r)!,
+ interaction.member as GuildMember,
+ interaction.guild?.members.me!
+ )[0]
);
+ const adding = rolesToChange
+ .filter((r) => !member!.roles.cache.has(r))
+ .map(
+ (r) =>
+ canEdit(
+ interaction.guild?.roles.cache.get(r)!,
+ interaction.member as GuildMember,
+ interaction.guild?.members.me!
+ )[0]
+ );
+ const embed = new EmojiEmbed()
+ .setTitle("Role")
+ .setDescription(
+ `${getEmojiByName("ICONS.EDIT")} Editing roles for <@${member.id}>\n\n` +
+ `Adding:\n` +
+ `${listToAndMore(adding.length > 0 ? adding : ["None"], 5)}\n` +
+ `Removing:\n` +
+ `${listToAndMore(removing.length > 0 ? removing : ["None"], 5)}\n`
+ )
+ .setEmoji("GUILD.ROLES.CREATE")
+ .setStatus("Success");
+
+ const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("roleSave")
+ .setLabel("Apply")
+ .setEmoji(getEmojiByName("ICONS.SAVE", "id") as APIMessageComponentEmoji)
+ .setStyle(ButtonStyle.Success),
+ new ButtonBuilder()
+ .setCustomId("roleDiscard")
+ .setLabel("Reset")
+ .setEmoji(getEmojiByName("CONTROL.CROSS", "id") as APIMessageComponentEmoji)
+ .setStyle(ButtonStyle.Danger)
+ );
await interaction.editReply({ embeds: [embed], components: [roleAdd, buttons] });
let i: RoleSelectMenuInteraction | ButtonInteraction | null;
try {
- i = await m.awaitMessageComponent({ filter: (i) => i.user.id === interaction.user.id, time: 300000 }) as RoleSelectMenuInteraction | ButtonInteraction;
+ i = (await m.awaitMessageComponent({ filter: (i) => i.user.id === interaction.user.id, time: 300000 })) as
+ | RoleSelectMenuInteraction
+ | ButtonInteraction;
} catch (e) {
closed = true;
continue;
}
i.deferUpdate();
- if(i.isButton()) {
- switch(i.customId) {
+ if (i.isButton()) {
+ switch (i.customId) {
case "roleSave": {
const roles = rolesToChange.map((r) => interaction.guild?.roles.cache.get(r)!);
await interaction.editReply({ embeds: LoadingEmbed, components: [] });
const rolesToAdd: Role[] = [];
const rolesToRemove: Role[] = [];
- for(const role of roles) {
- if(!canEdit(role, interaction.member as GuildMember, interaction.guild?.members.me!)[1]) continue;
- if(member.roles.cache.has(role.id)) {
+ for (const role of roles) {
+ if (!canEdit(role, interaction.member as GuildMember, interaction.guild?.members.me!)[1])
+ continue;
+ if (member.roles.cache.has(role.id)) {
rolesToRemove.push(role);
} else {
rolesToAdd.push(role);
@@ -135,9 +160,7 @@
} else {
rolesToChange = i.values;
}
-
} while (!closed);
-
};
const check = (interaction: CommandInteraction, partial: boolean = false) => {
@@ -145,7 +168,7 @@
// Check if the user has manage_roles permission
if (!member.permissions.has("ManageRoles")) return "You do not have the *Manage Roles* permission";
if (partial) return true;
- if (!interaction.guild) return
+ if (!interaction.guild) return;
const me = interaction.guild.members.me!;
// Check if Nucleus has permission to role
if (!me.permissions.has("ManageRoles")) return "I do not have the *Manage Roles* permission";
diff --git a/src/commands/user/track.ts b/src/commands/user/track.ts
index c7f441f..19b9da2 100644
--- a/src/commands/user/track.ts
+++ b/src/commands/user/track.ts
@@ -1,5 +1,17 @@
import { LoadingEmbed } from "../../utils/defaults.js";
-import Discord, { CommandInteraction, GuildMember, Message, ActionRowBuilder, ButtonBuilder, ButtonStyle, APIMessageComponentEmoji, StringSelectMenuBuilder, MessageComponentInteraction, StringSelectMenuInteraction, StringSelectMenuOptionBuilder } from "discord.js";
+import Discord, {
+ CommandInteraction,
+ GuildMember,
+ Message,
+ ActionRowBuilder,
+ ButtonBuilder,
+ ButtonStyle,
+ APIMessageComponentEmoji,
+ StringSelectMenuBuilder,
+ MessageComponentInteraction,
+ StringSelectMenuInteraction,
+ StringSelectMenuOptionBuilder
+} from "discord.js";
import type { SlashCommandSubcommandBuilder } from "discord.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import getEmojiByName from "../../utils/getEmojiByName.js";
@@ -14,7 +26,7 @@
.addUserOption((option) => option.setName("user").setDescription("The user to manage").setRequired(true));
const callback = async (interaction: CommandInteraction): Promise<unknown> => {
- const { renderUser, renderRole} = client.logger;
+ const { renderUser, renderRole } = client.logger;
const member = interaction.options.getMember("user") as GuildMember;
const guild = interaction.guild;
if (!guild) return;
@@ -63,13 +75,15 @@
for (const role of data.track) {
const disabled: boolean =
roles.get(role)!.position >= (interaction.member as GuildMember).roles.highest.position && !managed;
- allowed.push(!disabled)
+ allowed.push(!disabled);
}
- generated += "\n" + createVerticalTrack(
- data.track.map((role) => renderRole(roles.get(role)!)),
- data.track.map((role) => memberRoles.cache.has(role)),
- allowed.map((allow) => !allow)
- );
+ generated +=
+ "\n" +
+ createVerticalTrack(
+ data.track.map((role) => renderRole(roles.get(role)!)),
+ data.track.map((role) => memberRoles.cache.has(role)),
+ allowed.map((allow) => !allow)
+ );
const selected = [];
for (const position of data.track) {
if (memberRoles.cache.has(position)) selected.push(position);
@@ -117,7 +131,9 @@
],
components: [new ActionRowBuilder<StringSelectMenuBuilder | ButtonBuilder>().addComponents(dropdown)]
.concat(
- conflict && conflictDropdown.length ? [new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(conflictDropdown)] : []
+ conflict && conflictDropdown.length
+ ? [new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(conflictDropdown)]
+ : []
)
.concat([
new ActionRowBuilder<ButtonBuilder>().addComponents([
@@ -150,7 +166,13 @@
try {
component = await m.awaitMessageComponent({
time: 300000,
- filter: (i) => { return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.message.id === m.id }
+ filter: (i) => {
+ return (
+ i.user.id === interaction.user.id &&
+ i.channel!.id === interaction.channel!.id &&
+ i.message.id === m.id
+ );
+ }
});
} catch (e) {
timedOut = true;
@@ -158,7 +180,9 @@
}
component.deferUpdate();
if (component.customId === "conflict") {
- const rolesToRemove = selected.filter((role) => role !== (component as StringSelectMenuInteraction).values[0]);
+ const rolesToRemove = selected.filter(
+ (role) => role !== (component as StringSelectMenuInteraction).values[0]
+ );
await member.roles.remove(rolesToRemove);
} else if (component.customId === "promote") {
if (
@@ -196,7 +220,7 @@
if (member.id === interaction.guild!.ownerId) return true;
// Check if the user can manage any of the tracks
let managed = false;
- const memberRoles = member.roles.cache.map((r) => r.id)
+ const memberRoles = member.roles.cache.map((r) => r.id);
for (const element of tracks) {
if (!element.manageableBy.length) continue;
if (!element.manageableBy.some((role: string) => memberRoles.includes(role))) continue;
diff --git a/src/config/default.ts b/src/config/default.ts
index f1279c5..f0b931e 100644
--- a/src/config/default.ts
+++ b/src/config/default.ts
@@ -91,39 +91,39 @@
timeout: false,
role: null,
text: null,
- link: null,
+ link: null
},
kick: {
text: null,
- link: null,
+ link: null
},
ban: {
text: null,
- link: null,
+ link: null
},
softban: {
text: null,
- link: null,
+ link: null
},
warn: {
text: null,
- link: null,
+ link: null
},
role: {
role: null,
text: null,
- link: null,
+ link: null
},
nick: {
text: null,
- link: null,
+ link: null
}
},
tracks: [],
roleMenu: {
enabled: false,
allowWebUI: false,
- options: [],
+ options: []
},
tags: {},
autoPublish: {
diff --git a/src/config/format.ts b/src/config/format.ts
index e32bef6..0560796 100644
--- a/src/config/format.ts
+++ b/src/config/format.ts
@@ -1,4 +1,3 @@
-
import fs from "fs";
import * as readLine from "node:readline/promises";
@@ -24,7 +23,7 @@
password: "",
database: "",
host: "",
- authSource: "",
+ authSource: ""
},
baseUrl: "Your website where buttons such as Verify and Role menu will link to, e.g. https://example.com/",
pastebinApiKey: "An API key for pastebin (optional)",
@@ -64,7 +63,7 @@
let json: typeof defaultDict;
let out = true;
try {
- json = await import("./main.js") as unknown as typeof defaultDict;
+ json = (await import("./main.js")) as unknown as typeof defaultDict;
} catch (e) {
console.log("\x1b[31mâš No main.ts found, creating one.");
console.log(" \x1b[2mYou can edit src/config/main.ts directly using template written to the file.\x1b[0m\n");
@@ -75,7 +74,9 @@
if (Object.keys(json).length) {
if (json["token"] === defaultDict["token"] || json["developmentToken"] === defaultDict["developmentToken"]) {
console.log("\x1b[31mâš No main.ts found, creating one.");
- console.log(" \x1b[2mYou can edit src/config/main.ts directly using template written to the file.\x1b[0m\n");
+ console.log(
+ " \x1b[2mYou can edit src/config/main.ts directly using template written to the file.\x1b[0m\n"
+ );
json = {};
}
}
@@ -142,7 +143,7 @@
password: json["password"] as string,
database: json["database"] as string,
host: json["host"] as string,
- authSource: json["authSource"] as string,
+ authSource: json["authSource"] as string
};
fs.writeFileSync("./src/config/main.ts", "export default " + JSON.stringify(json, null, 4) + ";");
diff --git a/src/config/main.d.ts b/src/config/main.d.ts
index 75eb9e0..99c460d 100644
--- a/src/config/main.d.ts
+++ b/src/config/main.d.ts
@@ -1,24 +1,24 @@
declare const config: {
- developmentToken: string,
- developmentGuildID: string,
- enableDevelopment: boolean,
- token: string,
- managementGuildID: string,
- owners: string[],
- commandsFolder: string,
- eventsFolder: string,
- messageContextFolder: string,
- userContextFolder: string,
- verifySecret: string,
+ developmentToken: string;
+ developmentGuildID: string;
+ enableDevelopment: boolean;
+ token: string;
+ managementGuildID: string;
+ owners: string[];
+ commandsFolder: string;
+ eventsFolder: string;
+ messageContextFolder: string;
+ userContextFolder: string;
+ verifySecret: string;
mongoOptions: {
- username: string,
- password: string,
- database: string,
- host: string,
- authSource: string
- },
- baseUrl: string,
- rapidApiKey: string
+ username: string;
+ password: string;
+ database: string;
+ host: string;
+ authSource: string;
+ };
+ baseUrl: string;
+ rapidApiKey: string;
};
-export default config;
\ No newline at end of file
+export default config;
diff --git a/src/context/messages/purgeto.ts b/src/context/messages/purgeto.ts
index 3d7e95a..d2191d1 100644
--- a/src/context/messages/purgeto.ts
+++ b/src/context/messages/purgeto.ts
@@ -1,18 +1,28 @@
-import confirmationMessage from '../../utils/confirmationMessage.js';
-import EmojiEmbed from '../../utils/generateEmojiEmbed.js';
-import { LoadingEmbed } from '../../utils/defaults.js';
-import Discord, { ActionRowBuilder, ButtonBuilder, ButtonStyle, ContextMenuCommandBuilder, GuildMember, GuildTextBasedChannel, Message, MessageContextMenuCommandInteraction } from "discord.js";
+import confirmationMessage from "../../utils/confirmationMessage.js";
+import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
+import { LoadingEmbed } from "../../utils/defaults.js";
+import Discord, {
+ ActionRowBuilder,
+ ButtonBuilder,
+ ButtonStyle,
+ ContextMenuCommandBuilder,
+ GuildMember,
+ GuildTextBasedChannel,
+ Message,
+ MessageContextMenuCommandInteraction
+} from "discord.js";
import client from "../../utils/client.js";
-import { messageException } from '../../utils/createTemporaryStorage.js';
+import { messageException } from "../../utils/createTemporaryStorage.js";
-const command = new ContextMenuCommandBuilder()
- .setName("Purge up to here")
-
+const command = new ContextMenuCommandBuilder().setName("Purge up to here");
async function waitForButton(m: Discord.Message, member: Discord.GuildMember): Promise<boolean> {
let component;
try {
- component = m.awaitMessageComponent({ time: 200000, filter: (i) => i.user.id === member.id && i.channel!.id === m.channel.id && i.message.id === m.id });
+ component = m.awaitMessageComponent({
+ time: 200000,
+ filter: (i) => i.user.id === member.id && i.channel!.id === m.channel.id && i.message.id === m.id
+ });
} catch (e) {
return false;
}
@@ -20,7 +30,6 @@
return true;
}
-
const callback = async (interaction: MessageContextMenuCommandInteraction) => {
await interaction.targetMessage.fetch();
const targetMessage = interaction.targetMessage;
@@ -34,56 +43,74 @@
const history: Discord.Collection<string, Discord.Message> = await channel.messages.fetch({ limit: 100 });
if (Date.now() - targetMessage.createdTimestamp > 2 * 7 * 24 * 60 * 60 * 1000) {
- const m = await interaction.editReply({ embeds: [new EmojiEmbed()
- .setTitle("Purge")
- .setDescription("The message you selected is older than 2 weeks. Discord only allows bots to delete messages that are 2 weeks old or younger.")
- .setEmoji("CHANNEL.PURGE.RED")
- .setStatus("Danger")
- ], components: [
- new ActionRowBuilder<ButtonBuilder>().addComponents(
- new ButtonBuilder()
- .setCustomId("oldest")
- .setLabel("Select first allowed message")
- .setStyle(ButtonStyle.Primary),
- )
- ]});
- if (!await waitForButton(m, interaction.member as Discord.GuildMember)) return;
+ const m = await interaction.editReply({
+ embeds: [
+ new EmojiEmbed()
+ .setTitle("Purge")
+ .setDescription(
+ "The message you selected is older than 2 weeks. Discord only allows bots to delete messages that are 2 weeks old or younger."
+ )
+ .setEmoji("CHANNEL.PURGE.RED")
+ .setStatus("Danger")
+ ],
+ components: [
+ new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("oldest")
+ .setLabel("Select first allowed message")
+ .setStyle(ButtonStyle.Primary)
+ )
+ ]
+ });
+ if (!(await waitForButton(m, interaction.member as Discord.GuildMember))) return;
} else if (!history.has(targetMessage.id)) {
- const m = await interaction.editReply({ embeds: [new EmojiEmbed()
- .setTitle("Purge")
- .setDescription("The message you selected is not in the last 100 messages in this channel. Discord only allows bots to delete 100 messages at a time.")
- .setEmoji("CHANNEL.PURGE.YELLOW")
- .setStatus("Warning")
- ], components: [
- new ActionRowBuilder<ButtonBuilder>().addComponents(
- new ButtonBuilder()
- .setCustomId("oldest")
- .setLabel("Select first allowed message")
- .setStyle(ButtonStyle.Primary),
- )
- ]});
- if (!await waitForButton(m, interaction.member as Discord.GuildMember)) return;
+ const m = await interaction.editReply({
+ embeds: [
+ new EmojiEmbed()
+ .setTitle("Purge")
+ .setDescription(
+ "The message you selected is not in the last 100 messages in this channel. Discord only allows bots to delete 100 messages at a time."
+ )
+ .setEmoji("CHANNEL.PURGE.YELLOW")
+ .setStatus("Warning")
+ ],
+ components: [
+ new ActionRowBuilder<ButtonBuilder>().addComponents(
+ new ButtonBuilder()
+ .setCustomId("oldest")
+ .setLabel("Select first allowed message")
+ .setStyle(ButtonStyle.Primary)
+ )
+ ]
+ });
+ if (!(await waitForButton(m, interaction.member as Discord.GuildMember))) return;
} else {
allowedMessage = targetMessage;
}
if (!allowedMessage) {
// Find the oldest message thats younger than 2 weeks
- const messages = history.filter(m => Date.now() - m.createdTimestamp < 2 * 7 * 24 * 60 * 60 * 1000);
+ const messages = history.filter((m) => Date.now() - m.createdTimestamp < 2 * 7 * 24 * 60 * 60 * 1000);
allowedMessage = messages.sort((a, b) => a.createdTimestamp - b.createdTimestamp).first();
}
if (!allowedMessage) {
- await interaction.editReply({ embeds: [new EmojiEmbed()
- .setTitle("Purge")
- .setDescription("There are no valid messages in the last 100 messages. (No messages younger than 2 weeks)")
- .setEmoji("CHANNEL.PURGE.RED")
- .setStatus("Danger")
- ], components: [] });
+ await interaction.editReply({
+ embeds: [
+ new EmojiEmbed()
+ .setTitle("Purge")
+ .setDescription(
+ "There are no valid messages in the last 100 messages. (No messages younger than 2 weeks)"
+ )
+ .setEmoji("CHANNEL.PURGE.RED")
+ .setStatus("Danger")
+ ],
+ components: []
+ });
return;
}
- let reason: string | null = null
+ let reason: string | null = null;
let confirmation;
let chosen = false;
let timedOut = false;
@@ -95,8 +122,9 @@
.setTitle("Purge")
.setDescription(
`[[Selected Message]](${allowedMessage.url})\n\n` +
- (reason ? "\n> " + reason.replaceAll("\n", "\n> ") : "*No reason provided*") + "\n\n" +
- `Are you sure you want to delete all messages from below the selected message?`
+ (reason ? "\n> " + reason.replaceAll("\n", "\n> ") : "*No reason provided*") +
+ "\n\n" +
+ `Are you sure you want to delete all messages from below the selected message?`
)
.addCustomBoolean(
"includeSelected",
@@ -121,8 +149,8 @@
.setColor("Danger")
.addReasonButton(reason ?? "")
.setFailedMessage("No changes were made", "Success", "CHANNEL.PURGE.GREEN")
- .send(true)
- reason = reason ?? ""
+ .send(true);
+ reason = reason ?? "";
if (confirmation.cancelled) timedOut = true;
else if (confirmation.success !== undefined) chosen = true;
else if (confirmation.newReason) reason = confirmation.newReason;
@@ -133,9 +161,9 @@
} while (!chosen && !timedOut);
if (timedOut || !confirmation.success) return;
const filteredMessages = history
- .filter(m => m.createdTimestamp >= allowedMessage!.createdTimestamp) // older than selected
- .filter(m => deleteUser ? m.author.id === targetMember.id : true) // only selected user
- .filter(m => deleteSelected ? true : m.id !== allowedMessage!.id) // include selected
+ .filter((m) => m.createdTimestamp >= allowedMessage!.createdTimestamp) // older than selected
+ .filter((m) => (deleteUser ? m.author.id === targetMember.id : true)) // only selected user
+ .filter((m) => (deleteSelected ? true : m.id !== allowedMessage!.id)); // include selected
const deleted = await (channel as GuildTextBasedChannel).bulkDelete(filteredMessages, true);
if (deleted.size === 0) {
@@ -183,16 +211,24 @@
}
};
log(data);
- const messages: Message[] = deleted.map(m => m).filter(m => m instanceof Message).map(m => m as Message);
- if (messages.length === 1) messageException(interaction.guild!.id, interaction.channel.id, messages[0]!.id)
- const messageArray: Message[] = messages.filter(message => !(
- message!.components.some(
- component => component.components.some(
- child => child.customId?.includes("transcript") ?? false
- )
+ const messages: Message[] = deleted
+ .map((m) => m)
+ .filter((m) => m instanceof Message)
+ .map((m) => m as Message);
+ if (messages.length === 1) messageException(interaction.guild!.id, interaction.channel.id, messages[0]!.id);
+ const messageArray: Message[] = messages
+ .filter(
+ (message) =>
+ !message!.components.some((component) =>
+ component.components.some((child) => child.customId?.includes("transcript") ?? false)
+ )
)
- )).map(message => message as Message);
- const transcript = await client.database.transcripts.createTranscript(messageArray, interaction, interaction.member as GuildMember);
+ .map((message) => message as Message);
+ const transcript = await client.database.transcripts.createTranscript(
+ messageArray,
+ interaction,
+ interaction.member as GuildMember
+ );
const [code, key, iv] = await client.database.transcripts.create(transcript);
@@ -206,14 +242,18 @@
],
components: [
new Discord.ActionRowBuilder<ButtonBuilder>().addComponents([
- new ButtonBuilder().setLabel("View").setStyle(ButtonStyle.Link).setURL(`https://clicks.codes/nucleus/transcript/${code}?key=${key}&iv=${iv}`).setDisabled(!code),
+ new ButtonBuilder()
+ .setLabel("View")
+ .setStyle(ButtonStyle.Link)
+ .setURL(`https://clicks.codes/nucleus/transcript/${code}?key=${key}&iv=${iv}`)
+ .setDisabled(!code)
])
]
});
-}
+};
const check = async (_interaction: MessageContextMenuCommandInteraction) => {
return true;
-}
+};
-export { command, callback, check }
+export { command, callback, check };
diff --git a/src/context/users/userinfo.ts b/src/context/users/userinfo.ts
index 496f84e..7a75754 100644
--- a/src/context/users/userinfo.ts
+++ b/src/context/users/userinfo.ts
@@ -1,20 +1,19 @@
import { ContextMenuCommandBuilder, GuildMember, UserContextMenuCommandInteraction } from "discord.js";
import { userAbout } from "../../commands/user/about.js";
-const command = new ContextMenuCommandBuilder()
- .setName("User info")
+const command = new ContextMenuCommandBuilder().setName("User info");
const callback = async (interaction: UserContextMenuCommandInteraction) => {
- console.log("callback")
- const guild = interaction.guild!
- let member = interaction.targetMember
- if (!member) member = await guild.members.fetch(interaction.targetId)
- await userAbout(guild, member as GuildMember, interaction)
-}
+ console.log("callback");
+ const guild = interaction.guild!;
+ let member = interaction.targetMember;
+ if (!member) member = await guild.members.fetch(interaction.targetId);
+ await userAbout(guild, member as GuildMember, interaction);
+};
const check = async (_interaction: UserContextMenuCommandInteraction) => {
- console.log("check")
+ console.log("check");
return true;
-}
+};
-export { command, callback, check }
+export { command, callback, check };
diff --git a/src/events/channelCreate.ts b/src/events/channelCreate.ts
index b42ded7..90a7f6d 100644
--- a/src/events/channelCreate.ts
+++ b/src/events/channelCreate.ts
@@ -5,9 +5,10 @@
export async function callback(client: NucleusClient, channel: GuildBasedChannel) {
const { getAuditLog, log, isLogging, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger;
- if (!await isLogging(channel.guild.id, "channelUpdate")) return;
- const auditLog = (await getAuditLog(channel.guild, AuditLogEvent.ChannelCreate))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as GuildBasedChannel)!.id === channel.id)[0];
+ if (!(await isLogging(channel.guild.id, "channelUpdate"))) return;
+ const auditLog = (await getAuditLog(channel.guild, AuditLogEvent.ChannelCreate)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as GuildBasedChannel)!.id === channel.id
+ )[0];
if (!auditLog) return;
if (auditLog.executor!.id === client.user!.id) return;
let emoji;
@@ -81,4 +82,4 @@
}
};
log(data);
-};
+}
diff --git a/src/events/channelDelete.ts b/src/events/channelDelete.ts
index 890a15f..8dffd38 100644
--- a/src/events/channelDelete.ts
+++ b/src/events/channelDelete.ts
@@ -15,9 +15,10 @@
export async function callback(client: NucleusClient, channel: GuildBasedChannel) {
const { getAuditLog, log, isLogging, NucleusColors, entry, renderDelta, renderUser } = client.logger;
- if (!await isLogging(channel.guild.id, "channelUpdate")) return;
- const auditLog = (await getAuditLog(channel.guild, AuditLogEvent.ChannelDelete))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as GuildBasedChannel)!.id === channel.id)[0];
+ if (!(await isLogging(channel.guild.id, "channelUpdate"))) return;
+ const auditLog = (await getAuditLog(channel.guild, AuditLogEvent.ChannelDelete)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as GuildBasedChannel)!.id === channel.id
+ )[0];
if (!auditLog) return;
if (auditLog.executor!.id === client.user!.id) return;
@@ -30,32 +31,38 @@
readableType = "Text";
displayName = "Text Channel";
break;
- } case ChannelType.GuildAnnouncement: {
+ }
+ case ChannelType.GuildAnnouncement: {
emoji = "CHANNEL.TEXT.DELETE";
readableType = "Announcement";
displayName = "Announcement Channel";
break;
- } case ChannelType.GuildVoice: {
+ }
+ case ChannelType.GuildVoice: {
emoji = "CHANNEL.VOICE.DELETE";
readableType = "Voice";
displayName = "Voice Channel";
break;
- } case ChannelType.GuildCategory: {
+ }
+ case ChannelType.GuildCategory: {
emoji = "CHANNEL.CATEGORY.DELETE";
readableType = "Category";
displayName = "Category";
break;
- } case ChannelType.GuildStageVoice: {
+ }
+ case ChannelType.GuildStageVoice: {
emoji = "CHANNEL.VOICE.DELETE";
readableType = "Stage";
displayName = "Stage Channel";
break;
- } case ChannelType.GuildForum: {
+ }
+ case ChannelType.GuildForum: {
emoji = "CHANNEL.TEXT.DELETE";
readableType = "Forum";
displayName = "Forum Channel";
break;
- } default: {
+ }
+ default: {
emoji = "CHANNEL.TEXT.DELETE";
readableType = "Channel";
displayName = "Channel";
diff --git a/src/events/channelUpdate.ts b/src/events/channelUpdate.ts
index 052acc1..6491cc9 100644
--- a/src/events/channelUpdate.ts
+++ b/src/events/channelUpdate.ts
@@ -1,5 +1,5 @@
-import { GuildChannel, AuditLogEvent, ChannelType, TextChannel, VoiceChannel, StageChannel } from 'discord.js';
-import type { GuildAuditLogsEntry } from 'discord.js';
+import { GuildChannel, AuditLogEvent, ChannelType, TextChannel, VoiceChannel, StageChannel } from "discord.js";
+import type { GuildAuditLogsEntry } from "discord.js";
//@ts-expect-error
import humanizeDuration from "humanize-duration";
import type { NucleusClient } from "../utils/client.js";
@@ -10,12 +10,12 @@
let entry = c.logger.entry;
const channelTypeEmoji: Record<number, string> = {
- 0: "Text", // Text channel
- 2: "Voice", // Voice channel
- 5: "Announcement", // Announcement channel
- 13: "Stage", // Stage channel
- 15: "Forum", // Forum channel
- 99: "Rules" // Rules channel
+ 0: "Text", // Text channel
+ 2: "Voice", // Voice channel
+ 5: "Announcement", // Announcement channel
+ 13: "Stage", // Stage channel
+ 15: "Forum", // Forum channel
+ 99: "Rules" // Rules channel
};
interface channelChanges {
@@ -39,19 +39,20 @@
autoArchiveDuration?: ReturnType<typeof entry>;
}
-
-
export const event = "channelUpdate";
export async function callback(client: NucleusClient, oldChannel: GuildChannel, newChannel: GuildChannel) {
const { getAuditLog, log, isLogging, NucleusColors, renderDelta, renderUser, renderChannel } = client.logger;
- if (!await isLogging(newChannel.guild.id, "channelUpdate")) return;
+ if (!(await isLogging(newChannel.guild.id, "channelUpdate"))) return;
const config = await client.memory.readGuildInfo(newChannel.guild.id);
entry = client.logger.entry;
if (newChannel.parent && newChannel.parent.id === config.tickets.category) return;
- const auditLog: null | GuildAuditLogsEntry<AuditLogEvent.ChannelUpdate> = (await getAuditLog(newChannel.guild, AuditLogEvent.ChannelUpdate))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as GuildChannel)!.id === newChannel.id)[0] as GuildAuditLogsEntry<AuditLogEvent.ChannelUpdate> | null;
+ const auditLog: null | GuildAuditLogsEntry<AuditLogEvent.ChannelUpdate> = (
+ await getAuditLog(newChannel.guild, AuditLogEvent.ChannelUpdate)
+ ).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as GuildChannel)!.id === newChannel.id
+ )[0] as GuildAuditLogsEntry<AuditLogEvent.ChannelUpdate> | null;
if (!auditLog) return;
if (auditLog.executor!.id === client.user!.id) return;
@@ -62,11 +63,18 @@
channelId: entry(newChannel.id, `\`${newChannel.id}\``),
channel: entry(newChannel.id, renderChannel(newChannel)),
edited: entry(Date.now(), renderDelta(Date.now())),
- editedBy: entry(auditLog.executor!.id, renderUser((await newChannel.guild.members.fetch(auditLog.executor!.id)).user)),
+ editedBy: entry(
+ auditLog.executor!.id,
+ renderUser((await newChannel.guild.members.fetch(auditLog.executor!.id)).user)
+ )
};
- if (oldChannel.name !== newChannel.name) changes.name = entry([oldChannel.name, newChannel.name], `${oldChannel.name} -> ${newChannel.name}`);
+ if (oldChannel.name !== newChannel.name)
+ changes.name = entry([oldChannel.name, newChannel.name], `${oldChannel.name} -> ${newChannel.name}`);
if (oldChannel.position !== newChannel.position)
- changes.position = entry([oldChannel.position.toString(), newChannel.position.toString()], `${oldChannel.position} -> ${newChannel.position}`);
+ changes.position = entry(
+ [oldChannel.position.toString(), newChannel.position.toString()],
+ `${oldChannel.position} -> ${newChannel.position}`
+ );
switch (newChannel.type) {
case ChannelType.PrivateThread:
@@ -94,20 +102,46 @@
newTopic = "None";
}
const nsfw = ["", ""];
- nsfw[0] = (oldChannel as TextChannel).nsfw ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`;
- nsfw[1] = (newChannel as TextChannel).nsfw ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`;
+ nsfw[0] = (oldChannel as TextChannel).nsfw
+ ? `${getEmojiByName("CONTROL.TICK")} Yes`
+ : `${getEmojiByName("CONTROL.CROSS")} No`;
+ nsfw[1] = (newChannel as TextChannel).nsfw
+ ? `${getEmojiByName("CONTROL.TICK")} Yes`
+ : `${getEmojiByName("CONTROL.CROSS")} No`;
if (oldTopic !== newTopic)
- changes.description = entry([(oldChannel as TextChannel).topic ?? "", (newChannel as TextChannel).topic ?? ""], `\nBefore: ${oldTopic}\nAfter: ${newTopic}`);
- if ((oldChannel as TextChannel).nsfw !== (newChannel as TextChannel).nsfw) changes.nsfw = entry([(oldChannel as TextChannel).nsfw ? "On" : "Off", (newChannel as TextChannel).nsfw ? "On" : "Off"], `${nsfw[0]} -> ${nsfw[1]}`);
+ changes.description = entry(
+ [(oldChannel as TextChannel).topic ?? "", (newChannel as TextChannel).topic ?? ""],
+ `\nBefore: ${oldTopic}\nAfter: ${newTopic}`
+ );
+ if ((oldChannel as TextChannel).nsfw !== (newChannel as TextChannel).nsfw)
+ changes.nsfw = entry(
+ [(oldChannel as TextChannel).nsfw ? "On" : "Off", (newChannel as TextChannel).nsfw ? "On" : "Off"],
+ `${nsfw[0]} -> ${nsfw[1]}`
+ );
if ((oldChannel as TextChannel).rateLimitPerUser !== (newChannel as TextChannel).rateLimitPerUser)
changes.slowmode = entry(
- [((oldChannel as TextChannel).rateLimitPerUser).toString(), ((newChannel as TextChannel).rateLimitPerUser).toString()],
- `${humanizeDuration((oldChannel as TextChannel).rateLimitPerUser * 1000)} -> ${humanizeDuration((newChannel as TextChannel).rateLimitPerUser * 1000)}`
+ [
+ (oldChannel as TextChannel).rateLimitPerUser.toString(),
+ (newChannel as TextChannel).rateLimitPerUser.toString()
+ ],
+ `${humanizeDuration((oldChannel as TextChannel).rateLimitPerUser * 1000)} -> ${humanizeDuration(
+ (newChannel as TextChannel).rateLimitPerUser * 1000
+ )}`
);
- if((oldChannel as TextChannel).defaultAutoArchiveDuration !== (newChannel as TextChannel).defaultAutoArchiveDuration) {
+ if (
+ (oldChannel as TextChannel).defaultAutoArchiveDuration !==
+ (newChannel as TextChannel).defaultAutoArchiveDuration
+ ) {
changes.autoArchiveDuration = entry(
- [((oldChannel as TextChannel).defaultAutoArchiveDuration ?? 4320).toString(), ((newChannel as TextChannel).defaultAutoArchiveDuration ?? 4320).toString()],
- `${humanizeDuration(((oldChannel as TextChannel).defaultAutoArchiveDuration ?? 4320) * 60 * 1000)} -> ${humanizeDuration(((newChannel as TextChannel).defaultAutoArchiveDuration ?? 4320) * 60 * 1000)}`
+ [
+ ((oldChannel as TextChannel).defaultAutoArchiveDuration ?? 4320).toString(),
+ ((newChannel as TextChannel).defaultAutoArchiveDuration ?? 4320).toString()
+ ],
+ `${humanizeDuration(
+ ((oldChannel as TextChannel).defaultAutoArchiveDuration ?? 4320) * 60 * 1000
+ )} -> ${humanizeDuration(
+ ((newChannel as TextChannel).defaultAutoArchiveDuration ?? 4320) * 60 * 1000
+ )}`
);
}
@@ -134,12 +168,27 @@
newTopic = "None";
}
if ((oldChannel as TextChannel).nsfw !== (newChannel as TextChannel).nsfw) {
- changes.nsfw = entry([(oldChannel as TextChannel).nsfw ? "On" : "Off", (newChannel as TextChannel).nsfw ? "On" : "Off"], `${(oldChannel as TextChannel).nsfw ? "On" : "Off"} -> ${(newChannel as TextChannel).nsfw ? "On" : "Off"}`);
+ changes.nsfw = entry(
+ [(oldChannel as TextChannel).nsfw ? "On" : "Off", (newChannel as TextChannel).nsfw ? "On" : "Off"],
+ `${(oldChannel as TextChannel).nsfw ? "On" : "Off"} -> ${
+ (newChannel as TextChannel).nsfw ? "On" : "Off"
+ }`
+ );
}
- if((oldChannel as TextChannel).defaultAutoArchiveDuration !== (newChannel as TextChannel).defaultAutoArchiveDuration) {
+ if (
+ (oldChannel as TextChannel).defaultAutoArchiveDuration !==
+ (newChannel as TextChannel).defaultAutoArchiveDuration
+ ) {
changes.autoArchiveDuration = entry(
- [((oldChannel as TextChannel).defaultAutoArchiveDuration ?? 4320).toString(), ((newChannel as TextChannel).defaultAutoArchiveDuration ?? 4320).toString()],
- `${humanizeDuration(((oldChannel as TextChannel).defaultAutoArchiveDuration ?? 4320) * 60 * 1000)} -> ${humanizeDuration(((newChannel as TextChannel).defaultAutoArchiveDuration ?? 4320) * 60 * 1000)}`
+ [
+ ((oldChannel as TextChannel).defaultAutoArchiveDuration ?? 4320).toString(),
+ ((newChannel as TextChannel).defaultAutoArchiveDuration ?? 4320).toString()
+ ],
+ `${humanizeDuration(
+ ((oldChannel as TextChannel).defaultAutoArchiveDuration ?? 4320) * 60 * 1000
+ )} -> ${humanizeDuration(
+ ((newChannel as TextChannel).defaultAutoArchiveDuration ?? 4320) * 60 * 1000
+ )}`
);
}
break;
@@ -149,16 +198,29 @@
readableType = "Voice";
displayName = "Voice Channel";
if ((oldChannel as VoiceChannel).bitrate !== (newChannel as VoiceChannel).bitrate)
- changes.bitrate = entry([(oldChannel as VoiceChannel).bitrate.toString(), (newChannel as VoiceChannel).bitrate.toString()], `${(oldChannel as VoiceChannel).bitrate} -> ${(newChannel as VoiceChannel).bitrate}`);
+ changes.bitrate = entry(
+ [(oldChannel as VoiceChannel).bitrate.toString(), (newChannel as VoiceChannel).bitrate.toString()],
+ `${(oldChannel as VoiceChannel).bitrate} -> ${(newChannel as VoiceChannel).bitrate}`
+ );
if ((oldChannel as VoiceChannel).userLimit !== (newChannel as VoiceChannel).userLimit)
changes.maxUsers = entry(
- [(oldChannel as VoiceChannel).userLimit.toString(), (newChannel as VoiceChannel).userLimit.toString()],
- `${(oldChannel as VoiceChannel).userLimit ? (oldChannel as VoiceChannel).userLimit : "Unlimited"} -> ${(newChannel as VoiceChannel).userLimit}`
+ [
+ (oldChannel as VoiceChannel).userLimit.toString(),
+ (newChannel as VoiceChannel).userLimit.toString()
+ ],
+ `${
+ (oldChannel as VoiceChannel).userLimit ? (oldChannel as VoiceChannel).userLimit : "Unlimited"
+ } -> ${(newChannel as VoiceChannel).userLimit}`
);
if ((oldChannel as VoiceChannel).rtcRegion !== (newChannel as VoiceChannel).rtcRegion)
changes.region = entry(
- [(oldChannel as VoiceChannel).rtcRegion ?? "automatic", (newChannel as VoiceChannel).rtcRegion ?? "automatic"],
- `${capitalize((oldChannel as VoiceChannel).rtcRegion?.toUpperCase() ?? "automatic")} -> ${capitalize((newChannel as VoiceChannel).rtcRegion?.toUpperCase() ?? "automatic")}`
+ [
+ (oldChannel as VoiceChannel).rtcRegion ?? "automatic",
+ (newChannel as VoiceChannel).rtcRegion ?? "automatic"
+ ],
+ `${capitalize(
+ (oldChannel as VoiceChannel).rtcRegion?.toUpperCase() ?? "automatic"
+ )} -> ${capitalize((newChannel as VoiceChannel).rtcRegion?.toUpperCase() ?? "automatic")}`
);
break;
}
@@ -183,16 +245,29 @@
newTopic = "None";
}
if ((oldChannel as StageChannel).bitrate !== (newChannel as StageChannel).bitrate)
- changes.bitrate = entry([(oldChannel as StageChannel).bitrate.toString(), (newChannel as StageChannel).bitrate.toString()], `${(oldChannel as StageChannel).bitrate} -> ${(newChannel as StageChannel).bitrate}`);
+ changes.bitrate = entry(
+ [(oldChannel as StageChannel).bitrate.toString(), (newChannel as StageChannel).bitrate.toString()],
+ `${(oldChannel as StageChannel).bitrate} -> ${(newChannel as StageChannel).bitrate}`
+ );
if ((oldChannel as StageChannel).userLimit !== (newChannel as StageChannel).userLimit)
changes.maxUsers = entry(
- [(oldChannel as StageChannel).userLimit.toString(), (newChannel as StageChannel).userLimit.toString()],
- `${(oldChannel as StageChannel).userLimit ? (oldChannel as StageChannel).userLimit : "Unlimited"} -> ${(newChannel as StageChannel).userLimit}`
+ [
+ (oldChannel as StageChannel).userLimit.toString(),
+ (newChannel as StageChannel).userLimit.toString()
+ ],
+ `${
+ (oldChannel as StageChannel).userLimit ? (oldChannel as StageChannel).userLimit : "Unlimited"
+ } -> ${(newChannel as StageChannel).userLimit}`
);
if ((oldChannel as StageChannel).rtcRegion !== (newChannel as StageChannel).rtcRegion)
changes.region = entry(
- [(oldChannel as StageChannel).rtcRegion ?? "Automatic", (newChannel as StageChannel).rtcRegion ?? "Automatic"],
- `${capitalize((oldChannel as StageChannel).rtcRegion?.toLowerCase() ?? "automatic")} -> ${capitalize((newChannel as StageChannel).rtcRegion?.toLowerCase() ?? "automatic")}`
+ [
+ (oldChannel as StageChannel).rtcRegion ?? "Automatic",
+ (newChannel as StageChannel).rtcRegion ?? "Automatic"
+ ],
+ `${capitalize(
+ (oldChannel as StageChannel).rtcRegion?.toLowerCase() ?? "automatic"
+ )} -> ${capitalize((newChannel as StageChannel).rtcRegion?.toLowerCase() ?? "automatic")}`
);
break;
}
@@ -210,8 +285,7 @@
}
const ocType = channelTypeEmoji[oldChannel.type],
ncType = channelTypeEmoji[newChannel.type];
- if (oldChannel.type !== newChannel.type)
- changes.type = entry([ocType!, ncType!], `${ocType!} -> ${readableType}`);
+ if (oldChannel.type !== newChannel.type) changes.type = entry([ocType!, ncType!], `${ocType!} -> ${readableType}`);
if (!(Object.values(changes).length - 4)) return;
const data = {
meta: {
diff --git a/src/events/commandError.ts b/src/events/commandError.ts
index ff5f4ae..e7d9bf5 100644
--- a/src/events/commandError.ts
+++ b/src/events/commandError.ts
@@ -1,16 +1,20 @@
-import type { ButtonInteraction, ContextMenuCommandInteraction } from 'discord.js';
-import type { CommandInteraction } from 'discord.js';
+import type { ButtonInteraction, ContextMenuCommandInteraction } from "discord.js";
+import type { CommandInteraction } from "discord.js";
import type { NucleusClient } from "../utils/client.js";
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
export const event = "commandError";
-export async function callback(_: NucleusClient, interaction: CommandInteraction | ButtonInteraction | ContextMenuCommandInteraction, error: string) {
+export async function callback(
+ _: NucleusClient,
+ interaction: CommandInteraction | ButtonInteraction | ContextMenuCommandInteraction,
+ error: string
+) {
const embed = new EmojiEmbed()
.setTitle("Something went wrong")
.setDescription(error)
.setStatus("Danger")
- .setEmoji("CONTROL.BLOCKCROSS")
+ .setEmoji("CONTROL.BLOCKCROSS");
if (interaction.replied || interaction.deferred) {
await interaction.followUp({
embeds: [embed],
diff --git a/src/events/emojiCreate.ts b/src/events/emojiCreate.ts
index 2630295..96f7909 100644
--- a/src/events/emojiCreate.ts
+++ b/src/events/emojiCreate.ts
@@ -1,13 +1,14 @@
-import { AuditLogEvent } from 'discord.js';
+import { AuditLogEvent } from "discord.js";
import type { NucleusClient } from "../utils/client.js";
-import type { GuildEmoji, GuildAuditLogsEntry } from 'discord.js'
+import type { GuildEmoji, GuildAuditLogsEntry } from "discord.js";
export const event = "emojiCreate";
export async function callback(client: NucleusClient, emoji: GuildEmoji) {
const { getAuditLog, log, isLogging, NucleusColors, entry, renderUser, renderDelta, renderEmoji } = client.logger;
- if (!await isLogging(emoji.guild.id, "emojiUpdate")) return;
- const auditLog = (await getAuditLog(emoji.guild, AuditLogEvent.EmojiCreate))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as GuildEmoji)!.id === emoji.id)[0];
+ if (!(await isLogging(emoji.guild.id, "emojiUpdate"))) return;
+ const auditLog = (await getAuditLog(emoji.guild, AuditLogEvent.EmojiCreate)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as GuildEmoji)!.id === emoji.id
+ )[0];
if (!auditLog) return;
if (auditLog.executor!.id === client.user!.id) return;
const data = {
@@ -31,4 +32,3 @@
};
log(data);
}
-
diff --git a/src/events/emojiDelete.ts b/src/events/emojiDelete.ts
index c4b488e..52822cb 100644
--- a/src/events/emojiDelete.ts
+++ b/src/events/emojiDelete.ts
@@ -1,13 +1,14 @@
-import { AuditLogEvent } from 'discord.js';
+import { AuditLogEvent } from "discord.js";
import type { NucleusClient } from "../utils/client.js";
-import type { GuildEmoji, GuildAuditLogsEntry } from 'discord.js'
+import type { GuildEmoji, GuildAuditLogsEntry } from "discord.js";
export const event = "emojiDelete";
export async function callback(client: NucleusClient, emoji: GuildEmoji) {
const { getAuditLog, log, isLogging, NucleusColors, entry, renderUser, renderDelta, renderEmoji } = client.logger;
- if (!await isLogging(emoji.guild.id, "emojiUpdate")) return;
- const auditLog = (await getAuditLog(emoji.guild, AuditLogEvent.EmojiDelete))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as GuildEmoji)!.id === emoji.id)[0];
+ if (!(await isLogging(emoji.guild.id, "emojiUpdate"))) return;
+ const auditLog = (await getAuditLog(emoji.guild, AuditLogEvent.EmojiDelete)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as GuildEmoji)!.id === emoji.id
+ )[0];
if (!auditLog) return;
if (auditLog.executor!.id === client.user!.id) return;
const data = {
diff --git a/src/events/emojiUpdate.ts b/src/events/emojiUpdate.ts
index 98ff558..173f5c5 100644
--- a/src/events/emojiUpdate.ts
+++ b/src/events/emojiUpdate.ts
@@ -1,14 +1,15 @@
-import { AuditLogEvent } from 'discord.js';
+import { AuditLogEvent } from "discord.js";
import type { NucleusClient } from "../utils/client.js";
-import type { GuildEmoji, GuildAuditLogsEntry } from 'discord.js'
+import type { GuildEmoji, GuildAuditLogsEntry } from "discord.js";
export const event = "emojiUpdate";
export async function callback(client: NucleusClient, oldEmoji: GuildEmoji, newEmoji: GuildEmoji) {
const { getAuditLog, log, isLogging, NucleusColors, entry, renderUser, renderDelta, renderEmoji } = client.logger;
if (!(await isLogging(newEmoji.guild.id, "emojiUpdate"))) return;
- const auditLog = (await getAuditLog(newEmoji.guild, AuditLogEvent.EmojiUpdate))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as GuildEmoji)!.id === newEmoji.id)[0];
+ const auditLog = (await getAuditLog(newEmoji.guild, AuditLogEvent.EmojiUpdate)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as GuildEmoji)!.id === newEmoji.id
+ )[0];
if (!auditLog) return;
if (auditLog.executor!.id === client.user!.id) return;
@@ -16,7 +17,10 @@
emojiId: entry(newEmoji.id, `\`${newEmoji.id}\``),
emoji: entry(newEmoji.id, renderEmoji(newEmoji)),
edited: entry(newEmoji.createdTimestamp, renderDelta(newEmoji.createdTimestamp)),
- editedBy: entry(auditLog.executor!.id, renderUser((await newEmoji.guild.members.fetch(auditLog.executor!.id)).user)),
+ editedBy: entry(
+ auditLog.executor!.id,
+ renderUser((await newEmoji.guild.members.fetch(auditLog.executor!.id)).user)
+ ),
name: entry([oldEmoji.name!, newEmoji.name!], `\`:${oldEmoji.name}:\` -> \`:${newEmoji.name}:\``)
};
const data = {
diff --git a/src/events/guildBanAdd.ts b/src/events/guildBanAdd.ts
index cac4b41..93f4ec8 100644
--- a/src/events/guildBanAdd.ts
+++ b/src/events/guildBanAdd.ts
@@ -1,5 +1,5 @@
import type { GuildAuditLogsEntry, GuildBan, User } from "discord.js";
-import { AuditLogEvent } from 'discord.js';
+import { AuditLogEvent } from "discord.js";
import { purgeByUser } from "../actions/tickets/delete.js";
import { callback as statsChannelRemove } from "../reflex/statsChannelUpdate.js";
import type { NucleusClient } from "../utils/client.js";
@@ -11,8 +11,9 @@
await statsChannelRemove(client, undefined, ban.guild, ban.user);
purgeByUser(ban.user.id, ban.guild.id);
if (!(await isLogging(ban.guild.id, "guildMemberPunish"))) return;
- const auditLog: GuildAuditLogsEntry | undefined = (await getAuditLog(ban.guild, AuditLogEvent.MemberBanAdd))
- .filter((entry: GuildAuditLogsEntry) => ((entry.target! as User).id === ban.user.id))[0];
+ const auditLog: GuildAuditLogsEntry | undefined = (await getAuditLog(ban.guild, AuditLogEvent.MemberBanAdd)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target! as User).id === ban.user.id
+ )[0];
if (!auditLog) return;
if (auditLog.executor!.id === client.user!.id) return;
await client.database.history.create("ban", ban.guild.id, ban.user, auditLog.executor, auditLog.reason);
diff --git a/src/events/guildBanRemove.ts b/src/events/guildBanRemove.ts
index 3be4560..fc916ba 100644
--- a/src/events/guildBanRemove.ts
+++ b/src/events/guildBanRemove.ts
@@ -6,9 +6,10 @@
export async function callback(client: NucleusClient, ban: GuildBan) {
const { log, isLogging, NucleusColors, entry, renderUser, renderDelta, getAuditLog } = client.logger;
- if (!await isLogging(ban.guild.id, "guildMemberPunish")) return;
- const auditLog = (await getAuditLog(ban.guild, AuditLogEvent.MemberBanRemove))
- .filter((entry: GuildAuditLogsEntry) => ((entry.target! as User).id === ban.user.id))[0];
+ if (!(await isLogging(ban.guild.id, "guildMemberPunish"))) return;
+ const auditLog = (await getAuditLog(ban.guild, AuditLogEvent.MemberBanRemove)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target! as User).id === ban.user.id
+ )[0];
if (!auditLog) return;
if (auditLog.executor!.id === client.user!.id) return;
await client.database.history.create("unban", ban.guild.id, ban.user, auditLog.executor, auditLog.reason);
diff --git a/src/events/guildDelete.ts b/src/events/guildDelete.ts
index 92af401..0a4904e 100644
--- a/src/events/guildDelete.ts
+++ b/src/events/guildDelete.ts
@@ -1,10 +1,10 @@
-import client, { NucleusClient } from '../utils/client.js'
-import type { Guild } from 'discord.js'
+import client, { NucleusClient } from "../utils/client.js";
+import type { Guild } from "discord.js";
-export const event = 'guildDelete'
+export const event = "guildDelete";
export const callback = async (_client: NucleusClient, guild: Guild) => {
await client.database.guilds.delete(guild.id);
await client.database.history.delete(guild.id);
await client.database.notes.delete(guild.id);
await client.database.transcripts.deleteAll(guild.id);
-}
\ No newline at end of file
+};
diff --git a/src/events/guildMemberUpdate.ts b/src/events/guildMemberUpdate.ts
index 721978f..a0acd34 100644
--- a/src/events/guildMemberUpdate.ts
+++ b/src/events/guildMemberUpdate.ts
@@ -7,37 +7,49 @@
export async function callback(client: NucleusClient, before: GuildMember, after: GuildMember) {
const { log, NucleusColors, entry, renderUser, renderDelta, getAuditLog } = client.logger;
- if(before.guild.id === "684492926528651336") {
- await client.database.premium.checkAllPremium(after)
+ if (before.guild.id === "684492926528651336") {
+ await client.database.premium.checkAllPremium(after);
}
- if(!before.roles.cache.equals(after.roles.cache)) {
- const auditLog = (await getAuditLog(after.guild, AuditLogEvent.MemberRoleUpdate))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as GuildMember)!.id === after.id)[0];
+ if (!before.roles.cache.equals(after.roles.cache)) {
+ const auditLog = (await getAuditLog(after.guild, AuditLogEvent.MemberRoleUpdate)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as GuildMember)!.id === after.id
+ )[0];
if (!auditLog) return;
if (client.noLog.includes(`${after.guild.id}${after.id}${auditLog.id}`)) return;
generalException(`${after.guild.id}${after.id}${auditLog.id}`);
if (auditLog.executor!.id !== client.user!.id) {
- const rolesAdded = after.roles.cache.filter(role => !before.roles.cache.has(role.id));
- const rolesRemoved = before.roles.cache.filter(role => !after.roles.cache.has(role.id));
+ const rolesAdded = after.roles.cache.filter((role) => !before.roles.cache.has(role.id));
+ const rolesRemoved = before.roles.cache.filter((role) => !after.roles.cache.has(role.id));
let displayName = "Roles Removed";
let color = NucleusColors.red;
let emoji = "GUILD.ROLES.DELETE";
- if(rolesAdded.size > 0 && rolesRemoved.size > 0) {displayName = "Roles Changed"; color = NucleusColors.yellow; emoji = "GUILD.ROLES.EDIT";}
- else if(rolesAdded.size > 0) {displayName = "Roles Added"; color = NucleusColors.green; emoji = "GUILD.ROLES.CREATE";}
- const removedEntry = rolesRemoved.map(role => role.id);
- const addedEntry = rolesAdded.map(role => role.id);
+ if (rolesAdded.size > 0 && rolesRemoved.size > 0) {
+ displayName = "Roles Changed";
+ color = NucleusColors.yellow;
+ emoji = "GUILD.ROLES.EDIT";
+ } else if (rolesAdded.size > 0) {
+ displayName = "Roles Added";
+ color = NucleusColors.green;
+ emoji = "GUILD.ROLES.CREATE";
+ }
+ const removedEntry = rolesRemoved.map((role) => role.id);
+ const addedEntry = rolesAdded.map((role) => role.id);
let list = {
memberId: entry(after.id, `\`${after.id}\``),
- name: entry(after.user.id, renderUser(after.user)),
+ name: entry(after.user.id, renderUser(after.user))
};
if (rolesAdded.size > 0) {
- list = Object.assign(list, {rolesAdded: entry(addedEntry, addedEntry.map(id => `<@&${id}>`).join(", "))});
+ list = Object.assign(list, {
+ rolesAdded: entry(addedEntry, addedEntry.map((id) => `<@&${id}>`).join(", "))
+ });
}
if (rolesRemoved.size > 0) {
- list = Object.assign(list, {rolesRemoved: entry(removedEntry, removedEntry.map(id => `<@&${id}>`).join(", "))});
+ list = Object.assign(list, {
+ rolesRemoved: entry(removedEntry, removedEntry.map((id) => `<@&${id}>`).join(", "))
+ });
}
list = Object.assign(list, {
@@ -60,18 +72,23 @@
}
};
- if(rolesAdded.size > 0) {
- list = Object.assign(list, {rolesAdded: entry(addedEntry, addedEntry.map(id => `<@&${id}>`).join(", "))});
+ if (rolesAdded.size > 0) {
+ list = Object.assign(list, {
+ rolesAdded: entry(addedEntry, addedEntry.map((id) => `<@&${id}>`).join(", "))
+ });
}
- if(rolesRemoved.size > 0) {
- list = Object.assign(list, {rolesRemoved: entry(removedEntry, removedEntry.map(id => `<@&${id}>`).join(", "))});
+ if (rolesRemoved.size > 0) {
+ list = Object.assign(list, {
+ rolesRemoved: entry(removedEntry, removedEntry.map((id) => `<@&${id}>`).join(", "))
+ });
}
- data = Object.assign(data, {list: list});
+ data = Object.assign(data, { list: list });
log(data);
}
}
- const auditLog = (await getAuditLog(after.guild, AuditLogEvent.MemberUpdate))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as GuildMember)!.id === after.id)[0];
+ const auditLog = (await getAuditLog(after.guild, AuditLogEvent.MemberUpdate)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as GuildMember)!.id === after.id
+ )[0];
if (!auditLog) return;
if (auditLog.executor!.id === client.user!.id) return;
if (before.nickname !== after.nickname) {
diff --git a/src/events/guildUpdate.ts b/src/events/guildUpdate.ts
index 6b25e48..dbd747f 100644
--- a/src/events/guildUpdate.ts
+++ b/src/events/guildUpdate.ts
@@ -7,9 +7,10 @@
export async function callback(client: NucleusClient, before: Guild, after: Guild) {
await statsChannelUpdate(client, after.members.me!);
const { getAuditLog, isLogging, log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
- if (!await isLogging(after.id, "guildUpdate")) return;
- const auditLog = (await getAuditLog(after, AuditLogEvent.GuildUpdate))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as Guild)!.id === after.id)[0]!;
+ if (!(await isLogging(after.id, "guildUpdate"))) return;
+ const auditLog = (await getAuditLog(after, AuditLogEvent.GuildUpdate)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as Guild)!.id === after.id
+ )[0]!;
if (auditLog.executor!.id === client.user!.id) return;
const list: Record<string, ReturnType<typeof entry>> = {};
@@ -21,23 +22,19 @@
"Verified phone"
];
- const explicitContentFilterLevels = [
- "Disabled",
- "Members without roles",
- "All members"
- ];
+ const explicitContentFilterLevels = ["Disabled", "Members without roles", "All members"];
- const MFALevels = [
- "None",
- "Enabled"
- ];
+ const MFALevels = ["None", "Enabled"];
const beforeOwner = await before.fetchOwner();
const afterOwner = await after.fetchOwner();
if (before.name !== after.name) list["name"] = entry([before.name, after.name], `${before.name} -> ${after.name}`);
if (before.icon !== after.icon)
- list["icon"] = entry([before.icon!, after.icon!], `[Before](${before.iconURL()}) -> [After](${after.iconURL()})`);
+ list["icon"] = entry(
+ [before.icon!, after.icon!],
+ `[Before](${before.iconURL()}) -> [After](${after.iconURL()})`
+ );
if (before.splash !== after.splash)
list["splash"] = entry(
[before.splash!, after.splash!],
@@ -55,8 +52,13 @@
);
if (before.verificationLevel !== after.verificationLevel)
list["verificationLevel"] = entry(
- [verificationLevels[before.verificationLevel.valueOf()]!, verificationLevels[before.verificationLevel.valueOf()]!],
- `${verificationLevels[before.verificationLevel.valueOf()]} -> ${verificationLevels[before.verificationLevel.valueOf()]}`
+ [
+ verificationLevels[before.verificationLevel.valueOf()]!,
+ verificationLevels[before.verificationLevel.valueOf()]!
+ ],
+ `${verificationLevels[before.verificationLevel.valueOf()]} -> ${
+ verificationLevels[before.verificationLevel.valueOf()]
+ }`
);
if (before.explicitContentFilter !== after.explicitContentFilter)
list["explicitContentFilter"] = entry(
diff --git a/src/events/interactionCreate.ts b/src/events/interactionCreate.ts
index 80c2c1b..c91f8cd 100644
--- a/src/events/interactionCreate.ts
+++ b/src/events/interactionCreate.ts
@@ -11,17 +11,30 @@
export const event = "interactionCreate";
-
async function interactionCreate(interaction: Interaction) {
if (interaction.isButton()) {
switch (interaction.customId) {
- case "rolemenu": { return await roleMenu(interaction); }
- case "verifybutton": { return await verify(interaction); }
- case "createticket": { return await create(interaction); }
- case "closeticket": { return await close(interaction); }
- case "createtranscript": { return await createTranscript(interaction); }
- case "suggestionAccept": { return await modifySuggestion(interaction, true); }
- case "suggestionDeny": { return await modifySuggestion(interaction, false); }
+ case "rolemenu": {
+ return await roleMenu(interaction);
+ }
+ case "verifybutton": {
+ return await verify(interaction);
+ }
+ case "createticket": {
+ return await create(interaction);
+ }
+ case "closeticket": {
+ return await close(interaction);
+ }
+ case "createtranscript": {
+ return await createTranscript(interaction);
+ }
+ case "suggestionAccept": {
+ return await modifySuggestion(interaction, true);
+ }
+ case "suggestionDeny": {
+ return await modifySuggestion(interaction, false);
+ }
}
}
}
@@ -32,7 +45,10 @@
if (message.embeds.length === 0) return;
const embed = message.embeds[0];
const newcolor = accept ? "Success" : "Danger";
- const footer = {text: `Suggestion ${accept ? "accepted" : "denied"} by ${interaction.user.tag}`, iconURL: interaction.user.displayAvatarURL()};
+ const footer = {
+ text: `Suggestion ${accept ? "accepted" : "denied"} by ${interaction.user.tag}`,
+ iconURL: interaction.user.displayAvatarURL()
+ };
const newEmbed = new EmojiEmbed()
.setTitle(embed!.title!)
@@ -40,7 +56,7 @@
.setFooter(footer)
.setStatus(newcolor);
- await interaction.update({embeds: [newEmbed], components: []});
+ await interaction.update({ embeds: [newEmbed], components: [] });
}
export async function callback(_client: NucleusClient, interaction: Interaction) {
diff --git a/src/events/inviteCreate.ts b/src/events/inviteCreate.ts
index 34f66dc..240965c 100644
--- a/src/events/inviteCreate.ts
+++ b/src/events/inviteCreate.ts
@@ -6,11 +6,12 @@
export const event = "inviteCreate";
export async function callback(client: NucleusClient, invite: Invite) {
- if(!invite.guild) return; // This is a DM invite (not a guild invite
+ if (!invite.guild) return; // This is a DM invite (not a guild invite
const { getAuditLog, isLogging, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger;
- if (!await isLogging(invite.guild.id, "guildUpdate")) return;
- const auditLog = (await getAuditLog(invite.guild as Guild, AuditLogEvent.InviteCreate))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as Invite)!.code === invite.code)[0]!;
+ if (!(await isLogging(invite.guild.id, "guildUpdate"))) return;
+ const auditLog = (await getAuditLog(invite.guild as Guild, AuditLogEvent.InviteCreate)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as Invite)!.code === invite.code
+ )[0]!;
if (auditLog.executor!.id === client.user!.id) return;
const data = {
meta: {
diff --git a/src/events/inviteDelete.ts b/src/events/inviteDelete.ts
index 456af90..81285c7 100644
--- a/src/events/inviteDelete.ts
+++ b/src/events/inviteDelete.ts
@@ -6,11 +6,12 @@
export const event = "inviteDelete";
export async function callback(client: NucleusClient, invite: Invite) {
- if(!invite.guild) return; // This is a DM invite (not a guild invite
+ if (!invite.guild) return; // This is a DM invite (not a guild invite
const { getAuditLog, isLogging, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger;
- if (!await isLogging(invite.guild.id, "guildUpdate")) return;
- const auditLog = (await getAuditLog(invite.guild as Guild, AuditLogEvent.InviteDelete))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as Invite)!.code === invite.code)[0]!;
+ if (!(await isLogging(invite.guild.id, "guildUpdate"))) return;
+ const auditLog = (await getAuditLog(invite.guild as Guild, AuditLogEvent.InviteDelete)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as Invite)!.code === invite.code
+ )[0]!;
if (auditLog.executor!.id === client.user!.id) return;
const data = {
meta: {
diff --git a/src/events/memberJoin.ts b/src/events/memberJoin.ts
index 77b111f..bdfd999 100644
--- a/src/events/memberJoin.ts
+++ b/src/events/memberJoin.ts
@@ -9,7 +9,7 @@
welcome(client, member);
statsChannelAdd(client, member);
const { log, isLogging, NucleusColors, entry, renderUser, renderDelta } = client.logger;
- if (!await isLogging(member.guild.id, "guildMemberUpdate")) return;
+ if (!(await isLogging(member.guild.id, "guildMemberUpdate"))) return;
await client.database.history.create("join", member.guild.id, member.user, null, null);
const data = {
meta: {
diff --git a/src/events/memberLeave.ts b/src/events/memberLeave.ts
index 8b3d1b1..c4ce74e 100644
--- a/src/events/memberLeave.ts
+++ b/src/events/memberLeave.ts
@@ -11,11 +11,13 @@
purgeByUser(member.id, member.guild.id);
await statsChannelRemove(client, member);
const { getAuditLog, isLogging, log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
- if (!await isLogging(member.guild.id, "guildMemberUpdate")) return;
- const kickAuditLog = (await getAuditLog(member.guild as Guild, AuditLogEvent.MemberKick))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as GuildMember)!.id === member.id)[0];
- const banAuditLog = (await getAuditLog(member.guild as Guild, AuditLogEvent.MemberBanAdd))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as GuildMember)!.id === member.id)[0];
+ if (!(await isLogging(member.guild.id, "guildMemberUpdate"))) return;
+ const kickAuditLog = (await getAuditLog(member.guild as Guild, AuditLogEvent.MemberKick)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as GuildMember)!.id === member.id
+ )[0];
+ const banAuditLog = (await getAuditLog(member.guild as Guild, AuditLogEvent.MemberBanAdd)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as GuildMember)!.id === member.id
+ )[0];
let type = "leave";
if (kickAuditLog) {
if (kickAuditLog.executor!.id === client.user!.id) return;
@@ -27,16 +29,22 @@
if (banAuditLog.executor!.id === client.user!.id) return;
if (banAuditLog.createdAt.getTime() >= startTime) {
if (!kickAuditLog) {
- return
+ return;
} else if (kickAuditLog.createdAt.valueOf() < banAuditLog.createdAt.valueOf()) {
- return
+ return;
}
}
}
let data;
if (type === "kick") {
if (!kickAuditLog) return;
- await client.database.history.create("kick", member.guild.id, member.user, kickAuditLog.executor, kickAuditLog.reason);
+ await client.database.history.create(
+ "kick",
+ member.guild.id,
+ member.user,
+ kickAuditLog.executor,
+ kickAuditLog.reason
+ );
data = {
meta: {
type: "memberKick",
@@ -52,7 +60,10 @@
joined: entry(member.joinedTimestamp, renderDelta(member.joinedTimestamp?.valueOf()!)),
kicked: entry(Date.now(), renderDelta(Date.now())),
kickedBy: entry(kickAuditLog.executor!.id, renderUser(kickAuditLog.executor!)),
- reason: entry(kickAuditLog.reason, kickAuditLog.reason ? `\n> ${kickAuditLog.reason}` : "*No reason provided.*"),
+ reason: entry(
+ kickAuditLog.reason,
+ kickAuditLog.reason ? `\n> ${kickAuditLog.reason}` : "*No reason provided.*"
+ ),
accountCreated: entry(member.user.createdTimestamp, renderDelta(member.user.createdTimestamp)),
serverMemberCount: member.guild.memberCount
},
diff --git a/src/events/messageCreate.ts b/src/events/messageCreate.ts
index 14ec7e5..b106d61 100644
--- a/src/events/messageCreate.ts
+++ b/src/events/messageCreate.ts
@@ -13,10 +13,11 @@
if (!message.guild) return;
const config = await client.memory.readGuildInfo(message.guild.id);
- if (config.autoPublish.enabled
- && config.autoPublish.channels.includes(message.channel.id)
- && message.channel.type === ChannelType.GuildAnnouncement
- && message.reference === null
+ if (
+ config.autoPublish.enabled &&
+ config.autoPublish.channels.includes(message.channel.id) &&
+ message.channel.type === ChannelType.GuildAnnouncement &&
+ message.reference === null
) {
await message.crosspost();
}
@@ -34,11 +35,11 @@
const fileNames = await logAttachment(message);
const content = message.content.toLowerCase() || "";
- if(config.filters.clean.channels.includes(message.channel.id)) {
- const memberRoles = message.member!.roles.cache.map(role => role.id);
- const roleAllow = config.filters.clean.allowed.roles.some(role => memberRoles.includes(role));
+ if (config.filters.clean.channels.includes(message.channel.id)) {
+ const memberRoles = message.member!.roles.cache.map((role) => role.id);
+ const roleAllow = config.filters.clean.allowed.roles.some((role) => memberRoles.includes(role));
const userAllow = config.filters.clean.allowed.users.includes(message.author.id);
- if(!roleAllow && !userAllow) return await message.delete();
+ if (!roleAllow && !userAllow) return await message.delete();
}
const filter = getEmojiByName("ICONS.FILTER");
@@ -94,7 +95,11 @@
if (fileNames.files.length > 0) {
for (const element of fileNames.files) {
const url = element.url ? element.url : element.local;
- if (/\.(j(pe?g|fif)|a?png|gifv?|w(eb[mp]|av)|mp([34]|eg-\d)|ogg|avi|h\.26(4|5)|cda)$/.test(url.toLowerCase())) {
+ if (
+ /\.(j(pe?g|fif)|a?png|gifv?|w(eb[mp]|av)|mp([34]|eg-\d)|ogg|avi|h\.26(4|5)|cda)$/.test(
+ url.toLowerCase()
+ )
+ ) {
// jpg|jpeg|png|apng|gif|gifv|webm|webp|mp4|wav|mp3|ogg|jfif|MPEG-#|avi|h.264|h.265
if (
config.filters.images.NSFW &&
@@ -288,7 +293,7 @@
}
if (config.filters.pings.everyone && message.mentions.everyone) {
- if(!await isLogging(message.guild.id, "messageMassPing")) return;
+ if (!(await isLogging(message.guild.id, "messageMassPing"))) return;
const data = {
meta: {
type: "everyonePing",
@@ -313,7 +318,7 @@
if (!config.filters.pings.allowed.roles.includes(roleId)) {
messageException(message.guild.id, message.channel.id, message.id);
await message.delete();
- if(!await isLogging(message.guild.id, "messageMassPing")) return;
+ if (!(await isLogging(message.guild.id, "messageMassPing"))) return;
const data = {
meta: {
type: "rolePing",
@@ -340,7 +345,7 @@
if (message.mentions.users.size >= config.filters.pings.mass && config.filters.pings.mass) {
messageException(message.guild.id, message.channel.id, message.id);
await message.delete();
- if(!await isLogging(message.guild.id, "messageMassPing")) return;
+ if (!(await isLogging(message.guild.id, "messageMassPing"))) return;
const data = {
meta: {
type: "massPing",
diff --git a/src/events/messageDelete.ts b/src/events/messageDelete.ts
index aac83f4..c29bfd0 100644
--- a/src/events/messageDelete.ts
+++ b/src/events/messageDelete.ts
@@ -8,9 +8,10 @@
if (message.author.bot) return;
if (client.noLog.includes(`${message.guild!.id}/${message.channel.id}/${message.id}`)) return;
const { getAuditLog, isLogging, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger;
- if (!await isLogging(message.guild!.id, "messageDelete")) return;
- const auditLog = (await getAuditLog(message.guild!, AuditLogEvent.MemberBanAdd))
- .filter((entry: GuildAuditLogsEntry) => (entry.target! as User).id === message.author.id)[0];
+ if (!(await isLogging(message.guild!.id, "messageDelete"))) return;
+ const auditLog = (await getAuditLog(message.guild!, AuditLogEvent.MemberBanAdd)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target! as User).id === message.author.id
+ )[0];
if (auditLog) {
if (auditLog.createdTimestamp - 1000 < Date.now()) return;
}
@@ -19,7 +20,8 @@
content.replace("`", "\\`");
if (content.length > 256) content = content.substring(0, 253) + "...";
const attachments =
- message.attachments.size + (
+ message.attachments.size +
+ (
message.content.match(
/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/gi
) ?? []
@@ -28,7 +30,9 @@
const config = (await client.database.guilds.read(message.guild!.id)).logging.attachments.saved[
message.channel.id + message.id
];
- if (config) { attachmentJump = ` [[View attachments]](${config})`; }
+ if (config) {
+ attachmentJump = ` [[View attachments]](${config})`;
+ }
const data = {
meta: {
type: "messageDelete",
@@ -44,14 +48,20 @@
list: {
messageId: entry(message.id, `\`${message.id}\``),
sentBy: entry(message.author.id, renderUser(message.author)),
- sentIn: entry(message.channel.id, renderChannel(message.channel as Discord.GuildChannel | Discord.ThreadChannel)),
+ sentIn: entry(
+ message.channel.id,
+ renderChannel(message.channel as Discord.GuildChannel | Discord.ThreadChannel)
+ ),
deleted: entry(Date.now(), renderDelta(Date.now())),
mentions: message.mentions.users.size,
attachments: entry(attachments, attachments + attachmentJump),
repliedTo: entry(
replyTo ? replyTo.messageId! : null,
- replyTo ? `[[Jump to message]](https://discord.com/channels/${message.guild!.id}/${message.channel.id}/${replyTo.messageId})`
- : "None"
+ replyTo
+ ? `[[Jump to message]](https://discord.com/channels/${message.guild!.id}/${message.channel.id}/${
+ replyTo.messageId
+ })`
+ : "None"
)
},
hidden: {
diff --git a/src/events/messageEdit.ts b/src/events/messageEdit.ts
index f5a28a4..3b7f482 100644
--- a/src/events/messageEdit.ts
+++ b/src/events/messageEdit.ts
@@ -8,8 +8,9 @@
if (newMessage.author.id === client.user!.id) return;
if (newMessage.author.bot) return;
if (!newMessage.guild) return;
- const { log, isLogging, NucleusColors, entry, renderUser, renderDelta, renderNumberDelta, renderChannel } = client.logger;
-
+ const { log, isLogging, NucleusColors, entry, renderUser, renderDelta, renderNumberDelta, renderChannel } =
+ client.logger;
+
const replyTo: MessageReference | null = newMessage.reference;
let newContent = newMessage.cleanContent.replaceAll("`", "‘");
let oldContent = oldMessage.cleanContent.replaceAll("`", "‘");
@@ -21,7 +22,7 @@
attachmentJump = ` [[View attachments]](${config})`;
}
if (newMessage.crosspostable !== oldMessage.crosspostable) {
- if(!await isLogging(newMessage.guild.id, "messageAnnounce")) return;
+ if (!(await isLogging(newMessage.guild.id, "messageAnnounce"))) return;
if (!replyTo) {
const data = {
meta: {
@@ -38,15 +39,12 @@
list: {
messageId: entry(newMessage.id, `\`${newMessage.id}\``),
sentBy: entry(newMessage.author.id, renderUser(newMessage.author)),
- sentIn: entry(newMessage.channel.id, renderChannel(newMessage.channel as Discord.GuildBasedChannel)),
- sent: entry(
- newMessage.createdTimestamp,
- renderDelta(newMessage.createdTimestamp)
+ sentIn: entry(
+ newMessage.channel.id,
+ renderChannel(newMessage.channel as Discord.GuildBasedChannel)
),
- published: entry(
- newMessage.editedTimestamp!,
- renderDelta(newMessage.editedTimestamp!)
- ),
+ sent: entry(newMessage.createdTimestamp, renderDelta(newMessage.createdTimestamp)),
+ published: entry(newMessage.editedTimestamp!, renderDelta(newMessage.editedTimestamp!)),
mentions: renderNumberDelta(oldMessage.mentions.users.size, newMessage.mentions.users.size),
attachments: entry(
renderNumberDelta(oldMessage.attachments.size, newMessage.attachments.size),
@@ -60,7 +58,7 @@
return log(data);
}
}
- if (!await isLogging(newMessage.guild.id, "messageUpdate")) return;
+ if (!(await isLogging(newMessage.guild.id, "messageUpdate"))) return;
if (!newMessage.editedTimestamp) {
return;
}
diff --git a/src/events/roleCreate.ts b/src/events/roleCreate.ts
index be385f0..9b900f8 100644
--- a/src/events/roleCreate.ts
+++ b/src/events/roleCreate.ts
@@ -5,10 +5,11 @@
export async function callback(client: NucleusClient, role: Role) {
const { getAuditLog, isLogging, log, NucleusColors, entry, renderUser, renderDelta, renderRole } = client.logger;
- if (!await isLogging(role.guild.id, "guildRoleUpdate")) return;
+ if (!(await isLogging(role.guild.id, "guildRoleUpdate"))) return;
if (role.managed) return;
- const auditLog = (await getAuditLog(role.guild as Guild, AuditLogEvent.RoleCreate))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as Role)!.id === role.id)[0]!;
+ const auditLog = (await getAuditLog(role.guild as Guild, AuditLogEvent.RoleCreate)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as Role)!.id === role.id
+ )[0]!;
if (auditLog.executor!.id === client.user!.id) return;
const data = {
meta: {
diff --git a/src/events/roleDelete.ts b/src/events/roleDelete.ts
index b207f4f..e83d557 100644
--- a/src/events/roleDelete.ts
+++ b/src/events/roleDelete.ts
@@ -6,10 +6,11 @@
export async function callback(client: NucleusClient, role: Role) {
const { getAuditLog, isLogging, log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
- if (!await isLogging(role.guild.id, "guildRoleUpdate")) return;
+ if (!(await isLogging(role.guild.id, "guildRoleUpdate"))) return;
if (role.managed) return;
- const auditLog = (await getAuditLog(role.guild as Guild, AuditLogEvent.RoleDelete))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as Role)!.id === role.id)[0]!;
+ const auditLog = (await getAuditLog(role.guild as Guild, AuditLogEvent.RoleDelete)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as Role)!.id === role.id
+ )[0]!;
if (auditLog.executor!.id === client.user!.id) return;
const data = {
meta: {
diff --git a/src/events/roleUpdate.ts b/src/events/roleUpdate.ts
index 8d9ef10..236bc0f 100644
--- a/src/events/roleUpdate.ts
+++ b/src/events/roleUpdate.ts
@@ -6,9 +6,10 @@
export async function callback(client: NucleusClient, oldRole: Role, newRole: Role) {
const { getAuditLog, isLogging, log, NucleusColors, entry, renderDelta, renderUser, renderRole } = client.logger;
- if (!await isLogging(newRole.guild.id, "guildRoleUpdate")) return;
- const auditLog = (await getAuditLog(newRole.guild as Guild, AuditLogEvent.RoleUpdate))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as Role)!.id === newRole.id)[0];
+ if (!(await isLogging(newRole.guild.id, "guildRoleUpdate"))) return;
+ const auditLog = (await getAuditLog(newRole.guild as Guild, AuditLogEvent.RoleUpdate)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as Role)!.id === newRole.id
+ )[0];
if (!auditLog) return;
if (auditLog.executor!.id === client.user!.id) return;
@@ -16,22 +17,40 @@
roleId: entry(newRole.id, `\`${newRole.id}\``),
role: entry(newRole.id, renderRole(newRole)),
edited: entry(Date.now(), renderDelta(Date.now())),
- editedBy: entry(auditLog.executor!.id, renderUser((await newRole.guild.members.fetch(auditLog.executor!.id)).user))
+ editedBy: entry(
+ auditLog.executor!.id,
+ renderUser((await newRole.guild.members.fetch(auditLog.executor!.id)).user)
+ )
};
const mentionable = ["", ""];
const hoist = ["", ""];
- mentionable[0] = oldRole.mentionable ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`;
- mentionable[1] = newRole.mentionable ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`;
+ mentionable[0] = oldRole.mentionable
+ ? `${getEmojiByName("CONTROL.TICK")} Yes`
+ : `${getEmojiByName("CONTROL.CROSS")} No`;
+ mentionable[1] = newRole.mentionable
+ ? `${getEmojiByName("CONTROL.TICK")} Yes`
+ : `${getEmojiByName("CONTROL.CROSS")} No`;
hoist[0] = oldRole.hoist ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`;
hoist[1] = newRole.hoist ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`;
- if (oldRole.name !== newRole.name) changes["name"] = entry([oldRole.name, newRole.name], `${oldRole.name} -> ${newRole.name}`);
+ if (oldRole.name !== newRole.name)
+ changes["name"] = entry([oldRole.name, newRole.name], `${oldRole.name} -> ${newRole.name}`);
if (oldRole.position !== newRole.position)
- changes["position"] = entry([oldRole.position.toString(), newRole.position.toString()], `${oldRole.position} -> ${newRole.position}`);
- if (oldRole.hoist !== newRole.hoist) changes["showInMemberList"] = entry([oldRole.hoist, newRole.hoist], `${hoist[0]} -> ${hoist[1]}`);
+ changes["position"] = entry(
+ [oldRole.position.toString(), newRole.position.toString()],
+ `${oldRole.position} -> ${newRole.position}`
+ );
+ if (oldRole.hoist !== newRole.hoist)
+ changes["showInMemberList"] = entry([oldRole.hoist, newRole.hoist], `${hoist[0]} -> ${hoist[1]}`);
if (oldRole.mentionable !== newRole.mentionable)
- changes["mentionable"] = entry([oldRole.mentionable, newRole.mentionable], `${mentionable[0]} -> ${mentionable[1]}`);
+ changes["mentionable"] = entry(
+ [oldRole.mentionable, newRole.mentionable],
+ `${mentionable[0]} -> ${mentionable[1]}`
+ );
if (oldRole.hexColor !== newRole.hexColor)
- changes["color"] = entry([oldRole.hexColor, newRole.hexColor], `\`${oldRole.hexColor}\` -> \`${newRole.hexColor}\``);
+ changes["color"] = entry(
+ [oldRole.hexColor, newRole.hexColor],
+ `\`${oldRole.hexColor}\` -> \`${newRole.hexColor}\``
+ );
if (oldRole.permissions.bitfield !== newRole.permissions.bitfield) {
changes["permissions"] = entry(
[oldRole.permissions.bitfield.toString(), newRole.permissions.bitfield.toString()],
diff --git a/src/events/stickerCreate.ts b/src/events/stickerCreate.ts
index 5d2e443..01944fc 100644
--- a/src/events/stickerCreate.ts
+++ b/src/events/stickerCreate.ts
@@ -6,9 +6,10 @@
export async function callback(client: NucleusClient, sticker: Sticker) {
const { getAuditLog, isLogging, log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
- if (!await isLogging(sticker.guild!.id, "stickerUpdate")) return;
- const auditLog = (await getAuditLog(sticker.guild!, AuditLogEvent.StickerCreate))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as Sticker)!.id === sticker.id)[0]!;
+ if (!(await isLogging(sticker.guild!.id, "stickerUpdate"))) return;
+ const auditLog = (await getAuditLog(sticker.guild!, AuditLogEvent.StickerCreate)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as Sticker)!.id === sticker.id
+ )[0]!;
if (auditLog.executor!.id === client.user!.id) return;
if (client.noLog.includes(`${sticker.guild!.id}${auditLog.id}`)) return;
generalException(`${sticker.guild!.id}${auditLog.id}`);
diff --git a/src/events/stickerDelete.ts b/src/events/stickerDelete.ts
index d123f44..a348b73 100644
--- a/src/events/stickerDelete.ts
+++ b/src/events/stickerDelete.ts
@@ -5,9 +5,10 @@
export async function callback(client: NucleusClient, sticker: Sticker) {
const { getAuditLog, isLogging, log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
- if (!await isLogging(sticker.guild!.id, "stickerUpdate")) return;
- const auditLog = (await getAuditLog(sticker.guild!, AuditLogEvent.StickerDelete))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as Sticker)!.id === sticker.id)[0]!;
+ if (!(await isLogging(sticker.guild!.id, "stickerUpdate"))) return;
+ const auditLog = (await getAuditLog(sticker.guild!, AuditLogEvent.StickerDelete)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as Sticker)!.id === sticker.id
+ )[0]!;
if (auditLog.executor!.id === client.user!.id) return;
const data = {
meta: {
diff --git a/src/events/stickerUpdate.ts b/src/events/stickerUpdate.ts
index aef28a4..c42f775 100644
--- a/src/events/stickerUpdate.ts
+++ b/src/events/stickerUpdate.ts
@@ -5,16 +5,20 @@
export async function callback(client: NucleusClient, oldSticker: Sticker, newSticker: Sticker) {
const { getAuditLog, isLogging, log, NucleusColors, entry, renderDelta, renderUser } = client.logger;
- if (!await isLogging(newSticker.guild!.id, "stickerUpdate")) return;
+ if (!(await isLogging(newSticker.guild!.id, "stickerUpdate"))) return;
if (oldSticker.name === newSticker.name) return;
- const auditLog = (await getAuditLog(newSticker.guild!, AuditLogEvent.StickerUpdate))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as Sticker)!.id === newSticker.id)[0]!;
+ const auditLog = (await getAuditLog(newSticker.guild!, AuditLogEvent.StickerUpdate)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as Sticker)!.id === newSticker.id
+ )[0]!;
if (auditLog.executor!.id === client.user!.id) return;
const changes = {
stickerId: entry(newSticker.id, `\`${newSticker.id}\``),
edited: entry(newSticker.createdTimestamp, renderDelta(newSticker.createdTimestamp)),
- editedBy: entry(auditLog.executor!.id, renderUser((await newSticker.guild!.members.fetch(auditLog.executor!.id)).user)),
+ editedBy: entry(
+ auditLog.executor!.id,
+ renderUser((await newSticker.guild!.members.fetch(auditLog.executor!.id)).user)
+ ),
name: entry([oldSticker.name, newSticker.name], `\`:${oldSticker.name}:\` -> \`:${newSticker.name}:\``)
};
const data = {
diff --git a/src/events/threadCreate.ts b/src/events/threadCreate.ts
index f56e1bb..cefaf3b 100644
--- a/src/events/threadCreate.ts
+++ b/src/events/threadCreate.ts
@@ -6,9 +6,10 @@
export async function callback(client: NucleusClient, thread: ThreadChannel) {
const { getAuditLog, isLogging, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger;
- if (!await isLogging(thread.guild.id, "channelUpdate")) return;
- const auditLog = (await getAuditLog(thread.guild, AuditLogEvent.ThreadCreate))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as ThreadChannel)!.id === thread.id)[0]!;
+ if (!(await isLogging(thread.guild.id, "channelUpdate"))) return;
+ const auditLog = (await getAuditLog(thread.guild, AuditLogEvent.ThreadCreate)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as ThreadChannel)!.id === thread.id
+ )[0]!;
if (auditLog.executor!.id === client.user!.id) return;
const category = thread.parent
? entry(
diff --git a/src/events/threadDelete.ts b/src/events/threadDelete.ts
index bfac75e..ecbf4cf 100644
--- a/src/events/threadDelete.ts
+++ b/src/events/threadDelete.ts
@@ -6,9 +6,10 @@
export async function callback(client: NucleusClient, thread: ThreadChannel) {
const { getAuditLog, isLogging, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger;
- if (!await isLogging(thread.guild.id, "channelUpdate")) return;
- const auditLog = (await getAuditLog(thread.guild, AuditLogEvent.ThreadDelete))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as ThreadChannel)!.id === thread.id)[0]!;
+ if (!(await isLogging(thread.guild.id, "channelUpdate"))) return;
+ const auditLog = (await getAuditLog(thread.guild, AuditLogEvent.ThreadDelete)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as ThreadChannel)!.id === thread.id
+ )[0]!;
if (auditLog.executor!.id === client.user!.id) return;
const category = thread.parent
? entry(
diff --git a/src/events/threadUpdate.ts b/src/events/threadUpdate.ts
index af792bc..510ec30 100644
--- a/src/events/threadUpdate.ts
+++ b/src/events/threadUpdate.ts
@@ -7,9 +7,10 @@
export async function callback(client: NucleusClient, oldThread: ThreadChannel, newThread: ThreadChannel) {
const { getAuditLog, isLogging, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger;
- if (!await isLogging(newThread.guild.id, "channelUpdate")) return;
- const auditLog = (await getAuditLog(newThread.guild, AuditLogEvent.ThreadUpdate))
- .filter((entry: GuildAuditLogsEntry) => (entry.target as ThreadChannel)!.id === newThread.id)[0]!;
+ if (!(await isLogging(newThread.guild.id, "channelUpdate"))) return;
+ const auditLog = (await getAuditLog(newThread.guild, AuditLogEvent.ThreadUpdate)).filter(
+ (entry: GuildAuditLogsEntry) => (entry.target as ThreadChannel)!.id === newThread.id
+ )[0]!;
if (auditLog.executor!.id === client.user!.id) return;
const list: Record<string, ReturnType<typeof entry>> = {
threadId: entry(newThread.id, `\`${newThread.id}\``),
diff --git a/src/events/webhookUpdate.ts b/src/events/webhookUpdate.ts
index 004f754..438c66e 100644
--- a/src/events/webhookUpdate.ts
+++ b/src/events/webhookUpdate.ts
@@ -10,14 +10,21 @@
export async function callback(client: NucleusClient, channel: Discord.GuildChannel) {
try {
- const { getAuditLog, isLogging, log, NucleusColors, entry, renderUser, renderChannel, renderDelta } = client.logger;
- if (!await isLogging(channel.guild.id, "webhookUpdate")) return;
- const auditCreate = (await getAuditLog(channel.guild, AuditLogEvent.WebhookCreate))
- .filter((entry: GuildAuditLogsEntry | null) => (entry?.target) ? (entry.target as Webhook)!.channelId === channel.id : false)[0];
- const auditDelete = (await getAuditLog(channel.guild, AuditLogEvent.WebhookDelete, 0))
- .filter((entry: GuildAuditLogsEntry | null) => (entry?.target) ? (entry.target as Webhook)!.channelId === channel.id : false)[0];
- const auditUpdate = (await getAuditLog(channel.guild, AuditLogEvent.WebhookUpdate, 0))
- .filter((entry: GuildAuditLogsEntry | null) => (entry?.target) ? (entry.target as Webhook)!.channelId === channel.id : false)[0];
+ const { getAuditLog, isLogging, log, NucleusColors, entry, renderUser, renderChannel, renderDelta } =
+ client.logger;
+ if (!(await isLogging(channel.guild.id, "webhookUpdate"))) return;
+ const auditCreate = (await getAuditLog(channel.guild, AuditLogEvent.WebhookCreate)).filter(
+ (entry: GuildAuditLogsEntry | null) =>
+ entry?.target ? (entry.target as Webhook)!.channelId === channel.id : false
+ )[0];
+ const auditDelete = (await getAuditLog(channel.guild, AuditLogEvent.WebhookDelete, 0)).filter(
+ (entry: GuildAuditLogsEntry | null) =>
+ entry?.target ? (entry.target as Webhook)!.channelId === channel.id : false
+ )[0];
+ const auditUpdate = (await getAuditLog(channel.guild, AuditLogEvent.WebhookUpdate, 0)).filter(
+ (entry: GuildAuditLogsEntry | null) =>
+ entry?.target ? (entry.target as Webhook)!.channelId === channel.id : false
+ )[0];
if (!auditCreate && !auditUpdate && !auditDelete) return;
let action: "Create" | "Update" | "Delete" = "Create";
let list: Record<string, ReturnType<typeof entry> | string> = {};
@@ -25,7 +32,8 @@
const deleteTimestamp = auditDelete ? auditDelete.createdTimestamp : 0;
const updateTimestamp = auditUpdate ? auditUpdate.createdTimestamp : 0;
if (updateTimestamp > createTimestamp && updateTimestamp > deleteTimestamp && auditUpdate) {
- const { before, after } = auditUpdate.changes.reduce((acc: accType, change) => {
+ const { before, after } = auditUpdate.changes.reduce(
+ (acc: accType, change) => {
acc.before[change.key] = change.old?.toString()!;
acc.after[change.key] = change.new?.toString()!;
return acc;
@@ -37,20 +45,23 @@
if (before["channel_id"] !== after["channel_id"])
list["channel"] = entry(
[before["channel_id"]!, after["channel_id"]!],
- renderChannel(await client.channels.fetch(before["channel_id"]!) as GuildChannel) +
+ renderChannel((await client.channels.fetch(before["channel_id"]!)) as GuildChannel) +
" -> " +
- renderChannel(await client.channels.fetch(after["channel_id"]!) as GuildChannel)
+ renderChannel((await client.channels.fetch(after["channel_id"]!)) as GuildChannel)
);
if (!Object.keys(list).length) return;
list["created"] = entry(
- (auditUpdate.target! as Extract<GuildAuditLogsEntry, {createdTimestamp: number}>).createdTimestamp,
- renderDelta((auditUpdate.target! as Extract<GuildAuditLogsEntry, {createdTimestamp: number}>).createdTimestamp)
+ (auditUpdate.target! as Extract<GuildAuditLogsEntry, { createdTimestamp: number }>).createdTimestamp,
+ renderDelta(
+ (auditUpdate.target! as Extract<GuildAuditLogsEntry, { createdTimestamp: number }>).createdTimestamp
+ )
);
list["edited"] = entry(after["editedTimestamp"]!, renderDelta(Date.now()));
list["editedBy"] = entry(auditUpdate.executor!.id, renderUser(auditUpdate.executor!));
action = "Update";
} else if (deleteTimestamp > createTimestamp && deleteTimestamp > updateTimestamp && auditDelete) {
- const { before } = auditDelete.changes.reduce((acc: accType, change) => {
+ const { before } = auditDelete.changes.reduce(
+ (acc: accType, change) => {
acc.before[change.key] = change.old?.toString()!;
acc.after[change.key] = change.new?.toString()!;
return acc;
@@ -59,8 +70,18 @@
);
list = {
name: entry(before["name"]!, `${before["name"]}`),
- channel: entry(before["channel_id"]!, renderChannel((await client.channels.fetch(before["channel_id"]!)) as GuildChannel)),
- created: entry((auditDelete.target! as Extract<GuildAuditLogsEntry, {createdTimestamp: number}>).createdTimestamp, renderDelta((auditDelete.target! as Extract<GuildAuditLogsEntry, {createdTimestamp: number}>).createdTimestamp)),
+ channel: entry(
+ before["channel_id"]!,
+ renderChannel((await client.channels.fetch(before["channel_id"]!)) as GuildChannel)
+ ),
+ created: entry(
+ (auditDelete.target! as Extract<GuildAuditLogsEntry, { createdTimestamp: number }>)
+ .createdTimestamp,
+ renderDelta(
+ (auditDelete.target! as Extract<GuildAuditLogsEntry, { createdTimestamp: number }>)
+ .createdTimestamp
+ )
+ ),
deleted: entry(Date.now(), renderDelta(Date.now())),
deletedBy: entry(
auditDelete.executor!.id,
@@ -69,7 +90,8 @@
};
action = "Delete";
} else {
- const { before } = auditDelete!.changes.reduce((acc: accType, change) => {
+ const { before } = auditDelete!.changes.reduce(
+ (acc: accType, change) => {
acc.before[change.key] = change.old?.toString()!;
acc.after[change.key] = change.new?.toString()!;
return acc;
@@ -78,7 +100,10 @@
);
list = {
name: entry(before["name"]!, `${before["name"]}`),
- channel: entry(before["channel_id"]!, renderChannel(await client.channels.fetch(before["channel_id"]!) as GuildChannel)),
+ channel: entry(
+ before["channel_id"]!,
+ renderChannel((await client.channels.fetch(before["channel_id"]!)) as GuildChannel)
+ ),
createdBy: entry(
auditCreate!.executor!.id,
renderUser((await channel.guild.members.fetch(auditCreate!.executor!.id)).user)
diff --git a/src/index.ts b/src/index.ts
index ddcd97b..3d0972d 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -18,9 +18,13 @@
await client.database.premium.checkAllPremium();
});
-process.on("unhandledRejection", (err) => { console.error(err) });
-process.on("uncaughtException", (err) => { console.error(err) });
+process.on("unhandledRejection", (err) => {
+ console.error(err);
+});
+process.on("uncaughtException", (err) => {
+ console.error(err);
+});
-await client.login(config.enableDevelopment ? config.developmentToken : config.token)
+await client.login(config.enableDevelopment ? config.developmentToken : config.token);
await recordPerformance();
diff --git a/src/premium/attachmentLogs.ts b/src/premium/attachmentLogs.ts
index b2c8391..e719f22 100644
--- a/src/premium/attachmentLogs.ts
+++ b/src/premium/attachmentLogs.ts
@@ -1,4 +1,4 @@
-import { getCommandMentionByName } from './../utils/getCommandDataByName.js';
+import { getCommandMentionByName } from "./../utils/getCommandDataByName.js";
import client from "../utils/client.js";
import keyValueList from "../utils/generateKeyValueList.js";
import singleNotify from "../utils/singleNotify.js";
@@ -39,7 +39,9 @@
singleNotify(
"noAttachmentLogChannel",
message.guild.id,
- `No channel set for attachment logging. You can set one with ${getCommandMentionByName("settings/logs/attachments")}`,
+ `No channel set for attachment logging. You can set one with ${getCommandMentionByName(
+ "settings/logs/attachments"
+ )}`,
"Warning"
);
return { files: attachments };
@@ -49,7 +51,9 @@
singleNotify(
"attachmentLogChannelDeleted",
message.guild.id,
- `Your attachment history channel was deleted or is not longer accessible. You can set a new one with ${getCommandMentionByName("settings/logs/attachments")}`,
+ `Your attachment history channel was deleted or is not longer accessible. You can set a new one with ${getCommandMentionByName(
+ "settings/logs/attachments"
+ )}`,
"Warning"
);
return { files: attachments };
@@ -63,7 +67,7 @@
messageId: `\`${message.id}\``,
sentBy: renderUser(message.author),
sentIn: renderChannel(message.channel as GuildTextBasedChannel),
- sent: renderDelta((new Date(message.createdTimestamp)).getTime())
+ sent: renderDelta(new Date(message.createdTimestamp).getTime())
}) + `\n[[Jump to message]](${message.url})`
)
.setEmoji("ICONS.ATTACHMENT")
diff --git a/src/premium/createTranscript.ts b/src/premium/createTranscript.ts
index cdbc7b9..e7a0171 100644
--- a/src/premium/createTranscript.ts
+++ b/src/premium/createTranscript.ts
@@ -13,13 +13,13 @@
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
import getEmojiByName from "../utils/getEmojiByName.js";
import client from "../utils/client.js";
-import { messageException } from '../utils/createTemporaryStorage.js';
+import { messageException } from "../utils/createTemporaryStorage.js";
const noTopic = new EmojiEmbed()
.setTitle("User not found")
.setDescription("There is no user associated with this ticket.")
.setStatus("Danger")
- .setEmoji("CONTROL.BLOCKCROSS")
+ .setEmoji("CONTROL.BLOCKCROSS");
export default async function (interaction: CommandInteraction | MessageComponentInteraction) {
if (interaction.channel === null) return;
@@ -34,17 +34,16 @@
const deleted = await (interaction.channel as TextChannel).bulkDelete(fetched, true);
deletedCount = deleted.size;
messages = messages.concat(Array.from(deleted.values() as Iterable<Message>));
- if (messages.length === 1) messageException(interaction.guild!.id, interaction.channel.id, messages[0]!.id)
+ if (messages.length === 1) messageException(interaction.guild!.id, interaction.channel.id, messages[0]!.id);
} while (deletedCount === 100);
- messages = messages.filter(message => !(
- message.components.some(
- component => component.components.some(
- child => child.customId?.includes("transcript") ?? false
+ messages = messages.filter(
+ (message) =>
+ !message.components.some((component) =>
+ component.components.some((child) => child.customId?.includes("transcript") ?? false)
)
- )
- ));
+ );
- let topic
+ let topic;
let member: GuildMember = interaction.guild?.members.me!;
if (interaction.channel instanceof TextChannel) {
topic = interaction.channel.topic;
@@ -53,23 +52,24 @@
if (mem) member = mem;
} else {
topic = interaction.channel.name;
- const split = topic.split("-").map(p => p.trim()) as [string, string, string];
- const mem = interaction.guild!.members.cache.get(split[1])
+ const split = topic.split("-").map((p) => p.trim()) as [string, string, string];
+ const mem = interaction.guild!.members.cache.get(split[1]);
if (mem) member = mem;
}
const newOut = await client.database.transcripts.createTranscript(messages, interaction, member);
const [code, key, iv] = await client.database.transcripts.create(newOut);
- if(!code) return await interaction.reply({
- embeds: [
- new EmojiEmbed()
- .setTitle("Error")
- .setDescription("An error occurred while creating the transcript.")
- .setStatus("Danger")
- .setEmoji("CONTROL.BLOCKCROSS")
- ]
- })
+ if (!code)
+ return await interaction.reply({
+ embeds: [
+ new EmojiEmbed()
+ .setTitle("Error")
+ .setDescription("An error occurred while creating the transcript.")
+ .setStatus("Danger")
+ .setEmoji("CONTROL.BLOCKCROSS")
+ ]
+ });
const guildConfig = await client.database.guilds.read(interaction.guild!.id);
const m: Message = (await interaction.reply({
embeds: [
@@ -86,7 +86,10 @@
],
components: [
new ActionRowBuilder<ButtonBuilder>().addComponents([
- new ButtonBuilder().setLabel("View").setStyle(ButtonStyle.Link).setURL(`https://testing.coded.codes/nucleus/transcript/${code}?key=${key}&iv=${iv}`),
+ new ButtonBuilder()
+ .setLabel("View")
+ .setStyle(ButtonStyle.Link)
+ .setURL(`https://testing.coded.codes/nucleus/transcript/${code}?key=${key}&iv=${iv}`),
new ButtonBuilder()
.setLabel("Delete")
.setStyle(ButtonStyle.Danger)
@@ -100,7 +103,13 @@
try {
i = await m.awaitMessageComponent({
time: 300000,
- filter: (i) => { return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id && i.message.id === m.id }
+ filter: (i) => {
+ return (
+ i.user.id === interaction.user.id &&
+ i.channel!.id === interaction.channel!.id &&
+ i.message.id === m.id
+ );
+ }
});
await i.deferUpdate();
} catch {
diff --git a/src/reflex/guide.ts b/src/reflex/guide.ts
index a3027e4..1901d34 100644
--- a/src/reflex/guide.ts
+++ b/src/reflex/guide.ts
@@ -1,4 +1,4 @@
-import { getCommandMentionByName } from './../utils/getCommandDataByName.js';
+import { getCommandMentionByName } from "./../utils/getCommandDataByName.js";
import { LoadingEmbed } from "../utils/defaults.js";
import Discord, {
ActionRowBuilder,
@@ -19,19 +19,19 @@
export default async (guild: Guild, interaction?: CommandInteraction) => {
let c: GuildTextBasedChannel | null = guild.publicUpdatesChannel ? guild.publicUpdatesChannel : guild.systemChannel;
c = c
- ? c
- : (guild.channels.cache.find(
- (ch) =>
- [
- ChannelType.GuildText,
- ChannelType.GuildAnnouncement,
- ChannelType.PublicThread,
- ChannelType.PrivateThread,
- ChannelType.AnnouncementThread
- ].includes(ch.type) &&
- ch.permissionsFor(guild.roles.everyone).has("SendMessages") &&
- ch.permissionsFor(guild.members.me!).has("EmbedLinks")
- ) as GuildTextBasedChannel | undefined) ?? null;
+ ? c
+ : (guild.channels.cache.find(
+ (ch) =>
+ [
+ ChannelType.GuildText,
+ ChannelType.GuildAnnouncement,
+ ChannelType.PublicThread,
+ ChannelType.PrivateThread,
+ ChannelType.AnnouncementThread
+ ].includes(ch.type) &&
+ ch.permissionsFor(guild.roles.everyone).has("SendMessages") &&
+ ch.permissionsFor(guild.members.me!).has("EmbedLinks")
+ ) as GuildTextBasedChannel | undefined) ?? null;
if (interaction) c = interaction.channel as GuildTextBasedChannel;
if (!c) {
return;
@@ -71,12 +71,22 @@
"Nucleus can log server events and keep you informed with what content is being posted to your server.\n" +
"We have 2 different types of logs, which each can be configured to send to a channel of your choice:\n" +
"**General:** These are events like kicks and channel changes etc.\n" +
- `> These are standard logs and can be set with ${getCommandMentionByName("settings/logs/general")}\n` +
+ `> These are standard logs and can be set with ${getCommandMentionByName(
+ "settings/logs/general"
+ )}\n` +
"**Warnings:** Warnings like NSFW avatars and spam etc. that may require action by a server staff member.\n" +
- `> These may require special action by a moderator. You can set the channel with ${getCommandMentionByName("settings/logs/warnings")}\n` +
+ `> These may require special action by a moderator. You can set the channel with ${getCommandMentionByName(
+ "settings/logs/warnings"
+ )}\n` +
"**Attachments:** All images sent in the server - Used to keep a record of deleted images\n" +
- `> Sent to a separate log channel to avoid spam. This can be set with ${getCommandMentionByName("settings/logs/attachments")}\n` +
- `> ${getEmojiByName("NUCLEUS.PREMIUM")} Please note this feature is only available with ${getCommandMentionByName("nucleus/premium")}`
+ `> Sent to a separate log channel to avoid spam. This can be set with ${getCommandMentionByName(
+ "settings/logs/attachments"
+ )}\n` +
+ `> ${getEmojiByName(
+ "NUCLEUS.PREMIUM"
+ )} Please note this feature is only available with ${getCommandMentionByName(
+ "nucleus/premium"
+ )}`
)
.setEmoji("ICONS.LOGGING")
.setStatus("Danger")
@@ -90,15 +100,33 @@
.setTitle("Moderation")
.setDescription(
"Nucleus has a number of commands that can be used to moderate your server.\n" +
- `These commands are all found under ${getCommandMentionByName(("mod"))}, and they include:\n` +
- `${getEmojiByName("PUNISH.WARN.YELLOW")} ${getCommandMentionByName("mod/warn")}: The user is warned (via DM) that they violated server rules. More options given if DMs are disabled.\n` +
- `${getEmojiByName("PUNISH.CLEARHISTORY")} ${getCommandMentionByName("mod/purge")}: Deletes messages in a channel, giving options to only delete messages by a certain user.\n` +
- `${getEmojiByName("PUNISH.MUTE.YELLOW")} ${getCommandMentionByName("mod/mute")}: Stops users sending messages or joining voice chats.\n` +
- `${getEmojiByName("PUNISH.MUTE.GREEN")} ${getCommandMentionByName("mod/unmute")}: Allows user to send messages and join voice chats.\n` +
- `${getEmojiByName("PUNISH.KICK.RED")} ${getCommandMentionByName("mod/kick")}: Removes a member from the server. They will be able to rejoin.\n` +
- `${getEmojiByName("PUNISH.SOFTBAN")} ${getCommandMentionByName("mod/softban")}: Kicks the user, deleting their messages from every channel in a given time frame.\n` +
- `${getEmojiByName("PUNISH.BAN.RED")} ${getCommandMentionByName("mod/ban")}: Removes the user from the server, deleting messages from every channel and stops them from rejoining.\n` +
- `${getEmojiByName("PUNISH.BAN.GREEN")} ${getCommandMentionByName("mod/unban")}: Allows a member to rejoin the server after being banned.`
+ `These commands are all found under ${getCommandMentionByName(
+ "mod"
+ )}, and they include:\n` +
+ `${getEmojiByName("PUNISH.WARN.YELLOW")} ${getCommandMentionByName(
+ "mod/warn"
+ )}: The user is warned (via DM) that they violated server rules. More options given if DMs are disabled.\n` +
+ `${getEmojiByName("PUNISH.CLEARHISTORY")} ${getCommandMentionByName(
+ "mod/purge"
+ )}: Deletes messages in a channel, giving options to only delete messages by a certain user.\n` +
+ `${getEmojiByName("PUNISH.MUTE.YELLOW")} ${getCommandMentionByName(
+ "mod/mute"
+ )}: Stops users sending messages or joining voice chats.\n` +
+ `${getEmojiByName("PUNISH.MUTE.GREEN")} ${getCommandMentionByName(
+ "mod/unmute"
+ )}: Allows user to send messages and join voice chats.\n` +
+ `${getEmojiByName("PUNISH.KICK.RED")} ${getCommandMentionByName(
+ "mod/kick"
+ )}: Removes a member from the server. They will be able to rejoin.\n` +
+ `${getEmojiByName("PUNISH.SOFTBAN")} ${getCommandMentionByName(
+ "mod/softban"
+ )}: Kicks the user, deleting their messages from every channel in a given time frame.\n` +
+ `${getEmojiByName("PUNISH.BAN.RED")} ${getCommandMentionByName(
+ "mod/ban"
+ )}: Removes the user from the server, deleting messages from every channel and stops them from rejoining.\n` +
+ `${getEmojiByName("PUNISH.BAN.GREEN")} ${getCommandMentionByName(
+ "mod/unban"
+ )}: Allows a member to rejoin the server after being banned.`
)
.setEmoji("PUNISH.BAN.RED")
.setStatus("Danger")
@@ -112,7 +140,9 @@
.setTitle("Verify")
.setDescription(
"Nucleus has a verification system that allows users to prove they aren't bots.\n" +
- `This is done by running ${getCommandMentionByName("verify")} which sends a message only the user can see, giving them a link to a website to verify.\n` +
+ `This is done by running ${getCommandMentionByName(
+ "verify"
+ )} which sends a message only the user can see, giving them a link to a website to verify.\n` +
"After the user complete's the check, they are given a role, which can be set to unlock specific channels.\n" +
`You can set the role given with ${getCommandMentionByName("settings/verify")}`
)
@@ -129,7 +159,9 @@
.setDescription(
"Nucleus has a content scanning system that automatically scans links and images sent by users.\n" +
"The staff team can be notified when an NSFW image is detected, or malicious links are sent.\n" +
- `You can check and manage what to moderate in ${getCommandMentionByName("settings/automod")}`
+ `You can check and manage what to moderate in ${getCommandMentionByName(
+ "settings/automod"
+ )}`
)
.setEmoji("MOD.IMAGES.TOOSMALL")
.setStatus("Danger")
@@ -143,10 +175,16 @@
.setTitle("Tickets")
.setDescription(
"Nucleus has a ticket system which allows users to create tickets and talk to the server staff or support team.\n" +
- `Tickets can be created by users with ${getCommandMentionByName("ticket/create")}, or by clicking a button created by moderators.\n` +
+ `Tickets can be created by users with ${getCommandMentionByName(
+ "ticket/create"
+ )}, or by clicking a button created by moderators.\n` +
`After being created, a new channel or thread is created, and the user and support team are pinged. \n` +
- `The category or channel to create threads in can be set with ${getCommandMentionByName("settings/tickets")}\n` +
- `When the ticket is resolved, anyone can run ${getCommandMentionByName("ticket/close")} (or click the button) to close it.\n` +
+ `The category or channel to create threads in can be set with ${getCommandMentionByName(
+ "settings/tickets"
+ )}\n` +
+ `When the ticket is resolved, anyone can run ${getCommandMentionByName(
+ "ticket/close"
+ )} (or click the button) to close it.\n` +
`Running ${getCommandMentionByName("ticket/close")} again will delete the ticket.`
)
.setEmoji("GUILD.TICKET.CLOSE")
@@ -161,8 +199,12 @@
.setTitle("Tags")
.setDescription(
"Nucleus allows you to create tags, which allow a message to be sent when a specific tag is typed.\n" +
- `Tags can be created with ${getCommandMentionByName("tags/create")}, and can be edited with ${getCommandMentionByName("tags/edit")}\n` +
- `Tags can be deleted with ${getCommandMentionByName("tags/delete")}, and can be listed with ${getCommandMentionByName("tags/list")}\n` +
+ `Tags can be created with ${getCommandMentionByName(
+ "tags/create"
+ )}, and can be edited with ${getCommandMentionByName("tags/edit")}\n` +
+ `Tags can be deleted with ${getCommandMentionByName(
+ "tags/delete"
+ )}, and can be listed with ${getCommandMentionByName("tags/list")}\n` +
`To use a tag, you can type ${getCommandMentionByName("tag")}, followed by the tag to send`
)
.setEmoji("PUNISH.NICKNAME.RED")
@@ -177,9 +219,9 @@
.setTitle("Premium")
.setDescription(
"Nucleus Premium allows you to use extra features in your server, which are useful but not essential.\n" +
- "**No currently free commands will become premium features.**\n" +
- "Premium features include creating ticket transcripts and attachment logs.\n\n" +
- "Premium can be purchased in [our server](https://discord.gg/bPaNnxe) in the subscriptions page" // TODO: add a table graphic
+ "**No currently free commands will become premium features.**\n" +
+ "Premium features include creating ticket transcripts and attachment logs.\n\n" +
+ "Premium can be purchased in [our server](https://discord.gg/bPaNnxe) in the subscriptions page" // TODO: add a table graphic
)
.setEmoji("NUCLEUS.PREMIUM")
.setStatus("Danger")
@@ -203,10 +245,11 @@
if (selectPaneOpen) {
const options: Discord.StringSelectMenuOptionBuilder[] = [];
pages.forEach((embed) => {
- options.push(new Discord.StringSelectMenuOptionBuilder()
- .setLabel(embed.title)
- .setValue(embed.pageId.toString())
- .setDescription(embed.description || "")
+ options.push(
+ new Discord.StringSelectMenuOptionBuilder()
+ .setLabel(embed.title)
+ .setValue(embed.pageId.toString())
+ .setDescription(embed.description || "")
);
});
selectPane = [
@@ -257,7 +300,9 @@
try {
i = await m.awaitMessageComponent({
filter: interaction
- ? (i) => { return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id }
+ ? (i) => {
+ return i.user.id === interaction.user.id && i.channel!.id === interaction.channel!.id;
+ }
: publicFilter,
time: 300000
});
diff --git a/src/reflex/scanners.ts b/src/reflex/scanners.ts
index cf713e6..71e63b4 100644
--- a/src/reflex/scanners.ts
+++ b/src/reflex/scanners.ts
@@ -17,10 +17,10 @@
export async function testNSFW(link: string): Promise<NSFWSchema> {
const [p, hash] = await saveAttachment(link);
- const alreadyHaveCheck = await client.database.scanCache.read(hash)
- if(alreadyHaveCheck) return { nsfw: alreadyHaveCheck.data };
+ const alreadyHaveCheck = await client.database.scanCache.read(hash);
+ if (alreadyHaveCheck) return { nsfw: alreadyHaveCheck.data };
const data = new URLSearchParams();
- const r = createReadStream(p)
+ const r = createReadStream(p);
data.append("file", r.read(fs.statSync(p).size));
const result = await fetch("https://unscan.p.rapidapi.com/", {
method: "POST",
@@ -30,12 +30,14 @@
},
body: data
})
- .then((response) => response.status === 200 ? response.json() as Promise<NSFWSchema> : { nsfw: false, errored: true })
+ .then((response) =>
+ response.status === 200 ? (response.json() as Promise<NSFWSchema>) : { nsfw: false, errored: true }
+ )
.catch((err) => {
console.error(err);
return { nsfw: false, errored: true };
});
- if(!result.errored) {
+ if (!result.errored) {
client.database.scanCache.write(hash, result.nsfw);
}
return { nsfw: result.nsfw };
@@ -43,8 +45,8 @@
export async function testMalware(link: string): Promise<MalwareSchema> {
const [p, hash] = await saveAttachment(link);
- const alreadyHaveCheck = await client.database.scanCache.read(hash)
- if(alreadyHaveCheck) return { safe: alreadyHaveCheck.data };
+ const alreadyHaveCheck = await client.database.scanCache.read(hash);
+ if (alreadyHaveCheck) return { safe: alreadyHaveCheck.data };
const data = new URLSearchParams();
const f = createReadStream(p);
data.append("file", f.read(fs.statSync(p).size));
@@ -56,7 +58,9 @@
},
body: data
})
- .then((response) => response.status === 200 ? response.json() as Promise<MalwareSchema> : { safe: true, errored: true })
+ .then((response) =>
+ response.status === 200 ? (response.json() as Promise<MalwareSchema>) : { safe: true, errored: true }
+ )
.catch((err) => {
console.error(err);
return { safe: true, errored: true };
@@ -68,8 +72,8 @@
}
export async function testLink(link: string): Promise<{ safe: boolean; tags: string[] }> {
- const alreadyHaveCheck = await client.database.scanCache.read(link)
- if(alreadyHaveCheck) return { safe: alreadyHaveCheck.data, tags: [] };
+ const alreadyHaveCheck = await client.database.scanCache.read(link);
+ if (alreadyHaveCheck) return { safe: alreadyHaveCheck.data, tags: [] };
const scanned: { safe?: boolean; tags?: string[] } = await fetch("https://unscan.p.rapidapi.com/link", {
method: "POST",
headers: {
@@ -91,11 +95,11 @@
}
export async function saveAttachment(link: string): Promise<[string, string]> {
- const image = await (await fetch(link)).arrayBuffer()
+ const image = await (await fetch(link)).arrayBuffer();
const fileName = generateFileName(link.split("/").pop()!.split(".").pop()!);
const enc = new TextDecoder("utf-8");
writeFileSync(fileName, new DataView(image), "base64");
- return [fileName, createHash('sha512').update(enc.decode(image), 'base64').digest('base64')];
+ return [fileName, createHash("sha512").update(enc.decode(image), "base64").digest("base64")];
}
const linkTypes = {
diff --git a/src/reflex/statsChannelUpdate.ts b/src/reflex/statsChannelUpdate.ts
index daa82fd..6c601f7 100644
--- a/src/reflex/statsChannelUpdate.ts
+++ b/src/reflex/statsChannelUpdate.ts
@@ -1,4 +1,4 @@
-import { getCommandMentionByName } from '../utils/getCommandDataByName.js';
+import { getCommandMentionByName } from "../utils/getCommandDataByName.js";
import type { Guild, User } from "discord.js";
import type { NucleusClient } from "../utils/client.js";
import type { GuildMember } from "discord.js";
@@ -32,8 +32,9 @@
return singleNotify(
"statsChannelDeleted",
guild!.id,
- `One or more of your stats channels have been deleted. You can use ${getCommandMentionByName("settings/stats")}.\n` +
- `The channels name was: ${deleted!.name}`,
+ `One or more of your stats channels have been deleted. You can use ${getCommandMentionByName(
+ "settings/stats"
+ )}.\n` + `The channels name was: ${deleted!.name}`,
"Critical"
);
}
diff --git a/src/reflex/verify.ts b/src/reflex/verify.ts
index 290e372..a5991de 100644
--- a/src/reflex/verify.ts
+++ b/src/reflex/verify.ts
@@ -122,7 +122,7 @@
});
if (
await NSFWCheck(
- (interaction.member as GuildMember).user.displayAvatarURL({extension: "png", forceStatic: true})
+ (interaction.member as GuildMember).user.displayAvatarURL({ extension: "png", forceStatic: true })
)
) {
return await interaction.editReply({
@@ -184,14 +184,14 @@
let itt = 0;
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
do {
- itt ++;
+ itt++;
code = "";
for (let i = 0; i < length; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
if (itt > 1000) {
itt = 0;
- length ++;
+ length++;
}
} while (code in verify);
const role: Role | null = await interaction.guild!.roles.fetch(config.verify.role);
@@ -208,7 +208,14 @@
.setEmoji("CONTROL.BLOCKCROSS")
]
});
- singleNotify("verifyRoleDeleted", interaction.guild!.id, `The role given when a member is verified has been deleted. Use ${getCommandMentionByName("settings/verify")} to set a new one`, "Critical")
+ singleNotify(
+ "verifyRoleDeleted",
+ interaction.guild!.id,
+ `The role given when a member is verified has been deleted. Use ${getCommandMentionByName(
+ "settings/verify"
+ )} to set a new one`,
+ "Critical"
+ );
return;
}
verify[code] = {
diff --git a/src/reflex/welcome.ts b/src/reflex/welcome.ts
index c2eede3..5597b81 100644
--- a/src/reflex/welcome.ts
+++ b/src/reflex/welcome.ts
@@ -1,4 +1,4 @@
-import { getCommandMentionByName } from './../utils/getCommandDataByName.js';
+import { getCommandMentionByName } from "./../utils/getCommandDataByName.js";
import type { NucleusClient } from "../utils/client.js";
import convertCurlyBracketString from "../utils/convertCurlyBracketString.js";
import client from "../utils/client.js";
@@ -26,8 +26,18 @@
embeds: [new EmojiEmbed().setDescription(string).setStatus("Success")]
});
} else {
- const channel: GuildChannel | null = await member.guild.channels.fetch(config.welcome.channel) as GuildChannel | null;
- if (!channel) return await singleNotify("welcomeChannelDeleted", member.guild.id, `The welcome channel has been deleted or is no longer accessible. Use ${getCommandMentionByName("settings/welcome")} to set a new one`, "Warning")
+ const channel: GuildChannel | null = (await member.guild.channels.fetch(
+ config.welcome.channel
+ )) as GuildChannel | null;
+ if (!channel)
+ return await singleNotify(
+ "welcomeChannelDeleted",
+ member.guild.id,
+ `The welcome channel has been deleted or is no longer accessible. Use ${getCommandMentionByName(
+ "settings/welcome"
+ )} to set a new one`,
+ "Warning"
+ );
if (!(channel instanceof BaseGuildTextChannel)) return;
if (channel.guild.id !== member.guild.id) return;
try {
@@ -39,9 +49,11 @@
singleNotify(
"welcomeChannelDeleted",
member.guild.id,
- `The welcome channel has been deleted or is no longer accessible. Use ${getCommandMentionByName("settings/welcome")} to set a new one`,
+ `The welcome channel has been deleted or is no longer accessible. Use ${getCommandMentionByName(
+ "settings/welcome"
+ )} to set a new one`,
"Warning"
- )
+ );
}
}
}
diff --git a/src/utils/calculate.ts b/src/utils/calculate.ts
index fde1340..61e0cb2 100644
--- a/src/utils/calculate.ts
+++ b/src/utils/calculate.ts
@@ -17,14 +17,16 @@
"webhookUpdate",
"guildMemberVerify",
"autoModeratorDeleted",
- "ticketUpdate",
+ "ticketUpdate"
// "nucleusSettingsUpdated"
];
const tickets = ["support", "report", "question", "issue", "suggestion", "other"];
const toHexInteger = (permissions: string[], array?: string[]): string => {
- if (!array) { array = logs; }
+ if (!array) {
+ array = logs;
+ }
let int = 0n;
for (const perm of permissions) {
diff --git a/src/utils/client.ts b/src/utils/client.ts
index b1fa31f..f443d24 100644
--- a/src/utils/client.ts
+++ b/src/utils/client.ts
@@ -1,13 +1,12 @@
-import Discord, { Client, Interaction, AutocompleteInteraction, Collection } from 'discord.js';
+import Discord, { Client, Interaction, AutocompleteInteraction, Collection } from "discord.js";
import { Logger } from "../utils/log.js";
import Memory from "../utils/memory.js";
import type { VerifySchema } from "../reflex/verify.js";
-import { Guilds, History, ModNotes, Premium, PerformanceTest, ScanCache, Transcript, } from "../utils/database.js";
+import { Guilds, History, ModNotes, Premium, PerformanceTest, ScanCache, Transcript } from "../utils/database.js";
import EventScheduler from "../utils/eventScheduler.js";
import type { RoleMenuSchema } from "../actions/roleMenu.js";
import config from "../config/main.js";
-
class NucleusClient extends Client {
logger = Logger;
config: typeof config = config;
@@ -23,20 +22,35 @@
eventScheduler: EventScheduler;
performanceTest: PerformanceTest;
scanCache: ScanCache;
- transcripts: Transcript
+ transcripts: Transcript;
};
- preloadPage: Record<string, {command: string, argument: string}> = {}; // e.g. { channelID: { command: privacy, page: 3}}
- commands: Record<string, [{
- command: Discord.SlashCommandBuilder |
- ((builder: Discord.SlashCommandBuilder) => Discord.SlashCommandBuilder) |
- Discord.SlashCommandSubcommandBuilder | ((builder: Discord.SlashCommandSubcommandBuilder) => Discord.SlashCommandSubcommandBuilder) | Discord.SlashCommandSubcommandGroupBuilder | ((builder: Discord.SlashCommandSubcommandGroupBuilder) => Discord.SlashCommandSubcommandGroupBuilder),
- callback: (interaction: Interaction) => Promise<void>,
- check: (interaction: Interaction, partial: boolean) => Promise<boolean> | boolean,
- autocomplete: (interaction: AutocompleteInteraction) => Promise<string[]>
- } | undefined, {name: string, description: string}]> = {};
+ preloadPage: Record<string, { command: string; argument: string }> = {}; // e.g. { channelID: { command: privacy, page: 3}}
+ commands: Record<
+ string,
+ [
+ (
+ | {
+ command:
+ | Discord.SlashCommandBuilder
+ | ((builder: Discord.SlashCommandBuilder) => Discord.SlashCommandBuilder)
+ | Discord.SlashCommandSubcommandBuilder
+ | ((builder: Discord.SlashCommandSubcommandBuilder) => Discord.SlashCommandSubcommandBuilder)
+ | Discord.SlashCommandSubcommandGroupBuilder
+ | ((
+ builder: Discord.SlashCommandSubcommandGroupBuilder
+ ) => Discord.SlashCommandSubcommandGroupBuilder);
+ callback: (interaction: Interaction) => Promise<void>;
+ check: (interaction: Interaction, partial: boolean) => Promise<boolean> | boolean;
+ autocomplete: (interaction: AutocompleteInteraction) => Promise<string[]>;
+ }
+ | undefined
+ ),
+ { name: string; description: string }
+ ]
+ > = {};
fetchedCommands = new Collection<string, Discord.ApplicationCommand>();
constructor(database: typeof NucleusClient.prototype.database) {
- super({ intents: 0b1100011011011111111111});
+ super({ intents: 0b1100011011011111111111 });
this.database = database;
}
}
@@ -52,4 +66,4 @@
});
export default client;
-export { NucleusClient };
\ No newline at end of file
+export { NucleusClient };
diff --git a/src/utils/commandRegistration/getFilesInFolder.ts b/src/utils/commandRegistration/getFilesInFolder.ts
index 875e0b0..f5131bb 100644
--- a/src/utils/commandRegistration/getFilesInFolder.ts
+++ b/src/utils/commandRegistration/getFilesInFolder.ts
@@ -1,9 +1,9 @@
import fs from "fs";
export default async function getSubcommandsInFolder(path: string, indent: string = "") {
- const files = fs.readdirSync(path, { withFileTypes: true }).filter(
- file => !file.name.endsWith(".ts") && !file.name.endsWith(".map")
- );
+ const files = fs
+ .readdirSync(path, { withFileTypes: true })
+ .filter((file) => !file.name.endsWith(".ts") && !file.name.endsWith(".map"));
const subcommands = [];
const subcommandGroups = [];
let errors = 0;
@@ -15,7 +15,7 @@
subcommandGroups.push(await import(`../../../${path}/${file.name}/_meta.js`));
} else if (file.name.endsWith(".js")) {
// If its a file
- console.log(`│ ${indent}├─ Loading subcommand ${file.name}`)
+ console.log(`│ ${indent}├─ Loading subcommand ${file.name}`);
subcommands.push(await import(`../../../${path}/${file.name}`));
}
} catch (e) {
@@ -23,5 +23,5 @@
errors++;
}
}
- return {subcommands, subcommandGroups, errors};
+ return { subcommands, subcommandGroups, errors };
}
diff --git a/src/utils/commandRegistration/register.ts b/src/utils/commandRegistration/register.ts
index 33c88b0..fbd052f 100644
--- a/src/utils/commandRegistration/register.ts
+++ b/src/utils/commandRegistration/register.ts
@@ -1,10 +1,10 @@
-import type { CommandInteraction } from 'discord.js';
-import Discord, { Interaction, SlashCommandBuilder, ApplicationCommandType } from 'discord.js';
+import type { CommandInteraction } from "discord.js";
+import Discord, { Interaction, SlashCommandBuilder, ApplicationCommandType } from "discord.js";
import config from "../../config/main.js";
import client from "../client.js";
import fs from "fs";
-import EmojiEmbed from '../generateEmojiEmbed.js';
-import getEmojiByName from '../getEmojiByName.js';
+import EmojiEmbed from "../generateEmojiEmbed.js";
+import getEmojiByName from "../getEmojiByName.js";
const colors = {
red: "\x1b[31m",
@@ -13,163 +13,207 @@
blue: "\x1b[34m",
purple: "\x1b[35m",
none: "\x1b[0m"
-}
+};
async function registerCommands() {
const commands = [];
- const files: fs.Dirent[] = fs.readdirSync(config.commandsFolder, { withFileTypes: true }).filter(
- file => !file.name.endsWith(".ts") && !file.name.endsWith(".map")
- );
- console.log(`Registering ${files.length} commands`)
+ const files: fs.Dirent[] = fs
+ .readdirSync(config.commandsFolder, { withFileTypes: true })
+ .filter((file) => !file.name.endsWith(".ts") && !file.name.endsWith(".map"));
+ console.log(`Registering ${files.length} commands`);
let i = 0;
for (const file of files) {
const last = i === files.length - 1 ? "└" : "├";
if (file.isDirectory()) {
- console.log(`${last}─ ${colors.yellow}Loading subcommands of ${file.name}${colors.none}`)
- const fetched = (await import(`../../../${config.commandsFolder}/${file.name}/_meta.js`));
+ console.log(`${last}─ ${colors.yellow}Loading subcommands of ${file.name}${colors.none}`);
+ const fetched = await import(`../../../${config.commandsFolder}/${file.name}/_meta.js`);
commands.push(fetched.command);
} else if (file.name.endsWith(".js")) {
- console.log(`${last}─ ${colors.yellow}Loading command ${file.name}${colors.none}`)
- const fetched = (await import(`../../../${config.commandsFolder}/${file.name}`));
- fetched.command.setDMPermission(fetched.allowedInDMs ?? false)
- fetched.command.setNameLocalizations(fetched.nameLocalizations ?? {})
- fetched.command.setDescriptionLocalizations(fetched.descriptionLocalizations ?? {})
+ console.log(`${last}─ ${colors.yellow}Loading command ${file.name}${colors.none}`);
+ const fetched = await import(`../../../${config.commandsFolder}/${file.name}`);
+ fetched.command.setDMPermission(fetched.allowedInDMs ?? false);
+ fetched.command.setNameLocalizations(fetched.nameLocalizations ?? {});
+ fetched.command.setDescriptionLocalizations(fetched.descriptionLocalizations ?? {});
// if (fetched.nameLocalizations || fetched.descriptionLocalizations)
commands.push(fetched.command);
client.commands["commands/" + fetched.command.name] = [
fetched,
- {name: fetched.name ?? fetched.command.name, description: fetched.description ?? fetched.command.description}
+ {
+ name: fetched.name ?? fetched.command.name,
+ description: fetched.description ?? fetched.command.description
+ }
];
}
i++;
- console.log(`${last.replace("└", " ").replace("├", "│")} └─ ${colors.green}Loaded ${file.name} [${i} / ${files.length}]${colors.none}`)
+ console.log(
+ `${last.replace("└", " ").replace("├", "│")} └─ ${colors.green}Loaded ${file.name} [${i} / ${
+ files.length
+ }]${colors.none}`
+ );
}
- console.log(`${colors.yellow}Loaded ${commands.length} commands, processing...`)
- const processed = []
+ console.log(`${colors.yellow}Loaded ${commands.length} commands, processing...`);
+ const processed = [];
for (const subcommand of commands) {
if (subcommand instanceof Function) {
- processed.push(subcommand(new SlashCommandBuilder()))
+ processed.push(subcommand(new SlashCommandBuilder()));
} else {
- processed.push(subcommand)
+ processed.push(subcommand);
}
}
- console.log(`${colors.green}Processed ${processed.length} commands${colors.none}`)
+ console.log(`${colors.green}Processed ${processed.length} commands${colors.none}`);
return processed;
-
-};
+}
async function registerEvents() {
- console.log("Reading events")
- const files = fs.readdirSync(config.eventsFolder, { withFileTypes: true }).filter(
- file => !file.name.endsWith(".ts") && !file.name.endsWith(".map")
- );
- console.log(`Registering ${files.length} events`)
+ console.log("Reading events");
+ const files = fs
+ .readdirSync(config.eventsFolder, { withFileTypes: true })
+ .filter((file) => !file.name.endsWith(".ts") && !file.name.endsWith(".map"));
+ console.log(`Registering ${files.length} events`);
let i = 0;
let errors = 0;
for (const file of files) {
const last = i === files.length - 1 ? "└" : "├";
i++;
try {
- console.log(`${last}─ ${colors.yellow}Loading event ${file.name}${colors.none}`)
- const event = (await import(`../../../${config.eventsFolder}/${file.name}`));
+ console.log(`${last}─ ${colors.yellow}Loading event ${file.name}${colors.none}`);
+ const event = await import(`../../../${config.eventsFolder}/${file.name}`);
client.on(event.event, event.callback.bind(null, client));
- console.log(`${last.replace("└", " ").replace("├", "│")} └─ ${colors.green}Loaded ${file.name} [${i} / ${files.length}]${colors.none}`)
+ console.log(
+ `${last.replace("└", " ").replace("├", "│")} └─ ${colors.green}Loaded ${file.name} [${i} / ${
+ files.length
+ }]${colors.none}`
+ );
} catch (e) {
errors++;
- console.log(`${last.replace("└", " ").replace("├", "│")} └─ ${colors.red}Failed to load ${file.name} [${i} / ${files.length}]${colors.none}`)
+ console.log(
+ `${last.replace("└", " ").replace("├", "│")} └─ ${colors.red}Failed to load ${file.name} [${i} / ${
+ files.length
+ }]${colors.none}`
+ );
}
}
- console.log(`Loaded ${files.length - errors} events (${errors} failed)`)
-};
+ console.log(`Loaded ${files.length - errors} events (${errors} failed)`);
+}
async function registerContextMenus() {
- console.log("Reading context menus")
- const messageFiles = fs.readdirSync(config.messageContextFolder, { withFileTypes: true }).filter(
- file => !file.name.endsWith(".ts") && !file.name.endsWith(".map")
- );
- const userFiles = fs.readdirSync(config.userContextFolder, { withFileTypes: true }).filter(
- file => !file.name.endsWith(".ts") && !file.name.endsWith(".map")
- );
- console.log(`Registering ${messageFiles.length} message context menus and ${userFiles.length} user context menus`)
+ console.log("Reading context menus");
+ const messageFiles = fs
+ .readdirSync(config.messageContextFolder, { withFileTypes: true })
+ .filter((file) => !file.name.endsWith(".ts") && !file.name.endsWith(".map"));
+ const userFiles = fs
+ .readdirSync(config.userContextFolder, { withFileTypes: true })
+ .filter((file) => !file.name.endsWith(".ts") && !file.name.endsWith(".map"));
+ console.log(`Registering ${messageFiles.length} message context menus and ${userFiles.length} user context menus`);
let i = 0;
let errors = 0;
- const commands: (Discord.ContextMenuCommandBuilder)[] = []
+ const commands: Discord.ContextMenuCommandBuilder[] = [];
const totalFiles = messageFiles.length + userFiles.length;
for (const file of messageFiles) {
const last = i === totalFiles - 1 ? "└" : "├";
i++;
try {
- console.log(`${last}─ ${colors.yellow}Loading message context menu ${file.name}${colors.none}`)
- const context = (await import(`../../../${config.messageContextFolder}/${file.name}`));
+ console.log(`${last}─ ${colors.yellow}Loading message context menu ${file.name}${colors.none}`);
+ const context = await import(`../../../${config.messageContextFolder}/${file.name}`);
context.command.setType(ApplicationCommandType.Message);
- context.command.setDMPermission(context.allowedInDMs ?? false)
- context.command.setNameLocalizations(context.nameLocalizations ?? {})
+ context.command.setDMPermission(context.allowedInDMs ?? false);
+ context.command.setNameLocalizations(context.nameLocalizations ?? {});
commands.push(context.command);
- client.commands["contextCommands/message/" + context.command.name] = [context, {name: context.name ?? context.command.name, description: context.description ?? context.command.description}];
+ client.commands["contextCommands/message/" + context.command.name] = [
+ context,
+ {
+ name: context.name ?? context.command.name,
+ description: context.description ?? context.command.description
+ }
+ ];
- console.log(`${last.replace("└", " ").replace("├", "│")} └─ ${colors.green}Loaded ${file.name} [${i} / ${totalFiles}]${colors.none}`)
+ console.log(
+ `${last.replace("└", " ").replace("├", "│")} └─ ${colors.green}Loaded ${
+ file.name
+ } [${i} / ${totalFiles}]${colors.none}`
+ );
} catch (e) {
errors++;
- console.log(`${last.replace("└", " ").replace("├", "│")} └─ ${colors.red}Failed to load ${file.name} [${i} / ${totalFiles}] | ${e}${colors.none}`)
+ console.log(
+ `${last.replace("└", " ").replace("├", "│")} └─ ${colors.red}Failed to load ${
+ file.name
+ } [${i} / ${totalFiles}] | ${e}${colors.none}`
+ );
}
}
for (const file of userFiles) {
const last = i === totalFiles - 1 ? "└" : "├";
i++;
try {
- console.log(`${last}─ ${colors.yellow}Loading user context menu ${file.name}${colors.none}`)
- const context = (await import(`../../../${config.userContextFolder}/${file.name}`));
+ console.log(`${last}─ ${colors.yellow}Loading user context menu ${file.name}${colors.none}`);
+ const context = await import(`../../../${config.userContextFolder}/${file.name}`);
context.command.setType(ApplicationCommandType.User);
commands.push(context.command);
client.commands["contextCommands/user/" + context.command.name] = context;
- console.log(`${last.replace("└", " ").replace("├", "│")} └─ ${colors.green}Loaded ${file.name} [${i} / ${totalFiles}]${colors.none}`)
+ console.log(
+ `${last.replace("└", " ").replace("├", "│")} └─ ${colors.green}Loaded ${
+ file.name
+ } [${i} / ${totalFiles}]${colors.none}`
+ );
} catch (e) {
errors++;
- console.log(`${last.replace("└", " ").replace("├", "│")} └─ ${colors.red}Failed to load ${file.name} [${i} / ${totalFiles}]${colors.none}`)
+ console.log(
+ `${last.replace("└", " ").replace("├", "│")} └─ ${colors.red}Failed to load ${
+ file.name
+ } [${i} / ${totalFiles}]${colors.none}`
+ );
}
}
- console.log(`Loaded ${messageFiles.length + userFiles.length - errors} context menus (${errors} failed)`)
+ console.log(`Loaded ${messageFiles.length + userFiles.length - errors} context menus (${errors} failed)`);
return commands;
-};
+}
async function registerCommandHandler() {
client.on("interactionCreate", async (interaction: Interaction) => {
- if (interaction.isUserContextMenuCommand()) {;
+ if (interaction.isUserContextMenuCommand()) {
const commandName = "contextCommands/user/" + interaction.commandName;
- execute(client.commands[commandName]![0]?.check, client.commands[commandName]![0]?.callback, interaction)
+ execute(client.commands[commandName]![0]?.check, client.commands[commandName]![0]?.callback, interaction);
return;
} else if (interaction.isMessageContextMenuCommand()) {
const commandName = "contextCommands/message/" + interaction.commandName;
- execute(client.commands[commandName]![0]?.check, client.commands[commandName]![0]?.callback, interaction)
+ execute(client.commands[commandName]![0]?.check, client.commands[commandName]![0]?.callback, interaction);
return;
} else if (interaction.isAutocomplete()) {
const commandName = interaction.commandName;
const subcommandGroupName = interaction.options.getSubcommandGroup(false);
const subcommandName = interaction.options.getSubcommand(false);
- const fullCommandName = "commands/" + commandName + (subcommandGroupName ? `/${subcommandGroupName}` : "") + (subcommandName ? `/${subcommandName}` : "");
+ const fullCommandName =
+ "commands/" +
+ commandName +
+ (subcommandGroupName ? `/${subcommandGroupName}` : "") +
+ (subcommandName ? `/${subcommandName}` : "");
const choices = await client.commands[fullCommandName]![0]?.autocomplete(interaction);
- const formatted = (choices ?? []).map(choice => {
- return { name: choice, value: choice }
- })
- interaction.respond(formatted)
+ const formatted = (choices ?? []).map((choice) => {
+ return { name: choice, value: choice };
+ });
+ interaction.respond(formatted);
} else if (interaction.isChatInputCommand()) {
const commandName = interaction.commandName;
const subcommandGroupName = interaction.options.getSubcommandGroup(false);
const subcommandName = interaction.options.getSubcommand(false);
- const fullCommandName = "commands/" + commandName + (subcommandGroupName ? `/${subcommandGroupName}` : "") + (subcommandName ? `/${subcommandName}` : "");
+ const fullCommandName =
+ "commands/" +
+ commandName +
+ (subcommandGroupName ? `/${subcommandGroupName}` : "") +
+ (subcommandName ? `/${subcommandName}` : "");
// console.log(fullCommandName, client.commands[fullCommandName])
const command = client.commands[fullCommandName]![0];
@@ -187,34 +231,37 @@
let result;
try {
result = await check(data);
- } catch(e) {
+ } catch (e) {
result = false;
}
if (result === false) return;
if (typeof result === "string") {
- const { NucleusColors } = client.logger
- return data.reply({embeds: [new EmojiEmbed()
- .setDescription(result)
- .setColor(NucleusColors.red)
- .setEmoji(getEmojiByName("CONTROL.BLOCKCROSS"))
- ], ephemeral: true});
+ const { NucleusColors } = client.logger;
+ return data.reply({
+ embeds: [
+ new EmojiEmbed()
+ .setDescription(result)
+ .setColor(NucleusColors.red)
+ .setEmoji(getEmojiByName("CONTROL.BLOCKCROSS"))
+ ],
+ ephemeral: true
+ });
}
}
callback(data);
}
-
export default async function register() {
- let commandList: ( Discord.SlashCommandBuilder | Discord.ContextMenuCommandBuilder )[] = [];
+ let commandList: (Discord.SlashCommandBuilder | Discord.ContextMenuCommandBuilder)[] = [];
commandList = commandList.concat(await registerCommands());
commandList = commandList.concat(await registerContextMenus());
if (process.argv.includes("--update-commands")) {
if (config.enableDevelopment) {
const guild = await client.guilds.fetch(config.developmentGuildID);
- console.log(`${colors.purple}Registering commands in ${guild!.name}${colors.none}`)
+ console.log(`${colors.purple}Registering commands in ${guild!.name}${colors.none}`);
await guild.commands.set(commandList);
} else {
- console.log(`${colors.blue}Registering commands in production mode${colors.none}`)
+ console.log(`${colors.blue}Registering commands in production mode${colors.none}`);
const guild = await client.guilds.fetch(config.developmentGuildID);
await guild.commands.set([]);
await client.application?.commands.set(commandList);
@@ -222,9 +269,10 @@
}
await registerCommandHandler();
await registerEvents();
- console.log(`${colors.green}Registered commands, events and context menus${colors.none}`)
+ console.log(`${colors.green}Registered commands, events and context menus${colors.none}`);
console.log(
- (config.enableDevelopment ? `${colors.purple}Bot started in Development mode` :
- `${colors.blue}Bot started in Production mode`) + colors.none
- )
-};
+ (config.enableDevelopment
+ ? `${colors.purple}Bot started in Development mode`
+ : `${colors.blue}Bot started in Production mode`) + colors.none
+ );
+}
diff --git a/src/utils/commandRegistration/slashCommandBuilder.ts b/src/utils/commandRegistration/slashCommandBuilder.ts
index 66291b3..edfdfb7 100644
--- a/src/utils/commandRegistration/slashCommandBuilder.ts
+++ b/src/utils/commandRegistration/slashCommandBuilder.ts
@@ -5,13 +5,11 @@
import client from "../client.js";
import Discord from "discord.js";
-
const colors = {
red: "\x1b[31m",
green: "\x1b[32m",
none: "\x1b[0m"
-}
-
+};
export async function group(
name: string,
@@ -21,21 +19,30 @@
descriptionLocalizations?: Record<string, string>
) {
// If the name of the command does not match the path (e.g. attachment.ts has /attachments), use commandString
- console.log(`│ ├─ Loading group ${name}`)
- const fetched = await getSubcommandsInFolder(config.commandsFolder + "/" + path, "│ ")
- console.log(`│ │ └─ ${fetched.errors ? colors.red : colors.green}Loaded ${fetched.subcommands.length} subcommands for ${name} (${fetched.errors} failed)${colors.none}`)
+ console.log(`│ ├─ Loading group ${name}`);
+ const fetched = await getSubcommandsInFolder(config.commandsFolder + "/" + path, "│ ");
+ console.log(
+ `│ │ └─ ${fetched.errors ? colors.red : colors.green}Loaded ${
+ fetched.subcommands.length
+ } subcommands for ${name} (${fetched.errors} failed)${colors.none}`
+ );
return (subcommandGroup: SlashCommandSubcommandGroupBuilder) => {
- subcommandGroup
- .setName(name)
- .setDescription(description)
- if (nameLocalizations) { subcommandGroup.setNameLocalizations(nameLocalizations) }
- if (descriptionLocalizations) { subcommandGroup.setDescriptionLocalizations(descriptionLocalizations) }
+ subcommandGroup.setName(name).setDescription(description);
+ if (nameLocalizations) {
+ subcommandGroup.setNameLocalizations(nameLocalizations);
+ }
+ if (descriptionLocalizations) {
+ subcommandGroup.setDescriptionLocalizations(descriptionLocalizations);
+ }
for (const subcommand of fetched.subcommands) {
const processedCommand = subcommand.command(new SlashCommandSubcommandBuilder());
- client.commands["commands/" + path + "/" + processedCommand.name] = [subcommand, { name: processedCommand.name, description: processedCommand.description }]
+ client.commands["commands/" + path + "/" + processedCommand.name] = [
+ subcommand,
+ { name: processedCommand.name, description: processedCommand.description }
+ ];
subcommandGroup.addSubcommand(processedCommand);
- };
+ }
return subcommandGroup;
};
@@ -54,19 +61,23 @@
// If the name of the command does not match the path (e.g. attachment.ts has /attachments), use commandString
commandString = "commands/" + (commandString ?? path);
const fetched = await getSubcommandsInFolder(config.commandsFolder + "/" + path);
- console.log(`│ ├─ ${fetched.errors ? colors.red : colors.green}Loaded ${fetched.subcommands.length} subcommands and ${fetched.subcommandGroups.length} subcommand groups for ${name} (${fetched.errors} failed)${colors.none}`)
+ console.log(
+ `│ ├─ ${fetched.errors ? colors.red : colors.green}Loaded ${fetched.subcommands.length} subcommands and ${
+ fetched.subcommandGroups.length
+ } subcommand groups for ${name} (${fetched.errors} failed)${colors.none}`
+ );
// console.log({name: name, description: description})
- client.commands[commandString!] = [undefined, { name: name, description: description }]
+ client.commands[commandString!] = [undefined, { name: name, description: description }];
return (command: SlashCommandBuilder) => {
- command.setName(name)
- command.setDescription(description)
- command.setNameLocalizations(nameLocalizations ?? {})
- command.setDescriptionLocalizations(descriptionLocalizations ?? {})
- command.setDMPermission(allowedInDMs ?? false)
+ command.setName(name);
+ command.setDescription(description);
+ command.setNameLocalizations(nameLocalizations ?? {});
+ command.setDescriptionLocalizations(descriptionLocalizations ?? {});
+ command.setDMPermission(allowedInDMs ?? false);
if (userPermissions) {
- const bitfield = new Discord.PermissionsBitField()
- bitfield.add(userPermissions)
- command.setDefaultMemberPermissions(bitfield.bitfield)
+ const bitfield = new Discord.PermissionsBitField();
+ bitfield.add(userPermissions);
+ command.setDefaultMemberPermissions(bitfield.bitfield);
}
for (const subcommand of fetched.subcommands) {
@@ -76,14 +87,20 @@
} else {
fetchedCommand = subcommand.command;
}
- client.commands[commandString! + "/" + fetchedCommand.name] = [subcommand, { name: fetchedCommand.name, description: fetchedCommand.description }]
+ client.commands[commandString! + "/" + fetchedCommand.name] = [
+ subcommand,
+ { name: fetchedCommand.name, description: fetchedCommand.description }
+ ];
command.addSubcommand(fetchedCommand);
}
for (const group of fetched.subcommandGroups) {
const processedCommand = group.command(new SlashCommandSubcommandGroupBuilder());
- client.commands[commandString! + "/" + processedCommand.name] = [undefined, { name: processedCommand.name, description: processedCommand.description }]
+ client.commands[commandString! + "/" + processedCommand.name] = [
+ undefined,
+ { name: processedCommand.name, description: processedCommand.description }
+ ];
command.addSubcommandGroup(processedCommand);
- };
+ }
return command;
};
}
diff --git a/src/utils/confirmationMessage.ts b/src/utils/confirmationMessage.ts
index f7cccaf..05c5494 100644
--- a/src/utils/confirmationMessage.ts
+++ b/src/utils/confirmationMessage.ts
@@ -62,7 +62,11 @@
this.inverted = inverted;
return this;
}
- setFailedMessage(text: string, failedStatus: "Success" | "Danger" | "Warning" | null, failedEmoji: string | null = null) {
+ setFailedMessage(
+ text: string,
+ failedStatus: "Success" | "Danger" | "Warning" | null,
+ failedEmoji: string | null = null
+ ) {
this.failedMessage = text;
this.failedStatus = failedStatus;
this.failedEmoji = failedEmoji;
@@ -138,10 +142,14 @@
);
const components = [];
for (let i = 0; i < fullComponents.length; i += 5) {
- components.push(new ActionRowBuilder<
- Discord.ButtonBuilder | Discord.StringSelectMenuBuilder |
- Discord.RoleSelectMenuBuilder | Discord.UserSelectMenuBuilder
- >().addComponents(fullComponents.slice(i, i + 5)));
+ components.push(
+ new ActionRowBuilder<
+ | Discord.ButtonBuilder
+ | Discord.StringSelectMenuBuilder
+ | Discord.RoleSelectMenuBuilder
+ | Discord.UserSelectMenuBuilder
+ >().addComponents(fullComponents.slice(i, i + 5))
+ );
}
const object = {
embeds: [
@@ -158,7 +166,8 @@
} else {
return v.notValue ? `*${v.notValue}*\n` : "";
}
- }).join("")
+ })
+ .join("")
)
.setStatus(this.color)
],
@@ -181,7 +190,8 @@
let component;
try {
component = await m.awaitMessageComponent({
- filter: (i) => i.user.id === this.interaction.user.id && i.channel!.id === this.interaction.channel!.id,
+ filter: (i) =>
+ i.user.id === this.interaction.user.id && i.channel!.id === this.interaction.channel!.id,
time: 300000
});
} catch (e) {
@@ -244,12 +254,15 @@
});
let out;
try {
- out = await modalInteractionCollector(m, this.interaction.user) as Discord.ModalSubmitInteraction | null;
+ out = (await modalInteractionCollector(
+ m,
+ this.interaction.user
+ )) as Discord.ModalSubmitInteraction | null;
} catch (e) {
cancelled = true;
continue;
}
- if (out === null || out.isButton()) {
+ if (out === null || out.isButton()) {
cancelled = true;
continue;
}
@@ -270,28 +283,31 @@
const returnValue: Awaited<ReturnType<typeof this.send>> = {};
if (cancelled) {
- await this.timeoutError()
+ await this.timeoutError();
returnValue.cancelled = true;
}
if (success === false) {
await this.interaction.editReply({
- embeds: [new EmojiEmbed()
- .setTitle(this.title)
- .setDescription(this.failedMessage ?? "*Message timed out*")
- .setStatus(this.failedStatus ?? "Danger")
- .setEmoji(this.failedEmoji ?? this.redEmoji ?? this.emoji)
- ], components: []
+ embeds: [
+ new EmojiEmbed()
+ .setTitle(this.title)
+ .setDescription(this.failedMessage ?? "*Message timed out*")
+ .setStatus(this.failedStatus ?? "Danger")
+ .setEmoji(this.failedEmoji ?? this.redEmoji ?? this.emoji)
+ ],
+ components: []
});
- return {success: false}
+ return { success: false };
}
if (returnComponents || success !== undefined) returnValue.components = this.customButtons;
if (success !== undefined) returnValue.success = success;
if (newReason) returnValue.newReason = newReason;
- const typedReturnValue = returnValue as {cancelled: true} |
- { success: boolean, components: Record<string, CustomBoolean<unknown>>, newReason?: string} |
- { newReason: string, components: Record<string, CustomBoolean<unknown>> } |
- { components: Record<string, CustomBoolean<unknown>> };
+ const typedReturnValue = returnValue as
+ | { cancelled: true }
+ | { success: boolean; components: Record<string, CustomBoolean<unknown>>; newReason?: string }
+ | { newReason: string; components: Record<string, CustomBoolean<unknown>> }
+ | { components: Record<string, CustomBoolean<unknown>> };
return typedReturnValue;
}
@@ -306,7 +322,7 @@
.setEmoji("CONTROL.BLOCKCROSS")
],
components: []
- })
+ });
}
}
diff --git a/src/utils/createPageIndicator.ts b/src/utils/createPageIndicator.ts
index 6bc86a4..e16422d 100644
--- a/src/utils/createPageIndicator.ts
+++ b/src/utils/createPageIndicator.ts
@@ -2,16 +2,17 @@
function pageIndicator(amount: number, selected: number, showDetails?: boolean, disabled?: boolean | string) {
let out = "";
- disabled = disabled ? "GRAY." : ""
+ disabled = disabled ? "GRAY." : "";
if (amount === 1) {
- out += getEmojiByName("TRACKS.SINGLE." + (disabled) + (selected === 0 ? "ACTIVE" : "INACTIVE"));
+ out += getEmojiByName("TRACKS.SINGLE." + disabled + (selected === 0 ? "ACTIVE" : "INACTIVE"));
} else {
for (let i = 0; i < amount; i++) {
out += getEmojiByName(
"TRACKS.HORIZONTAL." +
- (i === 0 ? "LEFT" : i === amount - 1 ? "RIGHT" : "MIDDLE") +
- "." + (disabled) +
- (i === selected ? "ACTIVE" : "INACTIVE")
+ (i === 0 ? "LEFT" : i === amount - 1 ? "RIGHT" : "MIDDLE") +
+ "." +
+ disabled +
+ (i === selected ? "ACTIVE" : "INACTIVE")
);
}
}
@@ -21,7 +22,12 @@
return out;
}
-export const verticalTrackIndicator = (position: number, active: string | boolean, size: number, disabled: string | boolean) => {
+export const verticalTrackIndicator = (
+ position: number,
+ active: string | boolean,
+ size: number,
+ disabled: string | boolean
+) => {
active = active ? "ACTIVE" : "INACTIVE";
disabled = disabled ? "GRAY." : "";
if (position === 0 && size === 1) return "TRACKS.SINGLE." + disabled + active;
@@ -38,6 +44,6 @@
out += items[i] + "\n";
}
return out;
-}
+};
export default pageIndicator;
diff --git a/src/utils/createTemporaryStorage.ts b/src/utils/createTemporaryStorage.ts
index e8a8073..af41672 100644
--- a/src/utils/createTemporaryStorage.ts
+++ b/src/utils/createTemporaryStorage.ts
@@ -21,12 +21,12 @@
client.preloadPage[target] = {
command: command,
argument: message
- }
+ };
setTimeout(() => {
const object = Object.entries(client.preloadPage).filter((entry) => {
- const [k, _] = entry
+ const [k, _] = entry;
return k !== target;
- })
+ });
client.preloadPage = Object.fromEntries(object);
}, 60 * 5 * 1000);
}
diff --git a/src/utils/database.ts b/src/utils/database.ts
index a60cf74..e867775 100644
--- a/src/utils/database.ts
+++ b/src/utils/database.ts
@@ -1,23 +1,34 @@
-import { ButtonStyle, CommandInteraction, ComponentType, GuildMember, Message, MessageComponentInteraction } from "discord.js";
+import {
+ ButtonStyle,
+ CommandInteraction,
+ ComponentType,
+ GuildMember,
+ Message,
+ MessageComponentInteraction
+} from "discord.js";
import type Discord from "discord.js";
import { Collection, MongoClient } from "mongodb";
import config from "../config/main.js";
import client from "../utils/client.js";
import * as crypto from "crypto";
import _ from "lodash";
-import defaultData from '../config/default.js';
+import defaultData from "../config/default.js";
const username = encodeURIComponent(config.mongoOptions.username);
const password = encodeURIComponent(config.mongoOptions.password);
-const mongoClient = new MongoClient(username ? `mongodb://${username}:${password}@${config.mongoOptions.host}?authMechanism=DEFAULT` : `mongodb://${config.mongoOptions.host}`, {authSource: config.mongoOptions.authSource});
+const mongoClient = new MongoClient(
+ username
+ ? `mongodb://${username}:${password}@${config.mongoOptions.host}?authMechanism=DEFAULT`
+ : `mongodb://${config.mongoOptions.host}`,
+ { authSource: config.mongoOptions.authSource }
+);
await mongoClient.connect();
const database = mongoClient.db();
const collectionOptions = { authdb: config.mongoOptions.authSource, w: "majority" };
const getIV = () => crypto.randomBytes(16);
-
export class Guilds {
guilds: Collection<GuildConfig>;
defaultData: GuildConfig;
@@ -172,13 +183,13 @@
flags?: string[];
attachments?: TranscriptAttachment[];
stickerURLs?: string[];
- referencedMessage?: string | [string, string, string]; // the message id, the channel id, the guild id
+ referencedMessage?: string | [string, string, string]; // the message id, the channel id, the guild id
}
interface TranscriptSchema {
code: string;
for: TranscriptAuthor;
- type: "ticket" | "purge"
+ type: "ticket" | "purge";
guild: string;
channel: string;
messages: TranscriptMessage[];
@@ -186,7 +197,11 @@
createdBy: TranscriptAuthor;
}
-interface findDocSchema { channelID:string, messageID: string; transcript: string }
+interface findDocSchema {
+ channelID: string;
+ messageID: string;
+ transcript: string;
+}
export class Transcript {
transcripts: Collection<TranscriptSchema>;
@@ -208,21 +223,30 @@
do {
code = crypto.randomBytes(64).toString("base64").replace(/=/g, "").replace(/\//g, "_").replace(/\+/g, "-");
} while (await this.transcripts.findOne({ code: code }));
- const key = crypto.randomBytes(32**2).toString("base64").replace(/=/g, "").replace(/\//g, "_").replace(/\+/g, "-").substring(0, 32);
+ const key = crypto
+ .randomBytes(32 ** 2)
+ .toString("base64")
+ .replace(/=/g, "")
+ .replace(/\//g, "_")
+ .replace(/\+/g, "-")
+ .substring(0, 32);
const iv = getIV().toString("base64").replace(/=/g, "").replace(/\//g, "_").replace(/\+/g, "-");
- for(const message of transcript.messages) {
- if(message.content) {
+ for (const message of transcript.messages) {
+ if (message.content) {
const encCipher = crypto.createCipheriv("AES-256-CBC", key, iv);
message.content = encCipher.update(message.content, "utf8", "base64") + encCipher.final("base64");
}
}
const doc = await this.transcripts.insertOne(Object.assign(transcript, { code: code }), collectionOptions);
- if(doc.acknowledged) {
- client.database.eventScheduler.schedule("deleteTranscript", (Date.now() + 1000 * 60 * 60 * 24 * 7).toString(), { guild: transcript.guild, code: code, iv: iv, key: key });
+ if (doc.acknowledged) {
+ client.database.eventScheduler.schedule(
+ "deleteTranscript",
+ (Date.now() + 1000 * 60 * 60 * 24 * 7).toString(),
+ { guild: transcript.guild, code: code, iv: iv, key: key }
+ );
return [code, key, iv];
- }
- else return [null, null, null];
+ } else return [null, null, null];
}
async delete(code: string) {
@@ -242,30 +266,35 @@
// console.log("Transcript read")
let doc: TranscriptSchema | null = await this.transcripts.findOne({ code: code });
let findDoc: findDocSchema | null = null;
- if(!doc) findDoc = (await this.messageToTranscript.findOne({ transcript: code }));
- if(findDoc) {
- const message = await ((client.channels.cache.get(findDoc.channelID)) as Discord.TextBasedChannel | null)?.messages.fetch(findDoc.messageID);
- if(!message) return null;
+ if (!doc) findDoc = await this.messageToTranscript.findOne({ transcript: code });
+ if (findDoc) {
+ const message = await (
+ client.channels.cache.get(findDoc.channelID) as Discord.TextBasedChannel | null
+ )?.messages.fetch(findDoc.messageID);
+ if (!message) return null;
const attachment = message.attachments.first();
- if(!attachment) return null;
+ if (!attachment) return null;
const transcript = (await fetch(attachment.url)).body;
- if(!transcript) return null;
+ if (!transcript) return null;
const reader = transcript.getReader();
let data: Uint8Array | null = null;
let allPacketsReceived = false;
while (!allPacketsReceived) {
const { value, done } = await reader.read();
- if (done) {allPacketsReceived = true; continue;}
- if(!data) {
+ if (done) {
+ allPacketsReceived = true;
+ continue;
+ }
+ if (!data) {
data = value;
} else {
data = new Uint8Array(Buffer.concat([data, value]));
}
}
- if(!data) return null;
+ if (!data) return null;
doc = JSON.parse(Buffer.from(data).toString()) as TranscriptSchema;
}
- if(!doc) return null;
+ if (!doc) return null;
return doc;
}
@@ -273,32 +302,34 @@
// console.log("Transcript read")
let doc: TranscriptSchema | null = await this.transcripts.findOne({ code: code });
let findDoc: findDocSchema | null = null;
- if(!doc) findDoc = (await this.messageToTranscript.findOne({ transcript: code }));
- if(findDoc) {
- const message = await ((client.channels.cache.get(findDoc.channelID)) as Discord.TextBasedChannel | null)?.messages.fetch(findDoc.messageID);
- if(!message) return null;
+ if (!doc) findDoc = await this.messageToTranscript.findOne({ transcript: code });
+ if (findDoc) {
+ const message = await (
+ client.channels.cache.get(findDoc.channelID) as Discord.TextBasedChannel | null
+ )?.messages.fetch(findDoc.messageID);
+ if (!message) return null;
const attachment = message.attachments.first();
- if(!attachment) return null;
+ if (!attachment) return null;
const transcript = (await fetch(attachment.url)).body;
- if(!transcript) return null;
+ if (!transcript) return null;
const reader = transcript.getReader();
let data: Uint8Array | null = null;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, no-constant-condition
- while(true) {
+ while (true) {
const { value, done } = await reader.read();
if (done) break;
- if(!data) {
+ if (!data) {
data = value;
} else {
data = new Uint8Array(Buffer.concat([data, value]));
}
}
- if(!data) return null;
+ if (!data) return null;
doc = JSON.parse(Buffer.from(data).toString()) as TranscriptSchema;
}
- if(!doc) return null;
- for(const message of doc.messages) {
- if(message.content) {
+ if (!doc) return null;
+ for (const message of doc.messages) {
+ if (message.content) {
const decCipher = crypto.createDecipheriv("AES-256-CBC", key, iv);
message.content = decCipher.update(message.content, "base64", "utf8") + decCipher.final("utf8");
}
@@ -306,8 +337,12 @@
return doc;
}
- async createTranscript(messages: Message[], interaction: MessageComponentInteraction | CommandInteraction, member: GuildMember) {
- const interactionMember = await interaction.guild?.members.fetch(interaction.user.id)
+ async createTranscript(
+ messages: Message[],
+ interaction: MessageComponentInteraction | CommandInteraction,
+ member: GuildMember
+ ) {
+ const interactionMember = await interaction.guild?.members.fetch(interaction.user.id);
const newOut: Omit<TranscriptSchema, "code"> = {
type: "ticket",
for: {
@@ -317,7 +352,7 @@
topRole: {
color: member!.roles.highest.color
},
- iconURL: member!.user.displayAvatarURL({ forceStatic: true}),
+ iconURL: member!.user.displayAvatarURL({ forceStatic: true }),
bot: member!.user.bot
},
guild: interaction.guild!.id,
@@ -331,12 +366,12 @@
topRole: {
color: interactionMember?.roles.highest.color ?? 0x000000
},
- iconURL: interaction.user.displayAvatarURL({ forceStatic: true}),
+ iconURL: interaction.user.displayAvatarURL({ forceStatic: true }),
bot: interaction.user.bot
}
- }
- if(member.nickname) newOut.for.nickname = member.nickname;
- if(interactionMember?.roles.icon) newOut.createdBy.topRole.badgeURL = interactionMember.roles.icon.iconURL()!;
+ };
+ if (member.nickname) newOut.for.nickname = member.nickname;
+ if (interactionMember?.roles.icon) newOut.createdBy.topRole.badgeURL = interactionMember.roles.icon.iconURL()!;
messages.reverse().forEach((message) => {
const msg: TranscriptMessage = {
id: message.id,
@@ -347,55 +382,67 @@
topRole: {
color: message.member!.roles.highest.color
},
- iconURL: message.member!.user.displayAvatarURL({ forceStatic: true}),
+ iconURL: message.member!.user.displayAvatarURL({ forceStatic: true }),
bot: message.author.bot
},
createdTimestamp: message.createdTimestamp
};
- if(message.member?.nickname) msg.author.nickname = message.member.nickname;
+ if (message.member?.nickname) msg.author.nickname = message.member.nickname;
if (message.member!.roles.icon) msg.author.topRole.badgeURL = message.member!.roles.icon.iconURL()!;
if (message.content) msg.content = message.content;
- if (message.embeds.length > 0) msg.embeds = message.embeds.map(embed => {
- const obj: TranscriptEmbed = {};
- if (embed.title) obj.title = embed.title;
- if (embed.description) obj.description = embed.description;
- if (embed.fields.length > 0) obj.fields = embed.fields.map(field => {
- return {
- name: field.name,
- value: field.value,
- inline: field.inline ?? false
- }
+ if (message.embeds.length > 0)
+ msg.embeds = message.embeds.map((embed) => {
+ const obj: TranscriptEmbed = {};
+ if (embed.title) obj.title = embed.title;
+ if (embed.description) obj.description = embed.description;
+ if (embed.fields.length > 0)
+ obj.fields = embed.fields.map((field) => {
+ return {
+ name: field.name,
+ value: field.value,
+ inline: field.inline ?? false
+ };
+ });
+ if (embed.color) obj.color = embed.color;
+ if (embed.timestamp) obj.timestamp = embed.timestamp;
+ if (embed.footer)
+ obj.footer = {
+ text: embed.footer.text
+ };
+ if (embed.footer?.iconURL) obj.footer!.iconURL = embed.footer.iconURL;
+ if (embed.author)
+ obj.author = {
+ name: embed.author.name
+ };
+ if (embed.author?.iconURL) obj.author!.iconURL = embed.author.iconURL;
+ if (embed.author?.url) obj.author!.url = embed.author.url;
+ return obj;
});
- if (embed.color) obj.color = embed.color;
- if (embed.timestamp) obj.timestamp = embed.timestamp
- if (embed.footer) obj.footer = {
- text: embed.footer.text,
- };
- if (embed.footer?.iconURL) obj.footer!.iconURL = embed.footer.iconURL;
- if (embed.author) obj.author = {
- name: embed.author.name
- };
- if (embed.author?.iconURL) obj.author!.iconURL = embed.author.iconURL;
- if (embed.author?.url) obj.author!.url = embed.author.url;
- return obj;
- });
- if (message.components.length > 0) msg.components = message.components.map(component => component.components.map(child => {
- const obj: TranscriptComponent = {
- type: child.type
- }
- if (child.type === ComponentType.Button) {
- obj.style = child.style;
- obj.label = child.label ?? "";
- } else if (child.type > 2) {
- obj.placeholder = child.placeholder ?? "";
- }
- return obj
- }));
+ if (message.components.length > 0)
+ msg.components = message.components.map((component) =>
+ component.components.map((child) => {
+ const obj: TranscriptComponent = {
+ type: child.type
+ };
+ if (child.type === ComponentType.Button) {
+ obj.style = child.style;
+ obj.label = child.label ?? "";
+ } else if (child.type > 2) {
+ obj.placeholder = child.placeholder ?? "";
+ }
+ return obj;
+ })
+ );
if (message.editedTimestamp) msg.editedTimestamp = message.editedTimestamp;
msg.flags = message.flags.toArray();
- if (message.stickers.size > 0) msg.stickerURLs = message.stickers.map(sticker => sticker.url);
- if (message.reference) msg.referencedMessage = [message.reference.guildId ?? "", message.reference.channelId, message.reference.messageId ?? ""];
+ if (message.stickers.size > 0) msg.stickerURLs = message.stickers.map((sticker) => sticker.url);
+ if (message.reference)
+ msg.referencedMessage = [
+ message.reference.guildId ?? "",
+ message.reference.channelId,
+ message.reference.messageId ?? ""
+ ];
newOut.messages.push(msg);
});
return newOut;
@@ -407,10 +454,11 @@
if (message.referencedMessage) {
if (Array.isArray(message.referencedMessage)) {
out += `> [Crosspost From] ${message.referencedMessage[0]} in ${message.referencedMessage[1]} in ${message.referencedMessage[2]}\n`;
- }
- else out += `> [Reply To] ${message.referencedMessage}\n`;
+ } else out += `> [Reply To] ${message.referencedMessage}\n`;
}
- out += `${message.author.nickname ?? message.author.username}#${message.author.discriminator} (${message.author.id}) (${message.id})`;
+ out += `${message.author.nickname ?? message.author.username}#${message.author.discriminator} (${
+ message.author.id
+ }) (${message.id})`;
out += ` [${new Date(message.createdTimestamp).toISOString()}]`;
if (message.editedTimestamp) out += ` [Edited: ${new Date(message.editedTimestamp).toISOString()}]`;
out += "\n";
@@ -445,9 +493,9 @@
out += `[Attachment] ${attachment.filename} (${attachment.size} bytes) ${attachment.url}\n`;
}
}
- out += "\n\n"
+ out += "\n\n";
}
- return out
+ return out;
}
}
@@ -469,17 +517,20 @@
amount?: string | null
) {
// console.log("History create");
- await this.histories.insertOne({
- type: type,
- guild: guild,
- user: user.id,
- moderator: moderator ? moderator.id : null,
- reason: reason,
- occurredAt: new Date(),
- before: before ?? null,
- after: after ?? null,
- amount: amount ?? null
- }, collectionOptions);
+ await this.histories.insertOne(
+ {
+ type: type,
+ guild: guild,
+ user: user.id,
+ moderator: moderator ? moderator.id : null,
+ reason: reason,
+ occurredAt: new Date(),
+ before: before ?? null,
+ after: after ?? null,
+ amount: amount ?? null
+ },
+ collectionOptions
+ );
}
async read(guild: string, user: string, year: number) {
@@ -524,12 +575,18 @@
async write(hash: string, data: boolean, tags?: string[]) {
// console.log("ScanCache write");
- await this.scanCache.insertOne({ hash: hash, data: data, tags: tags ?? [], addedAt: new Date() }, collectionOptions);
+ await this.scanCache.insertOne(
+ { hash: hash, data: data, tags: tags ?? [], addedAt: new Date() },
+ collectionOptions
+ );
}
async cleanup() {
// console.log("ScanCache cleanup");
- await this.scanCache.deleteMany({ addedAt: { $lt: new Date(Date.now() - (1000 * 60 * 60 * 24 * 31)) }, hash: { $not$text: "http"} });
+ await this.scanCache.deleteMany({
+ addedAt: { $lt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 31) },
+ hash: { $not$text: "http" }
+ });
}
}
@@ -559,7 +616,7 @@
cpu: number;
memory: number;
temperature: number;
- }
+ };
}
export class ModNotes {
@@ -588,8 +645,8 @@
export class Premium {
premium: Collection<PremiumSchema>;
- cache: Map<string, [boolean, string, number, boolean, Date]>; // Date indicates the time one hour after it was created
- cacheTimeout = 1000 * 60 * 60; // 1 hour
+ cache: Map<string, [boolean, string, number, boolean, Date]>; // Date indicates the time one hour after it was created
+ cacheTimeout = 1000 * 60 * 60; // 1 hour
constructor() {
this.premium = database.collection<PremiumSchema>("premium");
@@ -598,7 +655,7 @@
async updateUser(user: string, level: number) {
// console.log("Premium updateUser");
- if(!(await this.userExists(user))) await this.createUser(user, level);
+ if (!(await this.userExists(user))) await this.createUser(user, level);
await this.premium.updateOne({ user: user }, { $set: { level: level } }, { upsert: true });
}
@@ -618,25 +675,32 @@
const cached = this.cache.get(guild);
if (cached && cached[4].getTime() < Date.now()) return [cached[0], cached[1], cached[2], cached[3]];
const entries = await this.premium.find({}).toArray();
- const members = (await client.guilds.fetch(guild)).members.cache
- for(const {user} of entries) {
+ const members = (await client.guilds.fetch(guild)).members.cache;
+ for (const { user } of entries) {
const member = members.get(user);
- if(member) { //TODO: Notify user if they've given premium to a server that has since gotten premium via a mod.
+ if (member) {
+ //TODO: Notify user if they've given premium to a server that has since gotten premium via a mod.
const modPerms = //TODO: Create list in config for perms
- member.permissions.has("Administrator") ||
- member.permissions.has("ManageChannels") ||
- member.permissions.has("ManageRoles") ||
- member.permissions.has("ManageEmojisAndStickers") ||
- member.permissions.has("ManageWebhooks") ||
- member.permissions.has("ManageGuild") ||
- member.permissions.has("KickMembers") ||
- member.permissions.has("BanMembers") ||
- member.permissions.has("ManageEvents") ||
- member.permissions.has("ManageMessages") ||
- member.permissions.has("ManageThreads")
- const entry = entries.find(e => e.user === member.id);
- if(entry && (entry.level === 3) && modPerms) {
- this.cache.set(guild, [true, member.id, entry.level, true, new Date(Date.now() + this.cacheTimeout)]);
+ member.permissions.has("Administrator") ||
+ member.permissions.has("ManageChannels") ||
+ member.permissions.has("ManageRoles") ||
+ member.permissions.has("ManageEmojisAndStickers") ||
+ member.permissions.has("ManageWebhooks") ||
+ member.permissions.has("ManageGuild") ||
+ member.permissions.has("KickMembers") ||
+ member.permissions.has("BanMembers") ||
+ member.permissions.has("ManageEvents") ||
+ member.permissions.has("ManageMessages") ||
+ member.permissions.has("ManageThreads");
+ const entry = entries.find((e) => e.user === member.id);
+ if (entry && entry.level === 3 && modPerms) {
+ this.cache.set(guild, [
+ true,
+ member.id,
+ entry.level,
+ true,
+ new Date(Date.now() + this.cacheTimeout)
+ ]);
return [true, member.id, entry.level, true];
}
}
@@ -648,7 +712,13 @@
}
}
});
- this.cache.set(guild, [entry ? true : false, entry?.user ?? "", entry?.level ?? 0, false, new Date(Date.now() + this.cacheTimeout)]);
+ this.cache.set(guild, [
+ entry ? true : false,
+ entry?.user ?? "",
+ entry?.level ?? 0,
+ false,
+ new Date(Date.now() + this.cacheTimeout)
+ ]);
return entry ? [true, entry.user, entry.level, false] : null;
}
@@ -662,11 +732,11 @@
async checkAllPremium(member?: GuildMember) {
// console.log("Premium checkAllPremium");
const entries = await this.premium.find({}).toArray();
- if(member) {
- const entry = entries.find(e => e.user === member.id);
- if(entry) {
+ if (member) {
+ const entry = entries.find((e) => e.user === member.id);
+ if (entry) {
const expiresAt = entry.expiresAt;
- if(expiresAt) expiresAt < Date.now() ? await this.premium.deleteOne({user: member.id}) : null;
+ if (expiresAt) expiresAt < Date.now() ? await this.premium.deleteOne({ user: member.id }) : null;
}
const roles = member.roles;
let level = 0;
@@ -681,17 +751,20 @@
}
await this.updateUser(member.id, level);
if (level > 0) {
- await this.premium.updateOne({ user: member.id }, {$unset: { expiresAt: ""}})
+ await this.premium.updateOne({ user: member.id }, { $unset: { expiresAt: "" } });
} else {
- await this.premium.updateOne({ user: member.id }, {$set: { expiresAt: (Date.now() + (1000*60*60*24*3)) }})
+ await this.premium.updateOne(
+ { user: member.id },
+ { $set: { expiresAt: Date.now() + 1000 * 60 * 60 * 24 * 3 } }
+ );
}
} else {
- const members = await (await client.guilds.fetch('684492926528651336')).members.fetch();
- for(const {roles, id} of members.values()) {
- const entry = entries.find(e => e.user === id);
- if(entry) {
+ const members = await (await client.guilds.fetch("684492926528651336")).members.fetch();
+ for (const { roles, id } of members.values()) {
+ const entry = entries.find((e) => e.user === id);
+ if (entry) {
const expiresAt = entry.expiresAt;
- if(expiresAt) expiresAt < Date.now() ? await this.premium.deleteOne({user: id}) : null;
+ if (expiresAt) expiresAt < Date.now() ? await this.premium.deleteOne({ user: id }) : null;
}
let level: number = 0;
if (roles.cache.has("1066468879309750313")) {
@@ -705,9 +778,12 @@
}
await this.updateUser(id, level);
if (level > 0) {
- await this.premium.updateOne({ user: id }, {$unset: { expiresAt: ""}})
+ await this.premium.updateOne({ user: id }, { $unset: { expiresAt: "" } });
} else {
- await this.premium.updateOne({ user: id }, {$set: { expiresAt: (Date.now() + (1000*60*60*24*3)) }})
+ await this.premium.updateOne(
+ { user: id },
+ { $set: { expiresAt: Date.now() + 1000 * 60 * 60 * 24 * 3 } }
+ );
}
}
}
@@ -773,13 +849,13 @@
allowed: {
users: string[];
roles: string[];
- }
- }
+ };
+ };
};
autoPublish: {
enabled: boolean;
channels: string[];
- }
+ };
welcome: {
enabled: boolean;
role: string | null;
@@ -846,7 +922,7 @@
nick: {
text: string | null;
link: string | null;
- }
+ };
};
tracks: {
name: string;
diff --git a/src/utils/defaults.ts b/src/utils/defaults.ts
index 1331ce1..0d4c9e3 100644
--- a/src/utils/defaults.ts
+++ b/src/utils/defaults.ts
@@ -9,7 +9,7 @@
export const LinkWarningFooter = {
text: "The button below will take you to a website set by the server moderators. Do not enter any passwords unless it is from a trusted website.",
iconURL: "https://cdn.discordapp.com/emojis/952295894370369587.webp?size=128&quality=lossless"
-}
+};
class Embed {
embed: EmojiEmbed = new EmojiEmbed();
diff --git a/src/utils/dualCollector.ts b/src/utils/dualCollector.ts
index 0b05779..bf9b0c0 100644
--- a/src/utils/dualCollector.ts
+++ b/src/utils/dualCollector.ts
@@ -1,4 +1,13 @@
-import { ButtonInteraction, Client, User, Interaction, InteractionCollector, Message, MessageComponentInteraction, ModalSubmitInteraction } from "discord.js";
+import {
+ ButtonInteraction,
+ Client,
+ User,
+ Interaction,
+ InteractionCollector,
+ Message,
+ MessageComponentInteraction,
+ ModalSubmitInteraction
+} from "discord.js";
import client from "./client.js";
export default async function (
@@ -10,14 +19,15 @@
try {
out = await new Promise((resolve, _reject) => {
const mes = m
- .createMessageComponentCollector({
- filter: (m) => interactionFilter(m),
- time: 300000
- })
- .on("collect", (m) => {
+ .createMessageComponentCollector({
+ filter: (m) => interactionFilter(m),
+ time: 300000
+ })
+ .on("collect", (m) => {
resolve(m);
});
- const int = m.channel.createMessageCollector({
+ const int = m.channel
+ .createMessageCollector({
filter: (m) => messageFilter(m),
time: 300000
})
@@ -45,15 +55,15 @@
}
function defaultInteractionFilter(i: MessageComponentInteraction, user: User, m: Message) {
- return i.channel!.id === m.channel!.id && i.user.id === user.id
+ return i.channel!.id === m.channel!.id && i.user.id === user.id;
}
function defaultModalFilter(i: ModalSubmitInteraction, user: User, m: Message) {
- return i.channel!.id === m.channel!.id && i.user.id === user.id
+ return i.channel!.id === m.channel!.id && i.user.id === user.id;
}
-
export async function modalInteractionCollector(
- m: Message, user: User,
+ m: Message,
+ user: User,
modalFilter?: (i: Interaction) => boolean | Promise<boolean>,
interactionFilter?: (i: MessageComponentInteraction) => boolean | Promise<boolean>
): Promise<null | ButtonInteraction | ModalSubmitInteraction> {
@@ -62,7 +72,8 @@
out = await new Promise((resolve, _reject) => {
const int = m
.createMessageComponentCollector({
- filter: (i: MessageComponentInteraction) => (interactionFilter ? interactionFilter(i) : true) && defaultInteractionFilter(i, user, m),
+ filter: (i: MessageComponentInteraction) =>
+ (interactionFilter ? interactionFilter(i) : true) && defaultInteractionFilter(i, user, m),
time: 300000
})
.on("collect", async (i: ButtonInteraction) => {
@@ -72,7 +83,8 @@
resolve(i);
});
const mod = new InteractionCollector(client as Client, {
- filter: (i: Interaction) => (modalFilter ? modalFilter(i) : true) && i.isModalSubmit() && defaultModalFilter(i, user, m),
+ filter: (i: Interaction) =>
+ (modalFilter ? modalFilter(i) : true) && i.isModalSubmit() && defaultModalFilter(i, user, m),
time: 300000
}).on("collect", async (i: ModalSubmitInteraction) => {
int.stop();
diff --git a/src/utils/ellipsis.ts b/src/utils/ellipsis.ts
index 6ec5888..4ba1f72 100644
--- a/src/utils/ellipsis.ts
+++ b/src/utils/ellipsis.ts
@@ -1,4 +1,4 @@
export default (str: string, max: number): string => {
if (str.length <= max) return str;
return str.slice(0, max - 3) + "...";
-}
\ No newline at end of file
+};
diff --git a/src/utils/eventScheduler.ts b/src/utils/eventScheduler.ts
index f3b7a00..2ef5fb4 100644
--- a/src/utils/eventScheduler.ts
+++ b/src/utils/eventScheduler.ts
@@ -23,20 +23,31 @@
await job.remove();
});
this.agenda.define("uploadTranscript", async (job) => {
- const channelID: string | null = (await client.database.guilds.read(job.attrs.data.guild)).logging.logs.channel;
+ const channelID: string | null = (await client.database.guilds.read(job.attrs.data.guild)).logging.logs
+ .channel;
if (!channelID) return;
const channel = await client.channels.fetch(channelID);
- if(!channel || !(channel instanceof TextChannel)) return;
- const transcript = await client.database.transcripts.read(job.attrs.data.transcript, job.attrs.data.key, job.attrs.data.iv);
+ if (!channel || !(channel instanceof TextChannel)) return;
+ const transcript = await client.database.transcripts.read(
+ job.attrs.data.transcript,
+ job.attrs.data.key,
+ job.attrs.data.iv
+ );
await client.database.transcripts.delete(job.attrs.data.transcript);
const file = Buffer.from(JSON.stringify(transcript), "base64");
const fileName = `${job.attrs.data.transcript}.json`;
const m = await channel.send({ files: [{ attachment: file, name: fileName }] });
- await client.database.transcripts.upload({ channelID: channel.id, messageID: m.id, transcript: job.attrs.data.transcript})
+ await client.database.transcripts.upload({
+ channelID: channel.id,
+ messageID: m.id,
+ transcript: job.attrs.data.transcript
+ });
await job.remove();
});
this.agenda.define("deleteFile", async (job) => {
- fs.rm(path.resolve("dist/utils/temp", job.attrs.data.fileName), (e) => { client.emit("error", e as Error); });
+ fs.rm(path.resolve("dist/utils/temp", job.attrs.data.fileName), (e) => {
+ client.emit("error", e as Error);
+ });
await job.remove();
});
this.agenda.define("naturalUnmute", async (job) => {
diff --git a/src/utils/generateEmojiEmbed.ts b/src/utils/generateEmojiEmbed.ts
index a326fc5..542fc18 100644
--- a/src/utils/generateEmojiEmbed.ts
+++ b/src/utils/generateEmojiEmbed.ts
@@ -13,9 +13,13 @@
description = "";
_generateTitle() {
- if (this._emoji && !this._title) return getEmojiByName(this._emoji)
- if (this._emoji) { return `${getEmojiByName(this._emoji)} ${this._title}`; }
- if (this._title) { return this._title };
+ if (this._emoji && !this._title) return getEmojiByName(this._emoji);
+ if (this._emoji) {
+ return `${getEmojiByName(this._emoji)} ${this._title}`;
+ }
+ if (this._title) {
+ return this._title;
+ }
return "";
}
@@ -42,5 +46,4 @@
}
}
-
export default EmojiEmbed;
diff --git a/src/utils/getCommandDataByName.ts b/src/utils/getCommandDataByName.ts
index da3e54b..46f4362 100644
--- a/src/utils/getCommandDataByName.ts
+++ b/src/utils/getCommandDataByName.ts
@@ -1,22 +1,20 @@
import type Discord from "discord.js";
import client from "./client.js";
-
export const getCommandMentionByName = (name: string): string => {
- const split = name.replaceAll("/", " ").split(" ")
+ const split = name.replaceAll("/", " ").split(" ");
const commandName: string = split[0]!;
const filterCommand = (command: Discord.ApplicationCommand) => command.name === commandName;
- const command = client.fetchedCommands.filter(c => filterCommand(c))
+ const command = client.fetchedCommands.filter((c) => filterCommand(c));
if (command.size === 0) return `\`/${name.replaceAll("/", " ")}\``;
const commandID = command.first()!.id;
return `</${split.join(" ")}:${commandID}>`;
-}
+};
-export const getCommandByName = (name: string): {name: string, description: string, mention: string} => {
-
- const split = name.replaceAll(" ", "/")
+export const getCommandByName = (name: string): { name: string; description: string; mention: string } => {
+ const split = name.replaceAll(" ", "/");
const command = client.commands["commands/" + split]!;
// console.log(command)
const mention = getCommandMentionByName(name);
@@ -24,5 +22,5 @@
name: command[1].name,
description: command[1].description,
mention: mention
- }
-}
\ No newline at end of file
+ };
+};
diff --git a/src/utils/getEmojiByName.ts b/src/utils/getEmojiByName.ts
index 9df17a4..99d1215 100644
--- a/src/utils/getEmojiByName.ts
+++ b/src/utils/getEmojiByName.ts
@@ -1,5 +1,5 @@
import emojis from "../config/emojis.json" assert { type: "json" };
-import lodash from 'lodash';
+import lodash from "lodash";
const isArray = lodash.isArray;
interface EmojisIndex {
diff --git a/src/utils/listToAndMore.ts b/src/utils/listToAndMore.ts
index 791ce40..047cbc9 100644
--- a/src/utils/listToAndMore.ts
+++ b/src/utils/listToAndMore.ts
@@ -1,7 +1,7 @@
export default (list: string[], max: number) => {
// PineappleFan, Coded, Mini (and 10 more)
- if(list.length > max) {
+ if (list.length > max) {
return list.slice(0, max).join(", ") + ` (and ${list.length - max} more)`;
}
return list.join(", ");
-}
\ No newline at end of file
+};
diff --git a/src/utils/log.ts b/src/utils/log.ts
index bb95eda..0601863 100644
--- a/src/utils/log.ts
+++ b/src/utils/log.ts
@@ -20,18 +20,20 @@
list: any;
hidden: {
guild: string;
- },
+ };
separate?: {
start?: string;
end?: string;
- }
+ };
}
async function isLogging(guild: string, type: string): Promise<boolean> {
const config = await client.database.guilds.read(guild);
if (!config.logging.logs.enabled) return false;
if (!config.logging.logs.channel) return false;
- if (!toHexArray(config.logging.logs.toLog).includes(type)) { return false; }
+ if (!toHexArray(config.logging.logs.toLog).includes(type)) {
+ return false;
+ }
return true;
}
@@ -52,16 +54,21 @@
const delta = num2 - num1;
return `${num1} -> ${num2} (${delta > 0 ? "+" : ""}${delta})`;
},
- entry(value: string | number | boolean | null | (string | boolean)[], displayValue: string): { value: string | boolean | null | (string | boolean | number)[]; displayValue: string } {
+ entry(
+ value: string | number | boolean | null | (string | boolean)[],
+ displayValue: string
+ ): { value: string | boolean | null | (string | boolean | number)[]; displayValue: string } {
if (typeof value === "number") value = value.toString();
return { value: value, displayValue: displayValue };
},
renderChannel(channel: Discord.GuildChannel | Discord.ThreadChannel | string) {
- if (typeof channel === "string") channel = client.channels.cache.get(channel) as Discord.GuildChannel | Discord.ThreadChannel;
+ if (typeof channel === "string")
+ channel = client.channels.cache.get(channel) as Discord.GuildChannel | Discord.ThreadChannel;
return `${channel.name} [<#${channel.id}>]`;
},
renderRole(role: Discord.Role | string, guild?: Discord.Guild | string) {
- if (typeof role === "string") role = (typeof guild === "string" ? client.guilds.cache.get(guild) : guild)!.roles.cache.get(role)!;
+ if (typeof role === "string")
+ role = (typeof guild === "string" ? client.guilds.cache.get(guild) : guild)!.roles.cache.get(role)!;
return `${role.name} [<@&${role.id}>]`;
},
renderEmoji(emoji: Discord.GuildEmoji) {
@@ -72,16 +79,20 @@
yellow: 0xf2d478,
green: 0x68d49e
},
- async getAuditLog(guild: Discord.Guild, event: Discord.GuildAuditLogsResolvable, delay?: number): Promise<Discord.GuildAuditLogsEntry[]> {
+ async getAuditLog(
+ guild: Discord.Guild,
+ event: Discord.GuildAuditLogsResolvable,
+ delay?: number
+ ): Promise<Discord.GuildAuditLogsEntry[]> {
await wait(delay ?? 250);
- const auditLog = (await guild.fetchAuditLogs({ type: event })).entries.map(m => m)
+ const auditLog = (await guild.fetchAuditLogs({ type: event })).entries.map((m) => m);
return auditLog as Discord.GuildAuditLogsEntry[];
},
async log(log: LoggerOptions): Promise<void> {
- if (!await isLogging(log.hidden.guild, log.meta.calculateType)) return;
- console.log(log.hidden.guild)
+ if (!(await isLogging(log.hidden.guild, log.meta.calculateType))) return;
+ console.log(log.hidden.guild);
const config = await client.database.guilds.read(log.hidden.guild);
- console.log(config.logging.logs.channel)
+ console.log(config.logging.logs.channel);
if (config.logging.logs.channel) {
const channel = (await client.channels.fetch(config.logging.logs.channel)) as Discord.TextChannel | null;
@@ -102,8 +113,8 @@
.setTitle(`${getEmojiByName(log.meta.emoji)} ${log.meta.displayName}`)
.setDescription(
(log.separate.start ? log.separate.start + "\n" : "") +
- generateKeyValueList(description) +
- (log.separate.end ? "\n" + log.separate.end : "")
+ generateKeyValueList(description) +
+ (log.separate.end ? "\n" + log.separate.end : "")
)
.setTimestamp(log.meta.timestamp)
.setColor(log.meta.color);
diff --git a/src/utils/memory.ts b/src/utils/memory.ts
index 60a6535..e43f82c 100644
--- a/src/utils/memory.ts
+++ b/src/utils/memory.ts
@@ -22,7 +22,7 @@
}
}
}, 1000 * 60 * 30);
- };
+ }
async readGuildInfo(guild: string): Promise<GuildData> {
if (!this.memory.has(guild)) {
@@ -37,7 +37,7 @@
});
}
return this.memory.get(guild)!;
- };
+ }
async forceUpdate(guild: string) {
if (this.memory.has(guild)) this.memory.delete(guild);
diff --git a/src/utils/performanceTesting/record.ts b/src/utils/performanceTesting/record.ts
index 71883c5..89f3ead 100644
--- a/src/utils/performanceTesting/record.ts
+++ b/src/utils/performanceTesting/record.ts
@@ -1,14 +1,13 @@
import client from "../client.js";
-import * as CP from 'child_process';
-import * as process from 'process';
+import * as CP from "child_process";
+import * as process from "process";
import systeminformation from "systeminformation";
import config from "../../config/main.js";
import singleNotify from "../singleNotify.js";
-
const discordPing = () => {
return client.ws.ping;
-}
+};
const databaseReadTime = async () => {
const guild = await client.guilds.fetch(config.managementGuildID);
@@ -18,15 +17,15 @@
client.database.history.read(guild.id, user, currentYear - 1);
const end = Date.now();
return end - start;
-}
+};
const resources = async () => {
return {
memory: process.memoryUsage().rss / 1024 / 1024,
cpu: parseFloat(CP.execSync(`ps -p ${process.pid} -o %cpu=`).toString().trim()),
temperature: (await systeminformation.cpuTemperature()).main
- }
-}
+ };
+};
const record = async () => {
if (config.enableDevelopment) return;
@@ -39,18 +38,22 @@
singleNotify(
"performanceTest",
config.developmentGuildID,
- `Discord ping time: \`${results.discord}ms\`\nDatabase read time: \`${results.databaseRead}ms\`\nCPU usage: \`${results.resources.cpu}%\`\nMemory usage: \`${Math.round(results.resources.memory)}MB\`\nCPU temperature: \`${results.resources.temperature}°C\``,
+ `Discord ping time: \`${results.discord}ms\`\nDatabase read time: \`${
+ results.databaseRead
+ }ms\`\nCPU usage: \`${results.resources.cpu}%\`\nMemory usage: \`${Math.round(
+ results.resources.memory
+ )}MB\`\nCPU temperature: \`${results.resources.temperature}°C\``,
"Critical",
config.owners
- )
+ );
} else {
- singleNotify("performanceTest", config.developmentGuildID, true)
+ singleNotify("performanceTest", config.developmentGuildID, true);
}
- client.database.performanceTest.record(results)
+ client.database.performanceTest.record(results);
setTimeout(async () => {
await record();
}, 60 * 1000);
-}
+};
export { record };
diff --git a/src/utils/search.ts b/src/utils/search.ts
index 310dbf8..5fce74f 100644
--- a/src/utils/search.ts
+++ b/src/utils/search.ts
@@ -2,17 +2,14 @@
function getResults(typed: string, options: string[]): string[] {
options = options.filter((option) => option.length <= 100); // thanks discord. 6000 character limit on slash command inputs but only 100 for autocomplete.
- if (!typed)
- return options
- .slice(0, 25)
- .sort()
+ if (!typed) return options.slice(0, 25).sort();
// @ts-expect-error
const fuse = new Fuse(options, {
useExtendedSearch: true,
findAllMatches: true,
- minMatchCharLength: typed.length > 3 ? 3 : typed.length,
+ minMatchCharLength: typed.length > 3 ? 3 : typed.length
}).search(typed);
- return fuse.slice(0, 25).map((option: {item: string }) => option.item );
+ return fuse.slice(0, 25).map((option: { item: string }) => option.item);
}
-export { getResults }
\ No newline at end of file
+export { getResults };
diff --git a/src/utils/singleNotify.ts b/src/utils/singleNotify.ts
index 6bf63e1..08c7af5 100644
--- a/src/utils/singleNotify.ts
+++ b/src/utils/singleNotify.ts
@@ -33,13 +33,15 @@
if (!channel) return;
if (!channel.isTextBased()) return;
const textChannel = channel as TextChannel | ThreadChannel | NewsChannel;
- let messageData = {embeds: [
- new EmojiEmbed()
- .setTitle(`${severity} notification`)
- .setDescription(message)
- .setStatus(severities.get(severity))
- .setEmoji("CONTROL.BLOCKCROSS")
- ]}
+ let messageData = {
+ embeds: [
+ new EmojiEmbed()
+ .setTitle(`${severity} notification`)
+ .setDescription(message)
+ .setStatus(severities.get(severity))
+ .setEmoji("CONTROL.BLOCKCROSS")
+ ]
+ };
if (pings) {
messageData = Object.assign(messageData, {
content: pings.map((ping) => `<@${ping}>`).join(" ")
diff --git a/tsconfig.json b/tsconfig.json
index 537e3dc..8b0fe7d 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -11,7 +11,7 @@
"resolveJsonModule": true,
"moduleResolution": "NodeNext",
"skipLibCheck": true,
- "noImplicitReturns": false,
+ "noImplicitReturns": false
},
"include": ["src/**/*", "src/*", "src/config/main.d.ts", "src/config/main.ts"],
"exclude": ["src/Unfinished/**/*"]