No typescript errors

pull/17/head
PineaFan 3 years ago
parent 5129610998
commit 638eb135ad
No known key found for this signature in database
GPG Key ID: D404018735F488C9

@ -1,6 +1,5 @@
import { unknownServerIcon } from './../utils/defaults.js'; import { unknownServerIcon } from './../utils/defaults.js';
import { import {
Interaction,
ButtonBuilder, ButtonBuilder,
CommandInteraction, CommandInteraction,
ButtonStyle, ButtonStyle,
@ -8,7 +7,8 @@ import {
StringSelectMenuOptionBuilder, StringSelectMenuOptionBuilder,
StringSelectMenuBuilder, StringSelectMenuBuilder,
GuildMemberRoleManager, GuildMemberRoleManager,
Role Role,
ContextMenuCommandInteraction
} from "discord.js"; } from "discord.js";
import EmojiEmbed from "../utils/generateEmojiEmbed.js"; import EmojiEmbed from "../utils/generateEmojiEmbed.js";
import { ActionRowBuilder } from "discord.js"; import { ActionRowBuilder } from "discord.js";
@ -27,7 +27,7 @@ export interface RoleMenuSchema {
user: string; user: string;
username: string; username: string;
data: GuildConfig["roleMenu"]["options"]; data: GuildConfig["roleMenu"]["options"];
interaction: Interaction; interaction: CommandInteraction | ButtonInteraction | ContextMenuCommandInteraction;
} }
export async function callback(interaction: CommandInteraction | ButtonInteraction) { export async function callback(interaction: CommandInteraction | ButtonInteraction) {
@ -95,7 +95,7 @@ export async function callback(interaction: CommandInteraction | ButtonInteracti
user: interaction.member!.user.id, user: interaction.member!.user.id,
username: interaction.member!.user.username, username: interaction.member!.user.username,
data: config.roleMenu.options, data: config.roleMenu.options,
interaction: interaction as Interaction interaction: interaction as CommandInteraction | ButtonInteraction
}; };
} }
await interaction.editReply({ await interaction.editReply({

@ -1,3 +1,4 @@
import type { Guild, GuildMember } from 'discord.js';
import type { NucleusClient } from '../utils/client.js'; import type { NucleusClient } from '../utils/client.js';
//@ts-expect-error //@ts-expect-error
import express from "express"; import express from "express";
@ -12,19 +13,19 @@ const app = express();
const port = 10000; const port = 10000;
const runServer = (client: NucleusClient) => { const runServer = (client: NucleusClient) => {
app.get("/", (req, res) => { app.get("/", (_req: express.Request, res: express.Response) => {
res.status(200).send(client.ws.ping); res.status(200).send(client.ws.ping);
}); });
app.post("/verify/:code", jsonParser, async function (req, res) { app.post("/verify/:code", jsonParser, async function (req: express.Request, res: express.Response) {
const code = req.params.code; const code = req.params.code;
const secret = req.body.secret; const secret = req.body.secret;
if (secret === client.config.verifySecret) { if (secret === client.config.verifySecret) {
const guild = await client.guilds.fetch(client.verify[code]!.gID); const guild = await client.guilds.fetch(client.verify[code]!.gID) as Guild | null;
if (!guild) { if (!guild) {
return res.status(404); return res.status(404);
} }
const member = await guild.members.fetch(client.verify[code]!.uID); const member = await guild.members.fetch(client.verify[code]!.uID) as GuildMember | null;
if (!member) { if (!member) {
return res.status(404); return res.status(404);
} }
@ -34,19 +35,21 @@ const runServer = (client: NucleusClient) => {
await member.roles.add(client.verify[code]!.rID); await member.roles.add(client.verify[code]!.rID);
const interaction = client.verify[code]!.interaction; const interaction = client.verify[code]!.interaction;
if (interaction) { interaction.editReply({
interaction.editReply({ embeds: [
embeds: [ new EmojiEmbed()
new EmojiEmbed() .setTitle("Verify")
.setTitle("Verify") .setDescription("Verification complete")
.setDescription("Verification complete") .setStatus("Success")
.setStatus("Success") .setEmoji("MEMBER.JOIN")
.setEmoji("MEMBER.JOIN") ],
], components: []
components: [] });
}); // client.verify.filter((v: VerifySchema) => v.code !== code);
} // delete the key by creating a new object without the key
client.verify = client.verify.filter((v) => v.code !== code); client.verify = Object.keys(client.verify)
.filter((k) => k !== code)
.reduce((obj, key) => {return { ...obj, [key]: client.verify[key]}}, {});
const { log, NucleusColors, entry, renderUser } = client.logger; const { log, NucleusColors, entry, renderUser } = client.logger;
try { try {
const data = { const data = {
@ -76,24 +79,22 @@ const runServer = (client: NucleusClient) => {
} }
}); });
app.get("/verify/:code", jsonParser, function (req, res) { app.get("/verify/:code", jsonParser, function (req: express.Request, res: express.Response) {
const code = req.params.code; const code = req.params.code;
if (client.verify[code]) { if (client.verify[code]) {
try { try {
const interaction = client.verify[code]!.interaction; const interaction = client.verify[code]!.interaction;
if (interaction) { interaction.editReply({
interaction.editReply({ embeds: [
embeds: [ new EmojiEmbed()
new EmojiEmbed() .setTitle("Verify")
.setTitle("Verify") .setDescription(
.setDescription( "Verify was opened in another tab or window, please complete the CAPTCHA there to continue"
"Verify was opened in another tab or window, please complete the CAPTCHA there to continue" )
) .setStatus("Success")
.setStatus("Success") .setEmoji("MEMBER.JOIN")
.setEmoji("MEMBER.JOIN") ]
] });
});
}
} catch { } catch {
return res.sendStatus(410); return res.sendStatus(410);
} }
@ -104,15 +105,15 @@ const runServer = (client: NucleusClient) => {
return res.sendStatus(404); return res.sendStatus(404);
}); });
app.post("/rolemenu/:code", jsonParser, async function (req, res) { app.post("/rolemenu/:code", jsonParser, async function (req: express.Request, res: express.Response) {
const code = req.params.code; const code = req.params.code;
const secret = req.body.secret; const secret = req.body.secret;
if (secret === client.config.verifySecret) { if (secret === client.config.verifySecret) {
const guild = await client.guilds.fetch(client.roleMenu[code]!.guild); const guild = await client.guilds.fetch(client.roleMenu[code]!.guild) as Guild | null;
if (!guild) { if (!guild) {
return res.status(404); return res.status(404);
} }
const member = await guild.members.fetch(client.roleMenu[code]!.user); const member = await guild.members.fetch(client.roleMenu[code]!.user) as GuildMember | null;
if (!member) { if (!member) {
return res.status(404); return res.status(404);
} }
@ -122,25 +123,23 @@ const runServer = (client: NucleusClient) => {
} }
}); });
app.get("/rolemenu/:code", jsonParser, function (req, res) { app.get("/rolemenu/:code", jsonParser, function (req: express.Request, res: express.Response) {
const code = req.params.code; const code = req.params.code;
if (client.roleMenu[code] !== undefined) { if (client.roleMenu[code] !== undefined) {
try { try {
const interaction = client.roleMenu[code]!.interaction; const interaction = client.roleMenu[code]!.interaction;
if (interaction) { interaction.editReply({
interaction.editReply({ embeds: [
embeds: [ new EmojiEmbed()
new EmojiEmbed() .setTitle("Roles")
.setTitle("Roles") .setDescription(
.setDescription( "The role menu was opened in another tab or window, please select your roles there to continue"
"The role menu was opened in another tab or window, please select your roles there to continue" )
) .setStatus("Success")
.setStatus("Success") .setEmoji("GUILD.GREEN")
.setEmoji("GUILD.GREEN") ],
], components: []
components: [] });
});
}
} catch { } catch {
return res.sendStatus(410); return res.sendStatus(410);
} }

@ -91,7 +91,7 @@ const callback = async (interaction: CommandInteraction): Promise<void> => {
const rulesChannel = interaction.guild!.rulesChannel?.id; const rulesChannel = interaction.guild!.rulesChannel?.id;
async function nameFromChannel(channel: GuildBasedChannel): Promise<string> { async function nameFromChannel(channel: GuildBasedChannel): Promise<string> {
let channelType = channel.type; let channelType: Discord.ChannelType | 99 = channel.type;
if (channelType === Discord.ChannelType.GuildCategory) return ""; if (channelType === Discord.ChannelType.GuildCategory) return "";
if (channel.id === rulesChannel) channelType = 99 if (channel.id === rulesChannel) channelType = 99
let threads: Discord.ThreadChannel[] = []; let threads: Discord.ThreadChannel[] = [];

@ -1,11 +1,11 @@
import { LoadingEmbed } from "../../../utils/defaults.js"; import { LoadingEmbed } from "../../../utils/defaults.js";
import Discord, { CommandInteraction, Message, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder, EmbedBuilder, StringSelectMenuInteraction } from "discord.js"; import Discord, { CommandInteraction, Message, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder, EmbedBuilder, StringSelectMenuInteraction } from "discord.js";
import type { SlashCommandSubcommandBuilder } from "@discordjs/builders"; import { SlashCommandSubcommandBuilder, StringSelectMenuOptionBuilder } from "@discordjs/builders";
import EmojiEmbed from "../../../utils/generateEmojiEmbed.js"; 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"; import { toHexArray, toHexInteger } from "../../../utils/calculate.js";
const logs = { const logs: Record<string, string> = {
channelUpdate: "Channels created, deleted or modified", channelUpdate: "Channels created, deleted or modified",
emojiUpdate: "Server emojis modified", emojiUpdate: "Server emojis modified",
stickerUpdate: "Server stickers modified", stickerUpdate: "Server stickers modified",
@ -42,6 +42,18 @@ const callback = async (interaction: CommandInteraction): Promise<void> => {
do { do {
const config = await client.database.guilds.read(interaction.guild!.id); const config = await client.database.guilds.read(interaction.guild!.id);
const converted = toHexArray(config.logging.logs.toLog); const converted = toHexArray(config.logging.logs.toLog);
const selectPane = new StringSelectMenuBuilder()
.setPlaceholder("Set events to log")
.setMaxValues(Object.keys(logs).length)
.setCustomId("logs")
.setMinValues(0)
Object.keys(logs).map((e, i) => {
selectPane.addOptions(new StringSelectMenuOptionBuilder()
.setLabel(logs[e]!)
.setValue(i.toString())
.setDefault(converted.includes(e))
)
});
m = (await interaction.editReply({ m = (await interaction.editReply({
embeds: [ embeds: [
new EmojiEmbed() new EmojiEmbed()
@ -53,20 +65,7 @@ const callback = async (interaction: CommandInteraction): Promise<void> => {
.setEmoji("CHANNEL.TEXT.CREATE") .setEmoji("CHANNEL.TEXT.CREATE")
], ],
components: [ components: [
new ActionRowBuilder<StringSelectMenuBuilder>().addComponents([ new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(selectPane),
new StringSelectMenuBuilder()
.setPlaceholder("Set events to log")
.setMaxValues(Object.keys(logs).length)
.setCustomId("logs")
.setMinValues(0)
.setOptions(
Object.keys(logs).map((e, i) => ({
label: (logs as any)[e],
value: i.toString(),
default: converted.includes(e)
}))
)
]),
new ActionRowBuilder<ButtonBuilder>().addComponents([ new ActionRowBuilder<ButtonBuilder>().addComponents([
new ButtonBuilder().setLabel("Select all").setStyle(ButtonStyle.Primary).setCustomId("all"), new ButtonBuilder().setLabel("Select all").setStyle(ButtonStyle.Primary).setCustomId("all"),
new ButtonBuilder().setLabel("Select none").setStyle(ButtonStyle.Danger).setCustomId("none") new ButtonBuilder().setLabel("Select none").setStyle(ButtonStyle.Danger).setCustomId("none")

@ -7,7 +7,6 @@ import Discord, {
GuildChannel, GuildChannel,
Message, Message,
ActionRowBuilder, ActionRowBuilder,
Component,
ButtonBuilder, ButtonBuilder,
MessageComponentInteraction, MessageComponentInteraction,
StringSelectMenuBuilder, StringSelectMenuBuilder,
@ -74,9 +73,9 @@ const callback = async (interaction: CommandInteraction): Promise<unknown> => {
})) as Message; })) as Message;
const options = { const options = {
enabled: (interaction.options.get("enabled")?.value as string).startsWith("yes") as boolean | null, enabled: (interaction.options.get("enabled")?.value as string).startsWith("yes") as boolean | null,
category: interaction.options.get("category")?.channel, category: interaction.options.get("category")?.channel as Discord.CategoryChannel | null,
maxtickets: interaction.options.get("maxticketsperuser")?.value as number, maxtickets: interaction.options.get("maxticketsperuser")?.value as number | null,
supportping: interaction.options.get("supportrole")?.role as Role supportping: interaction.options.get("supportrole")?.role as Role | null
}; };
if (options.enabled !== null || options.category || options.maxtickets || options.supportping) { if (options.enabled !== null || options.category || options.maxtickets || options.supportping) {
if (options.category) { if (options.category) {
@ -94,7 +93,6 @@ const callback = async (interaction: CommandInteraction): Promise<unknown> => {
] ]
}); });
} }
if (!channel) return;
channel = channel as Discord.CategoryChannel; channel = channel as Discord.CategoryChannel;
if (channel.guild.id !== interaction.guild.id) if (channel.guild.id !== interaction.guild.id)
return interaction.editReply({ return interaction.editReply({
@ -202,20 +200,20 @@ const callback = async (interaction: CommandInteraction): Promise<unknown> => {
}); });
} }
} }
let data = await client.database.guilds.read(interaction.guild.id); const data = await client.database.guilds.read(interaction.guild.id);
data.tickets.customTypes = (data.tickets.customTypes || []).filter( data.tickets.customTypes = (data.tickets.customTypes ?? []).filter(
(value: string, index: number, array: string[]) => array.indexOf(value) === index (value: string, index: number, array: string[]) => array.indexOf(value) === index
); );
let lastClicked = ""; let lastClicked = "";
let embed: EmojiEmbed = new EmojiEmbed(); const embed: EmojiEmbed = new EmojiEmbed();
let compiledData = { const compiledData = {
enabled: data.tickets.enabled, enabled: data.tickets.enabled,
category: data.tickets.category, category: data.tickets.category,
maxTickets: data.tickets.maxTickets, maxTickets: data.tickets.maxTickets,
supportRole: data.tickets.supportRole, supportRole: data.tickets.supportRole,
useCustom: data.tickets.useCustom, useCustom: data.tickets.useCustom,
types: data.tickets.types, types: data.tickets.types,
customTypes: data.tickets.customTypes customTypes: data.tickets.customTypes as string[] | null
}; };
let timedOut = false; let timedOut = false;
while (!timedOut) { while (!timedOut) {
@ -485,29 +483,27 @@ const callback = async (interaction: CommandInteraction): Promise<unknown> => {
continue; continue;
} }
out = out as ModalSubmitInteraction; out = out as ModalSubmitInteraction;
if (out.fields) { const title = out.fields.getTextInputValue("title");
const title = out.fields.getTextInputValue("title"); const description = out.fields.getTextInputValue("description");
const description = out.fields.getTextInputValue("description"); await interaction.channel!.send({
await interaction.channel!.send({ embeds: [
embeds: [ new EmojiEmbed()
new EmojiEmbed() .setTitle(title)
.setTitle(title) .setDescription(description)
.setDescription(description) .setStatus("Success")
.setStatus("Success") .setEmoji("GUILD.TICKET.OPEN")
.setEmoji("GUILD.TICKET.OPEN") ],
], components: [
components: [ new ActionRowBuilder<ButtonBuilder>().addComponents([
new ActionRowBuilder<ButtonBuilder>().addComponents([ new ButtonBuilder()
new ButtonBuilder() .setLabel("Create Ticket")
.setLabel("Create Ticket") .setEmoji(getEmojiByName("TICKETS.SUGGESTION", "id"))
.setEmoji(getEmojiByName("TICKETS.SUGGESTION", "id")) .setStyle(ButtonStyle.Success)
.setStyle(ButtonStyle.Success) .setCustomId("createticket")
.setCustomId("createticket") ])
]) ]
] });
}); templateSelected = true;
templateSelected = true;
}
} }
} }
} else if ((i.component as ButtonComponent).customId === "enabled") { } else if ((i.component as ButtonComponent).customId === "enabled") {
@ -516,7 +512,7 @@ const callback = async (interaction: CommandInteraction): Promise<unknown> => {
}); });
compiledData.enabled = !compiledData.enabled; compiledData.enabled = !compiledData.enabled;
} else if ((i.component as ButtonComponent).customId === "manageTypes") { } else if ((i.component as ButtonComponent).customId === "manageTypes") {
data = await manageTypes(interaction, data, m as Message); //TODO: Fix this data.tickets = await manageTypes(interaction, data.tickets, m as Message);
} }
} }
await interaction.editReply({ await interaction.editReply({
@ -713,24 +709,20 @@ async function manageTypes(interaction: CommandInteraction, data: GuildConfig["t
continue; continue;
} }
out = out as ModalSubmitInteraction; out = out as ModalSubmitInteraction;
if (out.fields) { let toAdd = out.fields.getTextInputValue("type");
let toAdd = out.fields.getTextInputValue("type"); if (!toAdd) {
if (!toAdd) {
continue;
}
toAdd = toAdd.substring(0, 80);
try {
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; continue;
} }
toAdd = toAdd.substring(0, 80);
try {
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 if ((i.component as ButtonComponent).customId === "switchToDefault") { } else if ((i.component as ButtonComponent).customId === "switchToDefault") {
i.deferUpdate(); i.deferUpdate();
await client.database.guilds.write(interaction.guild!.id, { "tickets.useCustom": false }, []); await client.database.guilds.write(interaction.guild!.id, { "tickets.useCustom": false }, []);

@ -1,5 +1,5 @@
import { LoadingEmbed } from "../../utils/defaults.js"; import { LoadingEmbed } from "../../utils/defaults.js";
import Discord, { CommandInteraction, GuildMember, Message, ActionRowBuilder, ButtonBuilder, ButtonStyle, SelectMenuOptionBuilder, APIMessageComponentEmoji, StringSelectMenuBuilder, MessageComponentInteraction, StringSelectMenuInteraction, Role } from "discord.js"; import Discord, { CommandInteraction, GuildMember, Message, ActionRowBuilder, ButtonBuilder, ButtonStyle, SelectMenuOptionBuilder, APIMessageComponentEmoji, StringSelectMenuBuilder, MessageComponentInteraction, StringSelectMenuInteraction } from "discord.js";
import type { SlashCommandSubcommandBuilder } from "@discordjs/builders"; import type { SlashCommandSubcommandBuilder } from "@discordjs/builders";
import EmojiEmbed from "../../utils/generateEmojiEmbed.js"; import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
import getEmojiByName from "../../utils/getEmojiByName.js"; import getEmojiByName from "../../utils/getEmojiByName.js";
@ -36,7 +36,7 @@ const callback = async (interaction: CommandInteraction): Promise<unknown> => {
let timedOut = false; let timedOut = false;
while (!timedOut) { while (!timedOut) {
const data = config.tracks[track]!; const data = config.tracks[track]!;
if (data.manageableBy !== undefined) if (data.manageableBy.length)
managed = data.manageableBy.some((element: string) => { managed = data.manageableBy.some((element: string) => {
return memberRoles.cache.has(element); return memberRoles.cache.has(element);
}); });
@ -94,7 +94,7 @@ const callback = async (interaction: CommandInteraction): Promise<unknown> => {
} }
const conflict = data.retainPrevious ? false : selected.length > 1; const conflict = data.retainPrevious ? false : selected.length > 1;
let conflictDropdown: StringSelectMenuBuilder[] = []; let conflictDropdown: StringSelectMenuBuilder[] = [];
let conflictDropdownOptions: SelectMenuOptionBuilder[] = []; const conflictDropdownOptions: SelectMenuOptionBuilder[] = [];
let currentRoleIndex: number = -1; let currentRoleIndex: number = -1;
if (conflict) { if (conflict) {
generated += `\n\n${getEmojiByName(`PUNISH.WARN.${managed ? "YELLOW" : "RED"}`)} This user has ${ generated += `\n\n${getEmojiByName(`PUNISH.WARN.${managed ? "YELLOW" : "RED"}`)} This user has ${
@ -202,7 +202,7 @@ const callback = async (interaction: CommandInteraction): Promise<unknown> => {
} }
} }
} else if (component.customId === "select") { } else if (component.customId === "select") {
track = (component as StringSelectMenuInteraction).values[0]; track = parseInt((component as StringSelectMenuInteraction).values[0]!);
} }
} }
}; };
@ -215,9 +215,10 @@ const check = async (interaction: CommandInteraction) => {
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 // Check if the user can manage any of the tracks
let managed = false; let managed = false;
const memberRoles = member.roles.cache.map((r) => r.id)
for (const element of tracks) { for (const element of tracks) {
if (!element.track.manageableBy) continue; if (!element.manageableBy.length) continue;
if (!element.track.manageableBy.some((role: Role) => member.roles.cache.has(role.id))) continue; if (!element.manageableBy.some((role: string) => memberRoles.includes(role))) continue;
managed = true; managed = true;
break; break;
} }

@ -1,4 +1,5 @@
import fs from "fs"; import fs from "fs";
// @ts-expect-error
import * as readLine from "node:readline/promises"; import * as readLine from "node:readline/promises";
const defaultDict: Record<string, string | string[] | boolean> = { const defaultDict: Record<string, string | string[] | boolean> = {

@ -92,9 +92,9 @@ console.log((oldChannel as TextChannel).rateLimitPerUser, (newChannel as TextCha
if ((oldChannel as TextChannel).topic !== (newChannel as TextChannel).topic) if ((oldChannel as TextChannel).topic !== (newChannel as TextChannel).topic)
changes.description = entry([(oldChannel as TextChannel).topic ?? "", (newChannel as TextChannel).topic ?? ""], `\nBefore: ${oldTopic}\nAfter: ${newTopic}`); changes.description = entry([(oldChannel as TextChannel).topic ?? "", (newChannel as TextChannel).topic ?? ""], `\nBefore: ${oldTopic}\nAfter: ${newTopic}`);
if ((oldChannel as TextChannel).nsfw !== (newChannel as TextChannel).nsfw) changes.nsfw = entry([(oldChannel as TextChannel).nsfw ? "On" : "Off", (newChannel as TextChannel).nsfw ? "On" : "Off"], `${nsfw[0]} -> ${nsfw[1]}`); if ((oldChannel as TextChannel).nsfw !== (newChannel as TextChannel).nsfw) changes.nsfw = entry([(oldChannel as TextChannel).nsfw ? "On" : "Off", (newChannel as TextChannel).nsfw ? "On" : "Off"], `${nsfw[0]} -> ${nsfw[1]}`);
if ((oldChannel as TextChannel).rateLimitPerUser !== (newChannel as TextChannel).rateLimitPerUser && (oldChannel as TextChannel).rateLimitPerUser !== undefined) if ((oldChannel as TextChannel).rateLimitPerUser !== (newChannel as TextChannel).rateLimitPerUser && (oldChannel as TextChannel).rateLimitPerUser !== 0)
changes.rateLimitPerUser = entry( changes.rateLimitPerUser = entry(
[((oldChannel as TextChannel).rateLimitPerUser ?? 0).toString(), ((newChannel as TextChannel).rateLimitPerUser ?? 0).toString()], [((oldChannel as TextChannel).rateLimitPerUser).toString(), ((newChannel as TextChannel).rateLimitPerUser).toString()],
`${humanizeDuration((oldChannel as TextChannel).rateLimitPerUser * 1000)} -> ${humanizeDuration((newChannel as TextChannel).rateLimitPerUser * 1000)}` `${humanizeDuration((oldChannel as TextChannel).rateLimitPerUser * 1000)} -> ${humanizeDuration((newChannel as TextChannel).rateLimitPerUser * 1000)}`
); );
@ -103,7 +103,7 @@ console.log((oldChannel as TextChannel).rateLimitPerUser, (newChannel as TextCha
case ChannelType.GuildAnnouncement: { case ChannelType.GuildAnnouncement: {
emoji = "CHANNEL.TEXT.EDIT"; emoji = "CHANNEL.TEXT.EDIT";
readableType = "Announcement"; readableType = "Announcement";
displayName = "Announcment Channel"; displayName = "Announcement Channel";
let oldTopic = (oldChannel as TextChannel).topic, let oldTopic = (oldChannel as TextChannel).topic,
newTopic = (newChannel as TextChannel).topic; newTopic = (newChannel as TextChannel).topic;
if (oldTopic) { if (oldTopic) {
@ -138,7 +138,7 @@ console.log((oldChannel as TextChannel).rateLimitPerUser, (newChannel as TextCha
if ((oldChannel as VoiceChannel).rtcRegion !== (newChannel as VoiceChannel).rtcRegion) if ((oldChannel as VoiceChannel).rtcRegion !== (newChannel as VoiceChannel).rtcRegion)
changes.region = entry( changes.region = entry(
[(oldChannel as VoiceChannel).rtcRegion ?? "Automatic", (newChannel as VoiceChannel).rtcRegion ?? "Automatic"], [(oldChannel as VoiceChannel).rtcRegion ?? "Automatic", (newChannel as VoiceChannel).rtcRegion ?? "Automatic"],
`${(oldChannel as VoiceChannel).rtcRegion?.toUpperCase() || "Automatic"} -> ${(newChannel as VoiceChannel).rtcRegion?.toUpperCase() || "Automatic"}` `${(oldChannel as VoiceChannel).rtcRegion?.toUpperCase() ?? "Automatic"} -> ${(newChannel as VoiceChannel).rtcRegion?.toUpperCase() ?? "Automatic"}`
); );
break; break;
} }
@ -172,7 +172,7 @@ console.log((oldChannel as TextChannel).rateLimitPerUser, (newChannel as TextCha
if ((oldChannel as StageChannel).rtcRegion !== (newChannel as StageChannel).rtcRegion) if ((oldChannel as StageChannel).rtcRegion !== (newChannel as StageChannel).rtcRegion)
changes.region = entry( changes.region = entry(
[(oldChannel as StageChannel).rtcRegion ?? "Automatic", (newChannel as StageChannel).rtcRegion ?? "Automatic"], [(oldChannel as StageChannel).rtcRegion ?? "Automatic", (newChannel as StageChannel).rtcRegion ?? "Automatic"],
`${(oldChannel as StageChannel).rtcRegion?.toUpperCase() || "Automatic"} -> ${(newChannel as StageChannel).rtcRegion?.toUpperCase() || "Automatic"}` `${(oldChannel as StageChannel).rtcRegion?.toUpperCase() ?? "Automatic"} -> ${(newChannel as StageChannel).rtcRegion?.toUpperCase() ?? "Automatic"}`
); );
break; break;
} }
@ -188,7 +188,7 @@ console.log((oldChannel as TextChannel).rateLimitPerUser, (newChannel as TextCha
displayName = "Channel"; displayName = "Channel";
} }
} }
let ocType = channelTypeEmoji[oldChannel.type], const ocType = channelTypeEmoji[oldChannel.type],
ncType = channelTypeEmoji[newChannel.type]; ncType = channelTypeEmoji[newChannel.type];
if (oldChannel.type !== newChannel.type) if (oldChannel.type !== newChannel.type)
changes.type = entry([ocType!, ncType!], `${ocType!} -> ${readableType}`); changes.type = entry([ocType!, ncType!], `${ocType!} -> ${readableType}`);

@ -11,7 +11,7 @@ export async function callback(client: NucleusClient, member: GuildMember) {
await statsChannelRemove(client, member); await statsChannelRemove(client, member);
const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = client.logger; const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
const auditLog = (await getAuditLog(member.guild as Guild, AuditLogEvent.MemberKick)) const auditLog = (await getAuditLog(member.guild as Guild, AuditLogEvent.MemberKick))
.filter((entry: GuildAuditLogsEntry) => (entry.target as GuildMember)!.id === member.id)[0]!; .filter((entry: GuildAuditLogsEntry) => (entry.target as GuildMember)!.id === member.id)[0];
let type = "leave"; let type = "leave";
if (auditLog) { if (auditLog) {
if (auditLog.executor!.id === client.user!.id) return; if (auditLog.executor!.id === client.user!.id) return;
@ -21,6 +21,7 @@ export async function callback(client: NucleusClient, member: GuildMember) {
} }
let data; let data;
if (type === "kick") { if (type === "kick") {
if (!auditLog) return;
await client.database.history.create("kick", member.guild.id, member.user, auditLog.executor, auditLog.reason); await client.database.history.create("kick", member.guild.id, member.user, auditLog.executor, auditLog.reason);
data = { data = {
meta: { meta: {

@ -6,7 +6,7 @@ export const event = "stickerDelete";
export async function callback(client: NucleusClient, sticker: Sticker) { export async function callback(client: NucleusClient, sticker: Sticker) {
const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = client.logger; const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
const auditLog = (await getAuditLog(sticker.guild!, AuditLogEvent.EmojiCreate)) const auditLog = (await getAuditLog(sticker.guild!, AuditLogEvent.EmojiCreate))
.filter((entry: GuildAuditLogsEntry) => (entry.target as Sticker)!.id === sticker.id)[0] as GuildAuditLogsEntry; .filter((entry: GuildAuditLogsEntry) => (entry.target as Sticker)!.id === sticker.id)[0]!;
if (auditLog.executor!.id === client.user!.id) return; if (auditLog.executor!.id === client.user!.id) return;
const data = { const data = {
meta: { meta: {

@ -6,7 +6,7 @@ export const event = "stickerDelete";
export async function callback(client: NucleusClient, sticker: Sticker) { export async function callback(client: NucleusClient, sticker: Sticker) {
const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = client.logger; const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta } = client.logger;
const auditLog = (await getAuditLog(sticker.guild!, AuditLogEvent.StickerDelete)) const auditLog = (await getAuditLog(sticker.guild!, AuditLogEvent.StickerDelete))
.filter((entry: GuildAuditLogsEntry) => (entry.target as Sticker)!.id === sticker.id)[0] as GuildAuditLogsEntry; .filter((entry: GuildAuditLogsEntry) => (entry.target as Sticker)!.id === sticker.id)[0]!;
if (auditLog.executor!.id === client.user!.id) return; if (auditLog.executor!.id === client.user!.id) return;
const data = { const data = {
meta: { meta: {

@ -8,7 +8,7 @@ export async function callback(client: NucleusClient, oldSticker: Sticker, newSt
if (oldSticker.name === newSticker.name) return; if (oldSticker.name === newSticker.name) return;
const auditLog = (await getAuditLog(newSticker.guild!, AuditLogEvent.StickerUpdate)) const auditLog = (await getAuditLog(newSticker.guild!, AuditLogEvent.StickerUpdate))
.filter((entry: GuildAuditLogsEntry) => (entry.target as Sticker)!.id === newSticker.id)[0] as GuildAuditLogsEntry; .filter((entry: GuildAuditLogsEntry) => (entry.target as Sticker)!.id === newSticker.id)[0]!;
if (auditLog.executor!.id === client.user!.id) return; if (auditLog.executor!.id === client.user!.id) return;
const changes = { const changes = {

@ -7,7 +7,7 @@ export const event = "threadCreate";
export async function callback(client: NucleusClient, thread: ThreadChannel) { export async function callback(client: NucleusClient, thread: ThreadChannel) {
const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger; const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger;
const auditLog = (await getAuditLog(thread.guild, AuditLogEvent.ThreadCreate)) const auditLog = (await getAuditLog(thread.guild, AuditLogEvent.ThreadCreate))
.filter((entry: GuildAuditLogsEntry) => (entry.target as ThreadChannel)!.id === thread.id)[0] as GuildAuditLogsEntry; .filter((entry: GuildAuditLogsEntry) => (entry.target as ThreadChannel)!.id === thread.id)[0]!;
if (auditLog.executor!.id === client.user!.id) return; if (auditLog.executor!.id === client.user!.id) return;
const category = thread.parent const category = thread.parent
? entry( ? entry(

@ -7,7 +7,7 @@ export const event = "threadDelete";
export async function callback(client: NucleusClient, thread: ThreadChannel) { export async function callback(client: NucleusClient, thread: ThreadChannel) {
const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger; const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger;
const auditLog = (await getAuditLog(thread.guild, AuditLogEvent.ThreadDelete)) const auditLog = (await getAuditLog(thread.guild, AuditLogEvent.ThreadDelete))
.filter((entry: GuildAuditLogsEntry) => (entry.target as ThreadChannel)!.id === thread.id)[0] as GuildAuditLogsEntry; .filter((entry: GuildAuditLogsEntry) => (entry.target as ThreadChannel)!.id === thread.id)[0]!;
if (auditLog.executor!.id === client.user!.id) return; if (auditLog.executor!.id === client.user!.id) return;
const category = thread.parent const category = thread.parent
? entry( ? entry(

@ -8,7 +8,7 @@ export const event = "threadUpdate";
export async function callback(client: NucleusClient, oldThread: ThreadChannel, newThread: ThreadChannel) { export async function callback(client: NucleusClient, oldThread: ThreadChannel, newThread: ThreadChannel) {
const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger; const { getAuditLog, log, NucleusColors, entry, renderUser, renderDelta, renderChannel } = client.logger;
const auditLog = (await getAuditLog(newThread.guild, AuditLogEvent.ThreadUpdate)) const auditLog = (await getAuditLog(newThread.guild, AuditLogEvent.ThreadUpdate))
.filter((entry: GuildAuditLogsEntry) => (entry.target as ThreadChannel)!.id === newThread.id)[0] as GuildAuditLogsEntry; .filter((entry: GuildAuditLogsEntry) => (entry.target as ThreadChannel)!.id === newThread.id)[0]!;
if (auditLog.executor!.id === client.user!.id) return; if (auditLog.executor!.id === client.user!.id) return;
const list: Record<string, ReturnType<typeof entry>> = { const list: Record<string, ReturnType<typeof entry>> = {
threadId: entry(newThread.id, `\`${newThread.id}\``), threadId: entry(newThread.id, `\`${newThread.id}\``),

@ -12,17 +12,19 @@ export async function callback(client: NucleusClient, channel: Discord.GuildChan
try { try {
const { getAuditLog, log, NucleusColors, entry, renderUser, renderChannel, renderDelta } = client.logger; const { getAuditLog, log, NucleusColors, entry, renderUser, renderChannel, renderDelta } = client.logger;
const auditCreate = (await getAuditLog(channel.guild, AuditLogEvent.WebhookCreate)) const auditCreate = (await getAuditLog(channel.guild, AuditLogEvent.WebhookCreate))
.filter((entry: GuildAuditLogsEntry) => (entry.target as Webhook)!.id === channel.id)[0] as GuildAuditLogsEntry; .filter((entry: GuildAuditLogsEntry) => (entry.target as Webhook)!.id === channel.id)[0]!;
const auditDelete = (await getAuditLog(channel.guild, AuditLogEvent.WebhookDelete)) const auditDelete = (await getAuditLog(channel.guild, AuditLogEvent.WebhookDelete))
.filter((entry: GuildAuditLogsEntry) => (entry.target as Webhook)!.id === channel.id)[0] as GuildAuditLogsEntry; .filter((entry: GuildAuditLogsEntry) => (entry.target as Webhook)!.id === channel.id)[0];
const auditUpdate = (await getAuditLog(channel.guild, AuditLogEvent.WebhookUpdate)) const auditUpdate = (await getAuditLog(channel.guild, AuditLogEvent.WebhookUpdate))
.filter((entry: GuildAuditLogsEntry) => (entry.target as Webhook)!.id === channel.id)[0] as GuildAuditLogsEntry; .filter((entry: GuildAuditLogsEntry) => (entry.target as Webhook)!.id === channel.id)[0];
if (!auditCreate && !auditUpdate && !auditDelete) return; if (!auditUpdate && !auditDelete) return;
let audit = auditCreate;
let action: "Create" | "Update" | "Delete" = "Create"; let action: "Create" | "Update" | "Delete" = "Create";
let list: Record<string, ReturnType<typeof entry> | string> = {}; let list: Record<string, ReturnType<typeof entry> | string> = {};
if (auditUpdate && auditUpdate.createdTimestamp > audit.createdTimestamp) { const createTimestamp = auditCreate.createdTimestamp;
const deleteTimestamp = auditDelete ? auditDelete.createdTimestamp : 0;
const updateTimestamp = auditUpdate ? auditUpdate.createdTimestamp : 0;
if (updateTimestamp > createTimestamp && updateTimestamp > deleteTimestamp && auditUpdate) {
const { before, after } = auditUpdate.changes.reduce((acc: accType, change) => { const { before, after } = auditUpdate.changes.reduce((acc: accType, change) => {
acc.before[change.key] = change.old?.toString()!; acc.before[change.key] = change.old?.toString()!;
acc.after[change.key] = change.new?.toString()!; acc.after[change.key] = change.new?.toString()!;
@ -46,9 +48,8 @@ export async function callback(client: NucleusClient, channel: Discord.GuildChan
); );
list["edited"] = entry(after["editedTimestamp"]!, renderDelta(new Date().getTime())); list["edited"] = entry(after["editedTimestamp"]!, renderDelta(new Date().getTime()));
list["editedBy"] = entry(auditUpdate.executor!.id, renderUser(auditUpdate.executor!)); list["editedBy"] = entry(auditUpdate.executor!.id, renderUser(auditUpdate.executor!));
audit = auditUpdate;
action = "Update"; action = "Update";
} else if (auditDelete && auditDelete.createdTimestamp > audit.createdTimestamp) { } else if (deleteTimestamp > createTimestamp && deleteTimestamp > updateTimestamp && auditDelete) {
const { before } = auditDelete.changes.reduce((acc: accType, change) => { const { before } = auditDelete.changes.reduce((acc: accType, change) => {
acc.before[change.key] = change.old?.toString()!; acc.before[change.key] = change.old?.toString()!;
acc.after[change.key] = change.new?.toString()!; acc.after[change.key] = change.new?.toString()!;
@ -59,17 +60,16 @@ export async function callback(client: NucleusClient, channel: Discord.GuildChan
list = { list = {
name: entry(before["name"]!, `${before["name"]}`), name: entry(before["name"]!, `${before["name"]}`),
channel: entry(before["channel_id"]!, renderChannel((await client.channels.fetch(before["channel_id"]!)) as GuildChannel)), channel: entry(before["channel_id"]!, renderChannel((await client.channels.fetch(before["channel_id"]!)) as GuildChannel)),
created: entry((auditUpdate.target! as Extract<GuildAuditLogsEntry, {createdTimestamp: number}>).createdTimestamp, renderDelta((auditUpdate.target! as Extract<GuildAuditLogsEntry, {createdTimestamp: number}>).createdTimestamp)), created: entry((auditDelete.target! as Extract<GuildAuditLogsEntry, {createdTimestamp: number}>).createdTimestamp, renderDelta((auditDelete.target! as Extract<GuildAuditLogsEntry, {createdTimestamp: number}>).createdTimestamp)),
deleted: entry(new Date().getTime(), renderDelta(new Date().getTime())), deleted: entry(new Date().getTime(), renderDelta(new Date().getTime())),
deletedBy: entry( deletedBy: entry(
auditDelete.executor!.id, auditDelete.executor!.id,
renderUser((await channel.guild.members.fetch(auditDelete.executor!.id)).user) renderUser((await channel.guild.members.fetch(auditDelete.executor!.id)).user)
) )
}; };
audit = auditDelete;
action = "Delete"; action = "Delete";
} else { } else {
const { before } = auditDelete.changes.reduce((acc: accType, change) => { const { before } = auditDelete!.changes.reduce((acc: accType, change) => {
acc.before[change.key] = change.old?.toString()!; acc.before[change.key] = change.old?.toString()!;
acc.after[change.key] = change.new?.toString()!; acc.after[change.key] = change.new?.toString()!;
return acc; return acc;
@ -96,7 +96,7 @@ export async function callback(client: NucleusClient, channel: Discord.GuildChan
type: "webhook" + action, type: "webhook" + action,
displayName: `Webhook ${action}d`, displayName: `Webhook ${action}d`,
calculateType: "webhookUpdate", calculateType: "webhookUpdate",
color: (NucleusColors as any)[cols[action]], color: NucleusColors[cols[action] as keyof typeof NucleusColors],
emoji: "WEBHOOK." + action.toUpperCase(), emoji: "WEBHOOK." + action.toUpperCase(),
timestamp: new Date().getTime() timestamp: new Date().getTime()
}, },

@ -42,7 +42,7 @@ async function registerCommands() {
i++; i++;
console.log(`${last.replace("└", " ").replace("├", "│")} └─ ${colours.green}Loaded ${file.name} [${i} / ${files.length}]${colours.none}`) console.log(`${last.replace("└", " ").replace("├", "│")} └─ ${colours.green}Loaded ${file.name} [${i} / ${files.length}]${colours.none}`)
} }
console.log(`Loaded ${commands.length} commands, processing...`) console.log(`${colours.yellow}Loaded ${commands.length} commands, processing...`)
const processed = [] const processed = []
for (const subcommand of commands) { for (const subcommand of commands) {
@ -53,7 +53,7 @@ async function registerCommands() {
} }
} }
console.log(`Processed ${processed.length} commands`) console.log(`${colours.green}Processed ${processed.length} commands`)
return processed; return processed;
}; };

Loading…
Cancel
Save