styling fixes and some typing
diff --git a/src/Unfinished/all.ts b/src/Unfinished/all.ts
index 1c6ce20..758947b 100644
--- a/src/Unfinished/all.ts
+++ b/src/Unfinished/all.ts
@@ -157,7 +157,7 @@
}
};
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
await interaction.reply({
embeds: LoadingEmbed,
ephemeral: true,
@@ -259,11 +259,11 @@
const check = async (interaction: CommandInteraction, _defaultCheck: WrappedCheck) => {
const member = interaction.member as GuildMember;
const me = interaction.guild.me!;
- if (!me.permissions.has("MANAGE_ROLES")) throw "I do not have the *Manage Roles* permission";
+ if (!me.permissions.has("MANAGE_ROLES")) throw new Error("I do not have the *Manage Roles* permission");
// Allow the owner to role anyone
if (member.id === interaction.guild.ownerId) return true;
// Check if the user has manage_roles permission
- if (!member.permissions.has("MANAGE_ROLES")) throw "You do not have the *Manage Roles* permission";
+ if (!member.permissions.has("MANAGE_ROLES")) throw new Error("You do not have the *Manage Roles* permission");
// Allow role
return true;
};
diff --git a/src/api/index.ts b/src/api/index.ts
index f77fe70..e5f0c38 100644
--- a/src/api/index.ts
+++ b/src/api/index.ts
@@ -43,7 +43,7 @@
components: []
});
}
- delete client.verify[code];
+ client.verify = client.verify.filter((v) => v.code !== code);
const { log, NucleusColors, entry, renderUser } = client.logger;
try {
const data = {
diff --git a/src/commands/mod/ban.ts b/src/commands/mod/ban.ts
index 87bfd28..4f2d4d7 100644
--- a/src/commands/mod/ban.ts
+++ b/src/commands/mod/ban.ts
@@ -1,5 +1,5 @@
import { CommandInteraction, GuildMember, MessageActionRow, MessageButton } from "discord.js";
-import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
+import type { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import confirmationMessage from "../../utils/confirmationMessage.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import keyValueList from "../../utils/generateKeyValueList.js";
@@ -160,24 +160,24 @@
const member = interaction.member as GuildMember;
const me = interaction.guild.me!;
const apply = interaction.options.getMember("user") as GuildMember;
- if (member === null || me === null || apply === null) throw "That member is not in the server";
+ if (member === null || me === null || apply === null) throw new Error("That member is not in the server");
const memberPos = member.roles ? member.roles.highest.position : 0;
const mePos = me.roles ? me.roles.highest.position : 0;
const applyPos = apply.roles ? apply.roles.highest.position : 0;
// Do not allow banning the owner
- if (member.id === interaction.guild.ownerId) throw "You cannot ban the owner of the server";
+ if (member.id === interaction.guild.ownerId) throw new Error("You cannot ban the owner of the server");
// Check if Nucleus can ban the member
- if (!(mePos > applyPos)) throw "I do not have a role higher than that member";
+ if (!(mePos > applyPos)) throw new Error("I do not have a role higher than that member");
// Check if Nucleus has permission to ban
- if (!me.permissions.has("BAN_MEMBERS")) throw "I do not have the *Ban Members* permission";
+ if (!me.permissions.has("BAN_MEMBERS")) throw new Error("I do not have the *Ban Members* permission");
// Do not allow banning Nucleus
- if (member.id === interaction.guild.me.id) throw "I cannot ban myself";
+ if (member.id === interaction.guild.me.id) throw new Error("I cannot ban myself");
// Allow the owner to ban anyone
if (member.id === interaction.guild.ownerId) return true;
// Check if the user has ban_members permission
- if (!member.permissions.has("BAN_MEMBERS")) throw "You do not have the *Ban Members* permission";
+ if (!member.permissions.has("BAN_MEMBERS")) throw new Error("You do not have the *Ban Members* permission");
// Check if the user is below on the role list
- if (!(memberPos > applyPos)) throw "You do not have a role higher than that member";
+ if (!(memberPos > applyPos)) throw new Error("You do not have a role higher than that member");
// Allow ban
return true;
};
diff --git a/src/commands/mod/info.ts b/src/commands/mod/info.ts
index af30989..f0257f8 100644
--- a/src/commands/mod/info.ts
+++ b/src/commands/mod/info.ts
@@ -1,12 +1,16 @@
-import { HistorySchema } from "../../utils/database.js";
+import type { HistorySchema } from "../../utils/database.js";
import Discord, {
CommandInteraction,
GuildMember,
+ Interaction,
+ Message,
MessageActionRow,
MessageButton,
+ MessageComponentInteraction,
+ ModalSubmitInteraction,
TextInputComponent
} from "discord.js";
-import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
+import type { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import getEmojiByName from "../../utils/getEmojiByName.js";
import client from "../../utils/client.js";
@@ -21,7 +25,7 @@
option.setName("user").setDescription("The user to get information about").setRequired(true)
);
-const types = {
+const types: Record<string, { emoji: string; text: string }> = {
warn: { emoji: "PUNISH.WARN.YELLOW", text: "Warned" },
mute: { emoji: "PUNISH.MUTE.YELLOW", text: "Muted" },
unmute: { emoji: "PUNISH.MUTE.GREEN", text: "Unmuted" },
@@ -36,8 +40,9 @@
};
function historyToString(history: HistorySchema) {
- let s = `${getEmojiByName(types[history.type].emoji)} ${history.amount ? history.amount + " " : ""}${
- types[history.type].text
+ if (!Object.keys(types).includes(history.type)) throw new Error("Invalid history type");
+ let s = `${getEmojiByName(types[history.type]!.emoji)} ${history.amount ? history.amount + " " : ""}${
+ types[history.type]!.text
} on <t:${Math.round(history.occurredAt.getTime() / 1000)}:F>`;
if (history.moderator) {
s += ` by <@${history.moderator}>`;
@@ -55,7 +60,7 @@
}
class TimelineSection {
- name: string;
+ name: string = "";
content: { data: HistorySchema; rendered: string }[] = [];
addContent = (content: { data: HistorySchema; rendered: string }) => {
@@ -66,8 +71,8 @@
return this.content.reduce((acc, cur) => acc + cur.rendered.length, 0);
};
generateName = () => {
- const first = Math.round(this.content[0].data.occurredAt.getTime() / 1000);
- const last = Math.round(this.content[this.content.length - 1].data.occurredAt.getTime() / 1000);
+ const first = Math.round(this.content[0]!.data.occurredAt.getTime() / 1000);
+ const last = Math.round(this.content[this.content.length - 1]!.data.occurredAt.getTime() / 1000);
if (first === last) {
return (this.name = `<t:${first}:F>`);
}
@@ -90,30 +95,36 @@
"December"
];
-async function showHistory(member, interaction: CommandInteraction) {
+async function showHistory(member: Discord.GuildMember, interaction: CommandInteraction) {
let currentYear = new Date().getFullYear();
- let pageIndex = null;
- let m, history, current;
+ let pageIndex: number | null = null;
+ let history, current: TimelineSection;
+ let m: Message;
let refresh = true;
- let filteredTypes = [];
+ let filteredTypes: string[] = [];
let openFilterPane = false;
while (true) {
if (refresh) {
history = await client.database.history.read(member.guild.id, member.id, currentYear);
- history = history.sort((a, b) => b.occurredAt.getTime() - a.occurredAt.getTime()).reverse();
+ history = history
+ .sort(
+ (a: { occurredAt: Date }, b: { occurredAt: Date }) =>
+ b.occurredAt.getTime() - a.occurredAt.getTime()
+ )
+ .reverse();
if (openFilterPane) {
let tempFilteredTypes = filteredTypes;
if (filteredTypes.length === 0) {
tempFilteredTypes = Object.keys(types);
}
- history = history.filter((h) => tempFilteredTypes.includes(h.type));
+ history = history.filter((h: { type: string }) => tempFilteredTypes.includes(h.type));
}
refresh = false;
}
const groups: TimelineSection[] = [];
if (history.length > 0) {
current = new TimelineSection();
- history.forEach((event) => {
+ history.forEach((event: HistorySchema) => {
if (current.contentLength() + historyToString(event).length > 2000 || current.content.length === 5) {
groups.push(current);
current.generateName();
@@ -130,6 +141,7 @@
pageIndex = groups.length - 1;
}
}
+ if (pageIndex === null) pageIndex = 0;
const components = (
openFilterPane
? [
@@ -192,8 +204,8 @@
" " +
currentYear.toString();
if (groups.length > 0) {
- const toRender = groups[Math.min(pageIndex, groups.length - 1)];
- m = await interaction.editReply({
+ const toRender = groups[Math.min(pageIndex, groups.length - 1)]!;
+ m = (await interaction.editReply({
embeds: [
new EmojiEmbed()
.setEmoji("MEMBER.JOIN")
@@ -207,9 +219,9 @@
})
],
components: components
- });
+ })) as Message;
} else {
- m = await interaction.editReply({
+ m = (await interaction.editReply({
embeds: [
new EmojiEmbed()
.setEmoji("MEMBER.JOIN")
@@ -221,9 +233,9 @@
})
],
components: components
- });
+ })) as Message;
}
- let i;
+ let i: MessageComponentInteraction;
try {
i = await m.awaitMessageComponent({ time: 300000 });
} catch (e) {
@@ -232,7 +244,7 @@
new EmojiEmbed()
.setEmoji("MEMBER.JOIN")
.setTitle("Moderation history for " + member.user.username)
- .setDescription(m.embeds[0].description)
+ .setDescription(m.embeds[0]!.description!)
.setStatus("Danger")
.setFooter({ text: "Message timed out" })
]
@@ -256,16 +268,16 @@
refresh = true;
}
if (i.customId === "prevPage") {
- pageIndex--;
- if (pageIndex < 0) {
+ pageIndex!--;
+ if (pageIndex! < 0) {
pageIndex = null;
currentYear--;
refresh = true;
}
}
if (i.customId === "nextPage") {
- pageIndex++;
- if (pageIndex >= groups.length) {
+ pageIndex!++;
+ if (pageIndex! >= groups.length) {
pageIndex = 0;
currentYear++;
refresh = true;
@@ -286,8 +298,8 @@
}
}
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
- let m;
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
+ let m: Message;
const member = interaction.options.getMember("user") as Discord.GuildMember;
await interaction.reply({
embeds: [new EmojiEmbed().setEmoji("NUCLEUS.LOADING").setTitle("Downloading Data").setStatus("Danger")],
@@ -302,7 +314,7 @@
await showHistory(member, interaction);
}
firstLoad = false;
- m = await interaction.editReply({
+ m = (await interaction.editReply({
embeds: [
new EmojiEmbed()
.setEmoji("MEMBER.JOIN")
@@ -324,8 +336,8 @@
.setEmoji(getEmojiByName("ICONS.HISTORY", "id"))
])
]
- });
- let i;
+ })) as Message;
+ let i: MessageComponentInteraction;
try {
i = await m.awaitMessageComponent({ time: 300000 });
} catch (e) {
@@ -370,13 +382,16 @@
try {
out = await modalInteractionCollector(
m,
- (m) => m.channel.id === interaction.channel.id,
+ (m: Interaction) =>
+ (m as MessageComponentInteraction | ModalSubmitInteraction).channelId === interaction.channelId,
(m) => m.customId === "modify"
);
} catch (e) {
- continue;
+ break;
}
- if (out.fields) {
+ if (out === null) {
+ continue;
+ } else if (out instanceof ModalSubmitInteraction) {
const toAdd = out.fields.getTextInputValue("note") || null;
await client.database.notes.create(member.guild.id, member.id, toAdd);
} else {
@@ -391,7 +406,8 @@
const check = (interaction: CommandInteraction) => {
const member = interaction.member as GuildMember;
- if (!member.permissions.has("MODERATE_MEMBERS")) throw "You do not have the *Moderate Members* permission";
+ if (!member.permissions.has("MODERATE_MEMBERS"))
+ throw new Error("You do not have the *Moderate Members* permission");
return true;
};
diff --git a/src/commands/mod/kick.ts b/src/commands/mod/kick.ts
index f10563e..d5b5b7a 100644
--- a/src/commands/mod/kick.ts
+++ b/src/commands/mod/kick.ts
@@ -12,7 +12,7 @@
.setDescription("Kicks a user from the server")
.addUserOption((option) => option.setName("user").setDescription("The user to kick").setRequired(true));
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
const { renderUser } = client.logger;
// TODO:[Modals] Replace this with a modal
let reason = null;
@@ -154,24 +154,24 @@
const member = interaction.member as GuildMember;
const me = interaction.guild.me!;
const apply = interaction.options.getMember("user") as GuildMember;
- if (member === null || me === null || apply === null) throw "That member is not in the server";
+ if (member === null || me === null || apply === null) throw new Error("That member is not in the server");
const memberPos = member.roles ? member.roles.highest.position : 0;
const mePos = me.roles ? me.roles.highest.position : 0;
const applyPos = apply.roles ? apply.roles.highest.position : 0;
// Do not allow kicking the owner
- if (member.id === interaction.guild.ownerId) throw "You cannot kick the owner of the server";
+ if (member.id === interaction.guild.ownerId) throw new Error("You cannot kick the owner of the server");
// Check if Nucleus can kick the member
- if (!(mePos > applyPos)) throw "I do not have a role higher than that member";
+ if (!(mePos > applyPos)) throw new Error("I do not have a role higher than that member");
// Check if Nucleus has permission to kick
- if (!me.permissions.has("KICK_MEMBERS")) throw "I do not have the *Kick Members* permission";
+ if (!me.permissions.has("KICK_MEMBERS")) throw new Error("I do not have the *Kick Members* permission");
// Do not allow kicking Nucleus
- if (member.id === interaction.guild.me.id) throw "I cannot kick myself";
+ if (member.id === interaction.guild.me.id) throw new Error("I cannot kick myself");
// Allow the owner to kick anyone
if (member.id === interaction.guild.ownerId) return true;
// Check if the user has kick_members permission
- if (!member.permissions.has("KICK_MEMBERS")) throw "You do not have the *Kick Members* permission";
+ if (!member.permissions.has("KICK_MEMBERS")) throw new Error("You do not have the *Kick Members* permission");
// Check if the user is below on the role list
- if (!(memberPos > applyPos)) throw "You do not have a role higher than that member";
+ if (!(memberPos > applyPos)) throw new Error("You do not have a role higher than that member");
// Allow kick
return true;
};
diff --git a/src/commands/mod/mute.ts b/src/commands/mod/mute.ts
index dc44e5a..151ff76 100644
--- a/src/commands/mod/mute.ts
+++ b/src/commands/mod/mute.ts
@@ -365,24 +365,25 @@
const member = interaction.member as GuildMember;
const me = interaction.guild.me!;
const apply = interaction.options.getMember("user") as GuildMember;
- if (member === null || me === null || apply === null) throw "That member is not in the server";
+ if (member === null || me === null || apply === null) throw new Error("That member is not in the server");
const memberPos = member.roles ? member.roles.highest.position : 0;
const mePos = me.roles ? me.roles.highest.position : 0;
const applyPos = apply.roles ? apply.roles.highest.position : 0;
// Do not allow muting the owner
- if (member.id === interaction.guild.ownerId) throw "You cannot mute the owner of the server";
+ if (member.id === interaction.guild.ownerId) throw new Error("You cannot mute the owner of the server");
// Check if Nucleus can mute the member
- if (!(mePos > applyPos)) throw "I do not have a role higher than that member";
+ if (!(mePos > applyPos)) throw new Error("I do not have a role higher than that member");
// Check if Nucleus has permission to mute
- if (!me.permissions.has("MODERATE_MEMBERS")) throw "I do not have the *Moderate Members* permission";
+ if (!me.permissions.has("MODERATE_MEMBERS")) throw new Error("I do not have the *Moderate Members* permission");
// Do not allow muting Nucleus
- if (member.id === me.id) throw "I cannot mute myself";
+ if (member.id === me.id) throw new Error("I cannot mute myself");
// Allow the owner to mute anyone
if (member.id === interaction.guild.ownerId) return true;
// Check if the user has moderate_members permission
- if (!member.permissions.has("MODERATE_MEMBERS")) throw "You do not have the *Moderate Members* permission";
+ if (!member.permissions.has("MODERATE_MEMBERS"))
+ throw new Error("You do not have the *Moderate Members* permission");
// Check if the user is below on the role list
- if (!(memberPos > applyPos)) throw "You do not have a role higher than that member";
+ if (!(memberPos > applyPos)) throw new Error("You do not have a role higher than that member");
// Allow mute
return true;
};
diff --git a/src/commands/mod/nick.ts b/src/commands/mod/nick.ts
index cba14f4..c6f0633 100644
--- a/src/commands/mod/nick.ts
+++ b/src/commands/mod/nick.ts
@@ -14,7 +14,7 @@
option.setName("name").setDescription("The name to set | Leave blank to clear").setRequired(false)
);
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
const { renderUser } = client.logger;
// TODO:[Modals] Replace this with a modal
let notify = true;
@@ -167,24 +167,25 @@
const member = interaction.member as GuildMember;
const me = interaction.guild.me!;
const apply = interaction.options.getMember("user") as GuildMember;
- if (member === null || me === null || apply === null) throw "That member is not in the server";
+ if (member === null || me === null || apply === null) throw new Error("That member is not in the server");
const memberPos = member.roles ? member.roles.highest.position : 0;
const mePos = me.roles ? me.roles.highest.position : 0;
const applyPos = apply.roles ? apply.roles.highest.position : 0;
// Do not allow any changing of the owner
- if (member.id === interaction.guild.ownerId) throw "You cannot change the owner's nickname";
+ if (member.id === interaction.guild.ownerId) throw new Error("You cannot change the owner's nickname");
// Check if Nucleus can change the nickname
- if (!(mePos > applyPos)) throw "I do not have a role higher than that member";
+ if (!(mePos > applyPos)) throw new Error("I do not have a role higher than that member");
// Check if Nucleus has permission to change the nickname
- if (!me.permissions.has("MANAGE_NICKNAMES")) throw "I do not have the *Manage Nicknames* permission";
+ if (!me.permissions.has("MANAGE_NICKNAMES")) throw new Error("I do not have the *Manage Nicknames* permission");
// Allow the owner to change anyone's nickname
if (member.id === interaction.guild.ownerId) return true;
// Check if the user has manage_nicknames permission
- if (!member.permissions.has("MANAGE_NICKNAMES")) throw "You do not have the *Manage Nicknames* permission";
+ if (!member.permissions.has("MANAGE_NICKNAMES"))
+ throw new Error("You do not have the *Manage Nicknames* permission");
// Allow changing your own nickname
if (member === apply) return true;
// Check if the user is below on the role list
- if (!(memberPos > applyPos)) throw "You do not have a role higher than that member";
+ if (!(memberPos > applyPos)) throw new Error("You do not have a role higher than that member");
// Allow change
return true;
};
diff --git a/src/commands/mod/purge.ts b/src/commands/mod/purge.ts
index 63a919c..24fea75 100644
--- a/src/commands/mod/purge.ts
+++ b/src/commands/mod/purge.ts
@@ -1,5 +1,5 @@
import Discord, { CommandInteraction, GuildChannel, GuildMember, TextChannel } from "discord.js";
-import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
+import type { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import confirmationMessage from "../../utils/confirmationMessage.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import keyValueList from "../../utils/generateKeyValueList.js";
@@ -25,7 +25,7 @@
option.setName("reason").setDescription("The reason for the purge").setRequired(false)
);
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
const user = (interaction.options.getMember("user") as GuildMember) ?? null;
const channel = interaction.channel as GuildChannel;
if (
@@ -396,11 +396,11 @@
const member = interaction.member as GuildMember;
const me = interaction.guild.me!;
// Check if nucleus has the manage_messages permission
- if (!me.permissions.has("MANAGE_MESSAGES")) throw "I do not have the *Manage Messages* permission";
+ if (!me.permissions.has("MANAGE_MESSAGES")) throw new Error("I do not have the *Manage Messages* permission");
// Allow the owner to purge
if (member.id === interaction.guild.ownerId) return true;
// Check if the user has manage_messages permission
- if (!member.permissions.has("MANAGE_MESSAGES")) throw "You do not have the *Manage Messages* permission";
+ if (!member.permissions.has("MANAGE_MESSAGES")) throw new Error("You do not have the *Manage Messages* permission");
// Allow purge
return true;
};
diff --git a/src/commands/mod/slowmode.ts b/src/commands/mod/slowmode.ts
index 5565534..654fbcc 100644
--- a/src/commands/mod/slowmode.ts
+++ b/src/commands/mod/slowmode.ts
@@ -1,6 +1,7 @@
+// @ts-expect-error
import humanizeDuration from "humanize-duration";
-import { CommandInteraction, GuildMember, TextChannel } from "discord.js";
-import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
+import type { CommandInteraction, GuildMember, TextChannel } from "discord.js";
+import type { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import keyValueList from "../../utils/generateKeyValueList.js";
import confirmationMessage from "../../utils/confirmationMessage.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
@@ -91,9 +92,9 @@
const member = interaction.member as GuildMember;
// Check if Nucleus can set the slowmode
if (!interaction.guild.me.permissions.has("MANAGE_CHANNELS"))
- throw "I do not have the *Manage Channels* permission";
+ throw new Error("I do not have the *Manage Channels* permission");
// Check if the user has manage_channel permission
- if (!member.permissions.has("MANAGE_CHANNELS")) throw "You do not have the *Manage Channels* permission";
+ if (!member.permissions.has("MANAGE_CHANNELS")) throw new Error("You do not have the *Manage Channels* permission");
// Allow slowmode
return true;
};
diff --git a/src/commands/mod/softban.ts b/src/commands/mod/softban.ts
index 57a70dc..67ecdd6 100644
--- a/src/commands/mod/softban.ts
+++ b/src/commands/mod/softban.ts
@@ -20,7 +20,7 @@
.setRequired(false)
);
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
const { renderUser } = client.logger;
// TODO:[Modals] Replace this with a modal
let reason = null;
@@ -145,24 +145,24 @@
const member = interaction.member as GuildMember;
const me = interaction.guild.me!;
const apply = interaction.options.getMember("user") as GuildMember;
- if (member === null || me === null || apply === null) throw "That member is not in the server";
+ if (member === null || me === null || apply === null) throw new Error("That member is not in the server");
const memberPos = member.roles ? member.roles.highest.position : 0;
const mePos = me.roles ? me.roles.highest.position : 0;
const applyPos = apply.roles ? apply.roles.highest.position : 0;
// Do not allow softbanning the owner
- if (member.id === interaction.guild.ownerId) throw "You cannot softban the owner of the server";
+ if (member.id === interaction.guild.ownerId) throw new Error("You cannot softban the owner of the server");
// Check if Nucleus can ban the member
- if (!(mePos > applyPos)) throw "I do not have a role higher than that member";
+ if (!(mePos > applyPos)) throw new Error("I do not have a role higher than that member");
// Check if Nucleus has permission to ban
- if (!me.permissions.has("BAN_MEMBERS")) throw "I do not have the *Ban Members* permission";
+ if (!me.permissions.has("BAN_MEMBERS")) throw new Error("I do not have the *Ban Members* permission");
// Do not allow softbanning Nucleus
- if (member.id === me.id) throw "I cannot softban myself";
+ if (member.id === me.id) throw new Error("I cannot softban myself");
// Allow the owner to softban anyone
if (member.id === interaction.guild.ownerId) return true;
// Check if the user has ban_members permission
- if (!member.permissions.has("BAN_MEMBERS")) throw "You do not have the *Ban Members* permission";
+ if (!member.permissions.has("BAN_MEMBERS")) throw new Error("You do not have the *Ban Members* permission");
// Check if the user is below on the role list
- if (!(memberPos > applyPos)) throw "You do not have a role higher than that member";
+ if (!(memberPos > applyPos)) throw new Error("You do not have a role higher than that member");
// Allow softban
return true;
};
diff --git a/src/commands/mod/unban.ts b/src/commands/mod/unban.ts
index 9ba10e1..81a29a2 100644
--- a/src/commands/mod/unban.ts
+++ b/src/commands/mod/unban.ts
@@ -13,7 +13,7 @@
option.setName("user").setDescription("The user to unban (Username or ID)").setRequired(true)
);
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
const bans = await interaction.guild.bans.fetch();
const user = interaction.options.getString("user");
let resolved = bans.find((ban) => ban.user.id === user);
@@ -110,11 +110,11 @@
const member = interaction.member as GuildMember;
const me = interaction.guild.me!;
// Check if Nucleus can unban members
- if (!me.permissions.has("BAN_MEMBERS")) throw "I do not have the *Ban Members* permission";
+ if (!me.permissions.has("BAN_MEMBERS")) throw new Error("I do not have the *Ban Members* permission");
// Allow the owner to unban anyone
if (member.id === interaction.guild.ownerId) return true;
// Check if the user has ban_members permission
- if (!member.permissions.has("BAN_MEMBERS")) throw "You do not have the *Ban Members* permission";
+ if (!member.permissions.has("BAN_MEMBERS")) throw new Error("You do not have the *Ban Members* permission");
// Allow unban
return true;
};
diff --git a/src/commands/mod/unmute.ts b/src/commands/mod/unmute.ts
index 40a2093..18363d5 100644
--- a/src/commands/mod/unmute.ts
+++ b/src/commands/mod/unmute.ts
@@ -11,7 +11,7 @@
.setDescription("Unmutes a user")
.addUserOption((option) => option.setName("user").setDescription("The user to unmute").setRequired(true));
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
const { log, NucleusColors, renderUser, entry, renderDelta } = client.logger;
// TODO:[Modals] Replace this with a modal
let reason = null;
@@ -63,7 +63,7 @@
}
const member = interaction.options.getMember("user") as GuildMember;
try {
- member.timeout(0, reason || "No reason provided");
+ member.timeout(0, reason ?? "No reason provided");
} catch {
await interaction.editReply({
embeds: [
@@ -134,22 +134,23 @@
const member = interaction.member as GuildMember;
const me = interaction.guild.me!;
const apply = interaction.options.getMember("user") as GuildMember;
- if (member === null || me === null || apply === null) throw "That member is not in the server";
+ if (member === null || me === null || apply === null) throw new Error("That member is not in the server");
const memberPos = member.roles ? member.roles.highest.position : 0;
const mePos = me.roles ? me.roles.highest.position : 0;
const applyPos = apply.roles ? apply.roles.highest.position : 0;
// Do not allow unmuting the owner
- if (member.id === interaction.guild.ownerId) throw "You cannot unmute the owner of the server";
+ if (member.id === interaction.guild.ownerId) throw new Error("You cannot unmute the owner of the server");
// Check if Nucleus can unmute the member
- if (!(mePos > applyPos)) throw "I do not have a role higher than that member";
+ if (!(mePos > applyPos)) throw new Error("I do not have a role higher than that member");
// Check if Nucleus has permission to unmute
- if (!me.permissions.has("MODERATE_MEMBERS")) throw "I do not have the *Moderate Members* permission";
+ if (!me.permissions.has("MODERATE_MEMBERS")) throw new Error("I do not have the *Moderate Members* permission");
// Allow the owner to unmute anyone
if (member.id === interaction.guild.ownerId) return true;
// Check if the user has moderate_members permission
- if (!member.permissions.has("MODERATE_MEMBERS")) throw "You do not have the *Moderate Members* permission";
+ if (!member.permissions.has("MODERATE_MEMBERS"))
+ throw new Error("You do not have the *Moderate Members* permission");
// Check if the user is below on the role list
- if (!(memberPos > applyPos)) throw "You do not have a role higher than that member";
+ if (!(memberPos > applyPos)) throw new Error("You do not have a role higher than that member");
// Allow unmute
return true;
};
diff --git a/src/commands/mod/viewas.ts b/src/commands/mod/viewas.ts
index 577192f..1120f72 100644
--- a/src/commands/mod/viewas.ts
+++ b/src/commands/mod/viewas.ts
@@ -159,7 +159,7 @@
const check = (interaction: CommandInteraction) => {
const member = interaction.member as GuildMember;
- if (!member.permissions.has("MANAGE_ROLES")) throw "You do not have the *Manage Roles* permission";
+ if (!member.permissions.has("MANAGE_ROLES")) throw new Error("You do not have the *Manage Roles* permission");
return true;
};
diff --git a/src/commands/mod/warn.ts b/src/commands/mod/warn.ts
index 5e321d0..87e6e07 100644
--- a/src/commands/mod/warn.ts
+++ b/src/commands/mod/warn.ts
@@ -12,7 +12,7 @@
.setDescription("Warns a user")
.addUserOption((option) => option.setName("user").setDescription("The user to warn").setRequired(true));
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
const { log, NucleusColors, renderUser, entry } = client.logger;
// TODO:[Modals] Replace this with a modal
let reason = null;
@@ -286,17 +286,18 @@
const member = interaction.member as GuildMember;
const me = interaction.guild.me!;
const apply = interaction.options.getMember("user") as GuildMember;
- if (member === null || me === null || apply === null) throw "That member is not in the server";
+ if (member === null || me === null || apply === null) throw new Error("That member is not in the server");
const memberPos = member.roles ? member.roles.highest.position : 0;
const applyPos = apply.roles ? apply.roles.highest.position : 0;
// Do not allow warning bots
- if (member.user.bot) throw "I cannot warn bots";
+ if (member.user.bot) throw new Error("I cannot warn bots");
// Allow the owner to warn anyone
if (member.id === interaction.guild.ownerId) return true;
// Check if the user has moderate_members permission
- if (!member.permissions.has("MODERATE_MEMBERS")) throw "You do not have the *Moderate Members* permission";
+ if (!member.permissions.has("MODERATE_MEMBERS"))
+ throw new Error("You do not have the *Moderate Members* permission");
// Check if the user is below on the role list
- if (!(memberPos > applyPos)) throw "You do not have a role higher than that member";
+ if (!(memberPos > applyPos)) throw new Error("You do not have a role higher than that member");
// Allow warn
return true;
};
diff --git a/src/commands/privacy.ts b/src/commands/privacy.ts
index 7903666..4de0c63 100644
--- a/src/commands/privacy.ts
+++ b/src/commands/privacy.ts
@@ -63,7 +63,7 @@
new EmojiEmbed()
.setTitle("Scanners")
.setDescription(
- "Nucleus uses [unscan](https://unscan.co) to scan links, images and files for malware and other threats.\n" +
+ "Nucleus uses [unscan](https://rapidapi.com/abcdan/api/unscan/) to scan links, images and files for malware and other threats.\n" +
'This service\'s [privacy policy](https://unscan.co/policies) is public, and they "do not store or sell your data."'
)
.setEmoji("NUCLEUS.LOGO")
diff --git a/src/commands/role/user.ts b/src/commands/role/user.ts
index 3b3eb79..736e247 100644
--- a/src/commands/role/user.ts
+++ b/src/commands/role/user.ts
@@ -27,7 +27,7 @@
])
);
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
const { renderUser, renderRole } = client.logger;
const action = interaction.options.getString("action");
// TODO:[Modals] Replace this with a modal
@@ -95,13 +95,13 @@
const member = interaction.member as GuildMember;
const me = interaction.guild.me!;
const apply = interaction.options.getMember("user") as GuildMember;
- if (member === null || me === null || apply === null) throw "That member is not in the server";
+ if (member === null || me === null || apply === null) throw new Error("That member is not in the server");
// Check if Nucleus has permission to role
- if (!me.permissions.has("MANAGE_ROLES")) throw "I do not have the *Manage Roles* permission";
+ if (!me.permissions.has("MANAGE_ROLES")) throw new Error("I do not have the *Manage Roles* permission");
// Allow the owner to role anyone
if (member.id === interaction.guild.ownerId) return true;
// Check if the user has manage_roles permission
- if (!member.permissions.has("MANAGE_ROLES")) throw "You do not have the *Manage Roles* permission";
+ if (!member.permissions.has("MANAGE_ROLES")) throw new Error("You do not have the *Manage Roles* permission");
// Allow role
return true;
};
diff --git a/src/commands/server/about.ts b/src/commands/server/about.ts
index 4465be5..116071e 100644
--- a/src/commands/server/about.ts
+++ b/src/commands/server/about.ts
@@ -1,4 +1,4 @@
-import { CommandInteraction, Guild } from "discord.js";
+import { CommandInteraction } from "discord.js";
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
diff --git a/src/commands/settings/commands.ts b/src/commands/settings/commands.ts
index 19a13e3..fe6a181 100644
--- a/src/commands/settings/commands.ts
+++ b/src/commands/settings/commands.ts
@@ -15,7 +15,7 @@
.setDescription("Links and text shown to a user after a moderator action is performed")
.addRoleOption((o) => o.setName("role").setDescription("The role given when a member is muted"));
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
await interaction.reply({
embeds: LoadingEmbed,
ephemeral: true,
@@ -218,7 +218,7 @@
const check = (interaction: CommandInteraction, _defaultCheck: WrappedCheck) => {
const member = interaction.member as Discord.GuildMember;
if (!member.permissions.has("MANAGE_GUILD"))
- throw "You must have the *Manage Server* permission to use this command";
+ throw new Error("You must have the *Manage Server* permission to use this command");
return true;
};
diff --git a/src/commands/settings/filters.ts b/src/commands/settings/filters.ts
index 3b0988e..1a297ca 100644
--- a/src/commands/settings/filters.ts
+++ b/src/commands/settings/filters.ts
@@ -11,7 +11,7 @@
const check = (interaction: CommandInteraction) => {
const member = interaction.member as Discord.GuildMember;
if (!member.permissions.has("MANAGE_MESSAGES"))
- throw "You must have the *Manage Messages* permission to use this command";
+ throw new Error("You must have the *Manage Messages* permission to use this command");
return true;
};
diff --git a/src/commands/settings/logs/attachment.ts b/src/commands/settings/logs/attachment.ts
index 8e72651..52fdd5f 100644
--- a/src/commands/settings/logs/attachment.ts
+++ b/src/commands/settings/logs/attachment.ts
@@ -20,7 +20,7 @@
.setRequired(false)
);
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
const m = (await interaction.reply({
embeds: LoadingEmbed,
ephemeral: true,
@@ -191,7 +191,7 @@
const check = (interaction: CommandInteraction, _defaultCheck: WrappedCheck) => {
const member = interaction.member as Discord.GuildMember;
if (!member.permissions.has("MANAGE_GUILD"))
- throw "You must have the *Manage Server* permission to use this command";
+ throw new Error("You must have the *Manage Server* permission to use this command");
return true;
};
diff --git a/src/commands/settings/logs/channel.ts b/src/commands/settings/logs/channel.ts
index 21437b2..c645581 100644
--- a/src/commands/settings/logs/channel.ts
+++ b/src/commands/settings/logs/channel.ts
@@ -19,7 +19,7 @@
.addChannelTypes([ChannelType.GuildNews, ChannelType.GuildText])
);
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
const m = (await interaction.reply({
embeds: LoadingEmbed,
ephemeral: true,
@@ -185,7 +185,7 @@
const check = (interaction: CommandInteraction, _defaultCheck: WrappedCheck) => {
const member = interaction.member as Discord.GuildMember;
if (!member.permissions.has("MANAGE_GUILD"))
- throw "You must have the *Manage Server* permission to use this command";
+ throw new Error("You must have the *Manage Server* permission to use this command");
return true;
};
diff --git a/src/commands/settings/logs/events.ts b/src/commands/settings/logs/events.ts
index a2dcc63..c3fbe41 100644
--- a/src/commands/settings/logs/events.ts
+++ b/src/commands/settings/logs/events.ts
@@ -117,7 +117,7 @@
const check = (interaction: CommandInteraction, _defaultCheck: WrappedCheck) => {
const member = interaction.member as Discord.GuildMember;
if (!member.permissions.has("MANAGE_GUILD"))
- throw "You must have the *Manage Server* permission to use this command";
+ throw new Error("You must have the *Manage Server* permission to use this command");
return true;
};
diff --git a/src/commands/settings/logs/staff.ts b/src/commands/settings/logs/staff.ts
index 8450bbb..715fbea 100644
--- a/src/commands/settings/logs/staff.ts
+++ b/src/commands/settings/logs/staff.ts
@@ -21,7 +21,7 @@
.setRequired(false)
);
-const callback = async (interaction: CommandInteraction): Promise<unknown | void> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
if (!interaction.guild) return;
const m = (await interaction.reply({
embeds: LoadingEmbed,
@@ -190,7 +190,7 @@
const check = (interaction: CommandInteraction, _defaultCheck: WrappedCheck) => {
const member = interaction.member as Discord.GuildMember;
if (!member.permissions.has("MANAGE_GUILD"))
- throw "You must have the *Manage Server* permission to use this command";
+ throw new Error("You must have the *Manage Server* permission to use this command");
return true;
};
diff --git a/src/commands/settings/rolemenu.ts b/src/commands/settings/rolemenu.ts
index 93fe70d..b9464b5 100644
--- a/src/commands/settings/rolemenu.ts
+++ b/src/commands/settings/rolemenu.ts
@@ -16,7 +16,7 @@
const check = (interaction: CommandInteraction, _defaultCheck: WrappedCheck) => {
const member = interaction.member as Discord.GuildMember;
if (!member.permissions.has("MANAGE_ROLES"))
- throw "You must have the *Manage Roles* permission to use this command";
+ throw Error("You must have the *Manage Roles* permission to use this command");
return true;
};
diff --git a/src/commands/settings/stats.ts b/src/commands/settings/stats.ts
index 08bf6f8..b4bca10 100644
--- a/src/commands/settings/stats.ts
+++ b/src/commands/settings/stats.ts
@@ -21,7 +21,7 @@
.setAutocomplete(true)
);
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
singleNotify("statsChannelDeleted", interaction.guild.id, true);
const m = (await interaction.reply({
embeds: LoadingEmbed,
@@ -219,7 +219,7 @@
const check = (interaction: CommandInteraction, _defaultCheck: WrappedCheck) => {
const member = interaction.member as Discord.GuildMember;
if (!member.permissions.has("MANAGE_CHANNELS"))
- throw "You must have the *Manage Channels* permission to use this command";
+ throw new Error("You must have the *Manage Channels* permission to use this command");
return true;
};
diff --git a/src/commands/settings/tickets.ts b/src/commands/settings/tickets.ts
index 3c6515d..8b84770 100644
--- a/src/commands/settings/tickets.ts
+++ b/src/commands/settings/tickets.ts
@@ -21,7 +21,7 @@
import { toHexInteger, toHexArray, tickets as ticketTypes } from "../../utils/calculate.js";
import { capitalize } from "../../utils/generateKeyValueList.js";
import { modalInteractionCollector } from "../../utils/dualCollector.js";
-import { GuildConfig } from "../../utils/database.js";
+import type { GuildConfig } from "../../utils/database.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
@@ -60,7 +60,7 @@
.setRequired(false)
);
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
let m = (await interaction.reply({
embeds: LoadingEmbed,
ephemeral: true,
@@ -75,9 +75,9 @@
if (options.enabled !== null || options.category || options.maxtickets || options.supportping) {
options.enabled = options.enabled === "yes" ? true : false;
if (options.category) {
- let channel: GuildChannel;
+ let channel: GuildChannel | null;
try {
- channel = await interaction.guild.channels.fetch(options.category.id);
+ channel = await interaction.guild!.channels.fetch(options.category.id);
} catch {
return await interaction.editReply({
embeds: [
@@ -89,8 +89,9 @@
]
});
}
+ if (!channel) return;
channel = channel as Discord.CategoryChannel;
- if (channel.guild.id !== interaction.guild.id)
+ if (channel.guild.id !== interaction.guild!.id)
return interaction.editReply({
embeds: [
new EmojiEmbed()
@@ -113,10 +114,10 @@
]
});
}
- let role: Role;
+ let role: Role | null;
if (options.supportping) {
try {
- role = await interaction.guild.roles.fetch(options.supportping.id);
+ role = await interaction.guild!.roles.fetch(options.supportping.id);
} catch {
return await interaction.editReply({
embeds: [
@@ -128,8 +129,9 @@
]
});
}
+ if (!role) return;
role = role as Discord.Role;
- if (role.guild.id !== interaction.guild.id)
+ if (role.guild.id !== interaction.guild!.id)
return interaction.editReply({
embeds: [
new EmojiEmbed()
@@ -162,13 +164,13 @@
.send(true);
if (confirmation.cancelled) return;
if (confirmation.success) {
- const toUpdate = {};
+ const toUpdate: Record<string, string | boolean | number> = {};
if (options.enabled !== null) toUpdate["tickets.enabled"] = options.enabled;
if (options.category) toUpdate["tickets.category"] = options.category.id;
if (options.maxtickets) toUpdate["tickets.maxTickets"] = options.maxtickets;
if (options.supportping) toUpdate["tickets.supportRole"] = options.supportping.id;
try {
- await client.database.guilds.write(interaction.guild.id, toUpdate);
+ await client.database.guilds.write(interaction.guild!.id, toUpdate);
} catch (e) {
return interaction.editReply({
embeds: [
@@ -194,7 +196,7 @@
});
}
}
- let data = await client.database.guilds.read(interaction.guild.id);
+ let data = await client.database.guilds.read(interaction.guild!.id);
data.tickets.customTypes = (data.tickets.customTypes || []).filter(
(value: string, index: number, array: string[]) => array.indexOf(value) === index
);
@@ -280,19 +282,19 @@
if ((i.component as MessageActionRowComponent).customId === "clearCategory") {
if (lastClicked === "cat") {
lastClicked = "";
- await client.database.guilds.write(interaction.guild.id, null, ["tickets.category"]);
+ await client.database.guilds.write(interaction.guild!.id, null, ["tickets.category"]);
data.category = undefined;
} else lastClicked = "cat";
} else if ((i.component as MessageActionRowComponent).customId === "clearMaxTickets") {
if (lastClicked === "max") {
lastClicked = "";
- await client.database.guilds.write(interaction.guild.id, null, ["tickets.maxTickets"]);
+ await client.database.guilds.write(interaction.guild!.id, null, ["tickets.maxTickets"]);
data.maxTickets = 5;
} else lastClicked = "max";
} else if ((i.component as MessageActionRowComponent).customId === "clearSupportPing") {
if (lastClicked === "sup") {
lastClicked = "";
- await client.database.guilds.write(interaction.guild.id, null, ["tickets.supportRole"]);
+ await client.database.guilds.write(interaction.guild!.id, null, ["tickets.supportRole"]);
data.supportRole = undefined;
} else lastClicked = "sup";
} else if ((i.component as MessageActionRowComponent).customId === "send") {
@@ -375,12 +377,12 @@
}
if ((i.component as MessageActionRowComponent).customId === "template") {
i.deferUpdate();
- await interaction.channel.send({
+ await interaction.channel!.send({
embeds: [
new EmojiEmbed()
- .setTitle(ticketMessages[parseInt((i as SelectMenuInteraction).values[0])].label)
+ .setTitle(ticketMessages[parseInt((i as SelectMenuInteraction).values[0]!)]!.label)
.setDescription(
- ticketMessages[parseInt((i as SelectMenuInteraction).values[0])].description
+ ticketMessages[parseInt((i as SelectMenuInteraction).values[0]!)]!.description
)
.setStatus("Success")
.setEmoji("GUILD.TICKET.OPEN")
@@ -398,7 +400,7 @@
break;
} else if ((i.component as MessageActionRowComponent).customId === "blank") {
i.deferUpdate();
- await interaction.channel.send({
+ await interaction.channel!.send({
components: [
new MessageActionRow().addComponents([
new MessageButton()
@@ -456,7 +458,7 @@
try {
out = await modalInteractionCollector(
m,
- (m) => m.channel.id === interaction.channel.id,
+ (m) => m.channel!.id === interaction.channel!.id,
(m) => m.customId === "modify"
);
} catch (e) {
@@ -724,7 +726,7 @@
const check = (interaction: CommandInteraction) => {
const member = interaction.member as Discord.GuildMember;
if (!member.permissions.has("MANAGE_GUILD"))
- throw "You must have the *Manage Server* permission to use this command";
+ throw new Error("You must have the *Manage Server* permission to use this command");
return true;
};
diff --git a/src/commands/settings/verify.ts b/src/commands/settings/verify.ts
index 614ecb9..0eb4553 100644
--- a/src/commands/settings/verify.ts
+++ b/src/commands/settings/verify.ts
@@ -1,13 +1,14 @@
import { LoadingEmbed } from "./../../utils/defaultEmbeds.js";
import Discord, {
CommandInteraction,
+ Interaction,
Message,
MessageActionRow,
MessageActionRowComponent,
MessageButton,
MessageComponentInteraction,
- MessageEmbed,
MessageSelectMenu,
+ ModalSubmitInteraction,
Role,
SelectMenuInteraction,
TextInputComponent
@@ -15,7 +16,7 @@
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import confirmationMessage from "../../utils/confirmationMessage.js";
import getEmojiByName from "../../utils/getEmojiByName.js";
-import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
+import type { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import client from "../../utils/client.js";
import { modalInteractionCollector } from "../../utils/dualCollector.js";
@@ -27,7 +28,7 @@
option.setName("role").setDescription("The role to give after verifying").setRequired(false)
);
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
const m = (await interaction.reply({
embeds: LoadingEmbed,
ephemeral: true,
@@ -49,7 +50,7 @@
});
}
role = role as Discord.Role;
- if (role.guild.id !== interaction.guild.id) {
+ if (role.guild.id !== interaction.guild!.id) {
return interaction.editReply({
embeds: [
new EmojiEmbed()
@@ -70,7 +71,7 @@
if (confirmation.cancelled) return;
if (confirmation.success) {
try {
- await client.database.guilds.write(interaction.guild.id, {
+ await client.database.guilds.write(interaction.guild!.id, {
"verify.role": role.id,
"verify.enabled": true
});
@@ -90,7 +91,7 @@
role: entry(role.id, renderRole(role))
},
hidden: {
- guild: interaction.guild.id
+ guild: interaction.guild!.id
}
};
log(data);
@@ -121,7 +122,7 @@
}
}
let clicks = 0;
- const data = await client.database.guilds.read(interaction.guild.id);
+ const data = await client.database.guilds.read(interaction.guild!.id);
let role = data.verify.role;
while (true) {
await interaction.editReply({
@@ -161,7 +162,7 @@
clicks += 1;
if (clicks === 2) {
clicks = 0;
- await client.database.guilds.write(interaction.guild.id, null, ["verify.role", "verify.enabled"]);
+ await client.database.guilds.write(interaction.guild!.id, null, ["verify.role", "verify.enabled"]);
role = undefined;
}
} else if ((i.component as MessageActionRowComponent).customId === "send") {
@@ -241,12 +242,12 @@
}
if ((i.component as MessageActionRowComponent).customId === "template") {
i.deferUpdate();
- await interaction.channel.send({
+ await interaction.channel!.send({
embeds: [
new EmojiEmbed()
- .setTitle(verifyMessages[parseInt((i as SelectMenuInteraction).values[0])].label)
+ .setTitle(verifyMessages[parseInt((i as SelectMenuInteraction).values[0]!)]!.label)
.setDescription(
- verifyMessages[parseInt((i as SelectMenuInteraction).values[0])].description
+ verifyMessages[parseInt((i as SelectMenuInteraction).values[0]!)]!.description
)
.setStatus("Success")
.setEmoji("CONTROL.BLOCKTICK")
@@ -264,7 +265,7 @@
break;
} else if ((i.component as MessageActionRowComponent).customId === "blank") {
i.deferUpdate();
- await interaction.channel.send({
+ await interaction.channel!.send({
components: [
new MessageActionRow().addComponents([
new MessageButton()
@@ -322,16 +323,20 @@
try {
out = await modalInteractionCollector(
m,
- (m) => m.channel.id === interaction.channel.id,
+ (m: Interaction) =>
+ (m as MessageComponentInteraction | ModalSubmitInteraction).channelId ===
+ interaction.channelId,
(m) => m.customId === "modify"
);
} catch (e) {
break;
}
- if (out.fields) {
+ if (out === null) {
+ continue;
+ } else if (out instanceof ModalSubmitInteraction) {
const title = out.fields.getTextInputValue("title");
const description = out.fields.getTextInputValue("description");
- await interaction.channel.send({
+ await interaction.channel!.send({
embeds: [
new EmojiEmbed()
.setTitle(title)
@@ -369,7 +374,7 @@
const check = (interaction: CommandInteraction) => {
const member = interaction.member as Discord.GuildMember;
if (!member.permissions.has("MANAGE_GUILD"))
- throw "You must have the *Manage Server* permission to use this command";
+ throw new Error("You must have the *Manage Server* permission to use this command");
return true;
};
diff --git a/src/commands/tags/create.ts b/src/commands/tags/create.ts
index 6350ad7..6d34258 100644
--- a/src/commands/tags/create.ts
+++ b/src/commands/tags/create.ts
@@ -1,5 +1,6 @@
-import Discord, { CommandInteraction } from "discord.js";
-import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
+import type Discord from "discord.js";
+import type { CommandInteraction } from "discord.js";
+import type { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import confirmationMessage from "../../utils/confirmationMessage.js";
import keyValueList from "../../utils/generateKeyValueList.js";
@@ -14,10 +15,10 @@
o.setName("value").setRequired(true).setDescription("The value of the tag, shown after running /tag name")
);
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
const name = interaction.options.getString("name");
const value = interaction.options.getString("value");
- if (name.length > 100)
+ if (name!.length > 100)
return await interaction.reply({
embeds: [
new EmojiEmbed()
@@ -28,7 +29,7 @@
],
ephemeral: true
});
- if (value.length > 1000)
+ if (value!.length > 1000)
return await interaction.reply({
embeds: [
new EmojiEmbed()
@@ -39,7 +40,7 @@
],
ephemeral: true
});
- const data = await client.database.guilds.read(interaction.guild.id);
+ const data = await client.database.guilds.read(interaction.guild!.id);
if (data.tags.length >= 100)
return await interaction.reply({
embeds: [
@@ -75,7 +76,7 @@
.setInverted(true)
.send();
if (confirmation.cancelled) return;
- if (!confirmation)
+ if (!confirmation.success)
return await interaction.editReply({
embeds: [
new EmojiEmbed()
@@ -86,7 +87,7 @@
]
});
try {
- await client.database.guilds.write(interaction.guild.id, {
+ await client.database.guilds.write(interaction.guild!.id, {
[`tags.${name}`]: value
});
} catch (e) {
@@ -116,7 +117,7 @@
const check = (interaction: CommandInteraction) => {
const member = interaction.member as Discord.GuildMember;
if (!member.permissions.has("MANAGE_MESSAGES"))
- throw "You must have the *Manage Messages* permission to use this command";
+ throw new Error("You must have the *Manage Messages* permission to use this command");
return true;
};
diff --git a/src/commands/tags/delete.ts b/src/commands/tags/delete.ts
index 1abdc48..69b4757 100644
--- a/src/commands/tags/delete.ts
+++ b/src/commands/tags/delete.ts
@@ -1,5 +1,6 @@
-import Discord, { CommandInteraction } from "discord.js";
-import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
+import type Discord from "discord.js";
+import type { CommandInteraction } from "discord.js";
+import type { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import confirmationMessage from "../../utils/confirmationMessage.js";
import keyValueList from "../../utils/generateKeyValueList.js";
@@ -11,9 +12,9 @@
.setDescription("Deletes a tag")
.addStringOption((o) => o.setName("name").setRequired(true).setDescription("The name of the tag"));
-const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
+const callback = async (interaction: CommandInteraction): Promise<unknown> => {
const name = interaction.options.getString("name");
- const data = await client.database.guilds.read(interaction.guild.id);
+ const data = await client.database.guilds.read(interaction.guild!.id);
if (!data.tags[name])
return await interaction.reply({
embeds: [
@@ -38,7 +39,7 @@
.setInverted(true)
.send();
if (confirmation.cancelled) return;
- if (!confirmation)
+ if (!confirmation.success)
return await interaction.editReply({
embeds: [
new EmojiEmbed()
@@ -49,7 +50,7 @@
]
});
try {
- await client.database.guilds.write(interaction.guild.id, null, ["tags." + name]);
+ await client.database.guilds.write(interaction.guild!.id, null, ["tags." + name]);
} catch (e) {
console.log(e);
return await interaction.editReply({
@@ -78,7 +79,7 @@
const check = (interaction: CommandInteraction) => {
const member = interaction.member as Discord.GuildMember;
if (!member.permissions.has("MANAGE_MESSAGES"))
- throw "You must have the *Manage Messages* permission to use this command";
+ throw new Error("You must have the *Manage Messages* permission to use this command");
return true;
};
diff --git a/src/commands/tags/edit.ts b/src/commands/tags/edit.ts
index 0ce306f..b5431fd 100644
--- a/src/commands/tags/edit.ts
+++ b/src/commands/tags/edit.ts
@@ -91,7 +91,7 @@
.setInverted(true)
.send();
if (confirmation.cancelled) return;
- if (!confirmation)
+ if (!confirmation.success)
return await interaction.editReply({
embeds: [
new EmojiEmbed()
@@ -102,8 +102,8 @@
]
});
try {
- const toSet = {};
- const toUnset = [];
+ const toSet: Record<string, string> = {};
+ const toUnset: string[] = [];
if (value) toSet[`tags.${name}`] = value;
if (newname) {
toUnset.push(`tags.${name}`);
diff --git a/src/commands/tags/list.ts b/src/commands/tags/list.ts
index e62dee8..bf124bd 100644
--- a/src/commands/tags/list.ts
+++ b/src/commands/tags/list.ts
@@ -6,18 +6,19 @@
MessageActionRowComponent,
MessageButton,
MessageComponentInteraction,
- SelectMenuInteraction
+ MessageEmbed,
+ SelectMenuInteraction,
+ MessageSelectOptionData
} from "discord.js";
-import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
+import type { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import client from "../../utils/client.js";
-import { SelectMenuOption } from "@discordjs/builders";
import getEmojiByName from "../../utils/getEmojiByName.js";
import createPageIndicator from "../../utils/createPageIndicator.js";
class Embed {
- embed: Discord.MessageEmbed;
- title: string;
+ embed: Discord.MessageEmbed = new MessageEmbed();
+ title: string = "";
description = "";
pageId = 0;
setEmbed(embed: Discord.MessageEmbed) {
@@ -42,7 +43,7 @@
builder.setName("list").setDescription("Lists all tags in the server");
const callback = async (interaction: CommandInteraction): Promise<void> => {
- const data = await client.database.guilds.read(interaction.guild.id);
+ const data = await client.database.guilds.read(interaction.guild!.id);
const tags = data.getKey("tags");
let strings = [];
if (data === {}) strings = ["*No tags exist*"];
@@ -82,18 +83,16 @@
let page = 0;
let selectPaneOpen = false;
while (true) {
- let selectPane = [];
+ let selectPane: MessageActionRow[] = [];
if (selectPaneOpen) {
- const options = [];
+ const options: MessageSelectOptionData[] = [];
pages.forEach((embed) => {
- options.push(
- new SelectMenuOption({
- label: embed.title,
- value: embed.pageId.toString(),
- description: embed.description || ""
- })
- );
+ options.push({
+ label: embed.title,
+ value: embed.pageId.toString(),
+ description: embed.description || ""
+ });
});
selectPane = [
new MessageActionRow().addComponents([
@@ -105,7 +104,7 @@
])
];
}
- const em = new Discord.MessageEmbed(pages[page].embed);
+ const em = new Discord.MessageEmbed(pages[page]!.embed);
em.setDescription(em.description + "\n\n" + createPageIndicator(pages.length, page));
await interaction.editReply({
embeds: [em],
@@ -149,10 +148,10 @@
} else if ((i.component as MessageActionRowComponent).customId === "select") {
selectPaneOpen = !selectPaneOpen;
} else if ((i.component as MessageActionRowComponent).customId === "page") {
- page = parseInt((i as SelectMenuInteraction).values[0]);
+ page = parseInt((i as SelectMenuInteraction).values[0]!);
selectPaneOpen = false;
} else {
- const em = new Discord.MessageEmbed(pages[page].embed);
+ const em = new Discord.MessageEmbed(pages[page]!.embed);
em.setDescription(em.description + "\n\n" + createPageIndicator(pages.length, page) + " | Message closed");
await interaction.editReply({
embeds: [em],
@@ -184,7 +183,7 @@
return;
}
}
- const em = new Discord.MessageEmbed(pages[page].embed);
+ const em = new Discord.MessageEmbed(pages[page]!.embed);
em.setDescription(em.description + "\n\n" + createPageIndicator(pages.length, page) + " | Message timed out");
await interaction.editReply({
embeds: [em],
diff --git a/src/commands/user/about.ts b/src/commands/user/about.ts
index 64c1ceb..6ae3231 100644
--- a/src/commands/user/about.ts
+++ b/src/commands/user/about.ts
@@ -161,7 +161,7 @@
"\n\n" +
generateKeyValueList({
member: renderUser(member.user),
- nickname: member.nickname || "*None set*",
+ nickname: member.nickname ?? "*None set*",
id: `\`${member.id}\``,
"joined the server": renderDelta(member.joinedTimestamp),
"joined discord": renderDelta(member.user.createdTimestamp),
diff --git a/src/config/format.ts b/src/config/format.ts
index 2035754..3890f66 100644
--- a/src/config/format.ts
+++ b/src/config/format.ts
@@ -15,7 +15,8 @@
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)",
pastebinUsername: "Your pastebin username (optional)",
- pastebinPassword: "Your pastebin password (optional)"
+ pastebinPassword: "Your pastebin password (optional)",
+ rapidApiKey: "Your RapidAPI key (optional), used for Unscan"
};
const readline = readLine.createInterface({
diff --git a/src/events/channelDelete.ts b/src/events/channelDelete.ts
index d42a12a..e92676d 100644
--- a/src/events/channelDelete.ts
+++ b/src/events/channelDelete.ts
@@ -48,15 +48,15 @@
}
}
const list: {
- channelId: { value: string; displayValue: string };
- name: { value: string; displayValue: string };
- topic?: { value: string; displayValue: string } | null;
- type: { value: string; displayValue: string };
- category: { value: string; displayValue: string };
- nsfw?: { value: string; displayValue: string } | null;
- created: { value: string; displayValue: string };
- deleted: { value: string; displayValue: string };
- deletedBy: { value: string; displayValue: string };
+ channelId: ReturnType<typeof entry>;
+ name: ReturnType<typeof entry>;
+ topic?: ReturnType<typeof entry> | null;
+ type: ReturnType<typeof entry>;
+ category: ReturnType<typeof entry>;
+ nsfw?: ReturnType<typeof entry> | null;
+ created: ReturnType<typeof entry>;
+ deleted: ReturnType<typeof entry>;
+ deletedBy: ReturnType<typeof entry>;
} = {
channelId: entry(channel.id, `\`${channel.id}\``),
name: entry(channel.id, `${channel.name}`),
diff --git a/src/events/threadUpdate.ts b/src/events/threadUpdate.ts
index 144dc84..4df2587 100644
--- a/src/events/threadUpdate.ts
+++ b/src/events/threadUpdate.ts
@@ -1,38 +1,43 @@
+import type { GuildAuditLogsEntry, ThreadChannel } from "discord.js";
+// @ts-expect-error
import humanizeDuration from "humanize-duration";
+// @ts-expect-error
+import type { HaikuClient } from "jshaiku";
+
export const event = "threadUpdate";
-export async function callback(client, before, after) {
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = after.client.logger;
+export async function callback(client: HaikuClient, before: ThreadChannel, after: ThreadChannel) {
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger;
const auditLog = await getAuditLog(after.guild, "THREAD_UPDATE");
- const audit = auditLog.entries.filter((entry) => entry.target.id === after.id).first();
+ const audit = auditLog.entries.filter((entry: GuildAuditLogsEntry) => entry.target!.id === after.id).first();
if (audit.executor.id === client.user.id) return;
- const list = {
+ const list: Record<string, ReturnType<typeof entry>> = {
threadId: entry(after.id, `\`${after.id}\``),
thread: entry(after.name, renderChannel(after)),
parentChannel: entry(after.parentId, renderChannel(after.parent))
};
if (before.name !== after.name) {
- list.name = entry([before.name, after.name], `${before.name} -> ${after.name}`);
+ list["name"] = entry([before.name, after.name], `${before.name} -> ${after.name}`);
}
if (before.autoArchiveDuration !== after.autoArchiveDuration) {
- list.autoArchiveDuration = entry(
+ list["autoArchiveDuration"] = entry(
[before.autoArchiveDuration, after.autoArchiveDuration],
- `${humanizeDuration(before.autoArchiveDuration * 60 * 1000, {
+ `${humanizeDuration((before.autoArchiveDuration ?? 0) * 60 * 1000, {
round: true
- })} -> ${humanizeDuration(after.autoArchiveDuration * 60 * 1000, {
+ })} -> ${humanizeDuration((after.autoArchiveDuration ?? 0) * 60 * 1000, {
round: true
})}`
);
}
if (before.rateLimitPerUser !== after.rateLimitPerUser) {
- list.slowmode = entry(
+ list["slowmode"] = entry(
[before.rateLimitPerUser, after.rateLimitPerUser],
- `${humanizeDuration(before.rateLimitPerUser * 1000)} -> ${humanizeDuration(after.rateLimitPerUser * 1000)}`
+ `${humanizeDuration((before.rateLimitPerUser ?? 0) * 1000)} -> ${humanizeDuration((after.rateLimitPerUser ?? 0) * 1000)}`
);
}
if (!(Object.keys(list).length - 3)) return;
- list.updated = entry(new Date().getTime(), renderDelta(new Date().getTime()));
- list.updatedBy = entry(audit.executor.id, renderUser(audit.executor));
+ list["updated"] = entry(new Date().getTime(), renderDelta(new Date().getTime()));
+ list["updatedBy"] = entry(audit.executor.id, renderUser(audit.executor));
const data = {
meta: {
type: "channelUpdate",
diff --git a/src/events/webhookUpdate.ts b/src/events/webhookUpdate.ts
index 2e95c4b..c58a340 100644
--- a/src/events/webhookUpdate.ts
+++ b/src/events/webhookUpdate.ts
@@ -1,3 +1,4 @@
+import type { GuildAuditLogsEntry, Webhook } from "discord.js";
import type Discord from "discord.js";
// @ts-expect-error
import type { HaikuClient } from "jshaiku";
@@ -14,20 +15,25 @@
auditLogUpdate,
auditLogDelete
]);
- const auditCreate = auditLogCreate.entries.filter((entry) => entry.target.channelId === channel.id).first();
- const auditUpdate = auditLogUpdate.entries.filter((entry) => entry.target.channelId === channel.id).first();
- const auditDelete = auditLogDelete.entries.filter((entry) => entry.target.channelId === channel.id).first();
+ const auditCreate = auditLogCreate.entries.filter((entry: GuildAuditLogsEntry | null) => {
+ if (entry === null) return false
+ return (entry.target! as Webhook).channelId === channel.id}
+ ).first();
+ const auditUpdate = auditLogUpdate.entries.filter((entry: GuildAuditLogsEntry | null) => {
+ if (entry === null) return false
+ return (entry.target! as Webhook).channelId === channel.id}
+ ).first();
+ const auditDelete = auditLogDelete.entries.filter((entry: GuildAuditLogsEntry | null) => {
+ if (entry === null) return false
+ return (entry.target! as Webhook).channelId === channel.id}
+ ).first();
if (!auditCreate && !auditUpdate && !auditDelete) return;
let audit = auditCreate;
- let action = "Create";
- let list = {} as {
- created: { value: string; displayValue: string };
- updated: { value: string; displayValue: string };
- deleted: { value: string; displayValue: string };
- };
+ let action: "Create" | "Update" | "Delete" = "Create";
+ let list: Record<string, ReturnType<typeof entry> | string> = {};
if (auditUpdate && auditUpdate.createdTimestamp > audit.createdTimestamp) {
const { before, after } = auditUpdate.changes.reduce(
- (acc, change) => {
+ (acc: {before: Record<string, string>, after: Record<string, string>}, change: {key: string, new: string, old: string}) => {
acc.before[change.key] = change.old;
acc.after[change.key] = change.new;
return acc;
@@ -35,23 +41,23 @@
{ before: {}, after: {} }
);
if (before.name !== after.name)
- list.name = entry([before.name, after.name], `${before.name} -> ${after.name}`);
+ list["name"] = entry([before.name, after.name], `${before.name} -> ${after.name}`);
if (before.channel_id !== after.channel_id)
- list.channel = entry(
+ list["channel"] = entry(
[before.channel_id, after.channel_id],
renderChannel(await client.channels.fetch(before.channel_id)) +
" -> " +
renderChannel(await client.channels.fetch(after.channel_id))
);
if (!Object.keys(list).length) return;
- list.created = entry(auditUpdate.target.createdTimestamp, renderDelta(auditUpdate.target.createdTimestamp));
- list.edited = entry(after.editedTimestamp, renderDelta(new Date().getTime()));
- list.editedBy = entry(auditUpdate.executor.id, renderUser(auditUpdate.executor));
+ list["created"] = entry(auditUpdate.target.createdTimestamp, renderDelta(auditUpdate.target.createdTimestamp));
+ list["edited"] = entry(after.editedTimestamp, renderDelta(new Date().getTime()));
+ list["editedBy"] = entry(auditUpdate.executor.id, renderUser(auditUpdate.executor));
audit = auditUpdate;
action = "Update";
} else if (auditDelete && auditDelete.createdTimestamp > audit.createdTimestamp) {
const { before } = auditDelete.changes.reduce(
- (acc, change) => {
+ (acc: {before: Record<string, string>, after: Record<string, string>}, change: {key: string, new: string, old: string}) => {
acc.before[change.key] = change.old;
acc.after[change.key] = change.new;
return acc;
@@ -72,7 +78,7 @@
action = "Delete";
} else {
const { before } = auditDelete.changes.reduce(
- (acc, change) => {
+ (acc: {before: Record<string, string>, after: Record<string, string>}, change: {key: string, new: string, old: string}) => {
acc.before[change.key] = change.old;
acc.after[change.key] = change.new;
return acc;
diff --git a/src/index.ts b/src/index.ts
index 87bbc02..49ade67 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -23,9 +23,9 @@
client.noLog = [] as string[];
client.database = {
guilds: await new Guilds().setup(),
- history: await new History().setup(),
- notes: await new ModNotes().setup(),
- premium: await new Premium().setup(),
+ history: new History(),
+ notes: new ModNotes(),
+ premium: new Premium(),
eventScheduler: await new EventScheduler().start()
} as {
guilds: Guilds;
diff --git a/src/premium/createTranscript.ts b/src/premium/createTranscript.ts
index 50bcbcf..c60bf23 100644
--- a/src/premium/createTranscript.ts
+++ b/src/premium/createTranscript.ts
@@ -1,11 +1,4 @@
-import {
- CommandInteraction,
- DMChannel,
- Message,
- MessageActionRow,
- MessageButton,
- TextChannel
-} from "discord.js";
+import { CommandInteraction, GuildMember, Message, MessageActionRow, MessageButton, TextChannel } from "discord.js";
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
import getEmojiByName from "../utils/getEmojiByName.js";
import { PasteClient, Publicity, ExpireDate } from "pastebin-api";
@@ -43,20 +36,25 @@
out += "\n\n";
}
});
- const member = interaction.guild!.members.cache.get(interaction.channel.topic.split(" ")[0]);
- let m;
+ const topic = interaction.channel.topic;
+ let member: GuildMember | null = null;
+ if (topic !== null) {
+ const part = topic.split(" ")[0] ?? null;
+ if (part !== null) member = interaction.guild!.members.cache.get(part) ?? null;
+ }
+ let m: Message;
if (out !== "") {
const url = await pbClient.createPaste({
code: out,
expireDate: ExpireDate.Never,
- name: `Ticket Transcript ${member ? ("for " + member.user.username + "#" + member.user.discriminator + " ") : ""}` +
- `(Created at ${new Date(
- interaction.channel.createdTimestamp
- ).toDateString()})`,
+ name:
+ `Ticket Transcript ${
+ member ? "for " + member.user.username + "#" + member.user.discriminator + " " : ""
+ }` + `(Created at ${new Date(interaction.channel.createdTimestamp).toDateString()})`,
publicity: Publicity.Unlisted
});
const guildConfig = await client.database.guilds.read(interaction.guild!.id);
- m = await interaction.reply({
+ m = (await interaction.reply({
embeds: [
new EmojiEmbed()
.setTitle("Transcript")
@@ -80,9 +78,9 @@
])
],
fetchReply: true
- });
+ })) as Message;
} else {
- m = await interaction.reply({
+ m = (await interaction.reply({
embeds: [
new EmojiEmbed()
.setTitle("Transcript")
@@ -102,7 +100,7 @@
])
],
fetchReply: true
- });
+ })) as Message;
}
let i;
try {
@@ -121,10 +119,7 @@
timestamp: new Date().getTime()
},
list: {
- ticketFor: member ? entry(
- member.id,
- renderUser(member.user)
- ) : entry(null, "*Unknown*"),
+ ticketFor: member ? entry(member.id, renderUser(member.user)) : entry(null, "*Unknown*"),
deletedBy: entry(interaction.member!.user.id, renderUser(interaction.member!.user)),
deleted: entry(new Date().getTime(), renderDelta(new Date().getTime()))
},
diff --git a/src/reflex/guide.ts b/src/reflex/guide.ts
index 849c880..ef7b255 100644
--- a/src/reflex/guide.ts
+++ b/src/reflex/guide.ts
@@ -1,6 +1,15 @@
import { LoadingEmbed } from "./../utils/defaultEmbeds.js";
-import { SelectMenuOption } from "@discordjs/builders";
-import Discord, { MessageActionRow, MessageButton } from "discord.js";
+import Discord, {
+ MessageActionRow,
+ MessageButton,
+ MessageComponentInteraction,
+ MessageSelectOptionData,
+ Guild,
+ CommandInteraction,
+ GuildTextBasedChannel,
+ Message,
+ SelectMenuInteraction
+} from "discord.js";
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
import getEmojiByName from "../utils/getEmojiByName.js";
import createPageIndicator from "../utils/createPageIndicator.js";
@@ -10,6 +19,11 @@
title: string;
description = "";
pageId = 0;
+
+ constructor() {
+ this.embed = new Discord.MessageEmbed();
+ this.title = "";
+ }
setEmbed(embed: Discord.MessageEmbed) {
this.embed = embed;
return this;
@@ -28,16 +42,26 @@
}
}
-export default async (guild, interaction?) => {
- let c = guild.publicUpdatesChannel ? guild.publicUpdatesChannel : guild.systemChannel;
+export default async (guild: Guild, interaction?: CommandInteraction) => {
+ let c: GuildTextBasedChannel | null = guild.publicUpdatesChannel ? guild.publicUpdatesChannel : guild.systemChannel;
c = c
? c
- : guild.channels.cache.find(
+ : (guild.channels.cache.find(
(ch) =>
- ch.type === "GUILD_TEXT" &&
+ [
+ "GUILD_TEXT",
+ "GUILD_NEWS",
+ "GUILD_NEWS_THREAD",
+ "GUILD_PRIVATE_THREAD",
+ "GUILD_PUBLIC_THREAD"
+ ].includes(ch.type) &&
ch.permissionsFor(guild.roles.everyone).has("SEND_MESSAGES") &&
- ch.permissionsFor(guild.me).has("EMBED_LINKS")
- );
+ ch.permissionsFor(guild.me!).has("EMBED_LINKS")
+ ) as GuildTextBasedChannel | undefined) ?? null;
+ if (interaction) c = interaction.channel as GuildTextBasedChannel;
+ if (!c) {
+ return;
+ }
const pages = [
new Embed()
.setEmbed(
@@ -188,37 +212,35 @@
.setDescription("Premium features")
.setPageId(7)
];
- let m;
+ let m: Message;
if (interaction) {
- m = await interaction.reply({
+ m = (await interaction.reply({
embeds: LoadingEmbed,
fetchReply: true,
ephemeral: true
- });
+ })) as Message;
} else {
m = await c.send({ embeds: LoadingEmbed });
}
let page = 0;
- const f = async (component) => {
+ const f = async (component: MessageComponentInteraction) => {
return (component.member as Discord.GuildMember).permissions.has("MANAGE_GUILD");
};
let selectPaneOpen = false;
while (true) {
- let selectPane = [];
+ let selectPane: MessageActionRow[] = [];
if (selectPaneOpen) {
- const options = [];
+ const options: MessageSelectOptionData[] = [];
pages.forEach((embed) => {
- options.push(
- new SelectMenuOption({
- label: embed.title,
- value: embed.pageId.toString(),
- description: embed.description || ""
- })
- );
+ options.push({
+ label: embed.title,
+ value: embed.pageId.toString(),
+ description: embed.description || ""
+ });
});
selectPane = [
new MessageActionRow().addComponents([
@@ -250,20 +272,19 @@
])
]);
if (interaction) {
- const em = new Discord.MessageEmbed(pages[page].embed);
+ const em = new Discord.MessageEmbed(pages[page]!.embed);
em.setDescription(em.description + "\n\n" + createPageIndicator(pages.length, page));
await interaction.editReply({
embeds: [em],
components: components
});
} else {
- const em = new Discord.MessageEmbed(pages[page].embed);
+ const em = new Discord.MessageEmbed(pages[page]!.embed);
em.setDescription(em.description + "\n\n" + createPageIndicator(pages.length, page));
- await m.edit({
+ (await m.edit({
embeds: [em],
- components: components,
- fetchReply: true
- });
+ components: components
+ })) as Message;
}
let i;
try {
@@ -279,7 +300,9 @@
break;
}
i.deferUpdate();
- if (i.component.customId === "left") {
+ if (!("customId" in i.component)) {
+ continue;
+ } else if (i.component.customId === "left") {
if (page > 0) page--;
selectPaneOpen = false;
} else if (i.component.customId === "right") {
@@ -288,11 +311,11 @@
} else if (i.component.customId === "select") {
selectPaneOpen = !selectPaneOpen;
} else if (i.component.customId === "page") {
- page = parseInt(i.values[0]);
+ page = parseInt((i as SelectMenuInteraction).values[0]!);
selectPaneOpen = false;
} else {
if (interaction) {
- const em = new Discord.MessageEmbed(pages[page].embed);
+ const em = new Discord.MessageEmbed(pages[page]!.embed);
em.setDescription(em.description + "\n\n" + createPageIndicator(pages.length, page));
em.setFooter({ text: "Message closed" });
interaction.editReply({
@@ -324,7 +347,7 @@
}
}
if (interaction) {
- const em = new Discord.MessageEmbed(pages[page].embed);
+ const em = new Discord.MessageEmbed(pages[page]!.embed);
em.setDescription(em.description + "\n\n" + createPageIndicator(pages.length, page)).setFooter({
text: "Message timed out"
});
@@ -351,7 +374,7 @@
]
});
} else {
- const em = new Discord.MessageEmbed(pages[page].embed);
+ const em = new Discord.MessageEmbed(pages[page]!.embed);
em.setDescription(em.description + "\n\n" + createPageIndicator(pages.length, page)).setFooter({
text: "Message timed out"
});
diff --git a/src/reflex/scanners.ts b/src/reflex/scanners.ts
index bd60f54..9761e4b 100644
--- a/src/reflex/scanners.ts
+++ b/src/reflex/scanners.ts
@@ -1,10 +1,10 @@
-// @ts-expect-error
-import * as us from "unscan";
import fetch from "node-fetch";
-import { writeFileSync } from "fs";
+import FormData from "form-data";
+import { writeFileSync, createReadStream } from "fs";
import generateFileName from "../utils/temp/generateFileName.js";
import Tesseract from "node-tesseract-ocr";
import type Discord from "discord.js";
+import client from "../utils/client.js";
interface NSFWSchema {
nsfw: boolean;
@@ -15,14 +15,68 @@
export async function testNSFW(link: string): Promise<NSFWSchema> {
const p = await saveAttachment(link);
- const result = await us.nsfw.file(p);
- return { nsfw: result.nsfw ?? false };
+ const data = new FormData();
+ console.log(link);
+ data.append("file", createReadStream(p));
+ const result = await fetch("https://unscan.p.rapidapi.com/", {
+ method: "POST",
+ headers: {
+ "X-RapidAPI-Key": client.config.rapidApiKey,
+ "X-RapidAPI-Host": "unscan.p.rapidapi.com"
+ },
+ body: data
+ })
+ .then((response) => response.json() as Promise<NSFWSchema>)
+ .catch((err) => {
+ console.error(err);
+ return { nsfw: false };
+ });
+ console.log(result);
+ return { nsfw: result.nsfw };
}
export async function testMalware(link: string): Promise<MalwareSchema> {
const p = await saveAttachment(link);
- const result = await us.malware.file(p);
- return { safe: result.safe ?? true };
+ const data = new FormData();
+ data.append("file", createReadStream(p));
+ console.log(link);
+ const result = await fetch("https://unscan.p.rapidapi.com/malware", {
+ method: "POST",
+ headers: {
+ "X-RapidAPI-Key": client.config.rapidApiKey,
+ "X-RapidAPI-Host": "unscan.p.rapidapi.com"
+ },
+ body: data
+ })
+ .then((response) => response.json() as Promise<MalwareSchema>)
+ .catch((err) => {
+ console.error(err);
+ return { safe: true };
+ });
+ console.log(result);
+ return { safe: result.safe };
+}
+
+export async function testLink(link: string): Promise<{ safe: boolean; tags: string[] }> {
+ console.log(link);
+ const scanned: { safe?: boolean; tags?: string[] } = await fetch("https://unscan.p.rapidapi.com/malware", {
+ method: "POST",
+ headers: {
+ "X-RapidAPI-Key": client.config.rapidApiKey,
+ "X-RapidAPI-Host": "unscan.p.rapidapi.com"
+ },
+ body: `{"link":"${link}"}`
+ })
+ .then((response) => response.json() as Promise<MalwareSchema>)
+ .catch((err) => {
+ console.error(err);
+ return { safe: true, tags: [] };
+ });
+ console.log(scanned);
+ return {
+ safe: scanned.safe ?? true,
+ tags: scanned.tags ?? []
+ };
}
export async function saveAttachment(link: string): Promise<string> {
@@ -32,19 +86,6 @@
return fileName;
}
-const defaultLinkTestResult: { safe: boolean; tags: string[] } = {
- safe: true,
- tags: []
-};
-export async function testLink(link: string): Promise<{ safe: boolean; tags: string[] }> {
- const scanned: { safe?: boolean; tags?: string[] } | undefined = await us.link.scan(link);
- if (scanned === undefined) return defaultLinkTestResult;
- return {
- safe: scanned.safe ?? defaultLinkTestResult.safe,
- tags: scanned.tags ?? defaultLinkTestResult.tags
- };
-}
-
const linkTypes = {
PHISHING: "Links designed to trick users into clicking on them.",
DATING: "Dating sites.",
diff --git a/src/reflex/statsChannelUpdate.ts b/src/reflex/statsChannelUpdate.ts
index a331537..644a75f 100644
--- a/src/reflex/statsChannelUpdate.ts
+++ b/src/reflex/statsChannelUpdate.ts
@@ -1,13 +1,15 @@
+// @ts-expect-error
+import type { HaikuClient } from "jshaiku";
+import type { GuildMember } from "discord.js";
import convertCurlyBracketString from "../utils/convertCurlyBracketString.js";
import singleNotify from "../utils/singleNotify.js";
-import client from "../utils/client.js";
interface PropSchema {
enabled: boolean;
name: string;
}
-export async function callback(_, member) {
+export async function callback(client: HaikuClient, member: GuildMember) {
const guild = await client.guilds.fetch(member.guild.id);
const config = await client.database.guilds.read(guild.id);
Object.entries(config.getKey("stats")).forEach(async ([channel, props]) => {
diff --git a/src/reflex/verify.ts b/src/reflex/verify.ts
index c366c8b..37f8d6c 100644
--- a/src/reflex/verify.ts
+++ b/src/reflex/verify.ts
@@ -1,5 +1,5 @@
import { LoadingEmbed } from "./../utils/defaultEmbeds.js";
-import Discord, { CommandInteraction, GuildMember, Interaction } from "discord.js";
+import Discord, { CommandInteraction, GuildMember, Interaction, Permissions, Role } from "discord.js";
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
import fetch from "node-fetch";
import { TestString, NSFWCheck } from "./scanners.js";
@@ -28,7 +28,7 @@
ephemeral: true,
fetchReply: true
});
- const config = await client.database.guilds.read(interaction.guild.id);
+ const config = await client.database.guilds.read(interaction.guild!.id);
if (!config.verify.enabled || !config.verify.role)
return interaction.editReply({
embeds: [
@@ -36,15 +36,13 @@
.setTitle("Verify")
.setDescription("Verify is not enabled on this server")
.setFooter({
- text: interaction.member.permissions.has("MANAGE_GUILD")
+ text: (interaction.member!.permissions as Permissions).has("MANAGE_GUILD")
? "You can enable it by running /settings verify"
: ""
})
.setStatus("Danger")
.setEmoji("CONTROL.BLOCKCROSS")
- ],
- ephemeral: true,
- fetchReply: true
+ ]
});
if ((interaction.member as GuildMember).roles.cache.has(config.verify.role)) {
return await interaction.editReply({
@@ -114,7 +112,7 @@
});
if (
await NSFWCheck(
- (interaction.member as GuildMember).user.avatarURL({
+ (interaction.member as GuildMember).user.displayAvatarURL({
format: "png"
})
)
@@ -191,21 +189,37 @@
}
break;
}
+ const role: Role | null = await interaction.guild!.roles.fetch(config.verify.role);
+ if (!role) {
+ await interaction.editReply({
+ embeds: [
+ new EmojiEmbed()
+ .setTitle("Verify")
+ .setDescription(
+ "The server's verify role was deleted, or could not be found. Please contact a staff member to fix this issue." +
+ step(4)
+ )
+ .setStatus("Danger")
+ .setEmoji("CONTROL.BLOCKCROSS")
+ ]
+ });
+ return; // TODO: SEN
+ }
verify[code] = {
- uID: interaction.member.user.id,
- gID: interaction.guild.id,
+ uID: interaction.member!.user.id,
+ gID: interaction.guild!.id,
rID: config.verify.role,
- rName: (await interaction.guild.roles.fetch(config.verify.role)).name,
- uName: interaction.member.user.username,
- gName: interaction.guild.name,
- gIcon: interaction.guild.iconURL({ format: "png" }),
+ rName: role.name,
+ uName: interaction.member!.user.username,
+ gName: interaction.guild!.name,
+ gIcon: interaction.guild!.iconURL({ format: "png" }),
interaction: interaction
};
await interaction.editReply({
embeds: [
new EmojiEmbed()
.setTitle("Verify")
- .setDescription("Looking good!\nClick the button below to get verified" + step(4))
+ .setDescription("Looking good!\nClick the button below to get verified." + step(4))
.setStatus("Success")
.setEmoji("MEMBER.JOIN")
],
diff --git a/src/reflex/welcome.ts b/src/reflex/welcome.ts
index 56391ec..36a93fb 100644
--- a/src/reflex/welcome.ts
+++ b/src/reflex/welcome.ts
@@ -1,9 +1,12 @@
+// @ts-expect-error
+import type { HaikuClient } from "jshaiku";
import convertCurlyBracketString from "../utils/convertCurlyBracketString.js";
import client from "../utils/client.js";
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
+import { GuildChannel, GuildMember, BaseGuildTextChannel } from "discord.js";
-export async function callback(_, member) {
- if (member.bot) return;
+export async function callback(_client: HaikuClient, member: GuildMember) {
+ if (member.user.bot) return;
const config = await client.database.guilds.read(member.guild.id);
if (!config.welcome.enabled) return;
@@ -22,9 +25,10 @@
embeds: [new EmojiEmbed().setDescription(string).setStatus("Success")]
});
} else {
- const channel = await member.guild.channels.fetch(config.welcome.channel);
+ const channel: GuildChannel | null = await member.guild.channels.fetch(config.welcome.channel);
+ if (!channel) return; // TODO: SEN
+ if (!(channel instanceof BaseGuildTextChannel)) return;
if (channel.guild.id !== member.guild.id) return;
- if (!channel) return;
try {
await channel.send({
embeds: [new EmojiEmbed().setDescription(string).setStatus("Success")],
diff --git a/src/utils/calculate.ts b/src/utils/calculate.ts
index 6bbbe2e..98d82c3 100644
--- a/src/utils/calculate.ts
+++ b/src/utils/calculate.ts
@@ -23,7 +23,7 @@
const tickets = ["support", "report", "question", "issue", "suggestion", "other"];
-const toHexInteger = (permissions, array?) => {
+const toHexInteger = (permissions: string[], array?: string[]) => {
if (!array) {
array = logs;
}
@@ -35,7 +35,7 @@
return int.toString(16);
};
-const toHexArray = (permissionsHex, array?) => {
+const toHexArray = (permissionsHex: string, array?: string[]) => {
if (!array) {
array = logs;
}
@@ -45,7 +45,7 @@
.split("")
.reverse();
for (const index in int) {
- if (int[index] === "1" && array.length > index) {
+ if (int[index] === "1" && array.length > parseInt(index)) {
permissions.push(array[index]);
}
}
diff --git a/src/utils/client.ts b/src/utils/client.ts
index 0ce61f1..1795cfa 100644
--- a/src/utils/client.ts
+++ b/src/utils/client.ts
@@ -1,3 +1,4 @@
+// @ts-expect-error
import { HaikuClient } from "jshaiku";
import { Intents } from "discord.js";
import config from "../config/main.json" assert { type: "json" };
diff --git a/src/utils/convertCurlyBracketString.ts b/src/utils/convertCurlyBracketString.ts
index 53c3267..5d2c23d 100644
--- a/src/utils/convertCurlyBracketString.ts
+++ b/src/utils/convertCurlyBracketString.ts
@@ -1,6 +1,14 @@
-async function convertCurlyBracketString(str, memberID, memberName, serverName, members): Promise<string> {
+import type { GuildMember, GuildMemberManager } from "discord.js";
+
+async function convertCurlyBracketString(
+ str: string,
+ memberID: string,
+ memberName: string,
+ serverName: string,
+ members: GuildMemberManager
+): Promise<string> {
const memberCount = (await members.fetch()).size;
- const bots = (await members.fetch()).filter((m) => m.user.bot).size;
+ const bots = (await members.fetch()).filter((m: GuildMember) => m.user.bot).size;
str = str
.replace("{member:mention}", memberID ? `<@${memberID}>` : "{member:mention}")
.replace("{member:name}", memberName ? `${memberName}` : "{member:name}")
diff --git a/src/utils/createLogException.ts b/src/utils/createLogException.ts
index 7a6c492..329f422 100644
--- a/src/utils/createLogException.ts
+++ b/src/utils/createLogException.ts
@@ -3,7 +3,7 @@
export default function (guild: string, channel: string, message: string) {
client.noLog.push(`${guild}/${channel}/${message}`);
setTimeout(() => {
- client.noLog = client.noLog.filter((i) => {
+ client.noLog = client.noLog.filter((i: string) => {
return i !== `${guild}/${channel}/${message}`;
});
}, 500);
diff --git a/src/utils/database.ts b/src/utils/database.ts
index 04c9e24..cda63d6 100644
--- a/src/utils/database.ts
+++ b/src/utils/database.ts
@@ -32,7 +32,6 @@
constructor() {
this.guilds = database.collection<GuildConfig>("guilds");
this.defaultData = null;
- return this;
}
async setup() {
@@ -122,11 +121,9 @@
export class History {
histories: Collection<HistorySchema>;
- defaultData: GuildConfig;
- async setup() {
+ constructor() {
this.histories = database.collection<HistorySchema>("history");
- return this;
}
async create(
@@ -135,20 +132,20 @@
user: Discord.User,
moderator: Discord.User | null,
reason: string | null,
- before?: null,
- after?: null,
- amount?: null
+ before?: string | null,
+ after?: string | null,
+ amount?: string | null
) {
await this.histories.insertOne({
type: type,
guild: guild,
user: user.id,
- moderator: moderator.id,
+ moderator: moderator ? moderator.id : null,
reason: reason,
occurredAt: new Date(),
- before: before,
- after: after,
- amount: amount
+ before: before ?? null,
+ after: after ?? null,
+ amount: amount ?? null
});
}
@@ -173,11 +170,9 @@
export class ModNotes {
modNotes: Collection<ModNoteSchema>;
- defaultData: GuildConfig;
- async setup() {
+ constructor() {
this.modNotes = database.collection<ModNoteSchema>("modNotes");
- return this;
}
async create(guild: string, user: string, note: string | null) {
@@ -193,9 +188,8 @@
export class Premium {
premium: Collection<PremiumSchema>;
- async setup() {
+ constructor() {
this.premium = database.collection<PremiumSchema>("premium");
- return this;
}
async hasPremium(guild: string) {
@@ -342,7 +336,7 @@
guild: string;
user: string;
moderator: string | null;
- reason: string;
+ reason: string | null;
occurredAt: Date;
before: string | null;
after: string | null;
@@ -352,7 +346,7 @@
export interface ModNoteSchema {
guild: string;
user: string;
- note: string;
+ note: string | null;
}
export interface PremiumSchema {
diff --git a/src/utils/generateKeyValueList.ts b/src/utils/generateKeyValueList.ts
index 54b8d99..b2b33e6 100644
--- a/src/utils/generateKeyValueList.ts
+++ b/src/utils/generateKeyValueList.ts
@@ -14,8 +14,8 @@
}
export function toCapitals(s: string) {
- if (s.startsWith(undefined)) return "";
- return s[0].toUpperCase() + s.slice(1).toLowerCase();
+ if (s === "") return "";
+ return s[0]!.toUpperCase() + s.slice(1).toLowerCase();
}
function keyValueList(data: Record<string, string>) {
diff --git a/src/utils/log.ts b/src/utils/log.ts
index cd2f3c7..d831a4b 100644
--- a/src/utils/log.ts
+++ b/src/utils/log.ts
@@ -37,7 +37,7 @@
return `<${emoji.animated ? "a" : ""}:${emoji.name}:${emoji.id}> [\`:${emoji.name}:\`]`;
}
- public readonly NucleusColors = {
+ public readonly NucleusColors: Record<string, number> = {
red: 0xf27878,
yellow: 0xf2d478,
green: 0x68d49e