defer to led server to provide functions

This commit is contained in:
jane 2021-05-27 14:56:26 -04:00
parent 1e30598bc4
commit 03bbf03279
6 changed files with 183 additions and 157 deletions

5
bot.js
View File

@ -1,4 +1,6 @@
import { createRequire } from 'module'; import { createRequire } from 'module';
import { discover } from './lights/light_parser.js';
import { contactServer } from './lights/request.js';
const require = createRequire(import.meta.url); const require = createRequire(import.meta.url);
import Eris from 'eris'; import Eris from 'eris';
@ -103,3 +105,6 @@ let cmd_dir = path.join(dir, 'cmd');
log.debug(dir); log.debug(dir);
let files = fs.readdirSync(cmd_dir); let files = fs.readdirSync(cmd_dir);
load_commands(); load_commands();
contactServer(discover, (err) => {
log.error(err);
})

View File

@ -1,56 +1,57 @@
import { CommandInitializer, Command } from '../parser.js'; import { CommandInitializer, Command } from '../parser.js';
import parse, { initialize, instructions } from '../lights/light_parser.js'; import parse, { discover, initialize, instructions } from '../lights/light_parser.js';
import req from '../lights/request.js'; import req from '../lights/request.js';
const initializer = new CommandInitializer(); const initializer = new CommandInitializer();
class LightsParser extends Command { class LightsParser extends Command {
init(ctx, log) { init(ctx, log) {
this.log = log; this.log = log;
initialize(ctx); initialize(ctx);
} }
name = 'lights'; name = 'lights';
whitelist = true; whitelist = true;
func(msg, args, ctx) { func(msg, args, ctx) {
if (ctx.sleep) { if (ctx.sleep) {
msg.channel.createMessage('i have sleep mode enabled. the lights are probably off.'); msg.channel.createMessage('i have sleep mode enabled. the lights are probably off.');
return; return;
} }
if (!args.length) { if (!args.length) {
msg.channel.createMessage('no args found.'); msg.channel.createMessage('no args found.');
return; return;
} }
let instructions = parse(args[0]); let instructions = parse(args[0]);
this.log.debug(instructions); this.log.debug(instructions);
let res = '```\n'; let res = '```\n';
instructions.forEach((instruction) => { instructions.forEach((instruction) => {
res += JSON.stringify(instruction) + '\n'; res += JSON.stringify(instruction) + '\n';
}); });
res += '```'; res += '```';
msg.channel.createMessage(`parsed instructions:\n${res}`); msg.channel.createMessage(`parsed instructions:\n${res}`);
req( req(
instructions.filter((i) => i.valid), instructions.filter((i) => i.valid),
(response) => { (response) => {
msg.channel.createMessage(`${response}`); msg.channel.createMessage(`${response}`);
}, },
(error) => { discover,
msg.channel.createMessage(`error: ${error.message}`); (error) => {
} msg.channel.createMessage(`error: ${error.message}`);
); }
} );
}
} }
initializer.addCommand(new LightsParser()); initializer.addCommand(new LightsParser());
class Sleep extends Command { class Sleep extends Command {
name = 'sleep'; name = 'sleep';
whitelist = true; whitelist = true;
func(msg, args, ctx) { func(msg, args, ctx) {
let sleep = ctx.sleep; let sleep = ctx.sleep;
sleep = !sleep; sleep = !sleep;
msg.channel.createMessage(`sleep mode is now ${sleep ? 'on' : 'off'}`); msg.channel.createMessage(`sleep mode is now ${sleep ? 'on' : 'off'}`);
ctx.set_ctx('sleep', sleep); ctx.set_ctx('sleep', sleep);
} }
} }
initializer.addCommand(new Sleep()); initializer.addCommand(new Sleep());

View File

@ -1,7 +1,7 @@
import Logger, { levels } from '../logger.js'; import Logger, { levels } from '../logger.js';
import { filename } from '../utils.js'; import { filename } from '../utils.js';
const log = new Logger(filename(import.meta.url), global.ctx.log_level); const log = new Logger(filename(import.meta.url), "DEBUG");
class Target { class Target {
constructor(channel) { constructor(channel) {
@ -58,17 +58,6 @@ class Instruction {
} }
export const instructions = [ export const instructions = [
{ n: 'CONSTANT', a: true },
{ n: 'ADD', a: true },
{ n: 'SUBTRACT', a: true },
{ n: 'MULTIPLY', a: true },
{ n: 'DIVIDE', a: true },
{ n: 'MODULO', a: true },
{ n: 'FADE', a: true },
{ n: 'RANDOM', a: false },
{ n: 'JMP', a: false },
{ n: 'JNZ', a: true },
{ n: 'JEZ', a: true },
]; ];
export function initialize(ctx) { export function initialize(ctx) {
@ -156,6 +145,18 @@ function parseSingleInstruction(str = '') {
return item; return item;
} }
export function discover(data) {
for (let value of data) {
if (value.n != undefined) {
let found = instructions.filter((val) => { return val.n == value.n });
if (!found.length) {
log.debug(`discovered new keyword ${value.n}`);
instructions.push(value);
}
}
}
}
export default function parse(str) { export default function parse(str) {
let parsed = []; let parsed = [];
let split = str.split('\n').filter((s) => s.length > 0); let split = str.split('\n').filter((s) => s.length > 0);

View File

@ -7,7 +7,22 @@ function getBinarySize(string) {
return Buffer.byteLength(string, 'utf8'); return Buffer.byteLength(string, 'utf8');
} }
export default function req(data, callback, errorCallback) { export function contactServer(callback, errorCallback) {
let client = new net.Socket();
let c_port = global.ctx.lights.port || port;
let c_addr = global.ctx.lights.addr || hostname;
client.connect(c_port, c_addr, () => {
});
client.on('data', (dat) => {
let arr = JSON.parse(dat);
callback(arr);
client.destroy();
})
}
export default function req(data, callback, newFuncCallback, errorCallback) {
let string_data = JSON.stringify(data); let string_data = JSON.stringify(data);
let size = getBinarySize(string_data); let size = getBinarySize(string_data);
if (size > 9999) { if (size > 9999) {
@ -19,11 +34,15 @@ export default function req(data, callback, errorCallback) {
let c_port = global.ctx.lights.port || port; let c_port = global.ctx.lights.port || port;
let c_addr = global.ctx.lights.addr || hostname; let c_addr = global.ctx.lights.addr || hostname;
client.connect(c_port, c_addr, () => { client.connect(c_port, c_addr, () => { });
client.on('data', (dat) => {
let arr = JSON.parse(dat);
newFuncCallback(arr);
client.write(string_data); client.write(string_data);
client.destroy(); client.destroy();
callback('success.'); callback('success.');
}); })
client.on('error', (e) => { client.on('error', (e) => {
client.destroy(); client.destroy();

198
parser.js
View File

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

View File

@ -1 +1 @@
{"guild":["656579275008245830","754155880173404260"],"user":["123601647258697730","240240073386229760","285424490916216832","529534860243632134"]} {"guild":["656579275008245830","754155880173404260","805978396974514206"],"user":["123601647258697730","240240073386229760","285424490916216832","529534860243632134"]}