Compare commits

..

No commits in common. "aded1e4193a9a49a2a11a9be64ea5cdbf3cf98e4" and "72c4622091639edd84d2c0fae14a736ba17fb759" have entirely different histories.

6 changed files with 513 additions and 525 deletions

16
.gitattributes vendored
View File

@ -1,16 +0,0 @@
# See this article for reference: https://help.github.com/articles/dealing-with-line-endings/
# Refreshing repo after line ending change:
# https://help.github.com/articles/dealing-with-line-endings/#refreshing-a-repository-after-changing-line-endings
# Handle line endings automatically for files detected as text
# and leave all files detected as binary untouched.
* text=auto
#
# The above will handle all files NOT found below
#
# These files are text and should be normalized (Convert crlf => lf)
# Use lf as eol for these files
*.js text eol=lf
*.ts text eol=lf
*.json text eol=lf

60
.gitignore vendored
View File

@ -1,31 +1,31 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies # dependencies
/node_modules /node_modules
/.pnp /.pnp
.pnp.js .pnp.js
# testing # testing
/coverage /coverage
# production # production
/build /build
/data /data
# misc # misc
.DS_Store .DS_Store
.env .env
.env.local .env.local
.env.development.local .env.development.local
.env.test.local .env.test.local
.env.production.local .env.production.local
/lib/**/*.old /lib/**/*.old
/lib/**/*.bak /lib/**/*.bak
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*
yarn-error.log* yarn-error.log*
# Editor # Editor
*.swp *.swp
*.swo *.swo

View File

@ -88,6 +88,7 @@ fs.watch('./lib/plugins', reloadplugin)
cfg.bot = bot cfg.bot = bot
// TODO better name, or switch to array // TODO better name, or switch to array
cfg.botAddressPrefix = '!' cfg.botAddressPrefix = '!'
cfg.botAddressRegex = new RegExp(`^${bot.username} (${cfg.botAddressPrefix}.+)`)
cfg.quiet = true cfg.quiet = true
@ -109,7 +110,6 @@ bot.once("spawn", () => {
} }
cfg.plugins = plugins cfg.plugins = plugins
cfg.botAddressRegex = new RegExp(`^${bot.username} (${cfg.botAddressPrefix}.+)`)
for (const plugin of Object.values(plugins)) { for (const plugin of Object.values(plugins)) {
try { try {

View File

@ -30,10 +30,11 @@ const events = {
whisper: function command_whisper(username, message) { whisper: function command_whisper(username, message) {
if ([bot.username, "me"].includes(username)) return if ([bot.username, "me"].includes(username)) return
if (/^gossip/.test(message)) return if (/^gossip/.test(message)) return
// if (/^!/.test(message) && username === cfg.admin){
if (username === cfg.admin) { if (username === cfg.admin) {
message = message.replace("\\", "@") message = message.replace("\\", "@")
console.info("whispered command", message) console.info("whispered command", message)
if (message.startsWith(cfg.botAddressPrefix)) { if (/^!/.test(message)) {
command(username, message) command(username, message)
} else { } else {
bot.chat(message) bot.chat(message)
@ -296,7 +297,7 @@ function command(username, message) {
switch (message_parts[1]) { switch (message_parts[1]) {
case "me": case "me":
if (player) { if (player) {
bot.lookAt(player.position.offset(0, 1, 0)) bot.lookAt((new v.Vec3(0, 1, 0)).add(player.position))
} else { } else {
cfg.quiet || bot.chat("can't see you") cfg.quiet || bot.chat("can't see you")
} }
@ -313,7 +314,7 @@ function command(username, message) {
break break
default: default:
const aPlayer = bot.players[message_parts[2]] ? bot.players[message_parts[2]].entity : null const aPlayer = bot.players[message_parts[2]] ? bot.players[message_parts[2]].entity : null
if (aPlayer) bot.lookAt(aPlayer.position.offset(0, 1, 0)) if (aPlayer) bot.lookAt((new v.Vec3(0, 1, 0)).add(aPlayer.position))
break; break;
} }
break break
@ -474,7 +475,7 @@ function command(username, message) {
case "howdy": case "howdy":
case "heyo": case "heyo":
case "yo": case "yo":
if (player) bot.lookAt(player.position.offset(0, 1, 0)) if (player) bot.lookAt((new v.Vec3(0, 1, 0)).add(player.position))
// TODO sneak // TODO sneak
// function swingArm() { // function swingArm() {

View File

@ -71,7 +71,9 @@ function lookForMobs() {
bot.pvp.attack(entityEnemy) bot.pvp.attack(entityEnemy)
} else if (entityEnemy) { } else if (entityEnemy) {
bot.lookAt( bot.lookAt(
// (new v.Vec3(0, 1, 0)).add(
entityEnemy.position entityEnemy.position
// )
) )
cfg.quiet || bot.chat("AH! A creeper! They creep me out!") cfg.quiet || bot.chat("AH! A creeper! They creep me out!")
} }

View File

@ -1,475 +1,476 @@
// import { createMachine, interpret, InterpreterStatus } from "xstate"; // import { createMachine, interpret, InterpreterStatus } from "xstate";
const { createMachine, interpret, InterpreterStatus } = require('xstate'); const { createMachine, interpret, InterpreterStatus } = require('xstate');
// import { access, mkdir, writeFile, readFile } from "fs"; // import { access, mkdir, writeFile, readFile } from "fs";
const { access, mkdir, writeFile, readFile } = require('fs'); const { access, mkdir, writeFile, readFile } = require('fs');
// ANGRAM_PREFIX='MINECRAFT' const v = require('vec3'); // for look dummy action, maybe not needed in future
const { MINECRAFT_DATA_FOLDER } = process.env || require("dotenv-packed").parseEnv().parsed; // ANGRAM_PREFIX='MINECRAFT'
const storage_dir = MINECRAFT_DATA_FOLDER || './data/' + "/sm/"; const { MINECRAFT_DATA_FOLDER } = process.env || require("dotenv-packed").parseEnv().parsed;
// import { createBot } from "mineflayer" const storage_dir = MINECRAFT_DATA_FOLDER || './data/' + "/sm/";
// let { pathfinder, Movements, goals } = require('mineflayer-pathfinder') // import { createBot } from "mineflayer"
// let cfg // let { pathfinder, Movements, goals } = require('mineflayer-pathfinder')
// let bot = createBot({ username: 'statebot' }) // let cfg
let bot; // let bot = createBot({ username: 'statebot' })
let quiet; let bot;
let updateRate = 20; let quiet;
const machines = { let updateRate = 20;
list: {}, const machines = {
running: {}, list: {},
}; running: {},
let webserver; };
let cfg = { let webserver;
statemachine: { let cfg = {
webserver: null, statemachine: {
// quiet: true, webserver: null,
quiet: quiet, // quiet: true,
list: {}, quiet: quiet,
running: {}, list: {},
draft: null, running: {},
recent: null, draft: null,
// debug: null, recent: null,
debug: true, // debug: null,
updateRate: updateRate debug: true,
} updateRate: updateRate
// FIXME temp variables to satisfy typescript autocomplete }
// , quiet: null // FIXME temp variables to satisfy typescript autocomplete
, // , quiet: null
bot: bot, ,
plugins: { statemachine: null } bot: bot,
}; plugins: { statemachine: null }
// Edit your machine(s) here };
function init(smName = "dummy", webserver) { // Edit your machine(s) here
access(storage_dir, err => { function init(smName = "dummy", webserver) {
if (err?.code === 'ENOENT') { access(storage_dir, err => {
mkdir(storage_dir, e => e && console.warn("sm init: create dir", e)); if (err?.code === 'ENOENT') {
} mkdir(storage_dir, e => e && console.warn("sm init: create dir", e));
else if (err) { }
console.warn("sm init: create dir", err); else if (err) {
} console.warn("sm init: create dir", err);
}); }
// const machine = newSM(smName) });
// machine.states.idle.on.TOGGLE = "start" // const machine = newSM(smName)
// machine.states.start.on.TOGGLE = "idle" // machine.states.idle.on.TOGGLE = "start"
const machine = createMachine({ // machine.states.start.on.TOGGLE = "idle"
id: smName, const machine = createMachine({
initial: "idle", id: smName,
states: { initial: "idle",
idle: { states: {
on: { TOGGLE: "start", NEXT: "start", PREV: "look", STOP: "finish" } idle: {
}, on: { TOGGLE: "start", NEXT: "start", PREV: "look", STOP: "finish" }
start: { },
on: { TOGGLE: "look", NEXT: "look", PREV: "idle" }, start: {
entry: 'lookAtPlayerOnce', on: { TOGGLE: "look", NEXT: "look", PREV: "idle" },
}, entry: 'lookAtPlayerOnce',
look: { },
on: { TOGGLE: "idle", NEXT: "idle", PREV: "start" }, look: {
// entry: ['look', 'blah'] on: { TOGGLE: "idle", NEXT: "idle", PREV: "start" },
// entry: 'lookAtPlayerOnce', // entry: ['look', 'blah']
activities: 'lookAtPlayer', // entry: 'lookAtPlayerOnce',
meta: { debug: true } activities: 'lookAtPlayer',
}, meta: { debug: true }
finish: { },
type: 'final' finish: {
}, type: 'final'
}, },
on: { START: '.start', STOP: '.idle' }, },
meta: { debug: true }, on: { START: '.start', STOP: '.idle' },
context: { player: null, rate: updateRate }, meta: { debug: true },
}, { context: { player: null, rate: updateRate },
actions: { }, {
// action implementation actions: {
lookAtPlayerOnce: (context, event) => { // action implementation
const player = context?.player || bot.nearestEntity(entity => entity.type === 'player'); lookAtPlayerOnce: (context, event) => {
if (player.position || player.entity) { const player = context?.player || bot.nearestEntity(entity => entity.type === 'player');
context.player = player; if (player.position || player.entity) {
bot.lookAt((player.entity || player).position.offset(0, 1, 0)); context.player = player;
} bot.lookAt((new v.Vec3(0, 1, 0)).add((player.entity || player).position));
} }
}, }
activities: { },
lookAtPlayer: (context, event) => { activities: {
const player = context?.player || bot.nearestEntity(entity => entity.type === 'player'); lookAtPlayer: (context, event) => {
// TODO check every event? const player = context?.player || bot.nearestEntity(entity => entity.type === 'player');
if (player.position || player.entity) { // TODO check every event?
context.player = player; if (player.position || player.entity) {
function looks() { context.player = player;
bot.lookAt((player.entity || player).position.offset(0, 1, 0)); function looks() {
} bot.lookAt((new v.Vec3(0, 1, 0)).add((player.entity || player).position));
bot.on("time", looks); }
return () => bot.off("time", looks); bot.on("time", looks);
} return () => bot.off("time", looks);
} }
}, }
delays: { },
/* ... */ delays: {
}, /* ... */
guards: { },
/* ... */ guards: {
}, /* ... */
services: { },
/* ... */ services: {
} /* ... */
}); }
console.log("sm init: machine", machine); });
const service = runSM(saveSM(machine)); console.log("sm init: machine", machine);
if (service?.send) { const service = runSM(saveSM(machine));
setTimeout(service.send, 200, "TOGGLE"); if (service?.send) {
// setTimeout(service.send, 400, "TOGGLE") setTimeout(service.send, 200, "TOGGLE");
} // setTimeout(service.send, 400, "TOGGLE")
else { }
console.warn("sm init: service", service); else {
} console.warn("sm init: service", service);
} }
function newSM(smName = "sm_" + Object.keys(cfg.statemachine.list).length) { }
smName = smName.replace(/\s+/, '_'); function newSM(smName = "sm_" + Object.keys(cfg.statemachine.list).length) {
if (cfg.statemachine.list[smName]) { smName = smName.replace(/\s+/, '_');
console.warn("sm exists", smName); if (cfg.statemachine.list[smName]) {
quiet || bot.chat(`sm ${smName} already exists, edit or use another name instead`); console.warn("sm exists", smName);
return; quiet || bot.chat(`sm ${smName} already exists, edit or use another name instead`);
} return;
const machine = createMachine({ }
id: smName, const machine = createMachine({
initial: "start", id: smName,
// TODO use history states for PAUSE and RESUME initial: "start",
states: { idle: { on: { START: "start" } }, start: { on: { STOP: "idle" } } } // TODO use history states for PAUSE and RESUME
}); states: { idle: { on: { START: "start" } }, start: { on: { STOP: "idle" } } }
cfg.statemachine.draft = machine; });
return machine; cfg.statemachine.draft = machine;
} return machine;
function saveSM(machine = cfg.statemachine.draft) { }
if (!machine?.id) { function saveSM(machine = cfg.statemachine.draft) {
console.warn("sm save: invalid", machine); if (!machine?.id) {
quiet || bot.chat("sm: couldn't save, invalid"); console.warn("sm save: invalid", machine);
return; quiet || bot.chat("sm: couldn't save, invalid");
} return;
// TODO do tests and validation }
// 1. ensure default states [start, idle] // TODO do tests and validation
// 2. ensure closed cycle from start to idle // 1. ensure default states [start, idle]
cfg.statemachine.list[machine.id] = machine; // 2. ensure closed cycle from start to idle
if (machine.id === cfg.statemachine.draft?.id) { cfg.statemachine.list[machine.id] = machine;
cfg.statemachine.draft = null; if (machine.id === cfg.statemachine.draft?.id) {
} cfg.statemachine.draft = null;
writeFile( }
// TODO writeFile(
// `${storage_dir}/${player}/${machine.id}.json` // TODO
`${storage_dir}/${machine.id}.json`, // `${storage_dir}/${player}/${machine.id}.json`
// TODO decide which data to store `${storage_dir}/${machine.id}.json`,
// https://xstate.js.org/docs/guides/states.html#persisting-state // TODO decide which data to store
// JSON.stringify(machine.toJSON), // https://xstate.js.org/docs/guides/states.html#persisting-state
// JSON.stringify(machine.states.toJSON), // + activities, delays, etc // JSON.stringify(machine.toJSON),
JSON.stringify({ config: machine.config, context: machine.context }), e => e && console.log("sm load sm: write file", e)); // JSON.stringify(machine.states.toJSON), // + activities, delays, etc
// return run ? runSM(machine) : machine JSON.stringify({ config: machine.config, context: machine.context }), e => e && console.log("sm load sm: write file", e));
return machine; // return run ? runSM(machine) : machine
} return machine;
function loadSM(name, run = true) { }
//: StateMachine<any, any, any> { function loadSM(name, run = true) {
readFile( //: StateMachine<any, any, any> {
// readFileSync( readFile(
// TODO // readFileSync(
// `${storage_dir}/${player}/${machine.id}.json` // TODO
`${storage_dir}/${name}.json`, afterRead // `${storage_dir}/${player}/${machine.id}.json`
// JSON.stringify(machine.toJSON), `${storage_dir}/${name}.json`, afterRead
); // JSON.stringify(machine.toJSON),
function afterRead(err, jsonString) { );
if (err) { function afterRead(err, jsonString) {
console.warn("sm load sm: read file", err); if (err) {
return; console.warn("sm load sm: read file", err);
} return;
else { }
const machine = createMachine(JSON.parse(jsonString).config); else {
// TODO do tests and validation const machine = createMachine(JSON.parse(jsonString).config);
// 1. ensure default states [start, idle] // TODO do tests and validation
// 2. ensure closed cycle from start to idle // 1. ensure default states [start, idle]
cfg.statemachine.list[machine.id] = machine; // 2. ensure closed cycle from start to idle
if (machine.id === cfg.statemachine.draft?.id) { cfg.statemachine.list[machine.id] = machine;
cfg.statemachine.draft = machine; if (machine.id === cfg.statemachine.draft?.id) {
} cfg.statemachine.draft = machine;
if (run) { }
runSM(machine); if (run) {
} runSM(machine);
} }
} }
// return run ? runSM(machine) : machine }
// return machine // return run ? runSM(machine) : machine
} // return machine
// function isInterpreter(SMorService: StateMachine<any, any, any> | Interpreter<any>): SMorService is Interpreter<any> { }
// return (SMorService as Interpreter<any>).start !== undefined; // function isInterpreter(SMorService: StateMachine<any, any, any> | Interpreter<any>): SMorService is Interpreter<any> {
// } // return (SMorService as Interpreter<any>).start !== undefined;
function getSM(name = cfg.statemachine.draft || cfg.statemachine.recent, asService = false, quiet = false) { // }
const machine = typeof name === "string" ? cfg.statemachine.list[name] function getSM(name = cfg.statemachine.draft || cfg.statemachine.recent, asService = false, quiet = false) {
: name; const machine = typeof name === "string" ? cfg.statemachine.list[name]
if (!machine) { : name;
console.warn("sm get: doesn't exist", name); if (!machine) {
cfg.statemachine.quiet || bot.chat(`sm ${name} doesn't exist`); console.warn("sm get: doesn't exist", name);
return; cfg.statemachine.quiet || bot.chat(`sm ${name} doesn't exist`);
} return;
if (asService) { }
const service = cfg.statemachine.running[machine?.id]; if (asService) {
if (!service) { const service = cfg.statemachine.running[machine?.id];
quiet || console.warn("sm get: already stopped", machine); if (!service) {
quiet || cfg.statemachine.quiet || bot.chat(`sm ${machine?.id} isn't running`); quiet || console.warn("sm get: already stopped", machine);
return interpret(machine); quiet || cfg.statemachine.quiet || bot.chat(`sm ${machine?.id} isn't running`);
} return interpret(machine);
return service; }
} return service;
else { }
// return machine.machine ? machine.machine : machine else {
return machine; // return machine.machine ? machine.machine : machine
} return machine;
} }
function runSM(name = getSM(undefined, undefined, true), player // or supervisor? }
, restart = false) { function runSM(name = getSM(undefined, undefined, true), player // or supervisor?
if (!name) , restart = false) {
return; if (!name)
const service = getSM(name, true, true); return;
if (!service) const service = getSM(name, true, true);
return; if (!service)
const machine = service.machine; return;
if (!machine) const machine = service.machine;
return; if (!machine)
switch (service.status) { return;
case InterpreterStatus.Running: switch (service.status) {
if (!restart) { case InterpreterStatus.Running:
console.warn("sm run: already running", service.id); if (!restart) {
quiet || bot.chat(`sm ${service.id} already running`); console.warn("sm run: already running", service.id);
return service; quiet || bot.chat(`sm ${service.id} already running`);
} return service;
stopSM(machine); }
case InterpreterStatus.NotStarted: stopSM(machine);
case InterpreterStatus.Stopped: case InterpreterStatus.NotStarted:
break; case InterpreterStatus.Stopped:
default: break;
console.warn("sm run: unknown status:", service.status, service); default:
return; console.warn("sm run: unknown status:", service.status, service);
break; return;
} break;
if (cfg.statemachine.debug || machine.meta?.debug) { }
service.onTransition((state) => { if (cfg.statemachine.debug || machine.meta?.debug) {
quiet || bot.chat(`sm trans: ${machine.id}, ${state.value}`); service.onTransition((state) => {
quiet || state.meta?.debug && bot.chat(`sm next events: ${machine.id}, ${state.nextEvents}`); quiet || bot.chat(`sm trans: ${machine.id}, ${state.value}`);
console.log("sm debug: trans", state.value, state); quiet || state.meta?.debug && bot.chat(`sm next events: ${machine.id}, ${state.nextEvents}`);
}).onDone((done) => { console.log("sm debug: trans", state.value, state);
quiet || bot.chat(`sm done: ${machine.id}, ${done}`); }).onDone((done) => {
console.log("sm debug: done", done.data, done); quiet || bot.chat(`sm done: ${machine.id}, ${done}`);
}); console.log("sm debug: done", done.data, done);
} });
cfg.statemachine.running[machine.id] = service; }
cfg.statemachine.recent = machine; cfg.statemachine.running[machine.id] = service;
service.start(); cfg.statemachine.recent = machine;
// // TODO check if idle state is different (maybe?) service.start();
console.log("sm run", service.state.value === machine.initialState.value, service.state); // // TODO check if idle state is different (maybe?)
console.log("sm run", service.state !== machine.initialState, machine.initialState); console.log("sm run", service.state.value === machine.initialState.value, service.state);
// return machine console.log("sm run", service.state !== machine.initialState, machine.initialState);
return service; // return machine
} return service;
function stopSM(name = getSM(), quiet = false) { }
let service = getSM(name, true, quiet); function stopSM(name = getSM(), quiet = false) {
if (!service) let service = getSM(name, true, quiet);
return; if (!service)
const machine = service.machine; return;
switch (service.status) { const machine = service.machine;
case InterpreterStatus.NotStarted: switch (service.status) {
case InterpreterStatus.Stopped: case InterpreterStatus.NotStarted:
console.log("sm stop status", service.status, service.id, cfg.statemachine.running[service.id]); case InterpreterStatus.Stopped:
// TODO check if any bugs console.log("sm stop status", service.status, service.id, cfg.statemachine.running[service.id]);
case InterpreterStatus.Running: // TODO check if any bugs
break; case InterpreterStatus.Running:
default: break;
console.warn("sm stop: unknown status:", service.status); default:
break; console.warn("sm stop: unknown status:", service.status);
} break;
service?.stop?.(); }
cfg.statemachine.running[machine.id] = null; service?.stop?.();
delete cfg.statemachine.running[machine.id]; cfg.statemachine.running[machine.id] = null;
// return machine delete cfg.statemachine.running[machine.id];
return service; // return machine
} return service;
function actionSM(action, name = getSM()) { }
if (!action) { function actionSM(action, name = getSM()) {
return console.warn("sm action", action); if (!action) {
} return console.warn("sm action", action);
let service = getSM(name, true, true); }
if (service.status !== InterpreterStatus.Running) let service = getSM(name, true, true);
return; if (service.status !== InterpreterStatus.Running)
// const machine = service.machine return;
service.send(action.toLowerCase()); // const machine = service.machine
} service.send(action.toLowerCase());
function stepSM(command = "", ...message_parts) { }
let service = getSM(undefined, true); function stepSM(command = "", ...message_parts) {
if (!service) let service = getSM(undefined, true);
return; if (!service)
if (!service.send) { return;
console.warn("sm step: can't send", service.machine); if (!service.send) {
// TODO start a temporary service to interpret console.warn("sm step: can't send", service.machine);
quiet || bot.chat("sm: step doesn't support machines that aren't running yet"); // TODO start a temporary service to interpret
return; quiet || bot.chat("sm: step doesn't support machines that aren't running yet");
} return;
if (service?.status !== InterpreterStatus.Running) { }
console.warn("sm step: machine not running, attempting start", service); if (service?.status !== InterpreterStatus.Running) {
runSM; console.warn("sm step: machine not running, attempting start", service);
} runSM;
// const machine = service.machine }
switch (command) { // const machine = service.machine
case "edit": switch (command) {
// maybe `edit <type>`, like `add`? case "edit":
// where type: // maybe `edit <type>`, like `add`?
// context // where type:
// action // context
// timeout | all timeout // action
break; // timeout | all timeout
case "undo": break;
break; case "undo":
case "del": break;
break; case "del":
case "p": break;
case "prev": case "p":
service?.send("PREV"); case "prev":
break; service?.send("PREV");
case "add": break;
// maybe `add <type>`? case "add":
// where type: // maybe `add <type>`?
// context // where type:
// action // context
// timeout // action
case "new": // timeout
break; case "new":
// case "with": break;
// console.log(this) // case "with":
// stepSM(getSM(message_parts[0], true, true), ...message_parts.slice(1)) // console.log(this)
// break; // stepSM(getSM(message_parts[0], true, true), ...message_parts.slice(1))
case "help": // break;
quiet || bot.chat("![sm ]step [ p(rev) | n(ext) ]"); case "help":
break; quiet || bot.chat("![sm ]step [ p(rev) | n(ext) ]");
case "n": break;
case "next": case "n":
default: case "next":
service?.send("NEXT"); default:
quiet || bot.chat("stepped"); service?.send("NEXT");
break; quiet || bot.chat("stepped");
} break;
} }
function tickSM(time = bot.time.timeOfDay, rate = 20) { }
if (time % rate !== 0) { function tickSM(time = bot.time.timeOfDay, rate = 20) {
return; if (time % rate !== 0) {
} return;
console.log("sm tick", rate, time); }
} console.log("sm tick", rate, time);
function debugSM(name = getSM()) { }
if (!name) function debugSM(name = getSM()) {
return; if (!name)
let service = getSM(name, true); return;
if (!service) let service = getSM(name, true);
return; if (!service)
const machine = service.machine; return;
machine.meta.debug = !!!machine.meta.debug; const machine = service.machine;
console.info("sm debug", machine.meta, service, machine); machine.meta.debug = !!!machine.meta.debug;
cfg.statemachine.quiet || machine.meta.debug && bot.chat("sm debug: " + machine.id); console.info("sm debug", machine.meta, service, machine);
} cfg.statemachine.quiet || machine.meta.debug && bot.chat("sm debug: " + machine.id);
function command(message_parts) { }
const message_parts2 = message_parts.slice(1); function command(message_parts) {
switch (message_parts[0]) { const message_parts2 = message_parts.slice(1);
case "add": switch (message_parts[0]) {
command(["new"].concat(message_parts2)); case "add":
break; command(["new"].concat(message_parts2));
case "finish": break;
case "done": case "finish":
case "end": case "done":
command(["save"].concat(message_parts2)); case "end":
break; command(["save"].concat(message_parts2));
case "do": break;
case "load": case "do":
case "start": case "load":
command(["run"].concat(message_parts2)); case "start":
break; command(["run"].concat(message_parts2));
case "debug": break;
switch (message_parts[1]) { case "debug":
case "sm": switch (message_parts[1]) {
case "global": case "sm":
case "meta": case "global":
cfg.statemachine.debug = !!!cfg.statemachine.debug; case "meta":
quiet || bot.chat(`sm debug: ${cfg.statemachine.debug}`); cfg.statemachine.debug = !!!cfg.statemachine.debug;
break; quiet || bot.chat(`sm debug: ${cfg.statemachine.debug}`);
} break;
case "new": }
case "save": case "new":
case "run": case "save":
case "step": case "run":
case "stop": case "step":
// temp case "stop":
case "action": // temp
switch (message_parts2.length) { case "action":
case 0: switch (message_parts2.length) {
console.warn(`sm ${message_parts[0]}: no name, using defaults`); case 0:
case 1: console.warn(`sm ${message_parts[0]}: no name, using defaults`);
// FIXME `this` doesn't work always case 1:
(this.runSM && this || cfg.plugins.statemachine)[message_parts[0] + "SM"](...message_parts2); // FIXME `this` doesn't work always
break; (this.runSM && this || cfg.plugins.statemachine)[message_parts[0] + "SM"](...message_parts2);
default: break;
if (["action"].includes(message_parts[0])) { default:
(this.runSM && this || cfg.plugins.statemachine)[message_parts[0] + "SM"](...message_parts2); if (["action"].includes(message_parts[0])) {
} (this.runSM && this || cfg.plugins.statemachine)[message_parts[0] + "SM"](...message_parts2);
else { }
console.warn(`sm ${message_parts[0]}: more than 1 arg passed`, message_parts2); else {
} console.warn(`sm ${message_parts[0]}: more than 1 arg passed`, message_parts2);
break; }
} break;
break; }
case "undo": break;
break; case "undo":
case "list": break;
case "status": case "list":
// TODO current/recent, updateRate case "status":
const { list, running } = cfg.statemachine; // TODO current/recent, updateRate
console.log("sm list", running, list); const { list, running } = cfg.statemachine;
quiet || bot.chat(`${Object.keys(running).length} of ${Object.keys(list).length} active: ${Object.keys(running)}` console.log("sm list", running, list);
+ (message_parts[1] === "all" ? `${Object.keys(list)}` : '')); quiet || bot.chat(`${Object.keys(running).length} of ${Object.keys(list).length} active: ${Object.keys(running)}`
break; + (message_parts[1] === "all" ? `${Object.keys(list)}` : ''));
case "quiet": break;
quiet = cfg.statemachine.quiet = !!!cfg.statemachine.quiet; case "quiet":
quiet || bot.chat(`sm: ${cfg.statemachine.quiet ? "" : "not "}being quiet`); quiet = cfg.statemachine.quiet = !!!cfg.statemachine.quiet;
break; quiet || bot.chat(`sm: ${cfg.statemachine.quiet ? "" : "not "}being quiet`);
default: break;
// TODO general helper from declarative commands object default:
quiet || bot.chat(`sm help: !sm [new | step| save | run | list | quiet | debug]`); // TODO general helper from declarative commands object
console.warn("sm unknown command", message_parts); quiet || bot.chat(`sm help: !sm [new | step| save | run | list | quiet | debug]`);
break; console.warn("sm unknown command", message_parts);
} break;
return true; }
} return true;
function load(config) { }
webserver = cfg.statemachine.webserver = config.statemachine?.webserver || webserver; function load(config) {
config.statemachine = cfg.statemachine || { webserver = cfg.statemachine.webserver = config.statemachine?.webserver || webserver;
webserver: null, config.statemachine = cfg.statemachine || {
// quiet: true, webserver: null,
quiet: false, // quiet: true,
list: {}, quiet: false,
running: {}, list: {},
draft: null, running: {},
recent: null, draft: null,
// debug: null, recent: null,
debug: true, // debug: null,
updateRate: updateRate debug: true,
}; updateRate: updateRate
cfg = config; };
bot = cfg.bot; cfg = config;
// pathfinder = bot.pathfinder || bot.loadPlugin(require('mineflayer-pathfinder').pathfinder) bot = cfg.bot;
// mcData = bot.mcData || (bot.mcData = require('minecraft-data')(bot.version)) // pathfinder = bot.pathfinder || bot.loadPlugin(require('mineflayer-pathfinder').pathfinder)
init(undefined, webserver); // mcData = bot.mcData || (bot.mcData = require('minecraft-data')(bot.version))
updateRate = cfg.statemachine.updateRate || updateRate; init(undefined, webserver);
bot.on('time', tickSM); updateRate = cfg.statemachine.updateRate || updateRate;
// bot.once('time', tickSM, 5) bot.on('time', tickSM);
console.log("sm load", cfg.statemachine); // bot.once('time', tickSM, 5)
} console.log("sm load", cfg.statemachine);
function unload() { }
const { list, running } = cfg.statemachine; function unload() {
bot.off('time', tickSM); const { list, running } = cfg.statemachine;
Object.keys(running).forEach(sm => { bot.off('time', tickSM);
stopSM(sm); Object.keys(running).forEach(sm => {
}); stopSM(sm);
// delete cfg.statemachine; });
cfg.statemachine = null; // delete cfg.statemachine;
console.log("sm unload: deleted", cfg.statemachine); cfg.statemachine = null;
} console.log("sm unload: deleted", cfg.statemachine);
module.exports = { }
load, unload, command, init, module.exports = {
newSM, saveSM, loadSM, runSM, stopSM, actionSM, stepSM, debugSM load, unload, command, init,
newSM, saveSM, loadSM, runSM, stopSM, actionSM, stepSM, debugSM
}; };