DiscordJS-Template/shared.js

53 lines
1.5 KiB
JavaScript
Raw Normal View History

2024-02-11 01:04:12 +00:00
import { readdir } from 'fs/promises';
import { join } from 'path';
import Module from 'module';
2024-02-06 15:18:06 +00:00
2024-02-11 01:04:12 +00:00
// Lists of required and optional attributes of command modules
2024-02-06 15:18:06 +00:00
const required = ['data', 'execute'];
const optional = ['autocomplete', 'modalSubmit'];
2024-02-11 01:04:12 +00:00
/**
* Recursively scans a directory for all files in it.
* @param {string} dir
2024-03-02 22:49:49 +00:00
* @returns {Promise<Array<string>>} Array of paths to the files within.
2024-02-11 01:04:12 +00:00
*/
2024-02-06 15:18:06 +00:00
export const getFiles = async (dir) => {
const dirents = await readdir(dir, { withFileTypes: true });
const files = await Promise.all(
dirents.map((dirent) => {
const res = join(dir, dirent.name);
return dirent.isDirectory() ? getFiles(res) : res;
})
);
return Array.prototype.concat(...files);
};
2024-02-11 01:04:12 +00:00
/**
* Imports and checks a command from a path as a module.
* @param {string} filePath
* @returns {Promise<Module|0>}
*/
2024-02-06 15:18:06 +00:00
export const importAndCheck = async (filePath) => {
if (!filePath.endsWith('.js') || filePath.endsWith('.example.js')) {
// Skip this file
return 0;
}
const command = await import(filePath);
// Warn incomplete commands
if (!required.every((name) => name in command)) {
console.error(
`[ERROR] The command at ${filePath} is missing a required "data" or "execute" property.`
);
return 0;
}
const properties = optional.filter((name) => !(name in command));
if (properties.length > 0)
properties.forEach((name) =>
console.warn(
`[WARNING] The command at ${filePath} is missing an optional "${name}" property.`
)
);
// Add command to collection
return command;
};