Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/examples/chest.js
Views: 789
/*1* Watch out, this is a big one!2*3* This is a demonstration to show you how you can interact with:4* - Chests5* - Furnaces6* - Dispensers7* - Enchantment Tables8*9* and of course with your own inventory.10*11* Each of the main commands makes the bot interact with the block and open12* its window. From there you can send another set of commands to actually13* interact with the window and make awesome stuff.14*15* There's also a bonus example which shows you how to use the /invsee command16* to see what items another user has in his inventory and what items he has17* equipped.18* This last one is usually reserved to Server Ops so make sure you have the19* appropriate permission to do it or it won't work.20*/21const mineflayer = require('mineflayer')2223if (process.argv.length < 4 || process.argv.length > 6) {24console.log('Usage : node chest.js <host> <port> [<name>] [<password>]')25process.exit(1)26}2728const bot = mineflayer.createBot({29host: process.argv[2],30port: parseInt(process.argv[3]),31username: process.argv[4] ? process.argv[4] : 'chest',32password: process.argv[5]33})3435bot.on('experience', () => {36bot.chat(`I am level ${bot.experience.level}`)37})3839bot.on('chat', (username, message) => {40if (username === bot.username) return41switch (true) {42case /^list$/.test(message):43sayItems()44break45case /^chest$/.test(message):46watchChest(false, ['chest', 'ender_chest', 'trapped_chest'])47break48case /^furnace$/.test(message):49watchFurnace()50break51case /^dispenser$/.test(message):52watchChest(false, ['dispenser'])53break54case /^enchant$/.test(message):55watchEnchantmentTable()56break57case /^chestminecart$/.test(message):58watchChest(true)59break60case /^invsee \w+( \d)?$/.test(message): {61// invsee Herobrine [or]62// invsee Herobrine 163const command = message.split(' ')64useInvsee(command[0], command[1])65break66}67}68})6970function sayItems (items = bot.inventory.items()) {71const output = items.map(itemToString).join(', ')72if (output) {73bot.chat(output)74} else {75bot.chat('empty')76}77}7879async function watchChest (minecart, blocks = []) {80let chestToOpen81if (minecart) {82chestToOpen = Object.keys(bot.entities)83.map(id => bot.entities[id]).find(e => e.entityType === bot.registry.entitiesByName.chest_minecart &&84e.objectData.intField === 1 &&85bot.entity.position.distanceTo(e.position) < 3)86if (!chestToOpen) {87bot.chat('no chest minecart found')88return89}90} else {91chestToOpen = bot.findBlock({92matching: blocks.map(name => bot.registry.blocksByName[name].id),93maxDistance: 694})95if (!chestToOpen) {96bot.chat('no chest found')97return98}99}100const chest = await bot.openContainer(chestToOpen)101sayItems(chest.containerItems())102chest.on('updateSlot', (slot, oldItem, newItem) => {103bot.chat(`chest update: ${itemToString(oldItem)} -> ${itemToString(newItem)} (slot: ${slot})`)104})105chest.on('close', () => {106bot.chat('chest closed')107})108109bot.on('chat', onChat)110111function onChat (username, message) {112if (username === bot.username) return113const command = message.split(' ')114switch (true) {115case /^close$/.test(message):116closeChest()117break118case /^withdraw \d+ \w+$/.test(message):119// withdraw amount name120// ex: withdraw 16 stick121withdrawItem(command[2], command[1])122break123case /^deposit \d+ \w+$/.test(message):124// deposit amount name125// ex: deposit 16 stick126depositItem(command[2], command[1])127break128}129}130131function closeChest () {132chest.close()133bot.removeListener('chat', onChat)134}135136async function withdrawItem (name, amount) {137const item = itemByName(chest.containerItems(), name)138if (item) {139try {140await chest.withdraw(item.type, null, amount)141bot.chat(`withdrew ${amount} ${item.name}`)142} catch (err) {143bot.chat(`unable to withdraw ${amount} ${item.name}`)144}145} else {146bot.chat(`unknown item ${name}`)147}148}149150async function depositItem (name, amount) {151const item = itemByName(chest.items(), name)152if (item) {153try {154await chest.deposit(item.type, null, amount)155bot.chat(`deposited ${amount} ${item.name}`)156} catch (err) {157bot.chat(`unable to deposit ${amount} ${item.name}`)158}159} else {160bot.chat(`unknown item ${name}`)161}162}163}164165async function watchFurnace () {166const furnaceBlock = bot.findBlock({167matching: ['furnace', 'lit_furnace'].filter(name => bot.registry.blocksByName[name] !== undefined).map(name => bot.registry.blocksByName[name].id),168maxDistance: 6169})170if (!furnaceBlock) {171bot.chat('no furnace found')172return173}174const furnace = await bot.openFurnace(furnaceBlock)175let output = ''176output += `input: ${itemToString(furnace.inputItem())}, `177output += `fuel: ${itemToString(furnace.fuelItem())}, `178output += `output: ${itemToString(furnace.outputItem())}`179bot.chat(output)180181furnace.on('updateSlot', (slot, oldItem, newItem) => {182bot.chat(`furnace update: ${itemToString(oldItem)} -> ${itemToString(newItem)} (slot: ${slot})`)183})184furnace.on('close', () => {185bot.chat('furnace closed')186})187furnace.on('update', () => {188console.log(`fuel: ${Math.round(furnace.fuel * 100)}% progress: ${Math.round(furnace.progress * 100)}%`)189})190191bot.on('chat', onChat)192193function onChat (username, message) {194if (username === bot.username) return195const command = message.split(' ')196switch (true) {197case /^close$/.test(message):198closeFurnace()199break200case /^(input|fuel) \d+ \w+$/.test(message):201// input amount name202// ex: input 32 coal203putInFurnace(command[0], command[2], command[1])204break205case /^take (input|fuel|output)$/.test(message):206// take what207// ex: take output208takeFromFurnace(command[0])209break210}211212function closeFurnace () {213furnace.close()214bot.removeListener('chat', onChat)215}216217async function putInFurnace (where, name, amount) {218const item = itemByName(furnace.items(), name)219if (item) {220const fn = {221input: furnace.putInput,222fuel: furnace.putFuel223}[where]224try {225await fn.call(furnace, item.type, null, amount)226bot.chat(`put ${amount} ${item.name}`)227} catch (err) {228bot.chat(`unable to put ${amount} ${item.name}`)229}230} else {231bot.chat(`unknown item ${name}`)232}233}234235async function takeFromFurnace (what) {236const fn = {237input: furnace.takeInput,238fuel: furnace.takeFuel,239output: furnace.takeOutput240}[what]241try {242const item = await fn.call(furnace)243bot.chat(`took ${item.name}`)244} catch (err) {245bot.chat('unable to take')246}247}248}249}250251async function watchEnchantmentTable () {252const enchantTableBlock = bot.findBlock({253matching: ['enchanting_table'].map(name => bot.registry.blocksByName[name].id),254maxDistance: 6255})256if (!enchantTableBlock) {257bot.chat('no enchantment table found')258return259}260const table = await bot.openEnchantmentTable(enchantTableBlock)261bot.chat(itemToString(table.targetItem()))262263table.on('updateSlot', (slot, oldItem, newItem) => {264bot.chat(`enchantment table update: ${itemToString(oldItem)} -> ${itemToString(newItem)} (slot: ${slot})`)265})266table.on('close', () => {267bot.chat('enchantment table closed')268})269table.on('ready', () => {270bot.chat(`ready to enchant. choices are ${table.enchantments.map(o => o.level).join(', ')}`)271})272273bot.on('chat', onChat)274275function onChat (username, message) {276if (username === bot.username) return277const command = message.split(' ')278switch (true) {279case /^close$/.test(message):280closeEnchantmentTable()281break282case /^put \w+$/.test(message):283// put name284// ex: put diamondsword285putItem(command[1])286break287case /^add lapis$/.test(message):288addLapis()289break290case /^enchant \d+$/.test(message):291// enchant choice292// ex: enchant 2293enchantItem(command[1])294break295case /^take$/.test(message):296takeEnchantedItem()297break298}299300function closeEnchantmentTable () {301table.close()302}303304async function putItem (name) {305const item = itemByName(table.window.items(), name)306if (item) {307try {308await table.putTargetItem(item)309bot.chat(`I put ${itemToString(item)}`)310} catch (err) {311bot.chat(`error putting ${itemToString(item)}`)312}313} else {314bot.chat(`unknown item ${name}`)315}316}317318async function addLapis () {319const item = itemByType(table.window.items(), ['dye', 'purple_dye', 'lapis_lazuli'].filter(name => bot.registry.itemByName[name] !== undefined)320.map(name => bot.registry.itemByName[name].id))321if (item) {322try {323await table.putLapis(item)324bot.chat(`I put ${itemToString(item)}`)325} catch (err) {326bot.chat(`error putting ${itemToString(item)}`)327}328} else {329bot.chat("I don't have any lapis")330}331}332333async function enchantItem (choice) {334choice = parseInt(choice, 10)335try {336const item = await table.enchant(choice)337bot.chat(`enchanted ${itemToString(item)}`)338} catch (err) {339bot.chat('error enchanting')340}341}342343async function takeEnchantedItem () {344try {345const item = await table.takeTargetItem()346bot.chat(`got ${itemToString(item)}`)347} catch (err) {348bot.chat('error getting item')349}350}351}352}353354function useInvsee (username, showEquipment) {355bot.once('windowOpen', (window) => {356const count = window.containerItems().length357const what = showEquipment ? 'equipment' : 'inventory items'358if (count) {359bot.chat(`${username}'s ${what}:`)360sayItems(window.containerItems())361} else {362bot.chat(`${username} has no ${what}`)363}364})365if (showEquipment) {366// any extra parameter triggers the easter egg367// and shows the other player's equipment368bot.chat(`/invsee ${username} 1`)369} else {370bot.chat(`/invsee ${username}`)371}372}373374function itemToString (item) {375if (item) {376return `${item.name} x ${item.count}`377} else {378return '(nothing)'379}380}381382function itemByType (items, type) {383let item384let i385for (i = 0; i < items.length; ++i) {386item = items[i]387if (item && item.type === type) return item388}389return null390}391392function itemByName (items, name) {393let item394let i395for (i = 0; i < items.length; ++i) {396item = items[i]397if (item && item.name === name) return item398}399return null400}401402403