galactic-bot/structure/components/observers/CommandHandler.js
2020-04-08 10:08:46 -06:00

108 lines
2.8 KiB
JavaScript

const { stripIndents } = require('common-tags');
const { escapeRegex } = require('escape-string-regexp');
const { Observer } = require('../../interfaces');
class CommandHandler extends Observer {
constructor(manager) {
super(manager, {
name: 'commandHandler',
priority: 5,
guarded: true
});
this.manager = manager;
this.hooks = [
['message', this.handleMessage.bind(this)]
];
this.commandPatterns = new Map();
}
async handleMessage(message) {
const client = message.client;
if(!this.manager._built
|| !client._built
|| message.webhookID
|| message.author.bot
|| (message.guild && !message.guild.available)) return undefined;
if(message.guild && !message.member) {
await message.guild.members.fetch(message.author.id);
}
const content = message.cleanContent;
const args = content.split(' ');
const command = await this._getCommand(message, args);
if(!command) return undefined;
return await this.handleCommand(message, command, args);
}
async handleCommand(message, command, args) {
}
async _getCommand(message, args = []) {
const pattern = await this._getCommandPattern(message.guild);
let command = await this._matchCommand(message, args, pattern, 2);
if(!command && !message.guild) command = await this._matchCommand(message, args, /^([^\s]+)/i);
return command || null;
}
async _getCommandPattern(guild) {
const createCommandPattern = (guild = null) => {
const prefix = this.client._options.discord.prefix;
const escapedPrefix = escapeRegex(prefix);
const pattern = new RegExp(`^(${escapedPrefix}\\s*|<@!?${this.client.user.id}>\\s+(?:${escapedPrefix})?)([^\\s]+)`, 'i');
const obj = { pattern, prefix };
if(guild) {
this.client.logger.debug(`Created command pattern ${guild.name}: ${pattern}`);
this.commandPatterns.set(guild.id, obj);
}
return obj;
};
if(!guild) return createCommandPattern().pattern;
let commandPattern = this.commandPatterns.get(guild.id);
return commandPattern.pattern;
}
async _matchCommand(message, args, pattern, index = 1) {
const matches = pattern.exec(message.cleanContent);
if(!matches) return null;
const command = message.client.resolver.components(matches[index], 'command', true)[0];
if(!command) return null;
const indice = message.content.startsWith('<@') ? 2 : 1;
args.splice(0, indice);
return command;
}
}
module.exports = CommandHandler;