GithubHelp home page GithubHelp logo

prismarinejs / mineflayer Goto Github PK

View Code? Open in Web Editor NEW
4.6K 84.0 841.0 12.05 MB

Create Minecraft bots with a powerful, stable, and high level JavaScript API.

Home Page: https://prismarinejs.github.io/mineflayer/

License: MIT License

JavaScript 100.00%
bot nodejs network minecraft minecraft-bot minecraft-api

mineflayer's Introduction

Mineflayer

NPM version Build Status Try it on gitpod Open In Colab GitHub Sponsors

Official Discord

EN English RU русский ES Español FR Français TR Türkçe ZH 中文 BR Português

Create Minecraft bots with a powerful, stable, and high level JavaScript API, also usable from Python.

First time using Node.js? You may want to start with the tutorial. Know Python? Checkout some Python examples and try out Mineflayer on Google Colab.

Features

  • Supports Minecraft 1.8 to 1.20.4 (1.8, 1.9, 1.10, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19 and 1.20)
  • Entity knowledge and tracking.
  • Block knowledge. You can query the world around you. Milliseconds to find any block.
  • Physics and movement - handle all bounding boxes
  • Attacking entities and using vehicles.
  • Inventory management.
  • Crafting, chests, dispensers, enchantment tables.
  • Digging and building.
  • Miscellaneous stuff such as knowing your health and whether it is raining.
  • Activating blocks and using items.
  • Chat.

Roadmap

Checkout this page to see what our current projects are.

Installation

First install Node.js >= 18 from nodejs.org then:

npm install mineflayer

To update mineflayer (or any Node.js) package and its dependencies, use

npm update --depth 9999

Documentation

link description
tutorial Begin with Node.js and mineflayer
FAQ.md Got a question ? go there first
api.md
unstable_api.md
The full API reference
history.md The changelog for mineflayer
examples/ Checkout all the mineflayer examples

Contribute

Please read CONTRIBUTING.md and prismarine-contribute

Usage

Videos

A tutorial video explaining the basic set up process for a bot can be found here.

If you want to learn more, more video tutorials are there, and the corresponding source codes for those bots is there.

tutorial 1 tutorial 2 tutorial 3 tutorial 4

Getting Started

Without a version specified, the version of the server will be guessed automatically. Without auth specified, the mojang auth style will be guessed.

Echo Example

const mineflayer = require('mineflayer')

const bot = mineflayer.createBot({
  host: 'localhost', // minecraft server ip
  username: 'Bot', // username to join as if auth is `offline`, else a unique identifier for this account. Switch if you want to change accounts
  auth: 'microsoft' // for offline mode servers, you can set this to 'offline'
  // port: 25565,              // set if you need a port that isn't 25565
  // version: false,           // only set if you need a specific version or snapshot (ie: "1.8.9" or "1.16.5"), otherwise it's set automatically
  // password: '12345678'      // set if you want to use password-based auth (may be unreliable). If specified, the `username` must be an email
})

bot.on('chat', (username, message) => {
  if (username === bot.username) return
  bot.chat(message)
})

// Log errors and kick reasons:
bot.on('kicked', console.log)
bot.on('error', console.log)

If auth is set to microsoft, you will be prompted to login to microsoft.com with a code in your browser. After signing in on your browser, the bot will automatically obtain and cache authentication tokens (under your specified username) so you don't have to sign-in again.

To switch the account, update the supplied username. By default, cached tokens will be stored in your user's .minecraft folder, or if profilesFolder is specified, they'll instead be stored there. For more information on bot options see node-minecraft-protocol's API doc.

Connecting to a Realm

To join a Realm that your Minecraft account has been invited to, you can pass a realms object with a selector function like below.

const client = mineflayer.createBot({
  username: '[email protected]', // minecraft username
  realms: {
    // This function is called with an array of Realms the account can join. It should return the one it wants to join.
    pickRealm: (realms) => realms[0]
  },
  auth: 'microsoft'
})

See what your bot is doing

Thanks to the prismarine-viewer project, it's possible to display in a browser window what your bot is doing. Just run npm install prismarine-viewer and add this to your bot:

const { mineflayer: mineflayerViewer } = require('prismarine-viewer')
bot.once('spawn', () => {
  mineflayerViewer(bot, { port: 3007, firstPerson: true }) // port is the minecraft server port, if first person is false, you get a bird's-eye view
})

And you'll get a live view looking like this:

viewer

More Examples

example description
viewer Display your bot world view in the browser
pathfinder Make your bot go to any location automatically
chest Use chests, furnaces, dispensers, enchantment tables
digger Learn how to create a simple bot that is capable of digging blocks
discord Connect a discord bot with a mineflayer bot
jumper Learn how to move, jump, ride vehicles, attack nearby entities
ansi Display your bot's chat with all of the chat colors shown in your terminal
guard Make a bot guard a defined area from nearby mobs
multiple-from-file Add a text file with accounts and have them all login

And many more in the examples folder.

Modules

A lot of the active development is happening inside of small npm packages which are used by mineflayer.

The Node Way™

"When applications are done well, they are just the really application-specific, brackish residue that can't be so easily abstracted away. All the nice, reusable components sublimate away onto github and npm where everybody can collaborate to advance the commons." — substack from "how I write modules"

Modules

These are the main modules that make up mineflayer:

module description
minecraft-protocol Parse and serialize minecraft packets, plus authentication and encryption.
minecraft-data Language independent module providing minecraft data for minecraft clients, servers and libraries.
prismarine-physics Provide the physics engine for minecraft entities
prismarine-chunk A class to hold chunk data for Minecraft
node-vec3 3d vector math with robust unit tests
prismarine-block Represent a minecraft block with its associated data
prismarine-chat A parser for a minecraft chat message (extracted from mineflayer)
node-yggdrasil Node.js library to interact with Mojang's authentication system, known as Yggdrasil
prismarine-world The core implementation of worlds for prismarine
prismarine-windows Represent minecraft windows
prismarine-item Represent a minecraft item with its associated data
prismarine-nbt An NBT parser for node-minecraft-protocol
prismarine-recipe Represent minecraft recipes
prismarine-biome Represent a minecraft biome with its associated data
prismarine-entity Represent a minecraft entity

Debug

You can enable some protocol debugging output using DEBUG environment variable:

DEBUG="minecraft-protocol" node [...]

On windows :

set DEBUG=minecraft-protocol
node your_script.js

Third Party Plugins

Mineflayer is pluggable; anyone can create a plugin that adds an even higher level API on top of Mineflayer.

The most updated and useful are :

  • pathfinder - advanced A* pathfinding with a lot of configurable features
  • prismarine-viewer - simple web chunk viewer
  • web-inventory - web based inventory viewer
  • statemachine - A state machine API for more complex bot behaviors
  • Armor Manager - automatic armor management
  • Dashboard - Frontend dashboard for mineflayer bot
  • PVP - Easy API for basic PVP and PVE.
  • Auto Eat - Automatic eating of food.
  • Auto Crystal - Automatic placing & breaking of end crystals.
  • Tool - A utility for automatic tool/weapon selection with a high level API.
  • Hawkeye - A utility for using auto-aim with bows.
  • GUI - Interact with nested GUI windows using async/await
  • Projectile - Get the required launch angle for projectiles
  • Movement - Smooth and realistic player movement, best suited for PvP
  • Collect Block - Quick and simple block collection API.

But also check out :

  • radar - web based radar interface using canvas and socket.io. YouTube Demo
  • auto-auth - chat-based bot authentication
  • Bloodhound - determine who and what is responsible for damage to another entity
  • tps - get the current tps (processed tps)
  • panorama - take Panorama Images of your world
  • player-death-event - emit player death event in Mineflayer.

Projects Using Mineflayer

Testing

Testing everything

Simply run:

npm test

Testing specific version

Run

npm run mocha_test -- -g <version>

where <version> is a minecraft version like 1.12, 1.15.2...

Testing specific test

Run

npm run mocha_test -- -g <test_name>

where <test_name> is a name of the test like bed, useChests, rayTrace...

Example

npm run mocha_test -- -g "1.18.1.*BlockFinder"

to run the block finder test for 1.18.1

License

MIT

mineflayer's People

Contributors

amoraschi avatar andrewrk avatar corgano avatar darthfett avatar deathcap avatar dependabot[bot] avatar extremeheat avatar frej4189 avatar greenkeeper[bot] avatar greenkeeperio-bot avatar hexatester avatar icetank avatar idanho avatar imharvol avatar karang avatar naomi-alt avatar nevercast avatar pietro210 avatar plexigras avatar roblabla avatar rom1504 avatar rom1504bot avatar sefirosweb avatar thedudefromci avatar thejoshwolfe avatar u5b avatar u9g avatar vogonistic avatar wvffle avatar zuazo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mineflayer's Issues

Creative mode support

When in creative, no damage is taken, digging is instant, and flying is allowed.
Items can be spawned, and blocks in the inventory are infinite. An API for this would be great.

Teach bots what metadata means

Bots want to know which half of the bed you can sleep in. This information is communicated through the metadata. Branch "drill" already has added a metadata field to mf.Block and mf.Item objects 895333f. We need some code somewhere that alleviates the need for scripts to hardcode metadata meanings. This could be as simple as enums in builtin_types.js.

Blocks still in memory after mining

I found this bug using my finder script. If I mine a block, the mf.blockAt function still reports the block as being there, until the chunk is unloaded, then reloaded.

Digging is broken

When I tell a bot to 'flatten' or 'tunnel' or 'drill', the bot is unable to dig any block.

Note: placing blocks works.

handleMultiBlockUpdate sometimes causes QHash iterator crashes

Game::handleMultiBlockUpdate():
Int3D absolute_location = iterator.key();

This line crashes with:
ASSERT: "item_exists()" in file ../../../qtsdk-2010.05/qt/include/QtCore/qhash.h, line 1032

The update is a wooden door swinging on its hinges. It has two blocks in the update, both wooden doors (64), stacked on top of eachother, with metadatas 5 and 13. This makes me think this is related to Issue #11.

Reproduce this problem by running a bot for a while (at least 10 seconds). and then opening/closing a wooden door. Then maybe it will happen. I wonder if it's a race condition.

README headless instructions obsolete?

instead of

EXTRA_CONFIG=headless qmake ../mineflayer/mineflayer.pro
make

it should be

qmake ../mineflayer/mineflayer.pro
EXTRA_CONFIG=headless make

or somesuch, or change mineflayer.pro put EXTRA_CONFIG in the root Makefile.

Unable to jump on top of a block

If I tell a bot to navhere, he gets stuck whenever he has to jump on top of a block. He will continuously jump, repeatedly informing me that he "can get there in X moves".

It seems that he is not jumping high enough.

Torch solution for drill/tunnel fails sometimes

I noticed today on superjoe.zapto.org that because there is delay, the torch solution for digging gravel in a column can sometimes fail. I think the reason is that the bot does not switch tools in time to place the torch. Instead, the bot digs the bot, switches to the torch, the gravel falls, and the bot gets stuck until rebooted.

I suspect that the cause is the combined time of the wait (to avoid the top block staying in place), along with a slow tool-switching operation, though I am not sure how the code is implemented yet.. I have on my todo list to take a look at the builder library's code.

Request: Player List Item (0xC9)

Hi,

1.8 seems to have fetched a few new features and a few hickups.

I'll split my posts out for ease.

I'd like to request the new features brought with 1.8's protocol including 0xC9 and 0xFE - both have stats about the state of the server and the other players currently online.

Exception when connecting to remote server

Around 1 second after it connects, it spits out an error and terminates. Works fine on a local server though.
I got Qt Creator but I'm not sure how to debug scripts.

Every script that connects to this remote server gives the same error.

Launching with:
./mineflayer --debug --url RuansBot@[server]:25565 examples/connection_notice.js

connected
Qt has caught an exception thrown from an event handler. Throwing
exceptions from an event handler is not supported in Qt. You must
reimplement QApplication::notify() and catch all exceptions there.

terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted

dmesg:
[179762.793904] mineflayer[22777]: segfault at 50 ip b66b8ec7 sp b217c2c0 error 4 in libQtCore.so.4.7.4[b665d000+289000]
Also getting this error when my bot gets stuck inside a block.

Segfault when tunneling through the sky

Stand atop a hill looking over a cliff and say "tunnel". Make sure your bot has plenty of cobblestone or dirt.

The bot will build 10 layers or so and then segfault. (tested on localhost)

Don't use bitfields in mineflayer_Block and mineflayer_Item

I'm just commenting to mention that your use of bitfields for sub-byte sizes is not portable or safe, since the actual ordering of the bits, and their storage/alignment/padding varies by system.

Simply put, your packets may suddenly cease to work on other systems/compilers, if those nibbles are individually padded to a full byte (which can happen).

Revert to Notch's coordinate system

It was fun sticking it to the man, but for mineflayer to work as a library, it makes much more sense to stick with the "standard" coordinate system.

Segmentation fault (core dumped) when trying to run one of the examples.

I do this command to run it and it doesn't run.

rymate@ryan-laptop ~/mineflayer/examples

mineflayer --url rymate1234@_______.dyndns.org --password _____ -I../lib/ random_wanderer.js
Got bus address: "unix:abstract=/tmp/dbus-boYALXTqE0,guid=b74a2b10ff268637ba97c8950000007b"
Connected to accessibility bus at: "unix:abstract=/tmp/dbus-boYALXTqE0,guid=b74a2b10ff268637ba97c8950000007b"
Registered DEC: true
Registered event listener change listener: true
Segmentation fault (core dumped)

How to fix this? :(

onEntityAttacked event which is called when one entity is attacking another

Hi. Mineflyaer javascript-engine provides a handlers for some gameplay events like "onChat()" or "onHealthChanged()" etc. Can you add a new event handler like a "onEntityAttacked", this event is called when one entity is attacking another (mob, player or self)? This event is helful to create an bots are strike if they are attacked, for example.

Regards, Cr0s.
P.S. Sorry for my bad english, I'am from Russian Federation.

Mineflayer crashes inconsistently

When I run mineflayer through Qt on Windows, it crashes at seemingly random times. The times it crashes are very inconsistent. Crashes bring up the "Mineflayer.exe has stopped working" windows dialog box.

follower script spamming

the follower.js script spams the player when navigator arrives, and there are no additional tasks. This is also related to task manager's postpone function not resuming correctly.

automated testing?

Would be nice to test:

  • test authentication with minecraft.net
  • test for crafting every recipe
  • test for digging every diggable block
  • test aborting digging for every diggable block
  • test for navigator
  • test for block finder
  • tests for inventory management
  • test for file reading
  • test for player tracker
  • test for sending and receiving chat
  • test animation detection
  • test small chests, large chests, dispenser, furnace
  • test jumping up a block
  • test signs
  • test time of day
  • test sleeping in a bed
  • test health knowledge
  • test looking in a direction
  • test shooting an arrow
  • test killing an entity

1.8 Broke login

Hi,

1.8 seems to have fetched a few new features and a few hickups.

I'll split my posts out for ease.

Aside from issue #23 - the server handshake/login seems to be broken.

Eventually get the message that connecting took too long.

Support native plugins

I'm thinking something like:

var native_library = mf.include_native("libhax.so");

or even:

mf.include("libhax.so");

It's a wild idea, I know. Just thought I'd start a discussion on it. To start, there's an obvious portability issue with the above examples.

Inventory library moving functions inefficient

There is some issues with the inventory library being inefficient when a chest is full. It noticeably clicks every stack in the chest.

The move functions are also due for an overhaul, and should probably support shift-clicking in the overhaul.

Drop the C Library interface

superjoe30 and I have talked about whether to keep maintaining or to drop the C Library interface. We both vote it should be dropped. This would enhance the interaction of the two components of the project and reduce a good deal of code that simply translates between C and C++ constructs.

QThread: Destroyed while thread is still running

This happens during shutdown sometimes and causes intermittent failures in the test suite.

Other such errors are these:

QMutex: mutex destroy failure: Device or resource busy
QWaitCondition::wakeAll(): mutex lock failure: Invalid argument

mineflayer doesn't support shift-clicking inventory items

Mineflayer currently sends 'false' for the "is_shift" value every time any window slot is clicked (see Game::doWindowClick), instead of presenting the javascript with an interface.

I'm not sure what sort of messages get passed between the server when someone shift-clicks (a regular click seems to get a TransactionResponse), but Game::handleTransaction doesn't seem to handle shift-clicks either.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.