Bug fixes and ~~performance~~ typing improvements
diff --git a/src/utils/calculate.ts b/src/utils/calculate.ts
index 6d0c55f..6bbbe2e 100644
--- a/src/utils/calculate.ts
+++ b/src/utils/calculate.ts
@@ -21,14 +21,7 @@
"ticketUpdate"
];
-const tickets = [
- "support",
- "report",
- "question",
- "issue",
- "suggestion",
- "other"
-];
+const tickets = ["support", "report", "question", "issue", "suggestion", "other"];
const toHexInteger = (permissions, array?) => {
if (!array) {
diff --git a/src/utils/confirmationMessage.ts b/src/utils/confirmationMessage.ts
index 728cc52..a8c7ab4 100644
--- a/src/utils/confirmationMessage.ts
+++ b/src/utils/confirmationMessage.ts
@@ -1,8 +1,11 @@
import Discord, {
CommandInteraction,
+ Interaction,
Message,
MessageActionRow,
MessageButton,
+ MessageComponentInteraction,
+ ModalSubmitInteraction,
TextInputComponent
} from "discord.js";
import { modalInteractionCollector } from "./dualCollector.js";
@@ -77,7 +80,12 @@
this.reason = reason;
return this;
}
- async send(editOnly?: boolean) {
+ async send(editOnly?: boolean): Promise<{
+ success?: boolean;
+ cancelled?: boolean;
+ components?: Record<string, CustomBoolean<unknown>>;
+ newReason?: string;
+ }> {
while (true) {
const fullComponents = [
new Discord.MessageButton()
@@ -97,8 +105,7 @@
.setLabel(v.title)
.setStyle(v.active ? "SUCCESS" : "PRIMARY")
.setDisabled(v.disabled);
- if (v.emoji !== undefined)
- button.setEmoji(getEmojiByName(v.emoji, "id"));
+ if (v.emoji !== undefined) button.setEmoji(getEmojiByName(v.emoji, "id"));
fullComponents.push(button);
});
if (this.reason !== null)
@@ -112,11 +119,7 @@
);
const components = [];
for (let i = 0; i < fullComponents.length; i += 5) {
- components.push(
- new MessageActionRow().addComponents(
- fullComponents.slice(i, i + 5)
- )
- );
+ components.push(new MessageActionRow().addComponents(fullComponents.slice(i, i + 5)));
}
const object = {
embeds: [
@@ -144,9 +147,7 @@
if (editOnly) {
m = (await this.interaction.editReply(object)) as Message;
} else {
- m = (await this.interaction.reply(
- object
- )) as unknown as Message;
+ m = (await this.interaction.reply(object)) as unknown as Message;
}
} catch {
return { cancelled: true };
@@ -196,9 +197,7 @@
embeds: [
new EmojiEmbed()
.setTitle(this.title)
- .setDescription(
- "Modal opened. If you can't see it, click back and try again."
- )
+ .setDescription("Modal opened. If you can't see it, click back and try again.")
.setStatus(this.color)
.setEmoji(this.emoji)
],
@@ -216,23 +215,27 @@
try {
out = await modalInteractionCollector(
m,
- (m) => m.channel.id === this.interaction.channel.id,
+ (m: Interaction) =>
+ (m as MessageComponentInteraction | ModalSubmitInteraction).channelId ===
+ this.interaction.channelId,
(m) => m.customId === "reason"
);
} catch (e) {
- return {};
+ return { cancelled: true };
}
- if (out.fields) {
+ if (out === null) {
+ return { cancelled: true };
+ }
+ if (out instanceof ModalSubmitInteraction) {
return {
- newReason: out.fields.getTextInputValue("reason") ?? ""
+ newReason: out.fields.getTextInputValue("reason")
};
} else {
- return { newReason: this.reason };
+ return { components: this.customButtons };
}
} else {
component.deferUpdate();
- this.customButtons[component.customId].active =
- !this.customButtons[component.customId].active;
+ this.customButtons[component.customId]!.active = !this.customButtons[component.customId]!.active;
return { components: this.customButtons };
}
}
diff --git a/src/utils/convertCurlyBracketString.ts b/src/utils/convertCurlyBracketString.ts
index 49a4418..53c3267 100644
--- a/src/utils/convertCurlyBracketString.ts
+++ b/src/utils/convertCurlyBracketString.ts
@@ -1,33 +1,13 @@
-async function convertCurlyBracketString(
- str,
- memberID,
- memberName,
- serverName,
- members
-): Promise<string> {
+async function convertCurlyBracketString(str, memberID, memberName, serverName, members): Promise<string> {
const memberCount = (await members.fetch()).size;
const bots = (await members.fetch()).filter((m) => m.user.bot).size;
str = str
- .replace(
- "{member:mention}",
- memberID ? `<@${memberID}>` : "{member:mention}"
- )
- .replace(
- "{member:name}",
- memberName ? `${memberName}` : "{member:name}"
- )
+ .replace("{member:mention}", memberID ? `<@${memberID}>` : "{member:mention}")
+ .replace("{member:name}", memberName ? `${memberName}` : "{member:name}")
.replace("{serverName}", serverName ? `${serverName}` : "{serverName}")
- .replace(
- "{memberCount}",
- memberCount ? `${memberCount}` : "{memberCount}"
- )
+ .replace("{memberCount}", memberCount ? `${memberCount}` : "{memberCount}")
.replace("{memberCount:bots}", bots ? `${bots}` : "{memberCount:bots}")
- .replace(
- "{memberCount:humans}",
- memberCount && bots
- ? `${memberCount - bots}`
- : "{memberCount:humans}"
- );
+ .replace("{memberCount:humans}", memberCount && bots ? `${memberCount - bots}` : "{memberCount:humans}");
return str;
}
diff --git a/src/utils/createPageIndicator.ts b/src/utils/createPageIndicator.ts
index ccf18e2..ee123d6 100644
--- a/src/utils/createPageIndicator.ts
+++ b/src/utils/createPageIndicator.ts
@@ -1,16 +1,10 @@
import getEmojiByName from "./getEmojiByName.js";
-function pageIndicator(
- amount: number,
- selected: number,
- showDetails?: boolean | true
-) {
+function pageIndicator(amount: number, selected: number, showDetails?: boolean | true) {
let out = "";
if (amount === 1) {
- out += getEmojiByName(
- "TRACKS.SINGLE." + (selected === 0 ? "ACTIVE" : "INACTIVE")
- );
+ out += getEmojiByName("TRACKS.SINGLE." + (selected === 0 ? "ACTIVE" : "INACTIVE"));
} else {
for (let i = 0; i < amount; i++) {
out += getEmojiByName(
diff --git a/src/utils/database.ts b/src/utils/database.ts
index 140dbcc..04c9e24 100644
--- a/src/utils/database.ts
+++ b/src/utils/database.ts
@@ -17,16 +17,9 @@
// eslint-disable-next-line @typescript-eslint/no-explicit-any
get(target: Record<string, any>, prop: string, receiver: any) {
let dataToReturn = data[prop];
- if (dataToReturn === null)
- return Reflect.get(target, prop, receiver);
- if (
- typeof dataToReturn === "object" &&
- !Array.isArray(dataToReturn)
- )
- dataToReturn = new Proxy(
- Reflect.get(target, prop, receiver),
- Entry(dataToReturn)
- );
+ if (dataToReturn === null) return Reflect.get(target, prop, receiver);
+ if (typeof dataToReturn === "object" && !Array.isArray(dataToReturn))
+ dataToReturn = new Proxy(Reflect.get(target, prop, receiver), Entry(dataToReturn));
return dataToReturn ?? Reflect.get(target, prop, receiver);
}
};
@@ -43,24 +36,17 @@
}
async setup() {
- this.defaultData = (
- await import("../config/default.json", { assert: { type: "json" } })
- ).default as unknown as GuildConfig;
+ this.defaultData = (await import("../config/default.json", { assert: { type: "json" } }))
+ .default as unknown as GuildConfig;
+ return this;
}
async read(guild: string) {
const entry = await this.guilds.findOne({ id: guild });
- return new Proxy(
- structuredClone(this.defaultData),
- Entry(entry)
- ) as unknown as GuildConfig;
+ return new Proxy(structuredClone(this.defaultData), Entry(entry)) as unknown as GuildConfig;
}
- async write(
- guild: string,
- set: object | null,
- unset: string[] | string = []
- ) {
+ async write(guild: string, set: object | null, unset: string[] | string = []) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const uo: Record<string, any> = {};
if (!Array.isArray(unset)) unset = [unset];
@@ -195,11 +181,7 @@
}
async create(guild: string, user: string, note: string | null) {
- await this.modNotes.updateOne(
- { guild: guild, user: user },
- { $set: { note: note } },
- { upsert: true }
- );
+ await this.modNotes.updateOne({ guild: guild, user: user }, { $set: { note: note } }, { upsert: true });
}
async read(guild: string, user: string) {
diff --git a/src/utils/defaultEmbeds.ts b/src/utils/defaultEmbeds.ts
index 68d8013..2200a5e 100644
--- a/src/utils/defaultEmbeds.ts
+++ b/src/utils/defaultEmbeds.ts
@@ -1,9 +1,5 @@
import EmojiEmbed from "./generateEmojiEmbed.js";
export const LoadingEmbed = [
- new EmojiEmbed()
- .setTitle("Loading")
- .setDescription("One moment...")
- .setStatus("Danger")
- .setEmoji("NUCLEUS.LOADING")
+ new EmojiEmbed().setTitle("Loading").setDescription("One moment...").setStatus("Danger").setEmoji("NUCLEUS.LOADING")
];
diff --git a/src/utils/dualCollector.ts b/src/utils/dualCollector.ts
index 8c6e55c..abc6bb3 100644
--- a/src/utils/dualCollector.ts
+++ b/src/utils/dualCollector.ts
@@ -1,15 +1,9 @@
-import Discord, {
- Interaction,
- Message,
- MessageComponentInteraction
-} from "discord.js";
+import Discord, { Interaction, Message, MessageComponentInteraction } from "discord.js";
import client from "./client.js";
export default async function (
m: Message,
- interactionFilter: (
- i: MessageComponentInteraction
- ) => boolean | Promise<boolean>,
+ interactionFilter: (i: MessageComponentInteraction) => boolean | Promise<boolean>,
messageFilter: (m: Message) => boolean | Promise<boolean>
) {
let out;
@@ -54,17 +48,14 @@
export async function modalInteractionCollector(
m: Message,
modalFilter: (i: Interaction) => boolean | Promise<boolean>,
- interactionFilter: (
- i: MessageComponentInteraction
- ) => boolean | Promise<boolean>
-) {
- let out;
+ interactionFilter: (i: MessageComponentInteraction) => boolean | Promise<boolean>
+): Promise<null | Interaction> {
+ let out: Interaction;
try {
out = await new Promise((resolve, _reject) => {
const int = m
.createMessageComponentCollector({
- filter: (i: MessageComponentInteraction) =>
- interactionFilter(i),
+ filter: (i: MessageComponentInteraction) => interactionFilter(i),
time: 300000
})
.on("collect", (i: Interaction) => {
diff --git a/src/utils/eventScheduler.ts b/src/utils/eventScheduler.ts
index 6923ede..203e05b 100644
--- a/src/utils/eventScheduler.ts
+++ b/src/utils/eventScheduler.ts
@@ -23,28 +23,16 @@
await job.remove();
});
this.agenda.define("deleteFile", async (job) => {
- fs.rm(
- path.resolve("dist/utils/temp", job.attrs.data.fileName),
- client._error
- );
+ fs.rm(path.resolve("dist/utils/temp", job.attrs.data.fileName), client._error);
await job.remove();
});
this.agenda.define("naturalUnmute", async (job) => {
- const { log, NucleusColors, entry, renderUser, renderDelta } =
- client.logger;
+ const { log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
const guild = await client.guilds.fetch(job.attrs.data.guild);
const user = await guild.members.fetch(job.attrs.data.user);
if (user.communicationDisabledUntil === null) return;
try {
- await client.database.history.create(
- "unmute",
- user.guild.id,
- user.user,
- null,
- null,
- null,
- null
- );
+ await client.database.history.create("unmute", user.guild.id, user.user, null, null, null, null);
} catch (e) {
client._error(e);
}
@@ -60,10 +48,7 @@
list: {
memberId: entry(user.user.id, `\`${user.user.id}\``),
name: entry(user.user.id, renderUser(user.user)),
- unmuted: entry(
- new Date().getTime(),
- renderDelta(new Date().getTime())
- ),
+ unmuted: entry(new Date().getTime(), renderDelta(new Date().getTime())),
unmutedBy: entry(null, "*Time out ended*")
},
hidden: {
diff --git a/src/utils/generateKeyValueList.ts b/src/utils/generateKeyValueList.ts
index a158391..54b8d99 100644
--- a/src/utils/generateKeyValueList.ts
+++ b/src/utils/generateKeyValueList.ts
@@ -7,8 +7,7 @@
.map((word) => {
return forceCaps.includes(word.toUpperCase())
? word.toUpperCase()
- : (word[0] ?? "").toUpperCase() +
- word.slice(1).toLowerCase().replace("discord", "Discord");
+ : (word[0] ?? "").toUpperCase() + word.slice(1).toLowerCase().replace("discord", "Discord");
})
.join(" ");
return s;
diff --git a/src/utils/log.ts b/src/utils/log.ts
index 6baa0a5..fdf17ef 100644
--- a/src/utils/log.ts
+++ b/src/utils/log.ts
@@ -34,9 +34,7 @@
return `${role.name} [<@&${role.id}>]`;
}
renderEmoji(emoji: Discord.GuildEmoji) {
- return `<${emoji.animated ? "a" : ""}:${emoji.name}:${emoji.id}> [\`:${
- emoji.name
- }:\`]`;
+ return `<${emoji.animated ? "a" : ""}:${emoji.name}:${emoji.id}> [\`:${emoji.name}:\`]`;
}
public readonly NucleusColors = {
@@ -59,17 +57,11 @@
const config = await client.database.guilds.read(log.hidden.guild);
if (!config.logging.logs.enabled) return;
if (!(log.meta.calculateType === true)) {
- if (
- !toHexArray(config.logging.logs.toLog).includes(
- log.meta.calculateType
- )
- )
+ if (!toHexArray(config.logging.logs.toLog).includes(log.meta.calculateType))
return console.log("Not logging this type of event");
}
if (config.logging.logs.channel) {
- const channel = (await client.channels.fetch(
- config.logging.logs.channel
- )) as Discord.TextChannel | null;
+ const channel = (await client.channels.fetch(config.logging.logs.channel)) as Discord.TextChannel | null;
const description: Record<string, string> = {};
Object.entries(log.list).map((entry) => {
const key: string = entry[0];
@@ -84,11 +76,7 @@
if (channel) {
log.separate = log.separate || {};
const embed = new Discord.MessageEmbed()
- .setTitle(
- `${getEmojiByName(log.meta.emoji)} ${
- log.meta.displayName
- }`
- )
+ .setTitle(`${getEmojiByName(log.meta.emoji)} ${log.meta.displayName}`)
.setDescription(
(log.separate.start ? log.separate.start + "\n" : "") +
generateKeyValueList(description) +
diff --git a/src/utils/temp/generateFileName.ts b/src/utils/temp/generateFileName.ts
index 956f1d7..8534846 100644
--- a/src/utils/temp/generateFileName.ts
+++ b/src/utils/temp/generateFileName.ts
@@ -12,10 +12,8 @@
if (fs.existsSync(`./${fileName}`)) {
fileName = generateFileName(ending);
}
- client.database.eventScheduler.schedule(
- "deleteFile",
- new Date().getTime() + 60 * 1000,
- { fileName: `${fileName}.${ending}` }
- );
+ client.database.eventScheduler.schedule("deleteFile", new Date().getTime() + 60 * 1000, {
+ fileName: `${fileName}.${ending}`
+ });
return path.join(__dirname, fileName + "." + ending);
}