Still got errors and warnings, mostly the same and easy to fix
diff --git a/.eslintrc.json b/.eslintrc.json
index 34a9df8..694dce5 100644
--- a/.eslintrc.json
+++ b/.eslintrc.json
@@ -1,7 +1,8 @@
{
"env": {
"browser": false,
- "es2021": true
+ "es2020": true,
+ "node": true
},
"ignorePatterns": ["dist/"],
"extends": [
@@ -43,6 +44,11 @@
}
],
"no-trailing-spaces": "error",
- "@typescript-eslint/no-explicit-any": "error"
+ "@typescript-eslint/no-explicit-any": "error",
+ "no-constant-condition": 0,
+ "comma-dangle": [
+ "error",
+ "never"
+ ]
}
}
diff --git a/ClicksMigratingProblems/index.js b/ClicksMigratingProblems/index.js
index c6f77bf..b79146c 100644
--- a/ClicksMigratingProblems/index.js
+++ b/ClicksMigratingProblems/index.js
@@ -1,31 +1,31 @@
-import fs from 'fs';
-import { MongoClient } from 'mongodb';
+import fs from "fs";
+import { MongoClient } from "mongodb";
-const mongoClient = new MongoClient('mongodb://127.0.0.1:27017/local');
-await mongoClient.connect()
+const mongoClient = new MongoClient("mongodb://127.0.0.1:27017/local");
+await mongoClient.connect();
const database = mongoClient.db("Nucleus");
const collection = database.collection("migrationTesting");
// Loop through all files in the oldData folder
-const files = fs.readdirSync('./oldData');
-let x = 0
+const files = fs.readdirSync("./oldData");
+let x = 0;
for (const file of files) {
console.log(`┌ Processing file ${x} of ${files.length - 1} | ${file}`);
// Read the file as a json
- let data
+ let data;
try {
data = JSON.parse(fs.readFileSync(`./oldData/${file}`));
} catch {
console.log(`└ Error reading file ${file}`);
- x++
+ x++;
continue;
}
// Check if data version is 3
if (data.version !== 3) {
console.log(`├ Version was too old on ${file}`);
- console.log(`└ Skipping file`);
+ console.log("└ Skipping file");
x++;
- continue
+ continue;
}
// Convert to the new format
const newData = {
@@ -44,11 +44,11 @@
"words": {
"strict": data.wordfilter.strict,
"loose": data.wordfilter.soft
- },
+ }
},
"invite": {
"enabled": data.invite ? data.invite.enabled : false,
- "channels": data.invite ? data.invite.whitelist.channels.map(channel => channel.toString()) : [],
+ "channels": data.invite ? data.invite.whitelist.channels.map(channel => channel.toString()) : []
},
"pings": {
"mass": 5,
@@ -60,7 +60,7 @@
"enabled": data.welcome ? (data.welcome.message.text !== null) : false,
"verificationRequired": {
"message": null,
- "role": null,
+ "role": null
},
"role": data.welcome ? (data.welcome.role !== null ? data.welcome.role.toString() : null) : null,
"channel": data.welcome ? (data.welcome.message.text !== null ? data.welcome.message.channel.toString() : null) : null,
@@ -74,12 +74,12 @@
"toLog": "3fffff"
},
"staff": {
- "channel": data.log_info.staff ? data.log_info.staff.toString() : null,
+ "channel": data.log_info.staff ? data.log_info.staff.toString() : null
}
},
"verify": {
"enabled": data.verify_role !== null,
- "role": data.verify_role ? data.verify_role.toString() : null,
+ "role": data.verify_role ? data.verify_role.toString() : null
},
"tickets": {
"enabled": data.modmail ? (data.modmail.cat !== null) : null,
@@ -119,7 +119,7 @@
"tracks": [],
"roleMenu": [],
"tags": data.tags
- }
+ };
// Insert the new data into the database
await collection.updateOne({ id: data.guild_info.id.toString() }, { $set: newData }, { upsert: true });
// Delete the old file
diff --git a/ClicksMigratingProblems/randomPunishments.js b/ClicksMigratingProblems/randomPunishments.js
index cf0575d..c9162e3 100644
--- a/ClicksMigratingProblems/randomPunishments.js
+++ b/ClicksMigratingProblems/randomPunishments.js
@@ -1,7 +1,7 @@
-import { MongoClient } from 'mongodb';
+import { MongoClient } from "mongodb";
-const mongoClient = new MongoClient('mongodb://127.0.0.1:27017/local');
-await mongoClient.connect()
+const mongoClient = new MongoClient("mongodb://127.0.0.1:27017/local");
+await mongoClient.connect();
const database = mongoClient.db("Nucleus");
const collection = database.collection("history");
@@ -20,7 +20,7 @@
reason: (["unban", "ban", "softban", "kick", "mute", "purge", "warn"].includes(type)) ? "Test" : null,
before: (type === "nickname") ? "TestBefore" : null,
after: (type === "nickname") ? "TestAfter" : null,
- amount: (type === "purge") ? Math.floor(Math.random() * 100) : null,
+ amount: (type === "purge") ? Math.floor(Math.random() * 100) : null
});
console.log("Inserted document " + i);
}
diff --git a/Installer.js b/Installer.js
index 1e3eafc..7997bba 100644
--- a/Installer.js
+++ b/Installer.js
@@ -1,4 +1,9 @@
-import format from "./src/config/format.js";
+let format;
+try {
+ format = await import("./dist/config/format.js");
+} catch (e) {
+ console.log("Please run `yarn` and `yarn build` first.");
+}
-await format(true)
-process.exit(0)
\ No newline at end of file
+await format(true);
+process.exit(0);
\ No newline at end of file
diff --git a/src/Unfinished/all.ts b/src/Unfinished/all.ts
index d49633c..db43527 100644
--- a/src/Unfinished/all.ts
+++ b/src/Unfinished/all.ts
@@ -1,4 +1,4 @@
-import { LoadingEmbed } from './../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "./../utils/defaultEmbeds.js";
import Discord, { CommandInteraction, GuildMember, MessageActionRow, MessageButton, MessageSelectMenu } from "discord.js";
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
@@ -9,14 +9,14 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder // TODO: DON'T RELEASE THIS
- .setName("all")
- .setDescription("Gives or removes a role from everyone")
+ .setName("all")
+ .setDescription("Gives or removes a role from everyone");
class Filter {
name: string;
data: object;
checkFunction: (member) => boolean;
- inverted: boolean = false;
+ inverted = false;
constructor(name: (data) => string | string, data: object, check: (member) => boolean) {
if (typeof name === "function") { this.name = name(data);
} else { this.name = name; }
@@ -25,8 +25,8 @@
}
flip() { this.inverted = true; return this; }
check(member) {
- if (this.inverted) return !this.checkFunction(member)
- else return this.checkFunction(member)
+ if (this.inverted) return !this.checkFunction(member);
+ else return this.checkFunction(member);
}
}
@@ -35,23 +35,23 @@
render: "Member",
has: {
render: "has",
- role: (role) => ( new Filter((data) => `Member has role <@&${data.role}>`, {role: role, type: Discord.Role, render: "role"}, (member) => { return member.roles.cache.has(role)}))
+ role: (role) => ( new Filter((data) => `Member has role <@&${data.role}>`, {role: role, type: Discord.Role, render: "role"}, (member) => { return member.roles.cache.has(role);}))
},
joined: {
render: "joined",
before: (date) => ( new Filter((data) => `Joined server before <t:${Math.round(date.getTime() / 1000)}:D>`, {date: date, type: Date, render: "before"}, (member) => {
- return member.joinedTimestamp < date.getTime()
+ return member.joinedTimestamp < date.getTime();
}))
},
nickname: {
render: "Nickname",
- set: () => ( new Filter((data) => `Member has a nickname set"`, {render: "set"}, (member) => { return member.nickname !== null})),
+ set: () => ( new Filter((data) => "Member has a nickname set\"", {render: "set"}, (member) => { return member.nickname !== null;})),
includes: (name) => ( new Filter((data) => `Nickname includes "${name}"`, {nickname: name, type: String, render: "includes"}, (member) => {
- return member.displayName.includes(name)})),
+ return member.displayName.includes(name);})),
startsWith: (name) => ( new Filter((data) => `Nickname starts with "${name}"`, {nickname: name, type: String, render: "starts with"}, (member) => {
- return member.displayName.startsWith(name)})),
+ return member.displayName.startsWith(name);})),
endsWith: (name) => ( new Filter((data) => `Nickname ends with "${name}"`, {nickname: name, type: String, render: "ends with"}, (member) => {
- return member.displayName.endsWith(name)}))
+ return member.displayName.endsWith(name);}))
}
},
account: {
@@ -59,49 +59,49 @@
created: {
render: "created",
before: (date) => ( new Filter((data) => `Account created before <t:${Math.round(date.getTime() / 1000)}:D>`, {date: date, type: Date, render: "before"}, (member) => {
- return member.user.createdTimestamp < date.getTime()
+ return member.user.createdTimestamp < date.getTime();
}))
},
is: {
render: "is",
- human: () => ( new Filter((data) => `Member is a human`, {human: true, render: "human"}, (member) => { return !member.bot })),
+ human: () => ( new Filter((data) => "Member is a human", {human: true, render: "human"}, (member) => { return !member.bot; }))
},
username: {
render: "Username",
includes: (name) => ( new Filter((data) => `Nickname includes "${name}"`, {nickname: name, type: String, render: "includes"}, (member) => {
- return member.user.name.includes(name)})),
+ return member.user.name.includes(name);})),
startsWith: (name) => ( new Filter((data) => `Nickname starts with "${name}"`, {nickname: name, type: String, render: "starts with"}, (member) => {
- return member.user.name.startsWith(name)})),
+ return member.user.name.startsWith(name);})),
endsWith: (name) => ( new Filter((data) => `Nickname ends with "${name}"`, {nickname: name, type: String, render: "ends with"}, (member) => {
- return member.user.name.endsWith(name)}))
+ return member.user.name.endsWith(name);}))
}
}
-}
+};
const callback = async (interaction: CommandInteraction): Promise<any> => {
- await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true})
- let filters: Filter[] = [
+ await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true});
+ const filters: Filter[] = [
filterList.member.has.role("959901346000154674"),
filterList.member.nickname.startsWith("Pinea"),
filterList.member.joined.before(new Date(2022, 1)).flip()
- ]
- let all = true;
+ ];
+ const all = true;
while (true) {
let count = 0;
- let affected = []
- let members = interaction.guild.members.cache
+ const affected = [];
+ const members = interaction.guild.members.cache;
if (all) {
members.forEach(member => {
let applies = true;
- filters.forEach(filter => { if (!filter.check(member)) { applies = false } })
- if (applies) { affected.push(member) }
- })
+ filters.forEach(filter => { if (!filter.check(member)) { applies = false; } });
+ if (applies) { affected.push(member); }
+ });
} else {
members.forEach(member => {
let applies = false;
- filters.forEach(filter => { if (filter.check(member)) { applies = true } })
- if (applies) { affected.push(member) }
- })
+ filters.forEach(filter => { if (filter.check(member)) { applies = true; } });
+ if (applies) { affected.push(member); }
+ });
}
await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Role all")
@@ -109,7 +109,7 @@
filters.map((f) => {
count ++;
return (count === 1 ? getEmojiByName("ICONS.FILTER") : (all ? "**and** " : "**or** ")) +
- (f.inverted ? "**not** " : "") + `${f.name}`
+ (f.inverted ? "**not** " : "") + `${f.name}`;
}).join("\n") + "\n\n" + `This will affect ${addPlural(affected.length, "member")}`)
.setEmoji("GUILD.ROLES.CREATE")
.setStatus("Success")
@@ -132,22 +132,22 @@
.setEmoji(client.emojis.cache.get(getEmojiByName("ICONS.FILTER", "id")))
.setDisabled(filters.length >= 25)
])
- ]})
- break
+ ]});
+ break;
}
-}
+};
const check = async (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as GuildMember)
- let me = (interaction.guild.me as GuildMember)
+ const member = (interaction.member as GuildMember);
+ const me = (interaction.guild.me as GuildMember);
if (!me.permissions.has("MANAGE_ROLES")) throw "I do not have the *Manage Roles* permission";
// Allow the owner to role anyone
- if (member.id === interaction.guild.ownerId) return true
+ 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";
// Allow role
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/Unfinished/categorisationTest.ts b/src/Unfinished/categorisationTest.ts
index c75d1bb..4d0d50a 100644
--- a/src/Unfinished/categorisationTest.ts
+++ b/src/Unfinished/categorisationTest.ts
@@ -1,22 +1,22 @@
-import { LoadingEmbed } from '../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "../utils/defaultEmbeds.js";
import { CommandInteraction, GuildChannel, MessageActionRow, MessageButton, MessageSelectMenu } from "discord.js";
import { SlashCommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
-import client from "../utils/client.js"
+import client from "../utils/client.js";
import addPlural from "../utils/plurals.js";
import getEmojiByName from "../utils/getEmojiByName.js";
const command = new SlashCommandBuilder()
.setName("categorise")
- .setDescription("Categorises your servers channels")
+ .setDescription("Categorises your servers channels");
const callback = async (interaction: CommandInteraction): Promise<any> => {
- let channels = interaction.guild.channels.cache.filter(c => c.type !== "GUILD_CATEGORY");
- let categorised = {}
+ const channels = interaction.guild.channels.cache.filter(c => c.type !== "GUILD_CATEGORY");
+ const categorised = {};
await interaction.reply({embeds: LoadingEmbed, ephemeral: true});
- let predicted = {}
- let types = {
+ const predicted = {};
+ const types = {
general: ["general", "muted", "main", "topic", "discuss"],
commands: ["bot", "command", "music"],
images: ["pic", "selfies", "image"],
@@ -26,25 +26,25 @@
staff: ["staff", "mod", "admin"],
spam: ["spam"],
other: ["random"]
- }
- for (let c of channels.values()) {
- for (let type in types) {
- for (let word of types[type]) {
+ };
+ for (const c of channels.values()) {
+ for (const type in types) {
+ for (const word of types[type]) {
if (c.name.toLowerCase().includes(word)) {
- predicted[c.id] = predicted[c.id] ?? []
- predicted[c.id].push(type)
+ predicted[c.id] = predicted[c.id] ?? [];
+ predicted[c.id].push(type);
}
}
}
}
let m;
- for (let c of channels) {
+ for (const c of channels) {
// convert channel to a channel if its a string
- let channel: any
- if (typeof c === "string") channel = interaction.guild.channels.cache.get(channel).id
- else channel = (c[0] as unknown as GuildChannel).id
- console.log(channel)
- if (!predicted[channel]) predicted[channel] = []
+ let channel: any;
+ if (typeof c === "string") channel = interaction.guild.channels.cache.get(channel).id;
+ else channel = (c[0] as unknown as GuildChannel).id;
+ console.log(channel);
+ if (!predicted[channel]) predicted[channel] = [];
m = await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Categorise")
.setDescription(`Select all types that apply to <#${channel}>.\n\n` +
@@ -65,7 +65,7 @@
new MessageButton().setLabel("Use \"Other\"").setCustomId("reject").setStyle("SECONDARY")
.setEmoji(client.emojis.cache.get(getEmojiByName("ICONS.CROSS", "id")))
])
- ]})
+ ]});
let i;
try {
i = await m.awaitMessageComponent({ time: 300000 });
@@ -77,21 +77,21 @@
.setDescription(`Select all types that apply to <#${channel}>.\n\n` +
`${addPlural(predicted[channel].length, "Suggestion")}: ${predicted[channel].join(", ")}`)
.setFooter({text: "Message timed out"})
- ]})
+ ]});
}
- i.deferUpdate()
+ i.deferUpdate();
let selected;
if (i.customId === "select") { selected = i.values; }
if (i.customId === "accept") { selected = predicted[channel]; }
if (i.customId === "reject") { selected = ["other"]; }
- categorised[channel] = selected
+ categorised[channel] = selected;
}
- console.log(categorised)
-}
+ console.log(categorised);
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/actions/createModActionTicket.ts b/src/actions/createModActionTicket.ts
index 7bd3d22..1d3406d 100644
--- a/src/actions/createModActionTicket.ts
+++ b/src/actions/createModActionTicket.ts
@@ -1,12 +1,12 @@
-import Discord, { MessageActionRow, MessageButton } from 'discord.js';
-import EmojiEmbed from '../utils/generateEmojiEmbed.js';
+import Discord, { MessageActionRow, MessageButton } from "discord.js";
+import EmojiEmbed from "../utils/generateEmojiEmbed.js";
import getEmojiByName from "../utils/getEmojiByName.js";
import client from "../utils/client.js";
export async function create(guild: Discord.Guild, member: Discord.User, createdBy: Discord.User, reason: string, customReason?: string) {
- let config = await client.database.guilds.read(guild.id);
- const { log, NucleusColors, entry, renderUser, renderChannel, renderDelta } = client.logger
- let overwrites = [{
+ const config = await client.database.guilds.read(guild.id);
+ const { log, NucleusColors, entry, renderUser, renderChannel, renderDelta } = client.logger;
+ const overwrites = [{
id: member,
allow: ["VIEW_CHANNEL", "SEND_MESSAGES", "ATTACH_FILES", "ADD_REACTIONS", "READ_MESSAGE_HISTORY"],
type: "member"
@@ -15,13 +15,13 @@
id: guild.roles.everyone,
deny: ["VIEW_CHANNEL"],
type: "role"
- })
+ });
if (config.tickets.supportRole !== null) {
overwrites.push({
id: guild.roles.cache.get(config.tickets.supportRole),
allow: ["VIEW_CHANNEL", "SEND_MESSAGES", "ATTACH_FILES", "ADD_REACTIONS", "READ_MESSAGE_HISTORY"],
type: "role"
- })
+ });
}
let c;
@@ -33,9 +33,9 @@
nsfw: false,
permissionOverwrites: (overwrites as Discord.OverwriteResolvable[]),
reason: "Creating ticket"
- })
+ });
} catch (e) {
- return null
+ return null;
}
try {
await c.send(
@@ -46,14 +46,14 @@
roles: (config.tickets.supportRole !== null ? [config.tickets.supportRole] : [])
}
}
- )
+ );
await c.send({ embeds: [new EmojiEmbed()
.setTitle("New Ticket")
.setDescription(
- `Ticket created by a Moderator\n` +
+ "Ticket created by a Moderator\n" +
`**Support type:** ${customReason ? customReason : "Appeal submission"}\n` + (reason !== null ? `**Reason:**\n> ${reason}\n` : "") +
`**Ticket ID:** \`${c.id}\`\n` +
- `Type \`/ticket close\` to close this ticket.`,
+ "Type `/ticket close` to close this ticket."
)
.setStatus("Success")
.setEmoji("GUILD.TICKET.OPEN")
@@ -62,32 +62,32 @@
.setStyle("DANGER")
.setCustomId("closeticket")
.setEmoji(getEmojiByName("CONTROL.CROSS", "id"))
- ])]})
- let data = {
+ ])]});
+ const data = {
meta:{
- type: 'ticketCreate',
- displayName: 'Ticket Created',
+ type: "ticketCreate",
+ displayName: "Ticket Created",
calculateType: "ticketUpdate",
color: NucleusColors.green,
- emoji: 'GUILD.TICKET.OPEN',
+ emoji: "GUILD.TICKET.OPEN",
timestamp: new Date().getTime()
},
list: {
ticketFor: entry(member.id, renderUser(member)),
createdBy: entry(createdBy.id, renderUser(createdBy)),
created: entry(new Date().getTime(), renderDelta(new Date().getTime())),
- ticketChannel: entry(c.id, renderChannel(c)),
+ ticketChannel: entry(c.id, renderChannel(c))
},
hidden: {
guild: guild.id
}
- }
+ };
log(data);
- } catch (e) { console.log(e); return null }
- return c.id
+ } catch (e) { console.log(e); return null; }
+ return c.id;
}
export async function areTicketsEnabled(guild: string) {
- let config = await client.database.guilds.read(guild);
+ const config = await client.database.guilds.read(guild);
return config.tickets.enabled;
}
\ No newline at end of file
diff --git a/src/actions/roleMenu.ts b/src/actions/roleMenu.ts
index 21e97ec..6fd73ac 100644
--- a/src/actions/roleMenu.ts
+++ b/src/actions/roleMenu.ts
@@ -1,42 +1,43 @@
import { Message, MessageButton } from "discord.js";
-import EmojiEmbed from '../utils/generateEmojiEmbed.js'
-import { MessageActionRow, MessageSelectMenu } from 'discord.js';
+import EmojiEmbed from "../utils/generateEmojiEmbed.js";
+import { MessageActionRow, MessageSelectMenu } from "discord.js";
import getEmojiByName from "../utils/getEmojiByName.js";
import client from "../utils/client.js";
import { LoadingEmbed } from "../utils/defaultEmbeds.js";
export async function callback(interaction) {
- let config = await client.database.guilds.read(interaction.guild.id);
+ const config = await client.database.guilds.read(interaction.guild.id);
if (!config.roleMenu.enabled) return await interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Roles")
.setDescription("Self roles are currently disabled. Please contact a staff member or try again later.")
.setStatus("Danger")
.setEmoji("CONTROL.BLOCKCROSS")
- ], ephemeral: true})
+ ], ephemeral: true});
if (config.roleMenu.options.length === 0) return await interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Roles")
.setDescription("There are no roles available. Please contact a staff member or try again later.")
.setStatus("Danger")
.setEmoji("CONTROL.BLOCKCROSS")
- ], ephemeral: true})
- await interaction.reply({embeds: LoadingEmbed, ephemeral: true})
+ ], ephemeral: true});
+ await interaction.reply({embeds: LoadingEmbed, ephemeral: true});
let m;
if (config.roleMenu.allowWebUI) {
- let code = ""
- let length = 5
- let itt = 0
+ let code = "";
+ let length = 5;
+ let itt = 0;
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
- while (true) {
- itt += 1
- code = ""
+ let valid = false;
+ while (!valid) {
+ itt += 1;
+ code = "";
for (let i = 0; i < length; i++) { code += chars.charAt(Math.floor(Math.random() * chars.length)); }
if (code in client.roleMenu) continue;
if (itt > 1000) {
- itt = 0
- length += 1
+ itt = 0;
+ length += 1;
continue;
}
- break;
+ valid = true;
}
client.roleMenu[code] = {
guild: interaction.guild.id,
@@ -47,11 +48,11 @@
data: config.roleMenu.options,
interaction: interaction
};
- let up = true
+ let up = true;
try {
- let status = await fetch(client.config.baseUrl).then(res => res.status);
- if (status !== 200) up = false
- } catch { up = false }
+ const status = await fetch(client.config.baseUrl).then(res => res.status);
+ if (status !== 200) up = false;
+ } catch { up = false; }
m = await interaction.editReply({
embeds: [new EmojiEmbed()
.setTitle("Roles")
@@ -69,22 +70,22 @@
.setStyle("PRIMARY")
.setCustomId("manual")
])]
- })
+ });
}
let component;
try { component = await (m as Message).awaitMessageComponent({time: 300000});
- } catch (e) { return }
- component.deferUpdate()
- let rolesToAdd = []
+ } catch (e) { return; }
+ component.deferUpdate();
+ let rolesToAdd = [];
for (let i = 0; i < config.roleMenu.options.length; i++) {
- let object = config.roleMenu.options[i];
- let m = await interaction.editReply({
+ const object = config.roleMenu.options[i];
+ const m = await interaction.editReply({
embeds: [
new EmojiEmbed()
.setTitle("Roles")
.setEmoji("GUILD.GREEN")
- .setDescription(`**${object.name}**` + (object.description ? `\n${object.description}` : ``) +
- `\n\nSelect ${object.min}` + (object.min !== object.max ? ` to ${object.max}` : ``) + ` role${object.max === 1 ? '' : 's'} to add.`)
+ .setDescription(`**${object.name}**` + (object.description ? `\n${object.description}` : "") +
+ `\n\nSelect ${object.min}` + (object.min !== object.max ? ` to ${object.max}` : "") + ` role${object.max === 1 ? "" : "s"} to add.`)
.setStatus("Success")
.setFooter({text: `Step ${i + 1}/${config.roleMenu.options.length}`})
],
@@ -95,59 +96,59 @@
.setStyle("DANGER")
.setCustomId("cancel")
.setEmoji(getEmojiByName("CONTROL.CROSS", "id"))
- ].concat(object.min === 0 ? [
- new MessageButton()
- .setLabel("Skip")
- .setStyle("SECONDARY")
- .setCustomId("skip")
- .setEmoji(getEmojiByName("CONTROL.RIGHT", "id"))
- ] : []))
+ ].concat(object.min === 0 ? [
+ new MessageButton()
+ .setLabel("Skip")
+ .setStyle("SECONDARY")
+ .setCustomId("skip")
+ .setEmoji(getEmojiByName("CONTROL.RIGHT", "id"))
+ ] : []))
].concat([new MessageActionRow().addComponents([new MessageSelectMenu()
.setPlaceholder(`${object.name}`)
.setCustomId("rolemenu")
.setMinValues(object.min)
.setMaxValues(object.max)
- .setOptions(object.options.map(o => { return {label: o.name, description: o.description, value: o.role} }))
+ .setOptions(object.options.map(o => { return {label: o.name, description: o.description, value: o.role}; }))
])])
});
let component;
try {
component = await (m as Message).awaitMessageComponent({time: 300000});
} catch (e) {
- return
+ return;
}
- component.deferUpdate()
+ component.deferUpdate();
if (component.customId === "rolemenu") {
- rolesToAdd = rolesToAdd.concat(component.values)
+ rolesToAdd = rolesToAdd.concat(component.values);
} else if (component.customId === "cancel") {
return await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Roles")
.setDescription("Cancelled. No changes were made.")
.setStatus("Danger")
.setEmoji("GUILD.RED")
- ], components: []})
+ ], components: []});
}
}
- let rolesToRemove = config.roleMenu.options.map(o => o.options.map(o => o.role)).flat()
- let memberRoles = interaction.member.roles.cache.map(r => r.id)
- rolesToRemove = rolesToRemove.filter(r => memberRoles.includes(r)).filter(r => !rolesToAdd.includes(r))
- rolesToAdd = rolesToAdd.filter(r => !memberRoles.includes(r))
+ let rolesToRemove = config.roleMenu.options.map(o => o.options.map(o => o.role)).flat();
+ const memberRoles = interaction.member.roles.cache.map(r => r.id);
+ rolesToRemove = rolesToRemove.filter(r => memberRoles.includes(r)).filter(r => !rolesToAdd.includes(r));
+ rolesToAdd = rolesToAdd.filter(r => !memberRoles.includes(r));
try {
- await interaction.member.roles.remove(rolesToRemove)
- await interaction.member.roles.add(rolesToAdd)
+ await interaction.member.roles.remove(rolesToRemove);
+ await interaction.member.roles.add(rolesToAdd);
} catch (e) {
return await interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Roles")
.setDescription("Something went wrong and your roles were not added. Please contact a staff member or try again later.")
.setStatus("Danger")
.setEmoji("GUILD.RED")
- ], components: []})
+ ], components: []});
}
await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Roles")
.setDescription("Roles have been added. You may close this message.")
.setStatus("Success")
.setEmoji("GUILD.GREEN")
- ], components: []})
- return
+ ], components: []});
+ return;
}
diff --git a/src/actions/tickets/create.ts b/src/actions/tickets/create.ts
index 28eb435..6c8d42c 100644
--- a/src/actions/tickets/create.ts
+++ b/src/actions/tickets/create.ts
@@ -5,14 +5,14 @@
import getEmojiByName from "../../utils/getEmojiByName.js";
function capitalize(s: string) {
- s = s.replace(/([A-Z])/g, ' $1');
+ s = s.replace(/([A-Z])/g, " $1");
return s.length < 3 ? s.toUpperCase() : s[0].toUpperCase() + s.slice(1).toLowerCase();
}
export default async function (interaction) {
- const { log, NucleusColors, entry, renderUser, renderChannel, renderDelta } = client.logger
+ const { log, NucleusColors, entry, renderUser, renderChannel, renderDelta } = client.logger;
- let config = await client.database.guilds.read(interaction.guild.id);
+ const config = await client.database.guilds.read(interaction.guild.id);
if (!config.tickets.enabled || !config.tickets.category) {
return await interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Tickets are disabled")
@@ -22,7 +22,7 @@
.setEmoji("CONTROL.BLOCKCROSS")
], ephemeral: true});
}
- let category = interaction.guild.channels.cache.get(config.tickets.category) as Discord.CategoryChannel;
+ const category = interaction.guild.channels.cache.get(config.tickets.category) as Discord.CategoryChannel;
let count = 0;
category.children.forEach(element => {
if (!(element.type === "GUILD_TEXT")) return;
@@ -41,8 +41,8 @@
], ephemeral: true});
}
let ticketTypes;
- let custom = false
- if (config.tickets.customTypes && config.tickets.useCustom) { ticketTypes = config.tickets.customTypes; custom = true }
+ let custom = false;
+ if (config.tickets.customTypes && config.tickets.useCustom) { ticketTypes = config.tickets.customTypes; custom = true; }
else if (config.tickets.types) ticketTypes = toHexArray(config.tickets.types, tickets);
else ticketTypes = [];
let chosenType;
@@ -54,7 +54,7 @@
return new MessageButton()
.setLabel(type)
.setStyle("PRIMARY")
- .setCustomId(type)
+ .setCustomId(type);
} else {
return new MessageButton()
.setLabel(capitalize(type))
@@ -66,7 +66,7 @@
for (let i = 0; i < formattedTicketTypes.length; i += 5) {
splitFormattedTicketTypes.push(new MessageActionRow().addComponents(formattedTicketTypes.slice(i, i + 5)));
}
- let m = await interaction.reply({embeds: [new EmojiEmbed()
+ const m = await interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Create Ticket")
.setDescription("Select a ticket type")
.setStatus("Success")
@@ -87,14 +87,14 @@
.setLabel(type)
.setStyle(chosenType === type ? "SUCCESS" : "SECONDARY")
.setCustomId(type)
- .setDisabled(true)
- } else {
- return new MessageButton()
+ .setDisabled(true);
+ } else {
+ return new MessageButton()
.setLabel(capitalize(type))
.setStyle(chosenType === type ? "SUCCESS" : "SECONDARY")
.setCustomId(type)
.setEmoji(getEmojiByName(("TICKETS." + type.toString().toUpperCase()), "id"))
- .setDisabled(true)
+ .setDisabled(true);
}
});
for (let i = 0; i < formattedTicketTypes.length; i += 5) {
@@ -107,13 +107,13 @@
.setEmoji("GUILD.TICKET.OPEN")
], components: splitFormattedTicketTypes});
} else {
- chosenType = null
+ chosenType = null;
await interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Create Ticket")
.setEmoji("GUILD.TICKET.OPEN")
- ], ephemeral: true, components: splitFormattedTicketTypes})
+ ], ephemeral: true, components: splitFormattedTicketTypes});
}
- let overwrites = [{
+ const overwrites = [{
id: interaction.member,
allow: ["VIEW_CHANNEL", "SEND_MESSAGES", "ATTACH_FILES", "ADD_REACTIONS", "READ_MESSAGE_HISTORY"],
type: "member"
@@ -122,13 +122,13 @@
id: interaction.guild.roles.everyone,
deny: ["VIEW_CHANNEL"],
type: "role"
- })
+ });
if (config.tickets.supportRole !== null) {
overwrites.push({
id: interaction.guild.roles.cache.get(config.tickets.supportRole),
allow: ["VIEW_CHANNEL", "SEND_MESSAGES", "ATTACH_FILES", "ADD_REACTIONS", "READ_MESSAGE_HISTORY"],
type: "role"
- })
+ });
}
let c;
@@ -140,7 +140,7 @@
nsfw: false,
permissionOverwrites: (overwrites as Discord.OverwriteResolvable[]),
reason: "Creating ticket"
- })
+ });
} catch (e) {
return await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Create Ticket")
@@ -158,17 +158,17 @@
roles: (config.tickets.supportRole !== null ? [config.tickets.supportRole] : [])
}
}
- )
+ );
let content = interaction.options ? interaction.options.getString("message") || "" : "";
if (content) content = `**Message:**\n> ${content}\n`;
- let emoji = custom ? "" : getEmojiByName("TICKETS." + chosenType.toUpperCase());
+ const emoji = custom ? "" : getEmojiByName("TICKETS." + chosenType.toUpperCase());
await c.send({ embeds: [new EmojiEmbed()
.setTitle("New Ticket")
.setDescription(
`Ticket created by <@${interaction.member.user.id}>\n` +
`**Support type:** ${chosenType !== null ? (emoji) + " " + capitalize(chosenType) : "General"}\n` +
`**Ticket ID:** \`${c.id}\`\n${content}\n` +
- `Type \`/ticket close\` to close this ticket.`,
+ "Type `/ticket close` to close this ticket."
)
.setStatus("Success")
.setEmoji("GUILD.TICKET.OPEN")
@@ -177,27 +177,27 @@
.setStyle("DANGER")
.setCustomId("closeticket")
.setEmoji(getEmojiByName("CONTROL.CROSS", "id"))
- ])]})
- let data = {
+ ])]});
+ const data = {
meta:{
- type: 'ticketCreate',
- displayName: 'Ticket Created',
+ type: "ticketCreate",
+ displayName: "Ticket Created",
calculateType: "ticketUpdate",
color: NucleusColors.green,
- emoji: 'GUILD.TICKET.OPEN',
+ emoji: "GUILD.TICKET.OPEN",
timestamp: new Date().getTime()
},
list: {
ticketFor: entry(interaction.member.user.id, renderUser(interaction.member.user)),
created: entry(new Date().getTime(), renderDelta(new Date().getTime())),
- ticketChannel: entry(c.id, renderChannel(c)),
+ ticketChannel: entry(c.id, renderChannel(c))
},
hidden: {
guild: interaction.guild.id
}
- }
+ };
log(data);
- } catch (e) { console.log(e)}
+ } catch (e) { console.log(e);}
await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Create Ticket")
.setDescription(`Ticket created. You can view it here: <#${c.id}>`)
diff --git a/src/actions/tickets/delete.ts b/src/actions/tickets/delete.ts
index d86396a..3419763 100644
--- a/src/actions/tickets/delete.ts
+++ b/src/actions/tickets/delete.ts
@@ -4,12 +4,12 @@
import getEmojiByName from "../../utils/getEmojiByName.js";
export default async function (interaction) {
- const { log, NucleusColors, entry, renderUser, renderChannel, renderDelta } = client.logger
+ const { log, NucleusColors, entry, renderUser, renderChannel, renderDelta } = client.logger;
- let config = await client.database.guilds.read(interaction.guild.id);
- let thread = false; let threadChannel
- if (interaction.channel instanceof Discord.ThreadChannel) thread = true; threadChannel = interaction.channel as Discord.ThreadChannel
- let channel = (interaction.channel as Discord.TextChannel)
+ const config = await client.database.guilds.read(interaction.guild.id);
+ let thread = false; let threadChannel;
+ if (interaction.channel instanceof Discord.ThreadChannel) thread = true; threadChannel = interaction.channel as Discord.ThreadChannel;
+ const channel = (interaction.channel as Discord.TextChannel);
if (!channel.parent || config.tickets.category !== channel.parent.id || (thread ? (threadChannel.parent.parent.id !== config.tickets.category) : false)) {
return interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Deleting Ticket...")
@@ -18,7 +18,7 @@
.setEmoji("CONTROL.BLOCKCROSS")
], ephemeral: true});
}
- let status = channel.topic.split(" ")[1];
+ const status = channel.topic.split(" ")[1];
if (status === "Archived") {
await interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Delete Ticket")
@@ -26,13 +26,13 @@
.setStatus("Danger")
.setEmoji("GUILD.TICKET.CLOSE")
]});
- let data = {
+ const data = {
meta:{
- type: 'ticketDeleted',
- displayName: 'Ticket Deleted',
+ type: "ticketDeleted",
+ displayName: "Ticket Deleted",
calculateType: "ticketUpdate",
color: NucleusColors.red,
- emoji: 'GUILD.TICKET.CLOSE',
+ emoji: "GUILD.TICKET.CLOSE",
timestamp: new Date().getTime()
},
list: {
@@ -43,7 +43,7 @@
hidden: {
guild: interaction.guild.id
}
- }
+ };
log(data);
interaction.channel.delete();
return;
@@ -54,7 +54,7 @@
.setStatus("Warning")
.setEmoji("GUILD.TICKET.ARCHIVED")
]});
- let overwrites = [
+ const overwrites = [
{
id: channel.topic.split(" ")[0],
deny: ["VIEW_CHANNEL"],
@@ -71,29 +71,29 @@
id: interaction.guild.roles.cache.get(config.tickets.supportRole),
allow: ["VIEW_CHANNEL", "SEND_MESSAGES", "ATTACH_FILES", "ADD_REACTIONS", "READ_MESSAGE_HISTORY"],
type: "role"
- })
+ });
}
- channel.edit({permissionOverwrites: overwrites})
+ channel.edit({permissionOverwrites: overwrites});
channel.setTopic(`${channel.topic.split(" ")[0]} Archived`);
- let data = {
+ const data = {
meta:{
- type: 'ticketClosed',
- displayName: 'Ticket Closed',
+ type: "ticketClosed",
+ displayName: "Ticket Closed",
calculateType: "ticketUpdate",
color: NucleusColors.yellow,
- emoji: 'GUILD.TICKET.ARCHIVED',
+ emoji: "GUILD.TICKET.ARCHIVED",
timestamp: new Date().getTime()
},
list: {
ticketFor: entry(channel.topic.split(" ")[0], renderUser((await interaction.guild.members.fetch(channel.topic.split(" ")[0])).user)),
closedBy: entry(interaction.member.user.id, renderUser(interaction.member.user)),
closed: entry(new Date().getTime(), renderDelta(new Date().getTime())),
- ticketChannel: entry(channel.id, renderChannel(channel)),
+ ticketChannel: entry(channel.id, renderChannel(channel))
},
hidden: {
guild: interaction.guild.id
}
- }
+ };
log(data);
await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Close Ticket")
@@ -107,8 +107,8 @@
.setStyle("DANGER")
.setCustomId("closeticket")
.setEmoji(getEmojiByName("CONTROL.CROSS", "id"))
- ].concat(client.database.premium.hasPremium(interaction.guild.id) ? [
- new MessageButton()
+ ].concat(client.database.premium.hasPremium(interaction.guild.id) ? [
+ new MessageButton()
.setLabel("Create Transcript and Delete")
.setStyle("PRIMARY")
.setCustomId("createtranscript")
@@ -120,42 +120,44 @@
}
async function purgeByUser(member, guild) {
- let config = await client.database.guilds.read(guild.id);
+ const config = await client.database.guilds.read(guild.id);
if (!config.tickets.category) return;
- let tickets = guild.channels.cache.get(config.tickets.category);
+ const tickets = guild.channels.cache.get(config.tickets.category);
if (!tickets) return;
- let ticketChannels = tickets.children;
- let deleted = 0
+ const ticketChannels = tickets.children;
+ let deleted = 0;
ticketChannels.forEach(element => {
if (element.type !== "GUILD_TEXT") return;
if (element.topic.split(" ")[0] === member) {
- try { element.delete(); } catch {}
- deleted++
+ try {
+ element.delete();
+ } catch { /* Errors if the channel does not exist (deleted already) */ }
+ deleted++;
}
});
if (deleted) {
- const { log, NucleusColors, entry, renderUser, renderDelta } = member.client.logger
- let data = {
+ const { log, NucleusColors, entry, renderUser, renderDelta } = member.client.logger;
+ const data = {
meta:{
- type: 'ticketPurge',
- displayName: 'Tickets Purged',
+ type: "ticketPurge",
+ displayName: "Tickets Purged",
calculateType: "ticketUpdate",
color: NucleusColors.red,
- emoji: 'GUILD.TICKET.DELETE',
+ emoji: "GUILD.TICKET.DELETE",
timestamp: new Date().getTime()
},
list: {
ticketFor: entry(member, renderUser(member)),
deletedBy: entry(null, "Member left server"),
deleted: entry(new Date().getTime(), renderDelta(new Date().getTime())),
- ticketsDeleted: deleted,
+ ticketsDeleted: deleted
},
hidden: {
guild: guild.id
}
- }
+ };
log(data);
}
}
-export { purgeByUser }
\ No newline at end of file
+export { purgeByUser };
\ No newline at end of file
diff --git a/src/api/index.ts b/src/api/index.ts
index 5cc4a99..1750509 100644
--- a/src/api/index.ts
+++ b/src/api/index.ts
@@ -1,9 +1,9 @@
-import { HaikuClient } from 'jshaiku';
-import express from 'express';
-import bodyParser from 'body-parser';
+import type { HaikuClient } from "jshaiku";
+import express from "express";
+import bodyParser from "body-parser";
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
-import structuredClone from '@ungap/structured-clone';
-import client from '../utils/client.js';
+import structuredClone from "@ungap/structured-clone";
+import client from "../utils/client.js";
const jsonParser = bodyParser.json();
@@ -11,38 +11,38 @@
const port = 10000;
const runServer = (client: HaikuClient) => {
- app.get('/', (req, res) => {
+ app.get("/", (req, res) => {
res.status(200).send(client.ws.ping);
});
- app.post('/verify/:code', jsonParser, async function (req, res) {
+ app.post("/verify/:code", jsonParser, async function (req, res) {
const code = req.params.code;
const secret = req.body.secret;
if (secret === client.config.verifySecret) {
- let guild = await client.guilds.fetch(client.verify[code].gID);
- if (!guild) { return res.status(404) }
- let member = await guild.members.fetch(client.verify[code].uID);
- if (!member) { return res.status(404) }
- if (member.roles.cache.has(client.verify[code].rID)) { return res.status(200) }
+ const guild = await client.guilds.fetch(client.verify[code].gID);
+ if (!guild) { return res.status(404); }
+ const member = await guild.members.fetch(client.verify[code].uID);
+ if (!member) { return res.status(404); }
+ if (member.roles.cache.has(client.verify[code].rID)) { return res.status(200); }
await member.roles.add(client.verify[code].rID);
- let interaction = client.verify[code].interaction;
+ const interaction = client.verify[code].interaction;
if (interaction) {
interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Verify")
- .setDescription(`Verification complete`)
+ .setDescription("Verification complete")
.setStatus("Success")
.setEmoji("MEMBER.JOIN")
], components: []});
}
delete client.verify[code];
- const { log, NucleusColors, entry, renderUser } = client.logger
+ const { log, NucleusColors, entry, renderUser } = client.logger;
try {
- let data = {
+ const data = {
meta:{
- type: 'memberVerify',
- displayName: 'Member Verified',
- calculateType: 'guildMemberVerify',
+ type: "memberVerify",
+ displayName: "Member Verified",
+ calculateType: "guildMemberVerify",
color: NucleusColors.green,
emoji: "CONTROL.BLOCKTICK",
timestamp: new Date().getTime()
@@ -54,74 +54,76 @@
hidden: {
guild: guild.id
}
- }
+ };
log(data);
- } catch {}
+ } catch {
+ res.sendStatus(500);
+ }
res.sendStatus(200);
} else {
res.sendStatus(403);
}
});
- app.get('/verify/:code', jsonParser, function (req, res) {
+ app.get("/verify/:code", jsonParser, function (req, res) {
const code = req.params.code;
if (client.verify[code]) {
try {
- let interaction = client.verify[code].interaction;
+ const interaction = client.verify[code].interaction;
if (interaction) {
interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Verify")
- .setDescription(`Verify was opened in another tab or window, please complete the CAPTCHA there to continue`)
+ .setDescription("Verify was opened in another tab or window, please complete the CAPTCHA there to continue")
.setStatus("Success")
.setEmoji("MEMBER.JOIN")
]});
}
- } catch {}
- let data = structuredClone(client.verify[code])
+ } catch { return res.sendStatus(410); }
+ const data = structuredClone(client.verify[code]);
delete data.interaction;
return res.status(200).send(data);
}
return res.sendStatus(404);
- })
+ });
- app.post('/rolemenu/:code', jsonParser, async function (req, res) {
+ app.post("/rolemenu/:code", jsonParser, async function (req, res) {
const code = req.params.code;
const secret = req.body.secret;
const data = req.body.data;
if (secret === client.config.verifySecret) {
- let guild = await client.guilds.fetch(client.roleMenu[code].guild);
- if (!guild) { return res.status(404) }
- let member = await guild.members.fetch(client.roleMenu[code].user);
- if (!member) { return res.status(404) }
+ const guild = await client.guilds.fetch(client.roleMenu[code].guild);
+ if (!guild) { return res.status(404); }
+ const member = await guild.members.fetch(client.roleMenu[code].user);
+ if (!member) { return res.status(404); }
res.sendStatus(200);
} else {
res.sendStatus(403);
}
});
- app.get('/rolemenu/:code', jsonParser, function (req, res) {
+ app.get("/rolemenu/:code", jsonParser, function (req, res) {
const code = req.params.code;
if (client.roleMenu[code] !== undefined) {
try {
- let interaction = client.roleMenu[code].interaction;
+ const interaction = client.roleMenu[code].interaction;
if (interaction) {
interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Roles")
- .setDescription(`The role menu was opened in another tab or window, please select your roles there to continue`)
+ .setDescription("The role menu was opened in another tab or window, please select your roles there to continue")
.setStatus("Success")
.setEmoji("GUILD.GREEN")
], components: []});
}
- } catch {}
- let data = structuredClone(client.roleMenu[code])
+ } catch { return res.sendStatus(410); }
+ const data = structuredClone(client.roleMenu[code]);
delete data.interaction;
- console.log(data)
+ console.log(data);
return res.status(200).send(data);
}
return res.sendStatus(404);
- })
+ });
app.listen(port);
-}
+};
export default runServer;
\ No newline at end of file
diff --git a/src/commands/help.ts b/src/commands/help.ts
index c3b015c..900f24c 100644
--- a/src/commands/help.ts
+++ b/src/commands/help.ts
@@ -4,15 +4,15 @@
const command = new SlashCommandBuilder()
.setName("help")
- .setDescription("Shows help for commands")
+ .setDescription("Shows help for commands");
-const callback = async (interaction: CommandInteraction): Promise<any> => {
+const callback = async (interaction: CommandInteraction): Promise<void> => {
interaction.reply("hel p"); // TODO: FINISH THIS FOR RELEASE
-}
+};
-const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
+const check = (_interaction: CommandInteraction, _defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/mod/ban.ts b/src/commands/mod/ban.ts
index 8fc98d2..57db408 100644
--- a/src/commands/mod/ban.ts
+++ b/src/commands/mod/ban.ts
@@ -9,15 +9,15 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("ban")
- .setDescription("Bans a user from the server")
- .addUserOption(option => option.setName("user").setDescription("The user to ban").setRequired(true))
- .addNumberOption(option => option.setName("delete").setDescription("The days of messages to delete | Default: 0").setMinValue(0).setMaxValue(7).setRequired(false))
+ .setName("ban")
+ .setDescription("Bans a user from the server")
+ .addUserOption(option => option.setName("user").setDescription("The user to ban").setRequired(true))
+ .addNumberOption(option => option.setName("delete").setDescription("The days of messages to delete | Default: 0").setMinValue(0).setMaxValue(7).setRequired(false));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- const { renderUser } = client.logger
+ const { renderUser } = client.logger;
// TODO:[Modals] Replace this with a modal
- let reason = null
+ let reason = null;
let notify = true;
let confirmation;
while (true) {
@@ -28,22 +28,22 @@
"user": renderUser(interaction.options.getUser("user")),
"reason": reason ? ("\n> " + ((reason ?? "").replaceAll("\n", "\n> "))) : "*No reason provided*"
})
- + `The user **will${notify ? '' : ' not'}** be notified\n`
+ + `The user **will${notify ? "" : " not"}** be notified\n`
+ `${addPlurals(interaction.options.getInteger("delete") ? interaction.options.getInteger("delete") : 0, "day")} of messages will be deleted\n\n`
+ `Are you sure you want to ban <@!${(interaction.options.getMember("user") as GuildMember).id}>?`)
.setColor("Danger")
.addReasonButton(reason ?? "")
- .send(reason !== null)
- reason = reason ?? ""
- if (confirmation.cancelled) return
- if (confirmation.success) break
- if (confirmation.newReason) reason = confirmation.newReason
- if (confirmation.components) notify = confirmation.components.notify.active
+ .send(reason !== null);
+ reason = reason ?? "";
+ if (confirmation.cancelled) return;
+ if (confirmation.success) break;
+ if (confirmation.newReason) reason = confirmation.newReason;
+ if (confirmation.components) notify = confirmation.components.notify.active;
}
if (confirmation.success) {
- let dmd = false
+ let dmd = false;
let dm;
- let config = await client.database.guilds.read(interaction.guild.id);
+ const config = await client.database.guilds.read(interaction.guild.id);
try {
if (notify) {
dm = await (interaction.options.getMember("user") as GuildMember).send({
@@ -59,23 +59,23 @@
.setLabel(config.moderation.ban.text)
.setURL(config.moderation.ban.link)
] : [])]
- })
- dmd = true
+ });
+ dmd = true;
}
- } catch {}
+ } catch { dmd = false; }
try {
- let member = (interaction.options.getMember("user") as GuildMember)
+ const member = (interaction.options.getMember("user") as GuildMember);
member.ban({
days: Number(interaction.options.getNumber("delete") ?? 0),
reason: reason ?? "No reason provided"
- })
- try { await client.database.history.create("ban", interaction.guild.id, member.user, interaction.user, reason) } catch {}
- const { log, NucleusColors, entry, renderUser, renderDelta } = client.logger
- let data = {
+ });
+ await client.database.history.create("ban", interaction.guild.id, member.user, interaction.user, reason);
+ const { log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
+ const data = {
meta: {
- type: 'memberBan',
- displayName: 'Member Banned',
- calculateType: 'guildMemberPunish',
+ type: "memberBan",
+ displayName: "Member Banned",
+ calculateType: "guildMemberPunish",
color: NucleusColors.red,
emoji: "PUNISH.BAN.RED",
timestamp: new Date().getTime()
@@ -87,64 +87,64 @@
bannedBy: entry(interaction.user.id, renderUser(interaction.user)),
reason: entry(reason, reason ? `\n> ${reason}` : "*No reason provided.*"),
accountCreated: entry(member.user.createdAt, renderDelta(member.user.createdAt)),
- serverMemberCount: interaction.guild.memberCount,
+ serverMemberCount: interaction.guild.memberCount
},
hidden: {
guild: interaction.guild.id
}
- }
+ };
log(data);
} catch {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("PUNISH.BAN.RED")
- .setTitle(`Ban`)
+ .setTitle("Ban")
.setDescription("Something went wrong and the user was not banned")
.setStatus("Danger")
- ], components: []})
- if (dmd) await dm.delete()
- return
+ ], components: []});
+ if (dmd) await dm.delete();
+ return;
}
- let failed = (dmd === false && notify)
+ const failed = (dmd === false && notify);
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji(`PUNISH.BAN.${failed ? "YELLOW" : "GREEN"}`)
- .setTitle(`Ban`)
+ .setTitle("Ban")
.setDescription("The member was banned" + (failed ? ", but could not be notified" : ""))
.setStatus(failed ? "Warning" : "Success")
- ], components: []})
+ ], components: []});
} else {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("PUNISH.BAN.GREEN")
- .setTitle(`Ban`)
+ .setTitle("Ban")
.setDescription("No changes were made")
.setStatus("Success")
- ], components: []})
+ ], components: []});
}
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as GuildMember)
- let me = (interaction.guild.me as GuildMember)
- let apply = (interaction.options.getMember("user") as GuildMember)
- if (member === null || me === null || apply === null) throw "That member is not in the server"
- let memberPos = member.roles ? member.roles.highest.position : 0
- let mePos = me.roles ? me.roles.highest.position : 0
- let applyPos = apply.roles ? apply.roles.highest.position : 0
+ const member = (interaction.member as GuildMember);
+ const me = (interaction.guild.me as GuildMember);
+ const apply = (interaction.options.getMember("user") as GuildMember);
+ if (member === null || me === null || apply === null) throw "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 "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 "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";
// 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 "I cannot ban myself";
// Allow the owner to ban anyone
- if (member.id === interaction.guild.ownerId) return true
+ 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";
// 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 "You do not have a role higher than that member";
// Allow ban
- return true
-}
+ return true;
+};
export { command, callback, check };
\ No newline at end of file
diff --git a/src/commands/mod/info.ts b/src/commands/mod/info.ts
index c50c6f4..482af5b 100644
--- a/src/commands/mod/info.ts
+++ b/src/commands/mod/info.ts
@@ -1,18 +1,18 @@
-import { HistorySchema } from '../../utils/database';
+import { HistorySchema } from "../../utils/database";
import Discord, { CommandInteraction, GuildMember, MessageActionRow, MessageButton, TextInputComponent } from "discord.js";
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import getEmojiByName from "../../utils/getEmojiByName.js";
import client from "../../utils/client.js";
-import { modalInteractionCollector } from '../../utils/dualCollector.js';
-import pageIndicator from '../../utils/createPageIndicator.js';
+import { modalInteractionCollector } from "../../utils/dualCollector.js";
+import pageIndicator from "../../utils/createPageIndicator.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("info")
- .setDescription("Shows moderator information about a user")
- .addUserOption(option => option.setName("user").setDescription("The user to get information about").setRequired(true))
+ .setName("info")
+ .setDescription("Shows moderator information about a user")
+ .addUserOption(option => option.setName("user").setDescription("The user to get information about").setRequired(true));
const types = {
"warn": {emoji: "PUNISH.WARN.YELLOW", text: "Warned"},
@@ -26,7 +26,7 @@
"unban": {emoji: "MEMBER.UNBAN", text: "Unbanned"},
"purge": {emoji: "PUNISH.CLEARHISTORY", text: "Messages cleared"},
"nickname": {emoji: "PUNISH.NICKNAME.YELLOW", text: "Nickname changed"}
-}
+};
function historyToString(history: HistorySchema) {
let s = `${getEmojiByName(types[history.type].emoji)} ${
@@ -44,16 +44,16 @@
class TimelineSection {
name: string;
- content: {data: HistorySchema, rendered: string}[] = []
+ content: {data: HistorySchema, rendered: string}[] = [];
- addContent = (content: {data: HistorySchema, rendered: string}) => { this.content.push(content); return this; }
+ addContent = (content: {data: HistorySchema, rendered: string}) => { this.content.push(content); return this; };
contentLength = () => { return this.content.reduce((acc, cur) => acc + cur.rendered.length, 0); };
generateName = () => {
- let first = Math.round(this.content[0].data.occurredAt.getTime() / 1000)
- let 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>`; }
return this.name = `<t:${first}:F> - <t:${last}:F>`;
- }
+ };
}
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
@@ -70,15 +70,15 @@
history = await client.database.history.read(member.guild.id, member.id, currentYear);
history = history.sort((a, b) => b.occurredAt.getTime() - a.occurredAt.getTime()).reverse();
if (openFilterPane) {
- let tempFilteredTypes = filteredTypes
+ let tempFilteredTypes = filteredTypes;
if (filteredTypes.length === 0) { tempFilteredTypes = Object.keys(types); }
- history = history.filter(h => tempFilteredTypes.includes(h.type))
- };
+ history = history.filter(h => tempFilteredTypes.includes(h.type));
+ }
refresh = false;
}
- let groups: TimelineSection[] = []
+ const groups: TimelineSection[] = [];
if (history.length > 0) {
- current = new TimelineSection()
+ current = new TimelineSection();
history.forEach(event => {
if (current.contentLength() + historyToString(event).length > 2000 || current.content.length === 5) {
groups.push(current);
@@ -91,17 +91,17 @@
groups.push(current);
if (pageIndex === null) { pageIndex = groups.length - 1; }
}
- let components = (
+ const components = (
openFilterPane ? [
- new MessageActionRow().addComponents([new Discord.MessageSelectMenu().setOptions(
- Object.entries(types).map(([key, value]) => ({
+ new MessageActionRow().addComponents([new Discord.MessageSelectMenu().setOptions(
+ Object.entries(types).map(([key, value]) => ({
label: value.text,
value: key,
default: filteredTypes.includes(key),
emoji: client.emojis.resolve(getEmojiByName(value.emoji, "id"))
- }))
- ).setMinValues(1).setMaxValues(Object.keys(types).length).setCustomId("filter").setPlaceholder("Select at least one event")])
- ] : []).concat([
+ }))
+ ).setMinValues(1).setMaxValues(Object.keys(types).length).setCustomId("filter").setPlaceholder("Select at least one event")])
+ ] : []).concat([
new MessageActionRow().addComponents([
new MessageButton()
.setCustomId("prevYear")
@@ -126,7 +126,7 @@
.setLabel((currentYear + 1).toString())
.setEmoji(getEmojiByName("CONTROL.RIGHT", "id"))
.setStyle("SECONDARY")
- .setDisabled(currentYear === new Date().getFullYear()),
+ .setDisabled(currentYear === new Date().getFullYear())
]), new MessageActionRow().addComponents([
new MessageButton()
.setLabel("Mod notes")
@@ -139,14 +139,14 @@
.setStyle(openFilterPane ? "SUCCESS" : "PRIMARY")
.setEmoji(getEmojiByName("ICONS.FILTER", "id"))
])
- ])
- let end = "\n\nJanuary " + currentYear.toString() + pageIndicator(
+ ]);
+ const end = "\n\nJanuary " + currentYear.toString() + pageIndicator(
Math.max(groups.length, 1),
groups.length === 0 ? 1 : pageIndex
) + (currentYear === new Date().getFullYear() ? monthNames[new Date().getMonth()] : "December"
- ) + " " + currentYear.toString()
+ ) + " " + currentYear.toString();
if (groups.length > 0) {
- let toRender = groups[Math.min(pageIndex, groups.length - 1)]
+ const toRender = groups[Math.min(pageIndex, groups.length - 1)];
m = await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("MEMBER.JOIN")
.setTitle("Moderation history for " + member.user.username)
@@ -158,7 +158,7 @@
m = await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("MEMBER.JOIN")
.setTitle("Moderation history for " + member.user.username)
- .setDescription(`**${currentYear}**\n\n*No events*` + `\n\n` + end)
+ .setDescription(`**${currentYear}**\n\n*No events*` + "\n\n" + end)
.setStatus("Success")
.setFooter({text: (openFilterPane && filteredTypes.length) ? "Filters are currently enabled" : ""})
], components: components});
@@ -174,9 +174,9 @@
.setStatus("Danger")
.setFooter({text: "Message timed out"})
]});
- return 0
+ return 0;
}
- i.deferUpdate()
+ i.deferUpdate();
if (i.customId === "filter") {
filteredTypes = i.values;
pageIndex = null;
@@ -193,15 +193,15 @@
if (pageIndex >= groups.length) { pageIndex = 0; currentYear++; refresh = true; }
}
if (i.customId === "today") { currentYear = new Date().getFullYear(); pageIndex = null; refresh = true; }
- if (i.customId === "modNotes") { return 1 }
- if (i.customId === "openFilter") { openFilterPane = !openFilterPane; refresh = true }
+ if (i.customId === "modNotes") { return 1; }
+ if (i.customId === "openFilter") { openFilterPane = !openFilterPane; refresh = true; }
}
}
const callback = async (interaction: CommandInteraction): Promise<any> => {
let m;
- let member = (interaction.options.getMember("user")) as Discord.GuildMember;
+ const member = (interaction.options.getMember("user")) as Discord.GuildMember;
await interaction.reply({embeds: [new EmojiEmbed()
.setEmoji("NUCLEUS.LOADING")
.setTitle("Downloading Data")
@@ -233,9 +233,9 @@
let i;
try {
i = await m.awaitMessageComponent({ time: 300000 });
- } catch (e) { return }
+ } catch (e) { return; }
if (i.customId === "modify") {
- await i.showModal(new Discord.Modal().setCustomId("modal").setTitle(`Editing moderator note`).addComponents(
+ await i.showModal(new Discord.Modal().setCustomId("modal").setTitle("Editing moderator note").addComponents(
new MessageActionRow<TextInputComponent>().addComponents(new TextInputComponent()
.setCustomId("note")
.setLabel("Note")
@@ -244,7 +244,7 @@
.setStyle("PARAGRAPH")
.setValue(note ? note : "")
)
- ))
+ ));
await interaction.editReply({
embeds: [new EmojiEmbed()
.setTitle("Mod notes for " + member.user.username)
@@ -260,24 +260,24 @@
});
let out;
try {
- out = await modalInteractionCollector(m, (m) => m.channel.id === interaction.channel.id, (m) => m.customId === "modify")
- } catch (e) { continue }
+ out = await modalInteractionCollector(m, (m) => m.channel.id === interaction.channel.id, (m) => m.customId === "modify");
+ } catch (e) { continue; }
if (out.fields) {
- let toAdd = out.fields.getTextInputValue("note") || null;
+ const toAdd = out.fields.getTextInputValue("note") || null;
await client.database.notes.create(member.guild.id, member.id, toAdd);
- } else { continue }
+ } else { continue; }
} else if (i.customId === "history") {
i.deferUpdate();
- if (!await showHistory(member, interaction) ) return
+ if (!await showHistory(member, interaction) ) return;
}
}
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as GuildMember)
+ const member = (interaction.member as GuildMember);
if (! member.permissions.has("MODERATE_MEMBERS")) throw "You do not have the *Moderate Members* permission";
- return true
-}
+ return true;
+};
export { command };
export { callback };
diff --git a/src/commands/mod/kick.ts b/src/commands/mod/kick.ts
index ef748e8..b9b1b2a 100644
--- a/src/commands/mod/kick.ts
+++ b/src/commands/mod/kick.ts
@@ -1,5 +1,5 @@
import { CommandInteraction, GuildMember, MessageActionRow, MessageButton } from "discord.js";
-import humanizeDuration from 'humanize-duration';
+import humanizeDuration from "humanize-duration";
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
import confirmationMessage from "../../utils/confirmationMessage.js";
@@ -9,16 +9,16 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("kick")
- .setDescription("Kicks a user from the server")
- .addUserOption(option => option.setName("user").setDescription("The user to kick").setRequired(true))
+ .setName("kick")
+ .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<any> => {
- const { renderUser } = client.logger
+ const { renderUser } = client.logger;
// TODO:[Modals] Replace this with a modal
let reason = null;
let notify = true;
- let confirmation
+ let confirmation;
while (true) {
confirmation = await new confirmationMessage(interaction)
.setEmoji("PUNISH.KICK.RED")
@@ -27,23 +27,23 @@
"user": renderUser(interaction.options.getUser("user")),
"reason": reason ? ("\n> " + ((reason ?? "").replaceAll("\n", "\n> "))) : "*No reason provided*"
})
- + `The user **will${notify ? '' : ' not'}** be notified\n\n`
+ + `The user **will${notify ? "" : " not"}** be notified\n\n`
+ `Are you sure you want to kick <@!${(interaction.options.getMember("user") as GuildMember).id}>?`)
.setColor("Danger")
.addReasonButton(reason ?? "")
- .send(reason !== null)
- reason = reason ?? ""
- if (confirmation.cancelled) return
- if (confirmation.success) break
- if (confirmation.newReason) reason = confirmation.newReason
+ .send(reason !== null);
+ reason = reason ?? "";
+ if (confirmation.cancelled) return;
+ if (confirmation.success) break;
+ if (confirmation.newReason) reason = confirmation.newReason;
if (confirmation.components) {
- notify = confirmation.components.notify.active
+ notify = confirmation.components.notify.active;
}
}
if (confirmation.success) {
- let dmd = false
+ let dmd = false;
let dm;
- let config = await client.database.guilds.read(interaction.guild.id);
+ const config = await client.database.guilds.read(interaction.guild.id);
try {
if (notify) {
dm = await (interaction.options.getMember("user") as GuildMember).send({
@@ -59,20 +59,20 @@
.setLabel(config.moderation.kick.text)
.setURL(config.moderation.kick.link)
] : [])]
- })
- dmd = true
+ });
+ dmd = true;
}
- } catch {}
+ } catch { dmd = false; }
try {
- (interaction.options.getMember("user") as GuildMember).kick(reason ?? "No reason provided.")
- let member = (interaction.options.getMember("user") as GuildMember)
- try { await client.database.history.create("kick", interaction.guild.id, member.user, interaction.user, reason) } catch {}
- const { log, NucleusColors, entry, renderUser, renderDelta } = client.logger
- let data = {
+ (interaction.options.getMember("user") as GuildMember).kick(reason ?? "No reason provided.");
+ const member = (interaction.options.getMember("user") as GuildMember);
+ await client.database.history.create("kick", interaction.guild.id, member.user, interaction.user, reason);
+ const { log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
+ const data = {
meta: {
- type: 'memberKick',
- displayName: 'Member Kicked',
- calculateType: 'guildMemberPunish',
+ type: "memberKick",
+ displayName: "Member Kicked",
+ calculateType: "guildMemberPunish",
color: NucleusColors.red,
emoji: "PUNISH.KICK.RED",
timestamp: new Date().getTime()
@@ -86,64 +86,64 @@
reason: entry(reason, reason ? `\n> ${reason}` : "*No reason provided.*"),
timeInServer: entry(new Date().getTime() - member.joinedTimestamp, humanizeDuration(new Date().getTime() - member.joinedTimestamp, { round: true })),
accountCreated: entry(member.user.createdAt, renderDelta(member.user.createdAt)),
- serverMemberCount: member.guild.memberCount,
+ serverMemberCount: member.guild.memberCount
},
hidden: {
guild: member.guild.id
}
- }
+ };
log(data);
} catch {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("PUNISH.KICK.RED")
- .setTitle(`Kick`)
+ .setTitle("Kick")
.setDescription("Something went wrong and the user was not kicked")
.setStatus("Danger")
- ], components: []})
- if (dmd) await dm.delete()
- return
+ ], components: []});
+ if (dmd) await dm.delete();
+ return;
}
- let failed = (dmd === false && notify)
+ const failed = (dmd === false && notify);
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji(`PUNISH.KICK.${failed ? "YELLOW" : "GREEN"}`)
- .setTitle(`Kick`)
+ .setTitle("Kick")
.setDescription("The member was kicked" + (failed ? ", but could not be notified" : ""))
.setStatus(failed ? "Warning" : "Success")
- ], components: []})
+ ], components: []});
} else {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("PUNISH.KICK.GREEN")
- .setTitle(`Kick`)
+ .setTitle("Kick")
.setDescription("No changes were made")
.setStatus("Success")
- ], components: []})
+ ], components: []});
}
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as GuildMember)
- let me = (interaction.guild.me as GuildMember)
- let apply = (interaction.options.getMember("user") as GuildMember)
- if (member === null || me === null || apply === null) throw "That member is not in the server"
- let memberPos = member.roles ? member.roles.highest.position : 0
- let mePos = me.roles ? me.roles.highest.position : 0
- let applyPos = apply.roles ? apply.roles.highest.position : 0
+ const member = (interaction.member as GuildMember);
+ const me = (interaction.guild.me as GuildMember);
+ const apply = (interaction.options.getMember("user") as GuildMember);
+ if (member === null || me === null || apply === null) throw "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 "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 "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";
// 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 "I cannot kick myself";
// Allow the owner to kick anyone
- if (member.id === interaction.guild.ownerId) return true
+ 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";
// 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 "You do not have a role higher than that member";
// Allow kick
- return true
-}
+ return true;
+};
export { command, callback, check };
\ No newline at end of file
diff --git a/src/commands/mod/mute.ts b/src/commands/mod/mute.ts
index 808d22d..183c487 100644
--- a/src/commands/mod/mute.ts
+++ b/src/commands/mod/mute.ts
@@ -1,4 +1,4 @@
-import { LoadingEmbed } from './../../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "./../../utils/defaultEmbeds.js";
import Discord, { CommandInteraction, GuildMember, MessageActionRow, MessageButton } from "discord.js";
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
@@ -12,30 +12,30 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("mute")
- .setDescription("Mutes a member, stopping them from talking in the server")
- .addUserOption(option => option.setName("user").setDescription("The user to mute").setRequired(true))
- .addIntegerOption(option => option.setName("days").setDescription("The number of days to mute the user for | Default: 0").setMinValue(0).setMaxValue(27).setRequired(false))
- .addIntegerOption(option => option.setName("hours").setDescription("The number of hours to mute the user for | Default: 0").setMinValue(0).setMaxValue(23).setRequired(false))
- .addIntegerOption(option => option.setName("minutes").setDescription("The number of minutes to mute the user for | Default: 0").setMinValue(0).setMaxValue(59).setRequired(false))
- .addIntegerOption(option => option.setName("seconds").setDescription("The number of seconds to mute the user for | Default: 0").setMinValue(0).setMaxValue(59).setRequired(false))
+ .setName("mute")
+ .setDescription("Mutes a member, stopping them from talking in the server")
+ .addUserOption(option => option.setName("user").setDescription("The user to mute").setRequired(true))
+ .addIntegerOption(option => option.setName("days").setDescription("The number of days to mute the user for | Default: 0").setMinValue(0).setMaxValue(27).setRequired(false))
+ .addIntegerOption(option => option.setName("hours").setDescription("The number of hours to mute the user for | Default: 0").setMinValue(0).setMaxValue(23).setRequired(false))
+ .addIntegerOption(option => option.setName("minutes").setDescription("The number of minutes to mute the user for | Default: 0").setMinValue(0).setMaxValue(59).setRequired(false))
+ .addIntegerOption(option => option.setName("seconds").setDescription("The number of seconds to mute the user for | Default: 0").setMinValue(0).setMaxValue(59).setRequired(false));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- const { log, NucleusColors, renderUser, entry, renderDelta } = client.logger
- const user = interaction.options.getMember("user") as GuildMember
+ const { log, NucleusColors, renderUser, entry, renderDelta } = client.logger;
+ const user = interaction.options.getMember("user") as GuildMember;
const time = {
days: interaction.options.getInteger("days") || 0,
hours: interaction.options.getInteger("hours") || 0,
minutes: interaction.options.getInteger("minutes") || 0,
seconds: interaction.options.getInteger("seconds") || 0
- }
- let config = await client.database.guilds.read(interaction.guild.id)
- let serverSettingsDescription = (config.moderation.mute.timeout ? "given a timeout" : "")
- if (config.moderation.mute.role) serverSettingsDescription += (serverSettingsDescription ? " and " : "") + `given the <@&${config.moderation.mute.role}> role`
+ };
+ const config = await client.database.guilds.read(interaction.guild.id);
+ let serverSettingsDescription = (config.moderation.mute.timeout ? "given a timeout" : "");
+ if (config.moderation.mute.role) serverSettingsDescription += (serverSettingsDescription ? " and " : "") + `given the <@&${config.moderation.mute.role}> role`;
- let muteTime = (time.days * 24 * 60 * 60) + (time.hours * 60 * 60) + (time.minutes * 60) + time.seconds
+ let muteTime = (time.days * 24 * 60 * 60) + (time.hours * 60 * 60) + (time.minutes * 60) + time.seconds;
if (muteTime === 0) {
- let m = await interaction.reply({embeds: [
+ const m = await interaction.reply({embeds: [
new EmojiEmbed()
.setEmoji("PUNISH.MUTE.GREEN")
.setTitle("Mute")
@@ -85,30 +85,30 @@
.setStyle("DANGER")
.setEmoji(getEmojiByName("CONTROL.CROSS", "id"))
])
- ], ephemeral: true, fetchReply: true})
+ ], ephemeral: true, fetchReply: true});
let component;
try {
component = await (m as Discord.Message).awaitMessageComponent({filter: (m) => m.user.id === interaction.user.id, time: 300000});
- } catch { return }
+ } catch { return; }
component.deferUpdate();
if (component.customId === "cancel") return interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("PUNISH.MUTE.RED")
.setTitle("Mute")
.setDescription("Mute cancelled")
.setStatus("Danger")
- ]})
+ ]});
switch (component.customId) {
- case "1m": { muteTime = 60; break; }
- case "10m": { muteTime = 60 * 10; break; }
- case "30m": { muteTime = 60 * 30; break; }
- case "1h": { muteTime = 60 * 60; break; }
- case "6h": { muteTime = 60 * 60 * 6; break; }
- case "12h": { muteTime = 60 * 60 * 12; break; }
- case "1d": { muteTime = 60 * 60 * 24; break; }
- case "1w": { muteTime = 60 * 60 * 24 * 7; break; }
+ case "1m": { muteTime = 60; break; }
+ case "10m": { muteTime = 60 * 10; break; }
+ case "30m": { muteTime = 60 * 30; break; }
+ case "1h": { muteTime = 60 * 60; break; }
+ case "6h": { muteTime = 60 * 60 * 6; break; }
+ case "12h": { muteTime = 60 * 60 * 12; break; }
+ case "1d": { muteTime = 60 * 60 * 24; break; }
+ case "1w": { muteTime = 60 * 60 * 24 * 7; break; }
}
} else {
- await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true})
+ await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true});
}
// TODO:[Modals] Replace this with a modal
let reason = null;
@@ -124,8 +124,8 @@
"time": `${humanizeDuration(muteTime * 1000, {round: true})}`,
"reason": reason ? ("\n> " + ((reason ?? "").replaceAll("\n", "\n> "))) : "*No reason provided*"
})
- + `The user will be ` + serverSettingsDescription + "\n"
- + `The user **will${notify ? '' : ' not'}** be notified\n\n`
+ + "The user will be " + serverSettingsDescription + "\n"
+ + `The user **will${notify ? "" : " not"}** be notified\n\n`
+ `Are you sure you want to mute <@!${user.id}>?`)
.setColor("Danger")
.addCustomBoolean(
@@ -134,20 +134,20 @@
"An appeal ticket will be created when Confirm is clicked", "CONTROL.TICKET", createAppealTicket)
.addCustomBoolean("notify", "Notify user", false, null, null, "ICONS.NOTIFY." + (notify ? "ON" : "OFF" ), notify)
.addReasonButton(reason ?? "")
- .send(true)
- reason = reason ?? ""
- if (confirmation.cancelled) return
- if (confirmation.success) break
- if (confirmation.newReason) reason = confirmation.newReason
+ .send(true);
+ reason = reason ?? "";
+ if (confirmation.cancelled) return;
+ if (confirmation.success) break;
+ if (confirmation.newReason) reason = confirmation.newReason;
if (confirmation.components) {
- notify = confirmation.components.notify.active
- createAppealTicket = confirmation.components.appeal.active
+ notify = confirmation.components.notify.active;
+ createAppealTicket = confirmation.components.appeal.active;
}
}
if (confirmation.success) {
- let dmd = false
+ let dmd = false;
let dm;
- let config = await client.database.guilds.read(interaction.guild.id);
+ const config = await client.database.guilds.read(interaction.guild.id);
try {
if (notify) {
dm = await user.send({
@@ -157,7 +157,7 @@
.setDescription(`You have been muted in ${interaction.guild.name}` +
(reason ? ` for:\n> ${reason}` : ".\n\n" +
`You will be unmuted at: <t:${Math.round((new Date).getTime() / 1000) + muteTime}:D> at <t:${Math.round((new Date).getTime() / 1000) + muteTime}:T> (<t:${Math.round((new Date).getTime() / 1000) + muteTime}:R>)`) +
- (confirmation.components.appeal.response ? `You can appeal this here: <#${confirmation.components.appeal.response}>` : ``))
+ (confirmation.components.appeal.response ? `You can appeal this here: <#${confirmation.components.appeal.response}>` : ""))
.setStatus("Danger")
],
components: [new MessageActionRow().addComponents(config.moderation.mute.text ? [new MessageButton()
@@ -165,60 +165,60 @@
.setLabel(config.moderation.mute.text)
.setURL(config.moderation.mute.link)
] : [])]
- })
- dmd = true
+ });
+ dmd = true;
}
- } catch {}
- let member = user
- let errors = 0
+ } catch { dmd = false; }
+ const member = user;
+ let errors = 0;
try {
if (config.moderation.mute.timeout) {
- await member.timeout(muteTime * 1000, reason || "No reason provided")
+ await member.timeout(muteTime * 1000, reason || "No reason provided");
if (config.moderation.mute.role !== null) {
- await member.roles.add(config.moderation.mute.role)
+ await member.roles.add(config.moderation.mute.role);
await client.database.eventScheduler.schedule("naturalUnmute", new Date().getTime() + muteTime * 1000, {
guild: interaction.guild.id,
user: user.id,
expires: new Date().getTime() + muteTime * 1000
- })
+ });
}
}
- } catch { errors++ }
+ } catch { errors++; }
try {
if (config.moderation.mute.role !== null) {
- await member.roles.add(config.moderation.mute.role)
+ await member.roles.add(config.moderation.mute.role);
await client.database.eventScheduler.schedule("unmuteRole", new Date().getTime() + muteTime * 1000, {
guild: interaction.guild.id,
user: user.id,
role: config.moderation.mute.role
- })
+ });
}
- } catch (e){ console.log(e); errors++ }
+ } catch (e){ console.log(e); errors++; }
if (errors === 2) {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("PUNISH.MUTE.RED")
- .setTitle(`Mute`)
+ .setTitle("Mute")
.setDescription("Something went wrong and the user was not muted")
.setStatus("Danger")
- ], components: []}) // TODO: make this clearer
- if (dmd) await dm.delete()
- return
+ ], components: []}); // TODO: make this clearer
+ if (dmd) await dm.delete();
+ return;
}
- try { await client.database.history.create("mute", interaction.guild.id, member.user, interaction.user, reason) } catch {}
- let failed = (dmd === false && notify)
+ await client.database.history.create("mute", interaction.guild.id, member.user, interaction.user, reason);
+ const failed = (dmd === false && notify);
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji(`PUNISH.MUTE.${failed ? "YELLOW" : "GREEN"}`)
- .setTitle(`Mute`)
- .setDescription("The member was muted" + (failed ? ", but could not be notified" : "") + (confirmation.components.appeal.response ? ` and an appeal ticket was opened in <#${confirmation.components.appeal.response}>` : ``))
+ .setTitle("Mute")
+ .setDescription("The member was muted" + (failed ? ", but could not be notified" : "") + (confirmation.components.appeal.response ? ` and an appeal ticket was opened in <#${confirmation.components.appeal.response}>` : ""))
.setStatus(failed ? "Warning" : "Success")
- ], components: []})
- let data = {
+ ], components: []});
+ const data = {
meta:{
- type: 'memberMute',
- displayName: 'Member Muted',
- calculateType: 'guildMemberPunish',
+ type: "memberMute",
+ displayName: "Member Muted",
+ calculateType: "guildMemberPunish",
color: NucleusColors.yellow,
- emoji: 'PUNISH.WARN.YELLOW',
+ emoji: "PUNISH.WARN.YELLOW",
timestamp: new Date().getTime()
},
list: {
@@ -227,47 +227,47 @@
mutedUntil: entry(new Date().getTime() + muteTime * 1000, renderDelta(new Date().getTime() + muteTime * 1000)),
muted: entry(new Date().getTime(), renderDelta(new Date().getTime() - 1000)),
mutedBy: entry(interaction.member.user.id, renderUser(interaction.member.user)),
- reason: entry(reason, reason ? reason : '*No reason provided*')
+ reason: entry(reason, reason ? reason : "*No reason provided*")
},
hidden: {
guild: interaction.guild.id
}
- }
+ };
log(data);
} else {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("PUNISH.MUTE.GREEN")
- .setTitle(`Mute`)
+ .setTitle("Mute")
.setDescription("No changes were made")
.setStatus("Success")
- ], components: []})
+ ], components: []});
}
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as GuildMember)
- let me = (interaction.guild.me as GuildMember)
- let apply = (interaction.options.getMember("user") as GuildMember)
- if (member === null || me === null || apply === null) throw "That member is not in the server"
- let memberPos = member.roles ? member.roles.highest.position : 0
- let mePos = me.roles ? me.roles.highest.position : 0
- let applyPos = apply.roles ? apply.roles.highest.position : 0
+ const member = (interaction.member as GuildMember);
+ const me = (interaction.guild.me as GuildMember);
+ const apply = (interaction.options.getMember("user") as GuildMember);
+ if (member === null || me === null || apply === null) throw "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 "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 "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";
// Do not allow muting Nucleus
- if (member.id === me.id) throw "I cannot mute myself"
+ if (member.id === me.id) throw "I cannot mute myself";
// Allow the owner to mute anyone
- if (member.id === interaction.guild.ownerId) return true
+ 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";
// 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 "You do not have a role higher than that member";
// Allow mute
- return true
-}
+ return true;
+};
export { command, callback, check };
\ No newline at end of file
diff --git a/src/commands/mod/nick.ts b/src/commands/mod/nick.ts
index d50becd..9cc8a7c 100644
--- a/src/commands/mod/nick.ts
+++ b/src/commands/mod/nick.ts
@@ -5,17 +5,17 @@
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import keyValueList from "../../utils/generateKeyValueList.js";
import { create, areTicketsEnabled } from "../../actions/createModActionTicket.js";
-import client from "../../utils/client.js"
+import client from "../../utils/client.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("nick")
- .setDescription("Changes a users nickname")
- .addUserOption(option => option.setName("user").setDescription("The user to change").setRequired(true))
- .addStringOption(option => option.setName("name").setDescription("The name to set | Leave blank to clear").setRequired(false))
+ .setName("nick")
+ .setDescription("Changes a users nickname")
+ .addUserOption(option => option.setName("user").setDescription("The user to change").setRequired(true))
+ .addStringOption(option => option.setName("name").setDescription("The name to set | Leave blank to clear").setRequired(false));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- const { renderUser } = client.logger
+ const { renderUser } = client.logger;
// TODO:[Modals] Replace this with a modal
let notify = true;
let confirmation;
@@ -27,19 +27,19 @@
"user": renderUser(interaction.options.getUser("user")),
"new nickname": `${interaction.options.getString("name") ? interaction.options.getString("name") : "*No nickname*"}`
})
- + `The user **will${notify ? '' : ' not'}** be notified\n\n`
+ + `The user **will${notify ? "" : " not"}** be notified\n\n`
+ `Are you sure you want to ${interaction.options.getString("name") ? "change" : "clear"} <@!${(interaction.options.getMember("user") as GuildMember).id}>'s nickname?`)
.setColor("Danger")
.addCustomBoolean("notify", "Notify user", false, null, null, "ICONS.NOTIFY." + (notify ? "ON" : "OFF" ), notify)
- .send(interaction.options.getString("name") !== null)
- if (confirmation.cancelled) return
- if (confirmation.success) break
+ .send(interaction.options.getString("name") !== null);
+ if (confirmation.cancelled) return;
+ if (confirmation.success) break;
if (confirmation.components) {
- notify = confirmation.components.notify.active
+ notify = confirmation.components.notify.active;
}
}
if (confirmation.success) {
- let dmd = false
+ let dmd = false;
let dm;
try {
if (notify) {
@@ -49,94 +49,94 @@
.setTitle("Nickname changed")
.setDescription(`Your nickname was ${interaction.options.getString("name") ? "changed" : "cleared"} in ${interaction.guild.name}.` +
(interaction.options.getString("name") ? ` it is now: ${interaction.options.getString("name")}` : "") + "\n\n" +
- (confirmation.components.appeal.response ? `You can appeal this here: <#${confirmation.components.appeal.response}>` : ``))
+ (confirmation.components.appeal.response ? `You can appeal this here: <#${confirmation.components.appeal.response}>` : ""))
.setStatus("Danger")
]
- })
- dmd = true
+ });
+ dmd = true;
}
- } catch {}
+ } catch { dmd = false; }
try {
- let member = (interaction.options.getMember("user") as GuildMember)
- let before = member.nickname
- let nickname = interaction.options.getString("name")
- member.setNickname(nickname ?? null, "Nucleus Nickname command")
- try { await client.database.history.create(
+ const member = (interaction.options.getMember("user") as GuildMember);
+ const before = member.nickname;
+ const nickname = interaction.options.getString("name");
+ member.setNickname(nickname ?? null, "Nucleus Nickname command");
+ await client.database.history.create(
"nickname", interaction.guild.id, member.user, interaction.user,
- null, before, nickname) } catch {}
- const { log, NucleusColors, entry, renderUser, renderDelta } = client.logger
- let data = {
+ null, before, nickname);
+ const { log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
+ const data = {
meta: {
- type: 'memberUpdate',
- displayName: 'Member Updated',
- calculateType: 'guildMemberUpdate',
+ type: "memberUpdate",
+ displayName: "Member Updated",
+ calculateType: "guildMemberUpdate",
color: NucleusColors.yellow,
emoji: "PUNISH.NICKNAME.YELLOW",
timestamp: new Date().getTime()
},
list: {
memberId: entry(member.id, `\`${member.id}\``),
- before: entry(before, before ? before : '*None*'),
- after: entry(nickname, nickname ? nickname : '*None*'),
+ before: entry(before, before ? before : "*None*"),
+ after: entry(nickname, nickname ? nickname : "*None*"),
updated: entry(new Date().getTime(), renderDelta(new Date().getTime())),
updatedBy: entry(interaction.user.id, renderUser(interaction.user))
},
hidden: {
guild: interaction.guild.id
}
- }
+ };
log(data);
} catch {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("PUNISH.NICKNAME.RED")
- .setTitle(`Nickname`)
+ .setTitle("Nickname")
.setDescription("Something went wrong and the users nickname could not be changed.")
.setStatus("Danger")
- ], components: []})
- if (dmd) await dm.delete()
- return
+ ], components: []});
+ if (dmd) await dm.delete();
+ return;
}
- let failed = (dmd === false && notify)
+ const failed = (dmd === false && notify);
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji(`PUNISH.NICKNAME.${failed ? "YELLOW" : "GREEN"}`)
- .setTitle(`Nickname`)
- .setDescription("The members nickname was changed" + (failed ? ", but was not notified" : "") + (confirmation.components.appeal.response ? ` and an appeal ticket was opened in <#${confirmation.components.appeal.response}>` : ``))
+ .setTitle("Nickname")
+ .setDescription("The members nickname was changed" + (failed ? ", but was not notified" : "") + (confirmation.components.appeal.response ? ` and an appeal ticket was opened in <#${confirmation.components.appeal.response}>` : ""))
.setStatus(failed ? "Warning" : "Success")
- ], components: []})
+ ], components: []});
} else {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("PUNISH.NICKNAME.GREEN")
- .setTitle(`Nickname`)
+ .setTitle("Nickname")
.setDescription("No changes were made")
.setStatus("Success")
- ], components: []})
+ ], components: []});
}
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as GuildMember)
- let me = (interaction.guild.me as GuildMember)
- let apply = (interaction.options.getMember("user") as GuildMember)
- if (member === null || me === null || apply === null) throw "That member is not in the server"
- let memberPos = member.roles ? member.roles.highest.position : 0
- let mePos = me.roles ? me.roles.highest.position : 0
- let applyPos = apply.roles ? apply.roles.highest.position : 0
+ const member = (interaction.member as GuildMember);
+ const me = (interaction.guild.me as GuildMember);
+ const apply = (interaction.options.getMember("user") as GuildMember);
+ if (member === null || me === null || apply === null) throw "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 "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 "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";
// Allow the owner to change anyone's nickname
- if (member.id === interaction.guild.ownerId) return true
+ 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";
// Allow changing your own nickname
- if (member === apply) return true
+ 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 "You do not have a role higher than that member";
// Allow change
- return true
-}
+ return true;
+};
export { command, callback, check };
\ No newline at end of file
diff --git a/src/commands/mod/purge.ts b/src/commands/mod/purge.ts
index 521d8a7..13e688b 100644
--- a/src/commands/mod/purge.ts
+++ b/src/commands/mod/purge.ts
@@ -9,20 +9,20 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("purge")
- .setDescription("Bulk deletes messages in a channel")
- .addIntegerOption(option => option
- .setName("amount")
- .setDescription("The amount of messages to delete")
- .setRequired(false)
- .setMinValue(1)
- .setMaxValue(100))
- .addUserOption(option => option.setName("user").setDescription("The user to purge messages from").setRequired(false))
- .addStringOption(option => option.setName("reason").setDescription("The reason for the purge").setRequired(false))
+ .setName("purge")
+ .setDescription("Bulk deletes messages in a channel")
+ .addIntegerOption(option => option
+ .setName("amount")
+ .setDescription("The amount of messages to delete")
+ .setRequired(false)
+ .setMinValue(1)
+ .setMaxValue(100))
+ .addUserOption(option => option.setName("user").setDescription("The user to purge messages from").setRequired(false))
+ .addStringOption(option => option.setName("reason").setDescription("The reason for the purge").setRequired(false));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- let user = interaction.options.getMember("user") as GuildMember ?? null
- let channel = (interaction.channel as GuildChannel)
+ const user = interaction.options.getMember("user") as GuildMember ?? null;
+ const channel = (interaction.channel as GuildChannel);
if (!(["GUILD_TEXT", "GUILD_NEWS", "GUILD_NEWS_THREAD", "GUILD_PUBLIC_THREAD", "GUILD_PRIVATE_THREAD"].includes(channel.type.toString()))) {
return await interaction.reply({
embeds: [
@@ -33,8 +33,8 @@
.setStatus("Danger")
],
components: [],
- ephemeral: true,
- })
+ ephemeral: true
+ });
}
// TODO:[Modals] Replace this with a modal
if ( !interaction.options.getInteger("amount") ) {
@@ -49,10 +49,10 @@
components: [],
ephemeral: true,
fetchReply: true
- })
- let deleted = [] as Discord.Message[]
+ });
+ let deleted = [] as Discord.Message[];
while (true) {
- let m = await interaction.editReply({
+ const m = await interaction.editReply({
embeds: [
new EmojiEmbed()
.setEmoji("CHANNEL.PURGE.RED")
@@ -74,8 +74,8 @@
.setCustomId("5")
.setLabel("5")
.setStyle("SECONDARY")
- ]),
- new Discord.MessageActionRow().addComponents([
+ ]),
+ new Discord.MessageActionRow().addComponents([
new Discord.MessageButton()
.setCustomId("10")
.setLabel("10")
@@ -97,7 +97,7 @@
.setEmoji(getEmojiByName("CONTROL.TICK", "id"))
])
]
- })
+ });
let component;
try {
component = await (m as Discord.Message).awaitMessageComponent({filter: (m) => m.user.id === interaction.user.id, time: 300000});
@@ -109,12 +109,12 @@
let messages;
await (interaction.channel as TextChannel).messages.fetch({limit: amount}).then(async (ms) => {
if (user) {
- ms = ms.filter(m => m.author.id === user.id)
+ ms = ms.filter(m => m.author.id === user.id);
}
messages = await (channel as TextChannel).bulkDelete(ms, true);
- })
+ });
if (messages) {
- deleted = deleted.concat(messages.map(m => m))
+ deleted = deleted.concat(messages.map(m => m));
}
}
if (deleted.length === 0) return await interaction.editReply({
@@ -126,49 +126,46 @@
.setStatus("Danger")
],
components: []
- })
+ });
if (user) {
- try { await client.database.history.create("purge", interaction.guild.id, user, interaction.options.getString("reason"), null, null, deleted.length) } catch {}
+ await client.database.history.create("purge", interaction.guild.id, user, interaction.options.getString("reason"), null, null, deleted.length);
}
- let attachmentObject;
- try {
- const { log, NucleusColors, entry, renderUser, renderChannel } = client.logger
- let data = {
- meta: {
- type: 'channelPurge',
- displayName: 'Channel Purged',
- calculateType: 'messageDelete',
- color: NucleusColors.red,
- emoji: "PUNISH.BAN.RED",
- timestamp: new Date().getTime()
- },
- list: {
- memberId: entry(interaction.user.id, `\`${interaction.user.id}\``),
- purgedBy: entry(interaction.user.id, renderUser(interaction.user)),
- channel: entry(interaction.channel.id, renderChannel(interaction.channel)),
- messagesCleared: entry(deleted.length, deleted.length),
- },
- hidden: {
- guild: interaction.guild.id
- }
+ const { log, NucleusColors, entry, renderUser, renderChannel } = client.logger;
+ const data = {
+ meta: {
+ type: "channelPurge",
+ displayName: "Channel Purged",
+ calculateType: "messageDelete",
+ color: NucleusColors.red,
+ emoji: "PUNISH.BAN.RED",
+ timestamp: new Date().getTime()
+ },
+ list: {
+ memberId: entry(interaction.user.id, `\`${interaction.user.id}\``),
+ purgedBy: entry(interaction.user.id, renderUser(interaction.user)),
+ channel: entry(interaction.channel.id, renderChannel(interaction.channel)),
+ messagesCleared: entry(deleted.length, deleted.length)
+ },
+ hidden: {
+ guild: interaction.guild.id
}
- log(data);
- let out = ""
- deleted.reverse().forEach(message => {
- out += `${message.author.username}#${message.author.discriminator} (${message.author.id}) [${new Date(message.createdTimestamp).toISOString()}]\n`
- let lines = message.content.split("\n")
- lines.forEach(line => {out += `> ${line}\n`})
- out += `\n\n`
- })
- attachmentObject = {
- attachment: Buffer.from(out),
- name: `purge-${channel.id}-${Date.now()}.txt`,
- description: "Purge log"
- }
- } catch {}
- let m = await interaction.editReply({embeds: [new EmojiEmbed()
- .setEmoji(`CHANNEL.PURGE.GREEN`)
- .setTitle(`Purge`)
+ };
+ log(data);
+ let out = "";
+ deleted.reverse().forEach(message => {
+ out += `${message.author.username}#${message.author.discriminator} (${message.author.id}) [${new Date(message.createdTimestamp).toISOString()}]\n`;
+ const lines = message.content.split("\n");
+ lines.forEach(line => {out += `> ${line}\n`;});
+ out += "\n\n";
+ });
+ const attachmentObject = {
+ attachment: Buffer.from(out),
+ name: `purge-${channel.id}-${Date.now()}.txt`,
+ description: "Purge log"
+ };
+ const m = await interaction.editReply({embeds: [new EmojiEmbed()
+ .setEmoji("CHANNEL.PURGE.GREEN")
+ .setTitle("Purge")
.setDescription("Messages cleared")
.setStatus("Success")
], components: [new Discord.MessageActionRow().addComponents([
@@ -177,29 +174,29 @@
.setLabel("Download transcript")
.setStyle("SUCCESS")
.setEmoji(getEmojiByName("CONTROL.DOWNLOAD", "id"))
- ])]})
+ ])]});
let component;
try {
component = await (m as Discord.Message).awaitMessageComponent({filter: (m) => m.user.id === interaction.user.id, time: 300000});
- } catch {}
+ } catch { return; }
if (component && component.customId === "download") {
interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("CHANNEL.PURGE.GREEN")
- .setTitle(`Purge`)
+ .setTitle("Purge")
.setDescription("Uploaded")
.setStatus("Success")
- ], components: [], files: [attachmentObject]})
+ ], components: [], files: [attachmentObject]});
} else {
interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("CHANNEL.PURGE.GREEN")
- .setTitle(`Purge`)
+ .setTitle("Purge")
.setDescription("Messages cleared")
.setStatus("Success")
- ], components: []})
+ ], components: []});
}
- return
+ return;
} else {
- let confirmation = await new confirmationMessage(interaction)
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("CHANNEL.PURGE.RED")
.setTitle("Purge")
.setDescription(keyValueList({
@@ -208,69 +205,66 @@
"reason": `\n> ${interaction.options.getString("reason") ? interaction.options.getString("reason") : "*No reason provided*"}`
}))
.setColor("Danger")
- .send()
- if (confirmation.cancelled) return
+ .send();
+ if (confirmation.cancelled) return;
if (confirmation.success) {
let messages;
try {
if (!user) {
- let toDelete = await (interaction.channel as TextChannel).messages.fetch({limit: interaction.options.getInteger("amount")})
+ const toDelete = await (interaction.channel as TextChannel).messages.fetch({limit: interaction.options.getInteger("amount")});
messages = await (channel as TextChannel).bulkDelete(toDelete, true);
} else {
- let toDelete = (await (await (interaction.channel as TextChannel).messages.fetch({limit: 100}))
- .filter(m => m.author.id === user.id)).first(interaction.options.getInteger("amount"))
+ const toDelete = (await (await (interaction.channel as TextChannel).messages.fetch({limit: 100}))
+ .filter(m => m.author.id === user.id)).first(interaction.options.getInteger("amount"));
messages = await (channel as TextChannel).bulkDelete(toDelete, true);
}
} catch(e) {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("CHANNEL.PURGE.RED")
- .setTitle(`Purge`)
+ .setTitle("Purge")
.setDescription("Something went wrong and no messages were deleted")
.setStatus("Danger")
- ], components: []})
+ ], components: []});
}
if (user) {
- try { await client.database.history.create("purge", interaction.guild.id, user, interaction.options.getString("reason"), null, null, messages.size) } catch {}
+ await client.database.history.create("purge", interaction.guild.id, user, interaction.options.getString("reason"), null, null, messages.size);
}
- let attachmentObject;
- try {
- const { log, NucleusColors, entry, renderUser, renderChannel } = client.logger
- let data = {
- meta: {
- type: 'channelPurge',
- displayName: 'Channel Purged',
- calculateType: 'messageDelete',
- color: NucleusColors.red,
- emoji: "PUNISH.BAN.RED",
- timestamp: new Date().getTime()
- },
- list: {
- memberId: entry(interaction.user.id, `\`${interaction.user.id}\``),
- purgedBy: entry(interaction.user.id, renderUser(interaction.user)),
- channel: entry(interaction.channel.id, renderChannel(interaction.channel)),
- messagesCleared: entry(messages.size, messages.size),
- },
- hidden: {
- guild: interaction.guild.id
- }
+ const { log, NucleusColors, entry, renderUser, renderChannel } = client.logger;
+ const data = {
+ meta: {
+ type: "channelPurge",
+ displayName: "Channel Purged",
+ calculateType: "messageDelete",
+ color: NucleusColors.red,
+ emoji: "PUNISH.BAN.RED",
+ timestamp: new Date().getTime()
+ },
+ list: {
+ memberId: entry(interaction.user.id, `\`${interaction.user.id}\``),
+ purgedBy: entry(interaction.user.id, renderUser(interaction.user)),
+ channel: entry(interaction.channel.id, renderChannel(interaction.channel)),
+ messagesCleared: entry(messages.size, messages.size)
+ },
+ hidden: {
+ guild: interaction.guild.id
}
- log(data);
- let out = ""
- messages.reverse().forEach(message => {
- out += `${message.author.username}#${message.author.discriminator} (${message.author.id}) [${new Date(message.createdTimestamp).toISOString()}]\n`
- let lines = message.content.split("\n")
- lines.forEach(line => {out += `> ${line}\n`})
- out += `\n\n`
- })
- attachmentObject = {
- attachment: Buffer.from(out),
- name: `purge-${channel.id}-${Date.now()}.txt`,
- description: `Purge log`
- }
- } catch {}
- let m = await interaction.editReply({embeds: [new EmojiEmbed()
- .setEmoji(`CHANNEL.PURGE.GREEN`)
- .setTitle(`Purge`)
+ };
+ log(data);
+ let out = "";
+ messages.reverse().forEach(message => {
+ out += `${message.author.username}#${message.author.discriminator} (${message.author.id}) [${new Date(message.createdTimestamp).toISOString()}]\n`;
+ const lines = message.content.split("\n");
+ lines.forEach(line => {out += `> ${line}\n`;});
+ out += "\n\n";
+ });
+ const attachmentObject = {
+ attachment: Buffer.from(out),
+ name: `purge-${channel.id}-${Date.now()}.txt`,
+ description: "Purge log"
+ };
+ const m = await interaction.editReply({embeds: [new EmojiEmbed()
+ .setEmoji("CHANNEL.PURGE.GREEN")
+ .setTitle("Purge")
.setDescription("Messages cleared")
.setStatus("Success")
], components: [new Discord.MessageActionRow().addComponents([
@@ -279,48 +273,48 @@
.setLabel("Download transcript")
.setStyle("SUCCESS")
.setEmoji(getEmojiByName("CONTROL.DOWNLOAD", "id"))
- ])]})
+ ])]});
let component;
try {
component = await (m as Discord.Message).awaitMessageComponent({filter: (m) => m.user.id === interaction.user.id, time: 300000});
- } catch {}
+ } catch { return; }
if (component && component.customId === "download") {
interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("CHANNEL.PURGE.GREEN")
- .setTitle(`Purge`)
+ .setTitle("Purge")
.setDescription("Transcript uploaded above")
.setStatus("Success")
- ], components: [], files: [attachmentObject]})
+ ], components: [], files: [attachmentObject]});
} else {
interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("CHANNEL.PURGE.GREEN")
- .setTitle(`Purge`)
+ .setTitle("Purge")
.setDescription("Messages cleared")
.setStatus("Success")
- ], components: []})
+ ], components: []});
}
} else {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("CHANNEL.PURGE.GREEN")
- .setTitle(`Purge`)
+ .setTitle("Purge")
.setDescription("No changes were made")
.setStatus("Success")
- ], components: []})
+ ], components: []});
}
}
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as GuildMember)
- let me = (interaction.guild.me as GuildMember)
+ const member = (interaction.member as GuildMember);
+ const me = (interaction.guild.me as GuildMember);
// Check if nucleus has the manage_messages permission
if (! me.permissions.has("MANAGE_MESSAGES")) throw "I do not have the *Manage Messages* permission";
// Allow the owner to purge
- if (member.id === interaction.guild.ownerId) return true
+ 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";
// Allow purge
- return true
-}
+ return true;
+};
export { command, callback, check };
\ No newline at end of file
diff --git a/src/commands/mod/slowmode.ts b/src/commands/mod/slowmode.ts
index 6b33e12..951dc53 100644
--- a/src/commands/mod/slowmode.ts
+++ b/src/commands/mod/slowmode.ts
@@ -1,4 +1,4 @@
-import humanizeDuration from 'humanize-duration';
+import humanizeDuration from "humanize-duration";
import { CommandInteraction, GuildMember, TextChannel } from "discord.js";
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
@@ -9,64 +9,64 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("slowmode")
- .setDescription("Manages slowmode in a channel")
- .addStringOption(option => option.setName("time").setDescription("The delay between messages").setRequired(false).addChoices([
- ["Off", "0"],
- ["5 seconds", "5"], ["10 seconds", "10"], ["15 seconds", "15"], ["30 seconds", "30"],
- ["1 minute", "60"], ["2 minutes", "120"], ["5 minutes", "300"], ["10 minutes", "600"],
- ["15 minutes", "900"], ["30 minutes", "1800"],
- ["1 hour", "3600"], ["2 hours", "7200"], ["6 hours", "21600"]
- ]))
+ .setName("slowmode")
+ .setDescription("Manages slowmode in a channel")
+ .addStringOption(option => option.setName("time").setDescription("The delay between messages").setRequired(false).addChoices([
+ ["Off", "0"],
+ ["5 seconds", "5"], ["10 seconds", "10"], ["15 seconds", "15"], ["30 seconds", "30"],
+ ["1 minute", "60"], ["2 minutes", "120"], ["5 minutes", "300"], ["10 minutes", "600"],
+ ["15 minutes", "900"], ["30 minutes", "1800"],
+ ["1 hour", "3600"], ["2 hours", "7200"], ["6 hours", "21600"]
+ ]));
const callback = async (interaction: CommandInteraction): Promise<any> => {
let time = parseInt(interaction.options.getString("time") ?? "0");
- if (time === 0 && (interaction.channel as TextChannel).rateLimitPerUser === 0) { time = 10 }
- let confirmation = await new confirmationMessage(interaction)
+ if (time === 0 && (interaction.channel as TextChannel).rateLimitPerUser === 0) { time = 10; }
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("CHANNEL.SLOWMODE.OFF")
.setTitle("Slowmode")
.setDescription(keyValueList({
- "time": time ? humanizeDuration(time * 1000, { round: true }) : "No delay",
+ "time": time ? humanizeDuration(time * 1000, { round: true }) : "No delay"
})
- + `Are you sure you want to set the slowmode in this channel?`)
+ + "Are you sure you want to set the slowmode in this channel?")
.setColor("Danger")
- .send()
- if (confirmation.cancelled) return
+ .send();
+ if (confirmation.cancelled) return;
if (confirmation.success) {
try {
- (interaction.channel as TextChannel).setRateLimitPerUser(time)
+ (interaction.channel as TextChannel).setRateLimitPerUser(time);
} catch (e) {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("CHANNEL.SLOWMODE.OFF")
- .setTitle(`Slowmode`)
+ .setTitle("Slowmode")
.setDescription("Something went wrong while setting the slowmode")
.setStatus("Danger")
- ], components: []})
+ ], components: []});
}
await interaction.editReply({embeds: [new EmojiEmbed()
- .setEmoji(`CHANNEL.SLOWMODE.ON`)
- .setTitle(`Slowmode`)
+ .setEmoji("CHANNEL.SLOWMODE.ON")
+ .setTitle("Slowmode")
.setDescription("The channel slowmode was set successfully")
.setStatus("Success")
- ], components: []})
+ ], components: []});
} else {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("CHANNEL.SLOWMODE.ON")
- .setTitle(`Slowmode`)
+ .setTitle("Slowmode")
.setDescription("No changes were made")
.setStatus("Success")
- ], components: []})
+ ], components: []});
}
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as GuildMember)
+ 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";
// Check if the user has manage_channel permission
if (! member.permissions.has("MANAGE_CHANNELS")) throw "You do not have the *Manage Channels* permission";
// Allow slowmode
- return true
-}
+ return true;
+};
export { command, callback, check };
\ No newline at end of file
diff --git a/src/commands/mod/softban.ts b/src/commands/mod/softban.ts
index 43d03fd..88ba531 100644
--- a/src/commands/mod/softban.ts
+++ b/src/commands/mod/softban.ts
@@ -9,43 +9,43 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("softban")
- .setDescription("Kicks a user and deletes their messages")
- .addUserOption(option => option.setName("user").setDescription("The user to softban").setRequired(true))
- .addIntegerOption(option => option.setName("delete").setDescription("The days of messages to delete | Default: 0").setMinValue(0).setMaxValue(7).setRequired(false))
+ .setName("softban")
+ .setDescription("Kicks a user and deletes their messages")
+ .addUserOption(option => option.setName("user").setDescription("The user to softban").setRequired(true))
+ .addIntegerOption(option => option.setName("delete").setDescription("The days of messages to delete | Default: 0").setMinValue(0).setMaxValue(7).setRequired(false));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- const { renderUser } = client.logger
+ const { renderUser } = client.logger;
// TODO:[Modals] Replace this with a modal
let reason = null;
let notify = true;
let confirmation;
while (true) {
- let confirmation = await new confirmationMessage(interaction)
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("PUNISH.BAN.RED")
.setTitle("Softban")
.setDescription(keyValueList({
"user": renderUser(interaction.options.getUser("user")),
"reason": reason ? ("\n> " + ((reason ?? "").replaceAll("\n", "\n> "))) : "*No reason provided*"
})
- + `The user **will${notify ? '' : ' not'}** be notified\n`
+ + `The user **will${notify ? "" : " not"}** be notified\n`
+ `${addPlural(interaction.options.getInteger("delete") ? interaction.options.getInteger("delete") : 0, "day")} of messages will be deleted\n\n`
+ `Are you sure you want to softban <@!${(interaction.options.getMember("user") as GuildMember).id}>?`)
.setColor("Danger")
.addCustomBoolean("notify", "Notify user", false, null, null, "ICONS.NOTIFY." + (notify ? "ON" : "OFF" ), notify)
.addReasonButton(reason ?? "")
- .send(reason !== null)
- reason = reason ?? ""
- if (confirmation.cancelled) return
- if (confirmation.success) break
- if (confirmation.newReason) reason = confirmation.newReason
+ .send(reason !== null);
+ reason = reason ?? "";
+ if (confirmation.cancelled) return;
+ if (confirmation.success) break;
+ if (confirmation.newReason) reason = confirmation.newReason;
if (confirmation.components) {
- notify = confirmation.components.notify.active
+ notify = confirmation.components.notify.active;
}
}
if (confirmation.success) {
let dmd = false;
- let config = await client.database.guilds.read(interaction.guild.id);
+ const config = await client.database.guilds.read(interaction.guild.id);
try {
if (notify) {
await (interaction.options.getMember("user") as GuildMember).send({
@@ -61,11 +61,11 @@
.setLabel(config.moderation.ban.text)
.setURL(config.moderation.ban.link)
] : [])]
- })
- dmd = true
+ });
+ dmd = true;
}
- } catch {}
- let member = (interaction.options.getMember("user") as GuildMember)
+ } catch { dmd = false;}
+ const member = (interaction.options.getMember("user") as GuildMember);
try {
await member.ban({
days: Number(interaction.options.getInteger("delete") ?? 0),
@@ -75,53 +75,53 @@
} catch {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("PUNISH.BAN.RED")
- .setTitle(`Softban`)
+ .setTitle("Softban")
.setDescription("Something went wrong and the user was not softbanned")
.setStatus("Danger")
- ], components: []})
+ ], components: []});
}
- try { await client.database.history.create("softban", interaction.guild.id, member.user, reason) } catch {}
- let failed = (dmd === false && notify)
+ await client.database.history.create("softban", interaction.guild.id, member.user, reason);
+ const failed = (dmd === false && notify);
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji(`PUNISH.BAN.${failed ? "YELLOW" : "GREEN"}`)
- .setTitle(`Softban`)
+ .setTitle("Softban")
.setDescription("The member was softbanned" + (failed ? ", but could not be notified" : ""))
.setStatus(failed ? "Warning" : "Success")
- ], components: []})
+ ], components: []});
} else {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("PUNISH.BAN.GREEN")
- .setTitle(`Softban`)
+ .setTitle("Softban")
.setDescription("No changes were made")
.setStatus("Success")
- ], components: []})
+ ], components: []});
}
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as GuildMember)
- let me = (interaction.guild.me as GuildMember)
- let apply = (interaction.options.getMember("user") as GuildMember)
- if (member === null || me === null || apply === null) throw "That member is not in the server"
- let memberPos = member.roles ? member.roles.highest.position : 0
- let mePos = me.roles ? me.roles.highest.position : 0
- let applyPos = apply.roles ? apply.roles.highest.position : 0
+ const member = (interaction.member as GuildMember);
+ const me = (interaction.guild.me as GuildMember);
+ const apply = (interaction.options.getMember("user") as GuildMember);
+ if (member === null || me === null || apply === null) throw "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 "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 "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";
// Do not allow softbanning Nucleus
- if (member.id === me.id) throw "I cannot softban myself"
+ if (member.id === me.id) throw "I cannot softban myself";
// Allow the owner to softban anyone
- if (member.id === interaction.guild.ownerId) return true
+ 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";
// 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 "You do not have a role higher than that member";
// Allow softban
- return true
-}
+ return true;
+};
export { command, callback, check };
\ No newline at end of file
diff --git a/src/commands/mod/unban.ts b/src/commands/mod/unban.ts
index 2605d28..faf1f08 100644
--- a/src/commands/mod/unban.ts
+++ b/src/commands/mod/unban.ts
@@ -8,46 +8,46 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("unban")
- .setDescription("Unbans a user")
- .addStringOption(option => option.setName("user").setDescription("The user to unban (Username or ID)").setRequired(true))
+ .setName("unban")
+ .setDescription("Unbans a user")
+ .addStringOption(option => option.setName("user").setDescription("The user to unban (Username or ID)").setRequired(true));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- let bans = await interaction.guild.bans.fetch()
- let user = interaction.options.getString("user")
- let resolved = bans.find(ban => ban.user.id === user)
- if (!resolved) resolved = bans.find(ban => ban.user.username.toLowerCase() === user.toLowerCase())
- if (!resolved) resolved = bans.find(ban => ban.user.tag.toLowerCase() === user.toLowerCase())
+ const bans = await interaction.guild.bans.fetch();
+ const user = interaction.options.getString("user");
+ let resolved = bans.find(ban => ban.user.id === user);
+ if (!resolved) resolved = bans.find(ban => ban.user.username.toLowerCase() === user.toLowerCase());
+ if (!resolved) resolved = bans.find(ban => ban.user.tag.toLowerCase() === user.toLowerCase());
if (!resolved) {
return interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Unban")
.setDescription(`Could not find any user called \`${user}\``)
.setEmoji("PUNISH.UNBAN.RED")
.setStatus("Danger")
- ], ephemeral: true})
+ ], ephemeral: true});
}
// TODO:[Modals] Replace this with a modal
- let confirmation = await new confirmationMessage(interaction)
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("PUNISH.UNBAN.RED")
.setTitle("Unban")
.setDescription(keyValueList({
- "user": `${resolved.user.username} [<@${resolved.user.id}>]`,
+ "user": `${resolved.user.username} [<@${resolved.user.id}>]`
})
+ `Are you sure you want to unban <@${resolved.user.id}>?`)
.setColor("Danger")
- .send()
- if (confirmation.cancelled) return
+ .send();
+ if (confirmation.cancelled) return;
if (confirmation.success) {
try {
await interaction.guild.members.unban(resolved.user as User, "Unban");
- let member = (resolved.user as User)
- try { await client.database.history.create("unban", interaction.guild.id, member, interaction.user) } catch {}
- const { log, NucleusColors, entry, renderUser, renderDelta } = client.logger
- let data = {
+ const member = (resolved.user as User);
+ await client.database.history.create("unban", interaction.guild.id, member, interaction.user);
+ const { log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
+ const data = {
meta: {
- type: 'memberUnban',
- displayName: 'Member Unbanned',
- calculateType: 'guildMemberPunish',
+ type: "memberUnban",
+ displayName: "Member Unbanned",
+ calculateType: "guildMemberPunish",
color: NucleusColors.green,
emoji: "PUNISH.BAN.GREEN",
timestamp: new Date().getTime()
@@ -57,48 +57,48 @@
name: entry(member.id, renderUser(member)),
unbanned: entry(new Date().getTime(), renderDelta(new Date().getTime())),
unbannedBy: entry(interaction.user.id, renderUser(interaction.user)),
- accountCreated: entry(member.createdAt, renderDelta(member.createdAt)),
+ accountCreated: entry(member.createdAt, renderDelta(member.createdAt))
},
hidden: {
guild: interaction.guild.id
}
- }
+ };
log(data);
} catch {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("PUNISH.UNBAN.RED")
- .setTitle(`Unban`)
+ .setTitle("Unban")
.setDescription("Something went wrong and the user was not unbanned")
.setStatus("Danger")
- ], components: []})
+ ], components: []});
}
await interaction.editReply({embeds: [new EmojiEmbed()
- .setEmoji(`PUNISH.UNBAN.GREEN`)
- .setTitle(`Unban`)
+ .setEmoji("PUNISH.UNBAN.GREEN")
+ .setTitle("Unban")
.setDescription("The member was unbanned")
.setStatus("Success")
- ], components: []})
+ ], components: []});
} else {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("PUNISH.UNBAN.GREEN")
- .setTitle(`Unban`)
+ .setTitle("Unban")
.setDescription("No changes were made")
.setStatus("Success")
- ], components: []})
+ ], components: []});
}
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as GuildMember)
- let me = (interaction.guild.me as GuildMember)
+ const member = (interaction.member as GuildMember);
+ const me = (interaction.guild.me as GuildMember);
// Check if Nucleus can unban members
if (! me.permissions.has("BAN_MEMBERS")) throw "I do not have the *Ban Members* permission";
// Allow the owner to unban anyone
- if (member.id === interaction.guild.ownerId) return true
+ 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";
// Allow unban
- return true
-}
+ return true;
+};
export { command, callback, check };
\ No newline at end of file
diff --git a/src/commands/mod/unmute.ts b/src/commands/mod/unmute.ts
index 6451837..e00c16d 100644
--- a/src/commands/mod/unmute.ts
+++ b/src/commands/mod/unmute.ts
@@ -8,12 +8,12 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("unmute")
- .setDescription("Unmutes a user")
- .addUserOption(option => option.setName("user").setDescription("The user to unmute").setRequired(true))
+ .setName("unmute")
+ .setDescription("Unmutes a user")
+ .addUserOption(option => option.setName("user").setDescription("The user to unmute").setRequired(true));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- const { log, NucleusColors, renderUser, entry, renderDelta } = client.logger
+ const { log, NucleusColors, renderUser, entry, renderDelta } = client.logger;
// TODO:[Modals] Replace this with a modal
let reason = null;
let notify = false;
@@ -26,20 +26,20 @@
"user": renderUser(interaction.options.getUser("user")),
"reason": `\n> ${reason ? reason : "*No reason provided*"}`
})
- + `The user **will${notify ? '' : ' not'}** be notified\n\n`
+ + `The user **will${notify ? "" : " not"}** be notified\n\n`
+ `Are you sure you want to unmute <@!${(interaction.options.getMember("user") as GuildMember).id}>?`)
.setColor("Danger")
.addReasonButton(reason ?? "")
- .send(reason !== null)
- if (confirmation.success) break
- if (confirmation.newReason) reason = confirmation.newReason
+ .send(reason !== null);
+ if (confirmation.success) break;
+ if (confirmation.newReason) reason = confirmation.newReason;
if (confirmation.components) {
- notify = confirmation.components.notify.active
+ notify = confirmation.components.notify.active;
}
}
- if (confirmation.cancelled) return
+ if (confirmation.cancelled) return;
if (confirmation.success) {
- let dmd = false
+ let dmd = false;
let dm;
try {
if (notify) {
@@ -51,29 +51,29 @@
(reason ? ` for:\n> ${reason}` : " with no reason provided."))
.setStatus("Success")
]
- })
- dmd = true
+ });
+ dmd = true;
}
- } catch {}
- let member = (interaction.options.getMember("user") as GuildMember)
+ } catch { dmd = false; }
+ 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: [new EmojiEmbed()
.setEmoji("PUNISH.MUTE.RED")
- .setTitle(`Unmute`)
+ .setTitle("Unmute")
.setDescription("Something went wrong and the user was not unmuted")
.setStatus("Danger")
- ], components: []})
- if (dmd) await dm.delete()
- return
+ ], components: []});
+ if (dmd) await dm.delete();
+ return;
}
- try { await client.database.history.create("unmute", interaction.guild.id, (interaction.options.getMember("user") as GuildMember).user, interaction.user, reason) } catch {}
- let data = {
+ await client.database.history.create("unmute", interaction.guild.id, (interaction.options.getMember("user") as GuildMember).user, interaction.user, reason);
+ const data = {
meta: {
- type: 'memberUnmute',
- displayName: 'Unmuted',
- calculateType: 'guildMemberPunish',
+ type: "memberUnmute",
+ displayName: "Unmuted",
+ calculateType: "guildMemberPunish",
color: NucleusColors.green,
emoji: "PUNISH.MUTE.GREEN",
timestamp: new Date().getTime()
@@ -82,52 +82,52 @@
memberId: entry(member.user.id, `\`${member.user.id}\``),
name: entry(member.user.id, renderUser(member.user)),
unmuted: entry(new Date().getTime(), renderDelta(new Date().getTime())),
- unmutedBy: entry(interaction.user.id, renderUser(interaction.user)),
+ unmutedBy: entry(interaction.user.id, renderUser(interaction.user))
},
hidden: {
guild: interaction.guild.id
}
- }
+ };
log(data);
- let failed = (dmd === false && notify)
+ const failed = (dmd === false && notify);
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji(`PUNISH.MUTE.${failed ? "YELLOW" : "GREEN"}`)
- .setTitle(`Unmute`)
+ .setTitle("Unmute")
.setDescription("The member was unmuted" + (failed ? ", but could not be notified" : ""))
.setStatus(failed ? "Warning" : "Success")
- ], components: []})
+ ], components: []});
} else {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("PUNISH.MUTE.GREEN")
- .setTitle(`Unmute`)
+ .setTitle("Unmute")
.setDescription("No changes were made")
.setStatus("Success")
- ], components: []})
+ ], components: []});
}
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as GuildMember)
- let me = (interaction.guild.me as GuildMember)
- let apply = (interaction.options.getMember("user") as GuildMember)
- if (member === null || me === null || apply === null) throw "That member is not in the server"
- let memberPos = member.roles ? member.roles.highest.position : 0
- let mePos = me.roles ? me.roles.highest.position : 0
- let applyPos = apply.roles ? apply.roles.highest.position : 0
+ const member = (interaction.member as GuildMember);
+ const me = (interaction.guild.me as GuildMember);
+ const apply = (interaction.options.getMember("user") as GuildMember);
+ if (member === null || me === null || apply === null) throw "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 "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 "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";
// Allow the owner to unmute anyone
- if (member.id === interaction.guild.ownerId) return true
+ 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";
// 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 "You do not have a role higher than that member";
// Allow unmute
- return true
-}
+ return true;
+};
export { command, callback, check };
\ No newline at end of file
diff --git a/src/commands/mod/viewas.ts b/src/commands/mod/viewas.ts
index 2f5cacc..a5bf5ea 100644
--- a/src/commands/mod/viewas.ts
+++ b/src/commands/mod/viewas.ts
@@ -7,40 +7,40 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("viewas")
- .setDescription("View the server as a specific member")
- .addUserOption(option => option.setName("member").setDescription("The member to view as").setRequired(true))
+ .setName("viewas")
+ .setDescription("View the server as a specific member")
+ .addUserOption(option => option.setName("member").setDescription("The member to view as").setRequired(true));
const callback = async (interaction: CommandInteraction): Promise<any> => {
let channels = [];
let m;
interaction.guild.channels.cache.forEach(channel => {
- if (!channel.parent && channel.type !== "GUILD_CATEGORY") channels.push(channel)
- })
- channels = [channels]
+ if (!channel.parent && channel.type !== "GUILD_CATEGORY") channels.push(channel);
+ });
+ channels = [channels];
channels = channels.concat(interaction.guild.channels.cache
.filter(c => c.type === "GUILD_CATEGORY")
.map(c => (c as CategoryChannel).children.map(c => c))
- )
- let autoSortBelow = ["GUILD_VOICE", "GUILD_STAGE_VOICE"]
+ );
+ const autoSortBelow = ["GUILD_VOICE", "GUILD_STAGE_VOICE"];
channels = channels.map(c => c.sort((a, b) => {
- if (autoSortBelow.includes(a.type) && autoSortBelow.includes(b.type)) return a.position - b.position
- if (autoSortBelow.includes(a.type)) return 1
- if (autoSortBelow.includes(b.type)) return -1
- return a.position - b.position
- }))
+ if (autoSortBelow.includes(a.type) && autoSortBelow.includes(b.type)) return a.position - b.position;
+ if (autoSortBelow.includes(a.type)) return 1;
+ if (autoSortBelow.includes(b.type)) return -1;
+ return a.position - b.position;
+ }));
// Sort all arrays by the position of the first channels parent position
channels = channels.sort((a, b) => {
- if (!a[0].parent) return -1
- if (!b[0].parent) return 1
- return a[0].parent.position - b[0].parent.position
- })
- let member = interaction.options.getMember("member") as Discord.GuildMember
+ if (!a[0].parent) return -1;
+ if (!b[0].parent) return 1;
+ return a[0].parent.position - b[0].parent.position;
+ });
+ const member = interaction.options.getMember("member") as Discord.GuildMember;
m = await interaction.reply({embeds: [new EmojiEmbed()
.setEmoji("MEMBER.JOIN")
.setTitle("Viewing as " + member.displayName)
.setStatus("Success")
- ], ephemeral: true, fetchReply: true})
+ ], ephemeral: true, fetchReply: true});
let page = 0;
while (true) {
m = await interaction.editReply({embeds: [new EmojiEmbed()
@@ -50,17 +50,17 @@
.setDescription(
`**${channels[page][0].parent ? channels[page][0].parent.name : "Uncategorised"}**` + "\n" +
channels[page].map(c => {
- let channelType = c.type
- if (interaction.guild.rulesChannelId === c.id) channelType = "RULES"
- else if ("nsfw" in c && c.nsfw) channelType += "_NSFW"
+ let channelType = c.type;
+ if (interaction.guild.rulesChannelId === c.id) channelType = "RULES";
+ else if ("nsfw" in c && c.nsfw) channelType += "_NSFW";
return c.permissionsFor(member).has("VIEW_CHANNEL") ? (
`${getEmojiByName("ICONS.CHANNEL." + channelType)} ${c.name}\n` + (() => {
if ("threads" in c && c.threads.cache.size > 0) {
return c.threads.cache.map(t => ` ${
getEmojiByName("ICONS.CHANNEL.THREAD_PIPE") + " " +
- getEmojiByName("ICONS.CHANNEL.THREAD_CHANNEL")} ${t.name}`).join("\n") + "\n"
- }return ""
- })()) : ""
+ getEmojiByName("ICONS.CHANNEL.THREAD_CHANNEL")} ${t.name}`).join("\n") + "\n";
+ }return "";
+ })()) : "";
}).join("") + "\n" + pageIndicator(channels.length, page)
)
], components: [
@@ -83,23 +83,23 @@
.setStyle("PRIMARY")
.setCustomId("next")
])
- ]})
+ ]});
let i;
try {
i = await m.awaitMessageComponent({ time: 300000 });
- } catch (e) { return }
- i.deferUpdate()
+ } catch (e) { return; }
+ i.deferUpdate();
if (i.customId === "next") { page++; }
else if (i.customId === "previous") { page--; }
else if (i.customId === "select") { page = parseInt(i.values[0]); }
}
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as GuildMember)
+ const member = (interaction.member as GuildMember);
if (! member.permissions.has("MANAGE_ROLES")) throw "You do not have the *Manage Roles* permission";
- return true
-}
+ return true;
+};
export { command, callback, check };
\ No newline at end of file
diff --git a/src/commands/mod/warn.ts b/src/commands/mod/warn.ts
index b007b29..0648f66 100644
--- a/src/commands/mod/warn.ts
+++ b/src/commands/mod/warn.ts
@@ -5,16 +5,16 @@
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import keyValueList from "../../utils/generateKeyValueList.js";
import { create, areTicketsEnabled } from "../../actions/createModActionTicket.js";
-import client from "../../utils/client.js"
+import client from "../../utils/client.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("warn")
- .setDescription("Warns a user")
- .addUserOption(option => option.setName("user").setDescription("The user to warn").setRequired(true))
+ .setName("warn")
+ .setDescription("Warns a user")
+ .addUserOption(option => option.setName("user").setDescription("The user to warn").setRequired(true));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- const { log, NucleusColors, renderUser, entry } = client.logger
+ const { log, NucleusColors, renderUser, entry } = client.logger;
// TODO:[Modals] Replace this with a modal
let reason = null;
let notify = true;
@@ -28,7 +28,7 @@
"user": renderUser(interaction.options.getUser("user")),
"reason": reason ? ("\n> " + ((reason ?? "").replaceAll("\n", "\n> "))) : "*No reason provided*"
})
- + `The user **will${notify ? '' : ' not'}** be notified\n\n`
+ + `The user **will${notify ? "" : " not"}** be notified\n\n`
+ `Are you sure you want to warn <@!${(interaction.options.getMember("user") as GuildMember).id}>?`)
.setColor("Danger")
.addCustomBoolean(
@@ -37,28 +37,28 @@
"An appeal ticket will be created when Confirm is clicked", "CONTROL.TICKET", createAppealTicket)
.addCustomBoolean("notify", "Notify user", false, null, null, "ICONS.NOTIFY." + (notify ? "ON" : "OFF" ), notify)
.addReasonButton(reason ?? "")
- .send(reason !== null)
- reason = reason ?? ""
- if (confirmation.cancelled) return
- if (confirmation.success) break
- if (confirmation.newReason) reason = confirmation.newReason
+ .send(reason !== null);
+ reason = reason ?? "";
+ if (confirmation.cancelled) return;
+ if (confirmation.success) break;
+ if (confirmation.newReason) reason = confirmation.newReason;
if (confirmation.components) {
- notify = confirmation.components.notify.active
- createAppealTicket = confirmation.components.appeal.active
+ notify = confirmation.components.notify.active;
+ createAppealTicket = confirmation.components.appeal.active;
}
}
if (confirmation.success) {
- let dmd = false
+ let dmd = false;
try {
if (notify) {
- const config = await client.database.guilds.read(interaction.guild.id)
+ const config = await client.database.guilds.read(interaction.guild.id);
await (interaction.options.getMember("user") as GuildMember).send({
embeds: [new EmojiEmbed()
.setEmoji("PUNISH.WARN.RED")
.setTitle("Warned")
.setDescription(`You have been warned in ${interaction.guild.name}` +
(reason ? ` for:\n> ${reason}` : ".") + "\n\n" +
- (confirmation.components.appeal.response ? `You can appeal this here ticket: <#${confirmation.components.appeal.response}>` : ``))
+ (confirmation.components.appeal.response ? `You can appeal this here ticket: <#${confirmation.components.appeal.response}>` : ""))
.setStatus("Danger")
.setFooter({
text: config.moderation.warn.text ? "The button below is set by the server admins. Do not enter any passwords or other account details on the linked site." : "",
@@ -70,17 +70,17 @@
.setLabel(config.moderation.warn.text)
.setURL(config.moderation.warn.link)
])] : []
- })
- dmd = true
+ });
+ dmd = true;
}
- } catch {}
- let data = {
+ } catch { dmd = false; }
+ const data = {
meta:{
- type: 'memberWarn',
- displayName: 'Member warned',
- calculateType: 'guildMemberPunish',
+ type: "memberWarn",
+ displayName: "Member warned",
+ calculateType: "guildMemberPunish",
color: NucleusColors.yellow,
- emoji: 'PUNISH.WARN.YELLOW',
+ emoji: "PUNISH.WARN.YELLOW",
timestamp: new Date().getTime()
},
list: {
@@ -91,27 +91,27 @@
hidden: {
guild: interaction.guild.id
}
- }
- try { await client.database.history.create(
+ };
+ await client.database.history.create(
"warn", interaction.guild.id,
(interaction.options.getMember("user") as GuildMember).user,
interaction.user, reason
- )} catch {}
+ );
log(data);
- let failed = (dmd === false && notify)
+ const failed = (dmd === false && notify);
if (!failed) {
await interaction.editReply({embeds: [new EmojiEmbed()
- .setEmoji(`PUNISH.WARN.GREEN`)
- .setTitle(`Warn`)
- .setDescription("The user was warned" + (confirmation.components.appeal.response ? ` and an appeal ticket was opened in <#${confirmation.components.appeal.response}>` : ``))
+ .setEmoji("PUNISH.WARN.GREEN")
+ .setTitle("Warn")
+ .setDescription("The user was warned" + (confirmation.components.appeal.response ? ` and an appeal ticket was opened in <#${confirmation.components.appeal.response}>` : ""))
.setStatus("Success")
- ], components: []})
+ ], components: []});
} else {
- let canSeeChannel = (interaction.options.getMember("user") as GuildMember).permissionsIn(interaction.channel as Discord.TextChannel).has("VIEW_CHANNEL")
- let m = await interaction.editReply({
+ const canSeeChannel = (interaction.options.getMember("user") as GuildMember).permissionsIn(interaction.channel as Discord.TextChannel).has("VIEW_CHANNEL");
+ const m = await interaction.editReply({
embeds: [new EmojiEmbed()
- .setEmoji(`PUNISH.WARN.RED`)
- .setTitle(`Warn`)
+ .setEmoji("PUNISH.WARN.RED")
+ .setTitle("Warn")
.setDescription("The user's DMs are not open\n\nWhat would you like to do?")
.setStatus("Danger")
], components: [
@@ -131,89 +131,89 @@
.setStyle(canSeeChannel ? "SECONDARY" : "PRIMARY")
])
]
- })
+ });
let component;
try {
component = await (m as Discord.Message).awaitMessageComponent({filter: (m) => m.user.id === interaction.user.id, time: 300000});
} catch (e) {
return await interaction.editReply({embeds: [new EmojiEmbed()
- .setEmoji(`PUNISH.WARN.GREEN`)
- .setTitle(`Warn`)
+ .setEmoji("PUNISH.WARN.GREEN")
+ .setTitle("Warn")
.setDescription("No changes were made")
.setStatus("Success")
- ], components: []})
+ ], components: []});
}
if ( component.customId === "here" ) {
await interaction.channel.send({
embeds: [new EmojiEmbed()
- .setEmoji(`PUNISH.WARN.RED`)
- .setTitle(`Warn`)
- .setDescription(`You have been warned` +
+ .setEmoji("PUNISH.WARN.RED")
+ .setTitle("Warn")
+ .setDescription("You have been warned" +
(reason ? ` for:\n> ${reason}` : "."))
.setStatus("Danger")
],
content: `<@!${(interaction.options.getMember("user") as GuildMember).id}>`,
allowedMentions: {users: [(interaction.options.getMember("user") as GuildMember).id]}
- })
+ });
return await interaction.editReply({embeds: [new EmojiEmbed()
- .setEmoji(`PUNISH.WARN.GREEN`)
- .setTitle(`Warn`)
- .setDescription("The user was warned" + (confirmation.response ? ` and an appeal ticket was opened in <#${confirmation.response}>` : ``))
+ .setEmoji("PUNISH.WARN.GREEN")
+ .setTitle("Warn")
+ .setDescription("The user was warned" + (confirmation.response ? ` and an appeal ticket was opened in <#${confirmation.response}>` : ""))
.setStatus("Success")
- ], components: []})
+ ], components: []});
} else if (component.customId === "log") {
await interaction.editReply({embeds: [new EmojiEmbed()
- .setEmoji(`PUNISH.WARN.GREEN`)
- .setTitle(`Warn`)
+ .setEmoji("PUNISH.WARN.GREEN")
+ .setTitle("Warn")
.setDescription("The warn was logged")
.setStatus("Success")
- ], components: []})
+ ], components: []});
} else if (component.customId === "ticket") {
- let ticketChannel = await create(interaction.guild, interaction.options.getUser("user"), interaction.user, reason, "Warn Notification")
+ const ticketChannel = await create(interaction.guild, interaction.options.getUser("user"), interaction.user, reason, "Warn Notification");
if (ticketChannel === null) {
return await interaction.editReply({embeds: [new EmojiEmbed()
- .setEmoji(`PUNISH.WARN.RED`)
- .setTitle(`Warn`)
+ .setEmoji("PUNISH.WARN.RED")
+ .setTitle("Warn")
.setDescription("A ticket could not be created")
.setStatus("Danger")
- ], components: []})
+ ], components: []});
}
await interaction.editReply({embeds: [new EmojiEmbed()
- .setEmoji(`PUNISH.WARN.GREEN`)
- .setTitle(`Warn`)
+ .setEmoji("PUNISH.WARN.GREEN")
+ .setTitle("Warn")
.setDescription(`A ticket was created in <#${ticketChannel}>`)
.setStatus("Success")
- ], components: []})
+ ], components: []});
}
}
} else {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("PUNISH.WARN.GREEN")
- .setTitle(`Warn`)
+ .setTitle("Warn")
.setDescription("No changes were made")
.setStatus("Success")
- ], components: []})
+ ], components: []});
}
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as GuildMember)
- let me = (interaction.guild.me as GuildMember)
- let apply = (interaction.options.getMember("user") as GuildMember)
- if (member === null || me === null || apply === null) throw "That member is not in the server"
- let memberPos = member.roles ? member.roles.highest.position : 0
- let mePos = me.roles ? me.roles.highest.position : 0
- let applyPos = apply.roles ? apply.roles.highest.position : 0
+ const member = (interaction.member as GuildMember);
+ const me = (interaction.guild.me as GuildMember);
+ const apply = (interaction.options.getMember("user") as GuildMember);
+ if (member === null || me === null || apply === null) throw "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 warning bots
- if (member.user.bot) throw "I cannot warn bots"
+ if (member.user.bot) throw "I cannot warn bots";
// Allow the owner to warn anyone
- if (member.id === interaction.guild.ownerId) return true
+ 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";
// 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 "You do not have a role higher than that member";
// Allow warn
- return true
-}
+ return true;
+};
export { command, callback, check };
\ No newline at end of file
diff --git a/src/commands/nucleus/guide.ts b/src/commands/nucleus/guide.ts
index 5f2cde2..507730b 100644
--- a/src/commands/nucleus/guide.ts
+++ b/src/commands/nucleus/guide.ts
@@ -7,17 +7,17 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("guide")
- .setDescription("Shows the welcome guide for the bot")
+ .setName("guide")
+ .setDescription("Shows the welcome guide for the bot");
const callback = async (interaction) => {
- guide(interaction.guild, interaction)
-}
+ guide(interaction.guild, interaction);
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- return true
-}
+ return true;
+};
export { command };
export { callback };
diff --git a/src/commands/nucleus/invite.ts b/src/commands/nucleus/invite.ts
index 96e1449..5a1ea59 100644
--- a/src/commands/nucleus/invite.ts
+++ b/src/commands/nucleus/invite.ts
@@ -2,12 +2,12 @@
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
-import client from "../../utils/client.js"
+import client from "../../utils/client.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("invite")
- .setDescription("Invites Nucleus to your server")
+ .setName("invite")
+ .setDescription("Invites Nucleus to your server");
const callback = async (interaction: CommandInteraction): Promise<any> => {
interaction.reply({embeds: [new EmojiEmbed()
@@ -20,11 +20,11 @@
.setStyle("LINK")
.setURL(`https://discord.com/api/oauth2/authorize?client_id=${client.user.id}&permissions=295157886134&scope=bot%20applications.commands`)
])], ephemeral: true});
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/nucleus/ping.ts b/src/commands/nucleus/ping.ts
index 6353843..c153e19 100644
--- a/src/commands/nucleus/ping.ts
+++ b/src/commands/nucleus/ping.ts
@@ -1,21 +1,21 @@
-import { LoadingEmbed } from './../../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "./../../utils/defaultEmbeds.js";
import { CommandInteraction } from "discord.js";
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import { WrappedCheck } from "jshaiku";
-import client from "../../utils/client.js"
+import client from "../../utils/client.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("ping")
- .setDescription("Gets the bot's ping time")
+ .setName("ping")
+ .setDescription("Gets the bot's ping time");
const callback = async (interaction: CommandInteraction): Promise<any> => {
// WEBSOCKET | Nucleus -> Discord
// EDITING | Nucleus -> discord -> nucleus | edit time / 2
- let initial = new Date().getTime();
+ const initial = new Date().getTime();
await interaction.reply({embeds: LoadingEmbed, ephemeral: true});
- let ping = new Date().getTime() - initial;
+ const ping = new Date().getTime() - initial;
interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Ping")
.setDescription(
@@ -25,12 +25,12 @@
)
.setEmoji("CHANNEL.SLOWMODE.OFF")
.setStatus("Danger")
- ]})
-}
+ ]});
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/nucleus/premium.ts b/src/commands/nucleus/premium.ts
index 9d273b9..c8c0f76 100644
--- a/src/commands/nucleus/premium.ts
+++ b/src/commands/nucleus/premium.ts
@@ -5,8 +5,8 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("premium")
- .setDescription("Information about Nucleus Premium")
+ .setName("premium")
+ .setDescription("Information about Nucleus Premium");
const callback = async (interaction: CommandInteraction): Promise<any> => {
interaction.reply({embeds: [new EmojiEmbed()
@@ -20,11 +20,11 @@
.setEmoji("NUCLEUS.LOGO")
.setStatus("Danger")
], ephemeral: true});
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/nucleus/stats.ts b/src/commands/nucleus/stats.ts
index beea94b..98b87be 100644
--- a/src/commands/nucleus/stats.ts
+++ b/src/commands/nucleus/stats.ts
@@ -2,12 +2,12 @@
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
-import client from "../../utils/client.js"
+import client from "../../utils/client.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("stats")
- .setDescription("Gets the bot's stats")
+ .setName("stats")
+ .setDescription("Gets the bot's stats");
const callback = async (interaction: CommandInteraction): Promise<any> => {
interaction.reply({
@@ -22,11 +22,11 @@
], ephemeral: true
});
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/nucleus/suggest.ts b/src/commands/nucleus/suggest.ts
index 0c596ff..238e7d5 100644
--- a/src/commands/nucleus/suggest.ts
+++ b/src/commands/nucleus/suggest.ts
@@ -3,55 +3,55 @@
import { WrappedCheck } from "jshaiku";
import confirmationMessage from "../../utils/confirmationMessage.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
-import client from "../../utils/client.js"
+import client from "../../utils/client.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("suggest")
- .setDescription("Sends a suggestion to the developers")
- .addStringOption(option => option.setName("suggestion").setDescription("The suggestion to send").setRequired(true))
+ .setName("suggest")
+ .setDescription("Sends a suggestion to the developers")
+ .addStringOption(option => option.setName("suggestion").setDescription("The suggestion to send").setRequired(true));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- const { renderUser } = client.logger
- let suggestion = interaction.options.getString("suggestion");
- let confirmation = await new confirmationMessage(interaction)
+ const { renderUser } = client.logger;
+ const suggestion = interaction.options.getString("suggestion");
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("ICONS.OPP.ADD")
.setTitle("Suggest")
.setDescription(`**Suggestion:**\n> ${suggestion}\n`
- + `Your username and ID will also be sent with your suggestion.\n\nAre you sure you want to send this suggestion?`)
+ + "Your username and ID will also be sent with your suggestion.\n\nAre you sure you want to send this suggestion?")
.setColor("Danger")
.setInverted(true)
- .send()
- if (confirmation.cancelled) return
+ .send();
+ if (confirmation.cancelled) return;
if (confirmation.success) {
- await (client.channels.cache.get('955161206459600976') as Discord.TextChannel).send({
+ await (client.channels.cache.get("955161206459600976") as Discord.TextChannel).send({
embeds: [
new EmojiEmbed()
- .setTitle(`Suggestion`)
+ .setTitle("Suggestion")
.setDescription(`**From:** ${renderUser(interaction.member.user)}\n**Suggestion:**\n> ${suggestion}`)
.setStatus("Danger")
.setEmoji("NUCLEUS.LOGO")
]
- })
+ });
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("ICONS.ADD")
- .setTitle(`Suggest`)
+ .setTitle("Suggest")
.setDescription("Your suggestion was sent successfully")
.setStatus("Success")
- ], components: []})
+ ], components: []});
} else {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("ICONS.OPP.ADD")
- .setTitle(`Suggest`)
+ .setTitle("Suggest")
.setDescription("No changes were made")
.setStatus("Danger")
- ], components: []})
+ ], components: []});
}
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/privacy.ts b/src/commands/privacy.ts
index 81d1503..ca56fcd 100644
--- a/src/commands/privacy.ts
+++ b/src/commands/privacy.ts
@@ -1,4 +1,4 @@
-import { LoadingEmbed } from './../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "./../utils/defaultEmbeds.js";
import Discord, { CommandInteraction, MessageActionRow, MessageButton } from "discord.js";
import { SelectMenuOption, SlashCommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
@@ -11,13 +11,13 @@
const command = new SlashCommandBuilder()
.setName("privacy")
- .setDescription("Information and options for you and your server's settings")
+ .setDescription("Information and options for you and your server's settings");
class Embed {
embed: Discord.MessageEmbed;
title: string;
- description: string = "";
- pageId: number = 0;
+ description = "";
+ pageId = 0;
components?: MessageActionRow[] = [];
setEmbed(embed: Discord.MessageEmbed) { this.embed = embed; return this; }
setTitle(title: string) { this.title = title; return this; }
@@ -27,7 +27,7 @@
}
const callback = async (interaction: CommandInteraction): Promise<any> => {
- let pages = [
+ const pages = [
new Embed()
.setEmbed(new EmojiEmbed()
.setTitle("Nucleus Privacy")
@@ -81,43 +81,43 @@
let nextFooter = null;
while (true) {
- let selectPane = []
+ let selectPane = [];
if (selectPaneOpen) {
- let options = [];
+ const options = [];
pages.forEach(embed => {
options.push(new SelectMenuOption({
label: embed.title,
value: embed.pageId.toString(),
- description: embed.description || "",
- }))
- })
+ description: embed.description || ""
+ }));
+ });
selectPane = [new MessageActionRow().addComponents([
new Discord.MessageSelectMenu()
.addOptions(options)
.setCustomId("page")
.setMaxValues(1)
.setPlaceholder("Choose a page...")
- ])]
+ ])];
}
- let components = selectPane.concat([new MessageActionRow().addComponents([
+ const components = selectPane.concat([new MessageActionRow().addComponents([
new MessageButton().setCustomId("left").setEmoji(getEmojiByName("CONTROL.LEFT", "id")).setStyle("SECONDARY").setDisabled(page === 0),
new MessageButton().setCustomId("select").setEmoji(getEmojiByName("CONTROL.MENU", "id")).setStyle(selectPaneOpen ? "PRIMARY" : "SECONDARY").setDisabled(false),
new MessageButton().setCustomId("right").setEmoji(getEmojiByName("CONTROL.RIGHT", "id")).setStyle("SECONDARY").setDisabled(page === pages.length - 1)
- ])])
- let 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: nextFooter ?? ""})
+ em.setFooter({text: nextFooter ?? ""});
await interaction.editReply({
embeds: [em],
components: components.concat(pages[page].components)
});
- let i
+ let i;
try {
i = await m.awaitMessageComponent({time: 300000});
- } catch(e) { break }
- nextFooter = null
- i.deferUpdate()
+ } catch(e) { break; }
+ nextFooter = null;
+ i.deferUpdate();
if (i.component.customId === "left") {
if (page > 0) page--;
selectPaneOpen = false;
@@ -130,15 +130,15 @@
page = parseInt(i.values[0]);
selectPaneOpen = false;
} else if (i.component.customId === "clear-all-data") {
- let confirmation = await new confirmationMessage(interaction)
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("CONTROL.BLOCKCROSS")
.setTitle("Clear All Data")
.setDescription(
- `Are you sure you want to delete all data on this server? This includes your settings and all punishment histories.\n\n` +
+ "Are you sure you want to delete all data on this server? This includes your settings and all punishment histories.\n\n" +
"**This cannot be undone.**"
)
.setColor("Danger")
- .send(true)
+ .send(true);
if (confirmation.cancelled) { break; }
if (confirmation.success) {
client.database.guilds.delete(interaction.guild.id);
@@ -150,25 +150,25 @@
continue;
}
} else {
- let em = new Discord.MessageEmbed(pages[page].embed)
- em.setDescription(em.description + "\n\n" + createPageIndicator(pages.length, page))
+ 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({embeds: [em], components: []});
- return
+ return;
}
}
- let em = new Discord.MessageEmbed(pages[page].embed)
- em.setDescription(em.description + "\n\n" + createPageIndicator(pages.length, page))
+ const em = new Discord.MessageEmbed(pages[page].embed);
+ em.setDescription(em.description + "\n\n" + createPageIndicator(pages.length, page));
em.setFooter({text: "Message timed out"});
await interaction.editReply({
embeds: [em],
components: []
});
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/role/user.ts b/src/commands/role/user.ts
index d361cf1..d2b05e9 100644
--- a/src/commands/role/user.ts
+++ b/src/commands/role/user.ts
@@ -8,21 +8,21 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("user")
- .setDescription("Gives or removes a role from someone")
- .addUserOption(option => option.setName("user").setDescription("The member to give or remove the role from").setRequired(true))
- .addRoleOption(option => option.setName("role").setDescription("The role to give or remove").setRequired(true))
- .addStringOption(option => option.setName("action").setDescription("The action to perform").setRequired(true).addChoices([
- ["Add", "give"],
- ["Remove", "remove"]
- ]))
+ .setName("user")
+ .setDescription("Gives or removes a role from someone")
+ .addUserOption(option => option.setName("user").setDescription("The member to give or remove the role from").setRequired(true))
+ .addRoleOption(option => option.setName("role").setDescription("The role to give or remove").setRequired(true))
+ .addStringOption(option => option.setName("action").setDescription("The action to perform").setRequired(true).addChoices([
+ ["Add", "give"],
+ ["Remove", "remove"]
+ ]));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- const { renderUser, renderRole } = client.logger
- let action = interaction.options.getString("action");
+ const { renderUser, renderRole } = client.logger;
+ const action = interaction.options.getString("action");
// TODO:[Modals] Replace this with a modal
- let confirmation = await new confirmationMessage(interaction)
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("GUILD.ROLES.DELETE")
.setTitle("Role")
.setDescription(keyValueList({
@@ -30,16 +30,16 @@
"role": renderRole(interaction.options.getRole("role"))
}) + `\nAre you sure you want to ${action === "give" ? "give the role to" : "remove the role from"} ${interaction.options.getUser("user")}?`)
.setColor("Danger")
- .send()
- if (confirmation.cancelled) return
+ .send();
+ if (confirmation.cancelled) return;
if (confirmation.success) {
try {
- let member = interaction.options.getMember("user") as GuildMember
- let role = interaction.options.getRole("role") as Role
+ const member = interaction.options.getMember("user") as GuildMember;
+ const role = interaction.options.getRole("role") as Role;
if (interaction.options.getString("action") === "give") {
- member.roles.add(role)
+ member.roles.add(role);
} else {
- member.roles.remove(role)
+ member.roles.remove(role);
}
} catch (e) {
return await interaction.editReply({embeds: [new EmojiEmbed()
@@ -47,38 +47,38 @@
.setDescription("Something went wrong and the role could not be added")
.setStatus("Danger")
.setEmoji("CONTROL.BLOCKCROSS")
- ], components: []})
+ ], components: []});
}
return await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Role")
.setDescription(`The role has been ${action === "give" ? "given" : "removed"} successfully`)
.setStatus("Success")
.setEmoji("GUILD.ROLES.CREATE")
- ], components: []})
+ ], components: []});
} else {
await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("GUILD.ROLES.CREATE")
.setTitle("Role")
- .setDescription(`No changes were made.`)
+ .setDescription("No changes were made.")
.setStatus("Danger")
- ], components: []})
+ ], components: []});
}
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as GuildMember)
- let me = (interaction.guild.me as GuildMember)
- let apply = (interaction.options.getMember("user") as GuildMember)
- if (member === null || me === null || apply === null) throw "That member is not in the server"
+ const member = (interaction.member as GuildMember);
+ const me = (interaction.guild.me as GuildMember);
+ const apply = (interaction.options.getMember("user") as GuildMember);
+ if (member === null || me === null || apply === null) throw "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";
// Allow the owner to role anyone
- if (member.id === interaction.guild.ownerId) return true
+ 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";
// Allow role
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/rolemenu.ts b/src/commands/rolemenu.ts
index 39e18f7..1a5f297 100644
--- a/src/commands/rolemenu.ts
+++ b/src/commands/rolemenu.ts
@@ -1,19 +1,19 @@
import { CommandInteraction } from "discord.js";
import { SlashCommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
-import { callback as roleMenu } from "../actions/roleMenu.js"
+import { callback as roleMenu } from "../actions/roleMenu.js";
const command = new SlashCommandBuilder()
.setName("rolemenu")
- .setDescription("Lets you choose from sets of roles to apply to yourself")
+ .setDescription("Lets you choose from sets of roles to apply to yourself");
const callback = async (interaction: CommandInteraction): Promise<any> => {
await roleMenu(interaction);
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/server/about.ts b/src/commands/server/about.ts
index 70998d5..b70d0a6 100644
--- a/src/commands/server/about.ts
+++ b/src/commands/server/about.ts
@@ -4,15 +4,15 @@
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import getEmojiByName from "../../utils/getEmojiByName.js";
import generateKeyValueList, { toCapitals } from "../../utils/generateKeyValueList.js";
-import client from "../../utils/client.js"
+import client from "../../utils/client.js";
const command = (builder: SlashCommandSubcommandBuilder) => builder
.setName("about")
- .setDescription("Shows info about the server")
+ .setDescription("Shows info about the server");
const callback = async (interaction: CommandInteraction): Promise<any> => {
- let guild = interaction.guild as Guild;
- const { renderUser, renderDelta } = client.logger
+ const guild = interaction.guild as Guild;
+ const { renderUser, renderDelta } = client.logger;
interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Server Info")
.setStatus("Success")
@@ -24,26 +24,26 @@
"owner": `${renderUser((await guild.fetchOwner()).user)}`,
"created": `${renderDelta(guild.createdTimestamp)}`,
"emojis": `${guild.emojis.cache.size}` + (guild.emojis.cache.size > 1 ? `\n> ${
- guild.emojis.cache.first(10).map((emoji) => `<${emoji.animated ? 'a' : ''}:${emoji.name}:${emoji.id}>`).join(" ")
- }` +
- (guild.emojis.cache.size > 10 ? ` and ${guild.emojis.cache.size - 10} more` : ``) : ""),
+ guild.emojis.cache.first(10).map((emoji) => `<${emoji.animated ? "a" : ""}:${emoji.name}:${emoji.id}>`).join(" ")
+ }` +
+ (guild.emojis.cache.size > 10 ? ` and ${guild.emojis.cache.size - 10} more` : "") : ""),
"icon": `[Discord](${guild.iconURL()})`,
"2 factor authentication": `${guild.mfaLevel === "NONE" ? `${getEmojiByName("CONTROL.CROSS")} No` : `${getEmojiByName("CONTROL.TICK")} Yes`}`,
"verification level": `${toCapitals(guild.verificationLevel)}`,
- "explicit content filter": `${toCapitals(guild.explicitContentFilter.toString().replace(/_/, " ", ))}`,
+ "explicit content filter": `${toCapitals(guild.explicitContentFilter.toString().replace(/_/, " " ))}`,
"nitro boost level": `${guild.premiumTier !== "NONE" ? guild.premiumTier.toString()[-1] : "0"}`,
"channels": `${guild.channels.cache.size}`,
"roles": `${guild.roles.cache.size}`,
- "members": `${guild.memberCount}`,
+ "members": `${guild.memberCount}`
})
)
.setThumbnail(guild.iconURL({dynamic: true}))
], ephemeral: true});
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/settings/commands.ts b/src/commands/settings/commands.ts
index 23d5c66..7b6b309 100644
--- a/src/commands/settings/commands.ts
+++ b/src/commands/settings/commands.ts
@@ -1,4 +1,4 @@
-import { LoadingEmbed } from './../../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "./../../utils/defaultEmbeds.js";
import Discord, { CommandInteraction, MessageActionRow, MessageButton, TextInputComponent } from "discord.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import getEmojiByName from "../../utils/getEmojiByName.js";
@@ -11,43 +11,43 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("commands")
- .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"))
+ .setName("commands")
+ .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<any> => {
await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true});
let m;
let clicked = "";
if (interaction.options.getRole("role")) {
- let confirmation = await new confirmationMessage(interaction)
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("GUILD.ROLES.DELETE")
.setTitle("Moderation Commands")
.setDescription(keyValueList({
- role: `<@&${interaction.options.getRole("role").id}>`,
+ role: `<@&${interaction.options.getRole("role").id}>`
}))
.setColor("Danger")
- .send(true)
+ .send(true);
if (confirmation.cancelled) return await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Moderation Commands")
.setDescription("No changes were made")
.setStatus("Success")
.setEmoji("GUILD.ROLES.CREATE")
- ]})
+ ]});
if (confirmation.success) {
await client.database.guilds.write(interaction.guild.id, {["moderation.mute.role"]: interaction.options.getRole("role").id});
}
}
while (true) {
- let config = await client.database.guilds.read(interaction.guild.id);
- let moderation = config.getKey("moderation");
+ const config = await client.database.guilds.read(interaction.guild.id);
+ const moderation = config.getKey("moderation");
m = await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Moderation Commands")
.setEmoji("PUNISH.BAN.GREEN")
.setStatus("Success")
.setDescription(
"These links are shown below the message sent in a user's DM when they are punished.\n\n" +
- `**Mute Role:** ` + (moderation.mute.role ? `<@&${moderation.mute.role}>` : "*None set*")
+ "**Mute Role:** " + (moderation.mute.role ? `<@&${moderation.mute.role}>` : "*None set*")
)
], components: [new MessageActionRow().addComponents([
new MessageButton().setLabel("Warn").setEmoji(getEmojiByName("PUNISH.WARN.YELLOW", "id")).setCustomId("warn").setStyle("SECONDARY"),
@@ -70,19 +70,19 @@
let i;
try {
i = await m.awaitMessageComponent({ time: 300000 });
- } catch (e) { return }
+ } catch (e) { return; }
let chosen = moderation[i.customId] ?? {text: null, url: null};
if (i.component.customId === "clearMuteRole") {
- i.deferUpdate()
+ i.deferUpdate();
if (clicked === "clearMuteRole") {
await client.database.guilds.write(interaction.guild.id, {"moderation.mute.role": null });
- } else { clicked = "clearMuteRole" }
- continue
- } else { clicked = "" }
+ } else { clicked = "clearMuteRole"; }
+ continue;
+ } else { clicked = ""; }
if (i.component.customId === "timeout") {
- await i.deferUpdate()
+ await i.deferUpdate();
await client.database.guilds.write(interaction.guild.id, {"moderation.mute.timeout": !moderation.mute.timeout } );
- continue
+ continue;
} else if (i.customId) {
await i.showModal(new Discord.Modal().setCustomId("modal").setTitle(`Options for ${i.customId}`).addComponents(
new MessageActionRow<TextInputComponent>().addComponents(new TextInputComponent()
@@ -101,7 +101,7 @@
.setStyle("SHORT")
.setValue(chosen.link ?? "")
)
- ))
+ ));
await interaction.editReply({
embeds: [new EmojiEmbed()
.setTitle("Moderation Links")
@@ -117,27 +117,27 @@
});
let out;
try {
- out = await modalInteractionCollector(m, (m) => m.channel.id === interaction.channel.id, (m) => true)
- } catch (e) { continue }
+ out = await modalInteractionCollector(m, (m) => m.channel.id === interaction.channel.id, (m) => true);
+ } catch (e) { continue; }
if (out.fields) {
- let buttonText = out.fields.getTextInputValue("name");
- let buttonLink = out.fields.getTextInputValue("url").replace(/{id}/gi, "{id}");
- let current = chosen;
+ const buttonText = out.fields.getTextInputValue("name");
+ const buttonLink = out.fields.getTextInputValue("url").replace(/{id}/gi, "{id}");
+ const current = chosen;
if (current.text !== buttonText || current.link !== buttonLink) {
chosen = { text: buttonText, link: buttonLink };
await client.database.guilds.write(interaction.guild.id, { ["moderation." + i.customId]: { text: buttonText, link: buttonLink }});
}
- } else { continue }
+ } else { continue; }
}
}
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as Discord.GuildMember)
- if (!member.permissions.has("MANAGE_GUILD")) throw "You must have the *Manage Server* permission to use this command"
+ 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";
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/settings/filters.ts b/src/commands/settings/filters.ts
index dfcff99..d35d210 100644
--- a/src/commands/settings/filters.ts
+++ b/src/commands/settings/filters.ts
@@ -1,28 +1,28 @@
-import { LoadingEmbed } from './../../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "./../../utils/defaultEmbeds.js";
import Discord, { CommandInteraction, MessageActionRow, MessageButton, MessageSelectMenu } from "discord.js";
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
-import client from '../../utils/client.js';
-import confirmationMessage from '../../utils/confirmationMessage.js';
-import generateKeyValueList from '../../utils/generateKeyValueList.js';
-import { ChannelType } from 'discord-api-types';
-import getEmojiByName from '../../utils/getEmojiByName.js';
+import client from "../../utils/client.js";
+import confirmationMessage from "../../utils/confirmationMessage.js";
+import generateKeyValueList from "../../utils/generateKeyValueList.js";
+import { ChannelType } from "discord-api-types";
+import getEmojiByName from "../../utils/getEmojiByName.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("filter")
- .setDescription("Setting for message filters")
+ .setName("filter")
+ .setDescription("Setting for message filters");
const callback = async (interaction: CommandInteraction): Promise<any> => {
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as Discord.GuildMember)
- if (!member.permissions.has("MANAGE_MESSAGES")) throw "You must have the *Manage Messages* permission to use this command"
+ 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";
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/settings/logs/attachment.ts b/src/commands/settings/logs/attachment.ts
index 2dae74e..edd1c61 100644
--- a/src/commands/settings/logs/attachment.ts
+++ b/src/commands/settings/logs/attachment.ts
@@ -1,5 +1,5 @@
-import { LoadingEmbed } from './../../../utils/defaultEmbeds.js';
-import { ChannelType } from 'discord-api-types';
+import { LoadingEmbed } from "./../../../utils/defaultEmbeds.js";
+import { ChannelType } from "discord-api-types";
import Discord, { CommandInteraction, MessageActionRow, MessageButton } from "discord.js";
import EmojiEmbed from "../../../utils/generateEmojiEmbed.js";
import confirmationMessage from "../../../utils/confirmationMessage.js";
@@ -10,76 +10,74 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("attachments")
- .setDescription("Where attachments should be logged to (Premium only)")
- .addChannelOption(option => option.setName("channel").setDescription("The channel to log attachments in").addChannelTypes([
- ChannelType.GuildNews, ChannelType.GuildText
- ]).setRequired(false))
+ .setName("attachments")
+ .setDescription("Where attachments should be logged to (Premium only)")
+ .addChannelOption(option => option.setName("channel").setDescription("The channel to log attachments in").addChannelTypes([
+ ChannelType.GuildNews, ChannelType.GuildText
+ ]).setRequired(false));
const callback = async (interaction: CommandInteraction): Promise<any> => {
let m;
m = await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true});
if (interaction.options.getChannel("channel")) {
- let channel
+ let channel;
try {
- channel = interaction.options.getChannel("channel")
+ channel = interaction.options.getChannel("channel");
} catch {
return await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("CHANNEL.TEXT.DELETE")
.setTitle("Attachment Log Channel")
.setDescription("The channel you provided is not a valid channel")
.setStatus("Danger")
- ]})
+ ]});
}
- channel = channel as Discord.TextChannel
+ channel = channel as Discord.TextChannel;
if (channel.guild.id !== interaction.guild.id) {
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Attachment Log Channel")
- .setDescription(`You must choose a channel in this server`)
+ .setDescription("You must choose a channel in this server")
.setStatus("Danger")
.setEmoji("CHANNEL.TEXT.DELETE")
]});
}
- let confirmation = await new confirmationMessage(interaction)
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("CHANNEL.TEXT.EDIT")
.setTitle("Attachment Log Channel")
.setDescription(
- `This will be the channel all attachments will be sent to.\n\n` +
+ "This will be the channel all attachments will be sent to.\n\n" +
`Are you sure you want to set the attachment log channel to <#${channel.id}>?`
)
.setColor("Warning")
.setInverted(true)
- .send(true)
- if (confirmation.cancelled) return
+ .send(true);
+ if (confirmation.cancelled) return;
if (confirmation.success) {
try {
- await client.database.guilds.write(interaction.guild.id, {"logging.attachments.channel": channel.id})
- const { log, NucleusColors, entry, renderUser, renderChannel } = client.logger
- try {
- let data = {
- meta:{
- type: 'attachmentChannelUpdate',
- displayName: 'Attachment Log Channel Updated',
- calculateType: 'nucleusSettingsUpdated',
- color: NucleusColors.yellow,
- emoji: "CHANNEL.TEXT.EDIT",
- timestamp: new Date().getTime()
- },
- list: {
- memberId: entry(interaction.user.id, `\`${interaction.user.id}\``),
- changedBy: entry(interaction.user.id, renderUser(interaction.user)),
- channel: entry(channel.id, renderChannel(channel)),
- },
- hidden: {
- guild: interaction.guild.id
- }
+ await client.database.guilds.write(interaction.guild.id, {"logging.attachments.channel": channel.id});
+ const { log, NucleusColors, entry, renderUser, renderChannel } = client.logger;
+ const data = {
+ meta:{
+ type: "attachmentChannelUpdate",
+ displayName: "Attachment Log Channel Updated",
+ calculateType: "nucleusSettingsUpdated",
+ color: NucleusColors.yellow,
+ emoji: "CHANNEL.TEXT.EDIT",
+ timestamp: new Date().getTime()
+ },
+ list: {
+ memberId: entry(interaction.user.id, `\`${interaction.user.id}\``),
+ changedBy: entry(interaction.user.id, renderUser(interaction.user)),
+ channel: entry(channel.id, renderChannel(channel))
+ },
+ hidden: {
+ guild: interaction.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
} catch (e) {
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Attachment Log Channel")
- .setDescription(`Something went wrong and the attachment log channel could not be set`)
+ .setDescription("Something went wrong and the attachment log channel could not be set")
.setStatus("Danger")
.setEmoji("CHANNEL.TEXT.DELETE")
], components: []});
@@ -87,14 +85,14 @@
} else {
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Attachment Log Channel")
- .setDescription(`No changes were made`)
+ .setDescription("No changes were made")
.setStatus("Success")
.setEmoji("CHANNEL.TEXT.CREATE")
], components: []});
}
}
let clicks = 0;
- let data = await client.database.guilds.read(interaction.guild.id);
+ const data = await client.database.guilds.read(interaction.guild.id);
let channel = data.logging.staff.channel;
while (true) {
await interaction.editReply({embeds: [new EmojiEmbed()
@@ -115,17 +113,17 @@
let i;
try {
i = await m.awaitMessageComponent({time: 300000});
- } catch(e) { break }
- i.deferUpdate()
+ } catch(e) { break; }
+ i.deferUpdate();
if (i.component.customId === "clear") {
clicks += 1;
if (clicks === 2) {
clicks = 0;
- await client.database.guilds.write(interaction.guild.id, null, ["logging.announcements.channel"])
+ await client.database.guilds.write(interaction.guild.id, null, ["logging.announcements.channel"]);
channel = undefined;
}
} else {
- break
+ break;
}
}
await interaction.editReply({embeds: [new EmojiEmbed()
@@ -141,13 +139,13 @@
.setStyle("SECONDARY")
.setDisabled(true)
])]});
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as Discord.GuildMember)
- if (!member.permissions.has("MANAGE_GUILD")) throw "You must have the *Manage Server* permission to use this command"
+ 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";
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/settings/logs/channel.ts b/src/commands/settings/logs/channel.ts
index 4030108..da0d156 100644
--- a/src/commands/settings/logs/channel.ts
+++ b/src/commands/settings/logs/channel.ts
@@ -1,5 +1,5 @@
-import { LoadingEmbed } from './../../../utils/defaultEmbeds.js';
-import { ChannelType } from 'discord-api-types';
+import { LoadingEmbed } from "./../../../utils/defaultEmbeds.js";
+import { ChannelType } from "discord-api-types";
import Discord, { CommandInteraction, MessageActionRow, MessageButton } from "discord.js";
import EmojiEmbed from "../../../utils/generateEmojiEmbed.js";
import confirmationMessage from "../../../utils/confirmationMessage.js";
@@ -10,74 +10,72 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("channel")
- .setDescription("Sets or shows the log channel")
- .addChannelOption(option => option.setName("channel").setDescription("The channel to set the log channel to").addChannelTypes([
- ChannelType.GuildNews, ChannelType.GuildText
- ]))
+ .setName("channel")
+ .setDescription("Sets or shows the log channel")
+ .addChannelOption(option => option.setName("channel").setDescription("The channel to set the log channel to").addChannelTypes([
+ ChannelType.GuildNews, ChannelType.GuildText
+ ]));
const callback = async (interaction: CommandInteraction): Promise<any> => {
let m;
m = await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true});
if (interaction.options.getChannel("channel")) {
- let channel
+ let channel;
try {
- channel = interaction.options.getChannel("channel")
+ channel = interaction.options.getChannel("channel");
} catch {
return await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("CHANNEL.TEXT.DELETE")
.setTitle("Log Channel")
.setDescription("The channel you provided is not a valid channel")
.setStatus("Danger")
- ]})
+ ]});
}
- channel = channel as Discord.TextChannel
+ channel = channel as Discord.TextChannel;
if (channel.guild.id !== interaction.guild.id) {
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Log Channel")
- .setDescription(`You must choose a channel in this server`)
+ .setDescription("You must choose a channel in this server")
.setStatus("Danger")
.setEmoji("CHANNEL.TEXT.DELETE")
]});
}
- let confirmation = await new confirmationMessage(interaction)
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("CHANNEL.TEXT.EDIT")
.setTitle("Log Channel")
.setDescription(`Are you sure you want to set the log channel to <#${channel.id}>?`)
.setColor("Warning")
.setInverted(true)
- .send(true)
- if (confirmation.cancelled) return
+ .send(true);
+ if (confirmation.cancelled) return;
if (confirmation.success) {
try {
- await client.database.guilds.write(interaction.guild.id, {"logging.logs.channel": channel.id})
- const { log, NucleusColors, entry, renderUser, renderChannel } = client.logger
- try {
- let data = {
- meta:{
- type: 'logChannelUpdate',
- displayName: 'Log Channel Changed',
- calculateType: 'nucleusSettingsUpdated',
- color: NucleusColors.yellow,
- emoji: "CHANNEL.TEXT.EDIT",
- timestamp: new Date().getTime()
- },
- list: {
- memberId: entry(interaction.user.id, `\`${interaction.user.id}\``),
- changedBy: entry(interaction.user.id, renderUser(interaction.user)),
- channel: entry(channel.id, renderChannel(channel)),
- },
- hidden: {
- guild: channel.guild.id
- }
+ await client.database.guilds.write(interaction.guild.id, {"logging.logs.channel": channel.id});
+ const { log, NucleusColors, entry, renderUser, renderChannel } = client.logger;
+ const data = {
+ meta:{
+ type: "logChannelUpdate",
+ displayName: "Log Channel Changed",
+ calculateType: "nucleusSettingsUpdated",
+ color: NucleusColors.yellow,
+ emoji: "CHANNEL.TEXT.EDIT",
+ timestamp: new Date().getTime()
+ },
+ list: {
+ memberId: entry(interaction.user.id, `\`${interaction.user.id}\``),
+ changedBy: entry(interaction.user.id, renderUser(interaction.user)),
+ channel: entry(channel.id, renderChannel(channel))
+ },
+ hidden: {
+ guild: channel.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
} catch (e) {
- console.log(e)
+ console.log(e);
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Log Channel")
- .setDescription(`Something went wrong and the log channel could not be set`)
+ .setDescription("Something went wrong and the log channel could not be set")
.setStatus("Danger")
.setEmoji("CHANNEL.TEXT.DELETE")
], components: []});
@@ -85,14 +83,14 @@
} else {
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Log Channel")
- .setDescription(`No changes were made`)
+ .setDescription("No changes were made")
.setStatus("Success")
.setEmoji("CHANNEL.TEXT.CREATE")
], components: []});
}
}
let clicks = 0;
- let data = await client.database.guilds.read(interaction.guild.id);
+ const data = await client.database.guilds.read(interaction.guild.id);
let channel = data.logging.logs.channel;
while (true) {
await interaction.editReply({embeds: [new EmojiEmbed()
@@ -110,17 +108,17 @@
let i;
try {
i = await m.awaitMessageComponent({time: 300000});
- } catch(e) { break }
- i.deferUpdate()
+ } catch(e) { break; }
+ i.deferUpdate();
if (i.component.customId === "clear") {
clicks += 1;
if (clicks === 2) {
clicks = 0;
- await client.database.guilds.write(interaction.guild.id, null, ["logging.logs.channel"])
+ await client.database.guilds.write(interaction.guild.id, null, ["logging.logs.channel"]);
channel = undefined;
}
} else {
- break
+ break;
}
}
await interaction.editReply({embeds: [new EmojiEmbed()
@@ -136,13 +134,13 @@
.setStyle("SECONDARY")
.setDisabled(true)
])]});
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as Discord.GuildMember)
- if (!member.permissions.has("MANAGE_GUILD")) throw "You must have the *Manage Server* permission to use this command"
+ 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";
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/settings/logs/events.ts b/src/commands/settings/logs/events.ts
index ef303cb..88386c4 100644
--- a/src/commands/settings/logs/events.ts
+++ b/src/commands/settings/logs/events.ts
@@ -1,9 +1,9 @@
-import { LoadingEmbed } from './../../../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "./../../../utils/defaultEmbeds.js";
import Discord, { CommandInteraction, MessageActionRow, MessageButton, MessageSelectMenu } from "discord.js";
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
import EmojiEmbed from "../../../utils/generateEmojiEmbed.js";
-import client from '../../../utils/client.js';
+import client from "../../../utils/client.js";
import { toHexArray, toHexInteger } from "../../../utils/calculate.js";
@@ -27,20 +27,20 @@
"guildMemberVerify": "Member runs verify",
"autoModeratorDeleted": "Messages auto deleted by Nucleus",
"nucleusSettingsUpdated": "Nucleus' settings updated by a moderator",
- "ticketUpdate": "Tickets created or deleted",
-}
+ "ticketUpdate": "Tickets created or deleted"
+};
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("events")
- .setDescription("Sets what events should be logged")
+ .setName("events")
+ .setDescription("Sets what events should be logged");
const callback = async (interaction: CommandInteraction): Promise<any> => {
await interaction.reply({embeds: LoadingEmbed, fetchReply: true, ephemeral: true});
let m;
while (true) {
- let config = await client.database.guilds.read(interaction.guild.id)
- let converted = toHexArray(config.logging.logs.toLog)
+ const config = await client.database.guilds.read(interaction.guild.id);
+ const converted = toHexArray(config.logging.logs.toLog);
m = await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Logging Events")
.setDescription("Below are the events being logged in the server. You can toggle them on and off in the dropdown")
@@ -68,25 +68,25 @@
.setStyle("DANGER")
.setCustomId("none")
])
- ]})
+ ]});
let i;
try {
i = await m.awaitMessageComponent({ time: 300000 });
} catch (e) {
- break
+ break;
}
- i.deferUpdate()
+ i.deferUpdate();
if (i.customId === "logs") {
- let selected = i.values;
- let newLogs = toHexInteger(selected.map(e => Object.keys(logs)[parseInt(e)]))
- await client.database.guilds.write(interaction.guild.id, {"logging.logs.toLog": newLogs})
+ const selected = i.values;
+ const newLogs = toHexInteger(selected.map(e => Object.keys(logs)[parseInt(e)]));
+ await client.database.guilds.write(interaction.guild.id, {"logging.logs.toLog": newLogs});
} else if (i.customId === "all") {
- let newLogs = toHexInteger(Object.keys(logs).map(e => e))
- await client.database.guilds.write(interaction.guild.id, {"logging.logs.toLog": newLogs})
+ const newLogs = toHexInteger(Object.keys(logs).map(e => e));
+ await client.database.guilds.write(interaction.guild.id, {"logging.logs.toLog": newLogs});
} else if (i.customId === "none") {
- await client.database.guilds.write(interaction.guild.id, {"logging.logs.toLog": 0})
+ await client.database.guilds.write(interaction.guild.id, {"logging.logs.toLog": 0});
} else {
- break
+ break;
}
}
m = await interaction.editReply({embeds: [new EmojiEmbed()
@@ -95,14 +95,14 @@
.setFooter({text: "Message timed out"})
.setStatus("Success")
.setEmoji("CHANNEL.TEXT.CREATE")
- ]})
-}
+ ]});
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as Discord.GuildMember)
- if (!member.permissions.has("MANAGE_GUILD")) throw "You must have the *Manage Server* permission to use this command"
+ 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";
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/settings/logs/staff.ts b/src/commands/settings/logs/staff.ts
index 5867338..2f0c819 100644
--- a/src/commands/settings/logs/staff.ts
+++ b/src/commands/settings/logs/staff.ts
@@ -1,85 +1,85 @@
-import { LoadingEmbed } from './../../../utils/defaultEmbeds.js';
-import { ChannelType } from 'discord-api-types';
+import { LoadingEmbed } from "./../../../utils/defaultEmbeds.js";
+import { ChannelType } from "discord-api-types";
import Discord, { CommandInteraction, MessageActionRow, MessageButton } from "discord.js";
import EmojiEmbed from "../../../utils/generateEmojiEmbed.js";
import confirmationMessage from "../../../utils/confirmationMessage.js";
import getEmojiByName from "../../../utils/getEmojiByName.js";
-import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
-import { WrappedCheck } from "jshaiku";
+import type { SlashCommandSubcommandBuilder } from "@discordjs/builders";
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore
+import type { WrappedCheck } from "jshaiku";
import client from "../../../utils/client.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("staff")
- .setDescription("Settings for the staff notifications channel")
- .addChannelOption(option => option.setName("channel").setDescription("The channel to set the staff notifications channel to").addChannelTypes([
- ChannelType.GuildNews, ChannelType.GuildText
- ]).setRequired(false))
+ .setName("staff")
+ .setDescription("Settings for the staff notifications channel")
+ .addChannelOption(option => option.setName("channel").setDescription("The channel to set the staff notifications channel to").addChannelTypes([
+ ChannelType.GuildNews, ChannelType.GuildText
+ ]).setRequired(false));
-const callback = async (interaction: CommandInteraction): Promise<any> => {
- let m;
- m = await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true});
+const callback = async (interaction: CommandInteraction): Promise<unknown | void> => {
+ if (!interaction.guild) return;
+ const m = await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true}) as Discord.Message<boolean>;
if (interaction.options.getChannel("channel")) {
- let channel
+ let channel;
try {
- channel = interaction.options.getChannel("channel")
+ channel = interaction.options.getChannel("channel");
} catch {
return await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("CHANNEL.TEXT.DELETE")
.setTitle("Staff Notifications Channel")
.setDescription("The channel you provided is not a valid channel")
.setStatus("Danger")
- ]})
+ ]});
}
- channel = channel as Discord.TextChannel
+ channel = channel as Discord.TextChannel;
if (channel.guild.id !== interaction.guild.id) {
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Staff Notifications Channel")
- .setDescription(`You must choose a channel in this server`)
+ .setDescription("You must choose a channel in this server")
.setStatus("Danger")
.setEmoji("CHANNEL.TEXT.DELETE")
]});
}
- let confirmation = await new confirmationMessage(interaction)
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("CHANNEL.TEXT.EDIT")
.setTitle("Staff Notifications Channel")
.setDescription(
- `This will be the channel all notifications, updates, user reports etc. will be sent to.\n\n` +
+ "This will be the channel all notifications, updates, user reports etc. will be sent to.\n\n" +
`Are you sure you want to set the staff notifications channel to <#${channel.id}>?`
)
.setColor("Warning")
.setInverted(true)
- .send(true)
- if (confirmation.cancelled) return
+ .send(true);
+ if (confirmation.cancelled) return;
if (confirmation.success) {
try {
- await client.database.guilds.write(interaction.guild.id, {"logging.staff.channel": channel.id})
- const { log, NucleusColors, entry, renderUser, renderChannel } = client.logger
- try {
- let data = {
- meta:{
- type: 'staffChannelUpdate',
- displayName: 'Staff Notifications Channel Updated',
- calculateType: 'nucleusSettingsUpdated',
- color: NucleusColors.yellow,
- emoji: "CHANNEL.TEXT.EDIT",
- timestamp: new Date().getTime()
- },
- list: {
- memberId: entry(interaction.user.id, `\`${interaction.user.id}\``),
- changedBy: entry(interaction.user.id, renderUser(interaction.user)),
- channel: entry(channel.id, renderChannel(channel)),
- },
- hidden: {
- guild: interaction.guild.id
- }
+ await client.database.guilds.write(interaction.guild.id, {"logging.staff.channel": channel.id});
+ const { log, NucleusColors, entry, renderUser, renderChannel } = client.logger;
+ const data = {
+ meta:{
+ type: "staffChannelUpdate",
+ displayName: "Staff Notifications Channel Updated",
+ calculateType: "nucleusSettingsUpdated",
+ color: NucleusColors.yellow,
+ emoji: "CHANNEL.TEXT.EDIT",
+ timestamp: new Date().getTime()
+ },
+ list: {
+ memberId: entry(interaction.user.id, `\`${interaction.user.id}\``),
+ changedBy: entry(interaction.user.id, renderUser(interaction.user)),
+ channel: entry(channel.id, renderChannel(channel))
+ },
+ hidden: {
+ guild: interaction.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
} catch (e) {
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Staff Notifications Channel")
- .setDescription(`Something went wrong and the staff notifications channel could not be set`)
+ .setDescription("Something went wrong and the staff notifications channel could not be set")
.setStatus("Danger")
.setEmoji("CHANNEL.TEXT.DELETE")
], components: []});
@@ -87,14 +87,14 @@
} else {
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Staff Notifications Channel")
- .setDescription(`No changes were made`)
+ .setDescription("No changes were made")
.setStatus("Success")
.setEmoji("CHANNEL.TEXT.CREATE")
], components: []});
}
}
let clicks = 0;
- let data = await client.database.guilds.read(interaction.guild.id);
+ const data = await client.database.guilds.read(interaction.guild.id);
let channel = data.logging.staff.channel;
while (true) {
await interaction.editReply({embeds: [new EmojiEmbed()
@@ -112,17 +112,17 @@
let i;
try {
i = await m.awaitMessageComponent({time: 300000});
- } catch(e) { break }
- i.deferUpdate()
- if (i.component.customId === "clear") {
+ } catch(e) { break; }
+ i.deferUpdate();
+ if ((i.component as MessageButton).customId === "clear") {
clicks += 1;
if (clicks === 2) {
clicks = 0;
- await client.database.guilds.write(interaction.guild.id, null, ["logging.staff.channel"])
+ await client.database.guilds.write(interaction.guild.id, null, ["logging.staff.channel"]);
channel = undefined;
}
} else {
- break
+ break;
}
}
await interaction.editReply({embeds: [new EmojiEmbed()
@@ -138,13 +138,13 @@
.setStyle("SECONDARY")
.setDisabled(true)
])]});
-}
+};
-const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as Discord.GuildMember)
- if (!member.permissions.has("MANAGE_GUILD")) throw "You must have the *Manage Server* permission to use this command"
+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";
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/settings/rolemenu.ts b/src/commands/settings/rolemenu.ts
index 891b6f1..9a4ceb0 100644
--- a/src/commands/settings/rolemenu.ts
+++ b/src/commands/settings/rolemenu.ts
@@ -1,25 +1,23 @@
-import Discord, { CommandInteraction, MessageActionRow, MessageButton } from "discord.js";
-import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
-import confirmationMessage from "../../utils/confirmationMessage.js";
-import getEmojiByName from "../../utils/getEmojiByName.js";
+import Discord, { CommandInteraction } from "discord.js";
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
-import client from "../../utils/client.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("rolemenu")
- .setDescription("rolemenu")// TODO
- .addRoleOption(option => option.setName("role").setDescription("The role to give after verifying")) // TODO
+ .setName("rolemenu")
+ .setDescription("rolemenu")// TODO
+ .addRoleOption(option => option.setName("role").setDescription("The role to give after verifying")); // FIXME FOR FUCK SAKE
-const callback = async (interaction: CommandInteraction): Promise<any> => {
-}
+const callback = async (interaction: CommandInteraction): Promise<void> => {
+ console.log("we changed the charger again because fuck you");
+ await interaction.reply("You're mum");
+};
-const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as Discord.GuildMember)
- if (!member.permissions.has("MANAGE_ROLES")) throw "You must have the *Manage Roles* permission to use this command"
+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";
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/settings/stats.ts b/src/commands/settings/stats.ts
index 10fba6b..4d61496 100644
--- a/src/commands/settings/stats.ts
+++ b/src/commands/settings/stats.ts
@@ -1,23 +1,23 @@
-import { LoadingEmbed } from './../../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "./../../utils/defaultEmbeds.js";
import Discord, { CommandInteraction, MessageActionRow, MessageSelectMenu } from "discord.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import confirmationMessage from "../../utils/confirmationMessage.js";
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
import client from "../../utils/client.js";
-import convertCurlyBracketString from '../../utils/convertCurlyBracketString.js';
+import convertCurlyBracketString from "../../utils/convertCurlyBracketString.js";
import {callback as statsChannelAddCallback} from "../../reflex/statsChannelUpdate.js";
-import singleNotify from '../../utils/singleNotify.js';
+import singleNotify from "../../utils/singleNotify.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("stats")
- .setDescription("Controls channels which update when someone joins or leaves the server")
- .addChannelOption(option => option.setName("channel").setDescription("The channel to modify"))
- .addStringOption(option => option.setName("name").setDescription("The new channel name | Enter any text or use the extra variables like {memberCount}").setAutocomplete(true))
+ .setName("stats")
+ .setDescription("Controls channels which update when someone joins or leaves the server")
+ .addChannelOption(option => option.setName("channel").setDescription("The channel to modify"))
+ .addStringOption(option => option.setName("name").setDescription("The new channel name | Enter any text or use the extra variables like {memberCount}").setAutocomplete(true));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- singleNotify("statsChannelDeleted", interaction.guild.id, true)
+ singleNotify("statsChannelDeleted", interaction.guild.id, true);
let m;
m = await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true});
let config = await client.database.guilds.read(interaction.guild.id);
@@ -29,72 +29,70 @@
.setTitle("Stats Channel")
.setDescription("You can only have 25 stats channels in a server")
.setStatus("Danger")
- ]})
+ ]});
}
try {
- channel = interaction.options.getChannel("channel")
+ channel = interaction.options.getChannel("channel");
} catch {
return await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("CHANNEL.TEXT.DELETE")
.setTitle("Stats Channel")
.setDescription("The channel you provided is not a valid channel")
.setStatus("Danger")
- ]})
+ ]});
}
- channel = channel as Discord.TextChannel
+ channel = channel as Discord.TextChannel;
if (channel.guild.id !== interaction.guild.id) {
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Stats Channel")
- .setDescription(`You must choose a channel in this server`)
+ .setDescription("You must choose a channel in this server")
.setStatus("Danger")
.setEmoji("CHANNEL.TEXT.DELETE")
]});
}
- let newName = await convertCurlyBracketString(interaction.options.getString("name"), null, null, interaction.guild.name, interaction.guild.members)
+ let newName = await convertCurlyBracketString(interaction.options.getString("name"), null, null, interaction.guild.name, interaction.guild.members);
if (interaction.options.getChannel("channel").type === "GUILD_TEXT") {
- newName = newName.toLowerCase().replace(/[\s]/g, "-")
+ newName = newName.toLowerCase().replace(/[\s]/g, "-");
}
- let confirmation = await new confirmationMessage(interaction)
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("CHANNEL.TEXT.EDIT")
.setTitle("Stats Channel")
.setDescription(`Are you sure you want to set <#${channel.id}> to a stats channel?\n\n*Preview: ${newName.replace(/^ +| $/g, "")}*`)
.setColor("Warning")
.setInverted(true)
- .send(true)
- if (confirmation.cancelled) return
+ .send(true);
+ if (confirmation.cancelled) return;
if (confirmation.success) {
try {
- let name = interaction.options.getString("name")
- let channel = interaction.options.getChannel("channel")
+ const name = interaction.options.getString("name");
+ const channel = interaction.options.getChannel("channel");
await client.database.guilds.write(interaction.guild.id, {[`stats.${channel.id}`]: {name: name, enabled: true}});
- const { log, NucleusColors, entry, renderUser, renderChannel } = client.logger
- try {
- let data = {
- meta:{
- type: 'statsChannelUpdate',
- displayName: 'Stats Channel Updated',
- calculateType: 'nucleusSettingsUpdated',
- color: NucleusColors.yellow,
- emoji: "CHANNEL.TEXT.EDIT",
- timestamp: new Date().getTime()
- },
- list: {
- memberId: entry(interaction.user.id, `\`${interaction.user.id}\``),
- changedBy: entry(interaction.user.id, renderUser(interaction.user)),
- channel: entry(channel.id, renderChannel(channel)),
- name: entry(interaction.options.getString("name"), `\`${interaction.options.getString("name")}\``)
- },
- hidden: {
- guild: interaction.guild.id
- }
+ const { log, NucleusColors, entry, renderUser, renderChannel } = client.logger;
+ const data = {
+ meta:{
+ type: "statsChannelUpdate",
+ displayName: "Stats Channel Updated",
+ calculateType: "nucleusSettingsUpdated",
+ color: NucleusColors.yellow,
+ emoji: "CHANNEL.TEXT.EDIT",
+ timestamp: new Date().getTime()
+ },
+ list: {
+ memberId: entry(interaction.user.id, `\`${interaction.user.id}\``),
+ changedBy: entry(interaction.user.id, renderUser(interaction.user)),
+ channel: entry(channel.id, renderChannel(channel)),
+ name: entry(interaction.options.getString("name"), `\`${interaction.options.getString("name")}\``)
+ },
+ hidden: {
+ guild: interaction.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
} catch (e) {
- console.log(e)
+ console.log(e);
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Stats Channel")
- .setDescription(`Something went wrong and the stats channel could not be set`)
+ .setDescription("Something went wrong and the stats channel could not be set")
.setStatus("Danger")
.setEmoji("CHANNEL.TEXT.DELETE")
], components: []});
@@ -102,7 +100,7 @@
} else {
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Stats Channel")
- .setDescription(`No changes were made`)
+ .setDescription("No changes were made")
.setStatus("Success")
.setEmoji("CHANNEL.TEXT.CREATE")
], components: []});
@@ -111,11 +109,11 @@
}
while (true) {
config = await client.database.guilds.read(interaction.guild.id);
- let stats = config.getKey("stats")
- let selectMenu = new MessageSelectMenu()
+ const stats = config.getKey("stats");
+ const selectMenu = new MessageSelectMenu()
.setCustomId("remove")
.setMinValues(1)
- .setMaxValues(Math.max(1, Object.keys(stats).length))
+ .setMaxValues(Math.max(1, Object.keys(stats).length));
await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Stats Channel")
.setDescription("The following channels update when someone joins or leaves the server. You can select a channel to remove it from the list.")
@@ -126,30 +124,30 @@
selectMenu.setPlaceholder("Select a stats channel to remove, stopping it updating").addOptions(Object.keys(stats).map(key => ({
label: interaction.guild.channels.cache.get(key).name,
value: key,
- description: `${stats[key].name}`,
+ description: `${stats[key].name}`
})))
] : [selectMenu.setPlaceholder("The server has no stats channels").setDisabled(true).setOptions([
{label: "*Placeholder*", value: "placeholder", description: "No stats channels"}
])])
- ]})
+ ]});
let i;
try {
i = await m.awaitMessageComponent({ time: 300000 });
- } catch (e) { break }
- i.deferUpdate()
+ } catch (e) { break; }
+ i.deferUpdate();
if (i.customId === "remove") {
- let toRemove = i.values;
+ const toRemove = i.values;
await client.database.guilds.write(interaction.guild.id, null, toRemove.map(k => `stats.${k}`));
}
}
await interaction.editReply({embeds: [m.embeds[0].setFooter({text: "Message closed"})], components: []});
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as Discord.GuildMember)
- if (!member.permissions.has("MANAGE_CHANNELS")) throw "You must have the *Manage Channels* permission to use this command"
+ 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";
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/settings/tickets.ts b/src/commands/settings/tickets.ts
index 8ebcf30..3d1901b 100644
--- a/src/commands/settings/tickets.ts
+++ b/src/commands/settings/tickets.ts
@@ -1,14 +1,14 @@
-import { LoadingEmbed } from './../../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "./../../utils/defaultEmbeds.js";
import getEmojiByName from "../../utils/getEmojiByName.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import confirmationMessage from "../../utils/confirmationMessage.js";
import Discord, { CommandInteraction, MessageActionRow, MessageButton, MessageSelectMenu, TextInputComponent } from "discord.js";
import { SelectMenuOption, SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
-import { ChannelType } from 'discord-api-types';
+import { ChannelType } from "discord-api-types";
import client from "../../utils/client.js";
import { toHexInteger, toHexArray, tickets as ticketTypes } from "../../utils/calculate.js";
-import { capitalize } from '../../utils/generateKeyValueList.js';
+import { capitalize } from "../../utils/generateKeyValueList.js";
import { modalInteractionCollector } from "../../utils/dualCollector.js";
const command = (builder: SlashCommandSubcommandBuilder) => builder
@@ -18,24 +18,24 @@
.addChoices([["Yes", "yes"], ["No", "no"]]))
.addChannelOption(option => option.setName("category").setDescription("The category where tickets are created").addChannelType(ChannelType.GuildCategory).setRequired(false))
.addNumberOption(option => option.setName("maxticketsperuser").setDescription("The maximum amount of tickets a user can create | Default: 5").setRequired(false).setMinValue(1))
- .addRoleOption(option => option.setName("supportrole").setDescription("This role will have view access to all tickets and will be pinged when a ticket is created").setRequired(false))
+ .addRoleOption(option => option.setName("supportrole").setDescription("This role will have view access to all tickets and will be pinged when a ticket is created").setRequired(false));
const callback = async (interaction: CommandInteraction): Promise<any> => {
let m;
- m = await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true})
- let options = {
+ m = await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true});
+ const options = {
enabled: interaction.options.getString("enabled") as string | boolean,
category: interaction.options.getChannel("category"),
maxtickets: interaction.options.getNumber("maxticketsperuser"),
supportping: interaction.options.getRole("supportrole")
- }
- console.log(m)
+ };
+ console.log(m);
if (options.enabled !== null || options.category || options.maxtickets || options.supportping) {
options.enabled = options.enabled === "yes" ? true : false;
if (options.category) {
- let channel
+ let channel;
try {
- channel = interaction.guild.channels.cache.get(options.category.id)
+ channel = interaction.guild.channels.cache.get(options.category.id);
} catch {
return await interaction.editReply({
embeds: [new EmojiEmbed()
@@ -44,13 +44,13 @@
.setDescription("The channel you provided is not a valid category")
.setStatus("Danger")
]
- })
+ });
}
- channel = channel as Discord.CategoryChannel
+ channel = channel as Discord.CategoryChannel;
if (channel.guild.id !== interaction.guild.id) return interaction.editReply({
embeds: [new EmojiEmbed()
.setTitle("Tickets > Category")
- .setDescription(`You must choose a category in this server`)
+ .setDescription("You must choose a category in this server")
.setStatus("Danger")
.setEmoji("CHANNEL.TEXT.DELETE")
]
@@ -60,16 +60,16 @@
if (options.maxtickets < 1) return interaction.editReply({
embeds: [new EmojiEmbed()
.setTitle("Tickets > Max Tickets")
- .setDescription(`You must choose a number greater than 0`)
+ .setDescription("You must choose a number greater than 0")
.setStatus("Danger")
.setEmoji("CHANNEL.TEXT.DELETE")
]
});
}
- let role
+ let role;
if (options.supportping) {
try {
- role = interaction.guild.roles.cache.get(options.supportping.id)
+ role = interaction.guild.roles.cache.get(options.supportping.id);
} catch {
return await interaction.editReply({
embeds: [new EmojiEmbed()
@@ -78,20 +78,20 @@
.setDescription("The role you provided is not a valid role")
.setStatus("Danger")
]
- })
+ });
}
- role = role as Discord.Role
+ role = role as Discord.Role;
if (role.guild.id !== interaction.guild.id) return interaction.editReply({
embeds: [new EmojiEmbed()
.setTitle("Tickets > Support Ping")
- .setDescription(`You must choose a role in this server`)
+ .setDescription("You must choose a role in this server")
.setStatus("Danger")
.setEmoji("GUILD.ROLE.DELETE")
]
});
}
- let confirmation = await new confirmationMessage(interaction)
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("GUILD.TICKET.ARCHIVED")
.setTitle("Tickets")
.setDescription(
@@ -99,26 +99,26 @@
(options.maxtickets ? `**Max Tickets:** ${options.maxtickets}\n` : "") +
(options.supportping ? `**Support Ping:** ${options.supportping.name}\n` : "") +
(options.enabled !== null ? `**Enabled:** ${options.enabled ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`
- }\n` : "") +
- `\nAre you sure you want to apply these settings?`
+ }\n` : "") +
+ "\nAre you sure you want to apply these settings?"
)
.setColor("Warning")
.setInverted(true)
- .send(true)
- if (confirmation.cancelled) return
+ .send(true);
+ if (confirmation.cancelled) return;
if (confirmation.success) {
- let toUpdate = {}
- 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
+ const toUpdate = {};
+ 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: [new EmojiEmbed()
.setTitle("Tickets")
- .setDescription(`Something went wrong and the staff notifications channel could not be set`)
+ .setDescription("Something went wrong and the staff notifications channel could not be set")
.setStatus("Danger")
.setEmoji("GUILD.TICKET.DELETE")
], components: []
@@ -128,7 +128,7 @@
return interaction.editReply({
embeds: [new EmojiEmbed()
.setTitle("Tickets")
- .setDescription(`No changes were made`)
+ .setDescription("No changes were made")
.setStatus("Success")
.setEmoji("GUILD.TICKET.OPEN")
], components: []
@@ -136,7 +136,7 @@
}
}
let data = await client.database.guilds.read(interaction.guild.id);
- data.tickets.customTypes = (data.tickets.customTypes || []).filter((v, i, a) => a.indexOf(v) === i)
+ data.tickets.customTypes = (data.tickets.customTypes || []).filter((v, i, a) => a.indexOf(v) === i);
let lastClicked = "";
let embed;
data = {
@@ -147,7 +147,7 @@
useCustom: data.tickets.useCustom,
types: data.tickets.types,
customTypes: data.tickets.customTypes
- }
+ };
while (true) {
embed = new EmojiEmbed()
.setTitle("Tickets")
@@ -161,7 +161,7 @@
`${getEmojiByName("TICKETS.REPORT")} *Indicates a setting stopping tickets from being used*`
)
.setStatus("Success")
- .setEmoji("GUILD.TICKET.OPEN")
+ .setEmoji("GUILD.TICKET.OPEN");
m = await interaction.editReply({
embeds: [embed], components: [new MessageActionRow().addComponents([
new MessageButton()
@@ -186,7 +186,7 @@
.setEmoji(getEmojiByName("CONTROL.CROSS", "id"))
.setStyle("DANGER")
.setCustomId("clearSupportPing")
- .setDisabled(data.supportRole === null),
+ .setDisabled(data.supportRole === null)
]), new MessageActionRow().addComponents([
new MessageButton()
.setLabel("Manage types")
@@ -197,40 +197,40 @@
.setLabel("Add create ticket button")
.setEmoji(getEmojiByName("TICKETS.SUGGESTION", "id"))
.setStyle("PRIMARY")
- .setCustomId("send"),
+ .setCustomId("send")
])]
});
let i;
try {
i = await m.awaitMessageComponent({ time: 300000 });
- } catch (e) { break }
- i.deferUpdate()
+ } catch (e) { break; }
+ i.deferUpdate();
if (i.component.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.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.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.customId === "send") {
const ticketMessages = [
{label: "Create ticket", description: "Click the button below to create a ticket"},
{label: "Issues, questions or feedback?", description: "Click below to open a ticket and get help from our staff team"},
- {label: "Contact Us", description: "Click the button below to speak to us privately"},
- ]
+ {label: "Contact Us", description: "Click the button below to speak to us privately"}
+ ];
while (true) {
- let enabled = data.enabled && data.category !== null;
+ const enabled = data.enabled && data.category !== null;
await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Ticket Button")
.setDescription("Select a message template to send in this channel")
@@ -240,8 +240,8 @@
], components: [
new MessageActionRow().addComponents([
new MessageSelectMenu().setOptions(ticketMessages.map((t: {label: string, description: string, value?: string}, index) => {
- t.value = index.toString(); return t as {value: string, label: string, description: string}
- })).setCustomId("template").setMaxValues(1).setMinValues(1).setPlaceholder("Select a message template"),
+ t.value = index.toString(); return t as {value: string, label: string, description: string};
+ })).setCustomId("template").setMaxValues(1).setMinValues(1).setPlaceholder("Select a message template")
]),
new MessageActionRow().addComponents([
new MessageButton()
@@ -263,9 +263,9 @@
let i;
try {
i = await m.awaitMessageComponent({time: 300000});
- } catch(e) { break }
+ } catch(e) { break; }
if (i.component.customId === "template") {
- i.deferUpdate()
+ i.deferUpdate();
await interaction.channel.send({embeds: [new EmojiEmbed()
.setTitle(ticketMessages[parseInt(i.values[0])].label)
.setDescription(ticketMessages[parseInt(i.values[0])].description)
@@ -277,18 +277,18 @@
.setStyle("SUCCESS")
.setCustomId("createticket")
])]});
- break
+ break;
} else if (i.component.customId === "blank") {
- i.deferUpdate()
+ i.deferUpdate();
await interaction.channel.send({components: [new MessageActionRow().addComponents([new MessageButton()
.setLabel("Create Ticket")
.setEmoji(getEmojiByName("TICKETS.SUGGESTION", "id"))
.setStyle("SUCCESS")
.setCustomId("createticket")
])]});
- break
+ break;
} else if (i.component.customId === "custom") {
- await i.showModal(new Discord.Modal().setCustomId("modal").setTitle(`Enter embed details`).addComponents(
+ await i.showModal(new Discord.Modal().setCustomId("modal").setTitle("Enter embed details").addComponents(
new MessageActionRow<TextInputComponent>().addComponents(new TextInputComponent()
.setCustomId("title")
.setLabel("Title")
@@ -303,7 +303,7 @@
.setRequired(true)
.setStyle("PARAGRAPH")
)
- ))
+ ));
await interaction.editReply({
embeds: [new EmojiEmbed()
.setTitle("Ticket Button")
@@ -319,11 +319,11 @@
});
let out;
try {
- out = await modalInteractionCollector(m, (m) => m.channel.id === interaction.channel.id, (m) => m.customId === "modify")
- } catch (e) { break }
+ out = await modalInteractionCollector(m, (m) => m.channel.id === interaction.channel.id, (m) => m.customId === "modify");
+ } catch (e) { break; }
if (out.fields) {
- let title = out.fields.getTextInputValue("title");
- let description = out.fields.getTextInputValue("description");
+ const title = out.fields.getTextInputValue("title");
+ const description = out.fields.getTextInputValue("description");
await interaction.channel.send({embeds: [new EmojiEmbed()
.setTitle(title)
.setDescription(description)
@@ -335,26 +335,26 @@
.setStyle("SUCCESS")
.setCustomId("createticket")
])]});
- break
- } else { continue }
+ break;
+ } else { continue; }
}
}
} else if (i.component.customId === "enabled") {
- await client.database.guilds.write(interaction.guild.id, { "tickets.enabled": !data.enabled })
+ await client.database.guilds.write(interaction.guild.id, { "tickets.enabled": !data.enabled });
data.enabled = !data.enabled;
} else if (i.component.customId === "manageTypes") {
data = await manageTypes(interaction, data, m);
} else {
- break
+ break;
}
}
await interaction.editReply({ embeds: [embed.setFooter({ text: "Message closed" })], components: [] });
-}
+};
async function manageTypes(interaction, data, m) {
while (true) {
if (data.useCustom) {
- let customTypes = data.customTypes;
+ const customTypes = data.customTypes;
await interaction.editReply({
embeds: [new EmojiEmbed()
.setTitle("Tickets > Types")
@@ -393,29 +393,29 @@
new MessageButton()
.setLabel("Switch to default types")
.setStyle("SECONDARY")
- .setCustomId("switchToDefault"),
+ .setCustomId("switchToDefault")
])
])
});
} else {
- let inUse = toHexArray(data.types, ticketTypes)
- let options = [];
+ const inUse = toHexArray(data.types, ticketTypes);
+ const options = [];
ticketTypes.forEach(type => {
options.push(new SelectMenuOption({
label: capitalize(type),
value: type,
emoji: client.emojis.cache.get(getEmojiByName(`TICKETS.${type.toUpperCase()}`, "id")),
default: inUse.includes(type)
- }))
- })
- let selectPane = new MessageActionRow().addComponents([
+ }));
+ });
+ const selectPane = new MessageActionRow().addComponents([
new Discord.MessageSelectMenu()
.addOptions(options)
.setCustomId("types")
.setMaxValues(ticketTypes.length)
.setMinValues(1)
.setPlaceholder("Select types to use")
- ])
+ ]);
await interaction.editReply({
embeds: [new EmojiEmbed()
.setTitle("Tickets > Types")
@@ -437,7 +437,7 @@
new MessageButton()
.setLabel("Switch to custom types")
.setStyle("SECONDARY")
- .setCustomId("switchToCustom"),
+ .setCustomId("switchToCustom")
])
]
});
@@ -445,20 +445,20 @@
let i;
try {
i = await m.awaitMessageComponent({ time: 300000 });
- } catch (e) { break }
+ } catch (e) { break; }
if (i.component.customId === "types") {
- i.deferUpdate()
- let types = toHexInteger(i.values, ticketTypes);
- await client.database.guilds.write(interaction.guild.id, { "tickets.types": types })
+ i.deferUpdate();
+ const types = toHexInteger(i.values, ticketTypes);
+ await client.database.guilds.write(interaction.guild.id, { "tickets.types": types });
data.types = types;
} else if (i.component.customId === "removeTypes") {
- i.deferUpdate()
- let types = i.values
+ i.deferUpdate();
+ const types = i.values;
let customTypes = data.customTypes;
if (customTypes) {
customTypes = customTypes.filter((t) => !types.includes(t));
customTypes = customTypes.length > 0 ? customTypes : null;
- await client.database.guilds.write(interaction.guild.id, { "tickets.customTypes": customTypes })
+ await client.database.guilds.write(interaction.guild.id, { "tickets.customTypes": customTypes });
data.customTypes = customTypes;
}
} else if (i.component.customId === "addType") {
@@ -472,7 +472,7 @@
.setRequired(true)
.setStyle("SHORT")
)
- ))
+ ));
await interaction.editReply({
embeds: [new EmojiEmbed()
.setTitle("Tickets > Types")
@@ -488,42 +488,42 @@
});
let out;
try {
- out = await modalInteractionCollector(m, (m) => m.channel.id === interaction.channel.id, (m) => m.customId === "addType")
- } catch (e) { continue }
+ out = await modalInteractionCollector(m, (m) => m.channel.id === interaction.channel.id, (m) => m.customId === "addType");
+ } catch (e) { continue; }
if (out.fields) {
let toAdd = out.fields.getTextInputValue("type");
- if (!toAdd) { continue }
- toAdd = toAdd.substring(0, 80)
+ if (!toAdd) { continue; }
+ toAdd = toAdd.substring(0, 80);
try {
- await client.database.guilds.append(interaction.guild.id, "tickets.customTypes", toAdd)
- } catch { continue }
+ await client.database.guilds.append(interaction.guild.id, "tickets.customTypes", toAdd);
+ } catch { continue; }
data.customTypes = data.customTypes || [];
if (!data.customTypes.includes(toAdd)) {
data.customTypes.push(toAdd);
}
- } else { continue }
+ } else { continue; }
} else if (i.component.customId === "switchToDefault") {
- i.deferUpdate()
- await client.database.guilds.write(interaction.guild.id, { "tickets.useCustom": false }, [])
+ i.deferUpdate();
+ await client.database.guilds.write(interaction.guild.id, { "tickets.useCustom": false }, []);
data.useCustom = false;
} else if (i.component.customId === "switchToCustom") {
- i.deferUpdate()
- await client.database.guilds.write(interaction.guild.id, { "tickets.useCustom": true }, [])
+ i.deferUpdate();
+ await client.database.guilds.write(interaction.guild.id, { "tickets.useCustom": true }, []);
data.useCustom = true;
} else {
- i.deferUpdate()
- break
+ i.deferUpdate();
+ break;
}
}
- return data
+ return data;
}
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as Discord.GuildMember)
- if (!member.permissions.has("MANAGE_GUILD")) throw "You must have the *Manage Server* permission to use this command"
+ 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";
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/settings/verify.ts b/src/commands/settings/verify.ts
index a77f2f4..c100d05 100644
--- a/src/commands/settings/verify.ts
+++ b/src/commands/settings/verify.ts
@@ -1,4 +1,4 @@
-import { LoadingEmbed } from './../../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "./../../utils/defaultEmbeds.js";
import Discord, { CommandInteraction, Emoji, MessageActionRow, MessageButton, MessageSelectMenu, TextInputComponent } from "discord.js";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import confirmationMessage from "../../utils/confirmationMessage.js";
@@ -6,76 +6,74 @@
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
import client from "../../utils/client.js";
-import { modalInteractionCollector } from '../../utils/dualCollector.js';
+import { modalInteractionCollector } from "../../utils/dualCollector.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("verify")
- .setDescription("Manage the role given after typing /verify")
- .addRoleOption(option => option.setName("role").setDescription("The role to give after verifying").setRequired(false))
+ .setName("verify")
+ .setDescription("Manage the role given after typing /verify")
+ .addRoleOption(option => option.setName("role").setDescription("The role to give after verifying").setRequired(false));
const callback = async (interaction: CommandInteraction): Promise<any> => {
let m;
m = await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true});
if (interaction.options.getRole("role")) {
- let role
+ let role;
try {
- role = interaction.options.getRole("role")
+ role = interaction.options.getRole("role");
} catch {
return await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("GUILD.ROLES.DELETE")
.setTitle("Verify Role")
.setDescription("The role you provided is not a valid role")
.setStatus("Danger")
- ]})
+ ]});
}
- role = role as Discord.Role
+ role = role as Discord.Role;
if (role.guild.id !== interaction.guild.id) {
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Verify Role")
- .setDescription(`You must choose a role in this server`)
+ .setDescription("You must choose a role in this server")
.setStatus("Danger")
.setEmoji("GUILD.ROLES.DELETE")
]});
}
- let confirmation = await new confirmationMessage(interaction)
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("GUILD.ROLES.EDIT")
.setTitle("Verify Role")
.setDescription(`Are you sure you want to set the verify role to <@&${role.id}>?`)
.setColor("Warning")
.setInverted(true)
- .send(true)
- if (confirmation.cancelled) return
+ .send(true);
+ if (confirmation.cancelled) return;
if (confirmation.success) {
try {
await client.database.guilds.write(interaction.guild.id, {"verify.role": role.id, "verify.enabled": true});
- const { log, NucleusColors, entry, renderUser, renderRole } = client.logger
- try {
- let data = {
- meta:{
- type: 'verifyRoleChanged',
- displayName: 'Verify Role Changed',
- calculateType: 'nucleusSettingsUpdated',
- color: NucleusColors.green,
- emoji: "CONTROL.BLOCKTICK",
- timestamp: new Date().getTime()
- },
- list: {
- memberId: entry(interaction.user.id, `\`${interaction.user.id}\``),
- changedBy: entry(interaction.user.id, renderUser(interaction.user)),
- role: entry(role.id, renderRole(role)),
- },
- hidden: {
- guild: interaction.guild.id
- }
+ const { log, NucleusColors, entry, renderUser, renderRole } = client.logger;
+ const data = {
+ meta:{
+ type: "verifyRoleChanged",
+ displayName: "Verify Role Changed",
+ calculateType: "nucleusSettingsUpdated",
+ color: NucleusColors.green,
+ emoji: "CONTROL.BLOCKTICK",
+ timestamp: new Date().getTime()
+ },
+ list: {
+ memberId: entry(interaction.user.id, `\`${interaction.user.id}\``),
+ changedBy: entry(interaction.user.id, renderUser(interaction.user)),
+ role: entry(role.id, renderRole(role))
+ },
+ hidden: {
+ guild: interaction.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
} catch (e) {
- console.log(e)
+ console.log(e);
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Verify Role")
- .setDescription(`Something went wrong while setting the verify role`)
+ .setDescription("Something went wrong while setting the verify role")
.setStatus("Danger")
.setEmoji("GUILD.ROLES.DELETE")
], components: []});
@@ -83,19 +81,19 @@
} else {
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Verify Role")
- .setDescription(`No changes were made`)
+ .setDescription("No changes were made")
.setStatus("Success")
.setEmoji("GUILD.ROLES.CREATE")
], components: []});
}
}
let clicks = 0;
- let 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({embeds: [new EmojiEmbed()
.setTitle("Verify Role")
- .setDescription(role ? `Your verify role is currently set to <@&${role}>` : `You have not set a verify role`)
+ .setDescription(role ? `Your verify role is currently set to <@&${role}>` : "You have not set a verify role")
.setStatus("Success")
.setEmoji("GUILD.ROLES.CREATE")
], components: [new MessageActionRow().addComponents([
@@ -114,21 +112,21 @@
let i;
try {
i = await m.awaitMessageComponent({time: 300000});
- } catch(e) { break }
- i.deferUpdate()
+ } catch(e) { break; }
+ i.deferUpdate();
if (i.component.customId === "clear") {
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.customId === "send") {
const verifyMessages = [
{label: "Verify", description: "Click the button below to get verified"},
{label: "Get verified", description: "To get access to the rest of the server, click the button below"},
- {label: "Ready to verify?", description: "Click the button below to verify yourself"},
- ]
+ {label: "Ready to verify?", description: "Click the button below to verify yourself"}
+ ];
while (true) {
await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Verify Button")
@@ -139,8 +137,8 @@
], components: [
new MessageActionRow().addComponents([
new MessageSelectMenu().setOptions(verifyMessages.map((t: {label: string, description: string, value?: string}, index) => {
- t.value = index.toString(); return t as {value: string, label: string, description: string}
- })).setCustomId("template").setMaxValues(1).setMinValues(1).setPlaceholder("Select a message template"),
+ t.value = index.toString(); return t as {value: string, label: string, description: string};
+ })).setCustomId("template").setMaxValues(1).setMinValues(1).setPlaceholder("Select a message template")
]),
new MessageActionRow().addComponents([
new MessageButton()
@@ -162,9 +160,9 @@
let i;
try {
i = await m.awaitMessageComponent({time: 300000});
- } catch(e) { break }
+ } catch(e) { break; }
if (i.component.customId === "template") {
- i.deferUpdate()
+ i.deferUpdate();
await interaction.channel.send({embeds: [new EmojiEmbed()
.setTitle(verifyMessages[parseInt(i.values[0])].label)
.setDescription(verifyMessages[parseInt(i.values[0])].description)
@@ -176,18 +174,18 @@
.setStyle("SUCCESS")
.setCustomId("verifybutton")
])]});
- break
+ break;
} else if (i.component.customId === "blank") {
- i.deferUpdate()
+ i.deferUpdate();
await interaction.channel.send({components: [new MessageActionRow().addComponents([new MessageButton()
.setLabel("Verify")
.setEmoji(getEmojiByName("CONTROL.TICK", "id"))
.setStyle("SUCCESS")
.setCustomId("verifybutton")
])]});
- break
+ break;
} else if (i.component.customId === "custom") {
- await i.showModal(new Discord.Modal().setCustomId("modal").setTitle(`Enter embed details`).addComponents(
+ await i.showModal(new Discord.Modal().setCustomId("modal").setTitle("Enter embed details").addComponents(
new MessageActionRow<TextInputComponent>().addComponents(new TextInputComponent()
.setCustomId("title")
.setLabel("Title")
@@ -202,7 +200,7 @@
.setRequired(true)
.setStyle("PARAGRAPH")
)
- ))
+ ));
await interaction.editReply({
embeds: [new EmojiEmbed()
.setTitle("Verify Button")
@@ -218,11 +216,11 @@
});
let out;
try {
- out = await modalInteractionCollector(m, (m) => m.channel.id === interaction.channel.id, (m) => m.customId === "modify")
- } catch (e) { break }
+ out = await modalInteractionCollector(m, (m) => m.channel.id === interaction.channel.id, (m) => m.customId === "modify");
+ } catch (e) { break; }
if (out.fields) {
- let title = out.fields.getTextInputValue("title");
- let description = out.fields.getTextInputValue("description");
+ const title = out.fields.getTextInputValue("title");
+ const description = out.fields.getTextInputValue("description");
await interaction.channel.send({embeds: [new EmojiEmbed()
.setTitle(title)
.setDescription(description)
@@ -234,23 +232,23 @@
.setStyle("SUCCESS")
.setCustomId("verifybutton")
])]});
- break
- } else { continue }
+ break;
+ } else { continue; }
}
}
} else {
- i.deferUpdate()
+ i.deferUpdate();
break;
}
}
await interaction.editReply({embeds: [m.embeds[0].setFooter({text: "Message closed"})], components: []});
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as Discord.GuildMember)
- if (!member.permissions.has("MANAGE_GUILD")) throw "You must have the *Manage Server* permission to use this command"
+ 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";
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/settings/welcome.ts b/src/commands/settings/welcome.ts
index 1a107ed..34ac292 100644
--- a/src/commands/settings/welcome.ts
+++ b/src/commands/settings/welcome.ts
@@ -1,109 +1,107 @@
-import { LoadingEmbed } from './../../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "./../../utils/defaultEmbeds.js";
import Discord, { CommandInteraction, MessageActionRow, MessageButton, MessageSelectMenu } from "discord.js";
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
-import client from '../../utils/client.js';
-import confirmationMessage from '../../utils/confirmationMessage.js';
-import generateKeyValueList from '../../utils/generateKeyValueList.js';
-import { ChannelType } from 'discord-api-types';
-import getEmojiByName from '../../utils/getEmojiByName.js';
+import client from "../../utils/client.js";
+import confirmationMessage from "../../utils/confirmationMessage.js";
+import generateKeyValueList from "../../utils/generateKeyValueList.js";
+import { ChannelType } from "discord-api-types";
+import getEmojiByName from "../../utils/getEmojiByName.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("welcome")
- .setDescription("Messages and roles sent or given when someone joins the server")
- .addStringOption(option => option.setName("message").setDescription("The message to send when someone joins the server").setAutocomplete(true))
- .addRoleOption(option => option.setName("role").setDescription("The role given when someone joins the server"))
- .addRoleOption(option => option.setName("ping").setDescription("The role pinged when someone joins the server"))
- .addChannelOption(option => option.setName("channel").setDescription("The channel the welcome message should be sent to").addChannelTypes([
- ChannelType.GuildText, ChannelType.GuildNews
- ]))
+ .setName("welcome")
+ .setDescription("Messages and roles sent or given when someone joins the server")
+ .addStringOption(option => option.setName("message").setDescription("The message to send when someone joins the server").setAutocomplete(true))
+ .addRoleOption(option => option.setName("role").setDescription("The role given when someone joins the server"))
+ .addRoleOption(option => option.setName("ping").setDescription("The role pinged when someone joins the server"))
+ .addChannelOption(option => option.setName("channel").setDescription("The channel the welcome message should be sent to").addChannelTypes([
+ ChannelType.GuildText, ChannelType.GuildNews
+ ]));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- const { renderRole, renderChannel, log, NucleusColors, entry, renderUser } = client.logger
+ const { renderRole, renderChannel, log, NucleusColors, entry, renderUser } = client.logger;
await interaction.reply({embeds: LoadingEmbed, fetchReply: true, ephemeral: true});
let m;
if (interaction.options.getRole("role") || interaction.options.getChannel("channel") || interaction.options.getString("message")) {
let role;
let ping;
- let message = interaction.options.getString("message");
+ const message = interaction.options.getString("message");
try {
- role = interaction.options.getRole("role")
- ping = interaction.options.getRole("ping")
+ role = interaction.options.getRole("role");
+ ping = interaction.options.getRole("ping");
} catch {
return await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("GUILD.ROLES.DELETE")
.setTitle("Welcome Events")
.setDescription("The role you provided is not a valid role")
.setStatus("Danger")
- ]})
+ ]});
}
let channel;
try {
- channel = interaction.options.getChannel("channel")
+ channel = interaction.options.getChannel("channel");
} catch {
return await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("GUILD.ROLES.DELETE")
.setTitle("Welcome Events")
.setDescription("The channel you provided is not a valid channel")
.setStatus("Danger")
- ]})
+ ]});
}
- role = role as Discord.Role
- ping = ping as Discord.Role
- channel = channel as Discord.TextChannel
- let options = {}
- if (role) options["role"] = renderRole(role)
- if (ping) options["ping"] = renderRole(ping)
- if (channel) options["channel"] = renderChannel(channel)
- if (message) options["message"] = "\n> " + message
- let confirmation = await new confirmationMessage(interaction)
+ role = role as Discord.Role;
+ ping = ping as Discord.Role;
+ channel = channel as Discord.TextChannel;
+ const options = {};
+ if (role) options["role"] = renderRole(role);
+ if (ping) options["ping"] = renderRole(ping);
+ if (channel) options["channel"] = renderChannel(channel);
+ if (message) options["message"] = "\n> " + message;
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("GUILD.ROLES.EDIT")
.setTitle("Welcome Events")
.setDescription(generateKeyValueList(options))
.setColor("Warning")
.setInverted(true)
- .send(true)
- if (confirmation.cancelled) return
+ .send(true);
+ if (confirmation.cancelled) return;
if (confirmation.success) {
try {
- let toChange = {}
- if (role) toChange["welcome.role"] = role.id
- if (ping) toChange["welcome.ping"] = ping.id
- if (channel) toChange["welcome.channel"] = channel.id
- if (message) toChange["welcome.message"] = message
+ const toChange = {};
+ if (role) toChange["welcome.role"] = role.id;
+ if (ping) toChange["welcome.ping"] = ping.id;
+ if (channel) toChange["welcome.channel"] = channel.id;
+ if (message) toChange["welcome.message"] = message;
await client.database.guilds.write(interaction.guild.id, toChange);
- let list = {
+ const list = {
memberId: entry(interaction.user.id, `\`${interaction.user.id}\``),
changedBy: entry(interaction.user.id, renderUser(interaction.user))
- }
- if (role) list["role"] = entry(role.id, renderRole(role))
- if (ping) list["ping"] = entry(ping.id, renderRole(ping))
- if (channel) list["channel"] = entry(channel.id, renderChannel(channel.id))
- if (message) list["message"] = entry(message, `\`${message}\``)
- try {
- let data = {
- meta:{
- type: 'welcomeSettingsUpdated',
- displayName: 'Welcome Settings Changed',
- calculateType: 'nucleusSettingsUpdated',
- color: NucleusColors.green,
- emoji: "CONTROL.BLOCKTICK",
- timestamp: new Date().getTime()
- },
- list: list,
- hidden: {
- guild: interaction.guild.id
- }
+ };
+ if (role) list["role"] = entry(role.id, renderRole(role));
+ if (ping) list["ping"] = entry(ping.id, renderRole(ping));
+ if (channel) list["channel"] = entry(channel.id, renderChannel(channel.id));
+ if (message) list["message"] = entry(message, `\`${message}\``);
+ const data = {
+ meta:{
+ type: "welcomeSettingsUpdated",
+ displayName: "Welcome Settings Changed",
+ calculateType: "nucleusSettingsUpdated",
+ color: NucleusColors.green,
+ emoji: "CONTROL.BLOCKTICK",
+ timestamp: new Date().getTime()
+ },
+ list: list,
+ hidden: {
+ guild: interaction.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
} catch (e) {
- console.log(e)
+ console.log(e);
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Welcome Events")
- .setDescription(`Something went wrong while updating welcome settings`)
+ .setDescription("Something went wrong while updating welcome settings")
.setStatus("Danger")
.setEmoji("GUILD.ROLES.DELETE")
], components: []});
@@ -111,15 +109,15 @@
} else {
return interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Welcome Events")
- .setDescription(`No changes were made`)
+ .setDescription("No changes were made")
.setStatus("Success")
.setEmoji("GUILD.ROLES.CREATE")
], components: []});
}
}
- let lastClicked = null
+ let lastClicked = null;
while (true) {
- let config = await client.database.guilds.read(interaction.guild.id)
+ const config = await client.database.guilds.read(interaction.guild.id);
m = await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Welcome Events")
.setDescription(
@@ -162,47 +160,47 @@
.setDisabled(config.welcome.channel == "dm")
.setStyle("SECONDARY")
])
- ]})
+ ]});
let i;
try {
i = await m.awaitMessageComponent({ time: 300000 });
} catch (e) {
- break
+ break;
}
- i.deferUpdate()
+ i.deferUpdate();
if (i.customId == "clear-message") {
if (lastClicked == "clear-message") {
await client.database.guilds.write(interaction.guild.id, {"welcome.message": null});
- lastClicked = null
- } else { lastClicked = "clear-message" }
+ lastClicked = null;
+ } else { lastClicked = "clear-message"; }
} else if (i.customId == "clear-role") {
if (lastClicked == "clear-role") {
await client.database.guilds.write(interaction.guild.id, {"welcome.role": null});
- lastClicked = null
- } else { lastClicked = "clear-role" }
+ lastClicked = null;
+ } else { lastClicked = "clear-role"; }
} else if (i.customId == "clear-ping") {
if (lastClicked == "clear-ping") {
await client.database.guilds.write(interaction.guild.id, {"welcome.ping": null});
- lastClicked = null
- } else { lastClicked = "clear-ping" }
+ lastClicked = null;
+ } else { lastClicked = "clear-ping"; }
} else if (i.customId == "clear-channel") {
if (lastClicked == "clear-channel") {
await client.database.guilds.write(interaction.guild.id, {"welcome.channel": null});
- lastClicked = null
- } else { lastClicked = "clear-channel" }
+ lastClicked = null;
+ } else { lastClicked = "clear-channel"; }
} else if (i.customId == "set-channel-dm") {
await client.database.guilds.write(interaction.guild.id, {"welcome.channel": "dm"});
- lastClicked = null
+ lastClicked = null;
}
}
await interaction.editReply({embeds: [m.embeds[0].setFooter({text: "Message closed"})], components: []});
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as Discord.GuildMember)
- if (!member.permissions.has("MANAGE_GUILD")) throw "You must have the *Manage Server* permission to use this command"
+ 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";
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/tag.ts b/src/commands/tag.ts
index 70d5a75..4cae8e3 100644
--- a/src/commands/tag.ts
+++ b/src/commands/tag.ts
@@ -1,35 +1,35 @@
import { AutocompleteInteraction, CommandInteraction, MessageActionRow, MessageButton } from "discord.js";
import { SlashCommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
-import client from "../utils/client.js"
+import client from "../utils/client.js";
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
const command = new SlashCommandBuilder()
.setName("tag")
.setDescription("Get and manage the servers tags")
- .addStringOption(o => o.setName("tag").setDescription("The tag to get").setAutocomplete(true).setRequired(true))
+ .addStringOption(o => o.setName("tag").setDescription("The tag to get").setAutocomplete(true).setRequired(true));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- const config = await client.database.guilds.read(interaction.guild.id)
- const tags = config.getKey("tags")
- const tag = tags[interaction.options.getString("tag")]
+ const config = await client.database.guilds.read(interaction.guild.id);
+ const tags = config.getKey("tags");
+ const tag = tags[interaction.options.getString("tag")];
if (!tag) {
return await interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Tag")
.setDescription(`Tag \`${interaction.options.getString("tag")}\` does not exist`)
.setEmoji("PUNISH.NICKNAME.RED")
.setStatus("Danger")
- ], ephemeral: true})
+ ], ephemeral: true});
}
- let url = ""
- let components = []
+ let url = "";
+ let components = [];
if (tag.match(/^(http|https):\/\/[^ "]+$/)) {
- url = tag
+ url = tag;
components = [new MessageActionRow().addComponents([new MessageButton()
.setLabel("Open")
.setURL(url)
.setStyle("LINK")
- ])]
+ ])];
}
return await interaction.reply({embeds: [new EmojiEmbed()
.setTitle(interaction.options.getString("tag"))
@@ -37,20 +37,20 @@
.setEmoji("PUNISH.NICKNAME.GREEN")
.setStatus("Success")
.setImage(url)
- ], components: components, ephemeral: true})
+ ], components: components, ephemeral: true});
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
return true;
-}
+};
const autocomplete = async (interaction: AutocompleteInteraction): Promise<string[]> => {
if (!interaction.guild) return [];
- const config = await client.database.guilds.read(interaction.guild.id)
+ const config = await client.database.guilds.read(interaction.guild.id);
const tags = Object.keys(config.getKey("tags"));
- return tags
-}
+ return tags;
+};
export { command };
export { callback };
diff --git a/src/commands/tags/create.ts b/src/commands/tags/create.ts
index 4615def..d2f15e1 100644
--- a/src/commands/tags/create.ts
+++ b/src/commands/tags/create.ts
@@ -8,14 +8,14 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("create")
- .setDescription("Creates a tag")
- .addStringOption(o => o.setName("name").setRequired(true).setDescription("The name of the tag"))
- .addStringOption(o => o.setName("value").setRequired(true).setDescription("The value of the tag, shown after running /tag name"))
+ .setName("create")
+ .setDescription("Creates a tag")
+ .addStringOption(o => o.setName("name").setRequired(true).setDescription("The name of the tag"))
+ .addStringOption(o => o.setName("value").setRequired(true).setDescription("The value of the tag, shown after running /tag name"));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- let name = interaction.options.getString("name");
- let value = interaction.options.getString("value");
+ const name = interaction.options.getString("name");
+ const value = interaction.options.getString("value");
if (name.length > 100) return await interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Tag Create")
.setDescription("Tag names cannot be longer than 100 characters")
@@ -28,7 +28,7 @@
.setStatus("Danger")
.setEmoji("PUNISH.NICKNAME.RED")
], ephemeral: true});
- let 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: [new EmojiEmbed()
.setTitle("Tag Create")
.setDescription("You cannot have more than 100 tags")
@@ -41,18 +41,18 @@
.setStatus("Danger")
.setEmoji("PUNISH.NICKNAME.RED")
], ephemeral: true});
- let confirmation = await new confirmationMessage(interaction)
- .setEmoji("PUNISH.NICKNAME.YELLOW")
+ const confirmation = await new confirmationMessage(interaction)
+ .setEmoji("PUNISH.NICKNAME.YELLOW")
.setTitle("Tag create")
.setDescription(keyValueList({
"name": `${name}`,
"value": `\n> ${value}`
})
- + `\nAre you sure you want to create this tag?`)
+ + "\nAre you sure you want to create this tag?")
.setColor("Warning")
.setInverted(true)
- .send()
- if (confirmation.cancelled) return
+ .send();
+ if (confirmation.cancelled) return;
if (!confirmation) return await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Tag Create")
.setDescription("No changes were made")
@@ -75,13 +75,13 @@
.setStatus("Success")
.setEmoji("PUNISH.NICKNAME.GREEN")
], components: []});
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as Discord.GuildMember)
- if (!member.permissions.has("MANAGE_MESSAGES")) throw "You must have the *Manage Messages* permission to use this command"
+ 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";
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/tags/delete.ts b/src/commands/tags/delete.ts
index 68a02d4..5a6d3d4 100644
--- a/src/commands/tags/delete.ts
+++ b/src/commands/tags/delete.ts
@@ -8,31 +8,31 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("delete")
- .setDescription("Deletes a tag")
- .addStringOption(o => o.setName("name").setRequired(true).setDescription("The name of the tag"))
+ .setName("delete")
+ .setDescription("Deletes a tag")
+ .addStringOption(o => o.setName("name").setRequired(true).setDescription("The name of the tag"));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- let name = interaction.options.getString("name");
- let data = await client.database.guilds.read(interaction.guild.id);
+ const name = interaction.options.getString("name");
+ const data = await client.database.guilds.read(interaction.guild.id);
if (!data.tags[name]) return await interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Tags")
.setDescription("That tag does not exist")
.setStatus("Danger")
.setEmoji("PUNISH.NICKNAME.RED")
], ephemeral: true});
- let confirmation = await new confirmationMessage(interaction)
+ const confirmation = await new confirmationMessage(interaction)
.setEmoji("PUNISH.NICKNAME.YELLOW")
.setTitle("Tag Delete")
.setDescription(keyValueList({
"name": `${name}`,
"value": `\n> ${data.tags[name]}`
})
- + `\nAre you sure you want to delete this tag?`)
+ + "\nAre you sure you want to delete this tag?")
.setColor("Warning")
.setInverted(true)
- .send()
- if (confirmation.cancelled) return
+ .send();
+ if (confirmation.cancelled) return;
if (!confirmation) return await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Tag Delete")
.setDescription("No changes were made")
@@ -42,7 +42,7 @@
try {
await client.database.guilds.write(interaction.guild.id, null, ["tags." + name]);
} catch (e) {
- console.log(e)
+ console.log(e);
return await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Tag Delete")
.setDescription("Something went wrong and the tag was not deleted")
@@ -56,13 +56,13 @@
.setStatus("Success")
.setEmoji("PUNISH.NICKNAME.GREEN")
], components: []});
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as Discord.GuildMember)
- if (!member.permissions.has("MANAGE_MESSAGES")) throw "You must have the *Manage Messages* permission to use this command"
+ 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";
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/tags/edit.ts b/src/commands/tags/edit.ts
index 2f585cd..f3698fc 100644
--- a/src/commands/tags/edit.ts
+++ b/src/commands/tags/edit.ts
@@ -8,16 +8,16 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("edit")
- .setDescription("Edits or renames a tag")
- .addStringOption(o => o.setName("name").setRequired(true).setDescription("The tag to edit"))
- .addStringOption(o => o.setName("value").setRequired(false).setDescription("The new value of the tag / Rename"))
- .addStringOption(o => o.setName("newname").setRequired(false).setDescription("The new name of the tag / Edit"))
+ .setName("edit")
+ .setDescription("Edits or renames a tag")
+ .addStringOption(o => o.setName("name").setRequired(true).setDescription("The tag to edit"))
+ .addStringOption(o => o.setName("value").setRequired(false).setDescription("The new value of the tag / Rename"))
+ .addStringOption(o => o.setName("newname").setRequired(false).setDescription("The new name of the tag / Edit"));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- let name = interaction.options.getString("name");
- let value = interaction.options.getString("value") || "";
- let newname = interaction.options.getString("newname") || "";
+ const name = interaction.options.getString("name");
+ const value = interaction.options.getString("value") || "";
+ const newname = interaction.options.getString("newname") || "";
if (!newname && !value) return await interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Tag Edit")
.setDescription("You must specify a value or a new name")
@@ -36,7 +36,7 @@
.setStatus("Danger")
.setEmoji("PUNISH.NICKNAME.RED")
], ephemeral: true});
- let 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: [new EmojiEmbed()
.setTitle("Tag Edit")
.setDescription("That tag does not exist")
@@ -49,18 +49,18 @@
.setStatus("Danger")
.setEmoji("PUNISH.NICKNAME.RED")
], ephemeral: true});
- let confirmation = await new confirmationMessage(interaction)
- .setEmoji("PUNISH.NICKNAME.YELLOW")
+ const confirmation = await new confirmationMessage(interaction)
+ .setEmoji("PUNISH.NICKNAME.YELLOW")
.setTitle("Tag Edit")
.setDescription(keyValueList({
"name": `${name}` + (newname ? ` -> ${newname}` : ""),
"value": `\n> ${value ? value : data.tags[name]}`
})
- + `\nAre you sure you want to edit this tag?`)
+ + "\nAre you sure you want to edit this tag?")
.setColor("Warning")
.setInverted(true)
- .send()
- if (confirmation.cancelled) return
+ .send();
+ if (confirmation.cancelled) return;
if (!confirmation) return await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Tag Edit")
.setDescription("No changes were made")
@@ -68,8 +68,8 @@
.setEmoji("PUNISH.NICKNAME.GREEN")
]});
try {
- let toSet = {};
- let toUnset = []
+ const toSet = {};
+ const toUnset = [];
if (value) toSet[`tags.${name}`] = value;
if (newname) {
toUnset.push(`tags.${name}`);
@@ -90,13 +90,13 @@
.setStatus("Success")
.setEmoji("PUNISH.NICKNAME.GREEN")
], components: []});
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let member = (interaction.member as Discord.GuildMember)
- if (!member.permissions.has("MANAGE_MESSAGES")) throw "You must have the *Manage Messages* permission to use this command"
+ 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";
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/tags/list.ts b/src/commands/tags/list.ts
index c335267..7f3637f 100644
--- a/src/commands/tags/list.ts
+++ b/src/commands/tags/list.ts
@@ -1,10 +1,10 @@
-import { LoadingEmbed } from './../../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "./../../utils/defaultEmbeds.js";
import Discord, { CommandInteraction, MessageActionRow, MessageButton } from "discord.js";
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import client from "../../utils/client.js";
-import { SelectMenuOption } from '@discordjs/builders';
+import { SelectMenuOption } from "@discordjs/builders";
import getEmojiByName from "../../utils/getEmojiByName.js";
import createPageIndicator from "../../utils/createPageIndicator.js";
@@ -12,8 +12,8 @@
class Embed {
embed: Discord.MessageEmbed;
title: string;
- description: string = "";
- pageId: number = 0;
+ description = "";
+ pageId = 0;
setEmbed(embed: Discord.MessageEmbed) { this.embed = embed; return this; }
setTitle(title: string) { this.title = title; return this; }
setDescription(description: string) { this.description = description; return this; }
@@ -23,61 +23,61 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
.setName("list")
- .setDescription("Lists all tags in the server")
+ .setDescription("Lists all tags in the server");
const callback = async (interaction: CommandInteraction): Promise<any> => {
- let data = await client.database.guilds.read(interaction.guild.id);
- let tags = data.getKey("tags");
- let strings = []
- if (data === {}) strings = ["*No tags exist*"]
+ const data = await client.database.guilds.read(interaction.guild.id);
+ const tags = data.getKey("tags");
+ let strings = [];
+ if (data === {}) strings = ["*No tags exist*"];
else {
- let string = ""
- for (let tag in tags) {
- let proposed = `**${tag}:** ${tags[tag]}\n`
+ let string = "";
+ for (const tag in tags) {
+ const proposed = `**${tag}:** ${tags[tag]}\n`;
if (string.length + proposed.length > 2000) {
- strings.push(string.slice(0, -1))
- string = ""
+ strings.push(string.slice(0, -1));
+ string = "";
}
- string += proposed
+ string += proposed;
}
- strings.push(string.slice(0, -1))
+ strings.push(string.slice(0, -1));
}
- let pages = []
- for (let string of strings) {
+ const pages = [];
+ for (const string of strings) {
pages.push(new Embed()
.setEmbed(new EmojiEmbed()
.setTitle("Tags")
.setDescription(string)
.setEmoji("PUNISH.NICKNAME.GREEN")
.setStatus("Success")
- ).setTitle(`Page ${pages.length + 1}`).setPageId(pages.length))
+ ).setTitle(`Page ${pages.length + 1}`).setPageId(pages.length));
}
let m;
m = await interaction.reply({embeds: LoadingEmbed, fetchReply: true, ephemeral: true});
let page = 0;
let selectPaneOpen = false;
while (true) {
- let selectPane = []
+ let selectPane = [];
if (selectPaneOpen) {
- let options = [];
+ const options = [];
pages.forEach(embed => {
options.push(new SelectMenuOption({
label: embed.title,
value: embed.pageId.toString(),
- description: embed.description || "",
- }))
- })
+ description: embed.description || ""
+ }));
+ });
selectPane = [new MessageActionRow().addComponents([
new Discord.MessageSelectMenu()
.addOptions(options)
.setCustomId("page")
.setMaxValues(1)
.setPlaceholder("Choose a page...")
- ])]
+ ])];
}
- let 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],
@@ -88,11 +88,11 @@
new MessageButton().setCustomId("close").setEmoji(getEmojiByName("CONTROL.CROSS", "id")).setStyle("DANGER")
])])
});
- let i
+ let i;
try {
i = await m.awaitMessageComponent({time: 300000 });
- } catch (e) { break }
- i.deferUpdate()
+ } catch (e) { break; }
+ i.deferUpdate();
if (i.component.customId === "left") {
if (page > 0) page--;
selectPaneOpen = false;
@@ -105,7 +105,7 @@
page = parseInt(i.values[0]);
selectPaneOpen = false;
} else {
- let 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], components: [new MessageActionRow().addComponents([
@@ -114,11 +114,11 @@
new MessageButton().setCustomId("right").setEmoji(getEmojiByName("CONTROL.RIGHT", "id")).setStyle("SECONDARY").setDisabled(true),
new MessageButton().setCustomId("close").setEmoji(getEmojiByName("CONTROL.CROSS", "id")).setStyle("DANGER").setDisabled(true)
])]
- })
+ });
return;
}
}
- let 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],
@@ -129,11 +129,11 @@
new MessageButton().setCustomId("close").setEmoji(getEmojiByName("CONTROL.CROSS", "id")).setStyle("DANGER").setDisabled(true)
])]
});
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/ticket/close.ts b/src/commands/ticket/close.ts
index 5a3371e..b3e5351 100644
--- a/src/commands/ticket/close.ts
+++ b/src/commands/ticket/close.ts
@@ -5,16 +5,16 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("close")
- .setDescription("Closes a ticket")
+ .setName("close")
+ .setDescription("Closes a ticket");
const callback = async (interaction: CommandInteraction): Promise<any> => {
await close(interaction);
-}
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/ticket/create.ts b/src/commands/ticket/create.ts
index 3d796aa..25de336 100644
--- a/src/commands/ticket/create.ts
+++ b/src/commands/ticket/create.ts
@@ -5,17 +5,17 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("create")
- .setDescription("Creates a new modmail ticket")
- .addStringOption(option => option.setName("message").setDescription("The content of the ticket").setRequired(false))
+ .setName("create")
+ .setDescription("Creates a new modmail ticket")
+ .addStringOption(option => option.setName("message").setDescription("The content of the ticket").setRequired(false));
const callback = async (interaction: CommandInteraction): Promise<any> => {
- await create(interaction)
-}
+ await create(interaction);
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/user/about.ts b/src/commands/user/about.ts
index 82eda6a..59ba2e6 100644
--- a/src/commands/user/about.ts
+++ b/src/commands/user/about.ts
@@ -1,4 +1,4 @@
-import { LoadingEmbed } from './../../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "./../../utils/defaultEmbeds.js";
import Discord, { CommandInteraction, MessageActionRow, MessageButton } from "discord.js";
import { SelectMenuOption, SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
@@ -6,20 +6,20 @@
import getEmojiByName from "../../utils/getEmojiByName.js";
import generateKeyValueList from "../../utils/generateKeyValueList.js";
import createPageIndicator from "../../utils/createPageIndicator.js";
-import client from "../../utils/client.js"
+import client from "../../utils/client.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("about")
- .setDescription("Shows info about a user")
- .addUserOption(option => option.setName("user").setDescription("The user to get info about | Default: Yourself"))
+ .setName("about")
+ .setDescription("Shows info about a user")
+ .addUserOption(option => option.setName("user").setDescription("The user to get info about | Default: Yourself"));
class Embed {
embed: Discord.MessageEmbed;
title: string;
- description: string = "";
- pageId: number = 0;
+ description = "";
+ pageId = 0;
setEmbed(embed: Discord.MessageEmbed) { this.embed = embed; return this; }
setTitle(title: string) { this.title = title; return this; }
setDescription(description: string) { this.description = description; return this; }
@@ -28,23 +28,23 @@
const callback = async (interaction: CommandInteraction): Promise<any> => {
- const { renderUser, renderDelta } = client.logger
- let member = (interaction.options.getMember("user") || interaction.member) as Discord.GuildMember;
- let flags: string[] = [];
+ const { renderUser, renderDelta } = client.logger;
+ const member = (interaction.options.getMember("user") || interaction.member) as Discord.GuildMember;
+ const flags: string[] = [];
if ([
"438733159748599813", // Pinea
"317731855317336067", // Mini
"261900651230003201", // Coded
- "511655498676699136", // Zan
- ].includes(member.user.id)) { flags.push("NUCLEUSDEVELOPER") }
- if ((await client.guilds.cache.get("684492926528651336")?.members.fetch())?.filter(m => m.roles.cache.has("760896837866749972"))?.map(m => m.id).includes(member.user.id)) { flags.push("CLICKSDEVELOPER") }
+ "511655498676699136" // Zan
+ ].includes(member.user.id)) { flags.push("NUCLEUSDEVELOPER"); }
+ if ((await client.guilds.cache.get("684492926528651336")?.members.fetch())?.filter(m => m.roles.cache.has("760896837866749972"))?.map(m => m.id).includes(member.user.id)) { flags.push("CLICKSDEVELOPER"); }
member.user.flags.toArray().map(flag => {
- flags.push(flag.toString())
- })
- if (member.user.bot === true) { flags.push("BOT") }
+ flags.push(flag.toString());
+ });
+ if (member.user.bot === true) { flags.push("BOT"); }
// Check if they are boosting the server
- if (member.premiumSince) { flags.push("BOOSTER") }
- let nameReplacements = {
+ if (member.premiumSince) { flags.push("BOOSTER"); }
+ const nameReplacements = {
"NUCLEUSDEVELOPER": "**Nucleus Developer**",
"CLICKSDEVELOPER": "Clicks Developer",
"HOUSE_BRAVERY": "Hypesquad Bravery",
@@ -59,31 +59,31 @@
"EARLY_VERIFIED_BOT_DEVELOPER": "Verified Bot Developer",
"BOT": "Bot",
"BOOSTER": "Server Booster"
- }
- let members = await interaction.guild.members.fetch()
- let membersArray = [...members.values()]
- membersArray.sort((a, b) => a.joinedTimestamp - b.joinedTimestamp)
- let joinPos = membersArray.findIndex(m => m.id === member.user.id)
+ };
+ const members = await interaction.guild.members.fetch();
+ const membersArray = [...members.values()];
+ membersArray.sort((a, b) => a.joinedTimestamp - b.joinedTimestamp);
+ const joinPos = membersArray.findIndex(m => m.id === member.user.id);
- let roles = member.roles.cache.filter(r => r.id !== interaction.guild.id).sort()
+ const roles = member.roles.cache.filter(r => r.id !== interaction.guild.id).sort();
let s = "";
let count = 0;
- let ended = false
+ let ended = false;
roles.map(item => {
if (ended) return;
- let string = `<@&${item.id}>, `
+ const string = `<@&${item.id}>, `;
if(s.length + string.length > 1000) {
- ended = true
- s += `and ${roles.size - count} more`
- return
- };
- count ++
+ ended = true;
+ s += `and ${roles.size - count} more`;
+ return;
+ }
+ count ++;
s += string;
- })
+ });
if(s.length > 0 && !ended) s = s.slice(0, -2);
- let perms = ""
- let permsArray = {
+ let perms = "";
+ const permsArray = {
"ADMINISTRATOR": "Administrator",
"MANAGE_GUILD": "Manage Server",
"MANAGE_ROLES": "Manage Roles",
@@ -96,15 +96,15 @@
"MANAGE_MESSAGES": "Manage Messages",
"VIEW_AUDIT_LOG": "View Audit Log",
"MENTION_EVERYONE": "Mention Everyone"
- }
+ };
Object.keys(permsArray).map(perm => {
- let hasPerm = member.permissions.has(perm as Discord.PermissionString)
- perms += `${getEmojiByName("CONTROL." + (hasPerm ? "TICK" : "CROSS"))} ${permsArray[perm]}\n`
- })
+ const hasPerm = member.permissions.has(perm as Discord.PermissionString);
+ perms += `${getEmojiByName("CONTROL." + (hasPerm ? "TICK" : "CROSS"))} ${permsArray[perm]}\n`;
+ });
let selectPaneOpen = false;
- let embeds = [
+ const embeds = [
new Embed()
.setEmbed(new EmojiEmbed()
.setTitle("User Info: General")
@@ -138,7 +138,7 @@
generateKeyValueList({
"member": renderUser(member.user),
"id": `\`${member.id}\``,
- "roles": `${member.roles.cache.size - 1}`,
+ "roles": `${member.roles.cache.size - 1}`
}) + "\n" +
(s.length > 0 ? s : "*None*") + "\n"
)
@@ -152,37 +152,37 @@
.setDescription(
generateKeyValueList({
"member": renderUser(member.user),
- "id": `\`${member.id}\``,
+ "id": `\`${member.id}\``
}) + "\n" + perms
)
.setThumbnail(await member.user.displayAvatarURL({dynamic: true}))
- ).setTitle("Key Permissions").setDescription("Key permissions the user has").setPageId(2),
- ]
- let m
+ ).setTitle("Key Permissions").setDescription("Key permissions the user has").setPageId(2)
+ ];
+ let m;
m = await interaction.reply({embeds: LoadingEmbed, fetchReply: true, ephemeral: true});
- let page = 0
- let breakReason = ""
+ let page = 0;
+ let breakReason = "";
while (true) {
- let em = new Discord.MessageEmbed(embeds[page].embed)
+ const em = new Discord.MessageEmbed(embeds[page].embed);
em.setDescription(em.description + "\n" + createPageIndicator(embeds.length, page));
- let selectPane = []
+ let selectPane = [];
if (selectPaneOpen) {
- let options = [];
+ const options = [];
embeds.forEach(embed => {
options.push(new SelectMenuOption({
label: embed.title,
value: embed.pageId.toString(),
- description: embed.description || "",
- }))
- })
+ description: embed.description || ""
+ }));
+ });
selectPane = [new MessageActionRow().addComponents([
new Discord.MessageSelectMenu()
.addOptions(options)
.setCustomId("page")
.setMaxValues(1)
.setPlaceholder("Choose a page...")
- ])]
+ ])];
}
await interaction.editReply({
embeds: [em],
@@ -207,12 +207,12 @@
.setCustomId("close")
.setStyle("DANGER")
])])
- })
- let i
+ });
+ let i;
try {
i = await m.awaitMessageComponent({time: 300000});
- } catch { breakReason = "Message timed out"; break }
- i.deferUpdate()
+ } catch { breakReason = "Message timed out"; break; }
+ i.deferUpdate();
if (i.component.customId === "left") {
if (page > 0) page--;
selectPaneOpen = false;
@@ -232,7 +232,7 @@
break;
}
}
- let em = new Discord.MessageEmbed(embeds[page].embed)
+ const em = new Discord.MessageEmbed(embeds[page].embed);
em.setDescription(em.description + "\n" + createPageIndicator(embeds.length, page) + " | " + breakReason);
await interaction.editReply({embeds: [em], components: [new MessageActionRow().addComponents([
new MessageButton()
@@ -255,12 +255,12 @@
.setCustomId("close")
.setStyle("DANGER")
.setDisabled(true)
- ])]})
-}
+ ])]});
+};
const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/user/avatar.ts b/src/commands/user/avatar.ts
index e72506f..8f327a5 100644
--- a/src/commands/user/avatar.ts
+++ b/src/commands/user/avatar.ts
@@ -2,19 +2,18 @@
import { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import { WrappedCheck } from "jshaiku";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
-import getEmojiByName from "../../utils/getEmojiByName.js";
import generateKeyValueList from "../../utils/generateKeyValueList.js";
-import client from "../../utils/client.js"
+import client from "../../utils/client.js";
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("avatar")
- .setDescription("Shows the avatar of a user")
- .addUserOption(option => option.setName("user").setDescription("The user to get the avatar of | Default: Yourself"))
+ .setName("avatar")
+ .setDescription("Shows the avatar of a user")
+ .addUserOption(option => option.setName("user").setDescription("The user to get the avatar of | Default: Yourself"));
-const callback = async (interaction: CommandInteraction): Promise<any> => {
- const { renderUser } = client.logger
- let member = (interaction.options.getMember("user") || interaction.member) as Discord.GuildMember;
+const callback = async (interaction: CommandInteraction): Promise<void> => {
+ const { renderUser } = client.logger;
+ const member = (interaction.options.getMember("user") || interaction.member) as Discord.GuildMember;
await interaction.reply({embeds: [new EmojiEmbed()
.setTitle("User Info")
.setStatus("Success")
@@ -22,16 +21,16 @@
.setDescription(
generateKeyValueList({
"member": renderUser(member.user),
- "url": member.user.displayAvatarURL({dynamic: true}),
+ "url": member.user.displayAvatarURL({dynamic: true})
})
)
.setImage(await member.user.displayAvatarURL({dynamic: true}))
], ephemeral: true, fetchReply: true});
-}
+};
-const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
+const check = (_interaction: CommandInteraction, _defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/user/track.ts b/src/commands/user/track.ts
index c2e0986..48733fc 100644
--- a/src/commands/user/track.ts
+++ b/src/commands/user/track.ts
@@ -1,6 +1,8 @@
-import { LoadingEmbed } from './../../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "./../../utils/defaultEmbeds.js";
import Discord, { CommandInteraction, GuildMember, Message, MessageActionRow, MessageButton } from "discord.js";
import { SelectMenuOption, SlashCommandSubcommandBuilder } from "@discordjs/builders";
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore
import { WrappedCheck } from "jshaiku";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import getEmojiByName from "../../utils/getEmojiByName.js";
@@ -9,91 +11,92 @@
const command = (builder: SlashCommandSubcommandBuilder) =>
builder
- .setName("track")
- .setDescription("Moves a user along a role track")
- .addUserOption(option => option.setName("user").setDescription("The user to manage").setRequired(true))
+ .setName("track")
+ .setDescription("Moves a user along a role track")
+ .addUserOption(option => option.setName("user").setDescription("The user to manage").setRequired(true));
-const generateFromTrack = (position: number, active: any, size: number, disabled: any) => {
- active = active ? "ACTIVE" : "INACTIVE"
- disabled = disabled ? "GREY." : ""
- if (position === 0 && size === 1) return "TRACKS.SINGLE." + disabled + active
- if (position === size - 1) return "TRACKS.VERTICAL.BOTTOM." + disabled + active
- if (position === 0) return "TRACKS.VERTICAL.TOP." + disabled + active
- return "TRACKS.VERTICAL.MIDDLE." + disabled + active
-}
+const generateFromTrack = (position: number, active: string | boolean, size: number, disabled: string | boolean) => {
+ active = active ? "ACTIVE" : "INACTIVE";
+ disabled = disabled ? "GREY." : "";
+ if (position === 0 && size === 1) return "TRACKS.SINGLE." + disabled + active;
+ if (position === size - 1) return "TRACKS.VERTICAL.BOTTOM." + disabled + active;
+ if (position === 0) return "TRACKS.VERTICAL.TOP." + disabled + active;
+ return "TRACKS.VERTICAL.MIDDLE." + disabled + active;
+};
-const callback = async (interaction: CommandInteraction): Promise<any> => {
+const callback = async (interaction: CommandInteraction): Promise<void | unknown> => {
const { renderUser } = client.logger;
const member = interaction.options.getMember("user") as GuildMember;
const guild = interaction.guild;
- let config = await client.database.guilds.read(guild.id);
- await interaction.reply({embeds: LoadingEmbed, ephemeral: true})
- let track = 0
+ if (!guild) return;
+ const config = await client.database.guilds.read(guild.id);
+ await interaction.reply({embeds: LoadingEmbed, ephemeral: true});
+ let track = 0;
let generated;
- const roles = await guild.roles.fetch()
- let memberRoles = await member.roles
- let managed
+ const roles = await guild.roles.fetch();
+ const memberRoles = await member.roles;
+ let managed: boolean;
while (true) {
- let data = config.tracks[track]
- if (data.manageableBy !== undefined) managed = data.manageableBy.some(element => {return memberRoles.cache.has(element)})
- else managed = false
- let dropdown = new Discord.MessageSelectMenu().addOptions(config.tracks.map((option, index) => {
- let hasRoleInTrack = option.track.some(element => {return memberRoles.cache.has(element)})
+ const data = config.tracks[track];
+ if (data.manageableBy !== undefined) managed = data.manageableBy.some((element: string) => {return memberRoles.cache.has(element);});
+ else managed = false;
+ const dropdown = new Discord.MessageSelectMenu().addOptions(config.tracks.map((option, index) => {
+ const hasRoleInTrack = option.track.some((element: string) => {return memberRoles.cache.has(element);});
return new SelectMenuOption({
default: index === track,
label: option.name,
value: index.toString(),
description: option.track.length === 0 ? "No" : addPlural(option.track.length, "role"),
emoji: client.emojis.resolve(getEmojiByName("TRACKS.SINGLE." + (hasRoleInTrack ? "ACTIVE" : "INACTIVE"), "id"))
- })
- })).setCustomId("select").setMaxValues(1)
- let allowed = []
- generated = "**Track:** " + data.name + "\n" + "**Member:** " + renderUser(member.user) + "\n"
- generated += (data.nullable ? "Members do not need a role in this track" : "A role in this track is required") + "\n"
- generated += (data.retainPrevious ? "When promoted, the user keeps previous roles" : "Members will lose their current role when promoted") + "\n"
+ });
+ })).setCustomId("select").setMaxValues(1);
+ const allowed = [];
+ generated = "**Track:** " + data.name + "\n" + "**Member:** " + renderUser(member.user) + "\n";
+ generated += (data.nullable ? "Members do not need a role in this track" : "A role in this track is required") + "\n";
+ generated += (data.retainPrevious ? "When promoted, the user keeps previous roles" : "Members will lose their current role when promoted") + "\n";
generated += "\n" + data.track.map((role, index) => {
- let allow = (roles.get(role).position >= (interaction.member as GuildMember).roles.highest.position) && !managed
- allowed.push(!allow)
+ const allow = (roles.get(role).position >= (interaction.member as GuildMember).roles.highest.position) && !managed;
+ allowed.push(!allow);
return getEmojiByName(generateFromTrack(
index,
memberRoles.cache.has(role),
data.track.length,
allow
)) + " " +
- roles.get(role).name + " [<@&" + roles.get(role).id + ">]"
- }).join("\n")
- let selected = [];
+ roles.get(role).name + " [<@&" + roles.get(role).id + ">]";
+ }).join("\n");
+ const selected = [];
for (let i = 0; i < data.track.length; i++) {
- if (memberRoles.cache.has(data.track[i])) selected.push(data.track[i])
+ if (memberRoles.cache.has(data.track[i])) selected.push(data.track[i]);
}
- let conflict = data.retainPrevious ? false : selected.length > 1;
- let conflictDropdown
- let currentRoleIndex
+ const conflict = data.retainPrevious ? false : selected.length > 1;
+ let conflictDropdown;
+ let currentRoleIndex;
if (conflict) {
- generated += `\n\n${getEmojiByName(`PUNISH.WARN.${managed ? "YELLOW" : "RED"}`)} This user has ${selected.length} roles from this track. `
- conflictDropdown = []
+ generated += `\n\n${getEmojiByName(`PUNISH.WARN.${managed ? "YELLOW" : "RED"}`)} This user has ${selected.length} roles from this track. `;
+ conflictDropdown = [];
if (
(roles.get(selected[0]).position < memberRoles.highest.position) || managed
) {
- generated += `In order to promote or demote this user, you must select which role the member should keep.`
+ generated += "In order to promote or demote this user, you must select which role the member should keep.";
selected.forEach(role => {
conflictDropdown.push(new SelectMenuOption({
label: roles.get(role).name,
- value: roles.get(role).id,
- }))
- })
+ value: roles.get(role).id
+ }));
+ });
conflictDropdown = [new Discord.MessageSelectMenu()
.addOptions(conflictDropdown)
.setCustomId("conflict")
.setMaxValues(1)
- .setPlaceholder("Select a role to keep")]
+ .setPlaceholder("Select a role to keep")];
} else {
- generated += "You don't have permission to manage one or more of the users roles, and therefore can't select one to keep."
+ generated += "You don't have permission to manage one or more of the users roles, and therefore can't select one to keep.";
}
} else {
- currentRoleIndex = selected.length === 0 ? -1 : data.track.indexOf(selected[0].toString())
+ currentRoleIndex = selected.length === 0 ? -1 : data.track.indexOf(selected[0].toString());
}
- let m = await interaction.editReply({embeds: [new EmojiEmbed()
+ const m = await interaction.editReply({embeds: [new EmojiEmbed()
.setEmoji("TRACKS.ICON")
.setTitle("Tracks")
.setDescription(`${generated}`)
@@ -101,82 +104,82 @@
], components: [
new MessageActionRow().addComponents(dropdown)
]
- .concat(conflict && conflictDropdown.length ? [new MessageActionRow().addComponents(conflictDropdown)] : [])
- .concat([
- new MessageActionRow().addComponents([
- new MessageButton()
- .setEmoji(getEmojiByName("CONTROL.UP", "id"))
- .setLabel("Move up")
- .setCustomId("promote")
- .setStyle("SUCCESS")
- .setDisabled(conflict || currentRoleIndex === 0 || (currentRoleIndex === -1 ? false : !allowed[currentRoleIndex - 1])),
- new MessageButton()
- .setEmoji(getEmojiByName("CONTROL.DOWN", "id"))
- .setLabel("Move down")
- .setCustomId("demote")
- .setStyle("DANGER")
- .setDisabled(conflict || (
- data.nullable ? currentRoleIndex <= -1 :
- currentRoleIndex === data.track.length - 1 || currentRoleIndex <= -1
- ) || !allowed[currentRoleIndex]),
- ])
- ])})
+ .concat(conflict && conflictDropdown.length ? [new MessageActionRow().addComponents(conflictDropdown)] : [])
+ .concat([
+ new MessageActionRow().addComponents([
+ new MessageButton()
+ .setEmoji(getEmojiByName("CONTROL.UP", "id"))
+ .setLabel("Move up")
+ .setCustomId("promote")
+ .setStyle("SUCCESS")
+ .setDisabled(conflict || currentRoleIndex === 0 || (currentRoleIndex === -1 ? false : !allowed[currentRoleIndex - 1])),
+ new MessageButton()
+ .setEmoji(getEmojiByName("CONTROL.DOWN", "id"))
+ .setLabel("Move down")
+ .setCustomId("demote")
+ .setStyle("DANGER")
+ .setDisabled(conflict || (
+ data.nullable ? currentRoleIndex <= -1 :
+ currentRoleIndex === data.track.length - 1 || currentRoleIndex <= -1
+ ) || !allowed[currentRoleIndex])
+ ])
+ ])});
let component;
try {
component = await (m as Message).awaitMessageComponent({time: 300000});
} catch (e) {
- return
+ return;
}
- component.deferUpdate()
+ component.deferUpdate();
if (component.customId === "conflict") {
- let rolesToRemove = selected.filter(role => role !== component.values[0])
- await member.roles.remove(rolesToRemove)
+ const rolesToRemove = selected.filter(role => role !== component.values[0]);
+ await member.roles.remove(rolesToRemove);
} else if (component.customId === "promote") {
if (
currentRoleIndex === -1 ? allowed[data.track.length - 1] :
- allowed[currentRoleIndex - 1] && allowed[currentRoleIndex]
+ allowed[currentRoleIndex - 1] && allowed[currentRoleIndex]
) {
if (currentRoleIndex === -1) {
- await member.roles.add(data.track[data.track.length - 1])
+ await member.roles.add(data.track[data.track.length - 1]);
} else if (currentRoleIndex < data.track.length) {
- if (!data.retainPrevious) await member.roles.remove(data.track[currentRoleIndex])
- await member.roles.add(data.track[currentRoleIndex - 1])
+ if (!data.retainPrevious) await member.roles.remove(data.track[currentRoleIndex]);
+ await member.roles.add(data.track[currentRoleIndex - 1]);
}
}
} else if (component.customId === "demote") {
if(allowed[currentRoleIndex]) {
if (currentRoleIndex === data.track.length - 1) {
- if (data.nullable) await member.roles.remove(data.track[currentRoleIndex])
+ if (data.nullable) await member.roles.remove(data.track[currentRoleIndex]);
} else if (currentRoleIndex > -1) {
- await member.roles.remove(data.track[currentRoleIndex])
- await member.roles.add(data.track[currentRoleIndex + 1])
+ await member.roles.remove(data.track[currentRoleIndex]);
+ await member.roles.add(data.track[currentRoleIndex + 1]);
}
}
} else if (component.customId === "select") {
- track = component.values[0]
+ track = component.values[0];
}
}
-}
+};
-const check = async (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
- let tracks = (await client.database.guilds.read(interaction.guild.id)).tracks
- if (tracks.length === 0) throw "This server does not have any tracks"
- let member = (interaction.member as GuildMember)
+const check = async (interaction: CommandInteraction, _defaultCheck: WrappedCheck) => {
+ const tracks = (await client.database.guilds.read(interaction.guild.id)).tracks;
+ if (tracks.length === 0) throw "This server does not have any tracks";
+ const member = (interaction.member as GuildMember);
// Allow the owner to promote anyone
- if (member.id === interaction.guild.ownerId) return true
+ if (member.id === interaction.guild.ownerId) return true;
// Check if the user can manage any of the tracks
- let managed = false
+ let managed = false;
for (const element of tracks) {
- if (!element.track.manageableBy) continue
- if (!element.track.manageableBy.some(role => member.roles.cache.has(role))) continue
+ if (!element.track.manageableBy) continue;
+ if (!element.track.manageableBy.some(role => member.roles.cache.has(role))) continue;
managed = true;
break;
- };
+ }
// Check if the user has manage_roles permission
if (!managed && ! member.permissions.has("MANAGE_ROLES")) throw "You do not have the *Manage Roles* permission";
// Allow track
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/commands/verify.ts b/src/commands/verify.ts
index bd71fe4..f7e66b8 100644
--- a/src/commands/verify.ts
+++ b/src/commands/verify.ts
@@ -1,19 +1,21 @@
-import { CommandInteraction } from "discord.js";
+import type { CommandInteraction } from "discord.js";
import { SlashCommandBuilder } from "@discordjs/builders";
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore
import { WrappedCheck } from "jshaiku";
import verify from "../reflex/verify.js";
const command = new SlashCommandBuilder()
.setName("verify")
- .setDescription("Get verified in the server")
+ .setDescription("Get verified in the server");
-const callback = async (interaction: CommandInteraction): Promise<any> => {
+const callback = async (interaction: CommandInteraction): Promise<void> => {
verify(interaction);
-}
+};
-const check = (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
+const check = (_interaction: CommandInteraction, _defaultCheck: WrappedCheck) => {
return true;
-}
+};
export { command };
export { callback };
diff --git a/src/config/format.js b/src/config/format.js
deleted file mode 100644
index bdd3fdb..0000000
--- a/src/config/format.js
+++ /dev/null
@@ -1,102 +0,0 @@
-import fs from 'fs';
-import * as readLine from 'node:readline/promises';
-import { exec } from 'node:child_process';
-
-const defaultDict = {
- "developmentToken": "Your development bot token (Used for testing in one server, rather than production)",
- "developmentGuildID": "Your development guild ID",
- "enableDevelopment": true,
- "token": "Your bot token",
- "managementGuildID": "Your management guild ID (Used for running management commands on the bot)",
- "owners": [],
- "verifySecret": "If using verify, enter a code here which matches the secret sent back by your website. You can use a random code if you do not have one already. (Optional)",
- "mongoUrl": "Your Mongo connection string, e.g. mongodb://127.0.0.1:27017",
- "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)",
-}
-
-const readline = readLine.createInterface({
- input: process.stdin,
- output: process.stdout,
-});
-
-async function getInput(prompt) {
- process.stdout.write(prompt);
-
- const answer = await readline.question(prompt);
- return answer.toString();
-}
-
-
-export default async function(walkthrough = false) {
- if (walkthrough) {
- console.log("\x1b[33m🛈 Entering walkthrough mode for any missing values.");
- console.log(" \x1b[2mIf you don't want to enter a value, just hit enter.\x1b[0m\n");
-
- // let toUse = await getInput("\x1b[36m[Installing packages] Use Yarn or NPM? \x1b[0m(\x1b[32my\x1b[0m/\x1b[31mN\x1b[0m) > ");
- // toUse = toUse.toLowerCase() === "y" ? "yarn install" : "npm i";
- // if ((await getInput(`\x1b[36m[Installing packages] Run ${toUse}? \x1b[0m(\x1b[32mY\x1b[0m/\x1b[31mn\x1b[0m) > `)).toLowerCase() !== "n") {
- // console.log(`\x1b[32m[Installing packages] Running ${toUse}...\x1b[0m`);
- // await exec(toUse);
- // console.log(`\x1b[32m[Installing packages] Installed\x1b[0m`);
- // } else {
- // console.log("\x1b[32m[Installing packages] Skipping...\x1b[0m");
- // }
- }
-
- let json;
- let out = true
- try {
- json = JSON.parse(fs.readFileSync('./src/config/main.json', 'utf8'));
- } catch (e) {
- console.log("\x1b[31m⚠ No main.json found, creating one.")
- console.log(" \x1b[2mYou can edit src/config/main.json directly using template written to the file.\x1b[0m\n")
- out = false
- json = {}
- }
- for (const key in defaultDict) {
- if (!json[key]) {
- if (walkthrough) {
- switch (key) {
- case "enableDevelopment": {
- json[key] = (await getInput("\x1b[36mEnable development mode? This redisters commands in a single server making it easier to test\x1b[0m(\x1b[32mY\x1b[0m/\x1b[31mn\x1b[0m) > ") || "Y").toLowerCase() === "y"; break;
- } case "owners": {
- let chosen = "!";
- let toWrite = []
- while (chosen !== "") {
- chosen = await getInput("\x1b[36mEnter an owner ID \x1b[0m(\x1b[35mleave blank to finish\x1b[0m) > ");
- if (chosen !== "") { toWrite.push(chosen); }
- }
- json[key] = toWrite; break;
- } default: {
- json[key] = await getInput(`\x1b[36m${key} \x1b[0m(\x1b[35m${defaultDict[key]}\x1b[0m) > `);
- }
- }
- }
- else { json[key] = defaultDict[key] }
- }
- }
- if (walkthrough && !json.mongoUrl) json.mongoUrl = "mongodb://127.0.0.1:27017"
- if (!json.mongoUrl.endsWith("/")) json.mongoUrl += "/";
- if (!json.baseUrl.endsWith("/")) json.baseUrl += "/";
- let hosts;
- try {
- hosts = fs.readFileSync('/etc/hosts', 'utf8').toString().split("\n");
- } catch (e) {
- return console.log("\x1b[31m⚠ No /etc/hosts found. Please ensure the file exists and is readable. (Windows is not supported, Mac and Linux users should not experience this error)")
- }
- let localhost = hosts.find(line => line.split(" ")[1] === "localhost");
- if (localhost) { localhost = localhost.split(" ")[0]; }
- else { localhost = "127.0.0.1" }
- json.mongoUrl = json.mongoUrl.replace("localhost", localhost);
- json.baseUrl = json.baseUrl.replace("localhost", localhost);
-
- fs.writeFileSync("./src/config/main.json", JSON.stringify(json, null, 4))
-
- if (walkthrough) {
- console.log("\x1b[32m✓ All properties added.\x1b[0m")
- }
- return out;
-}
diff --git a/src/events/channelCreate.ts b/src/events/channelCreate.ts
index fa66755..c4c1347 100644
--- a/src/events/channelCreate.ts
+++ b/src/events/channelCreate.ts
@@ -1,71 +1,70 @@
-export const event = 'channelCreate'
+export const event = "channelCreate";
export async function callback(client, channel) {
- try {
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = channel.client.logger
- let auditLog = await getAuditLog(channel.guild, 'CHANNEL_CREATE');
- let audit = auditLog.entries.filter(entry => entry.target.id === channel.id).first();
- if (audit.executor.id === client.user.id) return;
- let emoji;
- let readableType;
- let displayName;
- switch (channel.type) {
- case 'GUILD_TEXT': {
- emoji = "CHANNEL.TEXT.CREATE";
- readableType = "Text";
- displayName = "Text Channel"
- break;
- }
- case 'GUILD_NEWS': {
- emoji = "CHANNEL.TEXT.CREATE";
- readableType = "Announcement";
- displayName = "Announcement Channel"
- break;
- }
- case 'GUILD_VOICE': {
- emoji = "CHANNEL.VOICE.CREATE";
- readableType = "Voice";
- displayName = "Voice Channel"
- break;
- }
- case 'GUILD_STAGE': {
- emoji = "CHANNEL.VOICE.CREATE";
- readableType = "Stage";
- displayName = "Stage Channel"
- }
- case 'GUILD_CATEGORY': {
- emoji = "CHANNEL.CATEGORY.CREATE";
- readableType = "Category";
- displayName = "Category"
- break;
- }
- default: {
- emoji = "CHANNEL.TEXT.CREATE";
- readableType = "Channel";
- displayName = "Channel"
- }
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = channel.client.logger;
+ const auditLog = await getAuditLog(channel.guild, "CHANNEL_CREATE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === channel.id).first();
+ if (audit.executor.id === client.user.id) return;
+ let emoji;
+ let readableType;
+ let displayName;
+ switch (channel.type) {
+ case "GUILD_TEXT": {
+ emoji = "CHANNEL.TEXT.CREATE";
+ readableType = "Text";
+ displayName = "Text Channel";
+ break;
+ }
+ case "GUILD_NEWS": {
+ emoji = "CHANNEL.TEXT.CREATE";
+ readableType = "Announcement";
+ displayName = "Announcement Channel";
+ break;
+ }
+ case "GUILD_VOICE": {
+ emoji = "CHANNEL.VOICE.CREATE";
+ readableType = "Voice";
+ displayName = "Voice Channel";
+ break;
+ }
+ case "GUILD_STAGE": {
+ emoji = "CHANNEL.VOICE.CREATE";
+ readableType = "Stage";
+ displayName = "Stage Channel";
+ break;
+ }
+ case "GUILD_CATEGORY": {
+ emoji = "CHANNEL.CATEGORY.CREATE";
+ readableType = "Category";
+ displayName = "Category";
+ break;
+ }
+ default: {
+ emoji = "CHANNEL.TEXT.CREATE";
+ readableType = "Channel";
+ displayName = "Channel";
+ }
+ }
+ const data = {
+ meta: {
+ type: "channelCreate",
+ displayName: displayName + " Created",
+ calculateType: "channelUpdate",
+ color: NucleusColors.green,
+ emoji: emoji,
+ timestamp: channel.createdTimestamp
+ },
+ list: {
+ channelId: entry(channel.id, `\`${channel.id}\``),
+ name: entry(channel.name, renderChannel(channel)),
+ type: entry(channel.type, readableType),
+ category: entry(channel.parent ? channel.parent.id : null, channel.parent ? channel.parent.name : "Uncategorised"),
+ createdBy: entry(audit.executor.id, renderUser(audit.executor)),
+ created: entry(channel.createdTimestamp, renderDelta(channel.createdTimestamp))
+ },
+ hidden: {
+ guild: channel.guild.id
}
- let data = {
- meta: {
- type: 'channelCreate',
- displayName: displayName + ' Created',
- calculateType: 'channelUpdate',
- color: NucleusColors.green,
- emoji: emoji,
- timestamp: channel.createdTimestamp
- },
- list: {
- channelId: entry(channel.id, `\`${channel.id}\``),
- name: entry(channel.name, renderChannel(channel)),
- type: entry(channel.type, readableType),
- category: entry(channel.parent ? channel.parent.id : null, channel.parent ? channel.parent.name : "Uncategorised"),
- createdBy: entry(audit.executor.id, renderUser(audit.executor)),
- created: entry(channel.createdTimestamp, renderDelta(channel.createdTimestamp))
- },
- hidden: {
- guild: channel.guild.id
- }
- }
- log(data);
- } catch {}
+ };
+ log(data);
}
diff --git a/src/events/channelDelete.ts b/src/events/channelDelete.ts
index 25c9ce5..c8a72a4 100644
--- a/src/events/channelDelete.ts
+++ b/src/events/channelDelete.ts
@@ -1,73 +1,71 @@
import getEmojiByName from "../utils/getEmojiByName.js";
-export const event = 'channelDelete'
+export const event = "channelDelete";
export async function callback(client, channel) {
- try{
- const { getAuditLog, log, NucleusColors, entry, renderDelta, renderUser } = channel.client.logger
+ const { getAuditLog, log, NucleusColors, entry, renderDelta, renderUser } = channel.client.logger;
- let auditLog = await getAuditLog(channel.guild, 'CHANNEL_DELETE');
- let audit = auditLog.entries.filter(entry => entry.target.id === channel.id).first();
- if (audit.executor.id === client.user.id) return;
+ const auditLog = await getAuditLog(channel.guild, "CHANNEL_DELETE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === channel.id).first();
+ if (audit.executor.id === client.user.id) return;
- let emoji;
- let readableType;
- let displayName;
- switch (channel.type) {
- case 'GUILD_TEXT': {
- emoji = "CHANNEL.TEXT.DELETE";
- readableType = "Text";
- displayName = "Text Channel"
- break;
- }
- case 'GUILD_VOICE': {
- emoji = "CHANNEL.VOICE.DELETE";
- readableType = "Voice";
- displayName = "Voice Channel"
- break;
- }
- case 'GUILD_CATEGORY': {
- emoji = "CHANNEL.CATEGORY.DELETE";
- readableType = "Category";
- displayName = "Category"
- break;
- }
- default: {
- emoji = "CHANNEL.TEXT.DELETE";
- readableType = "Channel";
- displayName = "Channel"
- }
- }
- let list = {
- channelId: entry(channel.id, `\`${channel.id}\``),
- name: entry(channel.id, `${channel.name}`),
- topic: null,
- type: entry(channel.type, readableType),
- category: entry(channel.parent ? channel.parent.id : null, channel.parent ? channel.parent.name : "Uncategorised"),
- nsfw: null,
- created: entry(channel.createdTimestamp, renderDelta(channel.createdTimestamp)),
- deleted: entry(new Date().getTime(), renderDelta(new Date().getTime())),
- deletedBy: entry(audit.executor.id, renderUser(audit.executor))
- }
- if (channel.topic !== null ?? false) list.topic = entry(channel.topic, `\`\`\`\n${channel.topic.replace('`', "'")}\n\`\`\``);
- else delete list.topic;
- if (channel.nsfw !== null ?? false) list.nsfw = entry(channel.nsfw, channel.nsfw ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`);
- else delete list.nsfw;
+ let emoji;
+ let readableType;
+ let displayName;
+ switch (channel.type) {
+ case "GUILD_TEXT": {
+ emoji = "CHANNEL.TEXT.DELETE";
+ readableType = "Text";
+ displayName = "Text Channel";
+ break;
+ }
+ case "GUILD_VOICE": {
+ emoji = "CHANNEL.VOICE.DELETE";
+ readableType = "Voice";
+ displayName = "Voice Channel";
+ break;
+ }
+ case "GUILD_CATEGORY": {
+ emoji = "CHANNEL.CATEGORY.DELETE";
+ readableType = "Category";
+ displayName = "Category";
+ break;
+ }
+ default: {
+ emoji = "CHANNEL.TEXT.DELETE";
+ readableType = "Channel";
+ displayName = "Channel";
+ }
+ }
+ const list = {
+ channelId: entry(channel.id, `\`${channel.id}\``),
+ name: entry(channel.id, `${channel.name}`),
+ topic: null,
+ type: entry(channel.type, readableType),
+ category: entry(channel.parent ? channel.parent.id : null, channel.parent ? channel.parent.name : "Uncategorised"),
+ nsfw: null,
+ created: entry(channel.createdTimestamp, renderDelta(channel.createdTimestamp)),
+ deleted: entry(new Date().getTime(), renderDelta(new Date().getTime())),
+ deletedBy: entry(audit.executor.id, renderUser(audit.executor))
+ };
+ if (channel.topic !== null ?? false) list.topic = entry(channel.topic, `\`\`\`\n${channel.topic.replace("`", "'")}\n\`\`\``);
+ else delete list.topic;
+ if (channel.nsfw !== null ?? false) list.nsfw = entry(channel.nsfw, channel.nsfw ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`);
+ else delete list.nsfw;
- let data = {
- meta:{
- type: 'channelDelete',
- displayName: displayName + ' Deleted',
- calculateType: 'channelUpdate',
- color: NucleusColors.red,
- emoji: emoji,
- timestamp: audit.createdTimestamp
- },
- list: list,
- hidden: {
- guild: channel.guild.id
- }
+ const data = {
+ meta:{
+ type: "channelDelete",
+ displayName: displayName + " Deleted",
+ calculateType: "channelUpdate",
+ color: NucleusColors.red,
+ emoji: emoji,
+ timestamp: audit.createdTimestamp
+ },
+ list: list,
+ hidden: {
+ guild: channel.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
}
diff --git a/src/events/channelUpdate.ts b/src/events/channelUpdate.ts
index 568af0b..89692e8 100644
--- a/src/events/channelUpdate.ts
+++ b/src/events/channelUpdate.ts
@@ -1,135 +1,133 @@
-import humanizeDuration from 'humanize-duration';
-import getEmojiByName from '../utils/getEmojiByName.js';
+import humanizeDuration from "humanize-duration";
+import getEmojiByName from "../utils/getEmojiByName.js";
-export const event = 'channelUpdate';
+export const event = "channelUpdate";
export async function callback(client, oc, nc) {
- try {
- let config = await client.memory.readGuildInfo(nc.guild.id);
- const { getAuditLog, log, NucleusColors, entry, renderDelta, renderUser, renderChannel } = client.logger
+ const config = await client.memory.readGuildInfo(nc.guild.id);
+ const { getAuditLog, log, NucleusColors, entry, renderDelta, renderUser, renderChannel } = client.logger;
- if (nc.parent && (nc.parent.id === config.tickets.category)) return
+ if (nc.parent && (nc.parent.id === config.tickets.category)) return;
- let auditLog = await getAuditLog(nc.guild, 'CHANNEL_UPDATE');
- let audit = auditLog.entries.filter(entry => entry.target.id === nc.id).first();
- if (audit.executor.id === client.user.id) return;
+ const auditLog = await getAuditLog(nc.guild, "CHANNEL_UPDATE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === nc.id).first();
+ if (audit.executor.id === client.user.id) return;
- let emoji:string;
- let readableType:string;
- let displayName:string ;
- let changes = {
- channelId: entry(nc.id, `\`${nc.id}\``),
- channel: entry(nc.id, renderChannel(nc)),
- edited: entry(new Date().getTime(), renderDelta(new Date().getTime())),
- editedBy: entry(audit.executor.id, renderUser((await nc.guild.members.fetch(audit.executor.id)).user)),
+ let emoji:string;
+ let readableType:string;
+ let displayName:string ;
+ const changes = {
+ channelId: entry(nc.id, `\`${nc.id}\``),
+ channel: entry(nc.id, renderChannel(nc)),
+ edited: entry(new Date().getTime(), renderDelta(new Date().getTime())),
+ editedBy: entry(audit.executor.id, renderUser((await nc.guild.members.fetch(audit.executor.id)).user))
+ };
+ if (oc.name !== nc.name) changes["name"] = entry([oc.name, nc.name], `${oc.name} -> ${nc.name}`);
+ if (oc.position !== nc.position) changes["position"] = entry([oc.position, nc.position], `${oc.position} -> ${nc.position}`);
+
+ switch (nc.type) {
+ case "GUILD_TEXT": {
+ emoji = "CHANNEL.TEXT.EDIT";
+ readableType = "Text";
+ displayName = "Text Channel";
+ let oldTopic = oc.topic, newTopic = nc.topic;
+ if (oldTopic) {
+ if (oldTopic.length > 256) oldTopic = `\`\`\`\n${oldTopic.replace("`", "'").substring(0, 253) + "..."}\n\`\`\``;
+ else oldTopic = `\`\`\`\n${oldTopic.replace("`", "'")}\n\`\`\``;
+ } else { oldTopic = "None"; }
+ if (newTopic) {
+ if (newTopic.length > 256) newTopic = `\`\`\`\n${newTopic.replace("`", "'").substring(0, 253) + "..."}\n\`\`\``;
+ else newTopic = `\`\`\`\n${newTopic.replace("`", "'")}\n\`\`\``;
+ } else { newTopic = "None"; }
+ const nsfw = ["", ""];
+ nsfw[0] = oc.nsfw ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`;
+ nsfw[1] = nc.nsfw ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`;
+ if (oc.topic !== nc.topic) changes["description"] = entry([oc.topic, nc.topic], `\nBefore: ${oldTopic}\nAfter: ${newTopic}`);
+ if (oc.nsfw !== nc.nsfw) changes["nsfw"] = entry([oc.nsfw, nc.nsfw], `${nsfw[0]} -> ${nsfw[1]}`);
+ if (oc.rateLimitPerUser !== nc.rateLimitPerUser) changes["rateLimitPerUser"] = entry(
+ [oc.rateLimitPerUser, nc.rateLimitPerUser],
+ `${humanizeDuration(oc.rateLimitPerUser * 1000)} -> ${humanizeDuration(nc.rateLimitPerUser * 1000)}`
+ );
+
+ break;
+ }
+ case "GUILD_NEWS": {
+ emoji = "CHANNEL.TEXT.EDIT";
+ readableType = "News";
+ displayName = "News Channel";
+ let oldTopic = oc.topic, newTopic = nc.topic;
+ if (oldTopic) {
+ if (oldTopic.length > 256) oldTopic = `\`\`\`\n${oldTopic.replace("`", "'").substring(0, 253) + "..."}\n\`\`\``;
+ else oldTopic = `\`\`\`\n${oldTopic.replace("`", "'")}\n\`\`\``;
+ } else { oldTopic = "None"; }
+ if (newTopic) {
+ if (newTopic.length > 256) newTopic = `\`\`\`\n${newTopic.replace("`", "'").substring(0, 253) + "..."}\n\`\`\``;
+ else newTopic = `\`\`\`\n${newTopic.replace("`", "'")}\n\`\`\``;
+ } else { newTopic = "None"; }
+ if (oc.nsfw !== nc.nsfw) changes["nsfw"] = entry([oc.nsfw, nc.nsfw], `${oc.nsfw ? "On" : "Off"} -> ${nc.nsfw ? "On" : "Off"}`);
+ break;
+ }
+ case "GUILD_VOICE": {
+ emoji = "CHANNEL.VOICE.EDIT";
+ readableType = "Voice";
+ displayName = "Voice Channel";
+ if (oc.bitrate !== nc.bitrate) changes["bitrate"] = entry([oc.bitrate, nc.bitrate], `${oc.bitrate} -> ${nc.bitrate}`);
+ if (oc.userLimit !== nc.userLimit) changes["maxUsers"] = entry([oc.userLimit, nc.userLimit], `${oc.userLimit ? oc.userLimit : "Unlimited"} -> ${nc.userLimit}`);
+ if (oc.rtcRegion !== nc.rtcRegion) changes["region"] = entry(
+ [oc.rtcRegion, nc.rtcRegion],
+ `${oc.rtcRegion || "Automatic"} -> ${nc.rtcRegion || "Automatic"}`
+ );
+ break;
+ }
+ case "GUILD_STAGE": {
+ emoji = "CHANNEL.VOICE.EDIT";
+ readableType = "Stage";
+ displayName = "Stage Channel";
+ let oldTopic = oc.topic, newTopic = nc.topic;
+ if (oldTopic) {
+ if (oldTopic.length > 256) oldTopic = `\`\`\`\n${oldTopic.replace("`", "'").substring(0, 253) + "..."}\n\`\`\``;
+ else oldTopic = `\`\`\`\n${oldTopic.replace("`", "'")}\n\`\`\``;
+ } else { oldTopic = "None"; }
+ if (newTopic) {
+ if (newTopic.length > 256) newTopic = `\`\`\`\n${newTopic.replace("`", "'").substring(0, 253) + "..."}\n\`\`\``;
+ else newTopic = `\`\`\`\n${newTopic.replace("`", "'")}\n\`\`\``;
+ } else { newTopic = "None"; }
+ if (oc.bitrate !== nc.bitrate) changes["bitrate"] = entry([oc.bitrate, nc.bitrate], `${oc.bitrate} -> ${nc.bitrate}`);
+ if (oc.userLimit !== nc.userLimit) changes["maxUsers"] = entry([oc.userLimit, nc.userLimit], `${oc.userLimit ? oc.userLimit : "Unlimited"} -> ${nc.userLimit}`);
+ if (oc.rtcRegion !== nc.rtcRegion) changes["region"] = entry(
+ [oc.rtcRegion, nc.rtcRegion],
+ `${oc.rtcRegion || "Automatic"} -> ${nc.rtcRegion || "Automatic"}`
+ );
+ break;
+ }
+ case "GUILD_CATEGORY": {
+ emoji = "CHANNEL.CATEGORY.EDIT";
+ readableType = "Category";
+ displayName = "Category";
+ break;
+ }
+ default: {
+ emoji = "CHANNEL.TEXT.EDIT";
+ readableType = "Channel";
+ displayName = "Channel";
+ }
+ }
+ const t = oc.type.split("_")[1];
+ if (oc.type !== nc.type) changes["type"] = entry([oc.type, nc.type], `${t[0] + t.splice(1).toLowerCase()} -> ${readableType}`);
+ if (!(Object.values(changes).length - 4)) return;
+ const data = {
+ meta:{
+ type: "channelUpdate",
+ displayName: displayName + " Edited",
+ calculateType: "channelUpdate",
+ color: NucleusColors.yellow,
+ emoji: emoji,
+ timestamp: audit.createdTimestamp
+ },
+ list: changes,
+ hidden: {
+ guild: nc.guild.id
}
- if (oc.name !== nc.name) changes["name"] = entry([oc.name, nc.name], `${oc.name} -> ${nc.name}`);
- if (oc.position !== nc.position) changes["position"] = entry([oc.position, nc.position], `${oc.position} -> ${nc.position}`);
-
- switch (nc.type) {
- case 'GUILD_TEXT': {
- emoji = "CHANNEL.TEXT.EDIT";
- readableType = "Text";
- displayName = "Text Channel"
- let oldTopic = oc.topic, newTopic = nc.topic;
- if (oldTopic) {
- if (oldTopic.length > 256) oldTopic = `\`\`\`\n${oldTopic.replace('`', "'").substring(0, 253) + '...'}\n\`\`\``
- else oldTopic = `\`\`\`\n${oldTopic.replace('`', "'")}\n\`\`\``
- } else { oldTopic = "None"; }
- if (newTopic) {
- if (newTopic.length > 256) newTopic = `\`\`\`\n${newTopic.replace('`', "'").substring(0, 253) + '...'}\n\`\`\``
- else newTopic = `\`\`\`\n${newTopic.replace('`', "'")}\n\`\`\``
- } else { newTopic = "None"; }
- let nsfw = ["", ""]
- nsfw[0] = oc.nsfw ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`;
- nsfw[1] = nc.nsfw ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`;
- if (oc.topic !== nc.topic) changes["description"] = entry([oc.topic, nc.topic], `\nBefore: ${oldTopic}\nAfter: ${newTopic}`);
- if (oc.nsfw !== nc.nsfw) changes["nsfw"] = entry([oc.nsfw, nc.nsfw], `${nsfw[0]} -> ${nsfw[1]}`);
- if (oc.rateLimitPerUser !== nc.rateLimitPerUser) changes["rateLimitPerUser"] = entry(
- [oc.rateLimitPerUser, nc.rateLimitPerUser],
- `${humanizeDuration(oc.rateLimitPerUser * 1000)} -> ${humanizeDuration(nc.rateLimitPerUser * 1000)}`
- );
-
- break;
- }
- case 'GUILD_NEWS': {
- emoji = "CHANNEL.TEXT.EDIT";
- readableType = "News";
- displayName = "News Channel"
- let oldTopic = oc.topic, newTopic = nc.topic;
- if (oldTopic) {
- if (oldTopic.length > 256) oldTopic = `\`\`\`\n${oldTopic.replace('`', "'").substring(0, 253) + '...'}\n\`\`\``
- else oldTopic = `\`\`\`\n${oldTopic.replace('`', "'")}\n\`\`\``
- } else { oldTopic = "None"; }
- if (newTopic) {
- if (newTopic.length > 256) newTopic = `\`\`\`\n${newTopic.replace('`', "'").substring(0, 253) + '...'}\n\`\`\``
- else newTopic = `\`\`\`\n${newTopic.replace('`', "'")}\n\`\`\``
- } else { newTopic = "None"; }
- if (oc.nsfw !== nc.nsfw) changes["nsfw"] = entry([oc.nsfw, nc.nsfw], `${oc.nsfw ? "On" : "Off"} -> ${nc.nsfw ? "On" : "Off"}`);
- break;
- }
- case 'GUILD_VOICE': {
- emoji = "CHANNEL.VOICE.EDIT";
- readableType = "Voice";
- displayName = "Voice Channel"
- if (oc.bitrate !== nc.bitrate) changes["bitrate"] = entry([oc.bitrate, nc.bitrate], `${oc.bitrate} -> ${nc.bitrate}`);
- if (oc.userLimit !== nc.userLimit) changes["maxUsers"] = entry([oc.userLimit, nc.userLimit], `${oc.userLimit ? oc.userLimit : "Unlimited"} -> ${nc.userLimit}`);
- if (oc.rtcRegion !== nc.rtcRegion) changes["region"] = entry(
- [oc.rtcRegion, nc.rtcRegion],
- `${oc.rtcRegion || "Automatic"} -> ${nc.rtcRegion || "Automatic"}`
- );
- break;
- }
- case 'GUILD_STAGE': {
- emoji = "CHANNEL.VOICE.EDIT";
- readableType = "Stage";
- displayName = "Stage Channel"
- let oldTopic = oc.topic, newTopic = nc.topic;
- if (oldTopic) {
- if (oldTopic.length > 256) oldTopic = `\`\`\`\n${oldTopic.replace('`', "'").substring(0, 253) + '...'}\n\`\`\``
- else oldTopic = `\`\`\`\n${oldTopic.replace('`', "'")}\n\`\`\``
- } else { oldTopic = "None"; }
- if (newTopic) {
- if (newTopic.length > 256) newTopic = `\`\`\`\n${newTopic.replace('`', "'").substring(0, 253) + '...'}\n\`\`\``
- else newTopic = `\`\`\`\n${newTopic.replace('`', "'")}\n\`\`\``
- } else { newTopic = "None"; }
- if (oc.bitrate !== nc.bitrate) changes["bitrate"] = entry([oc.bitrate, nc.bitrate], `${oc.bitrate} -> ${nc.bitrate}`);
- if (oc.userLimit !== nc.userLimit) changes["maxUsers"] = entry([oc.userLimit, nc.userLimit], `${oc.userLimit ? oc.userLimit : "Unlimited"} -> ${nc.userLimit}`);
- if (oc.rtcRegion !== nc.rtcRegion) changes["region"] = entry(
- [oc.rtcRegion, nc.rtcRegion],
- `${oc.rtcRegion || "Automatic"} -> ${nc.rtcRegion || "Automatic"}`
- );
- break;
- }
- case 'GUILD_CATEGORY': {
- emoji = "CHANNEL.CATEGORY.EDIT";
- readableType = "Category";
- displayName = "Category"
- break;
- }
- default: {
- emoji = "CHANNEL.TEXT.EDIT";
- readableType = "Channel";
- displayName = "Channel"
- }
- }
- let t = oc.type.split("_")[1];
- if (oc.type !== nc.type) changes["type"] = entry([oc.type, nc.type], `${t[0] + t.splice(1).toLowerCase()} -> ${readableType}`);
- if (!(Object.values(changes).length - 4)) return
- let data = {
- meta:{
- type: 'channelUpdate',
- displayName: displayName + ' Edited',
- calculateType: 'channelUpdate',
- color: NucleusColors.yellow,
- emoji: emoji,
- timestamp: audit.createdTimestamp
- },
- list: changes,
- hidden: {
- guild: nc.guild.id
- }
- }
- log(data);
- } catch {}
+ };
+ log(data);
}
\ No newline at end of file
diff --git a/src/events/commandError.ts b/src/events/commandError.ts
index 8edb480..2ec6a5d 100644
--- a/src/events/commandError.ts
+++ b/src/events/commandError.ts
@@ -1,6 +1,6 @@
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
-export const event = 'commandError'
+export const event = "commandError";
export async function callback(client, interaction, error) {
if (interaction.replied || interaction.deferred) {
@@ -9,13 +9,13 @@
.setDescription(error.message ?? error.toString())
.setStatus("Danger")
.setEmoji("CONTROL.BLOCKCROSS")
- ], ephemeral: true})
+ ], ephemeral: true});
} else {
await interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Something went wrong")
.setDescription(error.message ?? error.toString())
.setStatus("Danger")
.setEmoji("CONTROL.BLOCKCROSS")
- ], ephemeral: true})
+ ], ephemeral: true});
}
}
diff --git a/src/events/emojiCreate.ts b/src/events/emojiCreate.ts
index 9e91012..83a30e2 100644
--- a/src/events/emojiCreate.ts
+++ b/src/events/emojiCreate.ts
@@ -1,30 +1,28 @@
-export const event = 'emojiCreate'
+export const event = "emojiCreate";
export async function callback(client, emoji) {
- try {
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderEmoji } = emoji.client.logger
- let auditLog = await getAuditLog(emoji.guild, 'EMOJI_CREATE');
- let audit = auditLog.entries.filter(entry => entry.target.id === emoji.id).first();
- if (audit.executor.id === client.user.id) return;
- let data = {
- meta: {
- type: 'emojiCreate',
- displayName: 'Emoji Created',
- calculateType: 'emojiUpdate',
- color: NucleusColors.green,
- emoji: "GUILD.EMOJI.CREATE",
- timestamp: emoji.createdTimestamp
- },
- list: {
- emojiId: entry(emoji.id, `\`${emoji.id}\``),
- emoji: entry(emoji.name, renderEmoji(emoji)),
- createdBy: entry(audit.executor.id, renderUser(audit.executor)),
- created: entry(emoji.createdTimestamp, renderDelta(emoji.createdTimestamp))
- },
- hidden: {
- guild: emoji.guild.id
- }
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderEmoji } = emoji.client.logger;
+ const auditLog = await getAuditLog(emoji.guild, "EMOJI_CREATE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === emoji.id).first();
+ if (audit.executor.id === client.user.id) return;
+ const data = {
+ meta: {
+ type: "emojiCreate",
+ displayName: "Emoji Created",
+ calculateType: "emojiUpdate",
+ color: NucleusColors.green,
+ emoji: "GUILD.EMOJI.CREATE",
+ timestamp: emoji.createdTimestamp
+ },
+ list: {
+ emojiId: entry(emoji.id, `\`${emoji.id}\``),
+ emoji: entry(emoji.name, renderEmoji(emoji)),
+ createdBy: entry(audit.executor.id, renderUser(audit.executor)),
+ created: entry(emoji.createdTimestamp, renderDelta(emoji.createdTimestamp))
+ },
+ hidden: {
+ guild: emoji.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
}
diff --git a/src/events/emojiDelete.ts b/src/events/emojiDelete.ts
index 0c39542..5ed7a87 100644
--- a/src/events/emojiDelete.ts
+++ b/src/events/emojiDelete.ts
@@ -1,31 +1,29 @@
-export const event = 'emojiDelete'
+export const event = "emojiDelete";
export async function callback(client, emoji) {
- try{
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderEmoji } = emoji.client.logger
- let auditLog = await getAuditLog(emoji.guild, 'EMOJI_DELETE');
- let audit = auditLog.entries.filter(entry => entry.target.id === emoji.id).first();
- if (audit.executor.id === client.user.id) return;
- let data = {
- meta: {
- type: 'emojiDelete',
- displayName: 'Emoji Deleted',
- calculateType: 'emojiUpdate',
- color: NucleusColors.red,
- emoji: "GUILD.EMOJI.DELETE",
- timestamp: audit.createdTimestamp,
- },
- list: {
- emojiId: entry(emoji.id, `\`${emoji.id}\``),
- emoji: entry(emoji.name, renderEmoji(emoji)),
- deletedBy: entry(audit.executor.id, renderUser(audit.executor)),
- created: entry(emoji.createdTimestamp, renderDelta(emoji.createdTimestamp)),
- deleted: entry(audit.createdTimestamp, renderDelta(audit.createdTimestamp)),
- },
- hidden: {
- guild: emoji.guild.id
- }
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderEmoji } = emoji.client.logger;
+ const auditLog = await getAuditLog(emoji.guild, "EMOJI_DELETE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === emoji.id).first();
+ if (audit.executor.id === client.user.id) return;
+ const data = {
+ meta: {
+ type: "emojiDelete",
+ displayName: "Emoji Deleted",
+ calculateType: "emojiUpdate",
+ color: NucleusColors.red,
+ emoji: "GUILD.EMOJI.DELETE",
+ timestamp: audit.createdTimestamp
+ },
+ list: {
+ emojiId: entry(emoji.id, `\`${emoji.id}\``),
+ emoji: entry(emoji.name, renderEmoji(emoji)),
+ deletedBy: entry(audit.executor.id, renderUser(audit.executor)),
+ created: entry(emoji.createdTimestamp, renderDelta(emoji.createdTimestamp)),
+ deleted: entry(audit.createdTimestamp, renderDelta(audit.createdTimestamp))
+ },
+ hidden: {
+ guild: emoji.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
}
diff --git a/src/events/emojiUpdate.ts b/src/events/emojiUpdate.ts
index a90de9a..d04c6c8 100644
--- a/src/events/emojiUpdate.ts
+++ b/src/events/emojiUpdate.ts
@@ -1,37 +1,33 @@
-import getEmojiByName from "../utils/getEmojiByName.js";
-
-export const event = 'emojiUpdate';
+export const event = "emojiUpdate";
export async function callback(client, oe, ne) {
- try {
- const { getAuditLog, log, NucleusColors, entry, renderDelta, renderUser, renderEmoji } = client.logger
+ const { getAuditLog, log, NucleusColors, entry, renderDelta, renderUser, renderEmoji } = client.logger;
- if (oe.name === ne.name) return
- let auditLog = await getAuditLog(ne.guild, 'EMOJI_UPDATE');
- let audit = auditLog.entries.first();
- if (audit.executor.id === client.user.id) return;
+ if (oe.name === ne.name) return;
+ const auditLog = await getAuditLog(ne.guild, "EMOJI_UPDATE");
+ const audit = auditLog.entries.first();
+ if (audit.executor.id === client.user.id) return;
- let changes = {
- emojiId: entry(ne.id, `\`${ne.id}\``),
- emoji: entry(ne.id, renderEmoji(ne)),
- edited: entry(ne.createdTimestamp, renderDelta(ne.createdTimestamp)),
- editedBy: entry(audit.executor.id, renderUser((await ne.guild.members.fetch(audit.executor.id)).user)),
- name: entry([oe.name, ne.name], `\`:${oe.name}:\` -> \`:${ne.name}:\``),
+ const changes = {
+ emojiId: entry(ne.id, `\`${ne.id}\``),
+ emoji: entry(ne.id, renderEmoji(ne)),
+ edited: entry(ne.createdTimestamp, renderDelta(ne.createdTimestamp)),
+ editedBy: entry(audit.executor.id, renderUser((await ne.guild.members.fetch(audit.executor.id)).user)),
+ name: entry([oe.name, ne.name], `\`:${oe.name}:\` -> \`:${ne.name}:\``)
+ };
+ const data = {
+ meta:{
+ type: "emojiUpdate",
+ displayName: "Emoji Edited",
+ calculateType: "emojiUpdate",
+ color: NucleusColors.yellow,
+ emoji: "GUILD.EMOJI.EDIT",
+ timestamp: audit.createdTimestamp
+ },
+ list: changes,
+ hidden: {
+ guild: ne.guild.id
}
- let data = {
- meta:{
- type: 'emojiUpdate',
- displayName: 'Emoji Edited',
- calculateType: 'emojiUpdate',
- color: NucleusColors.yellow,
- emoji: "GUILD.EMOJI.EDIT",
- timestamp: audit.createdTimestamp
- },
- list: changes,
- hidden: {
- guild: ne.guild.id
- }
- }
- log(data);
- } catch {}
+ };
+ log(data);
}
\ No newline at end of file
diff --git a/src/events/guildBanAdd.ts b/src/events/guildBanAdd.ts
index 06163a9..c5d269b 100644
--- a/src/events/guildBanAdd.ts
+++ b/src/events/guildBanAdd.ts
@@ -1,39 +1,37 @@
-import { purgeByUser } from '../actions/tickets/delete.js';
-import { callback as statsChannelRemove } from '../reflex/statsChannelUpdate.js';
+import { purgeByUser } from "../actions/tickets/delete.js";
+import { callback as statsChannelRemove } from "../reflex/statsChannelUpdate.js";
-export const event = 'guildBanAdd';
+export const event = "guildBanAdd";
export async function callback(client, ban) {
- try { await statsChannelRemove(client, ban.user); } catch {}
- try { purgeByUser(ban.user.id, ban.guild); } catch {}
- try {
- const { log, NucleusColors, entry, renderUser, renderDelta, getAuditLog } = ban.user.client.logger
- let auditLog = await getAuditLog(ban.guild, 'MEMBER_BAN_ADD')
- let audit = auditLog.entries.filter(entry => entry.target.id === ban.user.id).first();
- if (audit.executor.id === client.user.id) return
- try { await client.database.history.create("ban", ban.guild.id, ban.user, audit.executor, audit.reason) } catch {}
- let data = {
- meta: {
- type: 'memberBan',
- displayName: 'Member Banned',
- calculateType: 'guildMemberPunish',
- color: NucleusColors.red,
- emoji: "PUNISH.BAN.RED",
- timestamp: new Date().getTime()
- },
- list: {
- memberId: entry(ban.user.id, `\`${ban.user.id}\``),
- name: entry(ban.user.id, renderUser(ban.user)),
- banned: entry(new Date().getTime(), renderDelta(new Date().getTime())),
- bannedBy: entry(audit.executor.id, renderUser(audit.executor)),
- reason: entry(audit.reason, audit.reason ? `\n> ${audit.reason}` : "*No reason provided.*"),
- accountCreated: entry(ban.user.createdAt, renderDelta(ban.user.createdAt)),
- serverMemberCount: ban.guild.memberCount,
- },
- hidden: {
- guild: ban.guild.id
- }
+ await statsChannelRemove(client, ban.user);
+ purgeByUser(ban.user.id, ban.guild);
+ const { log, NucleusColors, entry, renderUser, renderDelta, getAuditLog } = ban.user.client.logger;
+ const auditLog = await getAuditLog(ban.guild, "MEMBER_BAN_ADD");
+ const audit = auditLog.entries.filter(entry => entry.target.id === ban.user.id).first();
+ if (audit.executor.id === client.user.id) return;
+ await client.database.history.create("ban", ban.guild.id, ban.user, audit.executor, audit.reason);
+ const data = {
+ meta: {
+ type: "memberBan",
+ displayName: "Member Banned",
+ calculateType: "guildMemberPunish",
+ color: NucleusColors.red,
+ emoji: "PUNISH.BAN.RED",
+ timestamp: new Date().getTime()
+ },
+ list: {
+ memberId: entry(ban.user.id, `\`${ban.user.id}\``),
+ name: entry(ban.user.id, renderUser(ban.user)),
+ banned: entry(new Date().getTime(), renderDelta(new Date().getTime())),
+ bannedBy: entry(audit.executor.id, renderUser(audit.executor)),
+ reason: entry(audit.reason, audit.reason ? `\n> ${audit.reason}` : "*No reason provided.*"),
+ accountCreated: entry(ban.user.createdAt, renderDelta(ban.user.createdAt)),
+ serverMemberCount: ban.guild.memberCount
+ },
+ hidden: {
+ guild: ban.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
}
diff --git a/src/events/guildBanRemove.ts b/src/events/guildBanRemove.ts
index 2a1b6de..352265f 100644
--- a/src/events/guildBanRemove.ts
+++ b/src/events/guildBanRemove.ts
@@ -1,38 +1,35 @@
-import humanizeDuration from 'humanize-duration';
-import { purgeByUser } from '../actions/tickets/delete.js';
-import { callback as statsChannelRemove } from '../reflex/statsChannelUpdate.js';
+import { purgeByUser } from "../actions/tickets/delete.js";
+import { callback as statsChannelRemove } from "../reflex/statsChannelUpdate.js";
-export const event = 'guildBanRemove';
+export const event = "guildBanRemove";
export async function callback(client, ban) {
- try { await statsChannelRemove(client, ban.user); } catch {}
- try { purgeByUser(ban.user.id, ban.guild); } catch {}
- try {
- const { log, NucleusColors, entry, renderUser, renderDelta, getAuditLog } = ban.user.client.logger
- let auditLog = await getAuditLog(ban.guild, 'MEMBER_BAN_REMOVE')
- let audit = auditLog.entries.filter(entry => entry.target.id === ban.user.id).first();
- if (audit.executor.id === client.user.id) return
- try { await client.database.history.create("unban", ban.guild.id, ban.user, audit.executor, audit.reason) } catch {}
- let data = {
- meta: {
- type: 'memberUnban',
- displayName: 'Member Unbanned',
- calculateType: 'guildMemberPunish',
- color: NucleusColors.green,
- emoji: "PUNISH.BAN.GREEN",
- timestamp: new Date().getTime()
- },
- list: {
- memberId: entry(ban.user.id, `\`${ban.user.id}\``),
- name: entry(ban.user.id, renderUser(ban.user)),
- unbanned: entry(new Date().getTime(), renderDelta(new Date().getTime())),
- unbannedBy: entry(audit.executor.id, renderUser(audit.executor)),
- accountCreated: entry(ban.user.createdAt, renderDelta(ban.user.createdAt)),
- },
- hidden: {
- guild: ban.guild.id
- }
+ await statsChannelRemove(client, ban.user);
+ purgeByUser(ban.user.id, ban.guild);
+ const { log, NucleusColors, entry, renderUser, renderDelta, getAuditLog } = ban.user.client.logger;
+ const auditLog = await getAuditLog(ban.guild, "MEMBER_BAN_REMOVE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === ban.user.id).first();
+ if (audit.executor.id === client.user.id) return;
+ await client.database.history.create("unban", ban.guild.id, ban.user, audit.executor, audit.reason);
+ const data = {
+ meta: {
+ type: "memberUnban",
+ displayName: "Member Unbanned",
+ calculateType: "guildMemberPunish",
+ color: NucleusColors.green,
+ emoji: "PUNISH.BAN.GREEN",
+ timestamp: new Date().getTime()
+ },
+ list: {
+ memberId: entry(ban.user.id, `\`${ban.user.id}\``),
+ name: entry(ban.user.id, renderUser(ban.user)),
+ unbanned: entry(new Date().getTime(), renderDelta(new Date().getTime())),
+ unbannedBy: entry(audit.executor.id, renderUser(audit.executor)),
+ accountCreated: entry(ban.user.createdAt, renderDelta(ban.user.createdAt))
+ },
+ hidden: {
+ guild: ban.guild.id
}
- log(data);
- } catch (e) {console.log(e)}
+ };
+ log(data);
}
diff --git a/src/events/guildCreate.ts b/src/events/guildCreate.ts
index 413e5fb..8f8d0f5 100644
--- a/src/events/guildCreate.ts
+++ b/src/events/guildCreate.ts
@@ -1,12 +1,11 @@
-import { MessageActionRow, MessageButton } from "discord.js";
-import EmojiEmbed from "../utils/generateEmojiEmbed.js";
-import getEmojiByName from "../utils/getEmojiByName.js";
+import type { Guild } from "discord.js";
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore
+import type { HaikuClient } from "jshaiku";
import guide from "../reflex/guide.js";
-export const event = 'guildCreate';
+export const event = "guildCreate";
-export async function callback(client, guild) {
- try{
- guide(guild)
- } catch {}
+export async function callback(_client: HaikuClient, guild: Guild) {
+ guide(guild);
}
diff --git a/src/events/guildMemberUpdate.ts b/src/events/guildMemberUpdate.ts
index d555647..a7f8c47 100644
--- a/src/events/guildMemberUpdate.ts
+++ b/src/events/guildMemberUpdate.ts
@@ -1,20 +1,20 @@
-export const event = 'guildMemberUpdate'
+export const event = "guildMemberUpdate";
export async function callback(client, before, after) {
try {
- const { log, NucleusColors, entry, renderUser, renderDelta, getAuditLog } = after.client.logger
- let auditLog = await getAuditLog(after.guild, 'MEMBER_UPDATE');
- let audit = auditLog.entries.filter(entry => entry.target.id === after.id).first();
+ const { log, NucleusColors, entry, renderUser, renderDelta, getAuditLog } = after.client.logger;
+ const auditLog = await getAuditLog(after.guild, "MEMBER_UPDATE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === after.id).first();
if (audit.executor.id === client.user.id) return;
if (before.nickname !== after.nickname) {
- try { await client.database.history.create(
+ await client.database.history.create(
"nickname", after.guild.id, after.user, audit.executor,
- null, before.nickname || before.user.username, after.nickname || after.user.username) } catch {}
- let data = {
+ null, before.nickname || before.user.username, after.nickname || after.user.username);
+ const data = {
meta: {
- type: 'memberUpdate',
- displayName: 'Nickname Changed',
- calculateType: 'guildMemberUpdate',
+ type: "memberUpdate",
+ displayName: "Nickname Changed",
+ calculateType: "guildMemberUpdate",
color: NucleusColors.yellow,
emoji: "PUNISH.NICKNAME.YELLOW",
timestamp: new Date().getTime()
@@ -22,25 +22,25 @@
list: {
memberId: entry(after.id, `\`${after.id}\``),
name: entry(after.user.id, renderUser(after.user)),
- before: entry(before.nickname, before.nickname ? before.nickname : '*None*'),
- after: entry(after.nickname, after.nickname ? after.nickname : '*None*'),
+ before: entry(before.nickname, before.nickname ? before.nickname : "*None*"),
+ after: entry(after.nickname, after.nickname ? after.nickname : "*None*"),
changed: entry(new Date().getTime(), renderDelta(new Date().getTime())),
changedBy: entry(audit.executor.id, renderUser(audit.executor))
},
hidden: {
guild: after.guild.id
}
- }
+ };
log(data);
} else if (before.communicationDisabledUntilTimestamp < new Date().getTime() && after.communicationDisabledUntil > new Date().getTime()) {
- try { await client.database.history.create(
+ await client.database.history.create(
"mute", after.guild.id, after.user, audit.executor, audit.reason, null, null, null
- )} catch {}
- let data = {
+ );
+ const data = {
meta: {
- type: 'memberMute',
- displayName: 'Muted',
- calculateType: 'guildMemberPunish',
+ type: "memberMute",
+ displayName: "Muted",
+ calculateType: "guildMemberPunish",
color: NucleusColors.yellow,
emoji: "PUNISH.MUTE.YELLOW",
timestamp: new Date().getTime()
@@ -51,12 +51,12 @@
mutedUntil: entry(after.communicationDisabledUntilTimestamp, renderDelta(after.communicationDisabledUntilTimestamp)),
muted: entry(new Date().getTime(), renderDelta(new Date().getTime())),
mutedBy: entry(audit.executor.id, renderUser(audit.executor)),
- reason: entry(audit.reason, audit.reason ? audit.reason : '\n> *No reason provided*')
+ reason: entry(audit.reason, audit.reason ? audit.reason : "\n> *No reason provided*")
},
hidden: {
guild: after.guild.id
}
- }
+ };
log(data);
client.database.eventScheduler.schedule("naturalUnmute", after.communicationDisabledUntil,
{guild: after.guild.id, user: after.id, expires: after.communicationDisabledUntilTimestamp}
@@ -65,14 +65,14 @@
after.communicationDisabledUntil === null && before.communicationDisabledUntilTimestamp !== null &&
new Date().getTime() >= audit.createdTimestamp
) {
- try { await client.database.history.create(
+ await client.database.history.create(
"unmute", after.guild.id, after.user, audit.executor, null, null, null, null
- )} catch {}
- let data = {
+ );
+ const data = {
meta: {
- type: 'memberUnmute',
- displayName: 'Unmuted',
- calculateType: 'guildMemberPunish',
+ type: "memberUnmute",
+ displayName: "Unmuted",
+ calculateType: "guildMemberPunish",
color: NucleusColors.green,
emoji: "PUNISH.MUTE.GREEN",
timestamp: new Date().getTime()
@@ -86,9 +86,9 @@
hidden: {
guild: after.guild.id
}
- }
+ };
log(data);
client.database.eventScheduler.cancel("naturalUnmute", {guild: after.guild.id, user: after.id, expires: before.communicationDisabledUntilTimestamp});
}
- } catch (e) { console.log(e) }
+ } catch (e) { console.log(e); }
}
diff --git a/src/events/guildUpdate.ts b/src/events/guildUpdate.ts
index e27975b..2cb1de8 100644
--- a/src/events/guildUpdate.ts
+++ b/src/events/guildUpdate.ts
@@ -1,61 +1,59 @@
-import { callback as statsChannelUpdate } from '../reflex/statsChannelUpdate.js';
+import { callback as statsChannelUpdate } from "../reflex/statsChannelUpdate.js";
-export const event = 'guildUpdate'
+export const event = "guildUpdate";
export async function callback(client, before, after) {
- try { await statsChannelUpdate(client, after.me); } catch(e) { console.log(e)}
- try {
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = after.client.logger
- let auditLog = await getAuditLog(after, 'GUILD_UPDATE');
- let audit = auditLog.entries.filter(entry => entry.target.id === after.id).first();
- if (audit.executor.id === client.user.id) return;
- let list = {}
+ await statsChannelUpdate(client, after.me);
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = after.client.logger;
+ const auditLog = await getAuditLog(after, "GUILD_UPDATE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === after.id).first();
+ if (audit.executor.id === client.user.id) return;
+ const list = {};
- const verificationLevels = {
- NONE: 'Unrestricted',
- LOW: 'Verified email',
- MEDIUM: 'Registered (5 minutes)',
- HIGH: 'Member (10 minutes)',
- VERY_HIGH: 'Verified phone'
+ const verificationLevels = {
+ NONE: "Unrestricted",
+ LOW: "Verified email",
+ MEDIUM: "Registered (5 minutes)",
+ HIGH: "Member (10 minutes)",
+ VERY_HIGH: "Verified phone"
+ };
+
+ const explicitContentFilterLevels = {
+ DISABLED: "Disabled",
+ MEMBERS_WITHOUT_ROLES: "Members without roles",
+ ALL_MEMBERS: "All members"
+ };
+
+ const MFALevels = {
+ NONE: "None",
+ ELEVATED: "Enabled"
+ };
+
+ if (before.name !== after.name) list["name"] = entry([before.name, after.name], `${before.name} -> ${after.name}`);
+ if (before.icon !== after.icon) list["icon"] = entry([before.icon, after.icon], `[Before](${before.iconURL()}) -> [After](${after.iconURL()})`);
+ if (before.splash !== after.splash) list["splash"] = entry([before.splash, after.splash], `[Before](${before.splashURL()}) -> [After](${after.splashURL()})`);
+ if (before.banner !== after.banner) list["banner"] = entry([before.banner, after.banner], `[Before](${before.bannerURL()}) -> [After](${after.bannerURL()})`);
+ if (before.owner !== after.owner) list["owner"] = entry([before.owner, after.owner], `${renderUser(before.owner.user)} -> ${renderUser(after.owner.user)}`);
+ if (before.verificationLevel !== after.verificationLevel) list["verificationLevel"] = entry([verificationLevels[before.verificationLevel], verificationLevels[after.verificationLevel]], `${verificationLevels[before.verificationLevel]} -> ${verificationLevels[after.verificationLevel]}`);
+ if (before.explicitContentFilter !== after.explicitContentFilter) list["explicitContentFilter"] = entry([explicitContentFilterLevels[before.explicitContentFilter], explicitContentFilterLevels[after.explicitContentFilter]], `${explicitContentFilterLevels[before.explicitContentFilter]} -> ${explicitContentFilterLevels[after.explicitContentFilter]}`);
+ if (before.mfaLevel !== after.mfaLevel) list["2 factor authentication"] = entry([MFALevels[before.mfaLevel], MFALevels[after.mfaLevel]], `${MFALevels[before.mfaLevel]} -> ${MFALevels[after.mfaLevel]}`);
+
+ if (!(Object.keys(list).length)) return;
+ list["updated"] = entry(new Date().getTime(), renderDelta(new Date().getTime()));
+ list["updatedBy"] = entry(audit.executor.id, renderUser(audit.executor));
+ const data = {
+ meta: {
+ type: "guildUpdate",
+ displayName: "Guild Edited",
+ calculateType: "guildUpdate",
+ color: NucleusColors.yellow,
+ emoji: "GUILD.YELLOW",
+ timestamp: new Date().getTime()
+ },
+ list: list,
+ hidden: {
+ guild: after.id
}
-
- const explicitContentFilterLevels = {
- DISABLED: 'Disabled',
- MEMBERS_WITHOUT_ROLES: 'Members without roles',
- ALL_MEMBERS: 'All members'
- }
-
- const MFALevels = {
- NONE: 'None',
- ELEVATED: 'Enabled'
- }
-
- if (before.name !== after.name) list["name"] = entry([before.name, after.name], `${before.name} -> ${after.name}`);
- if (before.icon !== after.icon) list["icon"] = entry([before.icon, after.icon], `[Before](${before.iconURL()}) -> [After](${after.iconURL()})`);
- if (before.splash !== after.splash) list["splash"] = entry([before.splash, after.splash], `[Before](${before.splashURL()}) -> [After](${after.splashURL()})`);
- if (before.banner !== after.banner) list["banner"] = entry([before.banner, after.banner], `[Before](${before.bannerURL()}) -> [After](${after.bannerURL()})`);
- if (before.owner !== after.owner) list["owner"] = entry([before.owner, after.owner], `${renderUser(before.owner.user)} -> ${renderUser(after.owner.user)}`);
- if (before.verificationLevel !== after.verificationLevel) list["verificationLevel"] = entry([verificationLevels[before.verificationLevel], verificationLevels[after.verificationLevel]], `${verificationLevels[before.verificationLevel]} -> ${verificationLevels[after.verificationLevel]}`);
- if (before.explicitContentFilter !== after.explicitContentFilter) list["explicitContentFilter"] = entry([explicitContentFilterLevels[before.explicitContentFilter], explicitContentFilterLevels[after.explicitContentFilter]], `${explicitContentFilterLevels[before.explicitContentFilter]} -> ${explicitContentFilterLevels[after.explicitContentFilter]}`);
- if (before.mfaLevel !== after.mfaLevel) list["2 factor authentication"] = entry([MFALevels[before.mfaLevel], MFALevels[after.mfaLevel]], `${MFALevels[before.mfaLevel]} -> ${MFALevels[after.mfaLevel]}`);
-
- if (!(Object.keys(list).length)) return;
- list["updated"] = entry(new Date().getTime(), renderDelta(new Date().getTime()))
- list["updatedBy"] = entry(audit.executor.id, renderUser(audit.executor))
- let data = {
- meta: {
- type: 'guildUpdate',
- displayName: 'Guild Edited',
- calculateType: 'guildUpdate',
- color: NucleusColors.yellow,
- emoji: "GUILD.YELLOW",
- timestamp: new Date().getTime()
- },
- list: list,
- hidden: {
- guild: after.id
- }
- }
- log(data);
- } catch (e) {}
+ };
+ log(data);
}
diff --git a/src/events/interactionCreate.ts b/src/events/interactionCreate.ts
index a4bb8c3..08fcc77 100644
--- a/src/events/interactionCreate.ts
+++ b/src/events/interactionCreate.ts
@@ -1,57 +1,56 @@
-import { callback as roleMenu } from "../actions/roleMenu.js"
+import { callback as roleMenu } from "../actions/roleMenu.js";
import verify from "../reflex/verify.js";
import create from "../actions/tickets/create.js";
import close from "../actions/tickets/delete.js";
import createTranscript from "../premium/createTranscript.js";
import Fuse from "fuse.js";
-import { autocomplete as tagAutocomplete } from "../commands/tag.js"
+import { autocomplete as tagAutocomplete } from "../commands/tag.js";
-export const event = 'interactionCreate';
+export const event = "interactionCreate";
function getAutocomplete(typed: string, options: string[]): object[] {
- options = options.filter(option => option.length <= 100) // thanks discord. 6000 character limit on slash command inputs but only 100 for autocomplete.
- if (!typed) return options.slice(0, 25).sort().map(option => ({name: option, value: option}))
- const fuse = new Fuse(options, {useExtendedSearch: true, findAllMatches: true, minMatchCharLength: 0}).search(typed)
- return fuse.slice(0, 25).map(option => ({name: option.item, value: option.item}))
+ options = options.filter(option => option.length <= 100); // thanks discord. 6000 character limit on slash command inputs but only 100 for autocomplete.
+ if (!typed) return options.slice(0, 25).sort().map(option => ({name: option, value: option}));
+ const fuse = new Fuse(options, {useExtendedSearch: true, findAllMatches: true, minMatchCharLength: 0}).search(typed);
+ return fuse.slice(0, 25).map(option => ({name: option.item, value: option.item}));
}
function generateStatsChannelAutocomplete(typed) {
- const validReplacements = ["serverName", "memberCount", "memberCount:bots", "memberCount:humans"]
- let autocompletions = []
- const beforeLastOpenBracket = typed.match(/(.*){[^{}]{0,15}$/)
- if (beforeLastOpenBracket !== null) { for (let replacement of validReplacements) { autocompletions.push(`${beforeLastOpenBracket[1]} {${replacement}}`) } }
- else { for (let replacement of validReplacements) { autocompletions.push(`${typed} {${replacement}}`) } }
- return getAutocomplete(typed, autocompletions)
+ const validReplacements = ["serverName", "memberCount", "memberCount:bots", "memberCount:humans"];
+ const autocompletions = [];
+ const beforeLastOpenBracket = typed.match(/(.*){[^{}]{0,15}$/);
+ if (beforeLastOpenBracket !== null) { for (const replacement of validReplacements) { autocompletions.push(`${beforeLastOpenBracket[1]} {${replacement}}`); } }
+ else { for (const replacement of validReplacements) { autocompletions.push(`${typed} {${replacement}}`); } }
+ return getAutocomplete(typed, autocompletions);
}
function generateWelcomeMessageAutocomplete(typed) {
- const validReplacements = ["serverName", "memberCount", "memberCount:bots", "memberCount:humans", "member:mention", "member:name"]
- let autocompletions = []
- const beforeLastOpenBracket = typed.match(/(.*){[^{}]{0,15}$/)
- if (beforeLastOpenBracket !== null) { for (let replacement of validReplacements) { autocompletions.push(`${beforeLastOpenBracket[1]} {${replacement}}`) } }
- else { for (let replacement of validReplacements) { autocompletions.push(`${typed} {${replacement}}`) } }
- return getAutocomplete(typed, autocompletions)
+ const validReplacements = ["serverName", "memberCount", "memberCount:bots", "memberCount:humans", "member:mention", "member:name"];
+ const autocompletions = [];
+ const beforeLastOpenBracket = typed.match(/(.*){[^{}]{0,15}$/);
+ if (beforeLastOpenBracket !== null) { for (const replacement of validReplacements) { autocompletions.push(`${beforeLastOpenBracket[1]} {${replacement}}`); } }
+ else { for (const replacement of validReplacements) { autocompletions.push(`${typed} {${replacement}}`); } }
+ return getAutocomplete(typed, autocompletions);
}
async function interactionCreate(interaction) {
if (interaction.componentType === "BUTTON") {
switch (interaction.customId) {
- case "rolemenu": { return await roleMenu(interaction) }
- case "verifybutton": { return verify(interaction) }
- case "createticket": { return create(interaction) }
- case "closeticket": { return close(interaction) }
- case "createtranscript": { return createTranscript(interaction) }
+ case "rolemenu": { return await roleMenu(interaction); }
+ case "verifybutton": { return verify(interaction); }
+ case "createticket": { return create(interaction); }
+ case "closeticket": { return close(interaction); }
+ case "createtranscript": { return createTranscript(interaction); }
}
- } else if (interaction.componentType === "MESSAGE_COMPONENT") {
} else if (interaction.type === "APPLICATION_COMMAND_AUTOCOMPLETE") {
switch (`${interaction.commandName} ${interaction.options.getSubcommandGroup(false)} ${interaction.options.getSubcommand(false)}`) {
- case `tag null null`: { return interaction.respond(getAutocomplete(interaction.options.getString("tag"), (await tagAutocomplete(interaction)))) }
- case `settings null stats`: { return interaction.respond(generateStatsChannelAutocomplete(interaction.options.getString("name"))) }
- case `settings null welcome`: { return interaction.respond(generateWelcomeMessageAutocomplete(interaction.options.getString("message"))) }
+ case "tag null null": { return interaction.respond(getAutocomplete(interaction.options.getString("tag"), (await tagAutocomplete(interaction)))); }
+ case "settings null stats": { return interaction.respond(generateStatsChannelAutocomplete(interaction.options.getString("name"))); }
+ case "settings null welcome": { return interaction.respond(generateWelcomeMessageAutocomplete(interaction.options.getString("message"))); }
}
}
}
export async function callback(client, interaction) {
- await interactionCreate(interaction)
+ await interactionCreate(interaction);
}
\ No newline at end of file
diff --git a/src/events/inviteCreate.ts b/src/events/inviteCreate.ts
index 5d47bf8..1cbed02 100644
--- a/src/events/inviteCreate.ts
+++ b/src/events/inviteCreate.ts
@@ -1,32 +1,30 @@
-import humanizeDuration from 'humanize-duration';
-export const event = 'inviteCreate'
+import humanizeDuration from "humanize-duration";
+export const event = "inviteCreate";
export async function callback(client, invite) {
- try {
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = invite.client.logger
- let auditLog = await getAuditLog(invite.guild, 'INVITE_CREATE');
- let audit = auditLog.entries.filter(entry => entry.target.id === invite.id).first();
- if (audit.executor.id === client.user.id) return;
- let data = {
- meta: {
- type: 'inviteCreate',
- displayName: 'Invite Created',
- calculateType: 'guildUpdate',
- color: NucleusColors.green,
- emoji: "INVITE.CREATE",
- timestamp: invite.createdTimestamp
- },
- list: {
- channel: entry(invite.channel.id, renderChannel(invite.channel)),
- link: entry(invite.url, invite.url),
- expires: entry(invite.maxAge, invite.maxAge ? humanizeDuration(invite.maxAge * 1000) : 'Never'),
- createdBy: entry(audit.executor.id, renderUser(audit.executor)),
- created: entry(invite.createdTimestamp, renderDelta(invite.createdTimestamp))
- },
- hidden: {
- guild: invite.guild.id
- }
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = invite.client.logger;
+ const auditLog = await getAuditLog(invite.guild, "INVITE_CREATE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === invite.id).first();
+ if (audit.executor.id === client.user.id) return;
+ const data = {
+ meta: {
+ type: "inviteCreate",
+ displayName: "Invite Created",
+ calculateType: "guildUpdate",
+ color: NucleusColors.green,
+ emoji: "INVITE.CREATE",
+ timestamp: invite.createdTimestamp
+ },
+ list: {
+ channel: entry(invite.channel.id, renderChannel(invite.channel)),
+ link: entry(invite.url, invite.url),
+ expires: entry(invite.maxAge, invite.maxAge ? humanizeDuration(invite.maxAge * 1000) : "Never"),
+ createdBy: entry(audit.executor.id, renderUser(audit.executor)),
+ created: entry(invite.createdTimestamp, renderDelta(invite.createdTimestamp))
+ },
+ hidden: {
+ guild: invite.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
}
diff --git a/src/events/inviteDelete.ts b/src/events/inviteDelete.ts
index acfc9dd..cbe4d4b 100644
--- a/src/events/inviteDelete.ts
+++ b/src/events/inviteDelete.ts
@@ -1,32 +1,30 @@
-import humanizeDuration from 'humanize-duration';
-export const event = 'inviteDelete'
+import humanizeDuration from "humanize-duration";
+export const event = "inviteDelete";
export async function callback(client, invite) {
- try {
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = invite.client.logger
- let auditLog = await getAuditLog(invite.guild, 'INVITE_DELETE');
- let audit = auditLog.entries.filter(entry => entry.target.id === invite.id).first();
- if (audit.executor.id === client.user.id) return;
- let data = {
- meta: {
- type: 'inviteDelete',
- displayName: 'Invite Deleted',
- calculateType: 'guildUpdate',
- color: NucleusColors.red,
- emoji: "INVITE.DELETE",
- timestamp: new Date().getTime()
- },
- list: {
- channel: entry(invite.channel.id, renderChannel(invite.channel)),
- link: entry(invite.url, invite.url),
- expires: entry(invite.maxAge, invite.maxAge ? humanizeDuration(invite.maxAge * 1000) : 'Never'),
- deletedBy: entry(audit.executor.id, renderUser(audit.executor)),
- deleted: entry(new Date().getTime(), renderDelta(new Date().getTime()))
- },
- hidden: {
- guild: invite.guild.id
- }
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = invite.client.logger;
+ const auditLog = await getAuditLog(invite.guild, "INVITE_DELETE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === invite.id).first();
+ if (audit.executor.id === client.user.id) return;
+ const data = {
+ meta: {
+ type: "inviteDelete",
+ displayName: "Invite Deleted",
+ calculateType: "guildUpdate",
+ color: NucleusColors.red,
+ emoji: "INVITE.DELETE",
+ timestamp: new Date().getTime()
+ },
+ list: {
+ channel: entry(invite.channel.id, renderChannel(invite.channel)),
+ link: entry(invite.url, invite.url),
+ expires: entry(invite.maxAge, invite.maxAge ? humanizeDuration(invite.maxAge * 1000) : "Never"),
+ deletedBy: entry(audit.executor.id, renderUser(audit.executor)),
+ deleted: entry(new Date().getTime(), renderDelta(new Date().getTime()))
+ },
+ hidden: {
+ guild: invite.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
}
diff --git a/src/events/memberJoin.ts b/src/events/memberJoin.ts
index 109f226..34545fb 100644
--- a/src/events/memberJoin.ts
+++ b/src/events/memberJoin.ts
@@ -1,36 +1,33 @@
-import { callback as statsChannelAdd } from '../reflex/statsChannelUpdate.js';
-import { callback as welcome } from '../reflex/welcome.js';
-import log from '../utils/log.js';
-import client from '../utils/client.js';
+import { callback as statsChannelAdd } from "../reflex/statsChannelUpdate.js";
+import { callback as welcome } from "../reflex/welcome.js";
+import client from "../utils/client.js";
-export const event = 'guildMemberAdd'
+export const event = "guildMemberAdd";
export async function callback(_, member) {
- try { welcome(_, member); } catch {}
- try { statsChannelAdd(_, member, ); } catch {}
- try {
- const { log, NucleusColors, entry, renderUser, renderDelta } = member.client.logger
- try { await client.database.history.create("join", member.guild.id, member.user, null, null) } catch {}
- let data = {
- meta: {
- type: 'memberJoin',
- displayName: 'Member Joined',
- calculateType: 'guildMemberUpdate',
- color: NucleusColors.green,
- emoji: "MEMBER" + (member.user.bot ? ".BOT" : "") + ".JOIN",
- timestamp: member.joinedTimestamp
- },
- list: {
- memberId: entry(member.id, `\`${member.id}\``),
- name: entry(member.id, renderUser(member.user)),
- joined: entry(member.joinedAt, renderDelta(member.joinedAt)),
- accountCreated: entry(member.user.createdAt, renderDelta(member.user.createdAt)),
- serverMemberCount: member.guild.memberCount,
- },
- hidden: {
- guild: member.guild.id
- }
+ welcome(_, member);
+ statsChannelAdd(_, member );
+ const { log, NucleusColors, entry, renderUser, renderDelta } = member.client.logger;
+ await client.database.history.create("join", member.guild.id, member.user, null, null);
+ const data = {
+ meta: {
+ type: "memberJoin",
+ displayName: "Member Joined",
+ calculateType: "guildMemberUpdate",
+ color: NucleusColors.green,
+ emoji: "MEMBER" + (member.user.bot ? ".BOT" : "") + ".JOIN",
+ timestamp: member.joinedTimestamp
+ },
+ list: {
+ memberId: entry(member.id, `\`${member.id}\``),
+ name: entry(member.id, renderUser(member.user)),
+ joined: entry(member.joinedAt, renderDelta(member.joinedAt)),
+ accountCreated: entry(member.user.createdAt, renderDelta(member.user.createdAt)),
+ serverMemberCount: member.guild.memberCount
+ },
+ hidden: {
+ guild: member.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
}
diff --git a/src/events/memberLeave.ts b/src/events/memberLeave.ts
index 5dff86f..842a48b 100644
--- a/src/events/memberLeave.ts
+++ b/src/events/memberLeave.ts
@@ -1,72 +1,70 @@
-import { purgeByUser } from '../actions/tickets/delete.js';
-import { callback as statsChannelRemove } from '../reflex/statsChannelUpdate.js';
+import { purgeByUser } from "../actions/tickets/delete.js";
+import { callback as statsChannelRemove } from "../reflex/statsChannelUpdate.js";
-export const event = 'guildMemberRemove'
+export const event = "guildMemberRemove";
export async function callback(client, member) {
- try { purgeByUser(member.id, member.guild); } catch {}
- try { await statsChannelRemove(client, member); } catch {}
- try {
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = member.client.logger
- let auditLog = await getAuditLog(member.guild, 'MEMBER_KICK');
- let audit = auditLog.entries.filter(entry => entry.target.id === member.id).first();
- let type = "leave"
- if (audit) {
- if (audit.executor.id === client.user.id) return
- if (audit.createdAt - 100 >= new Date().getTime()) {
- type = "kick"
- }
+ purgeByUser(member.id, member.guild);
+ await statsChannelRemove(client, member);
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = member.client.logger;
+ const auditLog = await getAuditLog(member.guild, "MEMBER_KICK");
+ const audit = auditLog.entries.filter(entry => entry.target.id === member.id).first();
+ let type = "leave";
+ if (audit) {
+ if (audit.executor.id === client.user.id) return;
+ if (audit.createdAt - 100 >= new Date().getTime()) {
+ type = "kick";
}
- let data
- if (type === "kick") {
- try { await client.database.history.create("kick", member.guild.id, member.user, audit.executor, audit.reason) } catch {}
- data = {
- meta: {
- type: 'memberKick',
- displayName: 'Member Kicked',
- calculateType: 'guildMemberPunish',
- color: NucleusColors.red,
- emoji: "PUNISH.KICK.RED",
- timestamp: new Date().getTime()
- },
- list: {
- memberId: entry(member.id, `\`${member.id}\``),
- name: entry(member.id, renderUser(member.user)),
- joined: entry(member.joinedAt, renderDelta(member.joinedAt)),
- kicked: entry(new Date().getTime(), renderDelta(new Date().getTime())),
- kickedBy: entry(audit.executor.id, renderUser(audit.executor)),
- reason: entry(audit.reason, audit.reason ? `\n> ${audit.reason}` : "*No reason provided.*"),
- accountCreated: entry(member.user.createdAt, renderDelta(member.user.createdAt)),
- serverMemberCount: member.guild.memberCount,
- },
- hidden: {
- guild: member.guild.id
- }
+ }
+ let data;
+ if (type === "kick") {
+ await client.database.history.create("kick", member.guild.id, member.user, audit.executor, audit.reason);
+ data = {
+ meta: {
+ type: "memberKick",
+ displayName: "Member Kicked",
+ calculateType: "guildMemberPunish",
+ color: NucleusColors.red,
+ emoji: "PUNISH.KICK.RED",
+ timestamp: new Date().getTime()
+ },
+ list: {
+ memberId: entry(member.id, `\`${member.id}\``),
+ name: entry(member.id, renderUser(member.user)),
+ joined: entry(member.joinedAt, renderDelta(member.joinedAt)),
+ kicked: entry(new Date().getTime(), renderDelta(new Date().getTime())),
+ kickedBy: entry(audit.executor.id, renderUser(audit.executor)),
+ reason: entry(audit.reason, audit.reason ? `\n> ${audit.reason}` : "*No reason provided.*"),
+ accountCreated: entry(member.user.createdAt, renderDelta(member.user.createdAt)),
+ serverMemberCount: member.guild.memberCount
+ },
+ hidden: {
+ guild: member.guild.id
}
- } else {
- try { await client.database.history.create("leave", member.guild.id, member.user, null, null) } catch {}
- data = {
- meta: {
- type: 'memberLeave',
- displayName: 'Member Left',
- calculateType: 'guildMemberUpdate',
- color: NucleusColors.red,
- emoji: "MEMBER." + (member.bot ? "BOT." : "") + "LEAVE",
- timestamp: new Date().getTime()
- },
- list: {
- memberId: entry(member.id, `\`${member.id}\``),
- name: entry(member.id, renderUser(member.user)),
- joined: entry(member.joinedTimestamp, renderDelta(member.joinedAt)),
- left: entry(new Date().getTime(), renderDelta(new Date().getTime())),
- accountCreated: entry(member.user.createdAt, renderDelta(member.user.createdAt)),
- serverMemberCount: member.guild.memberCount,
- },
- hidden: {
- guild: member.guild.id
- }
+ };
+ } else {
+ await client.database.history.create("leave", member.guild.id, member.user, null, null);
+ data = {
+ meta: {
+ type: "memberLeave",
+ displayName: "Member Left",
+ calculateType: "guildMemberUpdate",
+ color: NucleusColors.red,
+ emoji: "MEMBER." + (member.bot ? "BOT." : "") + "LEAVE",
+ timestamp: new Date().getTime()
+ },
+ list: {
+ memberId: entry(member.id, `\`${member.id}\``),
+ name: entry(member.id, renderUser(member.user)),
+ joined: entry(member.joinedTimestamp, renderDelta(member.joinedAt)),
+ left: entry(new Date().getTime(), renderDelta(new Date().getTime())),
+ accountCreated: entry(member.user.createdAt, renderDelta(member.user.createdAt)),
+ serverMemberCount: member.guild.memberCount
+ },
+ hidden: {
+ guild: member.guild.id
}
- }
- log(data);
- } catch (e) { console.log(e) }
+ };
+ }
+ log(data);
}
diff --git a/src/events/messageCreate.ts b/src/events/messageCreate.ts
index cbb1fa2..bbb6a32 100644
--- a/src/events/messageCreate.ts
+++ b/src/events/messageCreate.ts
@@ -1,28 +1,33 @@
-import { LinkCheck, MalwareCheck, NSFWCheck, SizeCheck, TestString, TestImage } from '../reflex/scanners.js'
-import logAttachment from '../premium/attachmentLogs.js'
-import createLogException from '../utils/createLogException.js'
-import getEmojiByName from '../utils/getEmojiByName.js';
-import client from '../utils/client.js';
-import {callback as a} from '../reflex/statsChannelUpdate.js'
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore
+import { HaikuClient } from "jshaiku";
+import { LinkCheck, MalwareCheck, NSFWCheck, SizeCheck, TestString, TestImage } from "../reflex/scanners.js";
+import logAttachment from "../premium/attachmentLogs.js";
+import createLogException from "../utils/createLogException.js";
+import getEmojiByName from "../utils/getEmojiByName.js";
+import client from "../utils/client.js";
+import {callback as a} from "../reflex/statsChannelUpdate.js";
+import type { Message } from "discord.js";
-export const event = 'messageCreate'
+export const event = "messageCreate";
-export async function callback(_, message) {
+export async function callback(_client: HaikuClient, message: Message) {
if(!message) return;
- if (message.author.bot) return
- if (message.channel.type === 'dm') return
- try { await a(client, await message.guild.members.fetch(message.author.id)); } catch(e) { console.log(e)}
+ if(!message.guild) return;
+ if (message.author.bot) return;
+ if (message.channel.type === "DM") return;
+ try { await a(client, await message.guild.members.fetch(message.author.id)); } catch(e) { console.log(e);}
- const { log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger
+ const { log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger;
- let fileNames = await logAttachment(message);
+ const fileNames = await logAttachment(message);
- let content = message.content.toLowerCase() || ''
- let config = await client.memory.readGuildInfo(message.guild.id);
- const filter = getEmojiByName("ICONS.FILTER")
- let attachmentJump = ""
- if (config.logging.attachments.saved[message.channel.id + message.id]) { attachmentJump = ` [[View attachments]](${config.logging.attachments.saved[message.channel.id + message.id]})` }
- let list = {
+ const content = message.content.toLowerCase() || "";
+ const config = await client.memory.readGuildInfo(message.guild.id);
+ const filter = getEmojiByName("ICONS.FILTER");
+ let attachmentJump = "";
+ if (config.logging.attachments.saved[message.channel.id + message.id]) { attachmentJump = ` [[View attachments]](${config.logging.attachments.saved[message.channel.id + message.id]})`; }
+ const list = {
messageId: entry(message.id, `\`${message.id}\``),
sentBy: entry(message.author.id, renderUser(message.author)),
sentIn: entry(message.channel.id, renderChannel(message.channel)),
@@ -33,116 +38,115 @@
message.reference ? message.reference.messageId : null,
message.reference ? `[[Jump to message]](https://discord.com/channels/${message.guild.id}/${message.channel.id}/${message.reference.messageId})` : "None"
)
- }
+ };
if (config.filters.invite.enabled) {
- if (!config.filters.invite.allowed.users.includes(message.author.id) ||
- !config.filters.invite.allowed.channels.includes(message.channel.id) ||
- !message.author.roles.cache.some(role => config.filters.invite.allowed.roles.includes(role.id))
- ) {
+ if (!config.filters.invite.allowed.channels.includes(message.channel.id)) {
if ((/(?:https?:\/\/)?discord(?:app)?\.(?:com\/invite|gg)\/[a-zA-Z0-9]+\/?/.test(content))) {
- createLogException(message.guild.id, message.channel.id, message.id)
+ createLogException(message.guild.id, message.channel.id, message.id);
message.delete();
- let data = {
+ const data = {
meta: {
- type: 'messageDelete',
- displayName: 'Message Deleted (Automated, Contained Invite)',
- calculateType: 'autoModeratorDeleted',
+ type: "messageDelete",
+ displayName: "Message Deleted (Automated, Contained Invite)",
+ calculateType: "autoModeratorDeleted",
color: NucleusColors.red,
- emoji: 'MESSAGE.DELETE',
+ emoji: "MESSAGE.DELETE",
timestamp: new Date().getTime()
},
separate: {
- start: filter + " Contained invite\n\n" + (content ? `**Message:**\n\`\`\`${content}\`\`\`` : '**Message:** *Message had no content*'),
+ start: filter + " Contained invite\n\n" + (content ? `**Message:**\n\`\`\`${content}\`\`\`` : "**Message:** *Message had no content*")
},
list: list,
hidden: {
guild: message.channel.guild.id
}
- }
+ };
return log(data);
}
}
}
if (fileNames.files.length > 0) {
- for (let element of fileNames.files) {
+ for (const element of fileNames.files) {
if(!message) return;
- let url = element.url ? element.url : element.local
+ const url = element.url ? element.url : element.local;
if (url !== undefined) {
if(/\.(jpg|jpeg|png|gif|gifv|webm|webp|mp4|wav|mp3|ogg)$/.test(url)) {
- if (config.filters.images.NSFW && !message.channel.nsfw) {
+ if (config.filters.images.NSFW && !(
+ message.channel.type === "GUILD_PUBLIC_THREAD" ? false : message.channel.nsfw
+ )) {
if (await NSFWCheck(url)) {
- createLogException(message.guild.id, message.channel.id, message.id)
- await message.delete()
- let data = {
+ createLogException(message.guild.id, message.channel.id, message.id);
+ await message.delete();
+ const data = {
meta: {
- type: 'messageDelete',
- displayName: 'Message Deleted',
- calculateType: 'autoModeratorDeleted',
+ type: "messageDelete",
+ displayName: "Message Deleted",
+ calculateType: "autoModeratorDeleted",
color: NucleusColors.red,
- emoji: 'MESSAGE.DELETE',
+ emoji: "MESSAGE.DELETE",
timestamp: new Date().getTime()
},
separate: {
- start: filter + " Image detected as NSFW\n\n" + (content ? `**Message:**\n\`\`\`${content}\`\`\`` : '**Message:** *Message had no content*'),
+ start: filter + " Image detected as NSFW\n\n" + (content ? `**Message:**\n\`\`\`${content}\`\`\`` : "**Message:** *Message had no content*")
},
list: list,
hidden: {
guild: message.channel.guild.id
}
- }
+ };
return log(data);
}
}
if (config.filters.wordFilter.enabled) {
- let text = await TestImage(url)
- let check = TestString(text, config.filters.wordFilter.words.loose, config.filters.wordFilter.words.strict)
+ const text = await TestImage(url);
+ const check = TestString(text ?? "", config.filters.wordFilter.words.loose, config.filters.wordFilter.words.strict);
if(check !== null) {
- createLogException(message.guild.id, message.channel.id, message.id)
- await message.delete()
- let data = {
+ createLogException(message.guild.id, message.channel.id, message.id);
+ await message.delete();
+ const data = {
meta: {
- type: 'messageDelete',
- displayName: 'Message Deleted',
- calculateType: 'autoModeratorDeleted',
+ type: "messageDelete",
+ displayName: "Message Deleted",
+ calculateType: "autoModeratorDeleted",
color: NucleusColors.red,
- emoji: 'MESSAGE.DELETE',
+ emoji: "MESSAGE.DELETE",
timestamp: new Date().getTime()
},
separate: {
- start: filter + " Image contained filtered word\n\n" + (content ? `**Message:**\n\`\`\`${content}\`\`\`` : '**Message:** *Message had no content*'),
+ start: filter + " Image contained filtered word\n\n" + (content ? `**Message:**\n\`\`\`${content}\`\`\`` : "**Message:** *Message had no content*")
},
list: list,
hidden: {
guild: message.channel.guild.id
}
- }
+ };
return log(data);
}
}
if (config.filters.images.size) {
if(url.match(/\.+(webp|png|jpg)$/gi)) {
if(!await SizeCheck(element)) {
- createLogException(message.guild.id, message.channel.id, message.id)
- await message.delete()
- let data = {
+ createLogException(message.guild.id, message.channel.id, message.id);
+ await message.delete();
+ const data = {
meta: {
- type: 'messageDelete',
- displayName: 'Message Deleted',
- calculateType: 'autoModeratorDeleted',
+ type: "messageDelete",
+ displayName: "Message Deleted",
+ calculateType: "autoModeratorDeleted",
color: NucleusColors.red,
- emoji: 'MESSAGE.DELETE',
+ emoji: "MESSAGE.DELETE",
timestamp: new Date().getTime()
},
separate: {
- start: filter + " Image was too small\n\n" + (content ? `**Message:**\n\`\`\`${content}\`\`\`` : '**Message:** *Message had no content*'),
+ start: filter + " Image was too small\n\n" + (content ? `**Message:**\n\`\`\`${content}\`\`\`` : "**Message:** *Message had no content*")
},
list: list,
hidden: {
guild: message.channel.guild.id
}
- }
+ };
return log(data);
}
}
@@ -150,150 +154,150 @@
}
if (config.filters.malware) {
if (!MalwareCheck(url)) {
- createLogException(message.guild.id, message.channel.id, message.id)
- await message.delete()
- let data = {
+ createLogException(message.guild.id, message.channel.id, message.id);
+ await message.delete();
+ const data = {
meta: {
- type: 'messageDelete',
- displayName: 'Message Deleted',
- calculateType: 'autoModeratorDeleted',
+ type: "messageDelete",
+ displayName: "Message Deleted",
+ calculateType: "autoModeratorDeleted",
color: NucleusColors.red,
- emoji: 'MESSAGE.DELETE',
+ emoji: "MESSAGE.DELETE",
timestamp: new Date().getTime()
},
separate: {
- start: filter + " File detected as malware\n\n" + (content ? `**Message:**\n\`\`\`${content}\`\`\`` : '**Message:** *Message had no content*'),
+ start: filter + " File detected as malware\n\n" + (content ? `**Message:**\n\`\`\`${content}\`\`\`` : "**Message:** *Message had no content*")
},
list: list,
hidden: {
guild: message.channel.guild.id
}
- }
+ };
return log(data);
}
}
}
- };
+ }
}
if(!message) return;
- let linkDetectionTypes = await LinkCheck(message)
+ const linkDetectionTypes = await LinkCheck(message);
if (linkDetectionTypes.length > 0) {
- createLogException(message.guild.id, message.channel.id, message.id)
- await message.delete()
- let data = {
+ createLogException(message.guild.id, message.channel.id, message.id);
+ await message.delete();
+ const data = {
meta: {
- type: 'messageDelete',
- displayName: `Message Deleted`,
- calculateType: 'autoModeratorDeleted',
+ type: "messageDelete",
+ displayName: "Message Deleted",
+ calculateType: "autoModeratorDeleted",
color: NucleusColors.red,
- emoji: 'MESSAGE.DELETE',
+ emoji: "MESSAGE.DELETE",
timestamp: new Date().getTime()
},
separate: {
- start: filter + ` Link filtered as ${linkDetectionTypes[0].toLowerCase()}\n\n` + (content ? `**Message:**\n\`\`\`${content}\`\`\`` : '**Message:** *Message had no content*'),
+ start: filter + ` Link filtered as ${linkDetectionTypes[0]?.toLowerCase()}\n\n` + (content ? `**Message:**\n\`\`\`${content}\`\`\`` : "**Message:** *Message had no content*")
},
list: list,
hidden: {
guild: message.channel.guild.id
}
- }
+ };
return log(data);
}
if (config.filters.wordFilter.enabled) {
- let check = TestString(content, config.filters.wordFilter.words.loose, config.filters.wordFilter.words.strict)
+ const check = TestString(content, config.filters.wordFilter.words.loose, config.filters.wordFilter.words.strict);
if(check !== null) {
- createLogException(message.guild.id, message.channel.id, message.id)
- await message.delete()
- let data = {
+ createLogException(message.guild.id, message.channel.id, message.id);
+ await message.delete();
+ const data = {
meta: {
- type: 'messageDelete',
- displayName: 'Message Deleted',
- calculateType: 'autoModeratorDeleted',
+ type: "messageDelete",
+ displayName: "Message Deleted",
+ calculateType: "autoModeratorDeleted",
color: NucleusColors.red,
- emoji: 'MESSAGE.DELETE',
+ emoji: "MESSAGE.DELETE",
timestamp: new Date().getTime()
},
separate: {
- start: filter + ` Message contained filtered word\n\n` + (content ? `**Message:**\n\`\`\`${content}\`\`\`` : '**Message:** *Message had no content*'),
+ start: filter + " Message contained filtered word\n\n" + (content ? `**Message:**\n\`\`\`${content}\`\`\`` : "**Message:** *Message had no content*")
},
list: list,
hidden: {
guild: message.channel.guild.id
}
- }
+ };
return log(data);
}
}
if (config.filters.pings.everyone && message.mentions.everyone) {
- let data = {
+ const data = {
meta: {
- type: 'everyonePing',
- displayName: 'Everyone Pinged',
- calculateType: 'messageMassPing',
+ type: "everyonePing",
+ displayName: "Everyone Pinged",
+ calculateType: "messageMassPing",
color: NucleusColors.yellow,
- emoji: 'MESSAGE.PING.EVERYONE',
+ emoji: "MESSAGE.PING.EVERYONE",
timestamp: new Date().getTime()
},
separate: {
- start: content ? `**Message:**\n\`\`\`${content}\`\`\`` : '**Message:** *Message had no content*',
+ start: content ? `**Message:**\n\`\`\`${content}\`\`\`` : "**Message:** *Message had no content*"
},
list: list,
hidden: {
guild: message.channel.guild.id
}
- }
+ };
return log(data);
}
if (config.filters.pings.roles) {
- for(let role of message.mentions.roles) {
+ for(const roleId in message.mentions.roles) {
if(!message) return;
- if (!config.filters.pings.allowed.roles.includes(role.id)) {
- createLogException(message.guild.id, message.channel.id, message.id)
- await message.delete()
- let data = {
+ if (!config.filters.pings.allowed.roles.includes(roleId)) {
+ createLogException(message.guild.id, message.channel.id, message.id);
+ await message.delete();
+ const data = {
meta: {
- type: 'rolePing',
- displayName: 'Role Pinged',
- calculateType: 'messageMassPing',
+ type: "rolePing",
+ displayName: "Role Pinged",
+ calculateType: "messageMassPing",
color: NucleusColors.yellow,
- emoji: 'MESSAGE.PING.ROLE',
+ emoji: "MESSAGE.PING.ROLE",
timestamp: new Date().getTime()
},
separate: {
- start: content ? `**Message:**\n\`\`\`${content}\`\`\`` : '**Message:** *Message had no content*',
+ start: content ? `**Message:**\n\`\`\`${content}\`\`\`` : "**Message:** *Message had no content*"
},
list: list,
hidden: {
guild: message.channel.guild.id
}
- }
+ };
return log(data);
}
}
}
if (message.mentions.users.size >= config.filters.pings.mass && config.filters.pings.mass) {
- createLogException(message.guild.id, message.channel.id, message.id)
- await message.delete()
- let data = {
+ createLogException(message.guild.id, message.channel.id, message.id);
+ await message.delete();
+ const data = {
meta: {
- type: 'massPing',
- displayName: `Mass Ping`,
- calculateType: 'messageMassPing',
+ type: "massPing",
+ displayName: "Mass Ping",
+ calculateType: "messageMassPing",
color: NucleusColors.yellow,
- emoji: 'MESSAGE.PING.MASS',
+ emoji: "MESSAGE.PING.MASS",
timestamp: new Date().getTime()
},
separate: {
- start: content ? `**Message:**\n\`\`\`${content}\`\`\`` : '**Message:** *Message had no content*',
+ start: content ? `**Message:**\n\`\`\`${content}\`\`\`` : "**Message:** *Message had no content*"
},
list: list,
hidden: {
guild: message.channel.guild.id
}
- }
+ };
return log(data);
}
}
diff --git a/src/events/messageDelete.ts b/src/events/messageDelete.ts
index b139297..473fa52 100644
--- a/src/events/messageDelete.ts
+++ b/src/events/messageDelete.ts
@@ -1,34 +1,34 @@
-export const event = 'messageDelete'
+export const event = "messageDelete";
export async function callback(client, message) {
try {
if (message.author.id === client.user.id) return;
if (client.noLog.includes(`${message.guild.id}/${message.channel.id}/${message.id}`)) return;
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = message.channel.client.logger
- let auditLog = await getAuditLog(message.guild, 'MEMBER_BAN_ADD')
- let audit = auditLog.entries.filter(entry => entry.target.id === message.author.id).first();
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = message.channel.client.logger;
+ const auditLog = await getAuditLog(message.guild, "MEMBER_BAN_ADD");
+ const audit = auditLog.entries.filter(entry => entry.target.id === message.author.id).first();
if (audit) {
if (audit.createdAt - 100 < new Date().getTime()) return;
}
- message.reference = message.reference || {}
- let content = message.cleanContent
- content.replace(`\``, `\\\``)
- if (content.length > 256) content = content.substring(0, 253) + '...'
- let attachments = message.attachments.size + (message.content.match(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi) ?? []).length
- let attachmentJump = ""
- let config = (await client.database.guilds.read(message.guild.id)).logging.attachments.saved[message.channel.id + message.id];
- if (config) { attachmentJump = ` [[View attachments]](${config})` }
- let data = {
+ message.reference = message.reference || {};
+ let content = message.cleanContent;
+ content.replace("`", "\\`");
+ if (content.length > 256) content = content.substring(0, 253) + "...";
+ const attachments = message.attachments.size + (message.content.match(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/gi) ?? []).length;
+ let attachmentJump = "";
+ const config = (await client.database.guilds.read(message.guild.id)).logging.attachments.saved[message.channel.id + message.id];
+ if (config) { attachmentJump = ` [[View attachments]](${config})`; }
+ const data = {
meta: {
- type: 'messageDelete',
- displayName: 'Message Deleted',
- calculateType: 'messageDelete',
+ type: "messageDelete",
+ displayName: "Message Deleted",
+ calculateType: "messageDelete",
color: NucleusColors.red,
- emoji: 'MESSAGE.DELETE',
+ emoji: "MESSAGE.DELETE",
timestamp: new Date().getTime()
},
separate: {
- start: content ? `**Message:**\n\`\`\`${content}\`\`\`` : '**Message:** *Message had no content*',
+ start: content ? `**Message:**\n\`\`\`${content}\`\`\`` : "**Message:** *Message had no content*"
},
list: {
messageId: entry(message.id, `\`${message.id}\``),
@@ -45,7 +45,7 @@
hidden: {
guild: message.channel.guild.id
}
- }
+ };
log(data);
- } catch(e) { console.log(e) }
+ } catch(e) { console.log(e); }
}
diff --git a/src/events/messageEdit.ts b/src/events/messageEdit.ts
index 9e0e521..148cdb7 100644
--- a/src/events/messageEdit.ts
+++ b/src/events/messageEdit.ts
@@ -1,85 +1,83 @@
-export const event = 'messageUpdate'
+export const event = "messageUpdate";
export async function callback(client, oldMessage, newMessage) {
- try {
- if (newMessage.author.id === client.user.id) return;
- const { log, NucleusColors, entry, renderUser, renderDelta, renderNumberDelta, renderChannel } = newMessage.channel.client.logger
- newMessage.reference = newMessage.reference || {}
- let newContent = newMessage.cleanContent.replaceAll("`", "‘")
- let oldContent = oldMessage.cleanContent.replaceAll("`", "‘")
- let attachmentJump = "";
- let config = (await client.database.guilds.read(newMessage.guild.id)).logging.attachments.saved[newMessage.channel.id + newMessage.id];
- if (config) { attachmentJump = ` [[View attachments]](${config})` }
- if (newContent === oldContent) {
- if (!oldMessage.flags.has("CROSSPOSTED") && newMessage.flags.has("CROSSPOSTED")) {
- let data = {
- meta: {
- type: 'messageAnnounce',
- displayName: 'Message Published',
- calculateType: 'messageAnnounce',
- color: NucleusColors.yellow,
- emoji: 'MESSAGE.CREATE',
- timestamp: newMessage.editedTimestamp
- },
- separate: {
- end: `[[Jump to message]](${newMessage.url})`
- },
- list: {
- messageId: entry(newMessage.id, `\`${newMessage.id}\``),
- sentBy: entry(newMessage.author.id, renderUser(newMessage.author)),
- sentIn: entry(newMessage.channel.id, renderChannel(newMessage.channel)),
- sent: entry(new Date(newMessage.createdTimestamp), renderDelta(new Date(newMessage.createdTimestamp))),
- published: entry(new Date(newMessage.editedTimestamp), renderDelta(new Date(newMessage.editedTimestamp))),
- mentions: renderNumberDelta(oldMessage.mentions.users.size, newMessage.mentions.users.size),
- attachments: entry(
- renderNumberDelta(oldMessage.attachments.size, newMessage.attachments.size),
- renderNumberDelta(oldMessage.attachments.size, newMessage.attachments.size) + attachmentJump
- )
- },
- hidden: {
- guild: newMessage.channel.guild.id
- }
+ if (newMessage.author.id === client.user.id) return;
+ const { log, NucleusColors, entry, renderUser, renderDelta, renderNumberDelta, renderChannel } = newMessage.channel.client.logger;
+ newMessage.reference = newMessage.reference || {};
+ let newContent = newMessage.cleanContent.replaceAll("`", "‘");
+ let oldContent = oldMessage.cleanContent.replaceAll("`", "‘");
+ let attachmentJump = "";
+ const config = (await client.database.guilds.read(newMessage.guild.id)).logging.attachments.saved[newMessage.channel.id + newMessage.id];
+ if (config) { attachmentJump = ` [[View attachments]](${config})`; }
+ if (newContent === oldContent) {
+ if (!oldMessage.flags.has("CROSSPOSTED") && newMessage.flags.has("CROSSPOSTED")) {
+ const data = {
+ meta: {
+ type: "messageAnnounce",
+ displayName: "Message Published",
+ calculateType: "messageAnnounce",
+ color: NucleusColors.yellow,
+ emoji: "MESSAGE.CREATE",
+ timestamp: newMessage.editedTimestamp
+ },
+ separate: {
+ end: `[[Jump to message]](${newMessage.url})`
+ },
+ list: {
+ messageId: entry(newMessage.id, `\`${newMessage.id}\``),
+ sentBy: entry(newMessage.author.id, renderUser(newMessage.author)),
+ sentIn: entry(newMessage.channel.id, renderChannel(newMessage.channel)),
+ sent: entry(new Date(newMessage.createdTimestamp), renderDelta(new Date(newMessage.createdTimestamp))),
+ published: entry(new Date(newMessage.editedTimestamp), renderDelta(new Date(newMessage.editedTimestamp))),
+ mentions: renderNumberDelta(oldMessage.mentions.users.size, newMessage.mentions.users.size),
+ attachments: entry(
+ renderNumberDelta(oldMessage.attachments.size, newMessage.attachments.size),
+ renderNumberDelta(oldMessage.attachments.size, newMessage.attachments.size) + attachmentJump
+ )
+ },
+ hidden: {
+ guild: newMessage.channel.guild.id
}
- return log(data);
- }
- };
- if (!newMessage.editedTimestamp) { return }
- if (newContent.length > 256) newContent = newContent.substring(0, 253) + '...'
- if (oldContent.length > 256) oldContent = oldContent.substring(0, 253) + '...'
- let data = {
- meta: {
- type: 'messageUpdate',
- displayName: 'Message Edited',
- calculateType: 'messageUpdate',
- color: NucleusColors.yellow,
- emoji: 'MESSAGE.EDIT',
- timestamp: newMessage.editedTimestamp
- },
- separate: {
- start: (oldContent ? `**Before:**\n\`\`\`\n${oldContent}\n\`\`\`\n` : '**Before:** *Message had no content*\n') +
- (newContent ? `**After:**\n\`\`\`\n${newContent}\n\`\`\`` : '**After:** *Message had no content*'),
- end: `[[Jump to message]](${newMessage.url})`
- },
- list: {
- messageId: entry(newMessage.id, `\`${newMessage.id}\``),
- sentBy: entry(newMessage.author.id, renderUser(newMessage.author)),
- sentIn: entry(newMessage.channel.id, renderChannel(newMessage.channel)),
- sent: entry(new Date(newMessage.createdTimestamp), renderDelta(new Date(newMessage.createdTimestamp))),
- edited: entry(new Date(newMessage.editedTimestamp), renderDelta(new Date(newMessage.editedTimestamp))),
- mentions: renderNumberDelta(oldMessage.mentions.users.size, newMessage.mentions.users.size),
- attachments: entry(
- renderNumberDelta(oldMessage.attachments.size, newMessage.attachments.size),
- renderNumberDelta(oldMessage.attachments.size, newMessage.attachments.size) + attachmentJump
- ),
- repliedTo: entry(
- newMessage.reference.messageId || null,
- newMessage.reference.messageId ? `[[Jump to message]](https://discord.com/channels/${newMessage.guild.id}/${newMessage.channel.id}/${newMessage.reference.messageId})` : "None"
- )
- },
- hidden: {
- guild: newMessage.channel.guild.id
- }
+ };
+ return log(data);
}
- log(data);
- } catch {}
-}
+ }
+ if (!newMessage.editedTimestamp) { return; }
+ if (newContent.length > 256) newContent = newContent.substring(0, 253) + "...";
+ if (oldContent.length > 256) oldContent = oldContent.substring(0, 253) + "...";
+ const data = {
+ meta: {
+ type: "messageUpdate",
+ displayName: "Message Edited",
+ calculateType: "messageUpdate",
+ color: NucleusColors.yellow,
+ emoji: "MESSAGE.EDIT",
+ timestamp: newMessage.editedTimestamp
+ },
+ separate: {
+ start: (oldContent ? `**Before:**\n\`\`\`\n${oldContent}\n\`\`\`\n` : "**Before:** *Message had no content*\n") +
+ (newContent ? `**After:**\n\`\`\`\n${newContent}\n\`\`\`` : "**After:** *Message had no content*"),
+ end: `[[Jump to message]](${newMessage.url})`
+ },
+ list: {
+ messageId: entry(newMessage.id, `\`${newMessage.id}\``),
+ sentBy: entry(newMessage.author.id, renderUser(newMessage.author)),
+ sentIn: entry(newMessage.channel.id, renderChannel(newMessage.channel)),
+ sent: entry(new Date(newMessage.createdTimestamp), renderDelta(new Date(newMessage.createdTimestamp))),
+ edited: entry(new Date(newMessage.editedTimestamp), renderDelta(new Date(newMessage.editedTimestamp))),
+ mentions: renderNumberDelta(oldMessage.mentions.users.size, newMessage.mentions.users.size),
+ attachments: entry(
+ renderNumberDelta(oldMessage.attachments.size, newMessage.attachments.size),
+ renderNumberDelta(oldMessage.attachments.size, newMessage.attachments.size) + attachmentJump
+ ),
+ repliedTo: entry(
+ newMessage.reference.messageId || null,
+ newMessage.reference.messageId ? `[[Jump to message]](https://discord.com/channels/${newMessage.guild.id}/${newMessage.channel.id}/${newMessage.reference.messageId})` : "None"
+ )
+ },
+ hidden: {
+ guild: newMessage.channel.guild.id
+ }
+ };
+ log(data);
+}
\ No newline at end of file
diff --git a/src/events/roleCreate.ts b/src/events/roleCreate.ts
index 2f159ac..a717242 100644
--- a/src/events/roleCreate.ts
+++ b/src/events/roleCreate.ts
@@ -1,31 +1,29 @@
-export const event = 'roleCreate'
+export const event = "roleCreate";
export async function callback(client, role) {
- try {
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderRole } = role.client.logger
- if (role.managed) return;
- let auditLog = await getAuditLog(role.guild, 'ROLE_CREATE');
- let audit = auditLog.entries.filter(entry => entry.target.id === role.id).first();
- if (audit.executor.id === client.user.id) return;
- let data = {
- meta: {
- type: 'roleCreate',
- displayName: 'Role Created',
- calculateType: 'guildRoleUpdate',
- color: NucleusColors.green,
- emoji: "GUILD.ROLES.CREATE",
- timestamp: role.createdTimestamp
- },
- list: {
- roleId: entry(role.id, `\`${role.id}\``),
- role: entry(role.name, renderRole(role)),
- createdBy: entry(audit.executor.id, renderUser(audit.executor)),
- created: entry(role.createdTimestamp, renderDelta(role.createdTimestamp))
- },
- hidden: {
- guild: role.guild.id
- }
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderRole } = role.client.logger;
+ if (role.managed) return;
+ const auditLog = await getAuditLog(role.guild, "ROLE_CREATE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === role.id).first();
+ if (audit.executor.id === client.user.id) return;
+ const data = {
+ meta: {
+ type: "roleCreate",
+ displayName: "Role Created",
+ calculateType: "guildRoleUpdate",
+ color: NucleusColors.green,
+ emoji: "GUILD.ROLES.CREATE",
+ timestamp: role.createdTimestamp
+ },
+ list: {
+ roleId: entry(role.id, `\`${role.id}\``),
+ role: entry(role.name, renderRole(role)),
+ createdBy: entry(audit.executor.id, renderUser(audit.executor)),
+ created: entry(role.createdTimestamp, renderDelta(role.createdTimestamp))
+ },
+ hidden: {
+ guild: role.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
}
diff --git a/src/events/roleDelete.ts b/src/events/roleDelete.ts
index 3b43a55..ad74584 100644
--- a/src/events/roleDelete.ts
+++ b/src/events/roleDelete.ts
@@ -1,38 +1,36 @@
import getEmojiByName from "../utils/getEmojiByName.js";
-export const event = 'roleDelete'
+export const event = "roleDelete";
export async function callback(client, role) {
- try {
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = role.client.logger
- if (role.managed) return;
- let auditLog = await getAuditLog(role.guild, 'ROLE_DELETE');
- let audit = auditLog.entries.filter(entry => entry.target.id === role.id).first();
- if (audit.executor.id === client.user.id) return;
- let data = {
- meta: {
- type: 'roleDelete',
- displayName: 'Role Deleted',
- calculateType: 'guildRoleUpdate',
- color: NucleusColors.red,
- emoji: "GUILD.ROLES.DELETE",
- timestamp: audit.createdTimestamp,
- },
- list: {
- roleId: entry(role.id, `\`${role.id}\``),
- role: entry(role.name, role.name),
- color: entry(role.hexColor, `\`${role.hexColor}\``),
- showInMemberList: entry(role.hoist, role.hoist ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`),
- mentionable: entry(role.mentionable, role.mentionable ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`),
- members: entry(role.members.size, `${role.members.size}`),
- deletedBy: entry(audit.executor.id, renderUser(audit.executor)),
- created: entry(role.createdTimestamp, renderDelta(role.createdTimestamp)),
- deleted: entry(new Date().getTime(), renderDelta(new Date().getTime()))
- },
- hidden: {
- guild: role.guild.id
- }
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = role.client.logger;
+ if (role.managed) return;
+ const auditLog = await getAuditLog(role.guild, "ROLE_DELETE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === role.id).first();
+ if (audit.executor.id === client.user.id) return;
+ const data = {
+ meta: {
+ type: "roleDelete",
+ displayName: "Role Deleted",
+ calculateType: "guildRoleUpdate",
+ color: NucleusColors.red,
+ emoji: "GUILD.ROLES.DELETE",
+ timestamp: audit.createdTimestamp
+ },
+ list: {
+ roleId: entry(role.id, `\`${role.id}\``),
+ role: entry(role.name, role.name),
+ color: entry(role.hexColor, `\`${role.hexColor}\``),
+ showInMemberList: entry(role.hoist, role.hoist ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`),
+ mentionable: entry(role.mentionable, role.mentionable ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`),
+ members: entry(role.members.size, `${role.members.size}`),
+ deletedBy: entry(audit.executor.id, renderUser(audit.executor)),
+ created: entry(role.createdTimestamp, renderDelta(role.createdTimestamp)),
+ deleted: entry(new Date().getTime(), renderDelta(new Date().getTime()))
+ },
+ hidden: {
+ guild: role.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
}
diff --git a/src/events/roleUpdate.ts b/src/events/roleUpdate.ts
index 7c03c97..c51a9b3 100644
--- a/src/events/roleUpdate.ts
+++ b/src/events/roleUpdate.ts
@@ -1,49 +1,47 @@
import getEmojiByName from "../utils/getEmojiByName.js";
-export const event = 'roleUpdate';
+export const event = "roleUpdate";
export async function callback(client, or, nr) {
- try {
- const { getAuditLog, log, NucleusColors, entry, renderDelta, renderUser, renderRole } = client.logger
+ const { getAuditLog, log, NucleusColors, entry, renderDelta, renderUser, renderRole } = client.logger;
- let auditLog = await getAuditLog(nr.guild, 'ROLE_UPDATE');
- let audit = auditLog.entries.first();
- if (audit.executor.id === client.user.id) return;
+ const auditLog = await getAuditLog(nr.guild, "ROLE_UPDATE");
+ const audit = auditLog.entries.first();
+ if (audit.executor.id === client.user.id) return;
- let changes = {
- roleId: entry(nr.id, `\`${nr.id}\``),
- role: entry(nr.id, renderRole(nr)),
- edited: entry(new Date().getTime(), renderDelta(new Date().getTime())),
- editedBy: entry(audit.executor.id, renderUser((await nr.guild.members.fetch(audit.executor.id)).user)),
+ const changes = {
+ roleId: entry(nr.id, `\`${nr.id}\``),
+ role: entry(nr.id, renderRole(nr)),
+ edited: entry(new Date().getTime(), renderDelta(new Date().getTime())),
+ editedBy: entry(audit.executor.id, renderUser((await nr.guild.members.fetch(audit.executor.id)).user))
+ };
+ const mentionable = ["", ""];
+ const hoist = ["", ""];
+ mentionable[0] = or.mentionable ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`;
+ mentionable[1] = nr.mentionable ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`;
+ hoist[0] = or.hoist ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`;
+ hoist[1] = nr.hoist ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`;
+ if (or.name !== nr.name) changes["name"] = entry([or.name, nr.name], `${or.name} -> ${nr.name}`);
+ if (or.position !== nr.position) changes["position"] = entry([or.position, nr.position], `${or.position} -> ${nr.position}`);
+ if (or.hoist !== nr.hoist) changes["showInMemberList"] = entry([or.hoist, nr.hoist], `${hoist[0]} -> ${hoist[1]}`);
+ if (or.mentionable !== nr.mentionable) changes["mentionable"] = entry([or.mentionable, nr.mentionable], `${mentionable[0]} -> ${mentionable[1]}`);
+ if (or.hexColor !== nr.hexColor) changes["color"] = entry([or.hexColor, nr.hexColor], `\`${or.hexColor}\` -> \`${nr.hexColor}\``);
+
+ if (Object.keys(changes).length === 4) return;
+
+ const data = {
+ meta:{
+ type: "roleUpdate",
+ displayName: "Role Edited",
+ calculateType: "guildRoleUpdate",
+ color: NucleusColors.yellow,
+ emoji: "GUILD.ROLES.EDIT",
+ timestamp: audit.createdTimestamp
+ },
+ list: changes,
+ hidden: {
+ guild: nr.guild.id
}
- let mentionable = ["", ""]
- let hoist = ["", ""]
- mentionable[0] = or.mentionable ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`
- mentionable[1] = nr.mentionable ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`
- hoist[0] = or.hoist ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`
- hoist[1] = nr.hoist ? `${getEmojiByName("CONTROL.TICK")} Yes` : `${getEmojiByName("CONTROL.CROSS")} No`
- if (or.name !== nr.name) changes["name"] = entry([or.name, nr.name], `${or.name} -> ${nr.name}`);
- if (or.position !== nr.position) changes["position"] = entry([or.position, nr.position], `${or.position} -> ${nr.position}`);
- if (or.hoist !== nr.hoist) changes["showInMemberList"] = entry([or.hoist, nr.hoist], `${hoist[0]} -> ${hoist[1]}`);
- if (or.mentionable !== nr.mentionable) changes["mentionable"] = entry([or.mentionable, nr.mentionable], `${mentionable[0]} -> ${mentionable[1]}`);
- if (or.hexColor !== nr.hexColor) changes["color"] = entry([or.hexColor, nr.hexColor], `\`${or.hexColor}\` -> \`${nr.hexColor}\``);
-
- if (Object.keys(changes).length === 4) return
-
- let data = {
- meta:{
- type: 'roleUpdate',
- displayName: 'Role Edited',
- calculateType: 'guildRoleUpdate',
- color: NucleusColors.yellow,
- emoji: "GUILD.ROLES.EDIT",
- timestamp: audit.createdTimestamp
- },
- list: changes,
- hidden: {
- guild: nr.guild.id
- }
- } // TODO: show perms changed (webpage)
- log(data);
- } catch {}
+ }; // TODO: show perms changed (webpage)
+ log(data);
}
\ No newline at end of file
diff --git a/src/events/stickerCreate.ts b/src/events/stickerCreate.ts
index 669de32..43f2e9c 100644
--- a/src/events/stickerCreate.ts
+++ b/src/events/stickerCreate.ts
@@ -1,30 +1,28 @@
-export const event = 'stickerCreate'
+export const event = "stickerCreate";
export async function callback(client, emoji) {
- try {
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = emoji.client.logger
- let auditLog = await getAuditLog(emoji.guild, 'STICKER_CREATE');
- let audit = auditLog.entries.filter(entry => entry.target.id === emoji.id).first();
- if (audit.executor.id === client.user.id) return;
- let data = {
- meta: {
- type: 'stickerCreate',
- displayName: 'Sticker Created',
- calculateType: 'stickerUpdate',
- color: NucleusColors.green,
- emoji: "GUILD.EMOJI.CREATE",
- timestamp: emoji.createdTimestamp
- },
- list: {
- stickerId: entry(emoji.id, `\`${emoji.id}\``),
- emoji: entry(emoji.name, `\`:${emoji.name}:\``),
- createdBy: entry(audit.executor.id, renderUser(audit.executor)),
- created: entry(emoji.createdTimestamp, renderDelta(emoji.createdTimestamp))
- },
- hidden: {
- guild: emoji.guild.id
- }
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = emoji.client.logger;
+ const auditLog = await getAuditLog(emoji.guild, "STICKER_CREATE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === emoji.id).first();
+ if (audit.executor.id === client.user.id) return;
+ const data = {
+ meta: {
+ type: "stickerCreate",
+ displayName: "Sticker Created",
+ calculateType: "stickerUpdate",
+ color: NucleusColors.green,
+ emoji: "GUILD.EMOJI.CREATE",
+ timestamp: emoji.createdTimestamp
+ },
+ list: {
+ stickerId: entry(emoji.id, `\`${emoji.id}\``),
+ emoji: entry(emoji.name, `\`:${emoji.name}:\``),
+ createdBy: entry(audit.executor.id, renderUser(audit.executor)),
+ created: entry(emoji.createdTimestamp, renderDelta(emoji.createdTimestamp))
+ },
+ hidden: {
+ guild: emoji.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
}
diff --git a/src/events/stickerDelete.ts b/src/events/stickerDelete.ts
index 0431bda..297e6b0 100644
--- a/src/events/stickerDelete.ts
+++ b/src/events/stickerDelete.ts
@@ -1,31 +1,29 @@
-export const event = 'stickerDelete'
+export const event = "stickerDelete";
export async function callback(client, emoji) {
- try{
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = emoji.client.logger
- let auditLog = await getAuditLog(emoji.guild, 'STICKER_DELETE');
- let audit = auditLog.entries.filter(entry => entry.target.id === emoji.id).first();
- if (audit.executor.id === client.user.id) return;
- let data = {
- meta: {
- type: 'stickerDelete',
- displayName: 'Sticker Deleted',
- calculateType: 'stickerUpdate',
- color: NucleusColors.red,
- emoji: "GUILD.EMOJI.DELETE",
- timestamp: audit.createdTimestamp,
- },
- list: {
- stickerId:entry(emoji.id, `\`${emoji.id}\``),
- sticker: entry(emoji.name, `\`${emoji.name}\``),
- deletedBy: entry(audit.executor.id, renderUser(audit.executor)),
- created: entry(emoji.createdTimestamp, renderDelta(emoji.createdTimestamp)),
- deleted: entry(audit.createdTimestamp, renderDelta(audit.createdTimestamp)),
- },
- hidden: {
- guild: emoji.guild.id
- }
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = emoji.client.logger;
+ const auditLog = await getAuditLog(emoji.guild, "STICKER_DELETE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === emoji.id).first();
+ if (audit.executor.id === client.user.id) return;
+ const data = {
+ meta: {
+ type: "stickerDelete",
+ displayName: "Sticker Deleted",
+ calculateType: "stickerUpdate",
+ color: NucleusColors.red,
+ emoji: "GUILD.EMOJI.DELETE",
+ timestamp: audit.createdTimestamp
+ },
+ list: {
+ stickerId:entry(emoji.id, `\`${emoji.id}\``),
+ sticker: entry(emoji.name, `\`${emoji.name}\``),
+ deletedBy: entry(audit.executor.id, renderUser(audit.executor)),
+ created: entry(emoji.createdTimestamp, renderDelta(emoji.createdTimestamp)),
+ deleted: entry(audit.createdTimestamp, renderDelta(audit.createdTimestamp))
+ },
+ hidden: {
+ guild: emoji.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
}
diff --git a/src/events/stickerUpdate.ts b/src/events/stickerUpdate.ts
index 363e072..1bb0fe6 100644
--- a/src/events/stickerUpdate.ts
+++ b/src/events/stickerUpdate.ts
@@ -1,34 +1,32 @@
-export const event = 'stickerUpdate';
+export const event = "stickerUpdate";
export async function callback(client, oe, ne) {
- try {
- const { getAuditLog, log, NucleusColors, entry, renderDelta, renderUser, renderEmoji } = client.logger
+ const { getAuditLog, log, NucleusColors, entry, renderDelta, renderUser } = client.logger;
- if (oe.name === ne.name) return
- let auditLog = await getAuditLog(ne.guild, 'EMOJI_UPDATE');
- let audit = auditLog.entries.first();
- if (audit.executor.id === client.user.id) return;
+ if (oe.name === ne.name) return;
+ const auditLog = await getAuditLog(ne.guild, "EMOJI_UPDATE");
+ const audit = auditLog.entries.first();
+ if (audit.executor.id === client.user.id) return;
- let changes = {
- stickerId:entry(ne.id, `\`${ne.id}\``),
- edited: entry(ne.createdTimestamp, renderDelta(ne.createdTimestamp)),
- editedBy: entry(audit.executor.id, renderUser((await ne.guild.members.fetch(audit.executor.id)).user)),
- name: entry([oe.name, ne.name], `\`:${oe.name}:\` -> \`:${ne.name}:\``),
+ const changes = {
+ stickerId:entry(ne.id, `\`${ne.id}\``),
+ edited: entry(ne.createdTimestamp, renderDelta(ne.createdTimestamp)),
+ editedBy: entry(audit.executor.id, renderUser((await ne.guild.members.fetch(audit.executor.id)).user)),
+ name: entry([oe.name, ne.name], `\`:${oe.name}:\` -> \`:${ne.name}:\``)
+ };
+ const data = {
+ meta:{
+ type: "stickerUpdate",
+ displayName: "Sticker Edited",
+ calculateType: "stickerUpdate",
+ color: NucleusColors.yellow,
+ emoji: "GUILD.EMOJI.EDIT",
+ timestamp: audit.createdTimestamp
+ },
+ list: changes,
+ hidden: {
+ guild: ne.guild.id
}
- let data = {
- meta:{
- type: 'stickerUpdate',
- displayName: 'Sticker Edited',
- calculateType: 'stickerUpdate',
- color: NucleusColors.yellow,
- emoji: "GUILD.EMOJI.EDIT",
- timestamp: audit.createdTimestamp
- },
- list: changes,
- hidden: {
- guild: ne.guild.id
- }
- }
- log(data);
- } catch {}
+ };
+ log(data);
}
\ No newline at end of file
diff --git a/src/events/threadCreate.ts b/src/events/threadCreate.ts
index ef7246d..d6b9e93 100644
--- a/src/events/threadCreate.ts
+++ b/src/events/threadCreate.ts
@@ -1,34 +1,32 @@
-import humanizeDuration from 'humanize-duration';
-export const event = 'threadCreate'
+import humanizeDuration from "humanize-duration";
+export const event = "threadCreate";
export async function callback(client, thread) {
- try {
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = thread.client.logger
- let auditLog = await getAuditLog(thread.guild, 'THREAD_CREATE');
- let audit = auditLog.entries.filter(entry => entry.target.id === thread.id).first();
- if (audit.executor.id === client.user.id) return;
- let data = {
- meta: {
- type: 'channelCreate',
- displayName: 'Thread Created',
- calculateType: 'channelUpdate',
- color: NucleusColors.green,
- emoji: "CHANNEL.TEXT.CREATE",
- timestamp: thread.createdTimestamp
- },
- list: {
- threadId:entry(thread.id, `\`${thread.id}\``),
- name: entry(thread.name, renderChannel(thread)),
- parentChannel: entry(thread.parentId, renderChannel(thread.parent)),
- category: entry(thread.parent.parent ? thread.parent.parent.name : 'None', thread.parent.parent ? renderChannel(thread.parent.parent) : 'None'),
- autoArchiveDuration: entry(thread.autoArchiveDuration, humanizeDuration(thread.autoArchiveDuration * 60 * 1000, { round: true })),
- createdBy: entry(audit.executor.id, renderUser(audit.executor)),
- created: entry(thread.createdTimestamp, renderDelta(thread.createdTimestamp))
- },
- hidden: {
- guild: thread.guild.id
- }
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = thread.client.logger;
+ const auditLog = await getAuditLog(thread.guild, "THREAD_CREATE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === thread.id).first();
+ if (audit.executor.id === client.user.id) return;
+ const data = {
+ meta: {
+ type: "channelCreate",
+ displayName: "Thread Created",
+ calculateType: "channelUpdate",
+ color: NucleusColors.green,
+ emoji: "CHANNEL.TEXT.CREATE",
+ timestamp: thread.createdTimestamp
+ },
+ list: {
+ threadId:entry(thread.id, `\`${thread.id}\``),
+ name: entry(thread.name, renderChannel(thread)),
+ parentChannel: entry(thread.parentId, renderChannel(thread.parent)),
+ category: entry(thread.parent.parent ? thread.parent.parent.name : "None", thread.parent.parent ? renderChannel(thread.parent.parent) : "None"),
+ autoArchiveDuration: entry(thread.autoArchiveDuration, humanizeDuration(thread.autoArchiveDuration * 60 * 1000, { round: true })),
+ createdBy: entry(audit.executor.id, renderUser(audit.executor)),
+ created: entry(thread.createdTimestamp, renderDelta(thread.createdTimestamp))
+ },
+ hidden: {
+ guild: thread.guild.id
}
- log(data);
- } catch {}
+ };
+ log(data);
}
diff --git a/src/events/threadDelete.ts b/src/events/threadDelete.ts
index 9574826..f3a59e7 100644
--- a/src/events/threadDelete.ts
+++ b/src/events/threadDelete.ts
@@ -1,17 +1,16 @@
-import humanizeDuration from 'humanize-duration';
-export const event = 'threadDelete'
+import humanizeDuration from "humanize-duration";
+export const event = "threadDelete";
export async function callback(client, thread) {
- try {
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = thread.client.logger
- let auditLog = await getAuditLog(thread.guild, 'THREAD_UPDATE');
- let audit = auditLog.entries.filter(entry => entry.target.id === thread.id).first();
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = thread.client.logger;
+ const auditLog = await getAuditLog(thread.guild, "THREAD_UPDATE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === thread.id).first();
if (audit.executor.id === client.user.id) return;
- let data = {
+ const data = {
meta: {
- type: 'channelDelete',
- displayName: 'Thread Deleted',
- calculateType: 'channelUpdate',
+ type: "channelDelete",
+ displayName: "Thread Deleted",
+ calculateType: "channelUpdate",
color: NucleusColors.red,
emoji: "CHANNEL.TEXT.DELETE",
timestamp: new Date().getTime()
@@ -20,7 +19,7 @@
threadId:entry(thread.id, `\`${thread.id}\``),
name: entry(thread.name, thread.name),
parentChannel: entry(thread.parentId, renderChannel(thread.parent)),
- category: entry(thread.parent.parent ? thread.parent.parent.name : 'None', thread.parent.parent ? renderChannel(thread.parent.parent) : 'None'),
+ category: entry(thread.parent.parent ? thread.parent.parent.name : "None", thread.parent.parent ? renderChannel(thread.parent.parent) : "None"),
autoArchiveDuration: entry(thread.autoArchiveDuration, humanizeDuration(thread.autoArchiveDuration * 60 * 1000, { round: true })),
membersInThread: entry(thread.memberCount, thread.memberCount),
deletedBy: entry(audit.executor.id, renderUser(audit.executor)),
@@ -30,7 +29,6 @@
hidden: {
guild: thread.guild.id
}
- }
+ };
log(data);
- } catch {}
}
diff --git a/src/events/threadUpdate.ts b/src/events/threadUpdate.ts
index 8550ffe..89a721c 100644
--- a/src/events/threadUpdate.ts
+++ b/src/events/threadUpdate.ts
@@ -1,43 +1,41 @@
-import humanizeDuration from 'humanize-duration';
-export const event = 'threadUpdate'
+import humanizeDuration from "humanize-duration";
+export const event = "threadUpdate";
export async function callback(client, before, after) {
- try {
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = after.client.logger
- let auditLog = await getAuditLog(after.guild, 'THREAD_UPDATE');
- let audit = auditLog.entries.filter(entry => entry.target.id === after.id).first();
- if (audit.executor.id === client.user.id) return;
- let list = {
- threadId:entry(after.id, `\`${after.id}\``),
- thread: entry(after.name, renderChannel(after)),
- parentChannel: entry(after.parentId, renderChannel(after.parent)),
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = after.client.logger;
+ const auditLog = await getAuditLog(after.guild, "THREAD_UPDATE");
+ const audit = auditLog.entries.filter(entry => entry.target.id === after.id).first();
+ if (audit.executor.id === client.user.id) return;
+ const list = {
+ 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}`);
+ }
+ if (before.autoArchiveDuration !== after.autoArchiveDuration) {
+ list["autoArchiveDuration"] = entry([before.autoArchiveDuration, after.autoArchiveDuration], `${humanizeDuration(before.autoArchiveDuration * 60 * 1000, { round: true })} -> ${humanizeDuration(after.autoArchiveDuration * 60 * 1000, { round: true })}`);
+ }
+ if (before.rateLimitPerUser !== after.rateLimitPerUser) {
+ list["slowmode"] = entry([before.rateLimitPerUser, after.rateLimitPerUser], `${humanizeDuration(before.rateLimitPerUser * 1000)} -> ${humanizeDuration(after.rateLimitPerUser * 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));
+ const data = {
+ meta: {
+ type: "channelUpdate",
+ displayName: "Thread Edited",
+ calculateType: "channelUpdate",
+ color: NucleusColors.yellow,
+ emoji: "CHANNEL.TEXT.EDIT",
+ timestamp: new Date().getTime()
+ },
+ list: list,
+ hidden: {
+ guild: after.guild.id
}
- if (before.name !== after.name) {
- list["name"] = entry([before.name, after.name], `${before.name} -> ${after.name}`);
- }
- if (before.autoArchiveDuration !== after.autoArchiveDuration) {
- list["autoArchiveDuration"] = entry([before.autoArchiveDuration, after.autoArchiveDuration], `${humanizeDuration(before.autoArchiveDuration * 60 * 1000, { round: true })} -> ${humanizeDuration(after.autoArchiveDuration * 60 * 1000, { round: true })}`);
- }
- if (before.rateLimitPerUser !== after.rateLimitPerUser) {
- list["slowmode"] = entry([before.rateLimitPerUser, after.rateLimitPerUser], `${humanizeDuration(before.rateLimitPerUser * 1000)} -> ${humanizeDuration(after.rateLimitPerUser * 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))
- let data = {
- meta: {
- type: 'channelUpdate',
- displayName: 'Thread Edited',
- calculateType: 'channelUpdate',
- color: NucleusColors.yellow,
- emoji: "CHANNEL.TEXT.EDIT",
- timestamp: new Date().getTime()
- },
- list: list,
- hidden: {
- guild: after.guild.id
- }
- }
- log(data);
- } catch {}
+ };
+ log(data);
}
diff --git a/src/events/webhookUpdate.ts b/src/events/webhookUpdate.ts
index 28768b2..a11fa63 100644
--- a/src/events/webhookUpdate.ts
+++ b/src/events/webhookUpdate.ts
@@ -1,35 +1,38 @@
-import humanizeDuration from 'humanize-duration';
-export const event = 'webhookUpdate'
+import type Discord from "discord.js";
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore
+import type { HaikuClient } from "jshaiku";
+export const event = "webhookUpdate";
-export async function callback(client, channel) {
+export async function callback(client: HaikuClient, channel: Discord.GuildChannel) {
try {
- const { getAuditLog, log, NucleusColors, entry, renderUser, renderChannel, renderDelta } = client.logger
- let auditLogCreate = getAuditLog(channel.guild, 'WEBHOOK_CREATE');
- let auditLogUpdate = getAuditLog(channel.guild, 'WEBHOOK_UPDATE');
- let auditLogDelete = getAuditLog(channel.guild, 'WEBHOOK_DELETE');
+ const { getAuditLog, log, NucleusColors, entry, renderUser, renderChannel, renderDelta } = client.logger;
+ let auditLogCreate = getAuditLog(channel.guild, "WEBHOOK_CREATE");
+ let auditLogUpdate = getAuditLog(channel.guild, "WEBHOOK_UPDATE");
+ let auditLogDelete = getAuditLog(channel.guild, "WEBHOOK_DELETE");
[auditLogCreate, auditLogUpdate, auditLogDelete] = await Promise.all([auditLogCreate, auditLogUpdate, auditLogDelete]);
- let auditCreate = auditLogCreate.entries.filter(entry => entry.target.channelId === channel.id).first();
- let auditUpdate = auditLogUpdate.entries.filter(entry => entry.target.channelId === channel.id).first();
- let auditDelete = auditLogDelete.entries.filter(entry => entry.target.channelId === channel.id).first();
+ 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();
if (!auditCreate && !auditUpdate && !auditDelete) return;
let audit = auditCreate;
let action = "Create";
- let list = {} as any;
+ let list = {} as {created: { value: string, displayValue: string }, updated: { value: string, displayValue: string }, deleted: { value: string, displayValue: string }};
if (auditUpdate && auditUpdate.createdTimestamp > audit.createdTimestamp) {
- let {before, after} = auditUpdate.changes.reduce(
+ const {before, after} = auditUpdate.changes.reduce(
(acc, change) => { acc.before[change.key] = change.old; acc.after[change.key] = change.new; return acc; },
{before: {}, after: {}}
);
- if (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([before.channel_id, after.channel_id], renderChannel(await client.channels.fetch(before.channel_id)) + ` -> ` + renderChannel(await client.channels.fetch(after.channel_id)))
+ if (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([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));
audit = auditUpdate;
- action = "Update"
+ action = "Update";
} else if (auditDelete && auditDelete.createdTimestamp > audit.createdTimestamp) {
- let {before, after} = auditDelete.changes.reduce(
+ const {before} = auditDelete.changes.reduce(
(acc, change) => { acc.before[change.key] = change.old; acc.after[change.key] = change.new; return acc; },
{before: {}, after: {}}
);
@@ -38,12 +41,12 @@
channel: entry(before.channel_id, renderChannel(await client.channels.fetch(before.channel_id))),
created: entry(auditDelete.target.createdTimestamp, renderDelta(auditDelete.target.createdTimestamp)),
deleted: entry(new Date().getTime(), renderDelta(new Date().getTime())),
- deletedBy: entry(auditDelete.executor.id, renderUser((await channel.guild.members.fetch(auditDelete.executor.id)).user)),
- }
+ deletedBy: entry(auditDelete.executor.id, renderUser((await channel.guild.members.fetch(auditDelete.executor.id)).user))
+ };
audit = auditDelete;
- action = "Delete"
+ action = "Delete";
} else {
- let {before, after} = auditDelete.changes.reduce(
+ const {before} = auditDelete.changes.reduce(
(acc, change) => { acc.before[change.key] = change.old; acc.after[change.key] = change.new; return acc; },
{before: {}, after: {}}
);
@@ -51,19 +54,19 @@
name: entry(before.name, `${before.name}`),
channel: entry(before.channel_id, renderChannel(await client.channels.fetch(before.channel_id))),
createdBy: entry(auditCreate.executor.id, renderUser((await channel.guild.members.fetch(auditCreate.executor.id)).user)),
- created: entry(new Date().getTime(), renderDelta(new Date().getTime())),
- }
+ created: entry(new Date().getTime(), renderDelta(new Date().getTime()))
+ };
}
- let cols = {
+ const cols = {
"Create": "green",
"Update": "yellow",
- "Delete": "red",
- }
- let data = {
+ "Delete": "red"
+ };
+ const data = {
meta: {
- type: 'webhook' + action,
+ type: "webhook" + action,
displayName: `Webhook ${action}d`,
- calculateType: 'webhookUpdate',
+ calculateType: "webhookUpdate",
color: NucleusColors[cols[action]],
emoji: "WEBHOOK." + action.toUpperCase(),
timestamp: new Date().getTime()
@@ -72,7 +75,7 @@
hidden: {
guild: channel.guild.id
}
- }
+ };
log(data);
- } catch(e) { console.log(e) }
+ } catch(e) { console.log(e); }
}
diff --git a/src/index.ts b/src/index.ts
index 5f5987e..22436e2 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,10 +1,10 @@
-import { Logger } from './utils/log.js';
-import runServer from './api/index.js';
-import Memory from './utils/memory.js';
-import { Guilds, History, ModNotes, Premium } from './utils/database.js';
-import client from './utils/client.js';
-import EventScheduler from './utils/eventScheduler.js';
+import { Logger } from "./utils/log.js";
+import runServer from "./api/index.js";
+import Memory from "./utils/memory.js";
+import { Guilds, History, ModNotes, Premium } from "./utils/database.js";
+import client from "./utils/client.js";
+import EventScheduler from "./utils/eventScheduler.js";
await client.registerCommandsIn("./commands");
await client.registerEventsIn("./events");
@@ -15,17 +15,17 @@
console.error(err);
});
-client.logger = new Logger()
-client.verify = {}
-client.roleMenu = {}
-client.memory = new Memory()
-client.noLog = []
+client.logger = new Logger();
+client.verify = {};
+client.roleMenu = {};
+client.memory = new Memory();
+client.noLog = [];
client.database = {
guilds: await new Guilds().setup(),
history: await new History().setup(),
notes: await new ModNotes().setup(),
premium: await new Premium().setup(),
eventScheduler: await new EventScheduler().start()
-}
+};
await client.login();
\ No newline at end of file
diff --git a/src/premium/attachmentLogs.ts b/src/premium/attachmentLogs.ts
index ed9a4ab..5a771bc 100644
--- a/src/premium/attachmentLogs.ts
+++ b/src/premium/attachmentLogs.ts
@@ -1,42 +1,44 @@
-import client from '../utils/client.js';
-import keyValueList from '../utils/generateKeyValueList.js';
-import singleNotify from '../utils/singleNotify.js';
-import { saveAttachment } from '../reflex/scanners.js';
-import EmojiEmbed from '../utils/generateEmojiEmbed.js';
-import addPlural from '../utils/plurals.js';
+import client from "../utils/client.js";
+import keyValueList from "../utils/generateKeyValueList.js";
+import singleNotify from "../utils/singleNotify.js";
+import { saveAttachment } from "../reflex/scanners.js";
+import EmojiEmbed from "../utils/generateEmojiEmbed.js";
+import addPlural from "../utils/plurals.js";
+import type { Message } from "discord.js";
-export default async function logAttachment(message): Promise<AttachmentLogSchema> {
+export default async function logAttachment(message: Message): Promise<AttachmentLogSchema> {
+ if (!message.guild) throw new Error("Tried to log an attachment in a non-guild message");
const { renderUser, renderChannel, renderDelta } = client.logger;
- let attachments = []
- for (let attachment of message.attachments.values()) {
- attachments.push({local: await saveAttachment(attachment.url), url: attachment.url})
+ const attachments = [];
+ for (const attachment of message.attachments.values()) {
+ attachments.push({local: await saveAttachment(attachment.url), url: attachment.url, height: attachment.height, width: attachment.width, size: attachment.size});
}
- let links = message.content.match(/https?:\/\/\S+/gi) || [];
- for (let link of links) {
+ const links = message.content.match(/https?:\/\/\S+/gi) || [];
+ for (const link of links) {
if (link.toLowerCase().match(/\.(jpg|jpeg|png|gif|gifv|webm|webp|mp4|wav|mp3|ogg)$/gi)) {
- attachments.push({local: await saveAttachment(link), url: link})
+ attachments.push({local: await saveAttachment(link), url: link, height: null, width: null});
}
}
- if (attachments.length === 0) return {files: []}
+ if (attachments.length === 0) return {files: []};
if (client.database.premium.hasPremium(message.guild.id)) {
- let channel = (await client.database.guilds.read(message.guild.id)).logging.attachments.channel;
+ const channel = (await client.database.guilds.read(message.guild.id)).logging.attachments.channel;
if (!channel) {
singleNotify("noAttachmentLogChannel", message.guild.id, "No channel set for attachment logging", "Warning");
return {files: attachments};
}
- let channelObj = await client.channels.fetch(channel);
+ const channelObj = await client.channels.fetch(channel);
if (!channelObj) {
singleNotify("attachmentLogChannelDeleted", message.guild.id, "Attachment history channel was deleted", "Warning");
return {files: attachments};
}
- let m = await channelObj.send({embeds: [new EmojiEmbed()
+ const m = await channelObj.send({embeds: [new EmojiEmbed()
.setTitle(`${addPlural(attachments.length, "Attachment")} Sent`)
.setDescription(keyValueList({
"messageId": `\`${message.id}\``,
"sentBy": renderUser(message.author),
"sentIn": renderChannel(message.channel),
- "sent": renderDelta(new Date(message.createdTimestamp)),
+ "sent": renderDelta(new Date(message.createdTimestamp))
}) + `\n[[Jump to message]](${message.url})`)
.setEmoji("ICONS.ATTACHMENT")
.setStatus("Success")
@@ -44,7 +46,7 @@
// await client.database.guilds.write(interaction.guild.id, {[`tags.${name}`]: value});
client.database.guilds.write(
message.guild.id,
- {[`logging.attachments.saved.${message.channel.id}${message.id}`]: m.url},
+ {[`logging.attachments.saved.${message.channel.id}${message.id}`]: m.url}
);
return {files: attachments, jump: m.url};
} else {
@@ -55,7 +57,9 @@
export interface AttachmentLogSchema {
files: {
url: string,
- local: string;
+ local: string,
+ height: number | null,
+ width: number | null
}[],
jump?: string;
}
\ No newline at end of file
diff --git a/src/premium/createTranscript.ts b/src/premium/createTranscript.ts
index 55697b9..d5d7bb8 100644
--- a/src/premium/createTranscript.ts
+++ b/src/premium/createTranscript.ts
@@ -2,50 +2,50 @@
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
import getEmojiByName from "../utils/getEmojiByName.js";
import { PasteClient, Publicity, ExpireDate } from "pastebin-api";
-import config from '../config/main.json' assert {type: 'json'};
+import config from "../config/main.json" assert {type: "json"};
import client from "../utils/client.js";
-const pbClient = new PasteClient(config.pastebinApiKey)
+const pbClient = new PasteClient(config.pastebinApiKey);
export default async function (interaction) {
- const { log, NucleusColors, entry, renderUser, renderChannel, renderDelta } = client.logger
+ const { log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
- let messages = []
+ let messages = [];
let deleted = 100;
while (deleted === 100) {
let fetched;
await (interaction.channel as TextChannel).messages.fetch({limit: 100}).then(async (ms) => {
fetched = await (interaction.channel as TextChannel).bulkDelete(ms, true);
- })
- deleted = fetched.size
+ });
+ deleted = fetched.size;
if (fetched) {
- messages = messages.concat(fetched.map(m => m))
+ messages = messages.concat(fetched.map(m => m));
}
}
- let out = ""
+ let out = "";
messages.reverse().forEach(message => {
if (!message.author.bot) {
- let sentDate = new Date(message.createdTimestamp)
- out += `${message.author.username}#${message.author.discriminator} (${message.author.id}) [${sentDate.toUTCString()}]\n`
- let lines = message.content.split("\n")
- lines.forEach(line => {out += `> ${line}\n`})
- out += `\n\n`
+ const sentDate = new Date(message.createdTimestamp);
+ out += `${message.author.username}#${message.author.discriminator} (${message.author.id}) [${sentDate.toUTCString()}]\n`;
+ const lines = message.content.split("\n");
+ lines.forEach(line => {out += `> ${line}\n`;});
+ out += "\n\n";
}
- })
- let member = interaction.channel.guild.members.cache.get(interaction.channel.topic.split(" ")[0])
+ });
+ const member = interaction.channel.guild.members.cache.get(interaction.channel.topic.split(" ")[0]);
let m;
if (out !== "") {
const url = await pbClient.createPaste({
code: out,
expireDate: ExpireDate.Never,
name: `Ticket Transcript for ${member.user.username}#${member.user.discriminator} (Created at ${new Date(interaction.channel.createdTimestamp).toDateString()})`,
- publicity: Publicity.Unlisted,
- })
- let guildConfig = await client.database.guilds.read(interaction.guild.id);
+ publicity: Publicity.Unlisted
+ });
+ const guildConfig = await client.database.guilds.read(interaction.guild.id);
m = await interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Transcript")
- .setDescription(`You can view the transcript using the link below. You can save the link for later` + (guildConfig.logging.logs.channel ?
+ .setDescription("You can view the transcript using the link below. You can save the link for later" + (guildConfig.logging.logs.channel ?
` or find it in <#${guildConfig.logging.logs.channel}> once you press delete below. After this the channel will be deleted.`
: "."))
.setStatus("Success")
@@ -64,7 +64,7 @@
} else {
m = await interaction.reply({embeds: [new EmojiEmbed()
.setTitle("Transcript")
- .setDescription(`The transcript was empty, so no changes were made. To delete this ticket, press the delete button below.`)
+ .setDescription("The transcript was empty, so no changes were made. To delete this ticket, press the delete button below.")
.setStatus("Success")
.setEmoji("CONTROL.DOWNLOAD")
], components: [new MessageActionRow().addComponents([
@@ -78,15 +78,15 @@
let i;
try {
i = await m.awaitMessageComponent({ time: 300000 });
- i.deferUpdate()
- } catch (e) { }
- let data = {
+ i.deferUpdate();
+ } catch { return; }
+ const data = {
meta:{
- type: 'ticketDeleted',
- displayName: 'Ticket Deleted',
+ type: "ticketDeleted",
+ displayName: "Ticket Deleted",
calculateType: "ticketUpdate",
color: NucleusColors.red,
- emoji: 'GUILD.TICKET.CLOSE',
+ emoji: "GUILD.TICKET.CLOSE",
timestamp: new Date().getTime()
},
list: {
@@ -97,8 +97,8 @@
hidden: {
guild: interaction.guild.id
}
- }
+ };
log(data);
- await interaction.channel.delete()
- return
+ await interaction.channel.delete();
+ return;
}
\ No newline at end of file
diff --git a/src/reflex/guide.ts b/src/reflex/guide.ts
index 517d7f4..640ec13 100644
--- a/src/reflex/guide.ts
+++ b/src/reflex/guide.ts
@@ -1,16 +1,15 @@
-import { LoadingEmbed } from './../utils/defaultEmbeds.js';
-import { SelectMenuOption } from '@discordjs/builders';
+import { LoadingEmbed } from "./../utils/defaultEmbeds.js";
+import { SelectMenuOption } from "@discordjs/builders";
import Discord, { MessageActionRow, MessageButton } from "discord.js";
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
import getEmojiByName from "../utils/getEmojiByName.js";
import createPageIndicator from "../utils/createPageIndicator.js";
-import client from "../utils/client.js";
class Embed {
embed: Discord.MessageEmbed;
title: string;
- description: string = "";
- pageId: number = 0;
+ description = "";
+ pageId = 0;
setEmbed(embed: Discord.MessageEmbed) { this.embed = embed; return this; }
setTitle(title: string) { this.title = title; return this; }
setDescription(description: string) { this.description = description; return this; }
@@ -20,7 +19,7 @@
export default async (guild, interaction?) => {
let c = guild.publicUpdatesChannel ? guild.publicUpdatesChannel : guild.systemChannel;
c = c ? c : guild.channels.cache.find(ch => ch.type === "GUILD_TEXT" && ch.permissionsFor(guild.roles.everyone).has("SEND_MESSAGES") && ch.permissionsFor(guild.me).has("EMBED_LINKS"));
- let pages = [
+ const pages = [
new Embed()
.setEmbed(new EmojiEmbed()
.setTitle("Welcome to Nucleus")
@@ -62,8 +61,8 @@
`**${getEmojiByName("PUNISH.BAN.RED")} Ban:** The user is removed from the server, and they are unable to rejoin.\n` +
`**${getEmojiByName("PUNISH.BAN.GREEN")} Unban:** The user is able to rejoin the server.`
)
- .setEmoji("PUNISH.BAN.RED")
- .setStatus("Danger")
+ .setEmoji("PUNISH.BAN.RED")
+ .setStatus("Danger")
).setTitle("Moderation").setDescription("Basic moderation commands").setPageId(2),
new Embed()
.setEmbed(new EmojiEmbed()
@@ -124,53 +123,53 @@
)
.setEmoji("NUCLEUS.COMMANDS.LOCK")
.setStatus("Danger")
- ).setTitle("Premium").setDescription("Premium features").setPageId(7),
- ]
+ ).setTitle("Premium").setDescription("Premium features").setPageId(7)
+ ];
let m;
if (interaction) { m = await interaction.reply({embeds: LoadingEmbed, fetchReply: true, ephemeral: true}); }
else { m = await c.send({embeds: LoadingEmbed }); }
let page = 0;
- let f = async (component) => {
+ const f = async (component) => {
return (component.member as Discord.GuildMember).permissions.has("MANAGE_GUILD");
- }
+ };
let selectPaneOpen = false;
while (true) {
- let selectPane = []
+ let selectPane = [];
if (selectPaneOpen) {
- let options = [];
+ const options = [];
pages.forEach(embed => {
options.push(new SelectMenuOption({
label: embed.title,
value: embed.pageId.toString(),
- description: embed.description || "",
- }))
- })
+ description: embed.description || ""
+ }));
+ });
selectPane = [new MessageActionRow().addComponents([
new Discord.MessageSelectMenu()
.addOptions(options)
.setCustomId("page")
.setMaxValues(1)
.setPlaceholder("Choose a page...")
- ])]
+ ])];
}
- let components = selectPane.concat([new MessageActionRow().addComponents([
+ const components = selectPane.concat([new MessageActionRow().addComponents([
new MessageButton().setCustomId("left").setEmoji(getEmojiByName("CONTROL.LEFT", "id")).setStyle("SECONDARY").setDisabled(page === 0),
new MessageButton().setCustomId("select").setEmoji(getEmojiByName("CONTROL.MENU", "id")).setStyle(selectPaneOpen ? "PRIMARY" : "SECONDARY").setDisabled(false),
new MessageButton().setCustomId("right").setEmoji(getEmojiByName("CONTROL.RIGHT", "id")).setStyle("SECONDARY").setDisabled(page === pages.length - 1)
- ])])
+ ])]);
if (interaction) {
- let 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 {
- let 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({
embeds: [em],
@@ -178,11 +177,11 @@
fetchReply: true
});
}
- let i
+ let i;
try {
- i = await m.awaitMessageComponent({filter: interaction ? () => { return true } : f, time: 300000});
- } catch(e) { break }
- i.deferUpdate()
+ i = await m.awaitMessageComponent({filter: interaction ? () => { return true; } : f, time: 300000});
+ } catch(e) { break; }
+ i.deferUpdate();
if (i.component.customId === "left") {
if (page > 0) page--;
selectPaneOpen = false;
@@ -196,9 +195,9 @@
selectPaneOpen = false;
} else {
if (interaction) {
- let 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"})
+ em.setFooter({text: "Message closed"});
interaction.editReply({embeds: [em], components: [new MessageActionRow().addComponents([
new MessageButton().setCustomId("left").setEmoji(getEmojiByName("CONTROL.LEFT", "id")).setStyle("SECONDARY").setDisabled(true),
new MessageButton().setCustomId("select").setEmoji(getEmojiByName("CONTROL.MENU", "id")).setStyle(selectPaneOpen ? "PRIMARY" : "SECONDARY").setDisabled(true),
@@ -211,7 +210,7 @@
}
}
if (interaction) {
- let 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"});
await interaction.editReply({
embeds: [em],
@@ -222,7 +221,7 @@
])]
});
} else {
- let 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"});
await m.edit({
embeds: [em],
@@ -233,4 +232,4 @@
])]
});
}
-}
+};
diff --git a/src/reflex/scanners.ts b/src/reflex/scanners.ts
index 3b80816..435ce4c 100644
--- a/src/reflex/scanners.ts
+++ b/src/reflex/scanners.ts
@@ -1,33 +1,36 @@
-import * as us from 'unscan'
-import fetch from 'node-fetch'
-import { writeFileSync } from 'fs'
-import generateFileName from '../utils/temp/generateFileName.js'
-import Tesseract from 'node-tesseract-ocr';
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore
+import * as us from "unscan";
+import fetch from "node-fetch";
+import { writeFileSync } from "fs";
+import generateFileName from "../utils/temp/generateFileName.js";
+import Tesseract from "node-tesseract-ocr";
+import type Discord from "discord.js";
interface NSFWSchema { nsfw: boolean }
interface MalwareSchema { safe: boolean }
export async function testNSFW(link: string): Promise<NSFWSchema> {
- let p = await saveAttachment(link)
- let result = await us.nsfw.file(p)
- return result
+ const p = await saveAttachment(link);
+ const result = await us.nsfw.file(p);
+ return result;
}
export async function testMalware(link: string): Promise<MalwareSchema> {
- let p = await saveAttachment(link)
- let result = await us.malware.file(p)
- return result
+ const p = await saveAttachment(link);
+ const result = await us.malware.file(p);
+ return result;
}
-export async function saveAttachment(link): Promise<string> {
- const image = (await (await fetch(link)).buffer()).toString('base64')
- let fileName = generateFileName(link.split('/').pop().split('.').pop())
- writeFileSync(fileName, image, 'base64')
- return fileName
+export async function saveAttachment(link: string): Promise<string> {
+ const image = (await (await fetch(link)).buffer()).toString("base64");
+ const fileName = generateFileName((link.split("/").pop() as string).split(".").pop() as string);
+ writeFileSync(fileName, image, "base64");
+ return fileName;
}
-export async function testLink(link: string): Promise<unknown> {
- return await us.link.scan(link)
+export async function testLink(link: string): Promise<{safe: boolean, tags: string[]}> {
+ return await us.link.scan(link);
}
@@ -49,71 +52,76 @@
"SCAMS": "Sites which are designed to trick you into doing something.",
"TORRENT": "Websites that download torrent files.",
"HATE": "Websites that spread hate towards groups or individuals.",
- "JUNK": "Websites that are designed to make you waste time.",
-}
+ "JUNK": "Websites that are designed to make you waste time."
+};
export { linkTypes };
-export async function LinkCheck(message): Promise<string[]> {
- let links = message.content.match(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi) ?? []
- let detections = []
- const promises = links.map(async element => {
+export async function LinkCheck(message: Discord.Message): Promise<string[]> {
+ const links = message.content.match(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/gi) ?? [];
+ const detections: {tags: string[], safe: boolean}[] = [];
+ const promises: Promise<void>[] = links.map(async element => {
+ let returned;
try {
- if (element.match(/https?:\/\/[a-zA-Z]+\.?discord(app)?\.(com|net)\/?/)) return // Also matches discord.net, not enough of a bug
- element = await testLink(element)
- } catch {}
- detections.push({tags: element.tags || [], safe: element.safe})
+ if (element.match(/https?:\/\/[a-zA-Z]+\.?discord(app)?\.(com|net)\/?/)) return; // Also matches discord.net, not enough of a bug
+ returned = await testLink(element);
+ } catch {
+ detections.push({tags: [], safe: true});
+ return;
+ }
+ if (returned) { detections.push({tags: returned.tags || [], safe: returned.safe}); }
+ else { detections.push({tags: [], safe: true}); }
});
await Promise.all(promises);
- let detectionsTypes = detections.map(element => {
- let type = Object.keys(linkTypes).find(type => element.tags.includes(type))
- if (type) return type
+ const detectionsTypes = detections.map(element => {
+ const type = Object.keys(linkTypes).find(type => element.tags.includes(type));
+ if (type) return type;
// if (!element.safe) return "UNSAFE"
- return undefined
- }).filter(element => element !== undefined)
- return detectionsTypes
+ return undefined;
+ }).filter(element => element !== undefined);
+ return detectionsTypes as string[];
}
-export async function NSFWCheck(element): Promise<boolean> {
+export async function NSFWCheck(element: string): Promise<boolean> {
try {
- let test = (await testNSFW(element))
- return test.nsfw
+ const test = (await testNSFW(element));
+ return test.nsfw;
} catch {
- return false
+ return false;
}
}
-export async function SizeCheck(element): Promise<boolean> {
- if (element.height === undefined || element.width === undefined) return true
- if (element.height < 20 || element.width < 20) return false
- return true
+export async function SizeCheck(element: {height: number | null, width: number | null}): Promise<boolean> {
+ if (element.height === null || element.width === null) return true;
+ if (element.height < 20 || element.width < 20) return false;
+ return true;
}
-export async function MalwareCheck(element): Promise<boolean> {
+export async function MalwareCheck(element: string): Promise<boolean> {
try {
- return (await testMalware(element)).safe
+ return (await testMalware(element)).safe;
} catch {
- return true
+ return true;
}
}
-export function TestString(string, soft, strict): object | null {
- for(let word of strict || []) {
+export function TestString(string: string, soft: string[], strict: string[]): object | null {
+ for(const word of strict || []) {
if (string.toLowerCase().includes(word)) {
- return {word: word, type: "strict"}
+ return {word: word, type: "strict"};
}
}
- for(let word of soft) {
- for(let word2 of string.match(/[a-z]+/gi) || []) {
+ for(const word of soft) {
+ for(const word2 of string.match(/[a-z]+/gi) || []) {
if (word2 === word) {
- return {word: word, type: "strict"}
+ return {word: word, type: "strict"};
}
}
}
- return null
+ return null;
}
-export async function TestImage(url): Promise<string | null> {
- let text = await Tesseract.recognize(url, {lang: "eng", oem: 1, psm: 3})
+export async function TestImage(url: string): Promise<string | null> {
+ const text = await Tesseract.recognize(url, {lang: "eng", oem: 1, psm: 3});
return text;
}
diff --git a/src/reflex/statsChannelUpdate.ts b/src/reflex/statsChannelUpdate.ts
index b306ecc..7301a60 100644
--- a/src/reflex/statsChannelUpdate.ts
+++ b/src/reflex/statsChannelUpdate.ts
@@ -1,38 +1,38 @@
-import convertCurlyBracketString from '../utils/convertCurlyBracketString.js'
-import singleNotify from '../utils/singleNotify.js';
-import client from '../utils/client.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) {
- let guild = await client.guilds.fetch(member.guild.id)
- let config = await client.database.guilds.read(guild.id);
+ 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]) => {
if ((props as PropSchema).enabled) {
- let string = (props as PropSchema).name
- if (!string) return
- string = await convertCurlyBracketString(string, member.id, member.displayName, guild.name, guild.members)
+ let string = (props as PropSchema).name;
+ if (!string) return;
+ string = await convertCurlyBracketString(string, member.id, member.displayName, guild.name, guild.members);
let fetchedChannel;
try {
- fetchedChannel = await guild.channels.fetch(channel)
- } catch (e) { fetchedChannel = null }
+ fetchedChannel = await guild.channels.fetch(channel);
+ } catch (e) { fetchedChannel = null; }
if (!fetchedChannel) {
- let deleted = config.getKey("stats")[channel]
- console.log(`stats.${channel}`)
- console.log(guild.id)
- await client.database.guilds.write(guild.id, null, `stats.${channel}`)
+ const deleted = config.getKey("stats")[channel];
+ console.log(`stats.${channel}`);
+ console.log(guild.id);
+ await client.database.guilds.write(guild.id, null, `stats.${channel}`);
return singleNotify(
"statsChannelDeleted",
guild.id,
"One or more of your stats channels have been deleted. Please use `/settings stats` if you wish to add the channel again.\n" +
`The channels name was: ${deleted.name}`,
"Critical"
- )
+ );
}
try {
- await fetchedChannel.setName(string.slice(0, 100))
+ await fetchedChannel.setName(string.slice(0, 100));
} catch (e) {
- console.error(e)
+ console.error(e);
}
}
});
diff --git a/src/reflex/verify.ts b/src/reflex/verify.ts
index bc7aa4f..d9fab66 100644
--- a/src/reflex/verify.ts
+++ b/src/reflex/verify.ts
@@ -1,4 +1,4 @@
-import { LoadingEmbed } from './../utils/defaultEmbeds.js';
+import { LoadingEmbed } from "./../utils/defaultEmbeds.js";
import Discord, { GuildMember } from "discord.js";
import EmojiEmbed from "../utils/generateEmojiEmbed.js";
import fetch from "node-fetch";
@@ -11,12 +11,12 @@
}
export default async function(interaction) {
- let verify = client.verify
+ const verify = client.verify;
await interaction.reply({embeds: LoadingEmbed, ephemeral: true, fetchReply: true});
- let 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: [new EmojiEmbed()
.setTitle("Verify")
- .setDescription(`Verify is not enabled on this server`)
+ .setDescription("Verify is not enabled on this server")
.setFooter({text: interaction.member.permissions.has("MANAGE_GUILD") ? "You can enable it by running /settings verify" : ""})
.setStatus("Danger")
.setEmoji("CONTROL.BLOCKCROSS")
@@ -31,16 +31,16 @@
}
await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Verify")
- .setDescription(`Checking our servers are up` + step(0))
+ .setDescription("Checking our servers are up" + step(0))
.setStatus("Warning")
.setEmoji("NUCLEUS.LOADING")
]});
try {
- let status = await fetch(client.config.baseUrl).then(res => res.status);
+ const status = await fetch(client.config.baseUrl).then(res => res.status);
if (status !== 200) {
return await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Verify")
- .setDescription(`Our servers appear to be down, please try again later` + step(0))
+ .setDescription("Our servers appear to be down, please try again later" + step(0))
.setStatus("Danger")
.setEmoji("CONTROL.BLOCKCROSS")
]});
@@ -48,7 +48,7 @@
} catch {
return await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Verify")
- .setDescription(`Our servers appear to be down, please try again later` + step(0))
+ .setDescription("Our servers appear to be down, please try again later" + step(0))
.setStatus("Danger")
.setEmoji("CONTROL.BLOCKCROSS")
], components: [new Discord.MessageActionRow().addComponents([
@@ -65,14 +65,14 @@
if (config.filters.images.NSFW) {
await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Verify")
- .setDescription(`Checking your avatar is safe for work` + step(1))
+ .setDescription("Checking your avatar is safe for work" + step(1))
.setStatus("Warning")
.setEmoji("NUCLEUS.LOADING")
]});
if (await NSFWCheck((interaction.member as GuildMember).user.avatarURL({format: "png"}))) {
return await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Verify")
- .setDescription(`Your avatar was detected as NSFW, which we do not allow in this server.\nPlease contact one of our staff members if you believe this is a mistake` + step(1))
+ .setDescription("Your avatar was detected as NSFW, which we do not allow in this server.\nPlease contact one of our staff members if you believe this is a mistake" + step(1))
.setStatus("Danger")
.setEmoji("CONTROL.BLOCKCROSS")
]});
@@ -81,14 +81,14 @@
if (config.filters.wordFilter) {
await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Verify")
- .setDescription(`Checking your name is allowed` + step(2))
+ .setDescription("Checking your name is allowed" + step(2))
.setStatus("Warning")
.setEmoji("NUCLEUS.LOADING")
]});
if (TestString((interaction.member as Discord.GuildMember).displayName, config.filters.wordFilter.words.loose, config.filters.wordFilter.words.strict) !== null) {
return await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Verify")
- .setDescription(`Your name contained a word we do not allow in this server.\nPlease contact one of our staff members if you believe this is a mistake` + step(2))
+ .setDescription("Your name contained a word we do not allow in this server.\nPlease contact one of our staff members if you believe this is a mistake" + step(2))
.setStatus("Danger")
.setEmoji("CONTROL.BLOCKCROSS")
]});
@@ -96,23 +96,23 @@
}
await interaction.editReply({embeds: [new EmojiEmbed()
.setTitle("Verify")
- .setDescription(`One moment...` + step(3))
+ .setDescription("One moment..." + step(3))
.setStatus("Warning")
.setEmoji("NUCLEUS.LOADING")
]});
- let code = ""
- let length = 5
- let itt = 0
+ let code = "";
+ let length = 5;
+ let itt = 0;
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
while (true) {
- itt += 1
- code = ""
+ itt += 1;
+ code = "";
for (let i = 0; i < length; i++) { code += chars.charAt(Math.floor(Math.random() * chars.length)); }
if (code in verify) continue;
if (itt > 1000) {
- itt = 0
- length += 1
- continue
+ itt = 0;
+ length += 1;
+ continue;
}
break;
}
@@ -125,10 +125,10 @@
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")
], components: [new Discord.MessageActionRow().addComponents([new Discord.MessageButton()
diff --git a/src/reflex/welcome.ts b/src/reflex/welcome.ts
index 9be71d5..b4bc374 100644
--- a/src/reflex/welcome.ts
+++ b/src/reflex/welcome.ts
@@ -1,39 +1,37 @@
-import convertCurlyBracketString from '../utils/convertCurlyBracketString.js'
-import client from '../utils/client.js';
-import EmojiEmbed from '../utils/generateEmojiEmbed.js';
+import convertCurlyBracketString from "../utils/convertCurlyBracketString.js";
+import client from "../utils/client.js";
+import EmojiEmbed from "../utils/generateEmojiEmbed.js";
export async function callback(_, member) {
- if (member.bot) return
- let config = await client.database.guilds.read(member.guild.id);
- if (!config.welcome.enabled) return
+ if (member.bot) return;
+ const config = await client.database.guilds.read(member.guild.id);
+ if (!config.welcome.enabled) return;
if (config.welcome.channel) {
- let string = config.welcome.message
+ let string = config.welcome.message;
if (string) {
- string = await convertCurlyBracketString(string, member.id, member.displayName, member.guild.name, member.guild.members)
- if (config.welcome.channel === 'dm') {
- try {
- await member.send({
- embeds: [new EmojiEmbed()
- .setDescription(string)
- .setStatus('Success')
- ]
- })
- } catch {}
+ string = await convertCurlyBracketString(string, member.id, member.displayName, member.guild.name, member.guild.members);
+ if (config.welcome.channel === "dm") {
+ await member.send({
+ embeds: [new EmojiEmbed()
+ .setDescription(string)
+ .setStatus("Success")
+ ]
+ });
} else {
- let channel = await member.guild.channels.fetch(config.welcome.channel)
- if (channel.guild.id !== member.guild.id) return
- if (!channel) return
+ const channel = await member.guild.channels.fetch(config.welcome.channel);
+ if (channel.guild.id !== member.guild.id) return;
+ if (!channel) return;
try {
await channel.send({
embeds: [new EmojiEmbed()
.setDescription(string)
- .setStatus('Success')
+ .setStatus("Success")
],
- content: (config.welcome.ping ? `<@${config.welcome.ping}>` : '') + `<@${member.id}>`
- })
+ content: (config.welcome.ping ? `<@${config.welcome.ping}>` : "") + `<@${member.id}>`
+ });
} catch (err) {
- console.error(err) // SEN
+ console.error(err); // TODO: SEN
}
}
}
diff --git a/src/utils/calculate.ts b/src/utils/calculate.ts
index 8badc58..9bdef3b 100644
--- a/src/utils/calculate.ts
+++ b/src/utils/calculate.ts
@@ -19,7 +19,7 @@
"autoModeratorDeleted",
"nucleusSettingsUpdated",
"ticketUpdate"
-]
+];
const tickets = [
"support",
@@ -28,7 +28,7 @@
"issue",
"suggestion",
"other"
-]
+];
const toHexInteger = (permissions, array?) => {
if (!array) {
@@ -36,29 +36,29 @@
}
let int = 0n;
- for(let perm of permissions) {
+ for(const perm of permissions) {
int += BigInt(2 ** array.indexOf(perm));
}
- return int.toString(16)
-}
+ return int.toString(16);
+};
const toHexArray = (permissionsHex, array?) => {
if (!array) {
array = logs;
}
- let permissions = [];
- let int = (BigInt("0x" + permissionsHex)).toString(2).split('').reverse();
- for (let index in int) {
+ const permissions = [];
+ const int = (BigInt("0x" + permissionsHex)).toString(2).split("").reverse();
+ for (const index in int) {
if (int[index] === "1" && array.length > index) {
permissions.push(array[index]);
}
}
return permissions;
-}
+};
export {
toHexInteger,
toHexArray,
tickets,
logs
-}
\ No newline at end of file
+};
\ No newline at end of file
diff --git a/src/utils/client.ts b/src/utils/client.ts
index 3f4a8a1..a343bcb 100644
--- a/src/utils/client.ts
+++ b/src/utils/client.ts
@@ -1,9 +1,9 @@
-import { HaikuClient } from 'jshaiku';
-import { Intents } from 'discord.js';
-import config from '../config/main.json' assert {type: 'json'};
+import { HaikuClient } from "jshaiku";
+import { Intents } from "discord.js";
+import config from "../config/main.json" assert {type: "json"};
const client = new HaikuClient({
- intents: new Intents(32767).bitfield, // This is a way of specifying all intents w/o having to type them out
+ intents: new Intents(32767).bitfield // This is a way of specifying all intents w/o having to type them out
}, config);
export default client;
\ No newline at end of file
diff --git a/src/utils/confirmationMessage.ts b/src/utils/confirmationMessage.ts
index dfdc3fb..a615fae 100644
--- a/src/utils/confirmationMessage.ts
+++ b/src/utils/confirmationMessage.ts
@@ -1,6 +1,6 @@
import Discord, { CommandInteraction, MessageActionRow, Message, MessageButton, TextInputComponent } from "discord.js";
import { modalInteractionCollector } from "./dualCollector.js";
-import EmojiEmbed from "./generateEmojiEmbed.js"
+import EmojiEmbed from "./generateEmojiEmbed.js";
import getEmojiByName from "./getEmojiByName.js";
@@ -8,7 +8,7 @@
title: string;
disabled: boolean;
value: string | null;
- emoji: string | null;
+ emoji: string | undefined;
active: boolean;
onClick: () => Promise<T>;
response: T | null;
@@ -16,33 +16,33 @@
class confirmationMessage {
interaction: CommandInteraction;
- title: string = "";
- emoji: string = "";
- description: string = "";
- color: string = "";
+ title = "";
+ emoji = "";
+ description = "";
+ color = "";
customButtons: {[index:string]: CustomBoolean<unknown>} = {};
- inverted: boolean = false;
+ inverted = false;
reason: string | null = null;
constructor(interaction: CommandInteraction) {
this.interaction = interaction;
}
- setTitle(title: string) { this.title = title; return this }
- setEmoji(emoji: string) { this.emoji = emoji; return this }
- setDescription(description: string) { this.description = description; return this }
- setColor(color: string) { this.color = color; return this }
- setInverted(inverted: boolean) { this.inverted = inverted; return this }
+ setTitle(title: string) { this.title = title; return this; }
+ setEmoji(emoji: string) { this.emoji = emoji; return this; }
+ setDescription(description: string) { this.description = description; return this; }
+ setColor(color: string) { this.color = color; return this; }
+ setInverted(inverted: boolean) { this.inverted = inverted; return this; }
addCustomBoolean(customId: string, title: string, disabled: boolean, callback: () => Promise<unknown> | null, callbackClicked: string | null, emoji?: string, initial?: boolean) { this.customButtons[customId] = {
- title: title,
- disabled: disabled,
- value: callbackClicked,
- emoji: emoji,
- active: initial ?? false,
- onClick: callback ?? (() => null),
- response: null,
- }
- return this;
+ title: title,
+ disabled: disabled,
+ value: callbackClicked,
+ emoji: emoji,
+ active: initial ?? false,
+ onClick: callback ?? (() => null),
+ response: null
+ };
+ return this;
}
addReasonButton(reason: string) {
this.reason = reason;
@@ -50,7 +50,7 @@
}
async send(editOnly?: boolean) {
while (true) {
- let fullComponents = [
+ const fullComponents = [
new Discord.MessageButton()
.setCustomId("yes")
.setLabel("Confirm")
@@ -61,27 +61,27 @@
.setLabel("Cancel")
.setStyle("SECONDARY")
.setEmoji(getEmojiByName("CONTROL.CROSS", "id"))
- ]
+ ];
Object.entries(this.customButtons).forEach(([k, v]) => {
fullComponents.push(new Discord.MessageButton()
.setCustomId(k)
.setLabel(v.title)
.setStyle(v.active ? "SUCCESS" : "PRIMARY")
.setEmoji(getEmojiByName(v.emoji, "id"))
- .setDisabled(v.disabled))
- })
+ .setDisabled(v.disabled));
+ });
if (this.reason !== null) fullComponents.push(new Discord.MessageButton()
.setCustomId("reason")
- .setLabel(`Edit Reason`)
+ .setLabel("Edit Reason")
.setStyle("PRIMARY")
.setEmoji(getEmojiByName("ICONS.EDIT", "id"))
.setDisabled(false)
- )
- let components = []
+ );
+ const components = [];
for (let i = 0; i < fullComponents.length; i += 5) {
components.push(new MessageActionRow().addComponents(fullComponents.slice(i, i + 5)));
}
- let object = {
+ const object = {
embeds: [
new EmojiEmbed()
.setEmoji(this.emoji)
@@ -95,15 +95,15 @@
components: components,
ephemeral: true,
fetchReply: true
- }
+ };
let m;
try {
if ( editOnly ) {
m = await this.interaction.editReply(object);
} else {
- m = await this.interaction.reply(object)
+ m = await this.interaction.reply(object);
}
- } catch { return { cancelled: true } }
+ } catch { return { cancelled: true }; }
let component;
try {
component = await (m as Message).awaitMessageComponent({filter: (m) => m.user.id === this.interaction.user.id, time: 300000});
@@ -112,17 +112,17 @@
}
if (component.customId === "yes") {
component.deferUpdate();
- for (let [k, v] of Object.entries(this.customButtons)) {
- if (!v.active) continue
+ for (const v of Object.values(this.customButtons)) {
+ if (!v.active) continue;
try { v.response = await v.onClick(); }
- catch (e) { console.log(e) }
- };
+ catch (e) { console.log(e); }
+ }
return { success: true, components: this.customButtons };
} else if (component.customId === "no") {
component.deferUpdate();
return { success: false, components: this.customButtons };
} else if (component.customId === "reason") {
- await component.showModal(new Discord.Modal().setCustomId("modal").setTitle(`Editing reason`).addComponents(
+ await component.showModal(new Discord.Modal().setCustomId("modal").setTitle("Editing reason").addComponents(
new MessageActionRow<TextInputComponent>().addComponents(new TextInputComponent()
.setCustomId("reason")
.setLabel("Reason")
@@ -132,7 +132,7 @@
.setPlaceholder("Spammed in #general")
.setValue(this.reason ? this.reason : "")
)
- ))
+ ));
await this.interaction.editReply({
embeds: [new EmojiEmbed()
.setTitle(this.title)
@@ -148,10 +148,10 @@
});
let out;
try {
- out = await modalInteractionCollector(m, (m) => m.channel.id === this.interaction.channel.id, (m) => m.customId === "reason")
- } catch (e) { return {} }
+ out = await modalInteractionCollector(m, (m) => m.channel.id === this.interaction.channel.id, (m) => m.customId === "reason");
+ } catch (e) { return {}; }
if (out.fields) { return { newReason: out.fields.getTextInputValue("reason") ?? "" }; }
- else { return { newReason: this.reason } }
+ else { return { newReason: this.reason }; }
} else {
component.deferUpdate();
this.customButtons[component.customId].active = !this.customButtons[component.customId].active;
diff --git a/src/utils/convertCurlyBracketString.ts b/src/utils/convertCurlyBracketString.ts
index 6ffdc8f..f05076e 100644
--- a/src/utils/convertCurlyBracketString.ts
+++ b/src/utils/convertCurlyBracketString.ts
@@ -1,6 +1,6 @@
async function convertCurlyBracketString(str, memberID, memberName, serverName, members): Promise<string> {
- let memberCount = (await members.fetch()).size
- let bots = (await members.fetch()).filter(m => m.user.bot).size
+ 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}")
@@ -9,7 +9,7 @@
.replace("{memberCount:bots}", bots ? `${bots}` : "{memberCount:bots}")
.replace("{memberCount:humans}", (memberCount && bots) ? `${memberCount - bots}` : "{memberCount:humans}");
- return str
+ return str;
}
export default convertCurlyBracketString;
diff --git a/src/utils/createLogException.ts b/src/utils/createLogException.ts
index 0223d2f..c62a824 100644
--- a/src/utils/createLogException.ts
+++ b/src/utils/createLogException.ts
@@ -3,6 +3,6 @@
export default function (guild: string, channel: string, message: string) {
client.noLog.push(`${guild}/${channel}/${message}`);
setTimeout(() => {
- client.noLog = client.noLog.filter((i) => {return i !== `${guild}/${channel}/${message}`});
+ client.noLog = client.noLog.filter((i) => {return i !== `${guild}/${channel}/${message}`;});
}, 500);
}
\ No newline at end of file
diff --git a/src/utils/database.ts b/src/utils/database.ts
index 8a5ca6f..cffdf04 100644
--- a/src/utils/database.ts
+++ b/src/utils/database.ts
@@ -1,57 +1,68 @@
-import Discord from 'discord.js';
-import { Collection, MongoClient } from 'mongodb';
-import structuredClone from '@ungap/structured-clone';
-import config from '../config/main.json' assert {type: 'json'};
+import type Discord from "discord.js";
+import { Collection, MongoClient } from "mongodb";
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore
+import structuredClone from "@ungap/structured-clone";
+import config from "../config/main.json" assert {type: "json"};
const mongoClient = new MongoClient(config.mongoUrl);
-await mongoClient.connect()
+await mongoClient.connect();
const database = mongoClient.db("Nucleus");
-
-export const Entry = data => {
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export const Entry = (data: any) => {
data = data ?? {};
- data.getKey = key => data[key]
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ data.getKey = (key: any) => data[key];
return {
- get(target, prop, receiver) {
- let dataToReturn = data[prop]
+ // 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),
- )
+ Entry(dataToReturn)
+ );
return dataToReturn ?? Reflect.get(target, prop, receiver);
}
- }
-}
+ };
+};
export class Guilds {
guilds: Collection<GuildConfig>;
- defaultData: GuildConfig;
- async setup() {
+ defaultData: GuildConfig | null;
+
+ constructor() {
this.guilds = database.collection<GuildConfig>("guilds");
- this.defaultData = (await import("../config/default.json", { assert: { type: "json" }})).default as unknown as GuildConfig;
+ this.defaultData = null;
return this;
}
+ async setup() {
+ this.defaultData = (await import("../config/default.json", { assert: { type: "json" }})).default as unknown as GuildConfig;
+ }
+
async read(guild: string) {
- let entry = await this.guilds.findOne({ id: guild });
- return new Proxy(structuredClone(this.defaultData), Entry(entry)) as unknown as GuildConfig
+ const entry = await this.guilds.findOne({ id: guild });
+ return new Proxy(structuredClone(this.defaultData), Entry(entry)) as unknown as GuildConfig;
}
async write(guild: string, set: object | null, unset: string[] | string = []) {
- let uo = {}
- if (!Array.isArray(unset)) unset = [unset]
- for (let key of unset) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const uo: Record<string, any> = {};
+ if (!Array.isArray(unset)) unset = [unset];
+ for (const key of unset) {
uo[key] = null;
}
- let out = {$set: {}, $unset: {}}
+ const out = {$set: {}, $unset: {}};
if (set) out["$set"] = set;
if (unset.length) out["$unset"] = uo;
await this.guilds.updateOne({ id: guild }, out, { upsert: true });
}
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
async append(guild: string, key: string, value: any) {
if (Array.isArray(value)) {
await this.guilds.updateOne({ id: guild }, {
@@ -64,8 +75,9 @@
}
}
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
async remove(guild: string, key: string, value: any, innerKey?: string | null) {
- console.log(Array.isArray(value))
+ console.log(Array.isArray(value));
if (innerKey) {
await this.guilds.updateOne({ id: guild }, {
$pull: { [key]: { [innerKey]: { $eq: value } } }
@@ -111,7 +123,7 @@
}
async read(guild: string, user: string, year: number) {
- let entry = (await this.histories.find({
+ const entry = (await this.histories.find({
guild: guild,
user: user,
occurredAt: {
@@ -141,7 +153,7 @@
}
async read(guild: string, user: string) {
- let entry = await this.modNotes.findOne({ guild: guild, user: user });
+ const entry = await this.modNotes.findOne({ guild: guild, user: user });
return entry?.note ?? null;
}
}
@@ -155,7 +167,7 @@
}
async hasPremium(guild: string) {
- let entry = await this.premium.findOne({ appliesTo: { $in: [guild] } });
+ const entry = await this.premium.findOne({ appliesTo: { $in: [guild] } });
return entry !== null;
}
}
@@ -186,11 +198,7 @@
},
invite: {
enabled: boolean,
- allowed: {
- users: string[],
- channels: string[],
- roles: string[]
- }
+ channels: string[]
},
pings: {
mass: number,
@@ -215,7 +223,7 @@
channel: string | null,
message: string | null,
}
- stats: {}
+ stats: Record<string, {name: string, enabled: boolean}>
logging: {
logs: {
enabled: boolean,
@@ -227,7 +235,7 @@
},
attachments: {
channel: string | null,
- saved: {} // {channelID+messageID: log url (string)}
+ saved: Record<string, string>
}
}
verify: {
@@ -292,8 +300,8 @@
}[]
}[]
}
- tags: {}
-};
+ tags: Record<string, string>
+}
export interface HistorySchema {
type: string,
diff --git a/src/utils/defaultEmbeds.ts b/src/utils/defaultEmbeds.ts
index e799307..ce6edc1 100644
--- a/src/utils/defaultEmbeds.ts
+++ b/src/utils/defaultEmbeds.ts
@@ -1,9 +1,9 @@
-import EmojiEmbed from "./generateEmojiEmbed.js"
+import EmojiEmbed from "./generateEmojiEmbed.js";
export const LoadingEmbed = [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 67cef5c..c785d0a 100644
--- a/src/utils/dualCollector.ts
+++ b/src/utils/dualCollector.ts
@@ -1,21 +1,19 @@
-import Discord from 'discord.js';
-import client from './client.js';
-import EmojiEmbed from "./generateEmojiEmbed.js";
+import Discord from "discord.js";
+import client from "./client.js";
export default async function (m, interactionFilter, messageFilter) {
let out;
try {
- out = await new Promise((resolve, reject) => {
- let mes, int;
- mes = m.createMessageComponentCollector({filter: (m) => interactionFilter(m), time: 300000})
- .on("collect", (m) => { resolve(m); })
- int = m.channel.createMessageCollector({filter: (m) => messageFilter(m), time: 300000})
- .then("collect", (m) => { try {m.delete();} catch {}; resolve(m); })
- mes.on("end", () => { int.stop(); })
- int.on("end", () => { mes.stop(); })
- })
+ out = await new Promise((resolve, _reject) => {
+ const mes = m.createMessageComponentCollector({filter: (m) => interactionFilter(m), time: 300000})
+ .on("collect", (m) => { resolve(m); });
+ const int = m.channel.createMessageCollector({filter: (m) => messageFilter(m), time: 300000})
+ .then("collect", (m) => { try {m.delete();} catch (e) { client._error(e); } resolve(m); });
+ mes.on("end", () => { int.stop(); });
+ int.on("end", () => { mes.stop(); });
+ });
} catch(e) {
- console.log(e)
+ console.log(e);
return null;
}
@@ -25,24 +23,23 @@
export async function modalInteractionCollector(m, modalFilter, interactionFilter) {
let out;
try {
- out = await new Promise((resolve, reject) => {
- let mod, int;
- int = m.createMessageComponentCollector({filter: (m) => interactionFilter(m), time: 300000})
- .on("collect", (m) => { resolve(m); })
- mod = new Discord.InteractionCollector(
+ out = await new Promise((resolve, _reject) => {
+ const int = m.createMessageComponentCollector({filter: (m) => interactionFilter(m), time: 300000})
+ .on("collect", (m) => { resolve(m); });
+ const mod = new Discord.InteractionCollector(
client, {
filter: (m) => modalFilter(m),
time: 300000
})
.on("collect", async (m) => {
int.stop();
- (m as Discord.ModalSubmitInteraction).deferUpdate()
- resolve((m as Discord.ModalSubmitInteraction)); })
- int.on("end", () => { mod.stop(); })
- mod.on("end", () => { int.stop(); })
- })
+ (m as Discord.ModalSubmitInteraction).deferUpdate();
+ resolve((m as Discord.ModalSubmitInteraction)); });
+ int.on("end", () => { mod.stop(); });
+ mod.on("end", () => { int.stop(); });
+ });
} catch(e) {
- console.log(e)
+ console.log(e);
return null;
}
return out;
diff --git a/src/utils/eventScheduler.ts b/src/utils/eventScheduler.ts
index 396b202..cde178f 100644
--- a/src/utils/eventScheduler.ts
+++ b/src/utils/eventScheduler.ts
@@ -1,39 +1,39 @@
import { Agenda } from "agenda/es.js";
-import client from './client.js';
-import * as fs from 'fs';
-import * as path from 'path';
-import config from '../config/main.json' assert {type: 'json'};
+import client from "./client.js";
+import * as fs from "fs";
+import * as path from "path";
+import config from "../config/main.json" assert {type: "json"};
class EventScheduler {
private agenda: Agenda;
constructor() {
- this.agenda = new Agenda({db: {address: config.mongoUrl + "Nucleus", collection: 'eventScheduler'}})
+ this.agenda = new Agenda({db: {address: config.mongoUrl + "Nucleus", collection: "eventScheduler"}});
this.agenda.define("unmuteRole", async (job: Agenda.job) => {
- let guild = await client.guilds.fetch(job.attrs.data.guild);
- let user = await guild.members.fetch(job.attrs.data.user);
- let role = await guild.roles.fetch(job.attrs.data.role);
+ const guild = await client.guilds.fetch(job.attrs.data.guild);
+ const user = await guild.members.fetch(job.attrs.data.user);
+ const role = await guild.roles.fetch(job.attrs.data.role);
await user.roles.remove(role);
await job.remove();
- })
+ });
this.agenda.define("deleteFile", async (job: Agenda.job) => {
- fs.rm(path.resolve("dist/utils/temp", job.attrs.data.fileName), (err) => {})
+ fs.rm(path.resolve("dist/utils/temp", job.attrs.data.fileName), client._error);
await job.remove();
- })
+ });
this.agenda.define("naturalUnmute", async (job: Agenda.job) => {
- const { log, NucleusColors, entry, renderUser, renderDelta } = client.logger
- let guild = await client.guilds.fetch(job.attrs.data.guild);
- let user = await guild.members.fetch(job.attrs.data.user);
- if (user.communicationDisabledUntil === null) return
+ 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
- )} catch {}
- let data = {
+ );} catch (e) { client._error(e); }
+ const data = {
meta: {
- type: 'memberUnmute',
- displayName: 'Unmuted',
- calculateType: 'guildMemberPunish',
+ type: "memberUnmute",
+ displayName: "Unmuted",
+ calculateType: "guildMemberPunish",
color: NucleusColors.green,
emoji: "PUNISH.MUTE.GREEN",
timestamp: new Date().getTime()
@@ -47,23 +47,25 @@
hidden: {
guild: guild.id
}
- }
+ };
log(data);
- })
+ });
}
async start() {
- await new Promise(resolve => this.agenda.once('ready', resolve));
- this.agenda.start()
- return this
+ await new Promise(resolve => this.agenda.once("ready", resolve));
+ this.agenda.start();
+ return this;
}
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
async schedule(name: string, time: string, data: any) {
- await this.agenda.schedule(time, name, data)
+ await this.agenda.schedule(time, name, data);
}
- cancel(name: string, data: Object) {
- this.agenda.cancel({name, data})
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ cancel(name: string, data: any) {
+ this.agenda.cancel({name, data});
}
}
diff --git a/src/utils/generateEmojiEmbed.ts b/src/utils/generateEmojiEmbed.ts
index 8fe594b..7587db7 100644
--- a/src/utils/generateEmojiEmbed.ts
+++ b/src/utils/generateEmojiEmbed.ts
@@ -1,16 +1,17 @@
-import Discord, { CommandInteraction, ColorResolvable, MessageEmbed } from "discord.js";
+import { MessageEmbed } from "discord.js";
import getEmojiByName from "./getEmojiByName.js";
const colors = {
"Danger": 0xF27878,
"Warning": 0xF2D478,
"Success": 0x68D49E
-}
+};
class EmojiEmbed extends MessageEmbed {
_title: string;
_emoji: string;
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// This *is* meant to be an accessor rather than a property
get title() {
@@ -21,9 +22,9 @@
this._title = title;
}
- setTitle(title: string) { this._title = title; return this }
- setEmoji(emoji: string) { this._emoji = emoji; return this }
- setStatus(color: string) { this.setColor(colors[color]); return this }
+ setTitle(title: string) { this._title = title; return this; }
+ setEmoji(emoji: string) { this._emoji = emoji; return this; }
+ setStatus(color: string) { this.setColor(colors[color]); return this; }
}
export default EmojiEmbed;
\ No newline at end of file
diff --git a/src/utils/generateKeyValueList.ts b/src/utils/generateKeyValueList.ts
index 1a76fa7..ecb9780 100644
--- a/src/utils/generateKeyValueList.ts
+++ b/src/utils/generateKeyValueList.ts
@@ -2,17 +2,17 @@
"ID",
"NSFW",
"URL"
-]
+];
export function capitalize(s: string) {
- s = s.replace(/([A-Z])/g, ' $1');
+ s = s.replace(/([A-Z])/g, " $1");
s = s.split(" ").map(word => {
return forceCaps.includes(word.toUpperCase()) ? word.toUpperCase() : word[0]
.toUpperCase() + word.slice(1)
.toLowerCase()
- .replace("discord", "Discord")
+ .replace("discord", "Discord");
}).join(" ");
- return s
+ return s;
}
export function toCapitals(s: string) {
@@ -22,8 +22,8 @@
function keyValueList(data) {
let out = "";
Object.entries(data).map(([key, value]) => {
- out += `**${capitalize(key)}:** ${value}\n`
- })
+ out += `**${capitalize(key)}:** ${value}\n`;
+ });
return out;
}
diff --git a/src/utils/getEmojiByName.ts b/src/utils/getEmojiByName.ts
index 80410df..63b2042 100644
--- a/src/utils/getEmojiByName.ts
+++ b/src/utils/getEmojiByName.ts
@@ -1,8 +1,8 @@
-import emojis from '../config/emojis.json' assert {type: 'json'};
+import emojis from "../config/emojis.json" assert {type: "json"};
function getEmojiByName(name: string, format?: string): string {
- let split = name.split(".");
- let id = emojis
+ const split = name.split(".");
+ let id = emojis;
split.forEach(part => {
id = id[part];
});
@@ -11,9 +11,9 @@
return id.toString();
}
if (id === undefined) {
- return `<a:_:946346549271732234>`
+ return "<a:_:946346549271732234>";
} else if (id.toString().startsWith("a")) {
- return `<a:_:${id.toString().slice(1, id.toString().length)}>`
+ return `<a:_:${id.toString().slice(1, id.toString().length)}>`;
}
return `<:_:${id}>`;
}
diff --git a/src/utils/log.ts b/src/utils/log.ts
index 0c6aa89..34b24c6 100644
--- a/src/utils/log.ts
+++ b/src/utils/log.ts
@@ -1,33 +1,32 @@
-import * as fs from 'fs';
-import * as Discord from 'discord.js';
-import getEmojiByName from './getEmojiByName.js';
-import { toHexArray } from './calculate.js';
-import { promisify } from 'util';
-import generateKeyValueList from './generateKeyValueList.js';
-import client from './client.js';
+import * as Discord from "discord.js";
+import getEmojiByName from "./getEmojiByName.js";
+import { toHexArray } from "./calculate.js";
+import { promisify } from "util";
+import generateKeyValueList from "./generateKeyValueList.js";
+import client from "./client.js";
const wait = promisify(setTimeout);
export class Logger {
renderUser(user: Discord.User | string) {
- if (typeof user === 'string') return `${user} [<@${user}>]`;
+ if (typeof user === "string") return `${user} [<@${user}>]`;
return `${user.username} [<@${user.id}>]`;
}
renderTime(t: number) {
- t = Math.floor(t /= 1000)
+ t = Math.floor(t /= 1000);
return `<t:${t}:D> at <t:${t}:T>`;
}
renderDelta(t: number) {
- t = Math.floor(t /= 1000)
+ t = Math.floor(t /= 1000);
return `<t:${t}:R> (<t:${t}:D> at <t:${t}:T>)`;
}
renderNumberDelta(num1, num2) {
- let delta = num2 - num1;
- return `${num1} -> ${num2} (${delta > 0 ? '+' : ''}${delta})`;
+ const delta = num2 - num1;
+ return `${num1} -> ${num2} (${delta > 0 ? "+" : ""}${delta})`;
}
entry(value, displayValue) {
- return { value: value, displayValue: displayValue }
+ return { value: value, displayValue: displayValue };
}
renderChannel(channel: Discord.GuildChannel | Discord.ThreadChannel) {
return `${channel.name} [<#${channel.id}>]`;
@@ -36,43 +35,45 @@
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 = {
red: 0xF27878,
yellow: 0xF2D478,
- green: 0x68D49E,
+ green: 0x68D49E
- }
+ };
async getAuditLog(guild: Discord.Guild, event): Promise<Discord.GuildAuditLogsEntry[]>{
- await wait(250)
- let auditLog = await guild.fetchAuditLogs({type: event});
+ await wait(250);
+ const auditLog = await guild.fetchAuditLogs({type: event});
return auditLog as unknown as Discord.GuildAuditLogsEntry[];
}
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
async log(log: any): Promise<void> {
- let config = await client.database.guilds.read(log.hidden.guild);
+ 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)) return console.log('Not logging this type of event');
+ if(!toHexArray(config.logging.logs.toLog).includes(log.meta.calculateType)) return console.log("Not logging this type of event");
}
if (config.logging.logs.channel) {
- let channel = await client.channels.fetch(config.logging.logs.channel) as Discord.TextChannel;
- let description = {};
+ const channel = await client.channels.fetch(config.logging.logs.channel) as Discord.TextChannel;
+ const description = {};
Object.entries(log.list).map(entry => {
- let key = entry[0];
- let value:any = entry[1];
+ const key = entry[0];
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const value: any = entry[1];
if(value.displayValue) {
description[key] = value.displayValue;
} else {
description[key] = value;
}
- })
+ });
if (channel) {
log.separate = log.separate || {};
- let embed = new Discord.MessageEmbed()
+ const embed = new Discord.MessageEmbed()
.setTitle(`${getEmojiByName(log.meta.emoji)} ${log.meta.displayName}`)
.setDescription(
(log.separate.start ? log.separate.start + "\n" : "") +
@@ -88,4 +89,4 @@
}
-export default {}
+export default {};
diff --git a/src/utils/memory.ts b/src/utils/memory.ts
index a06705b..070bd7f 100644
--- a/src/utils/memory.ts
+++ b/src/utils/memory.ts
@@ -1,29 +1,30 @@
import client from "./client.js";
class Memory {
- memory: {};
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ memory: Record<string, any>;
constructor() {
this.memory = {};
setInterval(() => {
- for (let guild in this.memory) {
+ for (const guild in this.memory) {
if (this.memory[guild].updated + 15 * 60 * 1000 < Date.now()) {
delete this.memory[guild];
}
}
- }, 1000 * 60 * 30)
+ }, 1000 * 60 * 30);
}
async readGuildInfo(guild: string): Promise<object> {
if (!this.memory[guild]) {
- let guildData = await client.database.guilds.read(guild);
+ const guildData = await client.database.guilds.read(guild);
this.memory[guild] = {
lastUpdated: Date.now(),
filters: guildData.filters,
logging: guildData.logging,
- tickets: guildData.tickets,
+ tickets: guildData.tickets
};
- };
+ }
return this.memory[guild];
}
}
diff --git a/src/utils/plurals.ts b/src/utils/plurals.ts
index 48b889c..619ced2 100644
--- a/src/utils/plurals.ts
+++ b/src/utils/plurals.ts
@@ -1,7 +1,7 @@
-function addPlural(amount: any, unit: string) {
+function addPlural(amount: number | string, unit: string) {
amount = amount.toString();
- if (amount === '1') return `${amount} ${unit}`
- return `${amount} ${unit}s`
+ if (amount === "1") return `${amount} ${unit}`;
+ return `${amount} ${unit}s`;
}
export default addPlural;
\ No newline at end of file
diff --git a/src/utils/singleNotify.ts b/src/utils/singleNotify.ts
index f29d775..44bb2d0 100644
--- a/src/utils/singleNotify.ts
+++ b/src/utils/singleNotify.ts
@@ -1,29 +1,29 @@
-import client from './client.js';
+import client from "./client.js";
import EmojiEmbed from "./generateEmojiEmbed.js";
-let severities = {
+const severities = {
"Critical": "Danger",
"Warning": "Warning",
"Info": "Success"
-}
+};
export default async function(type: string, guild: string, message: string | true, severity?: string) {
- let data = await client.database.guilds.read(guild);
+ const data = await client.database.guilds.read(guild);
if (message === true) {
return await client.database.guilds.write(guild, {[`singleEventNotifications.${type}`]: false});
}
if (data.singleEventNotifications[type]) return;
await client.database.guilds.write(guild, {[`singleEventNotifications.${type}`]: true});
try {
- let channel = await client.channels.fetch(data.logging.staff.channel);
+ const channel = await client.channels.fetch(data.logging.staff.channel);
if (!channel) return;
await channel.send({embeds: [new EmojiEmbed()
.setTitle(`${severity} notification`)
.setDescription(message)
.setStatus(severities[severity])
.setEmoji("CONTROL.BLOCKCROSS")
- ]})
+ ]});
} catch (err) {
- console.error(err)
+ console.error(err);
}
}
diff --git a/src/utils/temp/generateFileName.ts b/src/utils/temp/generateFileName.ts
index f9662ad..8a219b7 100644
--- a/src/utils/temp/generateFileName.ts
+++ b/src/utils/temp/generateFileName.ts
@@ -1,17 +1,17 @@
-import * as fs from 'fs';
-import * as crypto from 'crypto';
-import client from '../client.js';
-import * as path from 'path'
-import {fileURLToPath} from 'url';
+import * as fs from "fs";
+import * as crypto from "crypto";
+import client from "../client.js";
+import * as path from "path";
+import {fileURLToPath} from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default function generateFileName(ending: string): string {
- let fileName = crypto.randomBytes(35).toString('hex');
- fileName = fileName.replace(/([a-zA-Z0-9]{8})/g, '$1-');
+ let fileName = crypto.randomBytes(35).toString("hex");
+ fileName = fileName.replace(/([a-zA-Z0-9]{8})/g, "$1-");
if (fs.existsSync(`./${fileName}`)) {
fileName = generateFileName(ending);
}
client.database.eventScheduler.schedule("deleteFile", new Date().getTime() + (60 * 1000), {fileName: `${fileName}.${ending}`});
- return path.join(__dirname, fileName + '.' + ending);
+ return path.join(__dirname, fileName + "." + ending);
}
diff --git a/tsconfig.json b/tsconfig.json
index abdf24d..367a1f1 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,5 +1,5 @@
{
- "extends": "@tsconfig/node16-strictest-esm/tsconfig.json",
+ "extends": "@tsconfig/node18-strictest-esm/tsconfig.json",
"compilerOptions": {
"module": "esnext",
"target": "es2020",
@@ -10,7 +10,8 @@
"declarationMap": true,
"resolveJsonModule": true,
"moduleResolution": "node",
- "skipLibCheck": true
+ "skipLibCheck": true,
+ "noImplicitReturns": false
},
"include": ["src/**/*", "installer.js"],
"exclude": []