chipmunkbot-archive/commands.js
2023-06-26 23:04:54 -04:00

96 lines
No EOL
2.5 KiB
JavaScript

const fs = require('fs')
const path = require('path')
const cperms = require('./cperms.js')
commands = {}
function addCommand (command) {
if (!isValid(command))
return//throw new Error(`Command ${command} is invalid.`)
if (commands[command] == null)
commands[command] = command
command.aliases.forEach((alias) => {
alias = alias.toLowerCase()
if (commands[alias] == null) commands[alias] = command
})
}
function load () {
fs.readdirSync(
path.join(__dirname, 'commands')
).forEach((file) => {
if (file.endsWith(".js")) {
const command = path.join(__dirname, 'commands', file)
try {
const cmd = require(command)
addCommand(cmd)
} catch (e) {
console.log(`Error loading command ${command}:`)
console.log(require('util').inspect(e))
}
}
})
}
function reload() {
try {
Object.keys(commands).forEach(key => {
const command = commands[key];
delete require.cache[command.path];
})
} catch (err) { }
commands = {}
load()
}
function execute (bot, command, player, args, ...custom) {
const cmd = info(command)
if (!cmd.enabled)
return bot.core.run(`/bcraw &cThe command ${bot.prefix}${command} is disabled.`)
if (cmd.permLevel > 0) {
if (args.length < 1)
return bot.core.run(`/bcraw &cYou must provide a code to run this command.`)
const code = parseFloat(args.splice(-1, 1)[0].replace(/§./g, ''))
if (!cperms.validate(cmd.permLevel, code))
return bot.core.run(`/tellraw @a ${JSON.stringify([
{ text: `Invalid code: ${code}.`, color: bot.colors.error }
])}`)
}
try {
return cmd.execute(bot, command, player, args, module.exports, ...custom)
} catch (e) {
console.log(`Error executing command ${command}:`)
console.log(require('util').inspect(e))
bot.core.run(`/tellraw @a ${JSON.stringify({ text: e.stack.split('\n')[0], color: bot.colors.error })}`)
}
}
function info (command) {
return commands[command]
}
function isCommand (command) {
return commands[command] != null
}
function isValid(command) {
return command != null &&
typeof command.execute === 'function' &&
typeof command.name === 'string' &&
typeof command.description === 'string' &&
Array.isArray(command.usages) &&
Array.isArray(command.aliases) &&
typeof command.enabled === 'boolean' &&
command.aliases.length > 0 &&
typeof command.permLevel === 'number'
}
module.exports = { addCommand, load, reload, execute, info, isCommand, isValid, commands }