Skip to content

Commit

Permalink
Added projectwide logger implamentation
Browse files Browse the repository at this point in the history
  • Loading branch information
whizbangpop committed Nov 28, 2022
1 parent 06f76d1 commit d52899e
Show file tree
Hide file tree
Showing 8 changed files with 52 additions and 60 deletions.
1 change: 0 additions & 1 deletion src/listeners/newCommandHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { Client, Collection, GuildMember } from "discord.js"
import { Client as SClient } from "statcord.js"
import fs from "fs"
import path from "path"
import { createSimpleLogger } from "simple-node-logger"
import { QuickDB } from "quick.db"
import { webhookReporter } from "../utilities"
import { config } from "../../data/config"
Expand Down
10 changes: 5 additions & 5 deletions src/listeners/onMessageCreate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import fs from "fs";
import { AsciiTable3, AlignmentEnum } from "ascii-table3";

// Node logger
const log = createSimpleLogger("./data/mcb.log");
import { debug,log,error } from '../lib/tsabLogger';

// Automatic command importer
const commandArray: Array<string> = [];
Expand All @@ -25,7 +25,7 @@ fs.readdirSync(commandDir).forEach(file => {
file = file.toLowerCase();
if (file.startsWith('temp')) return;
commandArray.push(file);
log.info(`Imported Command: ${file}`);
log(`Imported Command: ${file}`);
})

const table = new AsciiTable3('Commands')
Expand Down Expand Up @@ -95,7 +95,7 @@ export default (client: Client, statcord: SClient): void => {
if (!member!.permissions.has(`${commandToRun.requiredPermissions[i]}`)) return msg.reply(config.responses.noPermission);
}

log.info('Special command run!')
log('Special command run!')
commandToRun.execute(msg, args, client);
return statcord.postCommand(command, msg.author.id);
} else {
Expand All @@ -111,7 +111,7 @@ export default (client: Client, statcord: SClient): void => {
}
});

client.on('error', async (error) => {
log.error(`OH F**K SOMETHING REALLY REALLY WENT WRONG. HERE'S THE RUNDOWN: \n\n${error}`)
client.on('error', async (e) => {
error(`SOMETHING REALLY REALLY WENT WRONG. HERE'S THE RUNDOWN: \n\n\`${e}\``, { sendWebhook:true })
})
};
28 changes: 13 additions & 15 deletions src/listeners/ready.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ import Statcord from "statcord.js"
import { REST } from "@discordjs/rest"
import { Routes } from "discord-api-types/v10"

const log = createSimpleLogger("./data/mcb.log")
log.setLevel("debug") // set to INFO for production (i mean unless you want lots more info then go ahead lol)
import { debug,log,error } from '../lib/tsabLogger';

const db = new QuickDB()
const sysInternals = db.table("sysInt")
Expand All @@ -32,7 +31,7 @@ export default (client: Client, statcord: Statcord.Client): void => {
checkForInfo()
await statcord.autopost()

log.info(`${client.user.tag} connected to Discord Gateway successfully`)
log(`${client.user.tag} connected to Discord Gateway successfully`)

const guild = client.guilds.cache.get(config.discord.serverId)
const logChannel = guild?.channels.cache.get(
Expand All @@ -41,14 +40,13 @@ export default (client: Client, statcord: Statcord.Client): void => {
const staffRole = guild?.roles.cache.get(config.discord.staffRole) as Role

// Log config info
log.debug(`Set guild to ${guild?.name} (${guild?.id})`)
log.debug(`Set log channel to #${logChannel.name} (${logChannel.id})`)
log.debug(`Set staff role to @${staffRole.name} (${staffRole.id})`)
log.debug(`Set shard count to ${config.discord.shardCount}`)
debug(`Set guild to ${guild?.name} (${guild?.id})`)
debug(`Set log channel to #${logChannel.name} (${logChannel.id})`)
debug(`Set staff role to @${staffRole.name} (${staffRole.id})`)

const statusText = "summer do the dev shuffle"
const statusText = "the suffering of humanity"
client.user.setActivity(statusText, { type: ActivityType.Watching })
log.debug(`Set custom status to ${statusText}`)
debug(`Set custom status to ${statusText}`, { sendWebhook:true })

const logEmbed1 = new EmbedBuilder()
.setTitle("Status Log")
Expand Down Expand Up @@ -78,26 +76,26 @@ export default (client: Client, statcord: Statcord.Client): void => {
content: "Checking API connection.. OK",
},
})
} catch (e) {
log.error(e)
} catch (e:any) {
error(`\`${e}\``, { sendWebhook:true })
}

mongoose
.connect(config.mongo.connectionUri, {
keepAlive: true,
})
.then(() => {
log.info("Connected to MongoDB database...")
log("Connected to MongoDB database...")
})
.catch((e) => {
log.error(`DB Error: ${e}`)
error(`DB Error: ${e}`)
})

try {
log.debug("Linking commands...")
debug("Linking commands...")
// linkCommandsOld(client);
} catch (e) {
log.error("Error linking commands, exiting...")
error("Error linking commands, exiting...")
process.abort()
}
})
Expand Down
9 changes: 4 additions & 5 deletions src/scripts/DiscordJS/clearCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@ import {createSimpleLogger} from "simple-node-logger";
import {QuickDB} from "quick.db";

const rest = new REST({ version: '10' }).setToken(config.discord.token);
const log = createSimpleLogger("./data/mcb.log");
log.setLevel('debug');
import { debug,error,log } from '../../lib/tsabLogger';
const db = new QuickDB();
const sysInternals = db.table("sysInt");

log.info('Starting deletion...')
log('Starting deletion...')
const commands: never[] = []

rest.put(Routes.applicationGuildCommands(config.discord.clientId, config.discord.serverId), {body: commands})
.then((data:any) => log.debug(`Successfully deleted all commands.`))
.catch(log.error)
.then((data:any) => debug(`Successfully deleted all commands.`))
.catch(error)
9 changes: 4 additions & 5 deletions src/scripts/DiscordJS/manCommandLoad.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,15 @@ import {createSimpleLogger} from "simple-node-logger";
import {QuickDB} from "quick.db";

const rest = new REST({ version: '10' }).setToken(config.discord.token);
const log = createSimpleLogger("./data/mcb.log");
log.setLevel('debug');
import { debug,log,error } from '../../lib/tsabLogger';
const db = new QuickDB();
const sysInternals = db.table("sysInt");

log.info('Manually syncing selected commands...')
log('Manually syncing selected commands...')
const commands = [
new SlashCommandBuilder().setName('ping').setDescription("Replies with system latency"),
].map(command=>command.toJSON());

rest.put(Routes.applicationGuildCommands(config.discord.clientId, config.discord.serverId), {body: commands})
.then((data:any) => log.debug(`Successfully registered ${data.length} application commands.`))
.catch(log.error)
.then((data:any) => debug(`Successfully registered ${data.length} application commands.`))
.catch(error)
9 changes: 4 additions & 5 deletions src/scripts/DiscordJS/syncCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import {QuickDB} from "quick.db";
import fs from "fs";

const rest = new REST({ version: '10' }).setToken(config.discord.token);
const log = createSimpleLogger("./data/mcb.log");
log.setLevel('debug');
import { debug,log,error } from '../../lib/tsabLogger';
const db = new QuickDB();
const sysInternals = db.table("sysInt");

Expand All @@ -26,13 +25,13 @@ fs.readdirSync(commandDir).forEach(file => {
if (cmd.data) {
commands.push(cmd.data.toJSON());
console.log(cmd)
log.info(`Imported Slash Command: ${file}`);
log(`Imported Slash Command: ${file}`);
}
})

console.log('Syncing commands..')

rest.put(Routes.applicationGuildCommands(config.discord.clientId, config.discord.serverId), {body: commands})
.then((data:any) => log.debug(`Successfully registered ${data.length} application commands.`))
.catch(log.error)
.then((data:any) => debug(`Successfully registered ${data.length} application commands.`))
.catch(error)

17 changes: 8 additions & 9 deletions src/theHeart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import * as figlet from "figlet";
import Statcord from "statcord.js";
import tempListener from "./listeners/customListeners/temp.listener";
import newCommandHandler from "./listeners/newCommandHandler";

const log = createSimpleLogger("./data/mcb.log");
import { debug,log,warn,error } from './lib/tsabLogger'

figlet.text(
"TSAB Framework",
Expand All @@ -19,16 +18,16 @@ figlet.text(
},
function (err, data) {
if (err) {
log.warn("Something went wrong...");
warn("Something went wrong...");
console.dir(err);
return;
}
console.log(data);
}
);

log.info("Built and Maintained by SDS | Please wait for all services to start...");
log.info("Starting bot...");
log("Built and Maintained by SDS | Please wait for all services to start...");
log("Starting bot...");


const client = new Client({
Expand Down Expand Up @@ -60,17 +59,17 @@ tempListener(client)

try {
client.login(config.discord.token).then(r => {
log.debug('Discord websocket connected!')
debug('Discord websocket connected!')
});
} catch (e) {
log.warn('Error when connecting to Discord Gateway')
warn('Error when connecting to Discord Gateway', { sendWebhook: true })
}

statcord.on("post", (status: any) => {
if (!status) {
log.debug("Successful post");
debug("Successful post");
}
else {
log.warn(status)
warn(status, { sendWebhook:true })
};
});
29 changes: 14 additions & 15 deletions src/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,24 @@ import { config } from "../data/config"
import { createSimpleLogger } from "simple-node-logger"
import { QuickDB } from "quick.db"
import { EmbedBuilder, WebhookClient } from "discord.js"

const log = createSimpleLogger("./data/mcb.log")
import { debug,log,warn,error } from "./lib/tsabLogger"
const db = new QuickDB()

/**
* Module to check if all required daat is present in the config.ts file.
*/
export function checkForInfo() {
if (!config.discord.serverId) {
log.error("No server specified, exit to prevent further errors...")
error("No server specified, exit to prevent further errors...")
return process.exit()
} else if (!config.discord.logChannel) {
log.error("No log channel, exit to prevent further errors...")
error("No log channel, exit to prevent further errors...")
return process.exit()
} else if (!config.discord.staffRole) {
log.error("No staff role, exit to prevent further errors...")
error("No staff role, exit to prevent further errors...")
return process.exit()
} else {
return log.debug("All checks passed, starting bot..")
return debug("All checks passed, starting bot..")
}
}

Expand All @@ -47,18 +46,18 @@ export async function disclaimerCheck(db: QuickDB, table: any) {
(await table.get("registered")) === null ||
(await table.get("registered")) === false
) {
log.info("-----")
log.warn(
log("-----")
warn(
"DISCLAIMER: SDS do not take responsibility for any loopholes or exploits in commands or internal systems."
)
log.warn(
warn(
"Any known vulnerabilities in the code we ship will be fixed ASAP, but any code you create, modify and/or delete, is your responsibility."
)
log.warn(
warn(
"This bot is NOT made to serve multiple guilds, it's only designed to serve 1 guild, so if you use the bot in multiple, things will at some point break."
)
log.info("-----")
log.debug("Disclaimer displayed, registering bot in DB")
log("-----")
debug("Disclaimer displayed, registering bot in DB")

await table.set("registered", true)
}
Expand Down Expand Up @@ -88,12 +87,12 @@ export async function customLogger(mode: string, user: string) {

/**
* Report different logs to a designated Discord webhook
* @param {string} mode - What type of log will be sent. debug, info, warn, error, note
* @param {string} mode - What type of log will be sent. debug, log, warn, error, note
* @param {string} text - Text to be sent along with the embed.
* @return {object} webhook - Returns a DiscordJS Webhook object */
export async function webhookReporter(mode: string, text: string) {
if (!config.tsabLoggerSetting.loggingWebhook) {
return log.error("No webhook found! Check your config!")
return error("No webhook found! Check your config!")
}

const whClient = new WebhookClient({
Expand Down Expand Up @@ -152,6 +151,6 @@ export async function webhookReporter(mode: string, text: string) {
return await whClient.send({ embeds: [noteEmbed] })

default:
return log.warn("Not a correct log type!")
return warn("Not a valid log type!")
}
}

0 comments on commit d52899e

Please sign in to comment.