Split ready event into dedicated event file, made some changes to init

This commit is contained in:
Essem 2022-09-28 23:38:19 -05:00
parent cee458cef1
commit a50c86a0e2
No known key found for this signature in database
GPG key ID: 7D497397CC3A2A8C
2 changed files with 151 additions and 139 deletions

230
app.js
View file

@ -17,7 +17,6 @@ import { fileURLToPath } from "url";
import { config } from "dotenv"; import { config } from "dotenv";
config({ path: resolve(dirname(fileURLToPath(import.meta.url)), ".env") }); config({ path: resolve(dirname(fileURLToPath(import.meta.url)), ".env") });
import { generateList, createPage } from "./utils/help.js";
import { reloadImageConnections } from "./utils/image.js"; import { reloadImageConnections } from "./utils/image.js";
// main services // main services
@ -30,21 +29,44 @@ import { exec as baseExec } from "child_process";
import { promisify } from "util"; import { promisify } from "util";
const exec = promisify(baseExec); const exec = promisify(baseExec);
// initialize command loader // initialize command loader
import { load, send } from "./utils/handler.js"; import { load } from "./utils/handler.js";
// command collections // command collections
import { paths } from "./utils/collections.js"; import { paths } from "./utils/collections.js";
// database stuff // database stuff
import database from "./utils/database.js"; import database from "./utils/database.js";
// lavalink stuff // lavalink stuff
import { checkStatus, connect, reload, status, connected } from "./utils/soundplayer.js"; import { checkStatus, reload } from "./utils/soundplayer.js";
// events // events
import { endBroadcast, startBroadcast, activityChanger, checkBroadcast } from "./utils/misc.js"; import { endBroadcast, startBroadcast } from "./utils/misc.js";
import { parseThreshold } from "./utils/tempimages.js"; import { parseThreshold } from "./utils/tempimages.js";
const { types } = JSON.parse(readFileSync(new URL("./config/commands.json", import.meta.url))); const { types } = JSON.parse(readFileSync(new URL("./config/commands.json", import.meta.url)));
const esmBotVersion = JSON.parse(readFileSync(new URL("./package.json", import.meta.url))).version; const esmBotVersion = JSON.parse(readFileSync(new URL("./package.json", import.meta.url))).version;
exec("git rev-parse HEAD").then(output => output.stdout.substring(0, 7), () => "unknown commit").then(o => process.env.GIT_REV = o).then(() => {
const intents = [
"GUILD_VOICE_STATES",
"DIRECT_MESSAGES"
];
if (types.classic) {
intents.push("GUILDS");
intents.push("GUILD_MESSAGES");
intents.push("MESSAGE_CONTENT");
}
async function* getFiles(dir) {
const dirents = await promises.readdir(dir, { withFileTypes: true });
for (const dirent of dirents) {
const name = dir + (dir.charAt(dir.length - 1) !== "/" ? "/" : "") + dirent.name;
if (dirent.isDirectory()) {
yield* getFiles(name);
} else if (dirent.name.endsWith(".js")) {
yield name;
}
}
}
async function init() {
await exec("git rev-parse HEAD").then(output => output.stdout.substring(0, 7), () => "unknown commit").then(o => process.env.GIT_REV = o);
console.log(` console.log(`
,*\`$ z\`"v ,*\`$ z\`"v
F zBw\`% A ,W "W F zBw\`% A ,W "W
@ -68,20 +90,80 @@ k <BBBw BBBBEBBBBBBBBBBBBBBBBBQ4BM #
esmBot ${esmBotVersion} (${process.env.GIT_REV}) esmBot ${esmBotVersion} (${process.env.GIT_REV})
`); `);
});
const intents = [ if (!types.classic && !types.application) {
"GUILD_VOICE_STATES", logger.error("Both classic and application commands are disabled! Please enable at least one command type in config/commands.json.");
"DIRECT_MESSAGES" return process.exit(1);
]; }
if (types.classic) {
intents.push("GUILDS");
intents.push("GUILD_MESSAGES");
intents.push("MESSAGE_CONTENT");
}
// PM2-specific handling // database handling
if (process.env.PM2_USAGE) { const dbResult = await database.upgrade(logger);
if (dbResult === 1) return process.exit(1);
await database.setup();
// process the threshold into bytes early
if (process.env.TEMPDIR && process.env.THRESHOLD) {
await parseThreshold();
}
// register commands and their info
const soundStatus = await checkStatus();
logger.log("info", "Attempting to load commands...");
for await (const commandFile of getFiles(resolve(dirname(fileURLToPath(import.meta.url)), "./commands/"))) {
logger.log("main", `Loading command from ${commandFile}...`);
try {
await load(null, commandFile, soundStatus);
} catch (e) {
logger.error(`Failed to register command from ${commandFile}: ${e}`);
}
}
logger.log("info", "Finished loading commands.");
if (process.env.API_TYPE === "ws") await reloadImageConnections();
// create the oceanic client
const client = new Client({
auth: `Bot ${process.env.TOKEN}`,
allowedMentions: {
everyone: false,
roles: false,
users: true,
repliedUser: true
},
gateway: {
concurrency: "auto",
maxShards: "auto",
presence: {
status: "idle",
activities: [{
type: 0,
name: "Starting esmBot..."
}]
},
intents
},
collectionLimits: {
messages: 50
}
});
// register events
logger.log("info", "Attempting to load events...");
for await (const file of getFiles(resolve(dirname(fileURLToPath(import.meta.url)), "./events/"))) {
logger.log("main", `Loading event from ${file}...`);
const eventArray = file.split("/");
const eventName = eventArray[eventArray.length - 1].split(".")[0];
if (eventName === "interactionCreate" && !types.application) {
logger.log("warn", `Skipped loading event from ${file} because application commands are disabled`);
continue;
}
const { default: event } = await import(file);
client.on(eventName, event.bind(null, client));
}
logger.log("info", "Finished loading events.");
// PM2-specific handling
if (process.env.PM2_USAGE) {
pm2.launchBus((err, pm2Bus) => { pm2.launchBus((err, pm2Bus) => {
if (err) { if (err) {
logger.error(err); logger.error(err);
@ -126,113 +208,9 @@ if (process.env.PM2_USAGE) {
} }
}); });
}); });
}
client.connect();
} }
database.upgrade(logger).then(result => { init();
if (result === 1) return process.exit(1);
});
// process the threshold into bytes early
if (process.env.TEMPDIR && process.env.THRESHOLD) {
parseThreshold();
}
if (!types.classic && !types.application) {
logger.error("Both classic and application commands are disabled! Please enable at least one command type in config/commands.json.");
process.exit(1);
}
const client = new Client({
auth: `Bot ${process.env.TOKEN}`,
allowedMentions: {
everyone: false,
roles: false,
users: true,
repliedUser: true
},
gateway: {
concurrency: "auto",
maxShards: "auto",
presence: {
status: "idle",
activities: [{
type: 0,
name: "Starting esmBot..."
}]
},
intents
},
collectionLimits: {
messages: 50
}
});
client.once("ready", async () => {
// register commands and their info
const soundStatus = await checkStatus();
logger.log("info", "Attempting to load commands...");
for await (const commandFile of getFiles(resolve(dirname(fileURLToPath(import.meta.url)), "./commands/"))) {
logger.log("main", `Loading command from ${commandFile}...`);
try {
await load(client, commandFile, soundStatus);
} catch (e) {
logger.error(`Failed to register command from ${commandFile}: ${e}`);
}
}
if (types.application) {
try {
await send(client);
} catch (e) {
logger.log("error", e);
logger.log("error", "Failed to send command data to Discord, slash/message commands may be unavailable.");
}
}
logger.log("info", "Finished loading commands.");
if (process.env.API_TYPE === "ws") await reloadImageConnections();
await database.setup();
// register events
logger.log("info", "Attempting to load events...");
for await (const file of getFiles(resolve(dirname(fileURLToPath(import.meta.url)), "./events/"))) {
logger.log("main", `Loading event from ${file}...`);
const eventArray = file.split("/");
const eventName = eventArray[eventArray.length - 1].split(".")[0];
if (eventName === "interactionCreate" && !types.application) {
logger.log("warn", `Skipped loading event from ${file} because application commands are disabled`);
continue;
}
const { default: event } = await import(file);
client.on(eventName, event.bind(null, client));
}
logger.log("info", "Finished loading events.");
// generate docs
if (process.env.OUTPUT && process.env.OUTPUT !== "") {
generateList();
await createPage(process.env.OUTPUT);
logger.log("info", "The help docs have been generated.");
}
// connect to lavalink
if (!status && !connected) connect(client);
checkBroadcast(client);
activityChanger(client);
logger.log("info", "Started esmBot.");
});
async function* getFiles(dir) {
const dirents = await promises.readdir(dir, { withFileTypes: true });
for (const dirent of dirents) {
const name = dir + (dir.charAt(dir.length - 1) !== "/" ? "/" : "") + dirent.name;
if (dirent.isDirectory()) {
yield* getFiles(name);
} else if (dirent.name.endsWith(".js")) {
yield name;
}
}
}
client.connect();

34
events/ready.js Normal file
View file

@ -0,0 +1,34 @@
import { activityChanger, checkBroadcast } from "../utils/misc.js";
import { connect, status, connected } from "../utils/soundplayer.js";
import { send } from "../utils/handler.js";
import { generateList, createPage } from "../utils/help.js";
import { logger } from "../utils/logger.js";
import { readFileSync } from "fs";
const { types } = JSON.parse(readFileSync(new URL("../config/commands.json", import.meta.url)));
export default async (client) => {
if (types.application) {
try {
await send(client);
} catch (e) {
logger.log("error", e);
logger.log("error", "Failed to send command data to Discord, slash/message commands may be unavailable.");
}
}
// generate docs
if (process.env.OUTPUT && process.env.OUTPUT !== "") {
generateList();
await createPage(process.env.OUTPUT);
logger.log("info", "The help docs have been generated.");
}
// connect to lavalink
if (!status && !connected) connect(client);
checkBroadcast(client);
activityChanger(client);
logger.log("info", "Started esmBot.");
};