UNPKG

@kamuridesu/whatframework

Version:

A simple WhatsApp Bot Framework on top of Baileys

77 lines (76 loc) 2.95 kB
import { Language } from "./lang/language.js"; import { stringFormat } from "./text.js"; export class CommandHandler { constructor() { this.commands = []; } register(...commands) { const allCommands = []; commands .flatMap(command => command.commands) .forEach(cmd => { [...cmd.aliases, cmd.name].forEach(aliasOrName => { if (allCommands.includes(aliasOrName)) { throw new Error(`Alias or command ${aliasOrName} already exists!`); } allCommands.push(aliasOrName); }); }); this.commands = this.commands.concat(commands); } handle(command, bot, message, args) { for (let c of this.commands) { const func = c.commands.filter(com => (com.name == command || com.aliases.includes(command)))[0]; if (func) return func.func(bot, message, args); } } getCommandDescription(bot, command) { for (let c of this.commands) { for (let com of c.commands) { if (com.name === command || com.aliases.includes(command)) { const text = stringFormat(com.description, { prefix: bot.prefix, command: command }); return `${command}\n\n${text}` + (com.aliases.length > 0 ? `\n\n[Aliases]:\n${com.aliases.join("\n")}` : ""); } } } return new Language(bot).get().commandNotFoundError; } getCommandsMenu(bot) { const lang = new Language(bot).get(); let text = `--==${bot.name}==--\n\n${lang.commands}:\n\n`; for (let c of this.commands) { text += `${c.category}:\n`; for (let com of c.commands) { text += "/" + com.name + "\n"; } text += "\n"; } return text.trim(); } getCommandsByCategory(bot, category) { const filtered = this.commands.find(c => c.category.toLowerCase() == category); if (!filtered) { return null; } const lang = new Language(bot).get(); let text = `--=={${bot.name}}==--\n\n${lang.category}: ${filtered.category}:\n\n`; for (let c of filtered.commands) { text += "/" + c.name + "\n"; } return text.trim(); } getHelp(bot, command) { return (command == undefined || command.trim() == "" || this.commands .find(c => c.commands .find(s => s.aliases.includes(command) || s.name == command) == undefined) == undefined) ? this.getCommandsMenu(bot) : this.commands.find(c => c.category.toLowerCase() == command.toLowerCase()) ? this.getCommandsByCategory(bot, command.toLowerCase()) : this.getCommandDescription(bot, command); } }