new format args

This commit is contained in:
jane 2021-05-26 20:18:11 -04:00
parent 0e827d1c85
commit 1e30598bc4
4 changed files with 212 additions and 218 deletions

104
bot.js
View file

@ -10,7 +10,7 @@ import fs from 'fs';
const cfg = require('./config.json');
if (!fs.existsSync('./whitelist.json')) {
fs.writeFileSync('./whitelist.json', '{}');
fs.writeFileSync('./whitelist.json', '{}');
}
const whitelist = require('./whitelist.json');
@ -19,45 +19,49 @@ const dir = dirname(import.meta.url);
const bot = new Eris(cfg.token);
global.ctx = {
bot: bot,
log_level: levels[cfg.log_level.toUpperCase()] || levels.WARN,
set_ctx: (key, value) => {
global.ctx[key] = value;
},
bot: bot,
log_level: levels[cfg.log_level.toUpperCase()] || levels.WARN,
set_ctx: (key, value) => {
global.ctx[key] = value;
},
lights: {
port: cfg.lights_port,
addr: cfg.lights_address
}
};
const log = new Logger(filename(import.meta.url), global.ctx.log_level);
const parse = new CommandParser(global.ctx, cfg.prefix || undefined);
const checkUser = (user) => {
if (cfg.user_whitelist.includes(user.id) || (whitelist.user && whitelist.user.includes(user.id))) {
return true;
}
log.info(`user not on whitelist: ${user.username}`);
return false;
if (cfg.user_whitelist.includes(user.id) || (whitelist.user && whitelist.user.includes(user.id))) {
return true;
}
log.info(`user not on whitelist: ${user.username}`);
return false;
};
const checkGuild = (guild) => {
if (cfg.whitelist.includes(guild.id) || (whitelist.guild && whitelist.guild.includes(guild.id))) {
return true;
}
log.info(`guild not on whitelist: ${guild.name}`);
return false;
if (cfg.whitelist.includes(guild.id) || (whitelist.guild && whitelist.guild.includes(guild.id))) {
return true;
}
log.info(`guild not on whitelist: ${guild.name}`);
return false;
};
const saveWhitelist = () => {
let data = JSON.stringify(whitelist);
fs.writeFileSync('./whitelist.json', data);
let data = JSON.stringify(whitelist);
fs.writeFileSync('./whitelist.json', data);
};
global.ctx.whitelist = {
guild: checkGuild,
user: checkUser,
save: saveWhitelist,
wl: whitelist,
guild: checkGuild,
user: checkUser,
save: saveWhitelist,
wl: whitelist,
};
bot.on('ready', () => {
log.info('ready recieved.');
bot.guilds.forEach((guild) => checkGuild(guild));
log.info('ready recieved.');
bot.guilds.forEach((guild) => checkGuild(guild));
});
bot.on('messageCreate', (msg) => parse.parseMsg(msg, global.ctx));
@ -67,32 +71,32 @@ bot.on('error', (err) => log.error(err.toString()));
bot.connect();
async function load_commands() {
for (let file of files) {
let p = path.join(cmd_dir, file);
log.debug(p);
let obj;
try {
obj = await import('file:////' + p);
} catch (e) {
log.warn(`loading file ${file}, ran into issue: ${e.stack}`);
continue;
}
if (obj.default != undefined) {
if (obj.default.constructor.name == 'CommandInitializer') {
obj.default.initialize(global.ctx);
let cmds = obj.default.getCommands();
if (parse.isCmd(cmds)) {
parse.addCommand(cmds);
} else if (cmds.constructor.name == 'Array') {
for (let cmd of cmds) {
parse.addCommand(cmd);
}
}
}
} else {
log.warn('module ' + file + ' returned an undefined module.');
}
}
for (let file of files) {
let p = path.join(cmd_dir, file);
log.debug(p);
let obj;
try {
obj = await import('file:////' + p);
} catch (e) {
log.warn(`loading file ${file}, ran into issue: ${e.stack}`);
continue;
}
if (obj.default != undefined) {
if (obj.default.constructor.name == 'CommandInitializer') {
obj.default.initialize(global.ctx);
let cmds = obj.default.getCommands();
if (parse.isCmd(cmds)) {
parse.addCommand(cmds);
} else if (cmds.constructor.name == 'Array') {
for (let cmd of cmds) {
parse.addCommand(cmd);
}
}
}
} else {
log.warn('module ' + file + ' returned an undefined module.');
}
}
}
let cmd_dir = path.join(dir, 'cmd');

View file

@ -4,156 +4,165 @@ import { filename } from '../utils.js';
const log = new Logger(filename(import.meta.url), global.ctx.log_level);
class Target {
constructor(channel) {
this.channel = channel;
}
channel;
value;
constructor(channel) {
this.channel = channel;
}
channel;
value;
}
const available_targets = {
r: new Target('r'),
g: new Target('g'),
b: new Target('b'),
stack: new Target('stack'),
stack2: new Target('stack2'),
stack3: new Target('stack3'),
stack4: new Target('stack4'),
stack5: new Target('stack5'),
stack6: new Target('stack6'),
stack6: new Target('stackr'),
stack6: new Target('stackg'),
stack6: new Target('stackb'),
tick: new Target('tick'),
index: new Target('index'),
r: new Target('r'),
g: new Target('g'),
b: new Target('b'),
stack: new Target('stack'),
stack2: new Target('stack2'),
stack3: new Target('stack3'),
stack4: new Target('stack4'),
stack5: new Target('stack5'),
stack6: new Target('stack6'),
stack6: new Target('stackr'),
stack6: new Target('stackg'),
stack6: new Target('stackb'),
tick: new Target('tick'),
index: new Target('index'),
};
class Instruction {
constructor(name, targets, args) {
let valid_targets = [];
targets.forEach((t) => {
if (t instanceof Target) {
let match = Object.keys(available_targets).find((key) => available_targets[key].channel === t.channel);
if (match) {
valid_targets.push(t);
}
}
});
this.name = name;
this.targets = valid_targets;
this.args = args;
}
name;
targets;
args;
constructor(name, targets, args) {
let valid_targets = [];
let matched_args = [];
targets.forEach((t, i) => {
if (t instanceof Target) {
let match = Object.keys(available_targets).find((key) => available_targets[key].channel === t.channel);
if (match) {
if (args[i]) {
matched_args.push({
...t,
arg: args[i]
})
}
else {
matched_args.push(t);
}
}
}
});
this.name = name;
this.targets = valid_targets;
this.args = matched_args;
}
name;
targets;
args;
}
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 },
{ 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) {
log.s(ctx.log_level);
log.s(ctx.log_level);
}
function parseSingleInstruction(str = '') {
let item = {
valid: false,
instruction: undefined,
errors: undefined,
};
let split = str.split(' ');
let cmd = split[0];
log.debug(cmd);
let match = instructions.filter((i) => i.n == cmd.toUpperCase());
log.debug(match);
split = split.slice(1);
if (match.length) {
let inst_targets = [];
let inst_args = [];
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;
}
}
inst_targets = parsed_args[0]
.split(',')
.map((s) => s.trim())
.map((t) => new Target(t));
let item = {
valid: false,
instruction: undefined,
errors: undefined,
};
let split = str.split(' ');
let cmd = split[0];
log.debug(cmd);
let match = instructions.filter((i) => i.n == cmd.toUpperCase());
log.debug(match);
split = split.slice(1);
if (match.length) {
let inst_targets = [];
let inst_args = [];
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;
}
}
inst_targets = parsed_args[0]
.split(',')
.map((s) => s.trim())
.map((t) => new Target(t));
if (!inst_targets.length) {
item.errors = 'No valid targets.';
}
inst_targets.forEach((t) => {
let match = Object.keys(available_targets).find((key) => available_targets[key].channel === t.channel);
if (!match) {
item.errors = `Invalid target: ${t.channel}`;
}
});
if (match[0].a) {
if (parsed_args.length < 2) {
item.errors = 'Not enough arguments.';
return item;
}
inst_args = parsed_args[1]
.split(',')
.map((s) => s.trim())
.map((s) => (available_targets[s] ? s : parseInt(s)));
if (!inst_args.length) {
item.errors = 'No valid args.';
}
inst_args.forEach((arg) => {
if (arg === NaN) {
item.errors = 'An argument is null or undefined.';
}
});
}
if (item.errors) {
return item;
}
if (!inst_targets.length) {
item.errors = 'No valid targets.';
}
inst_targets.forEach((t) => {
let match = Object.keys(available_targets).find((key) => available_targets[key].channel === t.channel);
if (!match) {
item.errors = `Invalid target: ${t.channel}`;
}
});
if (match[0].a) {
if (parsed_args.length < 2) {
item.errors = 'Not enough arguments.';
return item;
}
inst_args = parsed_args[1]
.split(',')
.map((s) => s.trim())
.map((s) => (available_targets[s] ? s : parseInt(s)));
if (!inst_args.length) {
item.errors = 'No valid args.';
}
inst_args.forEach((arg) => {
if (arg === NaN) {
item.errors = 'An argument is null or undefined.';
}
});
}
if (item.errors) {
return item;
}
item.instruction = new Instruction(match[0].n, inst_targets, inst_args || []);
} else {
item.errors = 'No command matched.';
return item;
}
item.valid = true;
return item;
item.instruction = new Instruction(match[0].n, inst_targets, inst_args || []);
} else {
item.errors = 'No command matched.';
return item;
}
item.valid = true;
return item;
}
export default function parse(str) {
let parsed = [];
let split = str.split('\n').filter((s) => s.length > 0);
split.forEach((item) => {
let parsedItem = parseSingleInstruction(item);
parsed.push(parsedItem);
log.debug(item);
});
return parsed;
let parsed = [];
let split = str.split('\n').filter((s) => s.length > 0);
split.forEach((item) => {
let parsedItem = parseSingleInstruction(item);
parsed.push(parsedItem);
log.debug(item);
});
return parsed;
}

View file

@ -4,26 +4,29 @@ const hostname = '192.168.1.219';
const port = 29999;
function getBinarySize(string) {
return Buffer.byteLength(string, 'utf8');
return Buffer.byteLength(string, 'utf8');
}
export default function req(data, callback, errorCallback) {
let string_data = JSON.stringify(data);
let size = getBinarySize(string_data);
let string_data = JSON.stringify(data);
let size = getBinarySize(string_data);
if (size > 9999) {
errorCallback("too long");
return;
}
let client = new net.Socket();
client.connect(port, hostname, () => {
client.write(string_data);
client.destroy();
callback('success.');
});
let client = new net.Socket();
client.on('error', (e) => {
client.destroy();
errorCallback(e);
});
let c_port = global.ctx.lights.port || port;
let c_addr = global.ctx.lights.addr || hostname;
client.connect(c_port, c_addr, () => {
client.write(string_data);
client.destroy();
callback('success.');
});
client.on('error', (e) => {
client.destroy();
errorCallback(e);
});
}

View file

@ -1,7 +1,6 @@
dependencies:
eris: 0.14.0
socket.engine: 1.0.0
lockfileVersion: 5.1
lockfileVersion: 5.2
packages:
/eris/0.14.0:
dependencies:
@ -14,31 +13,11 @@ packages:
tweetnacl: 1.0.3
resolution:
integrity: sha512-/W6X0SFR2swtA9oc4ga5Wh1TQcZtPgbUaDDdwYc67fvFUAtwC+V1xzWUZq2yDeJnTfB8Uot9SJWA8Lthe2sDtQ==
/fs/0.0.1-security:
dev: false
resolution:
integrity: sha1-invTcYa23d84E/I4WLV+yq9eQdQ=
/ip/1.1.5:
dev: false
resolution:
integrity: sha1-vd7XARQpCCjAoDnnLvJfWq7ENUo=
/net/1.0.2:
dev: false
resolution:
integrity: sha1-0XV+yaf7I3HYPPR1XOPifhCCk4g=
/opusscript/0.0.7:
dev: false
optional: true
resolution:
integrity: sha512-DcBadTdYTUuH9zQtepsLjQn4Ll6rs3dmeFvN+SD0ThPnxRBRm/WC1zXWPg+wgAJimB784gdZvUMA57gDP7FdVg==
/socket.engine/1.0.0:
dependencies:
fs: 0.0.1-security
ip: 1.1.5
net: 1.0.2
dev: false
resolution:
integrity: sha512-vwc9JVBNe33686TBl9T3Ro53FaF09z11NVnrf0HIlYUOIDaZ1OFA1J1O6igU57qhP3NyUv4a+kZtgMm6SnziaQ==
/tweetnacl/1.0.3:
dev: false
optional: true
@ -60,4 +39,3 @@ packages:
integrity: sha512-D3RuNkynyHmEJIpD2qrgVkc9DQ23OrN/moAwZX4L8DfvszsJxpjQuUq3LMx6HoYji9fbIOBY18XWBsAux1ZZUA==
specifiers:
eris: ^0.14.0
socket.engine: ^1.0.0