Skip to content

Commit

Permalink
Refactored code to rely less on importing features from main.js
Browse files Browse the repository at this point in the history
  • Loading branch information
Davoleo committed Jun 7, 2024
1 parent 1e00a38 commit d15deff
Show file tree
Hide file tree
Showing 12 changed files with 74 additions and 64 deletions.
16 changes: 8 additions & 8 deletions src/commandLoader.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import * as fs from 'fs';
import {logger} from './main.js';
import {Routes} from 'discord-api-types/v9'
import {REST} from '@discordjs/rest';
import Environment from './util/Environment.js';
import {Logger} from "./util/log.js";
import {readdirSync} from "fs";

export async function loadCommandFiles() {

let commands = [];

let files = fs.readdirSync('./build/commands');
let files = readdirSync('./build/commands');
files = files.filter(file => file.endsWith('.js'));
logger.info("Loading " + files.length + " commands");
Logger.I.info("Loading " + files.length + " commands");
for (const file of files) {
Logger.I.debug(file);
const script = await import('./commands/' + file);
//logger.info(script);
commands.push(script.command);
}

Expand All @@ -31,21 +31,21 @@ export function initCommands(commands) {
if (env.DevMode) {
for (let i = 0; i<env.TestingServers.length; i++) {
rest.put(Routes.applicationGuildCommands(env.BotId, env.TestingServers[i]), {body: jsonCommands})
.then(() => logger.info("Succesfully registered Slash Commands to Testing Server " + i))
.then(() => Logger.I.info("Succesfully registered Slash Commands to Testing Server " + i))
.catch(console.warn)
}
}
else {

rest.put(Routes.applicationCommands(env.BotId), {body: jsonCommands})
.then(() => {
logger.info("Succesfully registered GLOBAL Slash Commands");
Logger.I.info("Succesfully registered GLOBAL Slash Commands");
//Cleanup guild commands
return Promise.all(env.TestingServers.map(server => {
return rest.put(Routes.applicationGuildCommands(env.BotId, server))
}));
})
.then(() => logger.info("Successfully cleaned up Guild Commands"))
.then(() => Logger.I.info("Successfully cleaned up Guild Commands"))
.catch(console.warn)
}
}
4 changes: 2 additions & 2 deletions src/commands/latest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {buildModEmbed} from "../discord/embedBuilder.js";
import Command from "../model/Command.js";
import {CommandScope} from "../model/CommandGroup.js";
import {CommandPermission} from "../util/discord.js";
import {logger} from "../main.js";
import {Logger} from "../util/log.js";

async function latest(interaction: ChatInputCommandInteraction) {

Expand All @@ -18,7 +18,7 @@ async function latest(interaction: ChatInputCommandInteraction) {
catch (error) {
if (error.code === 404) {
void interaction.reply(":x: Project with id: `" + id + "` doesn't exist!")
logger.warn("latest: Project with id " + id + " not found!", error)
Logger.I.warn("latest: Project with id " + id + " not found!", error)
}
else
throw error
Expand Down
3 changes: 1 addition & 2 deletions src/commands/leaveguild.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import {ChatInputCommandInteraction, Snowflake} from "discord.js";
import {botClient} from "../main.js";
import Command from "../model/Command.js";
import {CommandScope} from "../model/CommandGroup.js";
import {CommandPermission} from "../util/discord.js";

async function leaveguild(interaction: ChatInputCommandInteraction) {
const id: Snowflake = interaction.options.getString('id', true)
const guild = await botClient.guilds.fetch(id);
const guild = await interaction.client.guilds.fetch(id);
await guild.leave();
void interaction.reply(`Guild "${guild.name}" has been left`);
}
Expand Down
6 changes: 3 additions & 3 deletions src/commands/schedule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {CommandPermission} from "../util/discord.js";
import GuildService from "../services/GuildService.js";
import {ErrorNotFound} from "node-curseforge/dist/objects/exceptions.js";
import {PrismaClientKnownRequestError} from "@prisma/client/runtime/library.js";
import {logger} from "../main.js";
import {Logger} from "../util/log.js";

const PROJECT_ID_KEY = 'project_id'

Expand All @@ -24,7 +24,7 @@ async function add(interaction: ChatInputCommandInteraction) {
void interaction.reply({content: `:x: Error: ${error.message} ID=${projectID}`, ephemeral: true});
}
else if (error instanceof Error) {
void interaction.reply({content: `:x: ${error.name} Error: ${error.message}`, ephemeral: true});
void interaction.reply({content: `:x: ${error.name}: ${error.message}`, ephemeral: true});
}
else {
void interaction.reply({content: `:x: ${error.name}!`, ephemeral: true});
Expand All @@ -46,7 +46,7 @@ async function remove(interaction: ChatInputCommandInteraction) {
if (error instanceof PrismaClientKnownRequestError) {
if (error.code === 'P2018' || error.code === 'P2025') {
void interaction.reply(":x: Couldn't find a project with `ID = " + projectID + "` in the bot schedule")
logger.error('schedule remove: ' + error.message)
Logger.I.error('schedule remove: ' + error.message)
}
}
else throw error;
Expand Down
4 changes: 2 additions & 2 deletions src/commands/updates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {CommandScope} from "../model/CommandGroup.js";
import {CommandPermission} from "../util/discord.js";
import {FilterModal} from "../discord/modals.js";
import UpdatesService from "../services/UpdatesService.js";
import {logger} from "../main.js";
import {Logger} from "../util/log.js";

//const ACCEPTED_CHANNEL_TYPES = [
// ChannelType.GuildNews, ChannelType.GuildNewsThread, ChannelType.GuildPrivateThread, ChannelType.GuildPublicThread, ChannelType.GuildText
Expand Down Expand Up @@ -122,7 +122,7 @@ async function setfilters(interaction: ChatInputCommandInteraction, externalConf
await modalWrapper.handleSubmission(submitted);
}
catch (e) {
logger.error(e.message);
Logger.I.error(e.message);
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/curseHelper.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {Curseforge, Mod, ModFile} from 'node-curseforge';
import Environment from './util/Environment.js';
import ModData from './model/ModData.js';
import {logger} from "./main.js";
import {Logger} from "./util/log.js";

const CFAPI = new Curseforge(Environment.get().CurseForgeAPIKey);

Expand Down Expand Up @@ -49,7 +49,7 @@ async function queryModById(id: number): Promise<ModData> {
changelog = await latestFile?.get_changelog();
}
catch (err) {
logger.warn("Changelog Request Error: ", err);
Logger.I.warn("Changelog Request Error: ", err);
}

//empty changelog string = no changelog
Expand Down
16 changes: 8 additions & 8 deletions src/data/dataHandler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {PrismaClient, PrismaPromise} from "@prisma/client";
import {logger} from "../main.js";
import {Logger} from "../util/log.js";

const activeTransactions: Map<string, PrismaPromise<unknown>[]> = new Map();

Expand All @@ -26,19 +26,19 @@ export const dbclient = new PrismaClient({

function init() {
dbclient.$on('query', (event) => {
logger.debug('Query: ' + event.query);
logger.debug('Params: ' + event.params);
logger.debug('Duration: ' + event.duration + 'ms');
Logger.I.debug('Query: ' + event.query);
Logger.I.debug('Params: ' + event.params);
Logger.I.debug('Duration: ' + event.duration + 'ms');
});

dbclient.$on('info', (event) => {
logger.info(event.message);
Logger.I.info(event.message);
});
dbclient.$on('warn', (event) => {
logger.warn(event.message);
Logger.I.warn(event.message);
});
dbclient.$on('error', (event) => {
logger.error(event.message);
Logger.I.error(event.message);
});
}

Expand All @@ -62,7 +62,7 @@ async function runTransaction(id: string): Promise<unknown[]> {
return dbclient.$transaction(transaction!);
}
else {
logger.warn("Attempted to run transaction for non-existent id: " + id);
Logger.I.warn("Attempted to run transaction for non-existent id: " + id);
return Promise.reject('No active transaction for id: ' + id)
}

Expand Down
6 changes: 3 additions & 3 deletions src/discord/modals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
import UpdatesService from "../services/UpdatesService.js";
import GameTag from "../model/GameTag.js";
import GuildService from "../services/GuildService.js";
import {logger} from "../main.js";
import {Logger} from "../util/log.js";

export interface Modal {
readonly id: string
Expand Down Expand Up @@ -68,8 +68,8 @@ export class FilterModal implements Modal {

const tagsString = interaction.fields.getField(FilterModal.TAGS_FILTER_INPUT, ComponentType.TextInput).value
const projectsString = interaction.fields.getField(FilterModal.PROJECTS_FILTER_INPUT, ComponentType.TextInput).value;
logger.debug("setfilters (tags): " + tagsString);
logger.debug("setfilters (projects): " + projectsString);
Logger.I.debug("setfilters (tags): " + tagsString);
Logger.I.debug("setfilters (projects): " + projectsString);

if (tagsString.length > 0) {
const tags = tagsString?.split('|').map(stag => GameTag.fromString(stag));
Expand Down
28 changes: 14 additions & 14 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ CurseHelper.init().catch(err => {

botClient.once(Events.ClientReady, () => {
assert(botClient.user)
logger.info(`Logged in as ${botClient.user.tag}!`);
Logger.I.info(`Logged in as ${botClient.user.tag}!`);

Utils.updateBotStatus(botClient.user, Environment.get().DevMode);
});
Expand Down Expand Up @@ -73,43 +73,43 @@ botClient.on(Events.GuildDelete, async (guild: Guild) => {

//Remove server from DB
await GuildService.removeServer(guild.id);
logger.info(`guildDelete(${guild.name}) successful!`)
Logger.I.info(`guildDelete(${guild.name}) successful!`)
}
catch (err) {
logger.error(`guildDelete(${guild.name}) error: ${err}`);
Logger.I.error(`guildDelete(${guild.name}) error: ${err}`);
Utils.sendDMtoBotOwner(botClient, `guildDelete(${guild.name}) error: ${err}`)
}
});

botClient.on(Events.Error, (err) => {
logger.error("ERROR: " + err.name);
logger.error("message: " + err.message);
logger.error(err.stack ?? 'NO STACK')
Logger.I.error("ERROR: " + err.name);
Logger.I.error("message: " + err.message);
Logger.I.error(err.stack ?? 'NO STACK')
});

botClient.on(Events.ShardError, err => {
logger.error("SHARD ERROR: " + err.name);
logger.error("message: " + err.message);
logger.error(err.stack ?? 'NO STACK')
Logger.I.error("SHARD ERROR: " + err.name);
Logger.I.error("message: " + err.message);
Logger.I.error(err.stack ?? 'NO STACK')
});

/*- Node.js events -*/
process.on('unhandledRejection', (reason, promise) => {
promise.catch(() => logger.error("Damn boi, how did this happen " + reason));
promise.catch(() => Logger.I.error("Damn boi, how did this happen " + reason));
throw reason;
});

process.on('uncaughtException', (error, origin) => {
Utils.sendDMtoBotOwner(botClient, "GENERIC ERROR - " + error.name + ": " + error.message)
logger.error("GENERIC ERROR - " + error.name + ": " + error.message);
Logger.I.error("GENERIC ERROR - " + error.name + ": " + error.message);
if (error.stack) {
logger.error(error.stack);
Logger.I.error(error.stack);
}

logger.error(origin);
Logger.I.error(origin);
});

process.on('warning', logger.warn);
process.on('warning', Logger.I.warn);
/*-------------------*/

initScheduler();
Expand Down
20 changes: 10 additions & 10 deletions src/model/Command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import {
} from "@discordjs/builders";
import {CommandScope} from "./CommandGroup.js";
import {AutocompleteInteraction, CommandInteraction} from "discord.js";
import {logger} from "../main.js";
import {PrismaClientKnownRequestError} from "@prisma/client/runtime/library.js";
import UninitializedGuildError from "./UninitializedGuildError.js";
import GuildService from "../services/GuildService.js";
import {Logger} from "../util/log.js";

type CommandHandler = (interaction: CommandInteraction) => Promise<void> | void;
type AutocompleteHandler = (interaction: AutocompleteInteraction) => void;
Expand Down Expand Up @@ -48,7 +48,7 @@ export default class Command extends SlashCommandBuilder {
}

try {
logger.info("calling: ", interaction.commandName, subcommand)
Logger.I.info("calling: ", interaction.commandName, subcommand)

if (this._actions.has(subcommand)) {
const action = this._actions.get(subcommand)!
Expand All @@ -59,29 +59,29 @@ export default class Command extends SlashCommandBuilder {

if (error instanceof PrismaClientKnownRequestError) {
void interaction.reply({ content: ":x: Generic Data Error", ephemeral: true })
logger.error(`Prisma Error (${error.code}): ${error.message}`)
Logger.I.error(`Prisma Error (${error.code}): ${error.message}`)
}
else if (error instanceof UninitializedGuildError) {
logger.warn("Uninitialized guild " + interaction.guild?.name + ", now initializing...")
Logger.I.warn("Uninitialized guild " + interaction.guild?.name + ", now initializing...")
await GuildService.initServer({ id: interaction.guildId!, name: interaction.guild!.name })
void interaction.reply({content: ":x: Server config was not yet populated, **this is a one-time only error, please try again.**", ephemeral: true})
}
else if (error.code === 400) {
logger.error("Request Error (" + error.code + "): " + error.name);
logger.error(error.message);
Logger.I.error("Request Error (" + error.code + "): " + error.name);
Logger.I.error(error.message);
void interaction.reply(":x: **CurseForge Bad Request Error!**");
}
else if (error.code === 503 || error.code === 500) {
logger.error("CurseForge Server Error (" + error.code + "): " + error.name);
logger.error(error.message);
Logger.I.error("CurseForge Server Error (" + error.code + "): " + error.name);
Logger.I.error(error.message);
void interaction.reply(":x: CurseForge Error!")
}
else if (error instanceof Error) {
await interaction.reply({content: `Error: ${error.name} while running command \`${this.name } ${subcommand}\``});
void interaction.followUp(error.message);

logger.warn("Running command: " + this.name + " " + subcommand + "has failed!!");
logger.error(error.name + ': ' + error.message);
Logger.I.warn("Running command: " + this.name + " " + subcommand + "has failed!!");
Logger.I.error(error.name + ': ' + error.message);
}
}
}
Expand Down
Loading

0 comments on commit d15deff

Please sign in to comment.