import { readdirSync, readFileSync, writeFileSync } from 'fs'; import { join } from 'path'; import { Client } from 'discord.js'; import emojis from "../Config/Emojis.json" assert { type: "json" }; import log from '../Utils/Functions/getColors.js'; import dotenv from 'dotenv' dotenv.config() import { QuickDB } from 'quick.db'; const db = new QuickDB({ filePath: './src/Database/SQLite/.sqlitedata' }); import { Database } from "quickmongo"; const mongo = new Database(process.env.MONGO_URL); import cache from '../Utils/.cache/.commandsCache.json' assert { type: "json" }; const fileCommandsName = []; const isNotModified = []; const searchFile = './src/Utils/.cache/.commandsCache.json'; export default class extends Client { constructor(options) { super(options); (async () => { this.SlashCommandArray = []; this.PrefixCommandArray = []; this.connectToMongoDB() this.getSlashCommands(); this.getPrefixCommands(); this.getEvents(); this.cooldown = new Set(); this.log = log; this.emoji = emojis; this.quickdb = db; this.mongo = mongo; })(); } async registerCommands() { this.log('Aguarde enquanto a aplicação carrega os comandos (/)...', 'system'); const cacheKeys = Object.keys(cache); const existingCommands = await this.application.commands.fetch(); const commandsInLocalScope = this.SlashCommandArray.filter(command => command.guildCollection).map(command => Object.assign(command, command.data)); const allCommands = [...existingCommands, ...commandsInLocalScope]; const commandNames = allCommands.map(command => command[1].name); const differentItems = cacheKeys.filter(key => !commandNames.includes(key)); const array1 = cacheKeys.sort().join(',') const array2 = fileCommandsName.sort().join(',') this.removeObjectFromJSONFile(differentItems) if (isNotModified.every((boolean) => boolean === true) && differentItems.length === 0 && array1 === array2) { this.log('Não há comandos para carregar. Nenhuma alteração foi efetuada!', 'cache') return; } else { // await this.application.commands.set([]) /* <-- clear global commands --> */ const commandsInGlobalScope = this.SlashCommandArray.filter(command => !command.guildCollection?.length).map(command => Object.assign(command, command.data)); if (commandsInLocalScope.length) { const guildIDs = commandsInLocalScope.flatMap(command => command.guildCollection) for (const guildID of guildIDs) { const commands = commandsInLocalScope.filter( cmd => cmd.guildCollection.includes(guildID) /* <-- filter local commands --> */ ) const guild = this.guilds.cache.get(guildID) if (!guild) return this.log(`O servidor ${guild.name} (${guild.id}) esta fora do cache do client`, 'error') //await guild.commands.set([]).catch((err) => this.log(err, 'error')) /* <-- clear local commands --> */ await guild.commands.set(this.SlashCommandArray).catch((err) => this.log(err, 'error')) this.log(`Os comandos (/) com scopo local da aplicação forma carregados com sucesso!`, 'client'); } } await this.application.commands.set(commandsInGlobalScope).catch((err) => this.log(err, 'error')) this.log('Os comandos (/) com scopo globais da aplicação foram carregados com sucesso!', 'client'); } } async getSlashCommands(path = 'src/SlashCommands') { const categories = readdirSync(path); for (const category of categories) { const commands = readdirSync(`${path}/${category}`); for (const command of commands) { const commandFile = join(process.cwd(), `${path}/${category}/${command}`); const { default: SlashCommands } = await import(commandFile); const cmd = new SlashCommands(this); const isModified = this.cacheCommands(cmd); isNotModified.push(!isModified); fileCommandsName.push(cmd?.name); this.SlashCommandArray.push(cmd); } } } async getPrefixCommands(path = 'src/PrefixCommands') { const categories = readdirSync(path); for (const category of categories) { const commands = readdirSync(`${path}/${category}`); for (const command of commands) { const commandFile = join(process.cwd(), `${path}/${category}/${command}`); const { default: PrefixCommands } = await import(commandFile); const cmd = new PrefixCommands(this); this.PrefixCommandArray.push(cmd); } } } async getEvents(path = 'src/Events') { const eventsFolders = readdirSync(path); for (const folders of eventsFolders) { const eventsFiles = readdirSync(`${path}/${folders}`); for (const files of eventsFiles) { if (!files.endsWith('.js')) return; const eventFile = join(process.cwd(), `${path}/${folders}/${files}`); const { default: EventMap } = await import(eventFile); const evnt = new EventMap(this); if (!evnt.once) { this.on(evnt.name, evnt.run); } else { this.once(evnt.name, evnt.run); } } } } cacheCommands(cmd) { const array = ['botPermissions', 'client', 'quickdb'] for (let values of array) { delete cmd[values]; } const name = cmd?.name; const cacheData = JSON.parse(readFileSync(searchFile, 'utf-8')); const existObj = cacheData.hasOwnProperty(name); const json = JSON.stringify(cmd, null, 2); const fileUpdate = { ...cacheData, [name]: json }; writeFileSync(searchFile, JSON.stringify(fileUpdate, null, 2), 'utf8'); const response = !existObj || cacheData[name] !== json; return response; } removeObjectFromJSONFile(objectToRemove) { const data = readFileSync(searchFile, 'utf8'); const json = JSON.parse(data); objectToRemove.forEach(key => delete json[key]); const updatedJson = JSON.stringify(json, null, 2); writeFileSync(searchFile, updatedJson, 'utf8') } antiCrash() { process.on("uncaughtException", (err, origin) => { console.log(chalk.gray("—————————————————————————————————")); console.log( chalk.white("["), chalk.red.bold("AntiCrash"), chalk.white("]"), chalk.gray(" : "), chalk.white.bold("Uncaught Exception/Catch") ); console.log(chalk.gray("—————————————————————————————————")); console.log(err, origin); }); } async connectToMongoDB() { mongo.on("ready", async () => { }); await mongo.connect(); } };