led-bot/parser.js

95 lines
2.0 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";
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(args) {
return [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).join(" "));
this.log.debug(snip);
this.log.debug(res);
this.log.debug(args);
if (res != undefined) {
this.log.debug(`execute function ${res.name}`);
res.func(msg, args, ctx);
}
}
}
}