if (process.argv.length < 4 || process.argv.length > 6) {
console.log('Usage : node guard.js <host> <port> [<name>] [<password>]')
process.exit(1)
}
const mineflayer = require('mineflayer')
const { pathfinder, Movements, goals } = require('mineflayer-pathfinder')
const pvp = require('mineflayer-pvp').plugin
const bot = mineflayer.createBot({
host: process.argv[2],
port: parseInt(process.argv[3]),
username: process.argv[4] ? process.argv[4] : 'Guard',
password: process.argv[5]
})
bot.loadPlugin(pathfinder)
bot.loadPlugin(pvp)
let guardPos = null
function guardArea (pos) {
guardPos = pos
if (!bot.pvp.target) {
moveToGuardPos()
}
}
function stopGuarding () {
guardPos = null
bot.pvp.stop()
bot.pathfinder.setGoal(null)
}
function moveToGuardPos () {
bot.pathfinder.setMovements(new Movements(bot))
bot.pathfinder.setGoal(new goals.GoalBlock(guardPos.x, guardPos.y, guardPos.z))
}
bot.on('stoppedAttacking', () => {
if (guardPos) {
moveToGuardPos()
}
})
bot.on('physicsTick', () => {
if (!guardPos) return
const filter = e => e.type === 'mob' && e.position.distanceTo(bot.entity.position) < 16 &&
e.displayName !== 'Armor Stand'
const entity = bot.nearestEntity(filter)
if (entity) {
bot.pvp.attack(entity)
}
})
bot.on('chat', (username, message) => {
if (message === 'guard') {
const player = bot.players[username]
if (!player) {
bot.chat("I can't see you.")
return
}
bot.chat('I will guard that location.')
guardArea(player.entity.position)
}
if (message === 'stop') {
bot.chat('I will no longer guard this area.')
stopGuarding()
}
})