Compare commits
54 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
feb0b0927a | ||
|
8276e68489 | ||
|
2b7163bef3 | ||
|
a0b4641f37 | ||
|
186d6ac3d2 | ||
|
984c9490c3 | ||
|
3379f75ab9 | ||
|
69b1ab0b0b | ||
|
3c9d62441f | ||
|
665102e19c | ||
|
db459f52e6 | ||
|
360eeff02f | ||
|
25faac2f4c | ||
|
ccf0c598e8 | ||
|
050e2b3bd9 | ||
|
e879d1f4ad | ||
|
df193da779 | ||
|
269d258763 | ||
|
cbb105fe49 | ||
|
356f83e39b | ||
|
5b3804893b | ||
|
9f6fea2423 | ||
|
3686bab167 | ||
|
e0c477a46f | ||
|
6046123074 | ||
|
ae1f7cf269 | ||
|
afd2e002df | ||
|
3c5ec6b360 | ||
|
b71728e503 | ||
|
d001280383 | ||
|
f50e388c39 | ||
|
135ce6567b | ||
|
e5803eee59 | ||
|
1b21fcb096 | ||
|
4b3e58ceb3 | ||
|
8e854a0a2f | ||
|
c42a3a2304 | ||
|
b453b7d6bd | ||
|
6b79f1fc60 | ||
|
6e1ef5aada | ||
|
e2ae7e5ad2 | ||
|
42138a421b | ||
|
aded1e4193 | ||
|
60394e38eb | ||
|
22490f7ec1 | ||
|
72c4622091 | ||
|
0757776d8b | ||
|
a0ffaf1654 | ||
|
1597acca72 | ||
|
1e82045221 | ||
|
33c4fc0c77 | ||
|
33c4233223 | ||
|
3f3ebbae10 | ||
|
fd0e1e1347 |
16
.gitattributes
vendored
Normal file
16
.gitattributes
vendored
Normal file
|
@ -0,0 +1,16 @@
|
||||||
|
# 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
|
59
.gitignore
vendored
59
.gitignore
vendored
|
@ -1,30 +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
|
||||||
# misc
|
|
||||||
.DS_Store
|
# misc
|
||||||
.env
|
.DS_Store
|
||||||
.env.local
|
.env
|
||||||
.env.development.local
|
.env.local
|
||||||
.env.test.local
|
.env.development.local
|
||||||
.env.production.local
|
.env.test.local
|
||||||
/lib/**/*.old
|
.env.production.local
|
||||||
/lib/**/*.bak
|
/lib/**/*.old
|
||||||
|
/lib/**/*.bak
|
||||||
npm-debug.log*
|
|
||||||
yarn-debug.log*
|
npm-debug.log*
|
||||||
yarn-error.log*
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
# Editor
|
|
||||||
*.swp
|
# Editor
|
||||||
|
*.swp
|
||||||
*.swo
|
*.swo
|
4
.vscode/settings.json
vendored
4
.vscode/settings.json
vendored
|
@ -3,6 +3,8 @@
|
||||||
"command",
|
"command",
|
||||||
"mover",
|
"mover",
|
||||||
"sleeper",
|
"sleeper",
|
||||||
"informer"
|
"informer",
|
||||||
|
"statemachine",
|
||||||
|
"builder"
|
||||||
]
|
]
|
||||||
}
|
}
|
56
lib/index.js
56
lib/index.js
|
@ -1,8 +1,8 @@
|
||||||
const env = require("dotenv-packed").parseEnv().parsed
|
const env = require("dotenv-packed").parseEnv().parsed
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
let cfg = {
|
const cfg = {
|
||||||
admin: "Applezaus",
|
admin: process.env.MINECRAFT_PLAYER_ADMIN || env.MINECRAFT_PLAYER_ADMIN || console.warn("main: bot admin user not provided"),
|
||||||
mods: ["Applezaus", "tanner6", "Angram42", "[WEB] Angram42", "[WEB] Applezaus"],
|
mods: process.env.MINECRAFT_PLAYER_MODS || env.MINECRAFT_PLAYER_MODS || [], // json array,
|
||||||
stateMachines: {}
|
stateMachines: {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -29,25 +29,28 @@ cfg.botOptions = options
|
||||||
|
|
||||||
let plugins = {}
|
let plugins = {}
|
||||||
|
|
||||||
function loadplugin(pluginname, pluginpath) {
|
function loadplugin(pluginname, pluginpath = './plugins/' + pluginname) {
|
||||||
try {
|
try {
|
||||||
plugins[pluginname] = require(pluginpath)
|
plugins[pluginname] = require(pluginpath)
|
||||||
plugins[pluginname].load(cfg)
|
plugins[pluginname].load(cfg)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error.code == 'MODULE_NOT_FOUND') {
|
if (error.code == 'MODULE_NOT_FOUND') {
|
||||||
console.warn('plugin not used:', pluginpath)
|
console.warn('plugin not used:', pluginpath)
|
||||||
|
} else if (plugins[pluginname] && !plugins[pluginname].load) {
|
||||||
|
unloadplugin(pluginname, pluginpath)
|
||||||
} else {
|
} else {
|
||||||
console.error(error)
|
console.error(error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function unloadplugin(pluginname, pluginpath) {
|
function unloadplugin(pluginname, pluginpath = './plugins/' + pluginname) {
|
||||||
pluginpath = pluginpath ? pluginpath : './plugins/' + pluginname
|
|
||||||
const plugin = require.resolve(pluginpath)
|
const plugin = require.resolve(pluginpath)
|
||||||
try {
|
try {
|
||||||
if (plugin && require.cache[plugin]) {
|
if (plugin && require.cache[plugin]) {
|
||||||
require.cache[plugin].exports.unload()
|
// `unload()` isn't exported sometimes,
|
||||||
|
// when plugin isn't properly loaded
|
||||||
|
require.cache[plugin].exports?.unload?.()
|
||||||
delete plugins[pluginname]
|
delete plugins[pluginname]
|
||||||
delete require.cache[plugin]
|
delete require.cache[plugin]
|
||||||
}
|
}
|
||||||
|
@ -56,20 +59,28 @@ function unloadplugin(pluginname, pluginpath) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
reloadplugin = (event, filename, pluginpath) => {
|
function reloadplugin(event, filename, pluginpath = './plugins/') {
|
||||||
if (!/\.js$/.test(filename)) { return }
|
if (!/\.js$/.test(filename)) { return }
|
||||||
|
filename = filename.replace("\\", "/") // windows
|
||||||
if (!cfg.fsTimeout) {
|
if (!cfg.fsTimeout) {
|
||||||
console.info(event, filename)
|
console.info(event, filename)
|
||||||
pluginpath = (pluginpath ? pluginpath : './plugins/') + filename
|
const fullpluginpath = pluginpath + filename
|
||||||
|
const pluginname = (filename.split(".js")[0]).replace(/\/.+/, "")
|
||||||
|
pluginpath = pluginpath + pluginname
|
||||||
|
const hassubplugin = fullpluginpath.replace(/\.js$/, "") !== pluginpath
|
||||||
const check = Object.keys(cfg.plugins)
|
const check = Object.keys(cfg.plugins)
|
||||||
console.info(`reload file:`, pluginpath)
|
console.info(`reload file: ./lib/${fullpluginpath}`)
|
||||||
const plugin = require.resolve(pluginpath)
|
const plugin = require.resolve(fullpluginpath)
|
||||||
if (plugin && require.cache[plugin]) {
|
if (plugin && require.cache[plugin]) {
|
||||||
// console.debug(Object.keys(cfg.plugins))
|
// console.debug(Object.keys(cfg.plugins))
|
||||||
unloadplugin(filename.split(".js")[0], pluginpath)
|
unloadplugin(pluginname)
|
||||||
console.assert(Object.keys(cfg.plugins).length == check.length - 1, "plugin not removed, potential memory leak")
|
console.assert(Object.keys(cfg.plugins).length == check.length - 1, "plugin not removed, potential memory leak")
|
||||||
|
if (hassubplugin) {
|
||||||
|
console.info("reload: also unloading sub")
|
||||||
|
unloadplugin(pluginname, fullpluginpath)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
loadplugin(filename.split(".js")[0], pluginpath)
|
loadplugin(pluginname)
|
||||||
if (Object.keys(cfg.plugins).length != check.length) {
|
if (Object.keys(cfg.plugins).length != check.length) {
|
||||||
// If left < right :
|
// If left < right :
|
||||||
// - new plugin that's not registered in cfg.plugins, so added
|
// - new plugin that's not registered in cfg.plugins, so added
|
||||||
|
@ -83,10 +94,11 @@ reloadplugin = (event, filename, pluginpath) => {
|
||||||
// console.log('file.js %s event', event)
|
// console.log('file.js %s event', event)
|
||||||
}
|
}
|
||||||
|
|
||||||
fs.watch('./lib/plugins', reloadplugin)
|
fs.watch('./lib/plugins', { recursive: true }, reloadplugin)
|
||||||
|
|
||||||
cfg.bot = bot
|
cfg.bot = bot
|
||||||
cfg.botAddress = new RegExp(`^${bot.username} (!.+)`)
|
// TODO better name, or switch to array
|
||||||
|
cfg.botAddressPrefix = '!'
|
||||||
cfg.quiet = true
|
cfg.quiet = true
|
||||||
|
|
||||||
|
|
||||||
|
@ -95,19 +107,23 @@ cfg.quiet = true
|
||||||
bot.once("spawn", () => {
|
bot.once("spawn", () => {
|
||||||
plugins = {
|
plugins = {
|
||||||
command: require('./plugins/command'),
|
command: require('./plugins/command'),
|
||||||
eater: require('./plugins/eater'),
|
|
||||||
inventory: require('./plugins/inventory'),
|
|
||||||
informer: require('./plugins/informer'),
|
informer: require('./plugins/informer'),
|
||||||
|
inventory: require('./plugins/inventory'),
|
||||||
finder: require('./plugins/finder'),
|
finder: require('./plugins/finder'),
|
||||||
sleeper: require('./plugins/sleeper'),
|
|
||||||
armor: require('./plugins/armor'),
|
|
||||||
mover: require('./plugins/mover'),
|
mover: require('./plugins/mover'),
|
||||||
|
sleeper: require('./plugins/sleeper'),
|
||||||
|
eater: require('./plugins/eater'),
|
||||||
|
armor: require('./plugins/armor'),
|
||||||
guard: require('./plugins/guard'),
|
guard: require('./plugins/guard'),
|
||||||
// miner: require('./plugins/miner.js'),
|
// miner: require('./plugins/miner.js'),
|
||||||
// statemachine: require('./plugins/statemachine'),
|
statemachine: require('./plugins/statemachine'),
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg.plugins = plugins
|
cfg.plugins = plugins
|
||||||
|
// cfg.botAddressPrefix = ${bot.username.substr(-2,2)}
|
||||||
|
cfg.botAddressRegex = new RegExp(`^${bot.username}:? (/|${cfg.botAddressPrefix}.+)`)
|
||||||
|
// FIXME leaks every load, so adding here instead of command.js to load only once
|
||||||
|
bot.addChatPattern("web", /\[WEB\] (\[.+\])?\s*([\w.]+): (.+)/, { parse: true })
|
||||||
|
|
||||||
for (const plugin of Object.values(plugins)) {
|
for (const plugin of Object.values(plugins)) {
|
||||||
try {
|
try {
|
||||||
|
|
|
@ -27,14 +27,13 @@ function checkItemExists(name) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const events = {
|
const events = {
|
||||||
whisper: function command_whisper(username, message) {
|
whisper: function command_whisper(username, _botusername, message, ...history) {
|
||||||
if ([bot.username, "me"].includes(username)) return
|
if ([bot.username, "me"].includes(username)) return // whisper back from server (afk msges, etc)
|
||||||
if (/^gossip/.test(message)) return
|
if (/^gossip/.test(message)) return
|
||||||
// if (/^!/.test(message) && username === cfg.admin){
|
|
||||||
if (username === cfg.admin) {
|
if (username === cfg.admin) {
|
||||||
|
console.info("whispered command", _botusername, message)
|
||||||
message = message.replace("\\", "@")
|
message = message.replace("\\", "@")
|
||||||
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)
|
||||||
|
@ -42,7 +41,7 @@ const events = {
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
bot.whisper(cfg.admin, `gossip ${username}: ${message}`)
|
bot.whisper(cfg.admin, `gossip ${username}: ${message}`)
|
||||||
console.info(username, "whispered", message)
|
console.info(username, "whispered", _botusername, message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
, chat: command
|
, chat: command
|
||||||
|
@ -57,11 +56,38 @@ const events = {
|
||||||
}, 15 * 60 * 1000, bot, cfg);
|
}, 15 * 60 * 1000, bot, cfg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// , message: systemMessage
|
||||||
|
, messagestr: function systemMessageStr(...args) { console.log("cmd msgstr:", ...args) }
|
||||||
|
, "chat:web": commandWeb
|
||||||
|
}
|
||||||
|
|
||||||
|
function systemMessage(...args) {
|
||||||
|
if (args[0]?.text) return
|
||||||
|
const metadata = (args[0]?.extra || args[0]?.with)?.map(v => v.text)
|
||||||
|
console.log(
|
||||||
|
"cmd msg:",
|
||||||
|
args[0]?.text || args[0]?.translate,
|
||||||
|
args[0]?.extra?.length || args[0]?.with?.length || Object.keys(args[0]?.json).length - 1,
|
||||||
|
metadata.length > 0 && metadata || args[0],
|
||||||
|
args.slice(1)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function commandWeb([[mode, username, message]]) {
|
||||||
|
// console.log("web msg:", mode, username, message)
|
||||||
|
message && command(username, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
function _clientSystemMessage(...args) {
|
||||||
|
console.log("cmd chat:", args[0]?.message, args[0]?.extra?.length, args[0]?.extra, args[0], args.slice(1))
|
||||||
}
|
}
|
||||||
|
|
||||||
const events_registered = []
|
const events_registered = []
|
||||||
|
|
||||||
function command(username, message) {
|
function command(username, message) {
|
||||||
|
// TODO better name, maybe an array?
|
||||||
|
cfg.botAddressPrefix = cfg.botAddressPrefix || "!"
|
||||||
|
|
||||||
function fuzzyRespond(responses, probability = 1, timeout = 1) {
|
function fuzzyRespond(responses, probability = 1, timeout = 1) {
|
||||||
if (Math.random() < probability) {
|
if (Math.random() < probability) {
|
||||||
const response = responses[Math.floor(Math.random() * responses.length)]
|
const response = responses[Math.floor(Math.random() * responses.length)]
|
||||||
|
@ -76,7 +102,7 @@ function command(username, message) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (username === bot.username && !message.startsWith("!")) return
|
if (username === bot.username && !message.startsWith(cfg.botAddressPrefix)) return
|
||||||
|
|
||||||
const player = bot.players[username] ? bot.players[username].entity : null
|
const player = bot.players[username] ? bot.players[username].entity : null
|
||||||
|
|
||||||
|
@ -88,11 +114,12 @@ function command(username, message) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
if (message.startsWith("!") || cfg.botAddress.test(message)) {
|
if (message.startsWith(cfg.botAddressPrefix) || cfg.botAddressRegex.test(message)) {
|
||||||
message = cfg.botAddress.test(message) ? cfg.botAddress.exec(message)[1] : message
|
message = cfg.botAddressRegex.test(message) ? cfg.botAddressRegex.exec(message)[1] : message
|
||||||
|
|
||||||
console.log(message)
|
console.log(message)
|
||||||
message = message.slice(1) // remove `!`
|
// remove `!`
|
||||||
|
message = message.startsWith(cfg.botAddressPrefix) ? message.slice(cfg.botAddressPrefix.length) : message
|
||||||
|
|
||||||
// TODO command dispatchEvent, for aliases
|
// TODO command dispatchEvent, for aliases
|
||||||
function subcommand(message) {
|
function subcommand(message) {
|
||||||
const message_parts = message.split(/\s+/)
|
const message_parts = message.split(/\s+/)
|
||||||
|
@ -293,7 +320,7 @@ function command(username, message) {
|
||||||
switch (message_parts[1]) {
|
switch (message_parts[1]) {
|
||||||
case "me":
|
case "me":
|
||||||
if (player) {
|
if (player) {
|
||||||
bot.lookAt((new v.Vec3(0, 1, 0)).add(player.position))
|
bot.lookAt(player.position.offset(0, 1, 0))
|
||||||
} else {
|
} else {
|
||||||
cfg.quiet || bot.chat("can't see you")
|
cfg.quiet || bot.chat("can't see you")
|
||||||
}
|
}
|
||||||
|
@ -310,7 +337,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((new v.Vec3(0, 1, 0)).add(aPlayer.position))
|
if (aPlayer) bot.lookAt(aPlayer.position.offset(0, 1, 0))
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
|
@ -327,7 +354,7 @@ function command(username, message) {
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
case "info":
|
case "info":
|
||||||
cfg.plugins.informer.command(message_parts.splice(1))
|
cfg.plugins.informer.command(message_parts.splice(1), player)
|
||||||
break
|
break
|
||||||
// case "use":
|
// case "use":
|
||||||
// bot.useOn(bot.nearestEntity())
|
// bot.useOn(bot.nearestEntity())
|
||||||
|
@ -404,6 +431,16 @@ function command(username, message) {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
case "sm":
|
||||||
|
case "step":
|
||||||
|
cfg.plugins.statemachine?.command?.(
|
||||||
|
message_parts[0] == "sm" ? message_parts.slice(1) : message_parts, player
|
||||||
|
)
|
||||||
|
// TODO refactor into plugin detection and command exec function
|
||||||
|
// safecommand(plugin_name, message_parts, player)
|
||||||
|
// message_parts includes command?
|
||||||
|
|| bot.chat("statemachine plugin not loaded")
|
||||||
|
break
|
||||||
case "location":
|
case "location":
|
||||||
// TODO put in /lib/location
|
// TODO put in /lib/location
|
||||||
switch (message_parts[1]) {
|
switch (message_parts[1]) {
|
||||||
|
@ -461,7 +498,7 @@ function command(username, message) {
|
||||||
case "howdy":
|
case "howdy":
|
||||||
case "heyo":
|
case "heyo":
|
||||||
case "yo":
|
case "yo":
|
||||||
if (player) bot.lookAt((new v.Vec3(0, 1, 0)).add(player.position))
|
if (player) bot.lookAt(player.position.offset(0, 1, 0))
|
||||||
|
|
||||||
// TODO sneak
|
// TODO sneak
|
||||||
// function swingArm() {
|
// function swingArm() {
|
||||||
|
@ -508,6 +545,8 @@ const load = (config) => {
|
||||||
bot.on(key, fn)
|
bot.on(key, fn)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// bot._client.on("chat", _clientSystemMessage)
|
||||||
}
|
}
|
||||||
|
|
||||||
const unload = () => {
|
const unload = () => {
|
||||||
|
@ -517,6 +556,8 @@ const unload = () => {
|
||||||
events_registered.shift()
|
events_registered.shift()
|
||||||
}
|
}
|
||||||
console.log("events_registered:", bot._eventsCount)
|
console.log("events_registered:", bot._eventsCount)
|
||||||
|
|
||||||
|
// bot._client.off("chat", _clientSystemMessage)
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { load, unload, events_registered, command }
|
module.exports = { load, unload, events_registered, command }
|
|
@ -2,11 +2,7 @@ let cfg = {}
|
||||||
let bot = {}
|
let bot = {}
|
||||||
let isEating = false
|
let isEating = false
|
||||||
|
|
||||||
function callbackHandle(err) {
|
function eat(callback = e => e && console.error(e)) {
|
||||||
if (err) console.error(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
function eat(callback) {
|
|
||||||
isEating = true
|
isEating = true
|
||||||
|
|
||||||
const foodNames = require('minecraft-data')(bot.version).foodsArray.map((item) => item.name)
|
const foodNames = require('minecraft-data')(bot.version).foodsArray.map((item) => item.name)
|
||||||
|
@ -37,23 +33,23 @@ function eat(callback) {
|
||||||
|
|
||||||
bot.equip(best_food, 'hand', function (error) {
|
bot.equip(best_food, 'hand', function (error) {
|
||||||
if (error) {
|
if (error) {
|
||||||
console.error(error)
|
console.warn(error, best_food)
|
||||||
isEating = false
|
isEating = false
|
||||||
bot.emit('eat_stop')
|
bot.emit('eat_stop')
|
||||||
} else {
|
} else {
|
||||||
bot.consume(function (err) {
|
try {
|
||||||
if (err) {
|
bot.consume().catch(error => {
|
||||||
console.error(err)
|
if (error.message === "Food is full") {
|
||||||
|
console.warn(error, best_food)
|
||||||
|
} else {
|
||||||
|
return callback({ error, best_food })
|
||||||
|
}
|
||||||
|
}).finally(() => {
|
||||||
isEating = false
|
isEating = false
|
||||||
bot.emit('eat_stop')
|
bot.emit('eat_stop')
|
||||||
return callback(err)
|
})
|
||||||
} else {
|
} catch { }
|
||||||
isEating = false
|
if (bot.food !== 20) eat(callback)
|
||||||
bot.emit('eat_stop')
|
|
||||||
callback(null)
|
|
||||||
if (!bot.food === 20) eat(callbackHandle)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -76,7 +72,7 @@ function checkFood() {
|
||||||
// TODO implement better idle state
|
// TODO implement better idle state
|
||||||
) || true // idle most likely
|
) || true // idle most likely
|
||||||
) {
|
) {
|
||||||
eat(callbackHandle)
|
eat()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -71,9 +71,7 @@ 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!")
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,38 +1,104 @@
|
||||||
let cfg
|
|
||||||
let bot
|
let bot
|
||||||
let mcData
|
let mcData
|
||||||
|
let quiet
|
||||||
|
// import v from 'vec3'
|
||||||
const v = require('vec3')
|
const v = require('vec3')
|
||||||
|
|
||||||
function block(pos) {
|
let cfg = {
|
||||||
const block = pos ? bot.blockAt(v(pos)) : bot.blockAtCursor()
|
info: {
|
||||||
console.log(block, block && block.getProperties())
|
quiet: quiet,
|
||||||
|
recentCommand: null,
|
||||||
|
},
|
||||||
|
// to satisfy typescript
|
||||||
|
quiet: null,
|
||||||
|
bot: bot
|
||||||
|
}
|
||||||
|
|
||||||
|
var RelativePosEnum
|
||||||
|
(function (RelativePosEnum) {
|
||||||
|
RelativePosEnum[RelativePosEnum["feet"] = 0] = "feet"
|
||||||
|
RelativePosEnum[RelativePosEnum["standing"] = 1] = "standing"
|
||||||
|
RelativePosEnum[RelativePosEnum["head"] = 2] = "head"
|
||||||
|
RelativePosEnum[RelativePosEnum["looking"] = 3] = "looking"
|
||||||
|
RelativePosEnum[RelativePosEnum["infront"] = 4] = "infront"
|
||||||
|
RelativePosEnum[RelativePosEnum["behind"] = 5] = "behind"
|
||||||
|
})(RelativePosEnum || (RelativePosEnum = {}))
|
||||||
|
|
||||||
|
function relPosToBlock(entity, relPos) {
|
||||||
|
let pos
|
||||||
|
if (!(relPos in RelativePosEnum)) return console.warn("info: not a relative position:", relPos)
|
||||||
|
relPos = typeof relPos === "number" ? RelativePosEnum[relPos] : relPos
|
||||||
|
switch (relPos) {
|
||||||
|
case "feet":
|
||||||
|
pos = entity.position;
|
||||||
|
break
|
||||||
|
case "standing":
|
||||||
|
pos = entity.position.offset(0, -1, 0)
|
||||||
|
break
|
||||||
|
// todo use CARDINAL directions api from pathfinder
|
||||||
|
// case "behind":
|
||||||
|
// entity.yaw
|
||||||
|
// pos = entity.position
|
||||||
|
// break
|
||||||
|
// case "front":
|
||||||
|
// case "infront":
|
||||||
|
// pos = entity.position
|
||||||
|
// break
|
||||||
|
case "head":
|
||||||
|
pos = entity.position.offset(0, 1.85, 0)
|
||||||
|
break
|
||||||
|
case "looking":
|
||||||
|
if (entity === bot.entity) {
|
||||||
|
return bot.blockAtCursor()
|
||||||
|
// return bot.blockInSight(128, 128)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
quiet || bot.chat(`info: pos '${relPos}' not implemented`)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if (pos) {
|
||||||
|
// nearest block
|
||||||
|
return bot.blockAt(pos)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isVec3(vec) {
|
||||||
|
return vec?.length === 3 || vec.x && vec.y && vec.z
|
||||||
|
}
|
||||||
|
|
||||||
|
function block(entity = bot.entity, pos = entity?.position?.offset(0, -1, 0)) {
|
||||||
|
console.assert(pos || entity)
|
||||||
|
const block = isVec3(pos) ? bot.blockAt(v(pos))
|
||||||
|
: typeof pos === "string" ? relPosToBlock(entity, RelativePosEnum[pos]) : pos
|
||||||
|
console.log(block, block?.getProperties && block.getProperties())
|
||||||
if (!block) {
|
if (!block) {
|
||||||
cfg.quiet || bot.chat("empty block")
|
quiet || bot.chat("empty block")
|
||||||
return block
|
return block
|
||||||
}
|
}
|
||||||
|
bot.lookAt(block?.position)
|
||||||
let info = [block.type, block.name]
|
let info = [block.type, block.name]
|
||||||
if (block.metadata) info.push(Object.entries(block.getProperties()))
|
if (block.metadata) info.push(Object.entries(block.getProperties()))
|
||||||
cfg.quiet || bot.chat(info.join(": "))
|
quiet || bot.chat(info.join(": "))
|
||||||
}
|
}
|
||||||
|
|
||||||
function item(
|
function item(
|
||||||
slot,
|
entity = bot.entity,
|
||||||
entity = bot.entity
|
slot = entity.heldItem
|
||||||
) {
|
) {
|
||||||
const item = slot ?
|
const item = typeof slot === "number" ?
|
||||||
bot.inventory.slots[parseInt(slot) + bot.QUICK_BAR_START] :
|
bot.inventory.slots[slot + bot.QUICK_BAR_START] :
|
||||||
entity.heldItem
|
slot
|
||||||
console.log(item)
|
console.log("info item:", item)
|
||||||
if (!item) {
|
if (!item) {
|
||||||
cfg.quiet || bot.chat("no item")
|
quiet || bot.chat("no item")
|
||||||
return item
|
return item
|
||||||
}
|
}
|
||||||
let info = [item.type, item.name]
|
let info = [item.type, item.name, item.count]
|
||||||
if (item.metadata) info.push("meta: " + item.metadata.length)
|
if (item.metadata) info.push("meta: " + item.metadata.length)
|
||||||
if (item.nbt) {
|
if (item.nbt) {
|
||||||
info.push(compound_value(item.nbt))
|
info.push(compound_value(item.nbt))
|
||||||
}
|
}
|
||||||
cfg.quiet || bot.chat(info.join("; "))
|
quiet || bot.chat(info.join("; "))
|
||||||
function compound_value(obj) {
|
function compound_value(obj) {
|
||||||
if (typeof obj.value == "object") {
|
if (typeof obj.value == "object") {
|
||||||
return compound_value(obj.value)
|
return compound_value(obj.value)
|
||||||
|
@ -50,38 +116,148 @@ function item(
|
||||||
return item
|
return item
|
||||||
}
|
}
|
||||||
|
|
||||||
function entity(name) {
|
var VillagerProfession
|
||||||
const entity = bot.nearestEntity((entity) => {
|
(function (VillagerProfession) {
|
||||||
const ename = entity.name || entity.username
|
VillagerProfession[VillagerProfession["Unemployed"] = 0] = "Unemployed"
|
||||||
return name && ename ? ename == name : true
|
VillagerProfession[VillagerProfession["Armourer"] = 1] = "Armourer"
|
||||||
})
|
VillagerProfession[VillagerProfession["Butcher"] = 2] = "Butcher"
|
||||||
console.log(entity)
|
VillagerProfession[VillagerProfession["Cartographer"] = 3] = "Cartographer"
|
||||||
|
VillagerProfession[VillagerProfession["Cleric"] = 4] = "Cleric"
|
||||||
|
VillagerProfession[VillagerProfession["Farmer"] = 5] = "Farmer"
|
||||||
|
VillagerProfession[VillagerProfession["Fisherman"] = 6] = "Fisherman"
|
||||||
|
VillagerProfession[VillagerProfession["Fletcher"] = 7] = "Fletcher"
|
||||||
|
VillagerProfession[VillagerProfession["Leatherworker"] = 8] = "Leatherworker"
|
||||||
|
VillagerProfession[VillagerProfession["Librarian"] = 9] = "Librarian"
|
||||||
|
VillagerProfession[VillagerProfession["Mason"] = 10] = "Mason"
|
||||||
|
VillagerProfession[VillagerProfession["Nitwit"] = 11] = "Nitwit"
|
||||||
|
VillagerProfession[VillagerProfession["Shepherd"] = 12] = "Shepherd"
|
||||||
|
VillagerProfession[VillagerProfession["Toolsmith"] = 13] = "Toolsmith"
|
||||||
|
VillagerProfession[VillagerProfession["Weaponsmith"] = 14] = "Weaponsmith"
|
||||||
|
})(VillagerProfession || (VillagerProfession = {}))
|
||||||
|
|
||||||
|
function entity(name = bot.nearestEntity()) {
|
||||||
|
const entity = typeof name === "string" ? (name = name.toLowerCase()) && bot.nearestEntity((entity) => {
|
||||||
|
const enames = [entity.username?.toLowerCase(), entity.name, entity.displayName?.toLowerCase()]
|
||||||
|
return enames.includes(name)
|
||||||
|
}) : name
|
||||||
|
console.log("info entity:", entity)
|
||||||
if (!entity) {
|
if (!entity) {
|
||||||
cfg.quiet || bot.chat("no entity")
|
quiet || bot.chat("no entity")
|
||||||
return entity
|
return entity
|
||||||
}
|
}
|
||||||
let info = [entity.type, entity.name || entity.username]
|
entity?.position && bot.lookAt(entity.position)
|
||||||
|
let info = [(entity.entityType && entity.entityType + ":" || "") + (entity.type === "object" ? entity.kind : entity.type)]
|
||||||
|
info.push(entity.username || entity.name)
|
||||||
|
// TODO various info depending on the type of entity; player, villager, etc
|
||||||
|
// TODO refactor and combine with compound_value()
|
||||||
|
switch (entity.type) {
|
||||||
|
case "object":
|
||||||
|
switch (entity.kind) {
|
||||||
|
case "Drops":
|
||||||
|
const item = entity.metadata[7];
|
||||||
|
entity.metadata;
|
||||||
|
if (item.present) {
|
||||||
|
info.push("item: " + item.itemId + ": "
|
||||||
|
+ mcData.items[item.itemId].name
|
||||||
|
+ `x${item.itemCount}`);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
console.warn("info entity: metadata expected item, got:", entity.metadata[7]);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "mob":
|
||||||
|
switch (name) {
|
||||||
|
case 'villager':
|
||||||
|
const { villagerProfession, ...otherProps } = entity.metadata[17]
|
||||||
|
info.push(VillagerProfession[villagerProfession])
|
||||||
|
info.push(Object.entries(otherProps).toString())
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
entity.metadata[8] && info.push("health:" + entity.metadata[8])
|
||||||
|
entity.metadata[15] && info.push("baby")
|
||||||
|
if (entity.heldItem) {
|
||||||
|
info.push("holding")
|
||||||
|
item(entity)
|
||||||
|
}
|
||||||
|
case "global":
|
||||||
|
case "orb":
|
||||||
|
case "player":
|
||||||
|
break;
|
||||||
|
case "other":
|
||||||
|
info.push("kind:" + entity.kind)
|
||||||
|
default:
|
||||||
|
}
|
||||||
if (entity.metadata) info.push("len: " + entity.metadata.length)
|
if (entity.metadata) info.push("len: " + entity.metadata.length)
|
||||||
cfg.quiet || bot.chat(info.join("; "))
|
quiet || bot.chat(info.join("; "))
|
||||||
|
return entity
|
||||||
}
|
}
|
||||||
|
|
||||||
function command(message_parts) {
|
function blockOrItemFromId(num, quiet = cfg.info.quiet) {
|
||||||
|
const block = mcData?.blocks[num]
|
||||||
|
const item = mcData?.items[num]
|
||||||
|
// const entity = mcData?.entities[num]
|
||||||
|
if (block || item) {
|
||||||
|
quiet || bot.chat(
|
||||||
|
(block && `block: ${block.name}, ` || "")
|
||||||
|
+ (item && `item: ${item.name}, ` || "")
|
||||||
|
// + (entity && `entity: ${entity.name}, ` || "")
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
quiet || bot.chat("info: nonexistent block or item")
|
||||||
|
}
|
||||||
|
return { block, item }
|
||||||
|
}
|
||||||
|
|
||||||
|
function command(message_parts, player) {
|
||||||
|
if (message_parts.length > 0) {
|
||||||
|
cfg.info.recentCommand = message_parts
|
||||||
|
}
|
||||||
|
if (player === null)
|
||||||
|
player = void 0
|
||||||
switch (message_parts.length) {
|
switch (message_parts.length) {
|
||||||
case 0:
|
case 0:
|
||||||
// TODO most recent command?
|
if (cfg.info.recentCommand) {
|
||||||
block()
|
command(cfg.info.recentCommand, player)
|
||||||
|
} else {
|
||||||
|
// TODO dispatch on instance of entity, block, etc..
|
||||||
|
// TODO have the logic inside the function or with a utility function
|
||||||
|
block()
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
case 1:
|
case 1:
|
||||||
switch (message_parts[0]) {
|
switch (message_parts[0]) {
|
||||||
|
case "quiet":
|
||||||
|
cfg.info.quiet = quiet = !quiet;
|
||||||
|
quiet || bot.chat(`info: ${quiet ? "" : "not "}being quiet`);
|
||||||
|
break;
|
||||||
|
case "i":
|
||||||
case "item":
|
case "item":
|
||||||
item()
|
item()
|
||||||
break
|
break
|
||||||
|
case "e":
|
||||||
case "entity":
|
case "entity":
|
||||||
entity()
|
entity()
|
||||||
break
|
break
|
||||||
|
case "me":
|
||||||
|
block(player)
|
||||||
|
break
|
||||||
|
case "b":
|
||||||
case "block":
|
case "block":
|
||||||
default:
|
|
||||||
block()
|
block()
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
const num = parseInt(message_parts[0])
|
||||||
|
if (isFinite(num)) {
|
||||||
|
blockOrItemFromId(num)
|
||||||
|
} else {
|
||||||
|
quiet || bot.chat("info usage: `!info [me|i|e|b|<num>|quiet]`")
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -89,9 +265,47 @@ function command(message_parts) {
|
||||||
|
|
||||||
case 2:
|
case 2:
|
||||||
switch (message_parts[0]) {
|
switch (message_parts[0]) {
|
||||||
|
case "i":
|
||||||
case "item":
|
case "item":
|
||||||
item(message_parts[1])
|
switch (message_parts[1]) {
|
||||||
|
case "me":
|
||||||
|
item(player)
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
const slot = parseInt(message_parts[1])
|
||||||
|
slot && item(undefined, slot)
|
||||||
|
break
|
||||||
|
}
|
||||||
break
|
break
|
||||||
|
case "b":
|
||||||
|
case "block":
|
||||||
|
switch (message_parts[1]) {
|
||||||
|
case "me":
|
||||||
|
block(player)
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
const aPlayer = bot.players[message_parts[1]]
|
||||||
|
if (message_parts[1] in RelativePosEnum) {
|
||||||
|
block(undefined, message_parts[1])
|
||||||
|
} else if (aPlayer) {
|
||||||
|
if (aPlayer.entity) {
|
||||||
|
block(aPlayer.entity)
|
||||||
|
} else {
|
||||||
|
quiet || bot.chat(`info: player ${aPlayer.username} too far!`)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// or entity(message_parts[1]).position
|
||||||
|
console.log(bot.players[message_parts[1]])
|
||||||
|
quiet || bot.chat("info: not yet implemented")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break
|
||||||
|
case "me":
|
||||||
|
if (message_parts[1] in RelativePosEnum) {
|
||||||
|
block(player, message_parts[1])
|
||||||
|
}
|
||||||
|
break
|
||||||
|
case "e":
|
||||||
case "entity":
|
case "entity":
|
||||||
default:
|
default:
|
||||||
entity(message_parts[1])
|
entity(message_parts[1])
|
||||||
|
@ -101,25 +315,25 @@ function command(message_parts) {
|
||||||
|
|
||||||
case 4:
|
case 4:
|
||||||
switch (message_parts[0]) {
|
switch (message_parts[0]) {
|
||||||
|
case "b":
|
||||||
case "block":
|
case "block":
|
||||||
default:
|
default:
|
||||||
block(message_parts.slice(1))
|
block(undefined, message_parts.slice(1))
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
|
cfg.quiet || bot.chat("info: unknown command")
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const load = (config) => {
|
const load = (config) => {
|
||||||
|
config.info = cfg.info
|
||||||
cfg = config
|
cfg = config
|
||||||
bot = cfg.bot
|
bot = cfg.bot
|
||||||
cfg.info = {
|
|
||||||
quiet: cfg.quiet,
|
|
||||||
}
|
|
||||||
mcData = bot.mcData || (bot.mcData = require('minecraft-data')(bot.version))
|
mcData = bot.mcData || (bot.mcData = require('minecraft-data')(bot.version))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -11,20 +11,32 @@ let movements = []
|
||||||
|
|
||||||
|
|
||||||
function initMoves(bot = bot, mcData = bot.mcData) {
|
function initMoves(bot = bot, mcData = bot.mcData) {
|
||||||
console.info(movements)
|
|
||||||
if (movements.length > 0) {
|
if (movements.length > 0) {
|
||||||
bot.pathfinder.setMovements(movements.defaultMove)
|
bot.pathfinder.setMovements(movements.defaultMove)
|
||||||
return console.warn("movements already initialized!")
|
return console.warn("go init: movements already initialized!", movements)
|
||||||
}
|
}
|
||||||
let defaultMove = new Movements(bot, mcData)
|
const normalMove = new Movements(bot, mcData)
|
||||||
defaultMove.canDig = false
|
normalMove.canDig = false
|
||||||
defaultMove.scafoldingBlocks.push(mcData.blocksByName.slime_block.id)
|
normalMove.scafoldingBlocks.push(mcData.blocksByName.slime_block.id)
|
||||||
defaultMove.blocksCantBreak.add(mcData.blocksByName.glass.id)
|
normalMove.blocksCantBreak.add(mcData.blocksByName.glass.id)
|
||||||
defaultMove.blocksToAvoid.add(mcData.blocksByName.magma_block.id)
|
normalMove.blocksToAvoid.add(mcData.blocksByName.magma_block.id)
|
||||||
movements.push(defaultMove)
|
movements.push(normalMove)
|
||||||
movements.defaultMove = movements[0]
|
movements.defaultMove = movements[0]
|
||||||
|
|
||||||
bot.pathfinder.setMovements(defaultMove)
|
const aggresiveMove = new Movements(bot, mcData)
|
||||||
|
//Object.create or assign?
|
||||||
|
Object.assign(aggresiveMove, normalMove)
|
||||||
|
aggresiveMove.canDig = true
|
||||||
|
movements.push(aggresiveMove)
|
||||||
|
|
||||||
|
const safeMove = new Movements(bot, mcData)
|
||||||
|
Object.assign(safeMove, normalMove)
|
||||||
|
safeMove.allowParkour = false
|
||||||
|
safeMove.canDig = false
|
||||||
|
movements.push(safeMove)
|
||||||
|
// console.info("go init: moves:", movements)
|
||||||
|
|
||||||
|
bot.pathfinder.setMovements(normalMove)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -82,9 +94,69 @@ function follow(entity, dynamic = true, distance = 3) {
|
||||||
bot.pathfinder.setGoal(new GoalFollow(entity, distance), dynamic)
|
bot.pathfinder.setGoal(new GoalFollow(entity, distance), dynamic)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function away(entity = bot.nearestEntity(), invertInvert = true, dynamic = true, distance = 10) {
|
||||||
|
const currentGoal = bot.pathfinder.goal
|
||||||
|
console.assert(currentGoal || entity)
|
||||||
|
const { GoalInvert } = require('mineflayer-pathfinder').goals
|
||||||
|
|
||||||
|
bot.pathfinder.setMovements(movements.defaultMove)
|
||||||
|
|
||||||
|
if (!currentGoal) {
|
||||||
|
const { GoalFollow } = require('mineflayer-pathfinder').goals
|
||||||
|
|
||||||
|
if (entity.entity) {
|
||||||
|
console.log("go away entity:", entity, entity.entity)
|
||||||
|
entity = entity.entity
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg.quiet || bot.chat(
|
||||||
|
`going away from ${entity?.type
|
||||||
|
}: ${entity?.username || entity?.displayName
|
||||||
|
}${dynamic ? "" : " once"}`
|
||||||
|
)
|
||||||
|
// alternative implementation
|
||||||
|
// follow(entity, dynamic, distance)
|
||||||
|
// bot.pathfinder.setGoal(new GoalInvert(bot.pathfinder.goal), dynamic)
|
||||||
|
return bot.pathfinder.setGoal(new GoalInvert(
|
||||||
|
new GoalFollow(entity, distance)
|
||||||
|
), dynamic)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentGoal instanceof GoalInvert) {
|
||||||
|
const currEntity = currentGoal.goal.entity
|
||||||
|
console.log("go away inverse goal:", currentGoal.goal)
|
||||||
|
if (invertInvert) {
|
||||||
|
cfg.quiet || bot.chat(
|
||||||
|
`switching towards ${currentGoal.goal?.constructor.name
|
||||||
|
}: ${currEntity?.type
|
||||||
|
}: ${currEntity?.username || currEntity?.displayName
|
||||||
|
}${dynamic ? "" : " once"}`
|
||||||
|
)
|
||||||
|
bot.pathfinder.setGoal(currentGoal.goal, dynamic)
|
||||||
|
} else {
|
||||||
|
cfg.quiet || bot.chat(
|
||||||
|
`already going away from ${currentGoal.goal?.constructor.name
|
||||||
|
}; not switching`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const currEntity = currentGoal.entity
|
||||||
|
console.log("go away goal:", currentGoal)
|
||||||
|
cfg.quiet || bot.chat(
|
||||||
|
`going away from ${currentGoal?.constructor.name
|
||||||
|
}: ${currEntity?.type
|
||||||
|
}: ${currEntity?.username || currEntity?.displayName
|
||||||
|
}${dynamic ? "" : " once"}`
|
||||||
|
)
|
||||||
|
bot.pathfinder.setGoal(new GoalInvert(currentGoal), dynamic)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
function ride(entity) {
|
function ride(entity) {
|
||||||
entity = entity?.entity || entity
|
entity = entity?.entity || entity
|
||||||
const ridableMobs = ["Horse", "Donkey", "Pig", "Strider"]
|
const ridableMobs = ["Horse", "Donkey", "Pig", "Strider", "Mule"]
|
||||||
const vehicle = entity && typeof entity !== "string" ? entity : bot.nearestEntity(e => {
|
const vehicle = entity && typeof entity !== "string" ? entity : bot.nearestEntity(e => {
|
||||||
if (typeof entity === "string") return e.name === entity
|
if (typeof entity === "string") return e.name === entity
|
||||||
const maybeRidableMob = e.mobType?.split(" ")
|
const maybeRidableMob = e.mobType?.split(" ")
|
||||||
|
@ -107,8 +179,9 @@ function ride(entity) {
|
||||||
function moveOrRide(turn = false, reverse = -1, directionLabel, message_parts2) {
|
function moveOrRide(turn = false, reverse = -1, directionLabel, message_parts2) {
|
||||||
// bot.once("attach", state = "vehiccel")
|
// bot.once("attach", state = "vehiccel")
|
||||||
if (bot.vehicle) {
|
if (bot.vehicle) {
|
||||||
const amount = parseInt(message_parts2[0]) || 10 * -reverse
|
// FIXME moveVehicle should be +-1 or 0?
|
||||||
bot.moveVehicle(turn && amount || 0, !turn && amount || 0)
|
const amount = parseInt(message_parts2[0]) * -reverse
|
||||||
|
bot.moveVehicle(turn && Math.sign(amount) || 0, !turn && amount || 0)
|
||||||
} else {
|
} else {
|
||||||
command([directionLabel].concat(message_parts2))
|
command([directionLabel].concat(message_parts2))
|
||||||
}
|
}
|
||||||
|
@ -230,6 +303,11 @@ function command(message_parts, player) {
|
||||||
case "mount":
|
case "mount":
|
||||||
ride(message_parts2[0])
|
ride(message_parts2[0])
|
||||||
break
|
break
|
||||||
|
case "away":
|
||||||
|
case "run":
|
||||||
|
case "runaway":
|
||||||
|
away()
|
||||||
|
break
|
||||||
case "w":
|
case "w":
|
||||||
case "f":
|
case "f":
|
||||||
moveOrRide(0, -1, "forward", message_parts2)
|
moveOrRide(0, -1, "forward", message_parts2)
|
||||||
|
@ -246,6 +324,11 @@ function command(message_parts, player) {
|
||||||
case "r":
|
case "r":
|
||||||
moveOrRide(1, 1, "left", message_parts2)
|
moveOrRide(1, 1, "left", message_parts2)
|
||||||
break
|
break
|
||||||
|
case "up":
|
||||||
|
case "u":
|
||||||
|
case "j":
|
||||||
|
moveOrRide(1, 1, "jump", message_parts2)
|
||||||
|
break
|
||||||
case "back":
|
case "back":
|
||||||
case "forward":
|
case "forward":
|
||||||
case "jump":
|
case "jump":
|
||||||
|
|
|
@ -1,115 +1,479 @@
|
||||||
// Load your dependency plugins.
|
// import { createMachine, interpret, InterpreterStatus } from "xstate";
|
||||||
|
const { createMachine, interpret, InterpreterStatus } = require('xstate');
|
||||||
const {pathfinder} = require('mineflayer-pathfinder')
|
// import { access, mkdir, writeFile, readFile } from "fs";
|
||||||
// bot.loadPlugin(require('prismarine-viewer').mineflayer)
|
const { access, mkdir, writeFile, readFile } = require('fs');
|
||||||
// const mineflayerViewer = require('prismarine-viewer').mineflayer
|
// ANGRAM_PREFIX='MINECRAFT'
|
||||||
|
const { MINECRAFT_DATA_FOLDER } = process.env || require("dotenv-packed").parseEnv().parsed;
|
||||||
// Import required behaviors.
|
const storage_dir = MINECRAFT_DATA_FOLDER || './data/' + "/sm/";
|
||||||
const {
|
// import { createBot } from "mineflayer"
|
||||||
StateTransition,
|
// let { pathfinder, Movements, goals } = require('mineflayer-pathfinder')
|
||||||
BotStateMachine,
|
// let cfg
|
||||||
EntityFilters,
|
// let bot = createBot({ username: 'statebot' })
|
||||||
BehaviorFollowEntity,
|
let bot;
|
||||||
BehaviorLookAtEntity,
|
let quiet;
|
||||||
BehaviorGetClosestEntity,
|
let updateRate = 20;
|
||||||
NestedStateMachine,
|
const machines = {
|
||||||
BehaviorIdle,
|
list: {},
|
||||||
StateMachineWebserver,
|
running: {},
|
||||||
} = require("mineflayer-statemachine");
|
};
|
||||||
|
let webserver;
|
||||||
// TODO chat
|
let cfg = {
|
||||||
|
statemachine: {
|
||||||
|
webserver: null,
|
||||||
|
// quiet: true,
|
||||||
// wait for our bot to login.
|
quiet: quiet,
|
||||||
function statemachineInit() {
|
list: {},
|
||||||
cfg.botAddress = new RegExp(`^${bot.username} (!.+)`)
|
running: {},
|
||||||
// This targets object is used to pass data between different states. It can be left empty.
|
draft: null,
|
||||||
const targets = new Object();
|
recent: null,
|
||||||
|
// debug: null,
|
||||||
// Create our states
|
debug: true,
|
||||||
const getClosestPlayer = new BehaviorGetClosestEntity(
|
updateRate: updateRate
|
||||||
bot, targets, entity => EntityFilters().PlayersOnly(entity) && bot.entity.position.distanceTo(entity.position) <= 50 ); // && a.username !== bot.username);
|
}
|
||||||
const followPlayer = new BehaviorFollowEntity(bot, targets);
|
// FIXME temp variables to satisfy typescript autocomplete
|
||||||
const lookAtPlayer = new BehaviorLookAtEntity(bot, targets);
|
// , quiet: null
|
||||||
const stay = new BehaviorIdle();
|
,
|
||||||
|
bot: bot,
|
||||||
// Create our transitions
|
plugins: { statemachine: null }
|
||||||
const transitions = [
|
};
|
||||||
|
// Edit your machine(s) here
|
||||||
// We want to start following the player immediately after finding them.
|
function init(smName = "dummy", webserver) {
|
||||||
// Since getClosestPlayer finishes instantly, shouldTransition() should always return true.
|
access(storage_dir, err => {
|
||||||
new StateTransition({
|
if (err?.code === 'ENOENT') {
|
||||||
parent: getClosestPlayer,
|
mkdir(storage_dir, e => e && console.warn("sm init: create dir", e));
|
||||||
child: followPlayer,
|
}
|
||||||
onTransition: (quiet) => quiet || bot.chat(`Hi ${targets.entity.username}!`),
|
else if (err) {
|
||||||
shouldTransition: () => bot.entity.position.distanceTo(targets.entity.position) <= 50,
|
console.warn("sm init: create dir", err);
|
||||||
// shouldTransition: () => getClosestPlayer.distanceToTarget() < 100 || console.info("player too far!") && false,
|
}
|
||||||
}),
|
});
|
||||||
|
// const machine = newSM(smName)
|
||||||
// If the distance to the player is less than two blocks, switch from the followPlayer
|
// machine.states.idle.on.TOGGLE = "start"
|
||||||
// state to the lookAtPlayer state.
|
// machine.states.start.on.TOGGLE = "idle"
|
||||||
new StateTransition({
|
const machine = createMachine({
|
||||||
parent: followPlayer,
|
id: smName,
|
||||||
child: lookAtPlayer,
|
initial: "idle",
|
||||||
// onTransition: () => console.log(targets),
|
states: {
|
||||||
shouldTransition: () => followPlayer.distanceToTarget() < 2,
|
idle: {
|
||||||
}),
|
on: { TOGGLE: "start", NEXT: "start", PREV: "look", STOP: "finish" }
|
||||||
|
},
|
||||||
// If the distance to the player is more than two blocks, switch from the lookAtPlayer
|
start: {
|
||||||
// state to the followPlayer state.
|
on: { TOGGLE: "look", NEXT: "look", PREV: "idle" },
|
||||||
new StateTransition({
|
entry: 'lookAtPlayerOnce',
|
||||||
parent: lookAtPlayer,
|
},
|
||||||
child: followPlayer,
|
look: {
|
||||||
shouldTransition: () => lookAtPlayer.distanceToTarget() >= 5,
|
on: { TOGGLE: "idle", NEXT: "idle", PREV: "start" },
|
||||||
}),
|
// entry: ['look', 'blah']
|
||||||
new StateTransition({
|
// entry: 'lookAtPlayerOnce',
|
||||||
parent: lookAtPlayer,
|
activities: 'lookAtPlayer',
|
||||||
child: stay,
|
meta: { debug: true }
|
||||||
onTransition: () => bot.chat("ok, staying"),
|
},
|
||||||
// shouldTransition: () => true,
|
finish: {
|
||||||
}),
|
type: 'final'
|
||||||
new StateTransition({
|
},
|
||||||
parent: stay,
|
},
|
||||||
child: getClosestPlayer,
|
on: { START: '.start', STOP: '.idle' },
|
||||||
// shouldTransition: () => Math.random() > 0.01,
|
meta: { debug: true },
|
||||||
// shouldTransition: () => Math.random() > 0.1 && getClosestPlayer.distanceToTarget() < 2,
|
context: { player: null, rate: updateRate },
|
||||||
}),
|
}, {
|
||||||
];
|
actions: {
|
||||||
|
// action implementation
|
||||||
// Now we just wrap our transition list in a nested state machine layer. We want the bot
|
lookAtPlayerOnce: (context, event) => {
|
||||||
// to start on the getClosestPlayer state, so we'll specify that here.
|
const player = context?.player && (context?.player?.isValid || context?.player?.entity?.isValid)
|
||||||
const rootLayer = new NestedStateMachine(transitions, getClosestPlayer, stay);
|
|| bot.nearestEntity(entity => entity.type === 'player');
|
||||||
|
if (player?.position || player?.entity) {
|
||||||
// We can start our state machine simply by creating a new instance.
|
context.player = player;
|
||||||
cfg.stateMachines.follow = new BotStateMachine(bot, rootLayer);
|
bot.lookAt((player.entity || player).position.offset(0, 1, 0));
|
||||||
const webserver = new StateMachineWebserver(bot, cfg.stateMachines.follow);
|
}
|
||||||
webserver.startServer();
|
}
|
||||||
|
},
|
||||||
// mineflayerViewer(bot, { port: 3000 })
|
activities: {
|
||||||
// const path = [bot.entity.position.clone()]
|
lookAtPlayer: (context, event) => {
|
||||||
// bot.on('move', () => {
|
const player = (context?.player?.isValid || context?.player?.entity?.isValid) && context?.player
|
||||||
// if (path[path.length - 1].distanceTo(bot.entity.position) > 1) {
|
|| bot.nearestEntity(entity => entity.type === 'player' && entity.isValid);
|
||||||
// path.push(bot.entity.position.clone())
|
// TODO check pos every event?
|
||||||
// bot.viewer.drawLine('path', path)
|
if (player?.position || player?.entity) {
|
||||||
// }
|
context.player = player;
|
||||||
// })
|
function looks() {
|
||||||
|
bot.lookAt((player.entity || player).position.offset(0, 1, 0));
|
||||||
|
}
|
||||||
|
bot.on("time", looks);
|
||||||
|
return () => bot.off("time", looks);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
quiet || bot.chat("look: no valid players");
|
||||||
|
// TODO use xstate logger
|
||||||
|
context.debug && console.log("sm: no valid player", this, context, player);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
delays: {
|
||||||
|
/* ... */
|
||||||
|
},
|
||||||
|
guards: {
|
||||||
|
/* ... */
|
||||||
|
},
|
||||||
|
services: {
|
||||||
|
/* ... */
|
||||||
|
}
|
||||||
|
});
|
||||||
|
console.log("sm init: machine", machine);
|
||||||
|
const service = runSM(saveSM(machine));
|
||||||
|
if (service?.send) {
|
||||||
|
setTimeout(service.send, 200, "TOGGLE");
|
||||||
|
// setTimeout(service.send, 400, "TOGGLE")
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
console.warn("sm init: service", service);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
function newSM(smName = "sm_" + Object.keys(cfg.statemachine.list).length) {
|
||||||
const load = (config) => {
|
smName = smName.replace(/\s+/, '_');
|
||||||
cfg = config
|
if (cfg.statemachine.list[smName]) {
|
||||||
bot = cfg.bot
|
console.warn("sm exists", smName);
|
||||||
// cfg.inventory = {
|
quiet || bot.chat(`sm ${smName} already exists, edit or use another name instead`);
|
||||||
// auto: true,
|
return;
|
||||||
// quiet: false
|
}
|
||||||
// }
|
const machine = createMachine({
|
||||||
// bot.on('chat', inventory)
|
id: smName,
|
||||||
bot.loadPlugin(pathfinder)
|
initial: "start",
|
||||||
// statemachineInit()
|
// TODO use history states for PAUSE and RESUME
|
||||||
|
states: { idle: { on: { START: "start" } }, start: { on: { STOP: "idle" } } }
|
||||||
|
});
|
||||||
|
cfg.statemachine.draft = machine;
|
||||||
|
return machine;
|
||||||
}
|
}
|
||||||
|
function saveSM(machine = cfg.statemachine.draft) {
|
||||||
const unload = () => {
|
if (!machine?.id) {
|
||||||
// bot.off('chat', inventory)
|
console.warn("sm save: invalid", machine);
|
||||||
|
quiet || bot.chat("sm: couldn't save, invalid");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// TODO do tests and validation
|
||||||
|
// 1. ensure default states [start, idle]
|
||||||
|
// 2. ensure closed cycle from start to idle
|
||||||
|
cfg.statemachine.list[machine.id] = machine;
|
||||||
|
if (machine.id === cfg.statemachine.draft?.id) {
|
||||||
|
cfg.statemachine.draft = null;
|
||||||
|
}
|
||||||
|
writeFile(
|
||||||
|
// TODO
|
||||||
|
// `${storage_dir}/${player}/${machine.id}.json`
|
||||||
|
`${storage_dir}/${machine.id}.json`,
|
||||||
|
// TODO decide which data to store
|
||||||
|
// https://xstate.js.org/docs/guides/states.html#persisting-state
|
||||||
|
// JSON.stringify(machine.toJSON),
|
||||||
|
// JSON.stringify(machine.states.toJSON), // + activities, delays, etc
|
||||||
|
JSON.stringify({ config: machine.config, context: machine.context }), e => e && console.log("sm load sm: write file", e));
|
||||||
|
// return run ? runSM(machine) : machine
|
||||||
|
return machine;
|
||||||
}
|
}
|
||||||
|
function loadSM(name, run = true) {
|
||||||
module.exports = { load, unload }
|
//: StateMachine<any, any, any> {
|
||||||
|
readFile(
|
||||||
|
// readFileSync(
|
||||||
|
// TODO
|
||||||
|
// `${storage_dir}/${player}/${machine.id}.json`
|
||||||
|
`${storage_dir}/${name}.json`, afterRead
|
||||||
|
// JSON.stringify(machine.toJSON),
|
||||||
|
);
|
||||||
|
function afterRead(err, jsonString) {
|
||||||
|
if (err) {
|
||||||
|
console.warn("sm load sm: read file", err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const machine = createMachine(JSON.parse(jsonString).config);
|
||||||
|
// TODO do tests and validation
|
||||||
|
// 1. ensure default states [start, idle]
|
||||||
|
// 2. ensure closed cycle from start to idle
|
||||||
|
cfg.statemachine.list[machine.id] = machine;
|
||||||
|
if (machine.id === cfg.statemachine.draft?.id) {
|
||||||
|
cfg.statemachine.draft = machine;
|
||||||
|
}
|
||||||
|
if (run) {
|
||||||
|
runSM(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 getSM(name = cfg.statemachine.draft || cfg.statemachine.recent, asService = false, quiet = false) {
|
||||||
|
const machine = typeof name === "string" ? cfg.statemachine.list[name]
|
||||||
|
: name;
|
||||||
|
if (!machine) {
|
||||||
|
console.warn("sm get: doesn't exist", name);
|
||||||
|
cfg.statemachine.quiet || bot.chat(`sm ${name} doesn't exist`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (asService) {
|
||||||
|
const service = cfg.statemachine.running[machine?.id];
|
||||||
|
if (!service) {
|
||||||
|
quiet || console.warn("sm get: already stopped", machine);
|
||||||
|
quiet || cfg.statemachine.quiet || bot.chat(`sm ${machine?.id} isn't running`);
|
||||||
|
return interpret(machine);
|
||||||
|
}
|
||||||
|
return service;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// return machine.machine ? machine.machine : machine
|
||||||
|
return machine;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function runSM(name = getSM(undefined, undefined, true), player // or supervisor?
|
||||||
|
, restart = false) {
|
||||||
|
if (!name)
|
||||||
|
return;
|
||||||
|
const service = getSM(name, true, true);
|
||||||
|
if (!service)
|
||||||
|
return;
|
||||||
|
const machine = service.machine;
|
||||||
|
if (!machine)
|
||||||
|
return;
|
||||||
|
switch (service.status) {
|
||||||
|
case InterpreterStatus.Running:
|
||||||
|
if (!restart) {
|
||||||
|
console.warn("sm run: already running", service.id);
|
||||||
|
quiet || bot.chat(`sm ${service.id} already running`);
|
||||||
|
return service;
|
||||||
|
}
|
||||||
|
stopSM(machine);
|
||||||
|
case InterpreterStatus.NotStarted:
|
||||||
|
case InterpreterStatus.Stopped:
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
console.warn("sm run: unknown status:", service.status, service);
|
||||||
|
return;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (cfg.statemachine.debug || machine.meta?.debug) {
|
||||||
|
service.onTransition((state) => {
|
||||||
|
quiet || bot.chat(`sm trans: ${machine.id}, ${state.value}`);
|
||||||
|
quiet || state.meta?.debug && bot.chat(`sm next events: ${machine.id}, ${state.nextEvents}`);
|
||||||
|
console.log("sm debug: trans", state.value, state);
|
||||||
|
}).onDone((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;
|
||||||
|
service.start();
|
||||||
|
// return machine
|
||||||
|
return service;
|
||||||
|
}
|
||||||
|
function stopSM(name = getSM(), quiet = false) {
|
||||||
|
let service = getSM(name, true, quiet);
|
||||||
|
if (!service)
|
||||||
|
return;
|
||||||
|
const machine = service.machine;
|
||||||
|
switch (service.status) {
|
||||||
|
case InterpreterStatus.NotStarted:
|
||||||
|
case InterpreterStatus.Stopped:
|
||||||
|
console.log("sm stop status", service.status, service.id, cfg.statemachine.running[service.id]);
|
||||||
|
// TODO check if any bugs
|
||||||
|
case InterpreterStatus.Running:
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
console.warn("sm stop: unknown status:", service.status);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
service?.stop?.();
|
||||||
|
cfg.statemachine.running[machine.id] = null;
|
||||||
|
delete cfg.statemachine.running[machine.id];
|
||||||
|
// return machine
|
||||||
|
return service;
|
||||||
|
}
|
||||||
|
function actionSM(action, name = getSM()) {
|
||||||
|
if (!action) {
|
||||||
|
return console.warn("sm action", action);
|
||||||
|
}
|
||||||
|
let service = getSM(name, true, true);
|
||||||
|
if (service.status !== InterpreterStatus.Running)
|
||||||
|
return;
|
||||||
|
// const machine = service.machine
|
||||||
|
service.send(action.toUpperCase());
|
||||||
|
}
|
||||||
|
function stepSM(command = "", ...message_parts) {
|
||||||
|
let service = getSM(undefined, true);
|
||||||
|
if (!service)
|
||||||
|
return;
|
||||||
|
if (!service.send) {
|
||||||
|
console.warn("sm step: can't send", service.machine);
|
||||||
|
// TODO start a temporary service to interpret
|
||||||
|
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);
|
||||||
|
runSM;
|
||||||
|
}
|
||||||
|
// const machine = service.machine
|
||||||
|
switch (command) {
|
||||||
|
case "edit":
|
||||||
|
// maybe `edit <type>`, like `add`?
|
||||||
|
// where type:
|
||||||
|
// context
|
||||||
|
// action
|
||||||
|
// timeout | all timeout
|
||||||
|
break;
|
||||||
|
case "undo":
|
||||||
|
break;
|
||||||
|
case "del":
|
||||||
|
break;
|
||||||
|
case "p":
|
||||||
|
case "prev":
|
||||||
|
service?.send("PREV");
|
||||||
|
break;
|
||||||
|
case "add":
|
||||||
|
// maybe `add <type>`?
|
||||||
|
// where type:
|
||||||
|
// context
|
||||||
|
// action
|
||||||
|
// timeout
|
||||||
|
case "new":
|
||||||
|
break;
|
||||||
|
// case "with":
|
||||||
|
// console.log(this)
|
||||||
|
// stepSM(getSM(message_parts[0], true, true), ...message_parts.slice(1))
|
||||||
|
// break;
|
||||||
|
case "help":
|
||||||
|
quiet || bot.chat("![sm ]step [ p(rev) | n(ext) ]");
|
||||||
|
break;
|
||||||
|
case "n":
|
||||||
|
case "next":
|
||||||
|
default:
|
||||||
|
service?.send("NEXT");
|
||||||
|
quiet || bot.chat("stepped");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function tickSM(time = bot.time.timeOfDay, rate = 20) {
|
||||||
|
if (time % rate !== 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log("sm tick", rate, time);
|
||||||
|
}
|
||||||
|
function debugSM(name = getSM()) {
|
||||||
|
if (!name)
|
||||||
|
return;
|
||||||
|
let service = getSM(name, true);
|
||||||
|
if (!service)
|
||||||
|
return;
|
||||||
|
const machine = service.machine;
|
||||||
|
machine.meta.debug = !!!machine.meta.debug;
|
||||||
|
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);
|
||||||
|
switch (message_parts[0]) {
|
||||||
|
case "add":
|
||||||
|
command(["new"].concat(message_parts2));
|
||||||
|
break;
|
||||||
|
case "finish":
|
||||||
|
case "done":
|
||||||
|
case "end":
|
||||||
|
command(["save"].concat(message_parts2));
|
||||||
|
break;
|
||||||
|
case "do":
|
||||||
|
case "load":
|
||||||
|
case "start":
|
||||||
|
command(["run"].concat(message_parts2));
|
||||||
|
break;
|
||||||
|
case "debug":
|
||||||
|
switch (message_parts[1]) {
|
||||||
|
case "sm":
|
||||||
|
case "global":
|
||||||
|
case "meta":
|
||||||
|
cfg.statemachine.debug = !!!cfg.statemachine.debug;
|
||||||
|
quiet || bot.chat(`sm debug: ${cfg.statemachine.debug}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "new":
|
||||||
|
case "save":
|
||||||
|
case "run":
|
||||||
|
case "step":
|
||||||
|
case "stop":
|
||||||
|
// temp
|
||||||
|
case "action":
|
||||||
|
switch (message_parts2.length) {
|
||||||
|
case 0:
|
||||||
|
console.warn(`sm ${message_parts[0]}: no name, using defaults`);
|
||||||
|
case 1:
|
||||||
|
// FIXME `this` doesn't work always
|
||||||
|
(this.runSM && this || cfg.plugins.statemachine)[message_parts[0] + "SM"](...message_parts2);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "undo":
|
||||||
|
break;
|
||||||
|
case "list":
|
||||||
|
case "status":
|
||||||
|
// TODO current/recent, updateRate
|
||||||
|
const { list, running } = cfg.statemachine;
|
||||||
|
console.log("sm list", running, list);
|
||||||
|
quiet || bot.chat(`${Object.keys(running).length} of ${Object.keys(list).length} active: ${Object.keys(running)}`
|
||||||
|
+ (message_parts[1] === "all" ? `${Object.keys(list)}` : ''));
|
||||||
|
break;
|
||||||
|
case "quiet":
|
||||||
|
quiet = cfg.statemachine.quiet = !!!cfg.statemachine.quiet;
|
||||||
|
quiet || bot.chat(`sm: ${cfg.statemachine.quiet ? "" : "not "}being quiet`);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
// TODO general helper from declarative commands object
|
||||||
|
quiet || bot.chat(`sm help: !sm [new | step| save | run | list | quiet | debug]`);
|
||||||
|
console.warn("sm unknown command", message_parts);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
function load(config) {
|
||||||
|
webserver = cfg.statemachine.webserver = config.statemachine?.webserver || webserver;
|
||||||
|
config.statemachine = cfg.statemachine || {
|
||||||
|
webserver: null,
|
||||||
|
// quiet: true,
|
||||||
|
quiet: false,
|
||||||
|
list: {},
|
||||||
|
running: {},
|
||||||
|
draft: null,
|
||||||
|
recent: null,
|
||||||
|
// debug: null,
|
||||||
|
debug: true,
|
||||||
|
updateRate: updateRate
|
||||||
|
};
|
||||||
|
cfg = config;
|
||||||
|
bot = cfg.bot;
|
||||||
|
// pathfinder = bot.pathfinder || bot.loadPlugin(require('mineflayer-pathfinder').pathfinder)
|
||||||
|
// mcData = bot.mcData || (bot.mcData = require('minecraft-data')(bot.version))
|
||||||
|
init(undefined, webserver);
|
||||||
|
updateRate = cfg.statemachine.updateRate || updateRate;
|
||||||
|
bot.on('time', tickSM);
|
||||||
|
// bot.once('time', tickSM, 5)
|
||||||
|
console.log("sm load", cfg.statemachine);
|
||||||
|
}
|
||||||
|
function unload() {
|
||||||
|
const { list, running } = cfg.statemachine;
|
||||||
|
bot.off('time', tickSM);
|
||||||
|
Object.keys(running).forEach(sm => {
|
||||||
|
stopSM(sm);
|
||||||
|
});
|
||||||
|
// delete cfg.statemachine;
|
||||||
|
cfg.statemachine = null;
|
||||||
|
console.log("sm unload: deleted", cfg.statemachine);
|
||||||
|
}
|
||||||
|
module.exports = {
|
||||||
|
load, unload, command, init,
|
||||||
|
newSM, saveSM, loadSM, runSM, stopSM, actionSM, stepSM, debugSM
|
||||||
|
};
|
24
package.json
24
package.json
|
@ -30,24 +30,26 @@
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/PrismarineJS/prismarine-template#readme",
|
"homepage": "https://github.com/PrismarineJS/prismarine-template#readme",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/node": "^14.14.41",
|
||||||
"jest": "^26.6.3",
|
"jest": "^26.6.3",
|
||||||
"require-self": "^0.2.3"
|
"require-self": "^0.2.3",
|
||||||
|
"typescript": "^4.2.4"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"dotenv-packed": "^1.2.1",
|
"dotenv-packed": "^1.2.2",
|
||||||
"minecraft-data": "^2.73.1",
|
"minecraft-data": "^2.84.0",
|
||||||
"mineflayer": "^2.40.1",
|
"mineflayer": "^3.6.0",
|
||||||
"mineflayer-armor-manager": "^1.4.0",
|
"mineflayer-armor-manager": "^1.4.1",
|
||||||
"mineflayer-pathfinder": "^1.3.6",
|
"mineflayer-pathfinder": "^1.6.1",
|
||||||
"mineflayer-pvp": "^1.0.2",
|
"mineflayer-pvp": "^1.0.2",
|
||||||
"prismarine-block": "^1.7.3",
|
"prismarine-block": "^1.8.0",
|
||||||
"prismarine-chat": "^1.0.3",
|
"prismarine-chat": "^1.0.3",
|
||||||
"prismarine-entity": "^1.1.0",
|
"prismarine-entity": "^1.1.0",
|
||||||
"prismarine-item": "^1.5.0",
|
"prismarine-item": "^1.8.0",
|
||||||
"prismarine-nbt": "^1.4.0",
|
"prismarine-nbt": "^1.5.0",
|
||||||
"prismarine-recipe": "^1.1.0",
|
"prismarine-recipe": "^1.1.0",
|
||||||
"typescript": "^4.1.3",
|
"vec3": "^0.1.7",
|
||||||
"vec3": "^0.1.7"
|
"xstate": "^4.18.0"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"lib/**/*"
|
"lib/**/*"
|
||||||
|
|
Loading…
Reference in New Issue
Block a user