led-bot/parser.js

122 lines
2.8 KiB
JavaScript

import Logger, { levels } from './logger.js';
import { filename } from './utils.js';
export class Command {
init(ctx, log) {
this.log = log;
}
log;
name = 'DEFAULT';
whitelist = false;
func() { }
}
export class CommandInitializer {
commands = [];
uninitialized = [];
initialize(ctx) {
for (let index in this.uninitialized) {
this.initCommand(this.uninitialized[index], ctx);
delete this.uninitialized[index];
}
}
initCommand(cmd, ctx) {
cmd.init(ctx, new Logger(`cmd.${cmd.name}`, ctx.log_level));
this.commands.push(cmd);
}
addCommand(cmd) {
this.uninitialized.push(cmd);
}
getCommands() {
return this.commands;
}
}
export default class CommandParser {
constructor(ctx, prefix = ';') {
this.log = new Logger(filename(import.meta.url), ctx.log_level);
this.prefix = prefix ? prefix : this.prefix || ';';
}
log;
prefix;
commands = [];
addCommand(cmd) {
this.log.debug(`cmd to add: ${JSON.stringify(cmd)}`);
if (this.isCmd(cmd)) {
this.commands.push(cmd);
}
}
hasCmd(str) {
let results = this.commands.filter((c) => c.name == str);
return results.length ? results[0] : undefined;
}
isCmd(cmd) {
return typeof cmd == 'object' && cmd instanceof Command;
}
getArgsList(split) {
let parsed_args = [];
let join_index = -1;
let add = true;
for (let index in split) {
if (split[index].startsWith('```')) {
join_index = index;
add = false;
}
if (add) {
parsed_args.push(split[index]);
}
if (split[index].endsWith('```') && join_index != -1) {
let joined = split
.slice(join_index, index + 1)
.join(' ')
.replace(/```/g, '');
parsed_args.push(joined);
add = true;
join_index = -1;
}
}
return parsed_args;
}
parseMsg(msg, ctx) {
if (msg.author.bot) {
return;
}
this.log.debug(msg.content);
this.log.debug(msg.content.startsWith(this.prefix));
this.log.debug(msg.content[0]);
this.log.debug(this.prefix);
if (msg.content.startsWith(this.prefix)) {
let snip = msg.content.slice(this.prefix.length);
let unsep = snip.split(' ');
let res = this.hasCmd(unsep[0]);
let args = this.getArgsList(unsep.slice(1));
this.log.debug(snip);
this.log.debug(res);
this.log.debug(args);
if (res != undefined) {
if (msg.channel.guild && !ctx.whitelist.guild(msg.channel.guild)) {
msg.channel.createMessage('guild not whitelisted');
return;
}
this.log.debug(`execute function ${res.name}`);
if (res.whitelist && !ctx.whitelist.user(msg.author)) {
msg.channel.createMessage('not whitelisted');
} else {
res.func(msg, args, ctx);
}
}
}
}
}