const fs = require('fs') const path = require('path') const util = require('util') function inject (bot) { bot.commands = { commands: {}, add, execute, info, isCommand, loadFromDir, isValid } bot.on('message', (player, message) => { if (!message.startsWith(bot.prefix)) { return } const args = message.slice(bot.prefix.length).split(' ') const command = args.shift().toLowerCase() if (!isCommand(command)) { return bot.core.run(`/tellraw @a ${JSON.stringify({ text: `Unknown command: ${bot.prefix}${command}`, color: bot.colors.error })}`) } bot.commands.execute(bot, command, player, args) }) function add (command) { if (!isValid(command)) throw new Error('Invalid command', 'invalid_command') command.aliases.forEach(alias => (bot.commands.commands[alias.toLowerCase()] = command)) } function loadFromDir (dirpath) { fs.readdirSync(dirpath).forEach(filename => { const filepath = path.resolve(dirpath, filename) if (!filepath.endsWith('js') || !fs.statSync(filepath).isFile()) return try { bot.commands.add(require(filepath)) } catch (err) { bot.console.error('Error loading command ' + filepath + ': ' + util.inspect(err)) } }) } function info (command) { const info = bot.commands.commands[command] ?? command if (isValid(info)) { return info } } function isCommand (command) { return bot.commands.info(command) != null } async function execute (bot, command, player, args, ...custom) { const info = bot.commands.info(command) if (info == null) { bot.core.run('minecraft:tellraw @a ' + JSON.stringify({ text: 'Unknown command: ' + bot.prefix + command, color: bot.colors.error })) return } if (!info.enabled) { bot.core.run('minecraft:tellraw @a ' + JSON.stringify({ text: bot.prefix + command + 'is disabled', color: bot.colors.error })) return } if (info.permLevel > 0) { bot.core.run('minecraft:tellraw @a ' + JSON.stringify({ text: 'Trusted commands are currently disabled', color: bot.colors.error })) return } try { return await info.execute(bot, command, player, args, ...custom) } catch (err) { bot.console.error('Error executing command ' + command + ': ' + util.inspect(err)) bot.core.run('minecraft:tellraw @a ' + JSON.stringify({ text: err.message, color: bot.colors.error })) } } } 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.bot = inject