Full Code of PrismarineJS/mineflayer for AI

master 89686596c8de cached
239 files
1.2 MB
361.4k tokens
322 symbols
1 requests
Download .txt
Showing preview only (1,328K chars total). Download the full file or copy to clipboard to get everything.
Repository: PrismarineJS/mineflayer
Branch: master
Commit: 89686596c8de
Files: 239
Total size: 1.2 MB

Directory structure:
gitextract_2smm4x0u/

├── .github/
│   ├── FUNDING.yml
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   ├── config.yml
│   │   └── feature_request.md
│   ├── dependabot.yml
│   ├── helper/
│   │   ├── package.json
│   │   └── updator.js
│   └── workflows/
│       ├── ci.yml
│       ├── commands.yml
│       ├── handle-update.yml
│       └── npm-publish.yml
├── .gitignore
├── .gitpod.yml
├── .npmignore
├── .npmrc
├── LICENSE
├── docs/
│   ├── .nojekyll
│   ├── CONTRIBUTING.md
│   ├── FAQ.md
│   ├── README.md
│   ├── _sidebar.md
│   ├── api.md
│   ├── br/
│   │   ├── CONTRIBUTING_BR.md
│   │   ├── FAQ_BR.md
│   │   ├── README_BR.md
│   │   ├── api_br.md
│   │   └── unstable_api_br.md
│   ├── demos.md
│   ├── es/
│   │   ├── CONTRIBUTING_ES.md
│   │   ├── FAQ_ES.md
│   │   ├── README_ES.md
│   │   ├── api_es.md
│   │   └── unstable_api_es.md
│   ├── fr/
│   │   ├── FAQ_FR.md
│   │   └── README_FR.md
│   ├── history.md
│   ├── index.html
│   ├── llm_contribute.md
│   ├── mineflayer.ipynb
│   ├── ru/
│   │   ├── CONTRIBUTING_RU.md
│   │   ├── FAQ_RU.md
│   │   ├── README_RU.md
│   │   ├── _sidebar.md
│   │   ├── api_ru.md
│   │   ├── demos_ru.md
│   │   ├── index.html
│   │   ├── tutorial_ru.md
│   │   └── unstable_api_ru.md
│   ├── tr/
│   │   └── README_TR.md
│   ├── tutorial.md
│   ├── unstable_api.md
│   ├── update_to_1_21_5.md
│   └── zh/
│       ├── CONTRIBUTING.md
│       ├── FAQ.md
│       ├── README_ZH_CN.md
│       ├── _sidebar.md
│       ├── api.md
│       ├── demos.md
│       ├── history.md
│       ├── index.html
│       └── tutorial.md
├── examples/
│   ├── advanced/
│   │   ├── README.md
│   │   └── chest_confirm.md
│   ├── ansi.js
│   ├── anvil.js
│   ├── anvil_saver/
│   │   ├── .npmrc
│   │   ├── package.json
│   │   └── saver.js
│   ├── armor_stand.js
│   ├── attack.js
│   ├── auto-eat.js
│   ├── auto_totem.js
│   ├── bee.js
│   ├── block_entity.js
│   ├── blockfinder.js
│   ├── book.js
│   ├── bossbar.js
│   ├── chat_parsing.js
│   ├── chatterbox.js
│   ├── chest.js
│   ├── cli/
│   │   └── readline.js
│   ├── collectblock.js
│   ├── command_block.js
│   ├── crossbower.js
│   ├── crystal.js
│   ├── digger.js
│   ├── discord.js
│   ├── echo.js
│   ├── elytra.js
│   ├── farmer.js
│   ├── fisherman.js
│   ├── graffiti.js
│   ├── guard.js
│   ├── inventory.js
│   ├── jumper.js
│   ├── looker.js
│   ├── modular_mineflayer/
│   │   ├── index.js
│   │   └── modules/
│   │       └── hello.js
│   ├── multiple.js
│   ├── multiple_from_file.js
│   ├── pathfinder/
│   │   ├── .npmrc
│   │   ├── gps.js
│   │   └── package.json
│   ├── perfectShotBow.js
│   ├── place_end_crystal/
│   │   ├── .npmrc
│   │   ├── index.js
│   │   └── package.json
│   ├── place_entity.js
│   ├── plugins/
│   │   ├── afk.js
│   │   └── hello_world.js
│   ├── python/
│   │   ├── README.md
│   │   ├── basic.py
│   │   └── chatterbox.py
│   ├── quitter.js
│   ├── raycast.js
│   ├── reconnector.js
│   ├── repl.js
│   ├── resourcepack.js
│   ├── scoreboard.js
│   ├── screenshot-with-node-canvas-webgl/
│   │   ├── .dockerignore
│   │   ├── .npmrc
│   │   ├── Dockerfile
│   │   ├── README.md
│   │   ├── package.json
│   │   └── screenshot.js
│   ├── session.js
│   ├── skin_blinker.js
│   ├── skin_data.js
│   ├── sleeper.js
│   ├── sound.js
│   ├── tab_complete.js
│   ├── telegram.js
│   ├── titles.js
│   ├── trader.js
│   └── viewer/
│       ├── .npmrc
│       ├── README.md
│       ├── package.json
│       └── viewer.js
├── index.d.ts
├── index.js
├── lib/
│   ├── bossbar.js
│   ├── conversions.js
│   ├── loader.js
│   ├── location.js
│   ├── math.js
│   ├── painting.js
│   ├── particle.js
│   ├── plugin_loader.js
│   ├── plugins/
│   │   ├── anvil.js
│   │   ├── bed.js
│   │   ├── block_actions.js
│   │   ├── blocks.js
│   │   ├── book.js
│   │   ├── boss_bar.js
│   │   ├── breath.js
│   │   ├── chat.js
│   │   ├── chest.js
│   │   ├── command_block.js
│   │   ├── craft.js
│   │   ├── creative.js
│   │   ├── digging.js
│   │   ├── enchantment_table.js
│   │   ├── entities.js
│   │   ├── experience.js
│   │   ├── explosion.js
│   │   ├── fishing.js
│   │   ├── furnace.js
│   │   ├── game.js
│   │   ├── generic_place.js
│   │   ├── health.js
│   │   ├── inventory.js
│   │   ├── kick.js
│   │   ├── particle.js
│   │   ├── physics.js
│   │   ├── place_block.js
│   │   ├── place_entity.js
│   │   ├── rain.js
│   │   ├── ray_trace.js
│   │   ├── resource_pack.js
│   │   ├── scoreboard.js
│   │   ├── settings.js
│   │   ├── simple_inventory.js
│   │   ├── sound.js
│   │   ├── spawn_point.js
│   │   ├── tablist.js
│   │   ├── team.js
│   │   ├── time.js
│   │   ├── title.js
│   │   └── villager.js
│   ├── promise_utils.js
│   ├── scoreboard.js
│   ├── team.js
│   └── version.js
├── package.json
├── test/
│   ├── common/
│   │   └── util.js
│   ├── externalTest.js
│   ├── externalTests/
│   │   ├── anvil.js
│   │   ├── bed.js
│   │   ├── book.js
│   │   ├── bossBar.js
│   │   ├── breath.js
│   │   ├── chat.js
│   │   ├── commandBlock.js
│   │   ├── complete.js
│   │   ├── consume.js
│   │   ├── crafting.js
│   │   ├── creative.js
│   │   ├── digAndBuild.js
│   │   ├── digEverything.js
│   │   ├── dimensionName.js
│   │   ├── displayName.js
│   │   ├── elytra.js
│   │   ├── enchanting.js
│   │   ├── exampleBee.js
│   │   ├── exampleBlockFinder.js
│   │   ├── exampleDigger.js
│   │   ├── exampleInventory.js
│   │   ├── experience.js
│   │   ├── fishing.js
│   │   ├── furnace.js
│   │   ├── gamemode.js
│   │   ├── heldItem.js
│   │   ├── nether.js
│   │   ├── particles.js
│   │   ├── placeEntity.js
│   │   ├── plugins/
│   │   │   └── testCommon.js
│   │   ├── rain.js
│   │   ├── rayTrace.js
│   │   ├── scoreboard.js
│   │   ├── sign.js
│   │   ├── sound.js
│   │   ├── spawnEvent.js
│   │   ├── team.js
│   │   ├── time.js
│   │   ├── title.js
│   │   ├── trade.js
│   │   └── useChests.js
│   └── internalTest.js
└── tsconfig.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms
open_collective: prismarinejs
custom: https://rysolv.com/repos/detail/74691b23-938d-4b2f-b65a-5c47bf5b3f0f
github: PrismarineJS


================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: possible bug,Stage1
assignees: ''

---

- [ ] The [FAQ](https://github.com/PrismarineJS/mineflayer/blob/master/docs/FAQ.md) doesn't contain a resolution to my issue 

## Versions
 - mineflayer: #.#.#
 - server: vanilla/spigot/paper #.#.#
 - node: #.#.#

## Detailed description of a problem
A clear and concise description of what the problem is, with as much context as possible.
What are you building? What problem are you trying to solve?

## What did you try yet?

Did you try any method from the API?
Did you try any example? Any error from those?

## Your current code
```js

/*
Some code here, replace this
*/


```

## Expected behavior
A clear and concise description of what you expected to happen.

## Additional context
Add any other context about the problem here.


================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
  - name: Github Discussions
    url: https://github.com/PrismarineJS/mineflayer/discussions
    about: Please make a post in our Github Discussions for questions and support requests.


================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: new feature,Stage1
assignees: ''

---

## Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

## Describe the solution you'd like
A clear and concise description of what you want to happen.

## Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

## Additional context
Add any other context or screenshots about the feature request here.


================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
- package-ecosystem: npm
  directory: "/"
  schedule:
    interval: daily
  open-pull-requests-limit: 10
  ignore:
  - dependency-name: "@types/node"
    versions:
    - 15.0.0


================================================
FILE: .github/helper/package.json
================================================
{
  "dependencies": {
    "gh-helpers": "^1.0.0"
  }
}

================================================
FILE: .github/helper/updator.js
================================================
#!/usr/bin/env node
/**
 * Updator script triggered from minecraft-data repository to auto generate PR
 */
const fs = require('fs')
const cp = require('child_process')
const assert = require('assert')
const github = require('gh-helpers')()
const { join } = require('path')
const exec = (cmd) => github.mock ? console.log('> ', cmd) : (console.log('> ', cmd), cp.execSync(cmd, { stdio: 'inherit' }))

console.log('Starting update process...')
// Sanitize and validate environment variables all non alpha numeric / underscore / dot
const newVersion = process.env.NEW_MC_VERSION?.replace(/[^a-zA-Z0-9_.]/g, '_')
const triggerBranch = process.env.MCDATA_BRANCH?.replace(/[^a-zA-Z0-9_.]/g, '_')
const mcdataPrURL = process.env.MCDATA_PR_URL
console.log({ newVersion, triggerBranch, mcdataPrURL })

assert(newVersion)
assert(triggerBranch)

async function main () {
  const currentSupportedPath = require.resolve('../../lib/version.js')
  const readmePath = join(__dirname, '../../docs/README.md')
  const ciPath = join(__dirname, '../../.github/workflows/ci.yml')

  // Update the version.js
  const currentSupportedVersion = require('../../lib/version.js')
  const currentContents = fs.readFileSync(currentSupportedPath, 'utf8')
  console.log('Current supported version:', currentContents)
  const latestV = currentSupportedVersion.testedVersions.at(-1)
  const newContents = currentContents.includes(newVersion)
    ? currentContents
    : currentContents
      .replace(`, '${latestV}'`, `, '${latestV}', '${newVersion}'`)

  // Update the README.md
  const currentContentsReadme = fs.readFileSync(readmePath, 'utf8')
  if (!currentContentsReadme.includes(newVersion)) {
    const newReadmeContents = currentContentsReadme
      .replace(/Minecraft 1\.8 to [0-9A-Za-z._-]+ \(/, `Minecraft 1.8 to ${newVersion} (`)
      .replace(') <!--version-->', `, ${newVersion}) <!--version-->`)
    fs.writeFileSync(readmePath, newReadmeContents)
    console.log('Updated README with new version:', newVersion)
  }
  fs.writeFileSync(currentSupportedPath, newContents)

  // Update the CI workflow
  const currentContentsCI = fs.readFileSync(ciPath, 'utf8')
  if (!currentContentsCI.includes(newVersion)) {
    const newCIContents = currentContentsCI.replace(
      'run: npm install', `run: npm install
      - run: cd node_modules && cd minecraft-data && mv minecraft-data minecraft-data-old && git clone -b ${triggerBranch} https://github.com/PrismarineJS/minecraft-data --depth 1 && node bin/generate_data.js
      - run: curl -o node_modules/protodef/src/serializer.js https://raw.githubusercontent.com/extremeheat/node-protodef/refs/heads/dlog/src/serializer.js && curl -o node_modules/protodef/src/compiler.js https://raw.githubusercontent.com/extremeheat/node-protodef/refs/heads/dlog/src/compiler.js
`)
    fs.writeFileSync(ciPath, newCIContents)
    console.log('Updated CI workflow with new version:', newVersion)
  }

  const branchName = 'pc' + newVersion.replace(/[^a-zA-Z0-9_]/g, '_')
  exec(`git checkout -b ${branchName}`)
  exec('git config user.name "github-actions[bot]"')
  exec('git config user.email "41898282+github-actions[bot]@users.noreply.github.com"')
  exec('git add --all')
  exec(`git commit -m "Update to version ${newVersion}"`)
  exec(`git push origin ${branchName} --force`)
  //     createPullRequest(title: string, body: string, fromBranch: string, intoBranch?: string): Promise<{ number: number, url: string }>;
  const pr = await github.createPullRequest(
    `🎈 ${newVersion}`,
    `This automated PR sets up the relevant boilerplate for Minecraft version ${newVersion}.

Ref: ${mcdataPrURL}

* You can help contribute to this PR by opening a PR against this <code branch>${branchName}</code> branch instead of <code>master</code>.
    `,
    branchName,
    'master'
  )
  console.log(`Pull request created`, pr)
}

main().catch(err => {
  console.error('Error during update process:', err)
  process.exit(1)
})


================================================
FILE: .github/workflows/ci.yml
================================================
name: CI

on:
  push:
    branches:
      - master
  pull_request:

jobs:
  Lint:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js 22.x
      uses: actions/setup-node@v1.4.4
      with:
        node-version: 22.x
    - run: npm i && npm run lint
  
  PrepareSupportedVersions:
    runs-on: ubuntu-latest
    outputs:
      matrix: ${{ steps.set-matrix.outputs.matrix }}

    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js 22.x
      uses: actions/setup-node@v1.4.4
      with:
        node-version: 22.x
    - id: set-matrix
      run: |
        node -e "
          const testedVersions = require('./lib/version').testedVersions;
          console.log('matrix='+JSON.stringify({'include': testedVersions.map(mcVersion => ({mcVersion}))}))
        " >> $GITHUB_OUTPUT

  MinecraftServer:
    needs: PrepareSupportedVersions
    runs-on: ubuntu-latest
    strategy:
      matrix: ${{fromJson(needs.PrepareSupportedVersions.outputs.matrix)}}
      fail-fast: false

    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js 22.x
        uses: actions/setup-node@v1.4.4
        with:
          node-version: 22.x
      - name: Setup Java JDK
        uses: actions/setup-java@v1.4.3
        with:
          java-version: 21
          java-package: jre
      - name: Install Dependencies
        run: npm install

      - name: Start Tests
        run: npm run mocha_test -- -g ${{ matrix.mcVersion }}v


================================================
FILE: .github/workflows/commands.yml
================================================
name: Repo Commands

on:
  issue_comment:        # Handle comment commands
    types: [created]
  pull_request:         # Handle renamed PRs
    types: [edited]

jobs:
  comment-trigger:
    runs-on: ubuntu-latest
    steps:
    - name: Check out repository
      uses: actions/checkout@v3
    - name: Run command handlers
      uses: PrismarineJS/prismarine-repo-actions@master
      with:
        # NOTE: You must specify a Personal Access Token (PAT) with repo access here. While you can use the default GITHUB_TOKEN, actions taken with it will not trigger other actions, so if you have a CI workflow, commits created by this action will not trigger it.
        token: ${{ secrets.PAT_PASSWORD }}
        # See `Options` section below for more info on these options
        install-command: npm install
        /fixlint.fix-command: npm run fix

================================================
FILE: .github/workflows/handle-update.yml
================================================
name: Update from minecraft-data

on:
  workflow_dispatch:
    inputs:
      new_mc_version:
        description: New minecraft version number
        required: true
        type: string
      mcdata_branch:
        description: minecraft-data branch for this version
        required: true
        type: string
      mcdata_pr_url:
        description: minecraft-data PR number to open a PR here against
        required: false
        default: ''
        type: string
      nmp_branch:
        description: minecraft-protocol branch for this version
        required: true
        type: string
      nmp_pr_url:
        description: minecraft-protocol PR number to open a PR here against
        required: false
        default: ''
        type: string

jobs:
  update:
    runs-on: ubuntu-latest
    
    steps:
    - name: Checkout repository
      uses: actions/checkout@v4
      with:
        token: ${{ secrets.PAT_PASSWORD }}

    - name: Use Node.js 22.x
      uses: actions/setup-node@v1.4.4
      with:
        node-version: 22.x

    - run: npm install PrismarineJS/node-minecraft-protocol#${{ github.event.inputs.nmp_branch }}

    - name: Run updator script
      run: cd .github/helper && npm install && node updator.js
      env:
        GITHUB_TOKEN: ${{ secrets.PAT_PASSWORD }}
        NEW_MC_VERSION: ${{ github.event.inputs.new_mc_version }}
        MCDATA_BRANCH: ${{ github.event.inputs.mcdata_branch }}
        MCDATA_PR_URL: ${{ github.event.inputs.mcdata_pr_url }}
        NMP_BRANCH: ${{ github.event.inputs.nmp_branch }}
        NMP_PR_URL: ${{ github.event.inputs.nmp_pr_url }}


================================================
FILE: .github/workflows/npm-publish.yml
================================================
name: npm-publish
on:
  push:
    branches:
      - master # Change this to your default branch
jobs:
  npm-publish:
    name: npm-publish
    runs-on: ubuntu-latest
    steps:
    - name: Checkout repository
      uses: actions/checkout@master
    - name: Set up Node.js
      uses: actions/setup-node@master
      with:
        node-version: 22.0.0
    - id: publish
      uses: JS-DevTools/npm-publish@v1
      with:
        token: ${{ secrets.NPM_AUTH_TOKEN }}
    - name: Create Release
      if: steps.publish.outputs.type != 'none'
      id: create_release
      uses: actions/create-release@v1
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      with:
        tag_name: ${{ steps.publish.outputs.version }}
        release_name: Release ${{ steps.publish.outputs.version }}
        body: ${{ steps.publish.outputs.version }}
        draft: false
        prerelease: false


================================================
FILE: .gitignore
================================================
# shared with .npmignore
# different than .npmignore
node_modules
package-lock.json
yarn.lock
/README.md
versions/
server_jars/
test/server_*
.vscode
.DS_Store
launcher_accounts.json
data

================================================
FILE: .gitpod.yml
================================================
tasks:
- command: npm install && sdk install java


================================================
FILE: .npmignore
================================================
# shared with .gitignore
# different than .gitignore
test


================================================
FILE: .npmrc
================================================
engine-strict=true
package-lock=false


================================================
FILE: LICENSE
================================================
The MIT License (MIT)

Copyright (c) 2015 Andrew Kelley

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: docs/.nojekyll
================================================


================================================
FILE: docs/CONTRIBUTING.md
================================================
# Contribute

Mineflayer has originally been made mostly by [andrewrk](http://github.com/andrewrk)
but has since then be improved and fixed by many [contributors](https://github.com/andrewrk/mineflayer/graphs/contributors).
That's why it is important to know the best ways to contribute to mineflayer.

## Issue organization

We have 3 stage labels to try to organize issues:

* Stage 1: just created by someone new to the project, we don't know yet if it deserves an implementation / a fix
* Stage 2: promising idea, but needs more thinking before implementation
* Stage 3: idea is precisely specified, only coding is left to do

Links like https://github.com/PrismarineJS/mineflayer/issues?q=is%3Aopen+is%3Aissue+-label%3AStage1 can be used to filter out stage 1 if you're looking for things that are ready for contribution

## Creating tests
Mineflayer has two kind of tests :

 * [internal tests](test/internalTest.js) : tests that are done against a simple server created with node-minecraft-protocol
 * [external tests](test/externalTests/) : tests that are done against the vanilla server
 
The objective of these tests is to know automatically what works and what doesn't in mineflayer, so it's easier to make mineflayer work.


## Running tests
You can run tests for Different Minecraft versions using the `-g` flag with npm run mocha_test. For example:

```bash
# Run all tests in all supported versions
npm run test

# Run a specific test in Minecraft 1.20.4
npm run mocha_test -- -g "mineflayer_external 1.20.4v.*exampleBee"

# Run all tests in just version 1.20.4
npm run mocha_test -- -g "mineflayer_external 1.20.4v"
```


### Creating an external test

In order to add an external test now you only need to create a file in [test/externalTests](test/externalTests)

An example : [test/externalTests/digAndBuild.js](https://github.com/PrismarineJS/mineflayer/blob/master/test/externalTests/digAndBuild.js)

That file needs to export a function returning a function or an array of function taking as parameter the bot object and a done callback,
 it should contain asserts to test if the tested functionality failed.


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

Several such third party plugins have already been [created](https://github.com/andrewrk/mineflayer#third-party-plugins)

In order to create a new one you need to :

1. create a new repo
2. in your index.js file, exports an init function taking in argument mineflayer ([example](https://github.com/andrewrk/mineflayer-navigate/blob/e24cb6a868ce64ae43bea2d035832c15ed01d301/index.js#L18))
3. that function returns a inject function taking in argument the bot object ([example](https://github.com/andrewrk/mineflayer-navigate/blob/e24cb6a868ce64ae43bea2d035832c15ed01d301/index.js#L23))
4. that inject function add functionalities to the bot object ([example](https://github.com/andrewrk/mineflayer-navigate/blob/e24cb6a868ce64ae43bea2d035832c15ed01d301/index.js#L32))

Since the mineflayer object is passed in parameter, that new package doesn't need to depend on mineflayer (no mineflayer dependency in the package.json)

See a [full example](https://github.com/andrewrk/mineflayer-navigate/tree/e24cb6a868ce64ae43bea2d035832c15ed01d301) here.

## Reporting bugs
Mineflayer works well for most usages, but it sometimes still has bugs.

When finding one it's best to report an issue providing these information :

* what you want to do (the objective in english)
* what you tried (the code)
* what happened
* what you expected to happen

## Mineflayer code
Some things to think about when submitting a Pull Request or making a commit :

### Error handling
In most cases, mineflayer shouldn't crash the bot. Even if something fails, the bot can take an alternative route to get to its objective.

What that means is we shouldn't use `throw(new Error("error"))` but instead use the node.js convention of passing the error in the callback.

For example : 

```js
function myfunction (param1, callback) {
  // do stuff
  let toDo = 1
  toDo = 2
  if (toDo === 2) { // everything worked
    callback()
  } else {
    callback(new Error('something failed'))
  }
}
```

See an other example of that in [mineflayer code](https://github.com/andrewrk/mineflayer/blob/a8736c4ea473cf1a609c5a29046c0cdad006d429/lib/plugins/bed.js#L10)

### Updating the documentation
The table of content of docs/api.md is made with doctoc. After updating that file, you should run doctoc docs/api.md to update the table of content.


================================================
FILE: docs/FAQ.md
================================================
## FAQ

This Frequently Asked Question document is meant to help people for the most common things.

### I get an error (ie. protocol/data) when bot is trying to connect to minecraft server

Make sure the Minecraft server version is supported (cf. root readme), else you should retry using one of the [mineflayer tested versions](../lib/version.js).

### I get an error when trying to login with a microsoft account.

Make sure the email you entered into the username option in createBot can be used to login to `minecraft.net` using the 'Login with Microsoft' button.
Make sure you have the option `auth: 'microsoft'` in your createBot options. 

When you get an error that says something about invalid credentials or 'Does this account own Minecraft?' try removing the password field in the `createBot` options and try again.

### How to hide errors ?

Use `hideErrors: true` in createBot options
You may also choose to add these listeners :
```js
client.on('error', () => {})
client.on('end', () => {})
```

### I'm not getting chat event on a custom server, how can I solve it ?

Spigot servers, in particular some plugins, use custom chat formats, you need to parse it with a custom regex / parser.
Read and adapt [chat_parsing.js](https://github.com/PrismarineJS/mineflayer/blob/master/examples/chat_parsing.js) to make it work for your particular
chat plugin. Also read http://prismarinejs.github.io/mineflayer/#/tutorial?id=custom-chat

### How can I collect info from an custom plugin in chat ?

Most custom minecraft servers have plugin support, and a lot of these plugins say something in chat when something happens. If it is just one message, it's best to use the solution discussed in the solution above, but when these messages are split into many small messages, another option is using the `"messagestr"` event as it allows for easily parsing multi-line messages.

**Example:**

chat message in chat looks like:
```
(!) U9G has won the /jackpot and received
$26,418,402,450! They purchased 2,350,000 (76.32%) ticket(s) out of the
3,079,185 ticket(s) sold!
```
```js
const regex = {
  first: /\(!\) (.+) has won the \/jackpot and received +/,
  second: /\$(.+)! They purchased (.+) \((.+)%\) ticket\(s\) out of the /,
  third: /(.+) ticket\(s\) sold!/
}

let jackpot = {}
bot.on('messagestr', msg => {
  if (regex.first.test(msg)) {
    const username = msg.match(regex.first)[1]
    jackpot.username = username
  } else if (regex.second.test(msg)) {
    const [, moneyWon, boughtTickets, winPercent] = msg.match(regex.second)
    jackpot.moneyWon = parseInt(moneyWon.replace(/,/g, ''))
    jackpot.boughtTickets = parseInt(boughtTickets.replace(/,/g, ''))
    jackpot.winPercent = parseFloat(winPercent)
  } else if (regex.third.test(msg)) {
    const totalTickets = msg.match(regex.third)[1]
    jackpot.totalTickets = parseInt(totalTickets.replace(/,/g, ''))
    onDone(jackpot)
    jackpot = {}
  }
})
```
### How can I send a command ?

By using `bot.chat()`.

**Example:**
```js
bot.chat('/give @p diamond')
```

### Is it possible to login multiple accounts using bot = mineflayer.createbot while controlling them all separately ?

Create different bot instances by calling createBot then do different things for each, see multiple.js

### How would I make the bot drop it's entire inventory?

bot.inventory.items() returns an array of the bot's items. You can use a recursive function to loop through them and drop every item using bot.toss(). Click [here](https://gist.github.com/dada513/3d88f772be4224b40f9e5d1787bd63e9) to see an example

### How do I check packets that are sent/received ?

Enabled debug mode https://github.com/PrismarineJS/mineflayer#debug

### I want to avoid disconnection even in case of server lag, how can I achieve this ?

One way is to increase the [checkTimeoutInterval](https://github.com/PrismarineJS/node-minecraft-protocol/blob/master/docs/API.md#mccreateclientoptions) option (to set in createBot) to an higher value (for example `300*1000` which is 5min instead of the default 30s). If you still get disconnected, you can auto reconnect using something like this example https://github.com/PrismarineJS/mineflayer/blob/master/examples/reconnector.js

### How to get the lore / text of an item ?

You can use the `item.nbt` property. It is also recommended to use the `prismarine-nbt` library. The `nbt.simplify()` method may be useful.

**Example:**
```js
function getLore (item) {
  let message = ''
  if (item.nbt == null) return message

  const nbt = require('prismarine-nbt')
  const ChatMessage = require('prismarine-chat')(bot.version)

  const data = nbt.simplify(item.nbt)
  const display = data.display
  if (display == null) return message

  const lore = display.Lore
  if (lore == null) return message
  for (const line of lore) {
    message += new ChatMessage(line).toString()
    message += '\n'
  }

  return message
}
```

### How can I send message from the console to the server?

You can use a library like `repl` to read the console input and use `bot.chat()` to send it. You can find an example [here.](https://github.com/PrismarineJS/mineflayer/blob/master/examples/repl.js)

### When creating a plugin, how can I specify another plugin as a dependency?

In the `inject()` function for your plugin, you can safely call `bot.loadPlugin(anotherPlugin)` to make sure that plugin is loaded. If the plugin was already loaded before, nothing happens.

Note that the order in which plugins are loaded is dynamic, so you should never call another plugin in your `inject()` function.

### How can I use a socks5 proxy?

In the options object for `mineflayer.createBot(options)`, remove your `host` option from the options object, have the following variables declared `PROXY_IP, PROXY_PORT, PROXY_USERNAME, PROXY_PASSWORD, MC_SERVER_ADDRESS, MC_SERVER_PORT` and add this to your options object:
```js
connect: (client) => {
    socks.createConnection({
      proxy: {
        host: PROXY_IP,
        port: PROXY_PORT,
        type: 5,
        userId: PROXY_USERNAME,
        password: PROXY_PASSWORD
      },
      command: 'connect',
      destination: {
        host: MC_SERVER_ADDRESS,
        port: MC_SERVER_PORT
      }
    }, (err, info) => {
      if (err) {
        console.log(err)
        return
      }
      client.setSocket(info.socket)
      client.emit('connect')
    })
  }
  ```
  `socks` is declared with `const socks = require('socks').SocksClient` and uses [this](https://www.npmjs.com/package/socks) package.
  Some servers might reject the connection. If that happens try adding `fakeHost: MC_SERVER_ADDRESS` to your createBot options.
  
# Common Errors

### `UnhandledPromiseRejectionWarning: Error: Failed to read asymmetric key`

This is what happens when either you gave mineflayer the wrong server version, or mineflayer detects the wrong server version

### `TypeError: Cannot read property '?' of undefined`

You may be trying to use something on the bot object that isn't there yet, try calling the statement after the `spawn` event

### `SyntaxError: Unexpected token '?'`

Update your node version.

### The bot can't break/place blocks or open chests

Check that spawn protection isn't stopping the bot from it's action



================================================
FILE: docs/README.md
================================================
# Mineflayer

[![NPM version](https://img.shields.io/npm/v/mineflayer.svg?color=success&label=npm%20package&logo=npm)](https://www.npmjs.com/package/mineflayer)
[![Build Status](https://img.shields.io/github/actions/workflow/status/PrismarineJS/mineflayer/ci.yml.svg?label=CI&logo=github&logoColor=lightgrey)](https://github.com/PrismarineJS/mineflayer/actions?query=workflow%3A%22CI%22)
[![Try it on gitpod](https://img.shields.io/static/v1.svg?label=try&message=on%20gitpod&color=brightgreen&logo=gitpod)](https://gitpod.io/#https://github.com/PrismarineJS/mineflayer)
[![Open In Colab](https://img.shields.io/static/v1.svg?label=open&message=on%20colab&color=blue&logo=google-colab)](https://colab.research.google.com/github/PrismarineJS/mineflayer/blob/master/docs/mineflayer.ipynb)
[![GitHub Sponsors](https://img.shields.io/github/sponsors/PrismarineJS)](https://github.com/sponsors/PrismarineJS)

[![Official Discord](https://img.shields.io/static/v1.svg?label=OFFICIAL&message=DISCORD&color=blue&logo=discord&style=for-the-badge)](https://discord.gg/GsEFRM8)

| <sub>EN</sub> [English](README.md) | <sub>RU</sub> [русский](ru/README_RU.md) | <sub>ES</sub> [Español](es/README_ES.md) | <sub>FR</sub> [Français](fr/README_FR.md) | <sub>TR</sub> [Türkçe](tr/README_TR.md) | <sub>ZH</sub> [中文](zh/README_ZH_CN.md) | <sub>BR</sub> [Português](br/README_BR.md) |
|-------------------------|----------------------------|----------------------------|----------------------------|----------------------------|-------------------------|--------------------|

Create Minecraft bots with a powerful, stable, and high level JavaScript [API](api.md), also usable from Python.

First time using Node.js? You may want to start with the [tutorial](tutorial.md). Know Python? Checkout some [Python examples](https://github.com/PrismarineJS/mineflayer/tree/master/examples/python) and try out [Mineflayer on Google Colab](https://colab.research.google.com/github/PrismarineJS/mineflayer/blob/master/docs/mineflayer.ipynb).

## Features

 * Supports Minecraft 1.8 to 1.21.11 (1.8, 1.9, 1.10, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19, 1.20, 1.21, 1.21.9, 1.21.11) <!--version-->
 * 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](https://github.com/PrismarineJS/mineflayer/wiki/Big-Prismarine-projects) to see what our current projects are.

## Installation

First install Node.js >= 18 from [nodejs.org](https://nodejs.org/) then:

```bash
npm install mineflayer
```

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

## Documentation

| link | description |
|---|---|
|[tutorial](tutorial.md) | Begin with Node.js and mineflayer |
| [FAQ.md](FAQ.md) | Got a question ? go there first |
| **[api.md](api.md)** <br/>[unstable_api.md](unstable_api.md) | The full API reference |
| [history.md](history.md) | The changelog for mineflayer |
| [examples/](https://github.com/PrismarineJS/mineflayer/tree/master/examples) | Checkout all the mineflayer examples |


## Contribute

Please read [CONTRIBUTING.md](CONTRIBUTING.md) and [prismarine-contribute](https://github.com/PrismarineJS/prismarine-contribute)

## Usage

**Videos**

A tutorial video explaining the basic set up process for a bot can be found [here.](https://www.youtube.com/watch?v=ltWosy4Z0Kw)

If you want to learn more, more video tutorials are [there,](https://www.youtube.com/playlist?list=PLh_alXmxHmzGy3FKbo95AkPp5D8849PEV) and the corresponding source codes for those bots is [there.](https://github.com/TheDudeFromCI/Mineflayer-Youtube-Tutorials)

[<img src="https://img.youtube.com/vi/ltWosy4Z0Kw/0.jpg" alt="tutorial 1" width="200">](https://www.youtube.com/watch?v=ltWosy4Z0Kw)
[<img src="https://img.youtube.com/vi/UWGSf08wQSc/0.jpg" alt="tutorial 2" width="200">](https://www.youtube.com/watch?v=UWGSf08wQSc)
[<img src="https://img.youtube.com/vi/ssWE0kXDGJE/0.jpg" alt="tutorial 3" width="200">](https://www.youtube.com/watch?v=ssWE0kXDGJE)
[<img src="https://img.youtube.com/vi/walbRk20KYU/0.jpg" alt="tutorial 4" width="200">](https://www.youtube.com/watch?v=walbRk20KYU)

**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
```js
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](https://github.com/PrismarineJS/node-minecraft-protocol/blob/master/docs/API.md#mccreateclientoptions).

#### 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.

```js
const client = mineflayer.createBot({
  username: 'email@example.com', // 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](https://github.com/PrismarineJS/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:
```js
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:

[<img src="https://prismarinejs.github.io/prismarine-viewer/test_1.16.1.png" alt="viewer" width="500">](https://prismarinejs.github.io/prismarine-viewer/)

#### More Examples

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

And many more in the [examples](https://github.com/PrismarineJS/mineflayer/tree/master/examples) folder.

### Modules

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

#### The Node Way&trade;

> "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"](https://gist.github.com/substack/5075355)

#### Modules

These are the main modules that make up mineflayer:

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


### Debug

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

```bash
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 :

 * [minecraft-mcp-server](https://github.com/yuniko-software/minecraft-mcp-server) A MCP server for mineflayer, allowing using mineflayer from an LLM
 * [pathfinder](https://github.com/Karang/mineflayer-pathfinder) - advanced A* pathfinding with a lot of configurable features
 * [prismarine-viewer](https://github.com/PrismarineJS/prismarine-viewer) - simple web chunk viewer
 * [web-inventory](https://github.com/ImHarvol/mineflayer-web-inventory) - web based inventory viewer
 * [statemachine](https://github.com/PrismarineJS/mineflayer-statemachine) - A state machine API for more complex bot behaviors
 * [Armor Manager](https://github.com/G07cha/MineflayerArmorManager) - automatic armor management
 * [Dashboard](https://github.com/wvffle/mineflayer-dashboard) - Frontend dashboard for mineflayer bot
 * [PVP](https://github.com/PrismarineJS/mineflayer-pvp) - Easy API for basic PVP and PVE.
 * [Auto Eat](https://github.com/link-discord/mineflayer-auto-eat) - Automatic eating of food.
 * [Auto Crystal](https://github.com/link-discord/mineflayer-autocrystal) - Automatic placing & breaking of end crystals.
 * [Tool](https://github.com/TheDudeFromCI/mineflayer-tool) - A utility for automatic tool/weapon selection with a high level API.
 * [Hawkeye](https://github.com/sefirosweb/minecraftHawkEye) - A utility for using auto-aim with bows.
 * [GUI](https://github.com/firejoust/mineflayer-GUI) - Interact with nested GUI windows using async/await
 * [Projectile](https://github.com/firejoust/mineflayer-projectile) - Get the required launch angle for projectiles
 * [Movement](https://github.com/firejoust/mineflayer-movement) - Smooth and realistic player movement, best suited for PvP
 * [Collect Block](https://github.com/PrismarineJS/mineflayer-collectblock) - Quick and simple block collection API.

 But also check out :

 * [radar](https://github.com/andrewrk/mineflayer-radar/) - web based radar
   interface using canvas and socket.io. [YouTube Demo](https://www.youtube.com/watch?v=FjDmAfcVulQ)
 * [auto-auth](https://github.com/G07cha/MineflayerAutoAuth) - chat-based bot authentication
 * [Bloodhound](https://github.com/Nixes/mineflayer-bloodhound) - determine who and what is responsible for damage to another entity
 * [tps](https://github.com/SiebeDW/mineflayer-tps) - get the current tps (processed tps)
 * [panorama](https://github.com/IceTank/mineflayer-panorama) - take Panorama Images of your world
 * [player-death-event](https://github.com/tuanzisama/mineflayer-death-event) - emit player death event in Mineflayer.

## Projects Using Mineflayer

 * [Voyager](https://github.com/MineDojo/Voyager) An Open-Ended Embodied Agent with Large Language Models
 * [mindcraft](https://github.com/kolbytn/mindcraft) Lib for using mineflayer with LLMs
 * [rom1504/rbot](https://github.com/rom1504/rbot)
   - [YouTube - building a spiral staircase](https://www.youtube.com/watch?v=UM1ZV5200S0)
   - [YouTube - replicating a building](https://www.youtube.com/watch?v=0cQxg9uDnzA)
 * [Darthfett/Helperbot](https://github.com/Darthfett/Helperbot)
 * [vogonistic/voxel](https://github.com/vogonistic/mineflayer-voxel) - visualize what
   the bot is up to using voxel.js
 * [JonnyD/Skynet](https://github.com/JonnyD/Skynet) -  log player activity onto an online API
 * [MinecraftChat](https://github.com/rom1504/MinecraftChat) (last open source version, built by AlexKvazos) -  Minecraft web based chat client
 * [Cheese Bot](https://github.com/Minecheesecraft/Cheese-Bot) - Plugin based bot with a clean GUI. Made with Node-Webkit.
 * [Chaoscraft](https://github.com/schematical/chaoscraft) - Minecraft bot using genetic algorithms, see [its youtube videos](https://www.youtube.com/playlist?list=PLLkpLgU9B5xJ7Qy4kOyBJl5J6zsDIMceH)
 * [hexatester/minetelegram](https://github.com/hexatester/minetelegram) -  Minecraft - Telegram bridge, build on top of mineflayer & telegraf.
 * [PrismarineJS/mineflayer-builder](https://github.com/PrismarineJS/mineflayer-builder) - Prints minecraft schematics in survival, keeping orientation
 * [SilkePilon/OpenDeliveryBot](https://github.com/SilkePilon/OpenDeliveryBot) - Minecraft bot in python to deliver items from place to place.
 * [and hundreds more](https://github.com/PrismarineJS/mineflayer/network/dependents) - All the projects that github detected are using mineflayer


## Testing

### Testing everything

Simply run: 

```bash
npm test
```

### Testing specific version
Run 

```bash
npm run mocha_test -- -g <version>
```

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

### Testing specific test
Run 

```bash
npm run mocha_test -- -g <test_name>
```

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

### Example

```bash
npm run mocha_test -- -g "1.18.1.*BlockFinder"
```
to run the block finder test for 1.18.1

## License

[MIT](/LICENSE)


================================================
FILE: docs/_sidebar.md
================================================
- Getting Started
  - [Introduction](/)
  - [API](api.md)
  - [FAQ](FAQ.md)
  - [Demos](demos.md)
  - [Tutorial](tutorial.md)
  - [Unstable API](unstable_api.md)
  - [Contribute](CONTRIBUTING.md)
  - [History](history.md)

================================================
FILE: docs/api.md
================================================
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents**  *generated with [DocToc](https://github.com/thlorenz/doctoc)*

- [API](#api)
  - [Enums](#enums)
    - [minecraft-data](#minecraft-data)
    - [mcdata.blocks](#mcdatablocks)
    - [mcdata.items](#mcdataitems)
    - [mcdata.materials](#mcdatamaterials)
    - [mcdata.recipes](#mcdatarecipes)
    - [mcdata.instruments](#mcdatainstruments)
    - [mcdata.biomes](#mcdatabiomes)
    - [mcdata.entities](#mcdataentities)
  - [Classes](#classes)
    - [vec3](#vec3)
    - [mineflayer.Location](#mineflayerlocation)
    - [Entity](#entity)
      - [Player Skin Data](#player-skin-data)
    - [Block](#block)
    - [Biome](#biome)
    - [Item](#item)
    - [windows.Window (base class)](#windowswindow-base-class)
      - [window.deposit(itemType, metadata, count, nbt)](#windowdeposititemtype-metadata-count-nbt)
      - [window.withdraw(itemType, metadata, count, nbt)](#windowwithdrawitemtype-metadata-count-nbt)
      - [window.close()](#windowclose)
    - [Recipe](#recipe)
    - [mineflayer.Container](#mineflayercontainer)
    - [mineflayer.Furnace](#mineflayerfurnace)
      - [furnace "update"](#furnace-update)
      - [furnace.takeInput()](#furnacetakeinput)
      - [furnace.takeFuel()](#furnacetakefuel)
      - [furnace.takeOutput()](#furnacetakeoutput)
      - [furnace.putInput(itemType, metadata, count)](#furnaceputinputitemtype-metadata-count)
      - [furnace.putFuel(itemType, metadata, count)](#furnaceputfuelitemtype-metadata-count)
      - [furnace.inputItem()](#furnaceinputitem)
      - [furnace.fuelItem()](#furnacefuelitem)
      - [furnace.outputItem()](#furnaceoutputitem)
      - [furnace.fuel](#furnacefuel)
      - [furnace.progress](#furnaceprogress)
    - [mineflayer.EnchantmentTable](#mineflayerenchantmenttable)
      - [enchantmentTable "ready"](#enchantmenttable-ready)
      - [enchantmentTable.targetItem()](#enchantmenttabletargetitem)
      - [enchantmentTable.xpseed](#enchantmenttablexpseed)
      - [enchantmentTable.enchantments](#enchantmenttableenchantments)
      - [enchantmentTable.enchant(choice)](#enchantmenttableenchantchoice)
      - [enchantmentTable.takeTargetItem()](#enchantmenttabletaketargetitem)
      - [enchantmentTable.putTargetItem(item)](#enchantmenttableputtargetitemitem)
      - [enchantmentTable.putLapis(item)](#enchantmenttableputlapisitem)
    - [mineflayer.anvil](#mineflayeranvil)
      - [anvil.combine(itemOne, itemTwo[, name])](#anvilcombineitemone-itemtwo-name)
      - [anvil.combine(item[, name])](#anvilcombineitem-name)
      - [villager "ready"](#villager-ready)
      - [villager.trades](#villagertrades)
      - [villager.trade(tradeIndex, [times])](#villagertradetradeindex-times)
    - [mineflayer.ScoreBoard](#mineflayerscoreboard)
      - [ScoreBoard.name](#scoreboardname)
      - [ScoreBoard.title](#scoreboardtitle)
      - [ScoreBoard.itemsMap](#scoreboarditemsmap)
      - [ScoreBoard.items](#scoreboarditems)
    - [mineflayer.Team](#mineflayerteam)
      - [Team.name](#teamname)
      - [Team.friendlyFire](#teamfriendlyfire)
      - [Team.nameTagVisibility](#teamnametagvisibility)
      - [Team.collisionRule](#teamcollisionrule)
      - [Team.color](#teamcolor)
      - [Team.prefix](#teamprefix)
      - [Team.suffix](#teamsuffix)
      - [Team.members](#teammembers)
    - [mineflayer.BossBar](#mineflayerbossbar)
      - [BossBar.title](#bossbartitle)
      - [BossBar.health](#bossbarhealth)
      - [BossBar.dividers](#bossbardividers)
      - [BossBar.entityUUID](#bossbarentityuuid)
      - [BossBar.shouldDarkenSky](#bossbarshoulddarkensky)
      - [BossBar.isDragonBar](#bossbarisdragonbar)
      - [BossBar.createFog](#bossbarcreatefog)
      - [BossBar.color](#bossbarcolor)
    - [mineflayer.Particle](#mineflayerparticle)
      - [Particle.id](#particleid)
      - [Particle.name](#particlename)
      - [Particle.position](#particleposition)
      - [Particle.offset](#particleoffset)
      - [Particle.longDistanceRender](#particlelongdistancerender)
      - [Particle.count](#particlecount)
      - [Particle.movementSpeed](#particlemovementspeed)
  - [Bot](#bot)
    - [mineflayer.createBot(options)](#mineflayercreatebotoptions)
    - [Properties](#properties)
      - [bot.registry](#botregistry)
      - [bot.world](#botworld)
        - [world "blockUpdate" (oldBlock, newBlock)](#world-blockupdate-oldblock-newblock)
        - [world "blockUpdate:(x, y, z)" (oldBlock, newBlock)](#world-blockupdatex-y-z-oldblock-newblock)
      - [bot.entity](#botentity)
      - [bot.entities](#botentities)
      - [bot.username](#botusername)
      - [bot.spawnPoint](#botspawnpoint)
      - [bot.heldItem](#bothelditem)
      - [bot.usingHeldItem](#botusinghelditem)
      - [bot.game.levelType](#botgameleveltype)
      - [bot.game.dimension](#botgamedimension)
      - [bot.game.difficulty](#botgamedifficulty)
      - [bot.game.gameMode](#botgamegamemode)
      - [bot.game.hardcore](#botgamehardcore)
      - [bot.game.maxPlayers](#botgamemaxplayers)
      - [bot.game.serverBrand](#botgameserverbrand)
      - [bot.game.minY](#botgameminy)
      - [bot.game.height](#botgameheight)
      - [bot.physicsEnabled](#botphysicsenabled)
      - [bot.player](#botplayer)
      - [bot.players](#botplayers)
      - [bot.tablist](#bottablist)
      - [bot.isRaining](#botisraining)
      - [bot.rainState](#botrainstate)
      - [bot.thunderState](#botthunderstate)
      - [bot.chatPatterns](#botchatpatterns)
      - [bot.settings.chat](#botsettingschat)
      - [bot.settings.colorsEnabled](#botsettingscolorsenabled)
      - [bot.settings.viewDistance](#botsettingsviewdistance)
      - [bot.settings.difficulty](#botsettingsdifficulty)
      - [bot.settings.skinParts](#botsettingsskinparts)
        - [bot.settings.skinParts.showCape - boolean](#botsettingsskinpartsshowcape---boolean)
        - [bot.settings.skinParts.showJacket - boolean](#botsettingsskinpartsshowjacket---boolean)
        - [bot.settings.skinParts.showLeftSleeve - boolean](#botsettingsskinpartsshowleftsleeve---boolean)
        - [bot.settings.skinParts.showRightSleeve - boolean](#botsettingsskinpartsshowrightsleeve---boolean)
        - [bot.settings.skinParts.showLeftPants - boolean](#botsettingsskinpartsshowleftpants---boolean)
        - [bot.settings.skinParts.showRightPants - boolean](#botsettingsskinpartsshowrightpants---boolean)
        - [bot.settings.skinParts.showHat - boolean](#botsettingsskinpartsshowhat---boolean)
      - [bot.settings.enableTextFiltering - boolean](#botsettingsenabletextfiltering---boolean)
      - [bot.settings.enableServerListing - boolean](#botsettingsenableserverlisting---boolean)
      - [bot.experience.level](#botexperiencelevel)
      - [bot.experience.points](#botexperiencepoints)
      - [bot.experience.progress](#botexperienceprogress)
      - [bot.health](#bothealth)
      - [bot.food](#botfood)
      - [bot.foodSaturation](#botfoodsaturation)
      - [bot.oxygenLevel](#botoxygenlevel)
      - [bot.physics](#botphysics)
      - [bot.fireworkRocketDuration](#botfireworkrocketduration)
      - [bot.simpleClick.leftMouse (slot)](#botsimpleclickleftmouse-slot)
      - [bot.simpleClick.rightMouse (slot)](#botsimpleclickrightmouse-slot)
      - [bot.time.doDaylightCycle](#bottimedodaylightcycle)
      - [bot.time.bigTime](#bottimebigtime)
      - [bot.time.time](#bottimetime)
      - [bot.time.timeOfDay](#bottimetimeofday)
      - [bot.time.day](#bottimeday)
      - [bot.time.isDay](#bottimeisday)
      - [bot.time.moonPhase](#bottimemoonphase)
      - [bot.time.bigAge](#bottimebigage)
      - [bot.time.age](#bottimeage)
      - [bot.quickBarSlot](#botquickbarslot)
      - [bot.inventory](#botinventory)
      - [bot.targetDigBlock](#bottargetdigblock)
      - [bot.isSleeping](#botissleeping)
      - [bot.scoreboards](#botscoreboards)
      - [bot.scoreboard](#botscoreboard)
      - [bot.teams](#botteams)
      - [bot.teamMap](#botteammap)
      - [bot.controlState](#botcontrolstate)
    - [Events](#events)
      - ["chat" (username, message, translate, jsonMsg, matches)](#chat-username-message-translate-jsonmsg-matches)
      - ["whisper" (username, message, translate, jsonMsg, matches)](#whisper-username-message-translate-jsonmsg-matches)
      - ["actionBar" (jsonMsg, verified)](#actionbar-jsonmsg-verified)
      - ["message" (jsonMsg, position, sender, verified)](#message-jsonmsg-position-sender-verified)
      - ["messagestr" (message, messagePosition, jsonMsg, sender, verified)](#messagestr-message-messageposition-jsonmsg-sender-verified)
      - ["inject_allowed"](#inject_allowed)
      - ["login"](#login)
      - ["spawn"](#spawn)
      - ["respawn"](#respawn)
      - ["game"](#game)
      - ["resourcePack" (url, hash)](#resourcepack-url-hash)
      - ["title" (title, type)](#title-title-type)
      - ["title_times" (fadeIn, stay, fadeOut)](#title_times-fadein-stay-fadeout)
      - ["title_clear"](#title_clear)
      - ["rain"](#rain)
      - ["weatherUpdate"](#weatherupdate)
      - ["time"](#time)
      - ["kicked" (reason, loggedIn)](#kicked-reason-loggedin)
      - ["end" (reason)](#end-reason)
      - ["error" (err)](#error-err)
      - ["spawnReset"](#spawnreset)
      - ["death"](#death)
      - ["health"](#health)
      - ["breath"](#breath)
      - ["entityAttributes" (entity)](#entityattributes-entity)
      - ["entitySwingArm" (entity)](#entityswingarm-entity)
      - ["entityHurt" (entity)](#entityhurt-entity)
      - ["entityDead" (entity)](#entitydead-entity)
      - ["entityTaming" (entity)](#entitytaming-entity)
      - ["entityTamed" (entity)](#entitytamed-entity)
      - ["entityShakingOffWater" (entity)](#entityshakingoffwater-entity)
      - ["entityEatingGrass" (entity)](#entityeatinggrass-entity)
      - ["entityHandSwap" (entity)](#entityhandswap-entity)
      - ["entityWake" (entity)](#entitywake-entity)
      - ["entityEat" (entity)](#entityeat-entity)
      - ["entityCriticalEffect" (entity)](#entitycriticaleffect-entity)
      - ["entityMagicCriticalEffect" (entity)](#entitymagiccriticaleffect-entity)
      - ["entityCrouch" (entity)](#entitycrouch-entity)
      - ["entityUncrouch" (entity)](#entityuncrouch-entity)
      - ["entityEquip" (entity)](#entityequip-entity)
      - ["entitySleep" (entity)](#entitysleep-entity)
      - ["entitySpawn" (entity)](#entityspawn-entity)
      - ["entityElytraFlew" (entity)](#entityelytraflew-entity)
      - ["itemDrop" (entity)](#itemdrop-entity)
      - ["playerCollect" (collector, collected)](#playercollect-collector-collected)
      - ["entityGone" (entity)](#entitygone-entity)
      - ["entityMoved" (entity)](#entitymoved-entity)
      - ["entityDetach" (entity, vehicle)](#entitydetach-entity-vehicle)
      - ["entityAttach" (entity, vehicle)](#entityattach-entity-vehicle)
      - ["entityUpdate" (entity)](#entityupdate-entity)
      - ["entityEffect" (entity, effect)](#entityeffect-entity-effect)
      - ["entityEffectEnd" (entity, effect)](#entityeffectend-entity-effect)
      - ["playerJoined" (player)](#playerjoined-player)
      - ["playerUpdated" (player)](#playerupdated-player)
      - ["playerLeft" (player)](#playerleft-player)
      - ["blockUpdate" (oldBlock, newBlock)](#blockupdate-oldblock-newblock)
      - ["blockUpdate:(x, y, z)" (oldBlock, newBlock)](#blockupdatex-y-z-oldblock-newblock)
      - ["blockPlaced" (oldBlock, newBlock)](#blockplaced-oldblock-newblock)
      - ["chunkColumnLoad" (point)](#chunkcolumnload-point)
      - ["chunkColumnUnload" (point)](#chunkcolumnunload-point)
      - ["soundEffectHeard" (soundName, position, volume, pitch)](#soundeffectheard-soundname-position-volume-pitch)
      - ["hardcodedSoundEffectHeard" (soundId, soundCategory, position, volume, pitch)](#hardcodedsoundeffectheard-soundid-soundcategory-position-volume-pitch)
      - ["noteHeard" (block, instrument, pitch)](#noteheard-block-instrument-pitch)
      - ["pistonMove" (block, isPulling, direction)](#pistonmove-block-ispulling-direction)
      - ["chestLidMove" (block, isOpen, block2)](#chestlidmove-block-isopen-block2)
      - ["blockBreakProgressObserved" (block, destroyStage, entity)](#blockbreakprogressobserved-block-destroystage-entity)
      - ["blockBreakProgressEnd" (block, entity)](#blockbreakprogressend-block-entity)
      - ["diggingCompleted" (block)](#diggingcompleted-block)
      - ["diggingAborted" (block)](#diggingaborted-block)
      - ["usedFirework" (fireworkEntityId)](#usedfirework-fireworkentityid)
      - ["move"](#move)
      - ["forcedMove"](#forcedmove)
      - ["mount"](#mount)
      - ["dismount" (vehicle)](#dismount-vehicle)
      - ["windowOpen" (window)](#windowopen-window)
      - ["windowClose" (window)](#windowclose-window)
      - ["sleep"](#sleep)
      - ["wake"](#wake)
      - ["experience"](#experience)
      - ["scoreboardCreated" (scoreboard)](#scoreboardcreated-scoreboard)
      - ["scoreboardDeleted" (scoreboard)](#scoreboarddeleted-scoreboard)
      - ["scoreboardTitleChanged" (scoreboard)](#scoreboardtitlechanged-scoreboard)
      - ["scoreUpdated" (scoreboard, item)](#scoreupdated-scoreboard-item)
      - ["scoreRemoved" (scoreboard, item)](#scoreremoved-scoreboard-item)
      - ["scoreboardPosition" (position, scoreboard)](#scoreboardposition-position-scoreboard)
      - ["teamCreated" (team)](#teamcreated-team)
      - ["teamRemoved" (team)](#teamremoved-team)
      - ["teamUpdated" (team)](#teamupdated-team)
      - ["teamMemberAdded" (team)](#teammemberadded-team)
      - ["teamMemberRemoved" (team)](#teammemberremoved-team)
      - ["bossBarCreated" (bossBar)](#bossbarcreated-bossbar)
      - ["bossBarDeleted" (bossBar)](#bossbardeleted-bossbar)
      - ["bossBarUpdated" (bossBar)](#bossbarupdated-bossbar)
      - ["heldItemChanged" (heldItem)](#helditemchanged-helditem)
      - ["physicsTick" ()](#physicstick-)
      - ["chat:name" (matches)](#chatname-matches)
      - ["particle"](#particle)
    - [Functions](#functions)
      - [bot.blockAt(point, extraInfos=true)](#botblockatpoint-extrainfostrue)
      - [bot.waitForChunksToLoad()](#botwaitforchunkstoload)
      - [bot.blockInSight(maxSteps, vectorLength)](#botblockinsightmaxsteps-vectorlength)
      - [bot.blockAtCursor(maxDistance=256)](#botblockatcursormaxdistance256)
      - [bot.entityAtCursor(maxDistance=3.5)](#botentityatcursormaxdistance35)
      - [bot.blockAtEntityCursor(entity=bot.entity, maxDistance=256)](#botblockatentitycursorentitybotentity-maxdistance256)
      - [bot.canSeeBlock(block)](#botcanseeblockblock)
      - [bot.findBlocks(options)](#botfindblocksoptions)
      - [bot.findBlock(options)](#botfindblockoptions)
      - [bot.canDigBlock(block)](#botcandigblockblock)
      - [bot.recipesFor(itemType, metadata, minResultCount, craftingTable)](#botrecipesforitemtype-metadata-minresultcount-craftingtable)
      - [bot.recipesAll(itemType, metadata, craftingTable)](#botrecipesallitemtype-metadata-craftingtable)
      - [bot.nearestEntity(match = (entity) => { return true })](#botnearestentitymatch--entity---return-true-)
    - [Methods](#methods)
      - [bot.end(reason)](#botendreason)
      - [bot.quit(reason)](#botquitreason)
      - [bot.tabComplete(str, [assumeCommand], [sendBlockInSight], [timeout])](#bottabcompletestr-assumecommand-sendblockinsight-timeout)
      - [bot.chat(message)](#botchatmessage)
      - [bot.whisper(username, message)](#botwhisperusername-message)
      - [bot.chatAddPattern(pattern, chatType, description)](#botchataddpatternpattern-chattype-description)
      - [bot.addChatPattern(name, pattern, chatPatternOptions)](#botaddchatpatternname-pattern-chatpatternoptions)
      - [bot.addChatPatternSet(name, patterns, chatPatternOptions)](#botaddchatpatternsetname-patterns-chatpatternoptions)
      - [bot.removeChatPattern(name)](#botremovechatpatternname)
      - [bot.awaitMessage(...args)](#botawaitmessageargs)
      - [bot.setSettings(options)](#botsetsettingsoptions)
      - [bot.loadPlugin(plugin)](#botloadpluginplugin)
      - [bot.loadPlugins(plugins)](#botloadpluginsplugins)
      - [bot.hasPlugin(plugin)](#bothaspluginplugin)
      - [bot.sleep(bedBlock)](#botsleepbedblock)
      - [bot.isABed(bedBlock)](#botisabedbedblock)
      - [bot.wake()](#botwake)
      - [bot.setControlState(control, state)](#botsetcontrolstatecontrol-state)
      - [bot.getControlState(control)](#botgetcontrolstatecontrol)
      - [bot.clearControlStates()](#botclearcontrolstates)
      - [bot.getExplosionDamages(entity, position, radius, [rawDamages])](#botgetexplosiondamagesentity-position-radius-rawdamages)
      - [bot.lookAt(point, [force])](#botlookatpoint-force)
      - [bot.look(yaw, pitch, [force])](#botlookyaw-pitch-force)
      - [bot.updateSign(block, text, back = false)](#botupdatesignblock-text-back--false)
      - [bot.equip(item, destination)](#botequipitem-destination)
      - [bot.unequip(destination)](#botunequipdestination)
      - [bot.tossStack(item)](#bottossstackitem)
      - [bot.toss(itemType, metadata, count)](#bottossitemtype-metadata-count)
      - [bot.elytraFly()](#botelytrafly)
      - [bot.dig(block, [forceLook = true], [digFace])](#botdigblock-forcelook--true-digface)
      - [bot.stopDigging()](#botstopdigging)
      - [bot.digTime(block)](#botdigtimeblock)
      - [bot.acceptResourcePack()](#botacceptresourcepack)
      - [bot.denyResourcePack()](#botdenyresourcepack)
      - [bot.placeBlock(referenceBlock, faceVector)](#botplaceblockreferenceblock-facevector)
      - [bot.placeEntity(referenceBlock, faceVector)](#botplaceentityreferenceblock-facevector)
      - [bot.activateBlock(block, direction?: Vec3, cursorPos?: Vec3)](#botactivateblockblock-direction-vec3-cursorpos-vec3)
      - [bot.activateEntity(entity)](#botactivateentityentity)
      - [bot.activateEntityAt(entity, position)](#botactivateentityatentity-position)
      - [bot.consume()](#botconsume)
      - [bot.fish()](#botfish)
      - [bot.activateItem(offHand=false)](#botactivateitemoffhandfalse)
      - [bot.deactivateItem()](#botdeactivateitem)
      - [bot.useOn(targetEntity)](#botuseontargetentity)
      - [bot.attack(entity, swing = true)](#botattackentity-swing--true)
      - [bot.swingArm([hand], showHand)](#botswingarmhand-showhand)
      - [bot.mount(entity)](#botmountentity)
      - [bot.dismount()](#botdismount)
      - [bot.moveVehicle(left,forward)](#botmovevehicleleftforward)
      - [bot.setQuickBarSlot(slot)](#botsetquickbarslotslot)
      - [bot.craft(recipe, count, craftingTable)](#botcraftrecipe-count-craftingtable)
      - [bot.writeBook(slot, pages)](#botwritebookslot-pages)
      - [bot.openContainer(containerBlock or containerEntity, direction?, cursorPos?)](#botopencontainercontainerblock-or-containerentity-direction-cursorpos)
      - [bot.openChest(chestBlock or minecartchestEntity, direction?, cursorPos?)](#botopenchestchestblock-or-minecartchestentity-direction-cursorpos)
      - [bot.openFurnace(furnaceBlock)](#botopenfurnacefurnaceblock)
      - [bot.openDispenser(dispenserBlock)](#botopendispenserdispenserblock)
      - [bot.openEnchantmentTable(enchantmentTableBlock)](#botopenenchantmenttableenchantmenttableblock)
      - [bot.openAnvil(anvilBlock)](#botopenanvilanvilblock)
      - [bot.openVillager(villagerEntity)](#botopenvillagervillagerentity)
      - [bot.trade(villagerInstance, tradeIndex, [times])](#bottradevillagerinstance-tradeindex-times)
      - [bot.setCommandBlock(pos, command, [options])](#botsetcommandblockpos-command-options)
      - [bot.supportFeature(name)](#botsupportfeaturename)
      - [bot.waitForTicks(ticks)](#botwaitforticksticks)
      - [bot.respawn()](#botrespawn)
    - [Lower level inventory methods](#lower-level-inventory-methods)
      - [bot.clickWindow(slot, mouseButton, mode)](#botclickwindowslot-mousebutton-mode)
      - [bot.putSelectedItemRange(start, end, window, slot)](#botputselecteditemrangestart-end-window-slot)
      - [bot.putAway(slot)](#botputawayslot)
      - [bot.closeWindow(window)](#botclosewindowwindow)
      - [bot.transfer(options)](#bottransferoptions)
      - [bot.openBlock(block, direction?: Vec3, cursorPos?: Vec3)](#botopenblockblock-direction-vec3-cursorpos-vec3)
      - [bot.openEntity(entity)](#botopenentityentity)
      - [bot.moveSlotItem(sourceSlot, destSlot)](#botmoveslotitemsourceslot-destslot)
      - [bot.updateHeldItem()](#botupdatehelditem)
      - [bot.getEquipmentDestSlot(destination)](#botgetequipmentdestslotdestination)
    - [bot.creative](#botcreative)
      - [bot.creative.setInventorySlot(slot, item)](#botcreativesetinventoryslotslot-item)
      - [bot.creative.clearSlot(slot)](#botcreativeclearslotslot)
      - [bot.creative.clearInventory()](#botcreativeclearinventory)
      - [bot.creative.flyTo(destination)](#botcreativeflytodestination)
      - [bot.creative.startFlying()](#botcreativestartflying)
      - [bot.creative.stopFlying()](#botcreativestopflying)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

# API

## Enums

These enums are stored in the language independent [minecraft-data](https://github.com/PrismarineJS/minecraft-data) project,
 and accessed through [node-minecraft-data](https://github.com/PrismarineJS/node-minecraft-data).

### minecraft-data
The data is available in [node-minecraft-data](https://github.com/PrismarineJS/node-minecraft-data) module

`require('minecraft-data')(bot.version)` gives you access to it.

### mcdata.blocks
blocks indexed by id

### mcdata.items
items indexed by id

### mcdata.materials

The key is the material. The value is an object with the key as the item id
of the tool and the value as the efficiency multiplier.

### mcdata.recipes
recipes indexed by id

### mcdata.instruments
instruments indexed by id

### mcdata.biomes
biomes indexed by id

### mcdata.entities
entities indexed by id

## Classes

### vec3

See [andrewrk/node-vec3](https://github.com/andrewrk/node-vec3)

All points in mineflayer are supplied as instances of this class.

 * x - south
 * y - up
 * z - west

Functions and methods which require a point argument accept `Vec3` instances
as well as an array with 3 values, and an object with `x`, `y`, and `z`
properties.

### mineflayer.Location

### Entity

Entities represent players, mobs, and objects. They are emitted
in many events, and you can access your own entity with `bot.entity`.
See [prismarine-entity](https://github.com/PrismarineJS/prismarine-entity)

#### Player Skin Data

The skin data is stored in the `skinData` property of the player object, if present.

```js
// player.skinData
{
  url: 'http://textures.minecraft.net/texture/...',
  model: 'slim' // or 'classic'
}
```

### Block

See [prismarine-block](https://github.com/PrismarineJS/prismarine-block)

Also `block.blockEntity` is additional field with block entity data as `Object`. The data in this varies between versions.
```js
// sign.blockEntity example from 1.19
{
  GlowingText: 0, // 0 for false, 1 for true
  Color: 'black',
  Text1: '{"text":"1"}',
  Text2: '{"text":"2"}',
  Text3: '{"text":"3"}',
  Text4: '{"text":"4"}'
}
```

Note if you want to get a sign's plain text, you can use [`block.getSignText()`](https://github.com/PrismarineJS/prismarine-block/blob/master/doc/API.md#sign) instead of unstable blockEntity data.
```java
> block = bot.blockAt(new Vec3(0, 60, 0)) // assuming a sign is here
> block.getSignText()
[ "Front text\nHello world", "Back text\nHello world" ]
```

### Biome

See [prismarine-biome](https://github.com/PrismarineJS/prismarine-biome)

### Item

See [prismarine-item](https://github.com/PrismarineJS/prismarine-item)

### windows.Window (base class)

See [prismarine-windows](https://github.com/PrismarineJS/prismarine-windows)

#### window.deposit(itemType, metadata, count, nbt)

This function returns a `Promise`, with `void` as its argument when done depositing.

 * `itemType` - numerical item id
 * `metadata` - numerical value. `null` means match anything.
 * `count` - how many to deposit. `null` is an alias to 1.
 * `nbt` - match nbt data. `null` is do not match nbt.

#### window.withdraw(itemType, metadata, count, nbt)

This function returns a `Promise`, with `void` as its argument when done withdrawing. Throws and error if the bot has no free room in its inventory.

 * `itemType` - numerical item id
 * `metadata` - numerical value. `null` means match anything.
 * `count` - how many to withdraw. `null` is an alias to 1.
 * `nbt` - match nbt data. `null` is do not match nbt.

#### window.close()

### Recipe

See [prismarine-recipe](https://github.com/PrismarineJS/prismarine-recipe)

### mineflayer.Container

Extends windows.Window for chests, dispensers, etc...
See `bot.openContainer(chestBlock or minecartchestEntity)`.

### mineflayer.Furnace

Extends windows.Window for furnace, smelter, etc...
See `bot.openFurnace(furnaceBlock)`.

#### furnace "update"

Fires when `furnace.fuel` and/or `furnace.progress` update.

#### furnace.takeInput()

This function returns a `Promise`, with `item` as its argument upon completion.


#### furnace.takeFuel()

This function returns a `Promise`, with `item` as its argument upon completion.


#### furnace.takeOutput()

This function returns a `Promise`, with `item` as its argument upon completion.


#### furnace.putInput(itemType, metadata, count)

This function returns a `Promise`, with `void` as its argument upon completion.

#### furnace.putFuel(itemType, metadata, count)

This function returns a `Promise`, with `void` as its argument upon completion.

#### furnace.inputItem()

Returns `Item` instance which is the input.

#### furnace.fuelItem()

Returns `Item` instance which is the fuel.

#### furnace.outputItem()

Returns `Item` instance which is the output.

#### furnace.fuel

How much fuel is left between 0 and 1.

#### furnace.progress

How much cooked the input is between 0 and 1.

### mineflayer.EnchantmentTable

Extends windows.Window for enchantment tables
See `bot.openEnchantmentTable(enchantmentTableBlock)`.

#### enchantmentTable "ready"

Fires when `enchantmentTable.enchantments` is fully populated and you
may make a selection by calling `enchantmentTable.enchant(choice)`.

#### enchantmentTable.targetItem()

Gets the target item. This is both the input and the output of the
enchantment table.

#### enchantmentTable.xpseed

The 16 bits xpseed sent by the server.

#### enchantmentTable.enchantments

Array of length 3 which are the 3 enchantments to choose from.
`level` can be `-1` if the server has not sent the data yet.

Looks like:

```js
[
  {
    level: 3
  },
  {
    level: 4
  },
  {
    level: 9
  }
]
```

#### enchantmentTable.enchant(choice)

This function returns a `Promise`, with `item` as its argument when the item has been enchanted.

 * `choice` - [0-2], the index of the enchantment you want to pick.

#### enchantmentTable.takeTargetItem()

This function returns a `Promise`, with `item` as its argument upon completion.


#### enchantmentTable.putTargetItem(item)

This function returns a `Promise`, with `void` as its argument upon completion.


#### enchantmentTable.putLapis(item)

This function returns a `Promise`, with `void` as its argument upon completion.


### mineflayer.anvil

Extends windows.Window for anvils
See `bot.openAnvil(anvilBlock)`.

#### anvil.combine(itemOne, itemTwo[, name])

This function returns a `Promise`, with `void` as its argument upon completion.


#### anvil.combine(item[, name])

This function returns a `Promise`, with `void` as its argument upon completion.


#### villager "ready"

Fires when `villager.trades` is loaded.

#### villager.trades

Array of trades.

Looks like:

```js
[
  {
    firstInput: Item,
    output: Item,
    hasSecondItem: false,
    secondaryInput: null,
    disabled: false,
    tooluses: 0,
    maxTradeuses: 7
  },
  {
    firstInput: Item,
    output: Item,
    hasSecondItem: false,
    secondaryInput: null,
    disabled: false,
    tooluses: 0,
    maxTradeuses: 7
  },
  {
    firstInput: Item,
    output: Item,
    hasSecondItem: true,
    secondaryInput: Item,
    disabled: false,
    tooluses: 0,
    maxTradeuses: 7
  }
]
```

#### villager.trade(tradeIndex, [times])
Is the same as [bot.trade(villagerInstance, tradeIndex, [times])](#bottradevillagerinstance-tradeindex-times)

### mineflayer.ScoreBoard

#### ScoreBoard.name

Name of the scoreboard.

#### ScoreBoard.title

The title of the scoreboard (does not always equal the name)

#### ScoreBoard.itemsMap

An object with all items in the scoreboard in it
```js
{
  wvffle: { name: 'wvffle', value: 3 },
  dzikoysk: { name: 'dzikoysk', value: 6 }
}
```

#### ScoreBoard.items

An array with all sorted items in the scoreboard in it
```js
[
  { name: 'dzikoysk', value: 6 },
  { name: 'wvffle', value: 3 }
]
```

### mineflayer.Team

#### Team.name

Name of the team

#### Team.friendlyFire

#### Team.nameTagVisibility

One of `always`, `hideForOtherTeams`, `hideForOwnTeam`

#### Team.collisionRule

One of `always`, `pushOtherTeams`, `pushOwnTeam`

#### Team.color

Color (or formatting) name of team, e.g. `dark_green`, `red`, `underlined`

#### Team.prefix

A chat component containing team prefix

#### Team.suffix

A chat component containing team suffix

#### Team.members

Array of team members. Usernames for players and UUIDs for other entities.

### mineflayer.BossBar

#### BossBar.title

Title of boss bar, instance of ChatMessage

#### BossBar.health

Percent of boss health, from `0` to `1`

#### BossBar.dividers

Number of boss bar dividers, one of `0`, `6`, `10`, `12`, `20`

#### BossBar.entityUUID

Boss bar entity uuid

#### BossBar.shouldDarkenSky

Determines whether or not to darken the sky

#### BossBar.isDragonBar

Determines whether or not boss bar is dragon bar

#### BossBar.createFog

Determines whether or not boss bar creates fog

#### BossBar.color

Determines what color the boss bar color is, one of `pink`, `blue`, `red`, `green`, `yellow`, `purple`, `white`

### mineflayer.Particle

#### Particle.id

Particle ID, as defined in the [protocol](https://minecraft.wiki/w/Protocol#Particle)

#### Particle.name

Particle Name, as defined in the [protocol](https://minecraft.wiki/w/Protocol#Particle)

#### Particle.position

Vec3 instance of where the particle was created

#### Particle.offset

Vec3 instance of the particle's offset

#### Particle.longDistanceRender

Determines whether or not to force the rendering of a particle despite client particle settings and increases maximum view distance from 256 to 65536

#### Particle.count

Amount of particles created

#### Particle.movementSpeed

Particle speed in a random direction

## Bot

### mineflayer.createBot(options)

Create and return an instance of the class bot.
`options` is an object containing the optional properties :
 * username : default to 'Player'
 * port : default to 25565
 * password : can be omitted (if the tokens are also omitted then it tries to connect in offline mode)
 * host : default to localhost
 * version : default to automatically guessing the version of the server. Example of value : "1.12.2"
 * auth : default to 'mojang', can also be 'microsoft'
 * clientToken : generated if a password is given
 * accessToken : generated if a password is given
 * logErrors : true by default, catch errors and log them
 * hideErrors : true by default, do not log errors (even if logErrors is true)
 * keepAlive : send keep alive packets : default to true
 * checkTimeoutInterval : default to `30*1000` (30s), check if keepalive received at that period, disconnect otherwise.
 * loadInternalPlugins : defaults to true
 * storageBuilder : an optional function, takes as argument version and worldName and return an instance of something with the same API as prismarine-provider-anvil. Will be used to save the world.
 * client : an instance of node-minecraft-protocol, if not specified, mineflayer makes its own client. This can be used to enable using mineflayer through a proxy of many clients or a vanilla client and a mineflayer client.
 * brand : the brand name for the client to use. Defaults to vanilla. Can be used to simulate custom clients for servers that require it.
 * respawn : when set to false disables bot from automatically respawning, defaults to true.
 * plugins : object : defaults to {}
   - pluginName : false : don't load internal plugin with given name ie. `pluginName`
   - pluginName : true : load internal plugin with given name ie. `pluginName` even though loadInternalplugins is set to false
   - pluginName : external plugin inject function : loads external plugin, overrides internal plugin with given name ie. `pluginName`
 * physicsEnabled : true by default, should the bot be affected by physics? can later be modified via bot.physicsEnabled
 * [chat](#bot.settings.chat)
 * [colorsEnabled](#bot.settings.colorsEnabled)
 * [viewDistance](#bot.settings.viewDistance)
 * [difficulty](#bot.settings.difficulty)
 * [skinParts](#bot.settings.skinParts)
 * [enableTextFiltering](#bot.settings.enableTextFiltering)
 * [enableServerListing](#bot.settings.enableServerListing)
 * chatLengthLimit : the maximum amount of characters that can be sent in a single message. If this is not set, it will be 100 in < 1.11 and 256 in >= 1.11.
 * defaultChatPatterns: defaults to true, set to false to not add the patterns such as chat and whisper

### Properties

#### bot.registry

Instance of minecraft-data used by the bot. Pass this to constructors that expect an instance of minecraft-data, such as prismarine-block.

#### bot.world

A sync representation of the world. Check the doc at http://github.com/PrismarineJS/prismarine-world

##### world "blockUpdate" (oldBlock, newBlock)

Fires when a block updates. Both `oldBlock` and `newBlock` provided for
comparison.
`oldBlock` may be `null` with normal block updates.

##### world "blockUpdate:(x, y, z)" (oldBlock, newBlock)

Fires for a specific point. Both `oldBlock` and `newBlock` provided for
comparison. All listeners receive null for `oldBlock` and `newBlock` and get automatically removed when the world is unloaded.
`oldBlock` may be `null` with normal block updates.


#### bot.entity

Your own entity. See `Entity`.

#### bot.entities

All nearby entities. This object is a map of entityId to entity.

#### bot.username

Use this to find out your own name.

#### bot.spawnPoint

Coordinates to the main spawn point, where all compasses point to.

#### bot.heldItem

The item in the bot's hand, represented as a [prismarine-item](https://github.com/PrismarineJS/prismarine-item) instance specified with arbitrary metadata, nbtdata, etc.

#### bot.usingHeldItem

Whether the bot is using the item that it's holding, for example eating food or using a shield.

#### bot.game.levelType

#### bot.game.dimension

The bot's current dimension, such as `overworld`, `the_end` or `the_nether`.

#### bot.game.difficulty

#### bot.game.gameMode

#### bot.game.hardcore

#### bot.game.maxPlayers

#### bot.game.serverBrand

#### bot.game.minY

minimum y of the world

#### bot.game.height

world height

#### bot.physicsEnabled

Enable physics, default true.

#### bot.player

Bot's player object
```js
{
  username: 'player',
  displayName: { toString: Function }, // ChatMessage object.
  gamemode: 0,
  ping: 28,
  entity: entity // null if you are too far away
}
```

A player's ping starts at 0, you might have to wait a bit for the server to send their actual ping.

#### bot.players

Map of username to people playing the game.

#### bot.tablist

bot's tablist object has two keys, `header` and `footer`.

```js
{
  header: { toString: Function }, // ChatMessage object.
  footer: { toString: Function } // ChatMessage object.
}
```

#### bot.isRaining

#### bot.rainState

A number indicating the current rain level. When it isn't raining, this
will be equal to 0. When it starts to rain, this value will increase
gradually up to 1. When it stops raining, this value gradually decreases back to 0.

Each time `bot.rainState` is changed, the "weatherUpdate" event is emitted.

#### bot.thunderState

A number indicating the current thunder level. When there isn't a thunderstorm, this
will be equal to 0. When a thunderstorm starts, this value will increase
gradually up to 1. When the thunderstorm stops, this value gradually decreases back to 0.

Each time `bot.thunderState` is changed, the "weatherUpdate" event is emitted.

This is the same as `bot.rainState`, but for thunderstorms.
For thunderstorms, both `bot.rainState` and `bot.thunderState` will change.

#### bot.chatPatterns

This is an array of pattern objects, of the following format:
{ /regex/, "chattype", "description")
 * /regex/ - a regular expression pattern, that should have at least two capture groups
 * 'chattype' - the type of chat the pattern matches, ex "chat" or "whisper", but can be anything.
 * 'description' - description of what the pattern is for, optional.

#### bot.settings.chat

Choices:

 * `enabled` (default)
 * `commandsOnly`
 * `disabled`

#### bot.settings.colorsEnabled

Default true, whether or not you receive color codes in chats from the server.

#### bot.settings.viewDistance

Can be a string listed below or a positive number.
Choices:
 * `far` (default)
 * `normal`
 * `short`
 * `tiny`

#### bot.settings.difficulty

Same as from server.properties.

#### bot.settings.skinParts

These boolean Settings control if extra Skin Details on the own players' skin should be visible

##### bot.settings.skinParts.showCape - boolean

If you have a cape you can turn it off by setting this to false.

##### bot.settings.skinParts.showJacket - boolean

##### bot.settings.skinParts.showLeftSleeve - boolean

##### bot.settings.skinParts.showRightSleeve - boolean

##### bot.settings.skinParts.showLeftPants - boolean

##### bot.settings.skinParts.showRightPants - boolean

##### bot.settings.skinParts.showHat - boolean

#### bot.settings.enableTextFiltering - boolean
Unused, defaults to false in Notchian (Vanilla) client.
#### bot.settings.enableServerListing - boolean
This setting is sent to the server to determine whether the player should show up in server listings
#### bot.experience.level

#### bot.experience.points

Total experience points.

#### bot.experience.progress

Between 0 and 1 - amount to get to the next level.

#### bot.health

Number in the range [0, 20] representing the number of half-hearts.

#### bot.food

Number in the range [0, 20] representing the number of half-turkey-legs.

#### bot.foodSaturation

Food saturation acts as a food "overcharge". Food values will not decrease
while the saturation is over zero. Players logging in automatically get a
saturation of 5.0. Eating food increases the saturation as well as the food bar.

#### bot.oxygenLevel

Number in the range [0, 20] representing the number of water-icons known as oxygen level.

#### bot.physics

Edit these numbers to tweak gravity, jump speed, terminal velocity, etc.
Do this at your own risk.

#### bot.fireworkRocketDuration

How many physics ticks worth of firework rocket boost are left.

#### bot.simpleClick.leftMouse (slot)

abstraction over `bot.clickWindow(slot, 0, 0)`

#### bot.simpleClick.rightMouse (slot)

abstraction over `bot.clickWindow(slot, 1, 0)`

#### bot.time.doDaylightCycle

Whether or not the gamerule doDaylightCycle is true or false.

#### bot.time.bigTime

The total number of ticks since day 0.

This value is of type BigInt and is accurate even at very large values. (more than 2^51 - 1 ticks)

#### bot.time.time

The total numbers of ticks since day 0.

Because the Number limit of Javascript is at 2^51 - 1 bot.time.time becomes inaccurate higher than this limit and the use of bot.time.bigTime is recommended.
Realistically though you'll probably never need to use bot.time.bigTime as it will only reach 2^51 - 1 ticks naturally after ~14280821 real years.

#### bot.time.timeOfDay

Time of the day, in ticks.

Time is based on ticks, where 20 ticks happen every second. There are 24000
ticks in a day, making Minecraft days exactly 20 minutes long.

The time of day is based on the timestamp modulo 24000. 0 is sunrise, 6000
is noon, 12000 is sunset, and 18000 is midnight.

#### bot.time.day

Day of the world.

#### bot.time.isDay

Whether it is day or not.

Based on whether the current time of day is between 0 and 13000 ticks (day + sunset).

#### bot.time.moonPhase

Phase of the moon.

0-7 where 0 is full moon.

#### bot.time.bigAge

Age of the world, in ticks.

This value is of type BigInt and is accurate even at very large values. (more than 2^51 - 1 ticks)

#### bot.time.age

Age of the world, in ticks.

Because the Number limit of Javascript is at 2^51 - 1 bot.time.age becomes inaccurate higher than this limit and the use of bot.time.bigAge is recommended.
Realistically though you'll probably never need to use bot.time.bigAge as it will only reach 2^51 - 1 ticks naturally after ~14280821 real years.

#### bot.quickBarSlot

Which quick bar slot is selected (0 - 8).

#### bot.inventory

A [`Window`](https://github.com/PrismarineJS/prismarine-windows#windowswindow-base-class) instance representing your inventory.

#### bot.targetDigBlock

The `block` that you are currently digging, or `null`.

#### bot.isSleeping

Boolean, whether or not you are in bed.

#### bot.scoreboards

All scoreboards known to the bot in an object scoreboard name -> scoreboard.

#### bot.scoreboard

All scoreboards known to the bot in an object scoreboard displaySlot -> scoreboard.

 * `belowName` - scoreboard placed in belowName
 * `sidebar` - scoreboard placed in sidebar
 * `list` - scoreboard placed in list
 * `0-18` - slots defined in [protocol](https://minecraft.wiki/w/Protocol#Display_Scoreboard)

#### bot.teams

All teams known to the bot

#### bot.teamMap

Mapping of member to team. Uses usernames for players and UUIDs for entities.

#### bot.controlState

An object whose keys are the main control states: ['forward', 'back', 'left', 'right', 'jump', 'sprint', 'sneak'].

Setting values for this object internally calls [bot.setControlState](#botsetcontrolstatecontrol-state).

### Events

#### "chat" (username, message, translate, jsonMsg, matches)

Only emitted when a player chats publicly.

 * `username` - who said the message (compare with `bot.username` to ignore your own chat)
 * `message` - stripped of all color and control characters
 * `translate` - chat message type. Null for most bukkit chat messages
 * `jsonMsg` - unmodified JSON message from the server
 * `matches` - array of returned matches from regular expressions. May be null

#### "whisper" (username, message, translate, jsonMsg, matches)

Only emitted when a player chats to you privately.

 * `username` - who said the message
 * `message` - stripped of all color and control characters
 * `translate` - chat message type. Null for most bukkit chat messages
 * `jsonMsg` - unmodified JSON message from the server
 * `matches` - array of returned matches from regular expressions. May be null

#### "actionBar" (jsonMsg, verified)

Emitted for every server message which appears on the Action Bar.

 * `jsonMsg` - unmodified JSON message from the server
 * `verified` -> null if non signed, true if signed and correct, false if signed and incorrect

#### "message" (jsonMsg, position, sender, verified)

Emitted for every server message, including chats.

 * `jsonMsg` - [ChatMessage](https://github.com/PrismarineJS/prismarine-chat) object containing the formatted chat message. Might additionally have the following properties:
   * unsigned - Unsigned ChatMessage object. Only present in 1.19.2+, and only when the server allows insecure chat and the server modified the chat message without the user's signature

 * `position` - (>= 1.8.1): position of Chat message can be
   * chat
   * system
   * game_info

 * `sender` - UUID of sender if known (1.16+), else null

 * `verified` -> null if non signed, true if signed and correct, false if signed and incorrect

#### "messagestr" (message, messagePosition, jsonMsg, sender, verified)

Alias for the "message" event but it calls .toString() on the prismarine-message object to get a string for the message before emitting.

 * `sender` - UUID of sender if known (1.16+), else null

 * `verified` -> null if non signed, true if signed and correct, false if signed and incorrect

#### "inject_allowed"
Fires when the index file has been loaded, you can load mcData and plugins here but it's better to wait for "spawn" event.

#### "login"

Fires after you successfully login to the server.
You probably want to wait for the `spawn` event
before doing anything though.

#### "spawn"

Emitted once after you log in and spawn for the first time
and then emitted when you respawn after death.

This is usually the event that you want to listen to
before doing anything on the server.

#### "respawn"

Emitted when you change dimensions and just before you spawn.
Usually you want to ignore this event and wait until the "spawn"
event instead.

#### "game"

Emitted when the server changes any of the game properties.

#### "resourcePack" (url, hash)

Emitted when the server sends a resource pack.

#### "title" (title, type)

Emitted when the server sends a title

* `title` - title's text
* `type` - title's type "subtitle", "title"

#### "title_times" (fadeIn, stay, fadeOut)

Emitted when the server sends a title times packet (i.e., when the fade-in, stay, and fade-out times for titles are set or updated).

 * `fadeIn` - fade-in time in ticks (number)
 * `stay` - stay time in ticks (number)
 * `fadeOut` - fade-out time in ticks (number)

Example:

```js
bot.on('title_times', (fadeIn, stay, fadeOut) => {
  console.log(`Title times: fadeIn=${fadeIn}, stay=${stay}, fadeOut=${fadeOut}`)
})
```

#### "title_clear"

Emitted when the server clears all titles.

#### "rain"

Emitted when it starts or stops raining. If you join a
server where it is already raining, this event will fire.

#### "weatherUpdate"

Emitted when either `bot.thunderState` or `bot.rainState` changes.
If you join a server where it is already raining, this event will fire.

#### "time"

Emitted when the server sends a time update. See `bot.time`.

#### "kicked" (reason, loggedIn)

Emitted when the bot is kicked from the server. `reason`
is a chat message explaining why you were kicked. `loggedIn`
is `true` if the client was kicked after successfully logging in,
or `false` if the kick occurred in the login phase.

#### "end" (reason)

Emitted when you are no longer connected to the server.
`reason` is a string explaining why the client was disconnected. (defaults to 'socketClosed')

#### "error" (err)

Emitted when an error occurs.

#### "spawnReset"

Fires when you cannot spawn in your bed and your spawn point gets reset.

#### "death"

Fires when you die.

#### "health"

Fires when your hp or food change.

#### "breath"

Fires when your oxygen level change.

#### "entityAttributes" (entity)

Fires when an attribute of an entity changes.

#### "entitySwingArm" (entity)
#### "entityHurt" (entity)
#### "entityDead" (entity)
#### "entityTaming" (entity)
#### "entityTamed" (entity)
#### "entityShakingOffWater" (entity)
#### "entityEatingGrass" (entity)
#### "entityHandSwap" (entity)
#### "entityWake" (entity)
#### "entityEat" (entity)
#### "entityCriticalEffect" (entity)
#### "entityMagicCriticalEffect" (entity)
#### "entityCrouch" (entity)
#### "entityUncrouch" (entity)
#### "entityEquip" (entity)
#### "entitySleep" (entity)
#### "entitySpawn" (entity)
#### "entityElytraFlew" (entity)

An entity started elytra flying.

#### "itemDrop" (entity)
#### "playerCollect" (collector, collected)

An entity picked up an item.

 * `collector` - entity that picked up the item.
 * `collected` - the entity that was the item on the ground.

#### "entityGone" (entity)
#### "entityMoved" (entity)
#### "entityDetach" (entity, vehicle)
#### "entityAttach" (entity, vehicle)

An entity is attached to a vehicle, such as a mine cart
or boat.

 * `entity` - the entity hitching a ride
 * `vehicle` - the entity that is the vehicle

#### "entityUpdate" (entity)
#### "entityEffect" (entity, effect)
#### "entityEffectEnd" (entity, effect)
#### "playerJoined" (player)
#### "playerUpdated" (player)
#### "playerLeft" (player)

#### "blockUpdate" (oldBlock, newBlock)

(It is better to use this event from bot.world instead of bot directly) Fires when a block updates. Both `oldBlock` and `newBlock` provided for
comparison.

Note that `oldBlock` may be `null`.

#### "blockUpdate:(x, y, z)" (oldBlock, newBlock)

(It is better to use this event from bot.world instead of bot directly) Fires for a specific point. Both `oldBlock` and `newBlock` provided for
comparison.

Note that `oldBlock` may be `null`.

#### "blockPlaced" (oldBlock, newBlock)

Fires when bot places block. Both `oldBlock` and `newBlock` provided for
comparison.

Note that `oldBlock` may be `null`.

#### "chunkColumnLoad" (point)
#### "chunkColumnUnload" (point)

Fires when a chunk has updated. `point` is the coordinates to the corner
of the chunk with the smallest x, y, and z values.

#### "soundEffectHeard" (soundName, position, volume, pitch)

Fires when the client hears a named sound effect.

 * `soundName`: name of the sound effect
 * `position`: a Vec3 instance where the sound originates
 * `volume`: floating point volume, 1.0 is 100%
 * `pitch`: integer pitch, 63 is 100%

#### "hardcodedSoundEffectHeard" (soundId, soundCategory, position, volume, pitch)

  Fires when the client hears a hardcoded sound effect.

   * `soundId`: id of the sound effect
   * `soundCategory`: category of the sound effect
   * `position`: a Vec3 instance where the sound originates
   * `volume`: floating point volume, 1.0 is 100%
   * `pitch`: integer pitch, 63 is 100%

#### "noteHeard" (block, instrument, pitch)

Fires when a note block goes off somewhere.

 * `block`: a Block instance, the block that emitted the noise
 * `instrument`:
   - `id`: integer id
   - `name`: one of [`harp`, `doubleBass`, `snareDrum`, `sticks`, `bassDrum`].
 * `pitch`: The pitch of the note (between 0-24 inclusive where 0 is the
   lowest and 24 is the highest). More information about how the pitch values
   correspond to notes in real life are available on the
   [official Minecraft wiki](http://minecraft.wiki/w/Note_Block).

#### "pistonMove" (block, isPulling, direction)

#### "chestLidMove" (block, isOpen, block2)
* `block`: a Block instance, the block whose lid opened. The right block if it's a double chest
* `isOpen`: number of players that have the chest open. 0 if it's closed
* `block2`: a Block instance, the other half of the block whose lid opened. null if it's not a double chest

#### "blockBreakProgressObserved" (block, destroyStage, entity)

Fires when the client observes a block in the process of being broken.

 * `block`: a Block instance, the block being broken
 * `destroyStage`: integer corresponding to the destroy progress (0-9)
 * `entity`: the entity which is breaking the block.

#### "blockBreakProgressEnd" (block, entity)

Fires when the client observes a block stops being broken.
This occurs whether the process was completed or aborted.

 * `block`: a Block instance, the block no longer being broken
 * `entity`: the entity which has stopped breaking the block

#### "diggingCompleted" (block)

 * `block` - the block that no longer exists

#### "diggingAborted" (block)

 * `block` - the block that still exists

#### "usedFirework" (fireworkEntityId)

Fires when the bot uses a firework while elytra flying.

 * `fireworkEntityId` - the entity id of the firework.

#### "move"

Fires when the bot moves. If you want the current position, use
`bot.entity.position` and for normal moves if you want the previous position, use
`bot.entity.position.minus(bot.entity.velocity)`.

#### "forcedMove"

Fires when the bot is force moved by the server (teleport, spawning, ...). If you want the current position, use
`bot.entity.position`.

#### "mount"

Fires when you mount an entity such as a minecart. To get access
to the entity, use `bot.vehicle`.

To mount an entity, use `mount`.

#### "dismount" (vehicle)

Fires when you dismount from an entity.

#### "windowOpen" (window)

Fires when you begin using a workbench, chest, brewing stand, etc.

#### "windowClose" (window)

Fires when you may no longer work with a workbench, chest, etc.

#### "sleep"

Fires when you sleep.

#### "wake"

Fires when you wake up.

#### "experience"

Fires when `bot.experience.*` has updated.

#### "scoreboardCreated" (scoreboard)

Fires when a scoreboard is added.

#### "scoreboardDeleted" (scoreboard)

Fires when a scoreboard is deleted.

#### "scoreboardTitleChanged" (scoreboard)

Fires when a scoreboard's title is updated.

#### "scoreUpdated" (scoreboard, item)

Fires when the score of a item in a scoreboard is updated.

#### "scoreRemoved" (scoreboard, item)

Fires when the score of a item in a scoreboard is removed.

#### "scoreboardPosition" (position, scoreboard)

Fires when the position of a scoreboard is updated.

#### "teamCreated" (team)

Fires when a team is added.

#### "teamRemoved" (team)

Fires when a team is removed.

#### "teamUpdated" (team)

Fires when a team is updated.

#### "teamMemberAdded" (team)

Fires when a team member or multiple members are added to a team.

#### "teamMemberRemoved" (team)

Fires when a team member or multiple members are removed from a team.

#### "bossBarCreated" (bossBar)

Fires when new boss bar is created.

#### "bossBarDeleted" (bossBar)

Fires when new boss bar is deleted.

#### "bossBarUpdated" (bossBar)

Fires when new boss bar is updated.

#### "heldItemChanged" (heldItem)

Fires when the held item is changed.

#### "physicsTick" ()

Fires every tick if bot.physicsEnabled is set to true.

#### "chat:name" (matches)

Fires when the all of a chat pattern's regexs have matches

#### "particle"

Fires when a particle is created

### Functions

#### bot.blockAt(point, extraInfos=true)

Returns the block at `point` or `null` if that point is not loaded. If `extraInfos` set to true, also returns information about signs, paintings and block entities (slower).
See `Block`.

#### bot.waitForChunksToLoad()

This function returns a `Promise`, with `void` as its argument when many chunks have loaded.

#### bot.blockInSight(maxSteps, vectorLength)

Deprecated, use `blockAtCursor` instead.

Returns the block at which bot is looking at or `null`
 * `maxSteps` - Number of steps to raytrace, defaults to 256.
 * `vectorLength` - Length of raytracing vector, defaults to `5/16`.

#### bot.blockAtCursor(maxDistance=256)

Returns the block at which bot is looking at or `null`
 * `maxDistance` - The maximum distance the block can be from the eye, defaults to 256.

#### bot.entityAtCursor(maxDistance=3.5)

Returns the entity at which bot is looking at or `null`
 * `maxDistance` - The maximum distance the entity can be from the eye, defaults to 3.5.

#### bot.blockAtEntityCursor(entity=bot.entity, maxDistance=256)

Returns the block at which specific entity is looking at or `null`
 * `entity` - Entity data as `Object`
 * `maxDistance` - The maximum distance the block can be from the eye, defaults to 256.

#### bot.canSeeBlock(block)

Returns true or false depending on whether the bot can see the specified `block`.

#### bot.findBlocks(options)

Finds the closest blocks from the given point.
 * `options` - Options for the search:
   - `point` - The start position of the search (center). Default is the bot position.
   - `matching` - A function that returns true if the given block is a match. Also supports this value being a block id or array of block ids.
   - `useExtraInfo` - To preserve backward compatibility can result in two behavior depending on the type
      - **boolean** - Provide your `matching` function more data - noticeably slower approach
      - **function** - Creates two stage matching, if block passes `matching` function it is passed further to `useExtraInfo` with additional info
   - `maxDistance` - The furthest distance for the search, defaults to 16.
   - `count` - Number of blocks to find before returning the search. Default to 1. Can return less if not enough blocks are found exploring the whole area.

Returns an array (possibly empty) with the found block coordinates (not the blocks). The array is sorted (closest first)

#### bot.findBlock(options)

Alias for `bot.blockAt(bot.findBlocks(options)[0])`. Return a single block or `null`.

#### bot.canDigBlock(block)

Returns whether `block` is diggable and within range.

#### bot.recipesFor(itemType, metadata, minResultCount, craftingTable)

Returns a list of `Recipe` instances that you could use to craft `itemType`
with `metadata`.

 * `itemType` - numerical item id of the thing you want to craft
 * `metadata` - the numerical metadata value of the item you want to craft
   `null` matches any metadata.
 * `minResultCount` - based on your current inventory, any recipe from the
   returned list will be able to produce this many items. `null` is an
   alias for `1`.
 * `craftingTable` - a `Block` instance. If `null`, only recipes that can
   be performed in your inventory window will be included in the list.

#### bot.recipesAll(itemType, metadata, craftingTable)

The same as bot.recipesFor except that it does not check whether the bot has enough materials for the recipe.

#### bot.nearestEntity(match = (entity) => { return true })

Return the nearest entity to the bot, matching the function (default to all entities). Return null if no entity is found.

Example:
```js
const cow = bot.nearestEntity(entity => entity.name.toLowerCase() === 'cow') // we use .toLowercase() because in 1.8 cow was capitalized, for newer versions that can be omitted
```

### Methods

#### bot.end(reason)

End the connection with the server.
* `reason` - Optional string that states the reason of the end.

#### bot.quit(reason)

Gracefully disconnect from the server with the given reason (defaults to 'disconnect.quitting').

#### bot.tabComplete(str, [assumeCommand], [sendBlockInSight], [timeout])

This function returns a `Promise`, with `matches` as its argument upon completion.

Requests chat completion from the server.
 * `str` - String to complete.
 * `assumeCommand` - Field sent to server, defaults to false.
 * `sendBlockInSight` - Field sent to server, defaults to true. Set this option to false if you want more performance.
 * `timeout` - Timeout in milliseconds, after which the function will return an empty array, defaults to 5000.

#### bot.chat(message)

Sends a publicly broadcast chat message. Breaks up big messages into multiple chat messages as necessary.

#### bot.whisper(username, message)

Shortcut for "/tell <username>". All split messages will be whispered to username.

#### bot.chatAddPattern(pattern, chatType, description)

Deprecated, use `addChatPattern` instead.

Adds a regex pattern to the bot's chat matching. Useful for bukkit servers where the chat format changes a lot.
 * `pattern` - regular expression to match chat
 * `chatType` - the event the bot emits when the pattern matches. Eg: "chat" or "whisper"
 * 'description ' - Optional, describes what the pattern is for

#### bot.addChatPattern(name, pattern, chatPatternOptions)

** this is an alias of `bot.addChatPatternSet(name, [pattern], chatPatternOptions)`

make an event that is called every time the pattern is matched to a message,
the event will be called `"chat:name"`, with name being the name passed
* `name` - the name used to listen for the event
* `pattern` - regular expression to match to messages received
* `chatPatternOptions` - object
  * `repeat` - defaults to true, whether to listen for this event after the first match
  * `parse` - instead of returning the actual message that was matched, return the capture groups from the regex
  * `deprecated` - (**unstable**) used by bot.chatAddPattern to keep compatibility, likely to be removed

returns a number which can be used with bot.removeChatPattern() to only delete this pattern

- :eyes: cf. [examples/chat_parsing](https://github.com/PrismarineJS/mineflayer/blob/master/examples/chat_parsing.js#L17-L36)

#### bot.addChatPatternSet(name, patterns, chatPatternOptions)

make an event that is called every time all patterns have been matched to messages,
the event will be called `"chat:name"`, with name being the name passed
* `name` - the name used to listen for the event
* `patterns` - array of regular expression to match to messages received
* `chatPatternOptions` - object
  * `repeat` - defaults to true, whether to listen for this event after the first match
  * `parse` - instead of returning the actual message that was matched, return the capture groups from the regex

returns a number which can be used with bot.removeChatPattern() to only delete this patternset

- :eyes: cf. [examples/chat_parsing](https://github.com/PrismarineJS/mineflayer/blob/master/examples/chat_parsing.js#L17-L36)

#### bot.removeChatPattern(name)

removes a chat pattern(s)
* `name` : string or number

if name is a string, all patterns that have that name will be removed
else if name is a number, only that exact pattern will be removed

#### bot.awaitMessage(...args)

promise that is resolved when one of the messages passed as an arg is resolved

Example:

```js
async function wait () {
  await bot.awaitMessage('<flatbot> hello world') // resolves on "hello world" in chat by flatbot
  await bot.awaitMessage(['<flatbot> hello', '<flatbot> world']) // resolves on "hello" or "world" in chat by flatbot
  await bot.awaitMessage(['<flatbot> hello', '<flatbot> world'], ['<flatbot> im', '<flatbot> batman']) // resolves on "hello" or "world" or "im" or "batman" in chat by flatbot
  await bot.awaitMessage('<flatbot> hello', '<flatbot> world') // resolves on "hello" or "world" in chat by flatbot
  await bot.awaitMessage(/<flatbot> (.+)/) // resolves on first message matching the regex
}
```

#### bot.setSettings(options)

See the `bot.settings` property.

#### bot.loadPlugin(plugin)

Injects a Plugin. Does nothing if the plugin is already loaded.

 * `plugin` - function

```js
function somePlugin (bot, options) {
  function someFunction () {
    bot.chat('Yay!')
  }

  bot.myPlugin = {} // Good practice to namespace plugin API
  bot.myPlugin.someFunction = someFunction
}

const bot = mineflayer.createBot({})
bot.loadPlugin(somePlugin)
bot.once('login', function () {
  bot.myPlugin.someFunction() // Yay!
})
```

#### bot.loadPlugins(plugins)

Injects plugins see `bot.loadPlugin`.
 * `plugins` - array of functions

#### bot.hasPlugin(plugin)

Checks if the given plugin is loaded (or scheduled to be loaded) on this bot.

#### bot.sleep(bedBlock)

This function returns a `Promise`, with `void` as its argument upon completion.

Sleep in a bed. `bedBlock` should be a `Block` instance which is a bed.

#### bot.isABed(bedBlock)

Return true if `bedBlock` is a bed

#### bot.wake()

This function returns a `Promise`, with `void` as its argument upon completion.

Get out of bed.

#### bot.setControlState(control, state)

This is the main method controlling the bot movements. It works similarly to pressing keys in minecraft.
For example forward with state true will make the bot move forward. Forward with state false will make the bot stop moving forward.
You may use bot.lookAt in conjunction with this to control movement. The jumper.js example shows how to use this.

 * `control` - one of ['forward', 'back', 'left', 'right', 'jump', 'sprint', 'sneak']
 * `state` - `true` or `false`

#### bot.getControlState(control)

Returns true if a control state is toggled.

* `control` - one of ['forward', 'back', 'left', 'right', 'jump', 'sprint', 'sneak']

#### bot.clearControlStates()

Sets all controls to off.

#### bot.getExplosionDamages(entity, position, radius, [rawDamages])

Returns how much damage will be done to the entity in a radius around the position of the explosion.
It will return `null` if the entity has no armor and rawDamages is not set to true, since the function can't calculate the damage with armor if there is no armor.

* `entity` - Entity instance
* `position` - [Vec3](https://github.com/andrewrk/node-vec3) instance
* `radius` - the explosion radius as a number
* `rawDamages` - optional, if true it ignores armor in the calculation

#### bot.lookAt(point, [force])

This function returns a `Promise`, with `void` as its argument when you are looking at `point`.

 * `point` [Vec3](https://github.com/andrewrk/node-vec3) instance - tilts your head so that it is directly facing this point.
 * `force` - See `force` in `bot.look`

#### bot.look(yaw, pitch, [force])

This function returns a `Promise`, with `void` as its argument called when you are looking at `yaw` and `pitch`.

Set the direction your head is facing.

 * `yaw` - The number of radians to rotate around the vertical axis, starting
   from due east. Counter clockwise.
 * `pitch` - Number of radians to point up or down. 0 means straight forward.
   pi / 2 means straight up. -pi / 2 means straight down.
 * `force` - If present and true, skips the smooth server-side transition.
   Specify this to true if you need the server to know exactly where you
   are looking, such as for dropping items or shooting arrows. This is not
   needed for client-side calculation such as walking direction.

#### bot.updateSign(block, text, back = false)

Changes the text on the sign. On Minecraft 1.20 and newer, a truthy `back` will try setting the text on the back of a sign (only visible if not attached to a wall).

#### bot.equip(item, destination)

This function returns a `Promise`, with `void` as its argument when you have successfully equipped the item or when you learn that you have failed to equip the item.

Equips an item from your inventory. If the argument `item` is of Instance `Item` equip will equip this specific item from its window slot. If the argument `item` is of type `number` equip will equip the first item found with that id searched by rising slot id (Hotbar is searched last. Armor, crafting, crafting result and off-hand slots are excluded).

 * `item` - `Item` instance or `number` for item id. See `window.items()`.
 * `destination`
   - `"hand"` - `null` aliases to this
   - `"head"`
   - `"torso"`
   - `"legs"`
   - `"feet"`
   - `"off-hand"` - when available

#### bot.unequip(destination)

This function returns a `Promise`, with `void` as its argument upon completion.

Remove an article of equipment.

#### bot.tossStack(item)

This function returns a `Promise`, with `void` as its argument when tossing is done.

 * `item` - the stack of items you wish to toss
   truthy, you were not able to complete the toss.

#### bot.toss(itemType, metadata, count)

This function returns a `Promise`, with `void` as its argument once tossing is complete.

 * `itemType` - numerical id of the item you wish to toss
 * `metadata` - metadata of the item you wish to toss. Use `null`
   to match any metadata
 * `count` - how many you want to toss. `null` is an alias for `1`.

#### bot.elytraFly()

This function returns a `Promise`, with `void` as its argument once activating
elytra flight is complete. It will throw an Error if it fails.

#### bot.dig(block, [forceLook = true], [digFace])

This function returns a `Promise`, with `void` as its argument when the block is broken or you are interrupted.

Begin digging into `block` with the currently equipped item.
See also "diggingCompleted" and "diggingAborted" events.

Note that once you begin digging into a block, you may not
dig any other blocks until the block has been broken, or you call
`bot.stopDigging()`.

 * `block` - the block to start digging into
 * `forceLook` - (optional) if true, look at the block and start mining instantly. If false, the bot will slowly turn to the block to mine. Additionally, this can be assigned to 'ignore' to prevent the bot from moving its head at all. Also, this can be assigned to 'raycast' to raycast from the bots head to place where the bot is looking.
 * `digFace` - (optional) Default is 'auto' looks at the center of the block and mines the top face. Can also be a vec3 vector
 of the face the bot should be looking at when digging the block. For example: ```vec3(0, 1, 0)``` when mining the top. Can also be 'raycast' raycast checks if there is a face visible by the bot and mines that face. Useful for servers with anti cheat.

If you call bot.dig twice before the first dig is finished, you will get a fatal 'diggingAborted' error.

#### bot.stopDigging()

#### bot.digTime(block)

Tells you how long it will take to dig the block, in milliseconds.

#### bot.acceptResourcePack()

Accepts resource pack.

#### bot.denyResourcePack()

Denies resource pack.

#### bot.placeBlock(referenceBlock, faceVector)

This function returns a `Promise`, with `void` as its argument when the server confirms that the block has indeed been placed.

 * `referenceBlock` - the block you want to place a new block next to
 * `faceVector` - one of the six cardinal directions, such as `new Vec3(0, 1, 0)` for the top face,
   indicating which face of the `referenceBlock` to place the block against.

The new block will be placed at `referenceBlock.position.plus(faceVector)`.

#### bot.placeEntity(referenceBlock, faceVector)

This function returns a `Promise`, with `Entity` as its argument upon completion.

 * `referenceBlock` - the block you want to place the entity next to
 * `faceVector` - one of the six cardinal directions, such as `new Vec3(0, 1, 0)` for the top face,
   indicating which face of the `referenceBlock` to place the block against.

The new block will be placed at `referenceBlock.position.plus(faceVector)`.

#### bot.activateBlock(block, direction?: Vec3, cursorPos?: Vec3)

This function returns a `Promise`, with `void` as its argument upon completion.

Punch a note block, open a door, etc.

 * `block` - the block to activate
 * `direction` Optional defaults to `new Vec3(0, 1, 0)` (up). A vector off the direction the container block should be interacted with. Does nothing when a container entity is targeted.
 * `cursorPos` Optional defaults to `new Vec3(0.5, 0.5, 0.5)` (block center). The curos position when opening the block instance. This is send with the activate block packet. Does nothing when a container entity is targeted.

#### bot.activateEntity(entity)

This function returns a `Promise`, with `void` as its argument upon completion.

Activate an entity, useful for villager for example.

 * `entity` - the entity to activate

#### bot.activateEntityAt(entity, position)

This function returns a `Promise`, with `void` as its argument upon completion.

Activate an entity at the given position, useful for armor stands.

 * `entity` - the entity to activate
 * `position` - the world position to click at

#### bot.consume()

This function returns a `Promise`, with `void` as its argument when consume ends.

Eat / drink currently held item


#### bot.fish()

This function returns a `Promise`, with `void` as its argument when fishing ends.

Use fishing rod


#### bot.activateItem(offHand=false)

Activates the currently held item. This is how you eat, shoot bows, throw an
egg, activate firework rockets, etc.

Optional parameter is `false` for main hand and `true` for off hand.

#### bot.deactivateItem()

Deactivates the currently held item. This is how you release an arrow, stop eating, etc.

#### bot.useOn(targetEntity)

Use the currently held item on an `Entity` instance. This is how you apply a saddle and
use shears.

#### bot.attack(entity, swing = true)

Attack a player or a mob.

 * `entity` is a type of entity. To get a specific entity use [bot.nearestEntity()](#botnearestentitymatch--entity---return-true-) or [bot.entities](#botentities).
 * `swing` Default to `true`. If false the bot does not swing its arm when attacking.

#### bot.swingArm([hand], showHand)

Play an arm swing animation.

 * `hand` can take `left` or `right` which is the arm that is animated. Default: `right`
 * `showHand` is a boolean whether to add the hand to the packet, Default: `true`

#### bot.mount(entity)

Mount a vehicle. To get back out, use `bot.dismount`.

#### bot.dismount()

Dismounts from the vehicle you are in.

#### bot.moveVehicle(left,forward)

Moves the vehicle :

 * left can take -1 or 1 : -1 means right, 1 means left
 * forward can take -1 or 1 : -1 means backward, 1 means forward

All the direction are relative to where the bot is looking at

#### bot.setQuickBarSlot(slot)

 * `slot` - 0-8 the quick bar slot to select.

#### bot.craft(recipe, count, craftingTable)

This function returns a `Promise`, with `void` as its argument when the crafting is complete and your inventory is updated.

 * `recipe` - A `Recipe` instance. See `bot.recipesFor`.
 * `count` - How many times you wish to perform the operation.
   If you want to craft planks into `8` sticks, you would set
   `count` to `2`. `null` is an alias for `1`.
 * `craftingTable` - A `Block` instance, the crafting table you wish to
   use. If the recipe does not require a crafting table, you may use
   `null` for this argument.

#### bot.writeBook(slot, pages)

This function returns a `Promise`, with `void` as its argument when the writing was successfully or an error occurred.

 * `slot` is in inventory window coordinates (where 36 is the first quickbar slot, etc.).
 * `pages` is an array of strings represents the pages.

#### bot.openContainer(containerBlock or containerEntity, direction?, cursorPos?)
Opens a block container or entity.

 * `containerBlock` or `containerEntity` The block instance to open or the entity to open.
 * `direction` Optional defaults to `new Vec3(0, 1, 0)` (up). A vector off the direction the container block should be interacted with. Does nothing when a container entity is targeted.
 * `cursorPos` Optional defaults to `new Vec3(0.5, 0.5, 0.5)` (block center). The curos position when opening the block instance. This is send with the activate block packet. Does nothing when a container entity is targeted.

Returns a promise on a `Container` instance which represents the container you are opening.

#### bot.openChest(chestBlock or minecartchestEntity, direction?, cursorPos?)

Deprecated. Same as `openContainer`

#### bot.openFurnace(furnaceBlock)

Returns a promise on a `Furnace` instance which represents the furnace you are opening.

#### bot.openDispenser(dispenserBlock)

Deprecated. Same as `openContainer`

#### bot.openEnchantmentTable(enchantmentTableBlock)

Returns a promise on an `EnchantmentTable` instance which represents the enchantment table
you are opening.

#### bot.openAnvil(anvilBlock)

Returns a promise on an `anvil` instance which represents the anvil you are opening.

#### bot.openVillager(villagerEntity)

Returns a promise on a `Villager` instance which represents the trading window you are opening.
You can listen to the `ready` event on this `Villager` to know when it's ready

#### bot.trade(villagerInstance, tradeIndex, [times])

This function returns a `Promise`, with `void` as its argument upon completion.

Uses the open `villagerInstance` to trade.

#### bot.setCommandBlock(pos, command, [options])

Set a command block's properties at `pos`.
Example `options` argument:
```js
{
  mode: 2,
  trackOutput: true,
  conditional: false,
  alwaysActive: true
}
```
options.mode can have 3 values: 0 (SEQUENCE), 1 (AUTO), 2 (REDSTONE)
All options attributes are false by default, except mode which is 2 (as to replicate the default command block in Minecraft).

#### bot.supportFeature(name)

This can be used to check is a specific feature is available in the current Minecraft version. This is usually only required for handling version-specific functionality.

The list of available features can be found inside the [./lib/features.json](https://github.com/PrismarineJS/mineflayer/blob/master/lib/features.json) file.

#### bot.waitForTicks(ticks)

This is a promise-based function that waits for a given number of in-game ticks to pass before continuing. This is useful for quick timers that need to function with specific timing, regardless of the given physics tick speed of the bot. This is similar to the standard Javascript setTimeout function, but runs on the physics timer of the bot specifically.

#### bot.respawn()

When `respawn` option is disabled, you can call this method manually to respawn.

### Lower level inventory methods

These are lower level methods for the inventory, they can be useful sometimes but prefer the inventory methods presented above if you can.

#### bot.clickWindow(slot, mouseButton, mode)

This function returns a `Promise`, with `void` as its argument upon completion.

mode support:
  - stable:
    - mouse clicks (0)

  - experimental:
    - shift clicks (1)
    - number clicks (2)
    - middle clicks (3)
    - drop clicks (4)

  - unimplemented:
    - drag clicks (5)
    - double clicks (6)

Click on the current window. See details at https://minecraft.wiki/w/Protocol#Click_Container

Prefer using bot.simpleClick.*

#### bot.putSelectedItemRange(start, end, window, slot)

This function returns a `Promise`, with `void` as its argument upon completion.

Put the item at `slot` in the specified range.

#### bot.putAway(slot)

This function returns a `Promise`, with `void` as its argument upon completion.

Put the item at `slot` in the inventory.

#### bot.closeWindow(window)

Close the `window`.

#### bot.transfer(options)

This function returns a `Promise`, with `void` as its argument upon completion.

Transfer some kind of item from one range to an other. `options` is an object containing :

 * `window` : Optional. the window where the item will be moved
 * `itemType` : the type of the moved items
 * `metadata` : Optional. the metadata of the moved items
 * `sourceStart` and `sourceEnd` : the source range. `sourceEnd` is optional and will default to `sourceStart` + 1
 * `destStart` and `destEnd` : the dest Range. `destEnd` is optional and will default to `destStart` + 1
 * `count` : the amount of items to transfer. Default: `1`
 * `nbt` : nbt data of the item to transfer. Default: `nullish` (ignores nbt)

#### bot.openBlock(block, direction?: Vec3, cursorPos?: Vec3)

Open a block, for example a chest, returns a promise on the opening `Window`.

 * `block` is the block the bot will open.
 * `direction` Optional defaults to `new Vec3(0, 1, 0)` (up). A vector off the direction the container block should be interacted with. Does nothing when a container entity is targeted.
 * `cursorPos` Optional defaults to `new Vec3(0.5, 0.5, 0.5)` (block center). The curos position when opening the block instance. This is send with the activate block packet. Does nothing when a container entity is targeted.

#### bot.openEntity(entity)

Open an entity with an inventory, for example a villager, returns a promise on the opening `Window`.

 * `entity` is the entity the bot will open

#### bot.moveSlotItem(sourceSlot, destSlot)

This function returns a `Promise`, with `void` as its argument upon completion.

Move an item from `sourceSlot` to `destSlot` in the current window.

#### bot.updateHeldItem()

Update `bot.heldItem`.

#### bot.getEquipmentDestSlot(destination)

Gets the inventory equipment slot id for the given equipment destination name.

Available destinations are:
* head
* torso
* legs
* feet
* hand
* off-hand

### bot.creative

This collection of apis is useful in creative mode.
Detecting and changing gamemodes is not implemented here,
but it is assumed and often required that the bot be in creative mode for these features to work.

#### bot.creative.setInventorySlot(slot, item)

This function returns a `Promise`, with `void` as its argument when gets fired when the server sets the slot.

Gives the bot the specified item in the specified inventory slot.

 * `slot` is in inventory window coordinates (where 36 is the first quickbar slot, etc.).
 * `item` is a [prismarine-item](https://github.com/PrismarineJS/prismarine-item) instance specified with arbitrary metadata, nbtdata, etc.
    If `item` is `null`, the item at the specified slot is deleted.

If this method changes anything, you can be notified via `bot.inventory.on("updateSlot")`.

#### bot.creative.clearSlot(slot)

This function returns a `Promise`, with `void` as its argument when gets fired when the server clears the slot.

Makes the sets the item in the slot given to null.

 * `slot` is in inventory window coordinates (where 36 is the first quickbar slot, etc.).

#### bot.creative.clearInventory()

This function returns a `Promise`, with `void` as its argument when gets fired when the server clears the slot.

#### bot.creative.flyTo(destination)

This function returns a `Promise`, with `void` as its argument when the bot arrives at the destination.

Calls `startFlying()` and moves at a constant speed through 3d space in a straight line to the destination.
`destination` is a `Vec3`, and often the `x` and `z` coordinates will end with `.5`.
This operation will not work if there is an obstacle in the way,
so it is advised to fly very short distances at a time.

This method does not attempt any path finding.
It is expected that a path finding implementation will use this method to move < 2 blocks at a time.

To resume normal physics, call `stopFlying()`.

#### bot.creative.startFlying()

Sets `bot.physics.gravity` to `0`.
To resume normal physics, call `stopFlying()`.

This method is useful if you want to hover while digging the ground below you.
It is not necessary to call this function before calling `flyTo()`.

Note that while flying, `bot.entity.velocity` will not be accurate.

#### bot.creative.stopFlying()

Restores `bot.physics.gravity` to its original value.


================================================
FILE: docs/br/CONTRIBUTING_BR.md
================================================
# Contribuir

O Mineflayer foi originalmente criado principalmente por [andrewrk](http://github.com/andrewrk), mas tem sido muito aprimorado e corrigido por muitos [contribuidores](https://github.com/andrewrk/mineflayer/graphs/contributors). Portanto, é importante saber a melhor maneira de contribuir para o Mineflayer.

## Organização de Problemas

Temos 3 etiquetas para 3 fases de organização de problemas:

* Estágio 1: (Fase 1) criado por alguém novo no projeto, não sabemos se merece uma implementação / solução
* Estágio 2: (Fase 2) ideia promissora, mas é necessário pensar mais sobre o assunto antes de implementá-lo
* Estágio 3: (Fase 3) a ideia é muito precisa, só precisa ser programada

Links como https://github.com/PrismarineJS/mineflayer/issues?q=is%3Aopen+is%3Aissue+-label%3AStage1 podem ser usados como filtro para a fase 1 se você estiver procurando coisas prontas para serem contribuídas.

## Criando Testes
O Mineflayer possui dois tipos de testes:

 * [Testes internos](test/internalTest.js): testes feitos com um servidor simples criado com o node-minecraft-protocol
 * [Testes externos](test/externalTests/): testes feitos com um servidor Vanilla
 
O objetivo desses testes é determinar automaticamente o que funciona e o que não funciona no Mineflayer, tornando mais fácil a correção de problemas.

### Criando um Teste Externo

Para criar um teste externo, basta criar um arquivo em [test/externalTests](test/externalTests).

Um exemplo: [test/externalTests/digAndBuild.js](https://github.com/PrismarineJS/mineflayer/blob/master/test/externalTests/digAndBuild.js)

Esse arquivo deve exportar uma função que retorna uma função ou um array de funções que recebem o objeto bot e um callback como parâmetros, e deve conter verificações para determinar se a função testada falhou.

## Criando um Plugin de Terceiros
O Mineflayer suporta plugins; qualquer pessoa pode criar um plugin que adiciona uma API de nível mais alto acima do Mineflayer.

Vários plugins de terceiros foram [criados](https://github.com/andrewrk/mineflayer#third-party-plugins).

Para criar um novo plugin, você deve:

1. Criar um novo repositório.
2. No seu arquivo index.js, exportar uma função para inicializar o plugin com o argumento Mineflayer ([exemplo](https://github.com/andrewrk/mineflayer-navigate/blob/e24cb6a868ce64ae43bea2d035832c15ed01d301/index.js#L18)).
3. Essa função deve retornar uma função para introduzir o plugin com o objeto bot ([exemplo](https://github.com/andrewrk/mineflayer-navigate/blob/e24cb6a868ce64ae43bea2d035832c15ed01d301/index.js#L23)).
4. A partir dessa função, você pode adicionar mais funcionalidades ao bot ([exemplo](https://github.com/andrewrk/mineflayer-navigate/blob/e24cb6a868ce64ae43bea2d035832c15ed01d301/index.js#L32)).

Como o objeto Mineflayer é passado como argumento, esse plugin de terceiros não deve depender do Mineflayer (não deve haver referência ao Mineflayer no package.json).

Veja um [exemplo completo](https://github.com/andrewrk/mineflayer-navigate/tree/e24cb6a868ce64ae43bea2d035832c15ed01d301) aqui.

## Relatando Bugs
O Mineflayer funciona bem na maioria das situações, mas às vezes ainda pode ter bugs.

Ao encontrar um bug, é melhor relatar o erro fornecendo as seguintes informações:

* O que você está tentando fazer (o objetivo em inglês).
* O que você tentou (o código).
* O que aconteceu.
* O que você esperava que acontecesse.

## Código do Mineflayer
Aqui estão algumas coisas a se considerar ao criar uma solicitação de pull (pull request) ou fazer um commit:

### Tratamento de Erros
Na maioria dos casos, o Mineflayer não deve quebrar ou travar o bot. Mesmo se algo der errado, o bot pode seguir uma rota alternativa para alcançar o objetivo.

Isso significa que não devemos usar `throw new Error("erro")`, mas sim passar o erro junto com o callback.

Por exemplo:

```js
function myfunction (param1, callback) {
  let toDo = 1
  toDo = 2
  if (toDo === 2) { // everything worked (todo está funcionado)
    callback()
  } else {
    callback(new Error('something failed')) // (algo falhou)
  }
}
```

Veja outro exemplo no [código do Mineflayer](https://github.com/andrewrk/mineflayer/blob/a8736c4ea473cf1a609c5a29046c0cdad006d429/lib/plugins/bed.js#L10).

### Atualizando a Documentação
A tabela de conteúdo no arquivo docs/api.md é gerada com o Doctoc. Após atualizar o arquivo, você deve executar doctoc docs/api.md para atualizar a tabela de conteúdo.

Esta documentação não é oficialmente mantida; para ver as informações mais recentes, consulte a documentação original: [unstable_api](../CONTRIBUTING.md).

================================================
FILE: docs/br/FAQ_BR.md
================================================
## Perguntas Frequentes

Este documento de perguntas frequentes tem o objetivo de ajudar as pessoas com informações básicas.

## Como ocultar erros?

Para ocultar erros, você pode adicionar a opção `hideErrors: true` nas configurações ao criar o bot. Também é possível usar os seguintes eventos:

```js
client.on('error', () => {})
client.on('end', () => {})
```

## Meu evento de chat não está sendo emitido em um servidor personalizado. Como posso resolver isso?

Alguns servidores Spigot, em particular certos plugins, utilizam formatos personalizados de chat. Nesse caso, é necessário analisar esses formatos com expressões regulares personalizadas. Recomenda-se ler e modificar o arquivo [chat_parsing.js](https://github.com/PrismarineJS/mineflayer/blob/master/examples/chat_parsing.js) para que funcione com o plugin de chat específico do seu servidor. Você também pode consultar http://prismarinejs.github.io/mineflayer/#/tutorial?id=custom-chat para obter mais informações.

## Como posso coletar informações de um plugin de chat personalizado?

A maioria dos servidores de Minecraft possui plugins que enviam mensagens ao chat quando ocorrem eventos. Se a informação enviada for simples, você pode utilizar a solução mencionada anteriormente. No entanto, se as mensagens contêm muita informação em um único bloco de texto, outra opção é utilizar o evento `"messagestr"`, que permite analisar as mensagens de forma mais fácil.

**Exemplo:**

Suponha que a mensagem seja semelhante a esta:

```
(!) U9G ganhou o /jackpot e recebeu
$26,418,402,450! Eles compraram 2,350,000 (76.32%) bilhetes
de um total de 3,079,185 bilhetes vendidos!
```

```js
const regex = {
  first: /\(!\) (.+) ganhou o \/jackpot e recebeu +/,
  second: /\$(.+)! Eles compraram (.+) \((.+)%\) bilhetes do total de /,
  third: /(.+) bilhetes vendidos!/
}

let jackpot = {}
bot.on('messagestr', msg => {
  if (regex.first.test(msg)) {
    const username = msg.match(regex.first)[1]
    jackpot.username = username
  } else if (regex.second.test(msg)) {
    const [, moneyWon, boughtTickets, winPercent] = msg.match(regex.second)
    jackpot.moneyWon = parseInt(moneyWon.replace(/,/g, ''))
    jackpot.boughtTickets = parseInt(boughtTickets.replace(/,/g, ''))
    jackpot.winPercent = parseFloat(winPercent)
  } else if (regex.third.test(msg)) {
    const totalTickets = msg.match(regex.third)[1]
    jackpot.totalTickets = parseInt(totalTickets.replace(/,/g, ''))
    onDone(jackpot)
    jackpot = {}
  }
})
```

## Como posso enviar um comando?

Usando `bot.chat()`.

**Exmemplo:**
```js
bot.chat('/give @p diamond')
```

### É possível criar vários bots e controlá-los separadamente?

Você pode criar bots diferentes com a função `createBot` e executar ações diferentes para cada um deles. Dê uma olhada no arquivo `multiple.js` para mais informações.

### Como faço para o bot largar todo o seu inventário?

Você pode usar a função `bot.inventory.items()` para obter uma matriz dos itens no inventário do bot. Você pode criar uma função recursiva para largar cada item usando `bot.toss()`. Veja um exemplo [aqui](https://gist.github.com/dada513/3d88f772be4224b40f9e5d1787bd63e9).

### Como vejo os pacotes que foram enviados/recebidos?

Você pode ativar o modo de depuração. Para obter mais informações, consulte [este link](https://github.com/PrismarineJS/mineflayer/blob/master/docs/br/README_BR.md#depuraci%C3%B3n).

### Quero evitar desconexões devido a lag no servidor, como posso fazer isso?

Uma maneira de evitar desconexões devido à latência no servidor é aumentar o valor na opção `checkTimeoutInterval` (por exemplo, `300*1000`, que representa 5 minutos, em vez do valor padrão, que é 30 segundos). Se mesmo assim você continuar sendo desconectado do servidor, você pode se reconectar automaticamente usando este exemplo [aqui](https://github.com/PrismarineJS/mineflayer/blob/master/examples/reconnector.js).

### Como posso obter a descrição/texto de um item?

Você pode usar a propriedade `item.nbt`. É recomendável utilizar a biblioteca `prismarine-nbt`. O método `nbt.simplify()` pode ser útil para simplificar a obtenção da descrição de um item.

**Exemplo:**
```js
function getLore (item) {
  let message = ''
  if (item.nbt == null) return message

  const nbt = require('prismarine-nbt')
  const ChatMessage = require('prismarine-chat')(bot.version)

  const data = nbt.simplify(item.nbt)
  const display = data.display
  if (display == null) return message

  const lore = display.Lore
  if (lore == null) return message
  for (const line of lore) {
    message += new ChatMessage(line).toString()
    message += '\n'
  }

  return message
}
```

### Como posso enviar uma mensagem do console para o servidor?

Você pode usar uma biblioteca como `repl` para ler o que você escreve no console e usar `bot.chat()` para enviá-lo para o servidor. Você pode encontrar um exemplo [aqui](https://github.com/PrismarineJS/mineflayer/blob/master/examples/repl.js).

### Ao criar um plugin, como posso especificar outro plugin como dependência?

Na função `inject()` do seu plugin, você pode executar a função `bot.loadPlugin()` para carregar esse plugin. Se o plugin já estiver carregado anteriormente, nada acontecerá.

Nota: a ordem em que os plugins são carregados é dinâmica; você nunca deve chamar outro plugin em sua função `inject()`.

### Como posso usar um proxy SOCKS5?

Nas opções de `mineflayer.createBot(opções)`, remova o seu `host` das opções e coloque as informações necessárias nas variáveis `PROXY_IP`, `PROXY_PORT`, `PROXY_USERNAME`, `PROXY_PASSWORD`, `MC_SERVER_IP` e `MC_SERVER_PORT`. Em seguida, adicione o seguinte ao seu objeto de opções:

```js
connect: (client) => {
  socks.createConnection({
    proxy: {
      host: PROXY_IP,
      port: PROXY_PORT,
      type: 5,
      userId: PROXY_USERNAME,
      password: PROXY_PASSWORD
    },
    command: 'connect',
    destination: {
      host: MC_SERVER_IP,
      port: MC_SERVER_PORT
    }
  }, (err, info) => {
    if (err) {
      console.log(err)
      return
    }
    client.setSocket(info.socket)
    client.emit('connect')
  })
}
```

# Erros Comuns

### `UnhandledPromiseRejectionWarning: Error: Failed to read asymmetric key`

Isso ocorre quando você fornece uma versão incorreta ao mineflayer, ou o mineflayer detecta a versão errada.

### `TypeError: Cannot read property '?' of undefined`

Você pode estar tentando acessar uma propriedade do bot que ainda não existe; tente acessar a propriedade após o evento `spawn`.

### `SyntaxError: Unexpected token '?'`

Atualize a versão do seu Node.js.

### O bot não consegue quebrar/colocar blocos ou abrir baús

Verifique se a proteção do spawn não está impedindo o bot de realizar a ação.

Esta documentação não é oficial. Para as informações mais atualizadas, consulte a documentação original: [FAQ](../FAQ.md).

================================================
FILE: docs/br/README_BR.md
================================================
# Mineflayer

[![NPM version](https://badge.fury.io/js/mineflayer.svg)](http://badge.fury.io/js/mineflayer)
[![Build Status](https://github.com/PrismarineJS/mineflayer/workflows/CI/badge.svg)](https://github.com/PrismarineJS/mineflayer/actions?query=workflow%3A%22CI%22)
[![Discord](https://img.shields.io/badge/chat-on%20discord-brightgreen.svg)](https://discord.gg/GsEFRM8)
[![Gitter](https://img.shields.io/badge/chat-on%20gitter-brightgreen.svg)](https://gitter.im/PrismarineJS/general)
[![Irc](https://img.shields.io/badge/chat-on%20irc-brightgreen.svg)](https://irc.gitter.im/)

[![Try it on gitpod](https://img.shields.io/badge/try-on%20gitpod-brightgreen.svg)](https://gitpod.io/#https://github.com/PrismarineJS/mineflayer)

| <sub>EN</sub> [English](../README.md) | <sub>RU</sub> [русский](../ru/README_RU.md) | <sub>ES</sub> [Español](../es/README_ES.md) | <sub>FR</sub> [Français](../fr/README_FR.md) | <sub>TR</sub> [Türkçe](../tr/README_TR.md) | <sub>ZH</sub> [中文](../zh/README_ZH_CN.md) | <sub>BR</sub> [Português](../br/README_BR.md) |
|-------------------------|----------------------------|----------------------------|----------------------------|----------------------------|-----------------|-----------------|

Crie bots para o Minecraft com uma API JavaScript poderosa, estável e de alto nível.

Primeira vez usando o Node.js? Você pode querer começar com o tutorial [tutorial](../tutorial.md)

## Recursos

 * Suporta Minecraft 1.8, 1.9, 1.10, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19 e 1.20.
 * Conhecimento e rastreamento de entidades.
 * Conhecimento de blocos. Você pode consultar o mundo ao seu redor em milissegundos para encontrar qualquer bloco.
 * Física e movimento - lida com todas as caixas delimitadoras.
 * Ataque a entidades e uso de veículos.
 * Gerenciamento de inventário.
 * Criação, baús, dispensadores, mesas de encantamento.
 * Escavação e construção.
 * Diversas funcionalidades, como saber sua saúde e se está chovendo.
 * Ativação de blocos e uso de itens.
 * Chat.

### Planos para o Futuro
- Dê uma olhada em nossos [projetos atuais](https://github.com/PrismarineJS/mineflayer/wiki/Big-Prismarine-projects)

## Instalação
- Primeiro, instale o Node.js >= 18 a partir do [nodejs.org](https://nodejs.org/)

`npm install mineflayer`

## Documentação

| Link | Descrição |
|---|---|
| [tutorial](../tutorial.md) | Comece com o Node.js e o Mineflayer |
| [FAQ_BR.md](FAQ_BR.md) | Alguma dúvida? Confira isso |
| [api_br.md](api_br.md) [unstable_api_br.md](unstable_api_br.md) | Toda a documentação da API |
| [history.md](../history.md) | Histórico de mudanças do Mineflayer |
| [examples/](https://github.com/PrismarineJS/mineflayer/tree/master/examples) | Todos os exemplos do Mineflayer |

## Contribuições

Por favor, leia [CONTRIBUTING_BR.md](CONTRIBUTING_BR.md) e [prismarine-contribute](https://github.com/PrismarineJS/prismarine-contribute)

## Uso

**Vídeos**

Você pode encontrar um tutorial que explica o processo de começar um bot [aqui](https://www.youtube.com/watch?v=ltWosy4Z0Kw) (em inglês).

Se você quiser aprender mais, pode verificar [aqui,](https://www.youtube.com/playlist?list=PLh_alXmxHmzGy3FKbo95AkPp5D8849PEV) os códigos usados nos vídeos [aqui](https://github.com/TheDudeFromCI/Mineflayer-Youtube-Tutorials)

[<img src="https://img.youtube.com/vi/ltWosy4Z0Kw/0.jpg" alt="tutorial 1" width="200">](https://www.youtube.com/watch?v=ltWosy4Z0Kw)
[<img src="https://img.youtube.com/vi/UWGSf08wQSc/0.jpg" alt="tutorial 2" width="200">](https://www.youtube.com/watch?v=UWGSf08wQSc)
[<img src="https://img.youtube.com/vi/ssWE0kXDGJE/0.jpg" alt="tutorial 3" width="200">](https://www.youtube.com/watch?v=ssWE0kXDGJE)
[<img src="https://img.youtube.com/vi/walbRk20KYU/0.jpg" alt="tutorial 4" width="200">](https://www.youtube.com/watch?v=walbRk20KYU)

**Começando**

Se não for especificada uma versão, a versão do servidor será detectada automaticamente. Se nenhuma forma de autenticação for especificada, o login da Mojang será usado automaticamente.

### Exemplo: echo
```js
const mineflayer = require('mineflayer')

const bot = mineflayer.createBot({
  host: 'localhost', // IP do servidor de Minecraft
  username: 'email@example.com', // Nome de usuário da conta, e-mail se for premium
  password: '12345678' // Senha para servidores premium
  // port: 25565, // Altere apenas se for um servidor que não usa a porta padrão (25565)
  // version: false, // Altere apenas se for necessário uma versão específica
  // auth: 'mojang', // Altere apenas se você tiver uma conta Microsoft (nesse caso, seria auth: 'microsoft')
})

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

// Imprimir erros e o motivo do kick se você for expulso:
bot.on('kicked', (reason, loggedIn) => console.log(reason, loggedIn))
bot.on('error', err => console.log(err))
```

### Veja o que o seu bot faz

Graças ao projeto [prismarine-viewer](https://github.com/PrismarineJS/prismarine-viewer), você pode visualizar em uma guia do seu navegador o que o seu bot está fazendo.

Tudo o que você precisa fazer é executar `npm install prismarine-viewer` e adicionar o seguinte ao seu bot:

```js
const { mineflayer: mineflayerViewer } = require('prismarine-viewer')
bot.once('spawn', () => {
  mineflayerViewer(bot, { port: 3007, firstPerson: true }) // a porta é onde o plug-in será hospedado no navegador, e firstPerson é para escolher se você deseja a visualização em primeira pessoa ou não
})
```

E você poderá ver uma representação *ao vivo* como esta:

[<img src="https://prismarinejs.github.io/prismarine-viewer/test_1.16.1.png" alt="viewer" width="500">](https://prismarinejs.github.io/prismarine-viewer/)

#### Exemplos Ruins

| Exemplo | Descrição |
|---|---|
| [viewer](https://github.com/PrismarineJS/mineflayer/tree/master/examples/viewer) | Visualize o que seu bot vê no jogo |
| [pathfinder](https://github.com/Karang/mineflayer-pathfinder/blob/master/examples/test.js) | Faça seu bot se locomover automaticamente para qualquer localização |
| [chest](https://github.com/PrismarineJS/mineflayer/blob/master/examples/chest.js) | Aprenda a usar baús, fornos, dispensadores e mesas de encantamento |
| [digger](https://github.com/PrismarineJS/mineflayer/blob/master/examples/digger.js) | Aprenda como criar um bot que pode quebrar blocos |
| [discord](https://github.com/PrismarineJS/mineflayer/blob/master/examples/discord.js) | Conecte um bot Discord com um bot Mineflayer |
| [jumper](https://github.com/PrismarineJS/mineflayer/blob/master/examples/jumper.js) | Aprenda a se mover, pular, usar veículos e atacar entidades próximas |
| [ansi](https://github.com/PrismarineJS/mineflayer/blob/master/examples/ansi.js) | Exibe todas as mensagens do chat no console com suas cores correspondentes |
| [guard](https://github.com/PrismarineJS/mineflayer/blob/master/examples/guard.js) | Crie um bot que defenda uma área predefinida de mobs |
| [multiple-from-file](https://github.com/PrismarineJS/mineflayer/blob/master/examples/multiple_from_file.js) | Use um arquivo de texto com contas para criar bots |

Mais exemplos na pasta de [exemplos](https://github.com/PrismarineJS/mineflayer/tree/master/examples)

### Módulos

A maioria do desenvolvimento está ocorrendo em pequenos módulos npm que são usados pelo Mineflayer.

#### O Caminho do Node™

> "Quando os aplicativos são bem feitos, eles são apenas o resíduo realmente específico da aplicação que não pode ser tão facilmente abstraído. Todos os componentes legais e reutilizáveis sublimam no GitHub e no npm, onde todos podem colaborar para avançar a comunidade." — substack de ["como eu escrevo módulos"](https://gist.github.com/substack/5075355)

#### Módulos
Estes são os principais módulos que compõem o Mineflayer:

| Módulo | Descrição |
|---|---|
| [minecraft-protocol](https://github.com/PrismarineJS/node-minecraft-protocol) | Analisa e cria pacotes do Minecraft, autenticação e criptografia.
| [minecraft-data](https://github.com/PrismarineJS/minecraft-data) | Módulo independente de linguagem que fornece dados do Minecraft para clientes, servidores e bibliotecas.
| [prismarine-physics](https://github.com/PrismarineJS/prismarine-physics) | Motor de física para entidades do Minecraft
| [prismarine-chunk](https://github.com/PrismarineJS/prismarine-chunk) | Representa um pedaço do Minecraft
| [node-vec3](https://github.com/PrismarineJS/node-vec3) | Usa vetores 3D com testes sólidos
| [prismarine-block](https://github.com/PrismarineJS/prismarine-block) | Representa um bloco e suas informações associadas no Minecraft
| [prismarine-chat](https://github.com/PrismarineJS/prismarine-chat) | Analisador de mensagens de chat do Minecraft (retirado do Mineflayer)
| [node-yggdrasil](https://github.com/PrismarineJS/node-yggdrasil) | Biblioteca Node.js para interagir com o sistema de autenticação da Mojang conhecido como Yggdrasil.
| [prismarine-world](https://github.com/PrismarineJS/prismarine-world) | Implementação principal dos mundos do Minecraft para o Prismarine
| [prismarine-windows](https://github.com/PrismarineJS/prismarine-windows) | Representa as interfaces do Minecraft
| [prismarine-item](https://github.com/PrismarineJS/prismarine-item) | Representa um item e suas informações associadas no Minecraft
| [prismarine-nbt](https://github.com/PrismarineJS/prismarine-nbt) | Analisador de NBT para node-minecraft-protocol
| [prismarine-recipe](https://github.com/PrismarineJS/prismarine-recipe) | Representa receitas de crafting do Minecraft
| [prismarine-biome](https://github.com/PrismarineJS/prismarine-biome) | Representa um bioma e suas informações associadas no Minecraft
| [prismarine-entity](https://github.com/PrismarineJS/prismarine-entity) | Representa uma entidade e suas informações associadas no Minecraft

### Depuração

Você pode habilitar a depuração do protocolo usando a variável de ambiente `DEBUG`:

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

No Windows:
```
set DEBUG=minecraft-protocol
node seu_arquivo.js
```

## Plugins de Terceiros

Mineflayer tem a capacidade de instalar plugins; qualquer pessoa pode criar um plugin que adiciona uma API de alto nível ao Mineflayer.

Os mais atualizados e úteis são:

* [pathfinder](https://github.com/Karang/mineflayer-pathfinder) - algoritmo de busca A* avançado com muitos recursos configuráveis
* [prismarine-viewer](https://github.com/PrismarineJS/prismarine-viewer) - visualizador de chunks na web
* [web-inventory](https://github.com/ImHarvol/mineflayer-web-inventory) - visualizador de inventário na web
* [statemachine](https://github.com/TheDudeFromCI/mineflayer-statemachine) - API para comportamentos mais complexos
* [Armor Manager](https://github.com/G07cha/MineflayerArmorManager) - gerenciamento automático de armaduras
* [Collect Block](https://github.com/TheDudeFromCI/mineflayer-collectblock) - API rápida e simples para coletar blocos.
* [Dashboard](https://github.com/wvffle/mineflayer-dashboard) - Painel de controle para um bot do Mineflayer
* [PVP](https://github.com/TheDudeFromCI/mineflayer-pvp) - API simples para PVP e PVE.
* [auto-eat](https://github.com/LINKdiscordd/mineflayer-auto-eat) - Plugin para comer automaticamente.
* [Tool](https://github.com/TheDudeFromCI/mineflayer-tool) - Plugin com uma API de alto nível para selecionar automaticamente a melhor arma/ferramenta.
* [Hawkeye](https://github.com/sefirosweb/minecraftHawkEye) - Plugin para mirar automaticamente com arcos.

Mas também dê uma olhada em:

* [radar](https://github.com/andrewrk/mineflayer-radar/) - interface de radar na web usando canvas e socket.io [Demo no Youtube](https://www.youtube.com/watch?v=FjDmAfcVulQ)
* [blockfinder](https://github.com/Darthfett/mineflayer-blockFinder) - encontra blocos no mundo tridimensional
* [scaffold](https://github.com/andrewrk/mineflayer-scaffold) - ir para um destino específico mesmo que seja necessário construir ou quebrar blocos para alcançá-lo [Demo no Youtube](http://youtu.be/jkg6psMUSE0)
* [auto-auth](https://github.com/G07cha/MineflayerAutoAuth) - autenticação automática por chat
* [Bloodhound](https://github.com/Nixes/mineflayer-bloodhound) - determina quem e/ou o que é responsável por causar dano a outra entidade
* [tps](https://github.com/SiebeDW/mineflayer-tps) - obter o tps atual (tps processado)
* [panorama](https://github.com/IceTank/mineflayer-panorama) - tirar imagens panorâmicas do seu mundo

## Projetos que Usam o Mineflayer

* [rom1504/rbot](https://github.com/rom1504/rbot)
   - [YouTube - construindo uma escada espiral](https://www.youtube.com/watch?v=UM1ZV5200S0)
   - [YouTube - replicando uma estrutura](https://www.youtube.com/watch?v=0cQxg9uDnzA)
* [Darthfett/Helperbot](https://github.com/Darthfett/Helperbot)
* [vogonistic/voxel](https://github.com/vogonistic/mineflayer-voxel) - visualiza o que o bot está fazendo usando voxel.js
* [JonnyD/Skynet](https://github.com/JonnyD/Skynet) - registra a atividade de um jogador em uma API online
* [MinecraftChat](https://github.com/rom1504/MinecraftChat) (última versão de código aberto, criada por AlexKvazos) - Interface de chat na web para o Minecraft <https://minecraftchat.net/>
* [Cheese Bot](https://github.com/Minecheesecraft/Cheese-Bot) - bot com uma interface limpa. Feito com Node-Webkit. http://bot.ezcha.net/
* [Chaoscraft](https://github.com/schematical/chaoscraft) - bot de Minecraft que usa algoritmos genéticos, veja [seus vídeos no YouTube](https://www.youtube.com/playlist?list=PLLkpLgU9B5xJ7Qy4kOyBJl5J6zsDIMceH)
* [hexatester/minetelegram](https://github.com/hexatester/minetelegram) - ponte para o Telegram, feita com Mineflayer e Telegraf.
* [e centenas mais](https://github.com/PrismarineJS/mineflayer/network/dependents) - todos os projetos que usam o Mineflayer e foram detectados pelo GitHub.

## Testes

### Executar Todos os Testes

Basta executar:

```bash
npm test
```

### Executar Testes para uma Versão Específica do Minecraft

Execute

```bash
npm test -- -g <versão>
```

onde `<versão>` é uma versão do Minecraft, como `1.12`, `1.15.2`...

### Executar um Teste Específico

Execute
```bash
npm test -- -g <nome_do_teste>
```

onde `<nome_do_teste>` é o nome do teste que você deseja executar, como `bed`, `useChests`, `rayTrace`...

## Licença

[MIT](../../LICENSE)

Esta documentação não é oficialmente mantida. Para ver as últimas atualizações, consulte a documentação original: [unstable_api](../README.md)


================================================
FILE: docs/br/api_br.md
================================================
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Tabela de conteúdos** *gerada com [DocToc](https://github.com/thlorenz/doctoc)*

- [API](#api)
  - [Enums](#enums)
    - [minecraft-data](#minecraft-data)
    - [mcdata.blocks](#mcdatablocks)
    - [mcdata.items](#mcdataitems)
    - [mcdata.materials](#mcdatamaterials)
    - [mcdata.recipes](#mcdatarecipes)
    - [mcdata.instruments](#mcdatainstruments)
    - [mcdata.biomes](#mcdatabiomes)
    - [mcdata.entities](#mcdataentities)
  - [Clases](#clases)
    - [vec3](#vec3)
    - [mineflayer.Location](#mineflayerlocation)
    - [Entity](#entity)
    - [Block](#block)
    - [Biome](#biome)
    - [Item](#item)
    - [windows.Window (base class)](#windowswindow-base-class)
      - [window.deposit(itemType, metadata, count, [callback])](#windowdeposititemtype-metadata-count-callback)
      - [window.withdraw(itemType, metadata, count, [callback])](#windowwithdrawitemtype-metadata-count-callback)
      - [window.close()](#windowclose)
    - [Recipe](#recipe)
    - [mineflayer.Container](#mineflayercontainer)
    - [mineflayer.Furnace](#mineflayerfurnace)
      - [furnace "update"](#furnace-update)
      - [furnace.takeInput([callback])](#furnacetakeinputcallback)
      - [furnace.takeFuel([callback])](#furnacetakefuelcallback)
      - [furnace.takeOutput([callback])](#furnacetakeoutputcallback)
      - [furnace.putInput(itemType, metadata, count, [cb])](#furnaceputinputitemtype-metadata-count-cb)
      - [furnace.putFuel(itemType, metadata, count, [cb])](#furnaceputfuelitemtype-metadata-count-cb)
      - [furnace.inputItem()](#furnaceinputitem)
      - [furnace.fuelItem()](#furnacefuelitem)
      - [furnace.outputItem()](#furnaceoutputitem)
      - [furnace.fuel](#furnacefuel)
      - [furnace.progress](#furnaceprogress)
    - [mineflayer.EnchantmentTable](#mineflayerenchantmenttable)
      - [enchantmentTable "ready"](#enchantmenttable-ready)
      - [enchantmentTable.targetItem()](#enchantmenttabletargetitem)
      - [enchantmentTable.xpseed](#enchantmenttablexpseed)
      - [enchantmentTable.enchantments](#enchantmenttableenchantments)
      - [enchantmentTable.enchant(choice, [callback])](#enchantmenttableenchantchoice-callback)
      - [enchantmentTable.takeTargetItem([callback])](#enchantmenttabletaketargetitemcallback)
      - [enchantmentTable.putTargetItem(item, [callback])](#enchantmenttableputtargetitemitem-callback)
      - [enchantmentTable.putLapis(item, [callback])](#enchantmenttableputlapisitem-callback)
    - [mineflayer.anvil](#mineflayeranvil)
      - [anvil.combine(itemOne, itemTwo[, name, callback])](#anvilcombineitemone-itemtwo-name-callback)
      - [anvil.combine(item[, name, callback])](#anvilcombineitem-name-callback)
      - [villager "ready"](#villager-ready)
      - [villager.trades](#villagertrades)
      - [villager.trade(tradeIndex, [times], [cb])](#villagertradetradeindex-times-cb)
    - [mineflayer.ScoreBoard](#mineflayerscoreboard)
      - [ScoreBoard.name](#scoreboardname)
      - [ScoreBoard.title](#scoreboardtitle)
      - [ScoreBoard.itemsMap](#scoreboarditemsmap)
      - [ScoreBoard.items](#scoreboarditems)
    - [mineflayer.BossBar](#mineflayerbossbar)
      - [BossBar.title](#bossbartitle)
      - [BossBar.health](#bossbarhealth)
      - [BossBar.dividers](#bossbardividers)
      - [BossBar.entityUUID](#bossbarentityuuid)
      - [BossBar.shouldDarkenSky](#bossbarshoulddarkensky)
      - [BossBar.isDragonBar](#bossbarisdragonbar)
      - [BossBar.createFog](#bossbarcreatefog)
      - [BossBar.color](#bossbarcolor)
  - [Bot](#bot)
    - [mineflayer.createBot(options)](#mineflayercreatebotoptions)
    - [Properties](#properties)
      - [bot.world](#botworld)
        - [world "blockUpdate" (oldBlock, newBlock)](#world-blockupdate-oldblock-newblock)
        - [world "blockUpdate:(x, y, z)" (oldBlock, newBlock)](#world-blockupdatex-y-z-oldblock-newblock)
      - [bot.entity](#botentity)
      - [bot.entities](#botentities)
      - [bot.username](#botusername)
      - [bot.spawnPoint](#botspawnpoint)
      - [bot.heldItem](#bothelditem)
      - [bot.game.levelType](#botgameleveltype)
      - [bot.game.dimension](#botgamedimension)
      - [bot.game.difficulty](#botgamedifficulty)
      - [bot.game.gameMode](#botgamegamemode)
      - [bot.game.hardcore](#botgamehardcore)
      - [bot.game.maxPlayers](#botgamemaxplayers)
      - [bot.game.serverBrand](#botgameserverbrand)
    - [bot.physicsEnabled](#botphysicsenabled)
    - [bot.player](#botplayer)
      - [bot.players](#botplayers)
      - [bot.isRaining](#botisraining)
      - [bot.rainState](#botrainstate)
      - [bot.thunderState](#botthunderstate)
      - [bot.chatPatterns](#botchatpatterns)
      - [bot.settings.chat](#botsettingschat)
      - [bot.settings.colorsEnabled](#botsettingscolorsenabled)
      - [bot.settings.viewDistance](#botsettingsviewdistance)
      - [bot.settings.difficulty](#botsettingsdifficulty)
      - [bot.settings.skinParts](#botsettingsskinparts)
        - [bot.settings.skinParts.showCape](#botsettingsskinpartsshowcape)
        - [bot.settings.skinParts.showJacket](#botsettingsskinpartsshowjacket)
        - [bot.settings.skinParts.showLeftSleeve](#botsettingsskinpartsshowleftsleeve)
        - [bot.settings.skinParts.showRightSleeve](#botsettingsskinpartsshowrightsleeve)
        - [bot.settings.skinParts.showLeftPants](#botsettingsskinpartsshowleftpants)
        - [bot.settings.skinParts.showRightPants](#botsettingsskinpartsshowrightpants)
        - [bot.settings.skinParts.showHat](#botsettingsskinpartsshowhat)
      - [bot.experience.level](#botexperiencelevel)
      - [bot.experience.points](#botexperiencepoints)
      - [bot.experience.progress](#botexperienceprogress)
      - [bot.health](#bothealth)
      - [bot.food](#botfood)
      - [bot.foodSaturation](#botfoodsaturation)
      - [bot.oxygenLevel](#botoxygenlevel)
      - [bot.physics](#botphysics)
      - [bot.simpleClick.leftMouse (slot)](#botsimpleclickleftmouse-slot)
      - [bot.simpleClick.rightMouse (slot)](#botsimpleclickrightmouse-slot)
      - [bot.time.doDaylightCycle](#bottimedodaylightcycle)
      - [bot.time.bigTime](#bottimebigtime)
      - [bot.time.time](#bottimetime)
      - [bot.time.timeOfDay](#bottimetimeofday)
      - [bot.time.day](#bottimeday)
      - [bot.time.isDay](#bottimeisday)
      - [bot.time.moonPhase](#bottimemoonphase)
      - [bot.time.bigAge](#bottimebigage)
      - [bot.time.age](#bottimeage)
      - [bot.quickBarSlot](#botquickbarslot)
      - [bot.inventory](#botinventory)
      - [bot.targetDigBlock](#bottargetdigblock)
      - [bot.isSleeping](#botissleeping)
      - [bot.scoreboards](#botscoreboards)
      - [bot.scoreboard](#botscoreboard)
      - [bot.controlState](#botcontrolstate)
    - [Events](#events)
      - ["chat" (username, message, translate, jsonMsg, matches)](#chat-username-message-translate-jsonmsg-matches)
      - ["whisper" (username, message, translate, jsonMsg, matches)](#whisper-username-message-translate-jsonmsg-matches)
      - ["actionBar" (jsonMsg)](#actionbar-jsonmsg)
      - ["message" (jsonMsg, position)](#message-jsonmsg-position)
      - ["messagestr" (message, messagePosition, jsonMsg)](#messagestr-message-messageposition-jsonmsg)
      - ["inject_allowed"](#inject_allowed)
      - ["login"](#login)
      - ["spawn"](#spawn)
      - ["respawn"](#respawn)
      - ["game"](#game)
      - ["resourcePack" (url, hash)](#resourcepack-url-hash)
      - ["title" (title, type)](#title-title-type)
      - ["rain"](#rain)
      - ["weatherUpdate"](#weatherupdate)
      - ["time"](#time)
      - ["kicked" (reason, loggedIn)](#kicked-reason-loggedin)
      - ["end"](#end)
      - ["error" (err)](#error-err)
      - ["spawnReset"](#spawnreset)
      - ["death"](#death)
      - ["health"](#health)
      - ["breath"](#breath)
      - ["entitySwingArm" (entity)](#entityswingarm-entity)
      - ["entityHurt" (entity)](#entityhurt-entity)
      - ["entityDead" (entity)](#entitydead-entity)
      - ["entityTaming" (entity)](#entitytaming-entity)
      - ["entityTamed" (entity)](#entitytamed-entity)
      - ["entityShakingOffWater" (entity)](#entityshakingoffwater-entity)
      - ["entityEatingGrass" (entity)](#entityeatinggrass-entity)
      - ["entityWake" (entity)](#entitywake-entity)
      - ["entityEat" (entity)](#entityeat-entity)
      - ["entityCriticalEffect" (entity)](#entitycriticaleffect-entity)
      - ["entityMagicCriticalEffect" (entity)](#entitymagiccriticaleffect-entity)
      - ["entityCrouch" (entity)](#entitycrouch-entity)
      - ["entityUncrouch" (entity)](#entityuncrouch-entity)
      - ["entityEquip" (entity)](#entityequip-entity)
      - ["entitySleep" (entity)](#entitysleep-entity)
      - ["entitySpawn" (entity)](#entityspawn-entity)
      - ["itemDrop" (entity)](#itemdrop-entity)
      - ["playerCollect" (collector, collected)](#playercollect-collector-collected)
      - ["entityGone" (entity)](#entitygone-entity)
      - ["entityMoved" (entity)](#entitymoved-entity)
      - ["entityDetach" (entity, vehicle)](#entitydetach-entity-vehicle)
      - ["entityAttach" (entity, vehicle)](#entityattach-entity-vehicle)
      - ["entityUpdate" (entity)](#entityupdate-entity)
      - ["entityEffect" (entity, effect)](#entityeffect-entity-effect)
      - ["entityEffectEnd" (entity, effect)](#entityeffectend-entity-effect)
      - ["playerJoined" (player)](#playerjoined-player)
      - ["playerUpdated" (player)](#playerupdated-player)
      - ["playerLeft" (player)](#playerleft-player)
      - ["blockUpdate" (oldBlock, newBlock)](#blockupdate-oldblock-newblock)
      - ["blockUpdate:(x, y, z)" (oldBlock, newBlock)](#blockupdatex-y-z-oldblock-newblock)
      - ["blockPlaced" (oldBlock, newBlock)](#blockplaced-oldblock-newblock)
      - ["chunkColumnLoad" (point)](#chunkcolumnload-point)
      - ["chunkColumnUnload" (point)](#chunkcolumnunload-point)
      - ["soundEffectHeard" (soundName, position, volume, pitch)](#soundeffectheard-soundname-position-volume-pitch)
      - ["hardcodedSoundEffectHeard" (soundId, soundCategory, position, volume, pitch)](#hardcodedsoundeffectheard-soundid-soundcategory-position-volume-pitch)
      - ["noteHeard" (block, instrument, pitch)](#noteheard-block-instrument-pitch)
      - ["pistonMove" (block, isPulling, direction)](#pistonmove-block-ispulling-direction)
      - ["chestLidMove" (block, isOpen, block2)](#chestlidmove-block-isopen-block2)
      - ["blockBreakProgressObserved" (block, destroyStage)](#blockbreakprogressobserved-block-destroystage)
      - ["blockBreakProgressEnd" (block)](#blockbreakprogressend-block)
      - ["diggingCompleted" (block)](#diggingcompleted-block)
      - ["diggingAborted" (block)](#diggingaborted-block)
      - ["move"](#move)
      - ["forcedMove"](#forcedmove)
      - ["mount"](#mount)
      - ["dismount" (vehicle)](#dismount-vehicle)
      - ["windowOpen" (window)](#windowopen-window)
      - ["windowClose" (window)](#windowclose-window)
      - ["sleep"](#sleep)
      - ["wake"](#wake)
      - ["experience"](#experience)
      - ["scoreboardCreated" (scoreboard)](#scoreboardcreated-scoreboard)
      - ["scoreboardDeleted" (scoreboard)](#scoreboarddeleted-scoreboard)
      - ["scoreboardTitleChanged" (scoreboard)](#scoreboardtitlechanged-scoreboard)
      - ["scoreUpdated" (scoreboard, item)](#scoreupdated-scoreboard-item)
      - ["scoreRemoved" (scoreboard, item)](#scoreremoved-scoreboard-item)
      - ["scoreboardPosition" (position, scoreboard)](#scoreboardposition-position-scoreboard)
      - ["bossBarCreated" (bossBar)](#bossbarcreated-bossbar)
      - ["bossBarDeleted" (bossBar)](#bossbardeleted-bossbar)
      - ["bossBarUpdated" (bossBar)](#bossbarupdated-bossbar)
      - ["heldItemChanged" (heldItem)](#helditemchanged-helditem)
      - ["physicsTick" ()](#physicstick-)
      - ["chat:name" (matches)](#chatname-matches)
    - [Functions](#functions)
      - [bot.blockAt(point, extraInfos=true)](#botblockatpoint-extrainfostrue)
      - [bot.waitForChunksToLoad(cb)](#botwaitforchunkstoloadcb)
      - [bot.blockInSight(maxSteps, vectorLength)](#botblockinsightmaxsteps-vectorlength)
      - [bot.blockAtCursor(maxDistance=256)](#botblockatcursormaxdistance256)
      - [bot.canSeeBlock(block)](#botcanseeblockblock)
      - [bot.findBlocks(options)](#botfindblocksoptions)
      - [bot.findBlock(options)](#botfindblockoptions)
      - [bot.canDigBlock(block)](#botcandigblockblock)
      - [bot.recipesFor(itemType, metadata, minResultCount, craftingTable)](#botrecipesforitemtype-metadata-minresultcount-craftingtable)
      - [bot.recipesAll(itemType, metadata, craftingTable)](#botrecipesallitemtype-metadata-craftingtable)
      - [bot.nearestEntity(match = (entity) => { return true })](#botnearestentitymatch--entity---return-true-)
    - [Methods](#methods)
      - [bot.end()](#botend)
      - [bot.quit(reason)](#botquitreason)
      - [bot.tabComplete(str, cb, [assumeCommand], [sendBlockInSight])](#bottabcompletestr-cb-assumecommand-sendblockinsight)
      - [bot.chat(message)](#botchatmessage)
      - [bot.whisper(username, message)](#botwhisperusername-message)
      - [bot.chatAddPattern(pattern, chatType, description)](#botchataddpatternpattern-chattype-description)
      - [bot.addChatPattern(name, pattern, chatPatternOptions)](#botaddchatpatternname-pattern-chatpatternoptions)
      - [bot.addChatPatternSet(name, patterns, chatPatternOptions)](#botaddchatpatternsetname-patterns-chatpatternoptions)
      - [bot.removeChatPattern(name)](#botremovechatpatternname)
      - [bot.awaitMessage(...args)](#botawaitmessageargs)
      - [bot.setSettings(options)](#botsetsettingsoptions)
      - [bot.loadPlugin(plugin)](#botloadpluginplugin)
      - [bot.loadPlugins(plugins)](#botloadpluginsplugins)
      - [bot.hasPlugin(plugin)](#bothaspluginplugin)
      - [bot.sleep(bedBlock, [cb])](#botsleepbedblock-cb)
      - [bot.isABed(bedBlock)](#botisabedbedblock)
      - [bot.wake([cb])](#botwakecb)
      - [bot.setControlState(control, state)](#botsetcontrolstatecontrol-state)
      - [bot.getControlState(control)](#botgetcontrolstatecontrol)
      - [bot.clearControlStates()](#botclearcontrolstates)
      - [bot.lookAt(point, [force], [callback])](#botlookatpoint-force-callback)
      - [bot.look(yaw, pitch, [force], [callback])](#botlookyaw-pitch-force-callback)
      - [bot.updateSign(block, text)](#botupdatesignblock-text)
      - [bot.equip(item, destination, [callback])](#botequipitem-destination-callback)
      - [bot.unequip(destination, [callback])](#botunequipdestination-callback)
      - [bot.tossStack(item, [callback])](#bottossstackitem-callback)
      - [bot.toss(itemType, metadata, count, [callback])](#bottossitemtype-metadata-count-callback)
      - [bot.dig(block, [forceLook = true], [digFace], [callback])](#botdigblock-forcelook--true-digface-callback)
      - [bot.stopDigging()](#botstopdigging)
      - [bot.digTime(block)](#botdigtimeblock)
      - [bot.acceptResourcePack()](#botacceptresourcepack)
      - [bot.denyResourcePack()](#botdenyresourcepack)
      - [bot.placeBlock(referenceBlock, faceVector, cb)](#botplaceblockreferenceblock-facevector-cb)
      - [bot.placeEntity(referenceBlock, faceVector)](#botplaceentityreferenceblock-facevector)
      - [bot.activateBlock(block, [callback])](#botactivateblockblock-callback)
      - [bot.activateEntity(entity, [callback])](#botactivateentityentity-callback)
      - [bot.activateEntityAt(entity, position, [callback])](#botactivateentityatentity-position-callback)
      - [bot.consume(callback)](#botconsumecallback)
      - [bot.fish(callback)](#botfishcallback)
      - [bot.activateItem(offHand=false)](#botactivateitemoffhandfalse)
      - [bot.deactivateItem()](#botdeactivateitem)
      - [bot.useOn(targetEntity)](#botuseontargetentity)
      - [bot.attack(entity)](#botattackentity)
      - [bot.swingArm([hand], showHand)](#botswingarmhand-showhand)
      - [bot.mount(entity)](#botmountentity)
      - [bot.dismount()](#botdismount)
      - [bot.moveVehicle(left,forward)](#botmovevehicleleftforward)
      - [bot.setQuickBarSlot(slot)](#botsetquickbarslotslot)
      - [bot.craft(recipe, count, craftingTable, [callback])](#botcraftrecipe-count-craftingtable-callback)
      - [bot.writeBook(slot, pages, [callback])](#botwritebookslot-pages-callback)
      - [bot.openContainer(containerBlock or containerEntity)](#botopencontainercontainerblock-or-containerentity)
      - [bot.openChest(chestBlock or minecartchestEntity)](#botopenchestchestblock-or-minecartchestentity)
      - [bot.openFurnace(furnaceBlock)](#botopenfurnacefurnaceblock)
      - [bot.openDispenser(dispenserBlock)](#botopendispenserdispenserblock)
      - [bot.openEnchantmentTable(enchantmentTableBlock)](#botopenenchantmenttableenchantmenttableblock)
      - [bot.openAnvil(anvilBlock)](#botopenanvilanvilblock)
      - [bot.openVillager(villagerEntity)](#botopenvillagervillagerentity)
      - [bot.trade(villagerInstance, tradeIndex, [times], [cb])](#bottradevillagerinstance-tradeindex-times-cb)
      - [bot.setCommandBlock(pos, command, [options])](#botsetcommandblockpos-command-options)
      - [bot.supportFeature(name)](#botsupportfeaturename)
      - [bot.waitForTicks(ticks)](#botwaitforticksticks)
    - [Lower level inventory methods](#lower-level-inventory-methods)
      - [bot.clickWindow(slot, mouseButton, mode, cb)](#botclickwindowslot-mousebutton-mode-cb)
      - [bot.putSelectedItemRange(start, end, window, slot)](#botputselecteditemrangestart-end-window-slot)
      - [bot.putAway(slot)](#botputawayslot)
      - [bot.closeWindow(window)](#botclosewindowwindow)
      - [bot.transfer(options, cb)](#bottransferoptions-cb)
      - [bot.openBlock(block)](#botopenblockblock)
      - [bot.openEntity(entity)](#botopenentityentity)
      - [bot.moveSlotItem(sourceSlot, destSlot, cb)](#botmoveslotitemsourceslot-destslot-cb)
      - [bot.updateHeldItem()](#botupdatehelditem)
      - [bot.getEquipmentDestSlot(destination)](#botgetequipmentdestslotdestination)
    - [bot.creative](#botcreative)
      - [bot.creative.setInventorySlot(slot, item, [callback])](#botcreativesetinventoryslotslot-item-callback)
      - [bot.creative.flyTo(destination, [cb])](#botcreativeflytodestination-cb)
      - [bot.creative.startFlying()](#botcreativestartflying)
      - [bot.creative.stopFlying()](#botcreativestopflying)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

# API

## Enums

Esses enums estão armazenados em um projeto independente da linguagem [minecraft-data](https://github.com/PrismarineJS/minecraft-data) e acessados pelo [node-minecraft-data](https://github.com/PrismarineJS/node-minecraft-data).

### minecraft-data
Os dados estão disponíveis no módulo [node-minecraft-data](https://github.com/PrismarineJS/node-minecraft-data)

`require('minecraft-data')(bot.version)` te dá acesso a eles.

### mcdata.blocks
Blocos ordenados por ID.

### mcdata.items
Itens ordenados por ID.

### mcdata.materials
A chave é o material. O valor é um objeto com a chave sendo o ID da ferramenta e o valor é o multiplicador de eficiência.

### mcdata.recipes
Receitas ordenadas por ID.

### mcdata.instruments
Ferramentas ordenadas por ID.

### mcdata.biomes
Biomas ordenados por ID.

### mcdata.entities
Entidades ordenadas por ID.

## Clases

### vec3

Veja [andrewrk/node-vec3](https://github.com/andrewrk/node-vec3)

Todos os pontos no mineflayer são instâncias dessa classe.

- x - sul
- y - para cima
- z - oeste

Funções e métodos que requerem um ponto aceitam instâncias `Vec3`, uma matriz com 3 valores e um objeto com as propriedades `x`, `y` e `z`.

### mineflayer.Location

### Entity

Entidades representam jogadores, mobs e objetos. Elas são emitidas em muitos eventos, mas você pode acessar sua própria entidade com `bot.entity`.
Veja [prismarine-entity](https://github.com/PrismarineJS/prismarine-entity)

### Block

Veja [prismarine-block](https://github.com/PrismarineJS/prismarine-block)

Além disso, `block.blockEntity` é um campo adicional com os dados da entidade do bloco em formato de `Object`.
```js
// sign.blockEntity
{
  x: -53,
  y: 88,
  z: 66,
  id: 'minecraft:sign', // 'Sign' in 1.10
  Text1: { toString: Function }, // ChatMessage object
  Text2: { toString: Function }, // ChatMessage object
  Text3: { toString: Function }, // ChatMessage object
  Text4: { toString: Function } // ChatMessage object
}
```

### Biome

Veja [prismarine-biome](https://github.com/PrismarineJS/prismarine-biome)

### Item

Veja [prismarine-item](https://github.com/PrismarineJS/prismarine-item)

### windows.Window (base class)

Veja [prismarine-windows](https://github.com/PrismarineJS/prismarine-windows)

#### window.deposit(itemType, metadata, count, [callback])

Esta função também retorna uma `Promise`, com `void` como argumento ao ser concluída.

- `itemType` - ID numérico do item.
- `metadata` - valor numérico. `null` significa que qualquer valor coincide.
- `count` - quantos itens devem ser depositados. `null` é um alias para 1.
- `callback(err)` - (opcional) - executado ao ser concluída.

#### window.withdraw(itemType, metadata, count, [callback])

Esta função também retorna uma `Promise`, com `void` como argumento ao ser concluída.

 * `itemType` - ID numérico do item
 * `metadata` - valor numérico. `null` significa que qualquer valor é correspondente.
 * `count` - quantos itens devem ser retirados. `null` é um alias para 1.
 * `callback(err)` - (opcional) - executado ao finalizar

#### window.close()

Fecha a interface/janela.

### Recipe

Veja [prismarine-recipe](https://github.com/PrismarineJS/prismarine-recipe).

### mineflayer.Container

Estende windows.Window para baús, dispensadores, etc...
Veja `bot.openContainer(blocoDoBaú ou entidadeDeCarrinhoDeMinério)`.

### mineflayer.Furnace

Estende windows.Window para fornalhas, fundidores, etc...
Veja `bot.openFurnace(blocoDaFornalha)`.

#### Furnace "update"

É emitido quando `fornalha.combustível` e/ou `fornalha.progresso` são atualizados.

#### furnace.takeInput([callback])

Esta função também retorna uma `Promise`, com `void` como argumento quando concluída.

 * `callback(err, item)`

#### furnace.takeFuel([callback])

Esta função também retorna uma `Promise`, com `void` como argumento quando concluída.

 * `callback(err, item)`

#### furnace.takeOutput([callback])

Esta função também retorna uma `Promise`, com `void` como argumento quando concluída.

 * `callback(err, item)`

#### furnace.putInput(itemType, metadata, count, [cb])

Esta função também retorna uma `Promise`, com `void` como argumento quando concluída.

#### furnace.putFuel(itemType, metadata, count, [cb])

Esta função também retorna uma `Promise`, com `void` como argumento quando concluída.

#### furnace.inputItem()

Retorna uma instância `Item` que é o item de entrada.

#### furnace.fuelItem()

Retorna uma instância `Item` que é o combustível.

#### furnace.outputItem()

Retorna uma instância `Item` que é o item de saída.

#### furnace.fuel

Quanto combustível resta, variando de 0 a 1.

#### furnace.progress

Quanto o item está avançado no processo, variando de 0 a 1.

### mineflayer.EnchantmentTable

Estende windows.Window para mesas de encantamento.
Veja `bot.openEnchantmentTable(blocoDaMesaDeEncantamento)`.

#### enchantmentTable "ready"

É emitido quando `mesaDeEncantamento.encantamentos` está completo e você pode escolher um encantamento executando `mesaDeEncantamento.encantar(escolha)`.

#### enchantmentTable.targetItem()

Retorna os itens de entrada e saída.

#### enchantmentTable.xpseed

A semente de XP de 16 bits enviada pelo servidor.

#### enchantmentTable.enchantments

Array de comprimento 3 com três encantamentos que você pode escolher.
`level` pode ser -1 se o servidor ainda não enviou os dados.

Parece com:

```js
[
  {
    level: 3
  },
  {
    level: 4
  },
  {
    level: 9
  }
]
```

#### enchantmentTable.enchant(choice, [callback])

Esta função também retorna uma `Promise`, com o `item` como argumento quando concluída.

* `escolha` - [0-2], o índice do encantamento que você deseja escolher.
* `callback(err, item)` - (opcional) executado ao finalizar.

#### enchantmentTable.takeTargetItem([callback])

Esta função também retorna uma `Promise`, com o `item` como argumento quando concluída.

* `callback(err, item)`

#### enchantmentTable.putTargetItem(item, [callback])

Esta função também retorna uma `Promise`, com `void` como argumento quando concluída.

* `callback(err)`

#### enchantmentTable.putLapis(item, [callback])

Esta função também retorna uma `Promise`, com `void` como argumento quando concluída.

* `callback(err)`

### mineflayer.anvil

Estende a janela de janelas para bigornas.
Veja `bot.openAnvil(anvilBlock)`.

#### anvil.combine(itemUm, itemDois[, nome, callback])

Esta função também retorna uma `Promise`, com `void` como argumento quando concluída.

* `callback(err)` - para usar o retorno de chamada, o nome deve estar vazio ('').

#### anvil.combine(item[, nome, callback])

Esta função também retorna uma `Promise`, com `void` como argumento quando concluída.

* `callback(err)`

#### villager "ready"

É emitido quando `vilarejo.trocas` foram carregadas.

#### villager.trades

Array de negociações

Semelhante a:

```js
[
  {
    firstInput: Item,
    output: Item,
    hasSecondItem: false,
    secondaryInput: null,
    disabled: false,
    tooluses: 0,
    maxTradeuses: 7
  },
  {
    firstInput: Item,
    output: Item,
    hasSecondItem: false,
    secondaryInput: null,
    disabled: false,
    tooluses: 0,
    maxTradeuses: 7
  },
  {
    firstInput: Item,
    output: Item,
    hasSecondItem: true,
    secondaryInput: Item,
    disabled: false,
    tooluses: 0,
    maxTradeuses: 7
  }
]
```

#### villager.trade(tradeIndex, [times], [cb])
É o mesmo que [bot.trade(villagerInstance, tradeIndex, [times], [cb])](#bottradevillagerinstance-tradeindex-times-cb)

### mineflayer.ScoreBoard

#### ScoreBoard.name

Nome do placar.

#### ScoreBoard.title

O título do placar (nem sempre é o mesmo que o nome).

#### ScoreBoard.itemsMap

Um objeto com todos os itens do placar nele.
```js
{
  wvffle: { name: 'wvffle', value: 3 },
  dzikoysk: { name: 'dzikoysk', value: 6 }
}
```

#### ScoreBoard.items

Uma matriz com todos os itens no placar.
```js
[
  { name: 'dzikoysk', value: 6 },
  { name: 'wvffle', value: 3 }
]
```

### mineflayer.BossBar

#### BossBar.title

Título da barra de vida do chefe, instância de ChatMessage

#### BossBar.health

Porcentagem da vida do chefe, de `0` a `1`

#### BossBar.dividers

Número de divisores na barra, pode ser `0`, `6`, `10`, `12` ou `20`

#### BossBar.entityUUID

UUID da entidade do chefe

#### BossBar.shouldDarkenSky

Determina se o céu deve escurecer ou não

#### BossBar.isDragonBar

Determina se a barra é a barra de vida do dragão

#### BossBar.createFog

Determina se a barra cria neblina ou não

#### BossBar.color

Determina el color de la barra entre `pink`, `blue`, `red`, `green`, `yellow`, `purple` y `white` (`rosa`, `azul`, `rojo`, `verde`, `amarillo`, `morado` y `blanco`)

## Bot

### mineflayer.createBot(options)

Crie e retorne uma instância da classe Bot.

`options` é um objeto que contém propriedades opcionais:
 * username : (usuário) o valor padrão é 'Player'
 * port : (porta) o valor padrão é 25565
 * password : (senha) pode ser omitida (se os tokens também forem omitidos, tentará conectar no modo offline)
 * host : (ip) o valor padrão é localhost
 * version : se omitido, tentará determinar automaticamente a versão. Por exemplo: "1.12.2"
 * auth : (autenticação) o valor padrão é 'mojang', também pode ser 'microsoft'
 * clientToken : gerado se uma senha for fornecida
 * accessToken : gerado se uma senha for fornecida
 * logErrors : o valor padrão é true, retém erros e os imprime
 * hideErrors : o valor padrão é true, para ocultar erros (mesmo se logErrors for true)
 * keepAlive : envia pacotes keepAlive: o valor padrão é true
 * checkTimeoutInterval : o valor padrão é `30*1000` (30s), verifica se o pacote keepAlive foi recebido neste período, desconecta o bot se não for recebido.
 * loadInternalPlugins : o valor padrão é true
 * storageBuilder : uma função opcional, que recebe a versão e o nome do mundo (worldName) como argumentos e retorna uma instância de algo com a mesma API que prismarine-provider-anvil. Será usado para salvar o mundo.
 * client : uma instância de node-minecraft-protocol, se não for especificado, o mineflayer criará seu próprio cliente. Isso é útil para usar o mineflayer por meio de um proxy de vários clientes ou para um cliente vanilla e um cliente mineflayer.
 * plugins : objeto: o valor padrão é {}
   - pluginName : false : não carrega o plugin interno com esse nome, por exemplo, `pluginName`
   - pluginName : true : carrega o plugin interno com esse nome, por exemplo, `pluginName`, mesmo se loadInternalPlugins estiver definido como false
   - pluginName : função para introduzir : carrega um plugin de terceiros (externo), anulando o plugin interno com o mesmo nome, por exemplo, `pluginName`
 * physicsEnabled : o valor padrão é true, se o bot deve ser afetado pela física, pode ser modificado através de bot.physicsEnabled
 * [chat](#bot.settings.chat)
 * [colorsEnabled](#bot.settings.colorsEnabled)
 * [viewDistance](#bot.settings.viewDistance)
 * [difficulty](#bot.settings.difficulty)
 * [skinParts](#bot.settings.skinParts)
 * chatLengthLimit : o valor máximo de caracteres que podem ser enviados com uma única mensagem. Se não for especificado, será 100 em versões anteriores à 1.11 e 256 na 1.11 e posteriores.

### Properties

#### bot.world

Uma representação sincronizada do mundo. Confira a documentação em http://github.com/PrismarineJS/prismarine-world

#### world "blockUpdate" (oldBlock, newBlock)

É emitido quando um bloco é atualizado. Retorna o bloco antigo `oldBlock` e o novo bloco `newBlock`.

Observação: `oldBlock` pode ser `null`.

#### world "blockUpdate:(x, y, z)" (oldBlock, newBlock)

É emitido quando um bloco em uma coordenada é atualizado. Retorna o bloco antigo `oldBlock` e o novo bloco `newBlock`.

Observação: `oldBlock` pode ser `null`.


#### bot.entity

Sua própria entidade. Consulte `Entity`.

#### bot.entities

Todas as entidades próximas. Este objeto é um mapa de entityId (id da entidade) para entity (entidade).

#### bot.username

Use isso para descobrir seu próprio nome.

#### bot.spawnPoint

Coordenadas do ponto de spawn, para onde todas as bússolas apontam.

#### bot.heldItem

O item na mão do bot, apresentado como uma instância [prismarine-item](https://github.com/PrismarineJS/prismarine-item) especificado com seus metadados, dados NBT, etc.

#### bot.game.levelType

Tipo do nível do jogo.

#### bot.game.dimension

Tipo da dimensão.

#### bot.game.difficulty

Tipo de dificuldade do jogo.

#### bot.game.gameMode

Modo de jogo do bot.

#### bot.game.hardcore

Se o jogo está no modo hardcore ou não.

#### bot.game.maxPlayers

O número máximo de jogadores no jogo.

#### bot.game.serverBrand

A marca do servidor.

#### bot.physicsEnabled

Se a física deve ser habilitada, o valor padrão é true.

#### bot.player

Objeto do jogador do bot
```js
{
  username: 'player',
  displayName: { toString: Function }, // Objeto ChatMessage.
  gamemode: 0,
  ping: 28,
  entity: entity // nulo se você estiver muito longe (fora da zona renderizada)
}
```

#### bot.players

Mapa dos nomes dos jogadores no jogo.

#### bot.isRaining

Determina se está chovendo.

#### bot.rainState

Um número indicando o nível de chuva atual. Se não estiver chovendo, este valor será 0. Quando começa a chover, o valor aumenta gradualmente para 1. E quando para de chover, diminui gradualmente para 0.

Cada vez que `bot.rainState` muda, o evento "weatherUpdate" é emitido.

#### bot.thunderState

Um número indicando o nível de tempestade de raios atual. Se não houver tempestade, este valor será 0. Quando começa uma tempestade, o valor aumenta gradualmente para 1. E quando a tempestade para, diminui gradualmente para 0.

Cada vez que `bot.thunderState` muda, o evento "weatherUpdate" é emitido.

Isso é semelhante ao `bot.rainState`, mas para tempestades de raios. Para tempestades de raios, `bot.rainState` e `bot.thunderState` mudarão.

#### bot.chatPatterns

Isso é uma matriz de objetos de padrões, no seguinte formato:
{ /regex/, "chattype", "descrição")
 * /regex/ - um padrão regex, deve ter pelo menos dois grupos de captura.
 * 'chattype' - o tipo de chat que deve corresponder, pode ser "chat" (conversa) ou "whisper" (sussurro), ou qualquer outro.
 * 'descrição' - descrição do padrão, opcional.

#### bot.settings.chat

Opções:

 * `enabled` (ativado) (padrão)
 * `commandsOnly` (apenasComandos)
 * `disabled` (desativado)

#### bot.settings.colorsEnabled

Seu valor padrão é verdadeiro, se deve receber códigos de cor do servidor.

#### bot.settings.viewDistance

Opções:
 * `far` (distante) (padrão)
 * `normal`
 * `short` (curto)
 * `tiny` (minúsculo)

#### bot.settings.difficulty

O mesmo que em server.properties.

#### bot.settings.skinParts

Esses booleanos controlam se as partes externas da skin do jogador devem ser visíveis.

##### bot.settings.skinParts.showCape

Se você tem uma capa, pode desativá-la alterando isso para falso.

##### bot.settings.skinParts.showJacket

Se a parte externa do peito deve ser mostrada.

##### bot.settings.skinParts.showLeftSleeve

Se a parte externa do braço esquerdo deve ser mostrada.

##### bot.settings.skinParts.showRightSleeve

Se a parte externa do braço direito deve ser mostrada.

##### bot.settings.skinParts.showLeftPants

Se a parte externa da perna esquerda deve ser mostrada.

##### bot.settings.skinParts.showRightPants

Se a parte externa da perna direita deve ser mostrada.

##### bot.settings.skinParts.showHat

Se a parte externa da cabeça deve ser mostrada.

#### bot.experience.level

O nível de experiência do bot.

#### bot.experience.points

Total de pontos de experiência do bot.

#### bot.experience.progress

Entre 0 e 1 - a quantidade que falta para atingir o próximo nível.

#### bot.health

Números entre 0 e 20 representando o número de metades de coração.

#### bot.food

Números de 0 a 20 representando o número de metades de coxas de frango.

#### bot.foodSaturation

A saturação atua como um "suprimento" de comida. Se a saturação for maior que 0, o nível de comida não diminuirá. Os jogadores que entram no jogo têm automaticamente uma saturação de 5,0. Comer aumenta a saturação e o nível de comida.

#### bot.oxygenLevel

Número de 0 a 20 representando o número de metades de bolhas do nível de oxigênio.

#### bot.physics

Modifique esses números para alterar a gravidade, velocidade de salto, velocidade terminal, etc. Faça isso por sua própria conta e risco.

#### bot.simpleClick.leftMouse (slot)

Abstração de `bot.clickWindow(slot, 0, 0)`

#### bot.simpleClick.rightMouse (slot)

Abstração de `bot.clickWindow(slot, 1, 0)`

#### bot.time.doDaylightCycle

Se o gamerule doDaylightCycle está ativado ou desativado.

#### bot.time.bigTime

O número total de ticks desde o dia 0.

Este valor é do tipo BigInt e é muito preciso, mesmo com valores muito grandes (mais de 2^51 - 1 ticks).

#### bot.time.time

O número total de ticks desde o dia 0.

Como o limite de números em JavaScript é 2^51 - 1, bot.time.time é menos preciso em valores mais altos que esse limite. Portanto, é recomendado o uso de bot.time.bigTime. Sendo realista, provavelmente você nunca terá que usar bot.time.bigTime, já que ele naturalmente alcançará 2^51 - 1 ticks após cerca de 14.280.821 anos reais.

#### bot.time.timeOfDay

Hora do dia, em ticks.

A hora é baseada em ticks, onde 20 ticks ocorrem a cada segundo. Há 24.000 ticks em um dia, o que torna os dias em Minecraft exatamente 20 minutos. A hora do dia é baseada no módulo 24.000 do timestamp. 0 é o amanhecer, 6.000 é o meio-dia, 12.000 é o anoitecer e 18.000 é a meia-noite.

#### bot.time.day

Dia do mundo.

#### bot.time.isDay

Se é dia ou não.

Baseado no horário atual estar entre 0 e 13000 ticks (dia + pôr do sol).

#### bot.time.moonPhase

Fase da lua.

De 0 a 7, onde 0 é lua cheia.

#### bot.time.bigAge

Idade do mundo, em ticks.

Este valor é do tipo BigInt e é preciso mesmo em valores muito altos (mais de 2^51 - 1 ticks).

#### bot.time.age

Idade do mundo, em ticks.

Como o limite de números em JavaScript é 2^51 - 1, bot.time.age é menos preciso em valores mais altos que esse limite. Portanto, é recomendado o uso de bot.time.bigAge. Sendo realista, provavelmente você nunca terá que usar bot.time.bigAge, já que ele naturalmente alcançará 2^51 - 1 ticks após cerca de 14.280.821 anos reais.

#### bot.quickBarSlot

Qual slot está selecionado na barra de acesso rápido (0 - 8).

#### bot.inventory

Uma instância de janela (interface) representando seu inventário.

#### bot.targetDigBlock

O bloco que você está quebrando no momento, ou `null`.

#### bot.isSleeping

Booleano representando se você está dormindo ou não.

#### bot.scoreboards

Todos os placares que o bot conhece em um objeto com o formato nome do placar -> placar.

#### bot.scoreboard

Todos os placares que o bot conhece em um objeto com o formato exibição de placar -> placar.
- `belowName` - placar exibido abaixo do nome
- `sidebar` - placar exibido na barra lateral
- `list` - placar exibido na lista
- `0-18` - entradas definidas no protocolo

#### bot.controlState

Um objeto que contém os estados de controle principais: ['frente', 'trás', 'esquerda', 'direita', 'pular', 'correr', 'agachar'].

Esses valores podem ser usados em bot.setControlState.

### Events

#### "chat" (username, message, translate, jsonMsg, matches)

Somente é emitido quando um jogador conversa publicamente.
- `username` - o jogador que enviou a mensagem (compare com `bot.username` para ignorar suas próprias mensagens).
- `message` - mensagem sem códigos de cores.
- `translate` - tipo de mensagem no chat. Nulo para a maioria das mensagens do Bukkit.
- `jsonMsg` - mensagem JSON não modificada do servidor.
- `matches` - matriz de correspondências retornadas pelas expressões regulares. Pode ser nulo.

#### "whisper" (username, message, translate, jsonMsg, matches)

Somente é emitido quando um jogador conversa com você em particular (sussurro).
- `username` - o jogador que enviou a mensagem.
- `message` - mensagem sem códigos de cores.
- `translate` - tipo de mensagem no chat. Nulo para a maioria das mensagens do Bukkit.
- `jsonMsg` - mensagem JSON não modificada do servidor.
- `matches` - matriz de correspondências retornadas pelas expressões regulares. Pode ser nulo.

#### "actionBar" (jsonMsg)

Este evento é emitido para cada mensagem do servidor que aparece na barra de ação.

 * `jsonMsg` - mensagem JSON não modificada do servidor

#### "message" (jsonMsg, position)

Este evento é emitido para cada mensagem do servidor, incluindo chats.

 * `jsonMsg` - mensagem JSON não modificada do servidor

 * `position` - (>= 1.8.1): a posição da mensagem de chat pode ser
   * chat
   * sistema
   * informações_do_jogo

#### "messagestr" (message, messagePosition, jsonMsg)

Similar a "message", mas converte a mensagem JSON em uma string antes de ser emitida.

#### "inject_allowed"

Este evento é emitido quando o arquivo index é carregado. Você pode carregar mcData ou os plugins aqui, mas é melhor esperar pelo evento "spawn".

#### "login"

É emitido após se registrar no servidor. No entanto, provavelmente você desejará aguardar o evento "spawn" antes de fazer qualquer coisa.

#### "spawn"

É emitido quando você se registra e aparece no mundo ou quando ressurge após a morte. Normalmente, este é o evento que você deseja receber antes de fazer qualquer coisa no servidor.

#### "respawn"

É emitido ao mudar de dimensões ou imediatamente antes de aparecer. Normalmente, você vai querer ignorar esse evento e esperar até que o evento "spawn" seja emitido.

#### "game"

É emitido quando o servidor altera algumas de suas propriedades.

#### "resourcePack" (url, hash)

É emitido quando o servidor envia um pacote de recursos.

#### "title" (title, type)

É emitido quando o servidor exibe um título.

 * `title` - texto do título
 * `type` - tipo do título "subtitle" ou "title"

#### "rain"

É emitido quando começa a chover ou quando para de chover. Se estiver chovendo quando você entrar no servidor, este evento será emitido.

#### "weatherUpdate"

É emitido quando o estado de chuva (`bot.thunderState` ou `bot.rainState`) muda. Se estiver chovendo quando você entrar no servidor, este evento será emitido.

#### "time"

É emitido quando o servidor altera ou atualiza a hora. Veja `bot.time`.

#### "kicked" (reason, loggedIn)

É emitido quando o bot é expulso do servidor. `motivo` é uma mensagem de chat com o motivo da expulsão. `loggedIn` será `true` se o cliente já estava conectado quando foi expulso e `false` se o cliente foi expulso durante o processo de registro.

#### "end"

É emitido quando você não está mais conectado ao servidor.

#### "error" (err)

É emitido quando ocorre um erro.

#### "spawnReset"

É emitido quando você não pode mais ressurgir em sua cama e seu ponto de ressurgimento é redefinido.

#### "death"

É emitido ao morrer.

#### "health"

É emitido quando sua vida ou nível de comida mudam.

#### "breath"

É emitido quando seu nível de oxigênio muda.

#### "entitySwingArm" (entity)

É emitido quando uma entidade move o braço.

#### "entityHurt" (entity)

É emitido quando uma entidade se machuca.

#### "entityDead" (entity)

É emitido quando uma entidade morre.

#### "entityTaming" (entity)

É emitido quando uma entidade está sendo domesticada.

#### "entityTamed" (entity)

É emitido quando uma entidade é domesticada.

#### "entityShakingOffWater" (entity)

É emitido quando uma entidade se sacode para se secar (por exemplo, lobos).

#### "entityEatingGrass" (entity)

É emitido quando uma entidade come grama.

#### "entityWake" (entity)

É emitido quando uma entidade acorda.

#### "entityEat" (entity)

É emitido quando uma entidade come.

#### "entityCriticalEffect" (entity)

É emitido quando uma entidade recebe um ataque crítico.

#### "entityMagicCriticalEffect" (entity)

É emitido quando uma entidade recebe um ataque crítico com poções.

#### "entityCrouch" (entity)

É emitido quando uma entidade se agacha.

#### "entityUncrouch" (entity)

É emitido quando uma entidade para de se agachar.

#### "entityEquip" (entity)

É emitido quando uma entidade equipa algo.

#### "entitySleep" (entity)

É emitido quando uma entidade dorme.

#### "entitySpawn" (entity)

É emitido quando uma entidade aparece.

#### "itemDrop" (entity)

É emitido quando uma entidade solta itens (os itens também são entidades).

#### "playerCollect" (collector, collected)

É emitido quando uma entidade coleta um item.

 * `coletor` - a entidade que coletou o item.
 * `coletado` - a entidade que foi coletada (o item).

#### "entityGone" (entity)

É emitido quando uma entidade desaparece (morre, despawna).

#### "entityMoved" (entity)

É emitido quando uma entidade se move.

#### "entityDetach" (entity, vehicle)

É emitido quando uma entidade sai de um veículo.

#### "entityAttach" (entity, vehicle)

É emitido quando uma entidade entra em um veículo.

 * `entidade` - a entidade que entrou
 * `veículo` - a entidade do veículo (carrinho, cavalo)

#### "entityUpdate" (entity)

É emitido quando uma entidade atualiza uma de suas propriedades.

#### "entityEffect" (entity, effect)

É emitido quando uma entidade recebe um efeito.

#### "entityEffectEnd" (entity, effect)

É emitido quando um efeito em uma entidade termina.

#### "playerJoined" (player)

É emitido quando um jogador entra no servidor.

#### "playerUpdated" (player)

É emitido quando um jogador atualiza uma de suas propriedades.

#### "playerLeft" (player)

É emitido quando um jogador se desconecta do servidor.

#### "blockUpdate" (oldBlock, newBlock)

(É melhor usar este evento a partir de bot.world em vez de bot diretamente) É emitido quando um bloco é atualizado. Retorna `blocoAntigo` e `blocoNovo`.

Observação: `blocoAntigo` pode ser `null`.

#### "blockUpdate:(x, y, z)" (oldBlock, newBlock)

(É melhor usar este evento a partir de bot.world em vez de bot diretamente) É emitido quando um bloco em uma coordenada específica é atualizado. Retorna `blocoAntigo` e `blocoNovo`.

Observação: `blocoAntigo` pode ser `null`.

#### "blockPlaced" (oldBlock, newBlock)

É emitido quando o bot coloca um bloco. Retorna `blocoAntigo` e `blocoNovo`.

Observação: `blocoAntigo` pode ser `null`.

#### "chunkColumnLoad" (point)

É emitido quando um chunk é carregado.

#### "chunkColumnUnload" (point)

É emitido quando um chunk é descarregado. `ponto` é a coordenada do canto do chunk com os valores x, y e z mais baixos.

#### "soundEffectHeard" (soundName, position, volume, pitch)

Isso ocorre quando o cliente ouve um efeito sonoro com um nome específico.

 * `nomeSom`: nome do efeito sonoro
 * `posição`: uma instância Vec3 indicando o ponto de onde o som originou
 * `volume`: volume em ponto flutuante, 1.0 é 100%
 * `altura`: pitch em números inteiros, 63 é 100%

#### "hardcodedSoundEffectHeard" (soundId, soundCategory, position, volume, pitch)

Isso ocorre quando o cliente ouve um efeito sonoro codificado.

   * `idSom`: ID do efeito sonoro
   * `categoriaSom`: categoria do efeito sonoro
   * `posição`: uma instância Vec3 indicando o ponto de onde o som originou
   * `volume`: volume em ponto flutuante, 1.0 é 100%
   * `altura`: pitch em números inteiros, 63 é 100%

#### "noteHeard" (block, instrument, pitch)

Isso ocorre quando um bloco de notas é disparado em algum lugar.

 * `bloco`: uma instância de Bloco, o bloco que emitiu o som
 * `instrumento`:
   - `id`: identificação numérica
   - `nome`: um dos seguintes [`harpa`, `contrabaixo`, `caixa de bateria`, `baquetas`, `bateria grave`]
 * `tom`: O tom da nota (entre 0 e 24, inclusivos, onde 0 é o mais baixo e 24 é o mais alto). Você pode ler mais (sobre como os valores de tom correspondem às notas na vida real) aqui: [Página oficial da Minecraft Wiki](http://minecraft.wiki/w/Note_Block).

#### "pistonMove" (block, isPulling, direction)

Isso ocorre quando um pistão se move.

#### "chestLidMove" (block, isOpen, block2)

Isso ocorre quando a tampa de um baú se move.

* `bloco`: uma instância de Bloco, o bloco da tampa que se moveu. O bloco à direita se for um baú duplo.
* `estáAberto`: número de jogadores que têm o baú aberto.
* `bloco2`: uma instância de Bloco, a outra metade do bloco onde a tampa se moveu. Nulo se não for um baú duplo.

#### "blockBreakProgressObserved" (block, destroyStage)

Isso ocorre quando o cliente observa um bloco enquanto ele está sendo quebrado.

 * `bloco`: uma instância de Bloco, o que está sendo quebrado.
 * `estágioDestruicao`: número inteiro correspondente ao progresso (0-9).

#### "blockBreakProgressEnd" (block)

Isso ocorre quando o cliente observa um bloco que termina de ser quebrado.
Isso ocorre quando o processo foi concluído ou cancelado.

 * `bloco`: uma instância de Bloco, o bloco que não está mais sendo quebrado.

#### "diggingCompleted" (block)

Isso ocorre quando a quebra de um bloco foi concluída.
 * `bloco` - o bloco que já não existe.

#### "diggingAborted" (block)

Isso ocorre quando o processo de quebra de um bloco foi abortado.
 * `bloco` - o bloco que ainda existe.

#### "move"

Se emite cuando o bot se move. Se deseja a posição atual, você pode usar `bot.entity.position` e se quiser descobrir a posição anterior, use `bot.entity.positon.minus(bot.entity.velocity)`.

#### "forcedMove"

Se emite q
Download .txt
gitextract_2smm4x0u/

├── .github/
│   ├── FUNDING.yml
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   ├── config.yml
│   │   └── feature_request.md
│   ├── dependabot.yml
│   ├── helper/
│   │   ├── package.json
│   │   └── updator.js
│   └── workflows/
│       ├── ci.yml
│       ├── commands.yml
│       ├── handle-update.yml
│       └── npm-publish.yml
├── .gitignore
├── .gitpod.yml
├── .npmignore
├── .npmrc
├── LICENSE
├── docs/
│   ├── .nojekyll
│   ├── CONTRIBUTING.md
│   ├── FAQ.md
│   ├── README.md
│   ├── _sidebar.md
│   ├── api.md
│   ├── br/
│   │   ├── CONTRIBUTING_BR.md
│   │   ├── FAQ_BR.md
│   │   ├── README_BR.md
│   │   ├── api_br.md
│   │   └── unstable_api_br.md
│   ├── demos.md
│   ├── es/
│   │   ├── CONTRIBUTING_ES.md
│   │   ├── FAQ_ES.md
│   │   ├── README_ES.md
│   │   ├── api_es.md
│   │   └── unstable_api_es.md
│   ├── fr/
│   │   ├── FAQ_FR.md
│   │   └── README_FR.md
│   ├── history.md
│   ├── index.html
│   ├── llm_contribute.md
│   ├── mineflayer.ipynb
│   ├── ru/
│   │   ├── CONTRIBUTING_RU.md
│   │   ├── FAQ_RU.md
│   │   ├── README_RU.md
│   │   ├── _sidebar.md
│   │   ├── api_ru.md
│   │   ├── demos_ru.md
│   │   ├── index.html
│   │   ├── tutorial_ru.md
│   │   └── unstable_api_ru.md
│   ├── tr/
│   │   └── README_TR.md
│   ├── tutorial.md
│   ├── unstable_api.md
│   ├── update_to_1_21_5.md
│   └── zh/
│       ├── CONTRIBUTING.md
│       ├── FAQ.md
│       ├── README_ZH_CN.md
│       ├── _sidebar.md
│       ├── api.md
│       ├── demos.md
│       ├── history.md
│       ├── index.html
│       └── tutorial.md
├── examples/
│   ├── advanced/
│   │   ├── README.md
│   │   └── chest_confirm.md
│   ├── ansi.js
│   ├── anvil.js
│   ├── anvil_saver/
│   │   ├── .npmrc
│   │   ├── package.json
│   │   └── saver.js
│   ├── armor_stand.js
│   ├── attack.js
│   ├── auto-eat.js
│   ├── auto_totem.js
│   ├── bee.js
│   ├── block_entity.js
│   ├── blockfinder.js
│   ├── book.js
│   ├── bossbar.js
│   ├── chat_parsing.js
│   ├── chatterbox.js
│   ├── chest.js
│   ├── cli/
│   │   └── readline.js
│   ├── collectblock.js
│   ├── command_block.js
│   ├── crossbower.js
│   ├── crystal.js
│   ├── digger.js
│   ├── discord.js
│   ├── echo.js
│   ├── elytra.js
│   ├── farmer.js
│   ├── fisherman.js
│   ├── graffiti.js
│   ├── guard.js
│   ├── inventory.js
│   ├── jumper.js
│   ├── looker.js
│   ├── modular_mineflayer/
│   │   ├── index.js
│   │   └── modules/
│   │       └── hello.js
│   ├── multiple.js
│   ├── multiple_from_file.js
│   ├── pathfinder/
│   │   ├── .npmrc
│   │   ├── gps.js
│   │   └── package.json
│   ├── perfectShotBow.js
│   ├── place_end_crystal/
│   │   ├── .npmrc
│   │   ├── index.js
│   │   └── package.json
│   ├── place_entity.js
│   ├── plugins/
│   │   ├── afk.js
│   │   └── hello_world.js
│   ├── python/
│   │   ├── README.md
│   │   ├── basic.py
│   │   └── chatterbox.py
│   ├── quitter.js
│   ├── raycast.js
│   ├── reconnector.js
│   ├── repl.js
│   ├── resourcepack.js
│   ├── scoreboard.js
│   ├── screenshot-with-node-canvas-webgl/
│   │   ├── .dockerignore
│   │   ├── .npmrc
│   │   ├── Dockerfile
│   │   ├── README.md
│   │   ├── package.json
│   │   └── screenshot.js
│   ├── session.js
│   ├── skin_blinker.js
│   ├── skin_data.js
│   ├── sleeper.js
│   ├── sound.js
│   ├── tab_complete.js
│   ├── telegram.js
│   ├── titles.js
│   ├── trader.js
│   └── viewer/
│       ├── .npmrc
│       ├── README.md
│       ├── package.json
│       └── viewer.js
├── index.d.ts
├── index.js
├── lib/
│   ├── bossbar.js
│   ├── conversions.js
│   ├── loader.js
│   ├── location.js
│   ├── math.js
│   ├── painting.js
│   ├── particle.js
│   ├── plugin_loader.js
│   ├── plugins/
│   │   ├── anvil.js
│   │   ├── bed.js
│   │   ├── block_actions.js
│   │   ├── blocks.js
│   │   ├── book.js
│   │   ├── boss_bar.js
│   │   ├── breath.js
│   │   ├── chat.js
│   │   ├── chest.js
│   │   ├── command_block.js
│   │   ├── craft.js
│   │   ├── creative.js
│   │   ├── digging.js
│   │   ├── enchantment_table.js
│   │   ├── entities.js
│   │   ├── experience.js
│   │   ├── explosion.js
│   │   ├── fishing.js
│   │   ├── furnace.js
│   │   ├── game.js
│   │   ├── generic_place.js
│   │   ├── health.js
│   │   ├── inventory.js
│   │   ├── kick.js
│   │   ├── particle.js
│   │   ├── physics.js
│   │   ├── place_block.js
│   │   ├── place_entity.js
│   │   ├── rain.js
│   │   ├── ray_trace.js
│   │   ├── resource_pack.js
│   │   ├── scoreboard.js
│   │   ├── settings.js
│   │   ├── simple_inventory.js
│   │   ├── sound.js
│   │   ├── spawn_point.js
│   │   ├── tablist.js
│   │   ├── team.js
│   │   ├── time.js
│   │   ├── title.js
│   │   └── villager.js
│   ├── promise_utils.js
│   ├── scoreboard.js
│   ├── team.js
│   └── version.js
├── package.json
├── test/
│   ├── common/
│   │   └── util.js
│   ├── externalTest.js
│   ├── externalTests/
│   │   ├── anvil.js
│   │   ├── bed.js
│   │   ├── book.js
│   │   ├── bossBar.js
│   │   ├── breath.js
│   │   ├── chat.js
│   │   ├── commandBlock.js
│   │   ├── complete.js
│   │   ├── consume.js
│   │   ├── crafting.js
│   │   ├── creative.js
│   │   ├── digAndBuild.js
│   │   ├── digEverything.js
│   │   ├── dimensionName.js
│   │   ├── displayName.js
│   │   ├── elytra.js
│   │   ├── enchanting.js
│   │   ├── exampleBee.js
│   │   ├── exampleBlockFinder.js
│   │   ├── exampleDigger.js
│   │   ├── exampleInventory.js
│   │   ├── experience.js
│   │   ├── fishing.js
│   │   ├── furnace.js
│   │   ├── gamemode.js
│   │   ├── heldItem.js
│   │   ├── nether.js
│   │   ├── particles.js
│   │   ├── placeEntity.js
│   │   ├── plugins/
│   │   │   └── testCommon.js
│   │   ├── rain.js
│   │   ├── rayTrace.js
│   │   ├── scoreboard.js
│   │   ├── sign.js
│   │   ├── sound.js
│   │   ├── spawnEvent.js
│   │   ├── team.js
│   │   ├── time.js
│   │   ├── title.js
│   │   ├── trade.js
│   │   └── useChests.js
│   └── internalTest.js
└── tsconfig.json
Download .txt
SYMBOL INDEX (322 symbols across 101 files)

FILE: .github/helper/updator.js
  function main (line 22) | async function main () {

FILE: examples/anvil.js
  function tossItem (line 62) | async function tossItem (name, amount) {
  function itemByName (line 82) | function itemByName (name) {
  function itemToString (line 86) | function itemToString (item) {
  function sayItems (line 94) | function sayItems (items = bot.inventory.items()) {
  function getAnvilIds (line 103) | function getAnvilIds () {
  function rename (line 112) | async function rename (bot, itemName, name) {
  function combine (line 126) | async function combine (bot, itemName1, itemName2, name) {

FILE: examples/attack.js
  function attackPlayer (line 27) | function attackPlayer (username) {
  function attackEntity (line 37) | function attackEntity () {

FILE: examples/bee.js
  function loop (line 18) | async function loop (n) {

FILE: examples/block_entity.js
  function spawner (line 25) | function spawner () {

FILE: examples/book.js
  function toss (line 42) | function toss () {
  function write (line 47) | async function write () {
  function print (line 57) | function print () {

FILE: examples/chat_parsing.js
  function makeChatMessages (line 38) | async function makeChatMessages () {

FILE: examples/chatterbox.js
  function canSee (line 60) | function canSee (pos) {
  function sayPosition (line 70) | function sayPosition (username) {
  function sayEquipment (line 75) | function sayEquipment () {
  function saySpawnPoint (line 90) | function saySpawnPoint () {
  function sayBlockUnder (line 94) | function sayBlockUnder () {
  function quit (line 100) | function quit (username) {
  function sayNick (line 104) | function sayNick () {

FILE: examples/chest.js
  function sayItems (line 71) | function sayItems (items = bot.inventory.items()) {
  function watchChest (line 80) | async function watchChest (minecart, blocks = []) {
  function watchFurnace (line 166) | async function watchFurnace () {
  function watchEnchantmentTable (line 252) | async function watchEnchantmentTable () {
  function useInvsee (line 355) | function useInvsee (username, showEquipment) {
  function itemToString (line 375) | function itemToString (item) {
  function itemByType (line 383) | function itemByType (items, type) {
  function itemByName (line 393) | function itemByName (items, name) {

FILE: examples/crossbower.js
  function sleep (line 55) | function sleep (ms) {

FILE: examples/digger.js
  function sayItems (line 50) | function sayItems (items = bot.inventory.items()) {
  function dig (line 59) | async function dig () {
  function build (line 79) | function build () {
  function equipDirt (line 106) | async function equipDirt () {
  function itemToString (line 121) | function itemToString (item) {

FILE: examples/elytra.js
  function sleep (line 64) | function sleep (ms) {

FILE: examples/farmer.js
  function blockToSow (line 19) | function blockToSow () {
  function blockToHarvest (line 31) | function blockToHarvest () {
  function loop (line 41) | async function loop () {

FILE: examples/fisherman.js
  function onCollect (line 38) | function onCollect (player, entity) {
  function startFishing (line 45) | async function startFishing () {
  function stopFishing (line 64) | function stopFishing () {
  function eat (line 72) | async function eat () {

FILE: examples/graffiti.js
  function watchPaintingOrSign (line 40) | function watchPaintingOrSign () {
  function updateSign (line 58) | function updateSign (message) {

FILE: examples/guard.js
  function guardArea (line 27) | function guardArea (pos) {
  function stopGuarding (line 37) | function stopGuarding () {
  function moveToGuardPos (line 44) | function moveToGuardPos () {

FILE: examples/inventory.js
  function sayItems (line 67) | function sayItems (items = null) {
  function tossItem (line 80) | async function tossItem (name, amount) {
  function equipItem (line 100) | async function equipItem (name, destination) {
  function unequipItem (line 114) | async function unequipItem (destination) {
  function useEquippedItem (line 123) | function useEquippedItem () {
  function craftItem (line 128) | async function craftItem (name, amount) {
  function itemToString (line 155) | function itemToString (item) {
  function itemByName (line 163) | function itemByName (name) {

FILE: examples/jumper.js
  function watchTarget (line 104) | function watchTarget () {

FILE: examples/modular_mineflayer/index.js
  constant OPTIONS (line 5) | const OPTIONS = {
  function injectModules (line 10) | function injectModules (bot) {
  function initBot (line 20) | function initBot () {

FILE: examples/multiple.js
  function next (line 9) | function next () {
  function createBot (line 20) | function createBot (name) {

FILE: examples/multiple_from_file.js
  function makeBot (line 19) | function makeBot ([_u, _p], ix) {
  function main (line 35) | async function main () {

FILE: examples/pathfinder/gps.js
  constant RANGE_GOAL (line 18) | const RANGE_GOAL = 1 // get within this radius of the player

FILE: examples/place_end_crystal/index.js
  constant AABB (line 9) | const AABB = require('prismarine-physics/lib/aabb')
  constant MAX_DIST_FROM_BLOCK_TO_PLACE (line 23) | const MAX_DIST_FROM_BLOCK_TO_PLACE = 4

FILE: examples/plugins/afk.js
  function rotate (line 46) | function rotate () {

FILE: examples/python/basic.py
  function handle (line 18) | def handle(*args):
  function handle (line 40) | def handle(*args):

FILE: examples/python/chatterbox.py
  function handle (line 40) | def handle(this, username, message, *args):
  function can_see (line 65) | def can_see(pos):
  function say_position (line 75) | def say_position(username):
  function say_equipment (line 83) | def say_equipment(username):
  function say_spawn (line 102) | def say_spawn():
  function say_block_under (line 106) | def say_block_under():
  function quit_game (line 112) | def quit_game(username):
  function say_nick (line 116) | def say_nick():
  function whisper (line 121) | def whisper(this, username, message, rawMessage, *a):
  function nonSpokenChat (line 127) | def nonSpokenChat(this, message):
  function login (line 132) | def login(this):
  function spawn (line 137) | def spawn(this):
  function spawnReset (line 142) | def spawnReset(this, message):
  function forcedMove (line 147) | def forcedMove(this):
  function health (line 153) | def health(this):
  function death (line 158) | def death(this):
  function kicked (line 163) | def kicked(this, reason, *a):
  function time (line 169) | def time(this):
  function rain (line 174) | def rain(this):
  function noteHeard (line 182) | def noteHeard(this, block, instrument, pitch):
  function chestLidMove (line 187) | def chestLidMove(this, block, isOpen, *a):
  function pistonMove (line 193) | def pistonMove(this, block, isPulling, direction):
  function playerJoined (line 199) | def playerJoined(this, player):
  function playerLeft (line 206) | def playerLeft(this, player):
  function playerCollect (line 213) | def playerCollect(this, collector, collected):
  function entitySpawn (line 223) | def entitySpawn(this, entity):
  function entityHurt (line 239) | def entityHurt(this, entity):
  function entitySwingArm (line 249) | def entitySwingArm(this, entity):
  function entityCrouch (line 254) | def entityCrouch(this, entity):
  function entityUncrouch (line 259) | def entityUncrouch(this, entity):
  function entitySleep (line 264) | def entitySleep(this, entity):
  function entityWake (line 269) | def entityWake(this, entity):
  function entityEat (line 274) | def entityEat(this, entity):
  function entityAttach (line 279) | def entityAttach(this, entity, vehicle):
  function entityDetach (line 285) | def entityDetach(this, entity, vehicle):
  function entityEquipmentChange (line 291) | def entityEquipmentChange(this, entity):
  function entityEffect (line 296) | def entityEffect(this, entity, effect):
  function entityEffectEnd (line 301) | def entityEffectEnd(this, entity, effect):

FILE: examples/raycast.js
  function block (line 21) | function block () {

FILE: examples/reconnector.js
  function createBot (line 11) | function createBot () {

FILE: examples/screenshot-with-node-canvas-webgl/screenshot.js
  constant THREE (line 11) | const THREE = require('three')
  class Camera (line 41) | class Camera extends EventEmitter {
    method constructor (line 42) | constructor (bot) {
    method _init (line 56) | async _init () {
    method takePicture (line 70) | async takePicture (direction, name) {

FILE: examples/skin_blinker.js
  function toggleSkin (line 23) | function toggleSkin () {

FILE: examples/sleeper.js
  function goToSleep (line 42) | async function goToSleep () {
  function wakeUp (line 58) | async function wakeUp () {

FILE: examples/tab_complete.js
  function complete (line 23) | async function complete (str) {

FILE: examples/trader.js
  function showVillagers (line 48) | function showVillagers () {
  function showInventory (line 55) | function showInventory () {
  function showTrades (line 62) | async function showTrades (id) {
  function trade (line 84) | async function trade (id, index, count) {
  function stringifyTrades (line 148) | function stringifyTrades (trades) {
  function stringifyItem (line 158) | function stringifyItem (item) {

FILE: index.d.ts
  type BotOptions (line 18) | interface BotOptions extends ClientOptions {
  type ChatLevel (line 38) | type ChatLevel = 'enabled' | 'commandsOnly' | 'disabled'
  type ViewDistance (line 39) | type ViewDistance = 'far' | 'normal' | 'short' | 'tiny' | number
  type MainHands (line 40) | type MainHands = 'left' | 'right'
  type PluginOptions (line 42) | interface PluginOptions {
  type Plugin (line 46) | type Plugin = (bot: Bot, options: BotOptions) => void
  type BotEvents (line 48) | interface BotEvents {
  type CommandBlockOptions (line 168) | interface CommandBlockOptions {
  type Bot (line 175) | interface Bot extends TypedEmitter<BotEvents> {
  type simpleClick (line 447) | interface simpleClick {
  type Tablist (line 452) | interface Tablist {
  type chatPatternOptions (line 457) | interface chatPatternOptions {
  type GameState (line 462) | interface GameState {
  type LevelType (line 472) | type LevelType =
  type GameMode (line 480) | type GameMode = 'survival' | 'creative' | 'adventure' | 'spectator'
  type Dimension (line 481) | type Dimension = 'the_nether' | 'overworld' | 'the_end'
  type Difficulty (line 482) | type Difficulty = 'peaceful' | 'easy' | 'normal' | 'hard'
  type Player (line 484) | interface Player {
  type SkinData (line 498) | interface SkinData {
  type ChatPattern (line 503) | interface ChatPattern {
  type SkinParts (line 509) | interface SkinParts {
  type GameSettings (line 519) | interface GameSettings {
  type Experience (line 528) | interface Experience {
  type PhysicsOptions (line 534) | interface PhysicsOptions {
  type Time (line 550) | interface Time {
  type ControlStateStatus (line 562) | interface ControlStateStatus {
  type ControlState (line 572) | type ControlState =
  type Effect (line 581) | interface Effect {
  type Instrument (line 587) | interface Instrument {
  type FindBlockOptions (line 592) | interface FindBlockOptions {
  type EquipmentDestination (line 600) | type EquipmentDestination = 'hand' | 'head' | 'torso' | 'legs' | 'feet' ...
  type TransferOptions (line 602) | interface TransferOptions {
  type creativeMethods (line 613) | interface creativeMethods {
  class Location (line 630) | class Location {
  class Painting (line 641) | class Painting {
  type StorageEvents (line 650) | interface StorageEvents {
  type FurnaceEvents (line 656) | interface FurnaceEvents extends StorageEvents {
  type ConditionalStorageEvents (line 660) | interface ConditionalStorageEvents extends StorageEvents {
  class Chest (line 664) | class Chest extends Window<StorageEvents> {
  class Furnace (line 682) | class Furnace extends Window<FurnaceEvents> {
  class Dispenser (line 715) | class Dispenser extends Window<StorageEvents> {
  class EnchantmentTable (line 733) | class EnchantmentTable extends Window<ConditionalStorageEvents> {
  class Anvil (line 753) | class Anvil {
  type Enchantment (line 758) | interface Enchantment {
  class Villager (line 763) | class Villager extends Window<ConditionalStorageEvents> {
  type VillagerTrade (line 771) | interface VillagerTrade {
  class ScoreBoard (line 786) | class ScoreBoard {
  type ScoreBoardItem (line 801) | interface ScoreBoardItem {
  class Team (line 807) | class Team {
  type DisplaySlot (line 832) | type DisplaySlot =
  class BossBar (line 853) | class BossBar {
  class Particle (line 874) | class Particle {

FILE: lib/bossbar.js
  function loader (line 4) | function loader (registry) {

FILE: lib/conversions.js
  constant PI_2 (line 5) | const PI_2 = Math.PI * 2
  constant TO_RAD (line 6) | const TO_RAD = PI / 180
  constant TO_DEG (line 7) | const TO_DEG = 1 / TO_RAD
  constant FROM_NOTCH_BYTE (line 8) | const FROM_NOTCH_BYTE = 360 / 256
  constant FROM_NOTCH_VEL (line 10) | const FROM_NOTCH_VEL = 1 / 8000
  function toRadians (line 22) | function toRadians (degrees) {
  function toDegrees (line 26) | function toDegrees (radians) {
  function fromNotchianYaw (line 30) | function fromNotchianYaw (yaw) {
  function fromNotchianPitch (line 34) | function fromNotchianPitch (pitch) {
  function fromNotchVelocity (line 38) | function fromNotchVelocity (vel) {

FILE: lib/loader.js
  function createBot (line 66) | function createBot (options = {}) {

FILE: lib/location.js
  constant CHUNK_SIZE (line 2) | const CHUNK_SIZE = new Vec3(16, 16, 16)
  class Location (line 4) | class Location {
    method constructor (line 5) | constructor (absoluteVector) {

FILE: lib/painting.js
  function Painting (line 1) | function Painting (id, pos, name, direction) {

FILE: lib/particle.js
  function loader (line 5) | function loader (registry) {

FILE: lib/plugin_loader.js
  function inject (line 5) | function inject (bot, options) {

FILE: lib/plugins/anvil.js
  function inject (line 7) | function inject (bot) {

FILE: lib/plugins/bed.js
  constant CARDINAL_DIRECTIONS (line 5) | const CARDINAL_DIRECTIONS = ['south', 'west', 'north', 'east']
  function inject (line 7) | function inject (bot) {

FILE: lib/plugins/block_actions.js
  constant CARDINALS (line 5) | const CARDINALS = {
  constant FACING_MAP (line 12) | const FACING_MAP = {
  function inject (line 19) | function inject (bot) {

FILE: lib/plugins/blocks.js
  function inject (line 23) | function inject (bot, { version, storageBuilder, hideErrors }) {
  function onesInShort (line 607) | function onesInShort (n) {

FILE: lib/plugins/book.js
  function inject (line 6) | function inject (bot) {

FILE: lib/plugins/boss_bar.js
  function inject (line 3) | function inject (bot, { version }) {

FILE: lib/plugins/breath.js
  function inject (line 3) | function inject (bot) {

FILE: lib/plugins/chat.js
  constant USERNAME_REGEX (line 3) | const USERNAME_REGEX = '(?:\\(.{1,15}\\)|\\[.{1,15}\\]|.){0,5}?(\\w+)'
  constant LEGACY_VANILLA_CHAT_REGEX (line 4) | const LEGACY_VANILLA_CHAT_REGEX = new RegExp(`^${USERNAME_REGEX}\\s?[>:\...
  function inject (line 8) | function inject (bot, options) {

FILE: lib/plugins/chest.js
  function inject (line 5) | function inject (bot) {

FILE: lib/plugins/command_block.js
  function inject (line 6) | function inject (bot) {

FILE: lib/plugins/craft.js
  function inject (line 6) | function inject (bot) {

FILE: lib/plugins/creative.js
  function inject (line 8) | function inject (bot) {
  function vecMagnitude (line 110) | function vecMagnitude (vec) {

FILE: lib/plugins/digging.js
  function inject (line 8) | function inject (bot) {
  function noop (line 262) | function noop (err) {

FILE: lib/plugins/enchantment_table.js
  function inject (line 6) | function inject (bot) {

FILE: lib/plugins/entities.js
  constant PLAYER_HEIGHT (line 5) | const PLAYER_HEIGHT = 1.8
  constant CROUCH_HEIGHT (line 6) | const CROUCH_HEIGHT = 1.5
  constant PLAYER_WIDTH (line 7) | const PLAYER_WIDTH = 0.6
  constant PLAYER_EYEHEIGHT (line 8) | const PLAYER_EYEHEIGHT = 1.62
  constant CROUCH_EYEHEIGHT (line 9) | const CROUCH_EYEHEIGHT = 1.27
  function inject (line 32) | function inject (bot) {
  function parseMetadata (line 936) | function parseMetadata (metadata, entityMetadata = {}) {
  function extractSkinInformation (line 946) | function extractSkinInformation (properties) {

FILE: lib/plugins/experience.js
  function inject (line 3) | function inject (bot) {

FILE: lib/plugins/explosion.js
  function calcExposure (line 6) | function calcExposure (playerPos, explosionPos, world) {
  function getDamageAfterAbsorb (line 33) | function getDamageAfterAbsorb (damages, armorValue, toughness) {
  function getAttributeValue (line 40) | function getAttributeValue (prop) {
  function inject (line 58) | function inject (bot) {

FILE: lib/plugins/fishing.js
  function inject (line 6) | function inject (bot) {

FILE: lib/plugins/furnace.js
  function inject (line 5) | function inject (bot) {

FILE: lib/plugins/game.js
  function inject (line 20) | function inject (bot, options) {

FILE: lib/plugins/generic_place.js
  function inject (line 4) | function inject (bot) {
  function vectorToDirection (line 93) | function vectorToDirection (v) {

FILE: lib/plugins/health.js
  function inject (line 3) | function inject (bot, options) {

FILE: lib/plugins/inventory.js
  constant DIG_CLICK_TIMEOUT (line 9) | const DIG_CLICK_TIMEOUT = 500
  constant CONSUME_TIMEOUT (line 13) | const CONSUME_TIMEOUT = 2500
  constant WINDOW_TIMEOUT (line 15) | const WINDOW_TIMEOUT = 5000
  constant ALWAYS_CONSUMABLES (line 17) | const ALWAYS_CONSUMABLES = [
  function inject (line 24) | function inject (bot, { hideErrors }) {

FILE: lib/plugins/kick.js
  function inject (line 3) | function inject (bot) {

FILE: lib/plugins/particle.js
  function inject (line 3) | function inject (bot, { version }) {

FILE: lib/plugins/physics.js
  constant PI_2 (line 13) | const PI_2 = Math.PI * 2
  constant PHYSICS_INTERVAL_MS (line 14) | const PHYSICS_INTERVAL_MS = 50
  constant PHYSICS_TIMESTEP (line 15) | const PHYSICS_TIMESTEP = PHYSICS_INTERVAL_MS / 1000 // 0.05
  function inject (line 17) | function inject (bot, { physicsEnabled, maxCatchupTicks }) {

FILE: lib/plugins/place_block.js
  function inject (line 5) | function inject (bot) {

FILE: lib/plugins/place_entity.js
  function inject (line 5) | function inject (bot) {

FILE: lib/plugins/rain.js
  function inject (line 4) | function inject (bot) {

FILE: lib/plugins/ray_trace.js
  function getViewDirection (line 5) | function getViewDirection (pitch, yaw) {

FILE: lib/plugins/resource_pack.js
  constant UUID (line 1) | const UUID = require('uuid-1345')
  function inject (line 5) | function inject (bot) {

FILE: lib/plugins/scoreboard.js
  function inject (line 3) | function inject (bot) {

FILE: lib/plugins/settings.js
  function inject (line 23) | function inject (bot, options) {
  function extend (line 102) | function extend (obj, src) {

FILE: lib/plugins/simple_inventory.js
  constant QUICK_BAR_COUNT (line 5) | const QUICK_BAR_COUNT = 9
  constant QUICK_BAR_START (line 6) | const QUICK_BAR_START = 36
  function inject (line 8) | function inject (bot) {

FILE: lib/plugins/sound.js
  function inject (line 5) | function inject (bot) {

FILE: lib/plugins/spawn_point.js
  function inject (line 5) | function inject (bot) {

FILE: lib/plugins/tablist.js
  function inject (line 7) | function inject (bot) {

FILE: lib/plugins/team.js
  constant TEAM_MODES (line 4) | const TEAM_MODES = ['add', 'remove', 'change', 'join', 'leave']
  function inject (line 6) | function inject (bot) {

FILE: lib/plugins/time.js
  function inject (line 3) | function inject (bot) {
  function longToBigInt (line 36) | function longToBigInt (arr) {

FILE: lib/plugins/title.js
  function inject (line 2) | function inject (bot) {

FILE: lib/plugins/villager.js
  function inject (line 6) | function inject (bot, { version }) {

FILE: lib/promise_utils.js
  function sleep (line 1) | function sleep (ms) {
  function createTask (line 5) | function createTask () {
  function createDoneTask (line 26) | function createDoneTask () {
  function onceWithCleanup (line 47) | function onceWithCleanup (emitter, event, { timeout = 0, checkCondition ...
  function once (line 75) | function once (emitter, event, timeout = 20000) {
  function withTimeout (line 79) | function withTimeout (promise, timeout) {

FILE: lib/scoreboard.js
  class ScoreBoard (line 10) | class ScoreBoard {
    method constructor (line 11) | constructor (packet) {
    method setTitle (line 17) | setTitle (title) {
    method add (line 25) | add (name, value) {
    method remove (line 40) | remove (name) {
    method items (line 46) | get items () {
  method list (line 52) | get list () {
  method sidebar (line 56) | get sidebar () {
  method belowName (line 60) | get belowName () {

FILE: lib/team.js
  function colorString (line 1) | function colorString (color) {
  function loader (line 30) | function loader (registry) {

FILE: test/externalTest.js
  constant START_THE_SERVER (line 13) | const START_THE_SERVER = true
  constant TEST_TIMEOUT_MS (line 15) | const TEST_TIMEOUT_MS = 90000
  constant MC_SERVER_PATH (line 34) | const MC_SERVER_PATH = path.join(__dirname, 'server')
  function begin (line 56) | function begin () {

FILE: test/externalTests/anvil.js
  function runTest (line 5) | async function runTest (bot, testFunction) {
  function addTest (line 41) | function addTest (name, f) {

FILE: test/externalTests/chat.js
  function runTest (line 5) | async function runTest (bot, testFunction) {
  function addTest (line 11) | function addTest (name, f) {

FILE: test/externalTests/crafting.js
  function findCraftingTable (line 18) | function findCraftingTable () {
  function craft (line 30) | async function craft (amount, name) {

FILE: test/externalTests/creative.js
  constant SLOT (line 3) | const SLOT = 36

FILE: test/externalTests/digAndBuild.js
  function waitForFall (line 21) | async function waitForFall () {

FILE: test/externalTests/digEverything.js
  function digSomething (line 68) | async function digSomething (blockId, bot) {

FILE: test/externalTests/exampleInventory.js
  function makeTest (line 71) | function makeTest (inStr, outStr) {
  function makeListener (line 77) | function makeListener (wantedMessage) {

FILE: test/externalTests/fishing.js
  function onPlayerCollect (line 10) | function onPlayerCollect (collector, collected) {

FILE: test/externalTests/gamemode.js
  function addTest (line 9) | function addTest (name, f) {

FILE: test/externalTests/particles.js
  function onParticleEvent (line 7) | function onParticleEvent (particle) {

FILE: test/externalTests/placeEntity.js
  function runTest (line 6) | async function runTest (bot, testFunction) {
  function addTest (line 12) | function addTest (name, f) {
  function placeBlocksForTest (line 38) | async function placeBlocksForTest (blockName) {

FILE: test/externalTests/plugins/testCommon.js
  function inject (line 12) | function inject (bot) {

FILE: test/externalTests/trade.js
  function expectAmount (line 5) | function expectAmount (amount, greaterThan) {
  function verifyTrade (line 134) | function verifyTrade (trade) {

FILE: test/externalTests/useChests.js
  function itemByName (line 31) | function itemByName (items, name) {
  function depositBones (line 39) | async function depositBones (chestLocation, count) {
  function withdrawBones (line 53) | async function withdrawBones (chestLocation, count) {
  function handler (line 91) | async function handler (block, isOpen, block2) {
  function getRandomStackableItem (line 136) | function getRandomStackableItem () {
  function createRandomLayout (line 148) | async function createRandomLayout (window, slotPopulationFactor) {
  function testMouseClick (line 170) | async function testMouseClick (window, clicks) {
  function clearLargeChest (line 177) | function clearLargeChest () {

FILE: test/internalTest.js
  function chatText (line 17) | function chatText (text) {
  function generateChunkPacket (line 24) | function generateChunkPacket (chunk) {
  function onChat (line 185) | function onChat (packet) {
Condensed preview — 239 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,344K chars).
[
  {
    "path": ".github/FUNDING.yml",
    "chars": 174,
    "preview": "# These are supported funding model platforms\nopen_collective: prismarinejs\ncustom: https://rysolv.com/repos/detail/7469"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "chars": 859,
    "preview": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: possible bug,Stage1\nassignees: ''\n\n---\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "chars": 228,
    "preview": "blank_issues_enabled: false\ncontact_links:\n  - name: Github Discussions\n    url: https://github.com/PrismarineJS/minefla"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "chars": 607,
    "preview": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: new feature,Stage1\nassignees: ''\n\n--"
  },
  {
    "path": ".github/dependabot.yml",
    "chars": 197,
    "preview": "version: 2\nupdates:\n- package-ecosystem: npm\n  directory: \"/\"\n  schedule:\n    interval: daily\n  open-pull-requests-limit"
  },
  {
    "path": ".github/helper/package.json",
    "chars": 58,
    "preview": "{\r\n  \"dependencies\": {\r\n    \"gh-helpers\": \"^1.0.0\"\r\n  }\r\n}"
  },
  {
    "path": ".github/helper/updator.js",
    "chars": 4026,
    "preview": "#!/usr/bin/env node\r\n/**\r\n * Updator script triggered from minecraft-data repository to auto generate PR\r\n */\r\nconst fs "
  },
  {
    "path": ".github/workflows/ci.yml",
    "chars": 1472,
    "preview": "name: CI\n\non:\n  push:\n    branches:\n      - master\n  pull_request:\n\njobs:\n  Lint:\n    runs-on: ubuntu-latest\n\n    steps:"
  },
  {
    "path": ".github/workflows/commands.yml",
    "chars": 868,
    "preview": "name: Repo Commands\r\n\r\non:\r\n  issue_comment:        # Handle comment commands\r\n    types: [created]\r\n  pull_request:    "
  },
  {
    "path": ".github/workflows/handle-update.yml",
    "chars": 1660,
    "preview": "name: Update from minecraft-data\r\n\r\non:\r\n  workflow_dispatch:\r\n    inputs:\r\n      new_mc_version:\r\n        description: "
  },
  {
    "path": ".github/workflows/npm-publish.yml",
    "chars": 895,
    "preview": "name: npm-publish\non:\n  push:\n    branches:\n      - master # Change this to your default branch\njobs:\n  npm-publish:\n   "
  },
  {
    "path": ".gitignore",
    "chars": 187,
    "preview": "# shared with .npmignore\n# different than .npmignore\nnode_modules\npackage-lock.json\nyarn.lock\n/README.md\nversions/\nserve"
  },
  {
    "path": ".gitpod.yml",
    "chars": 50,
    "preview": "tasks:\n- command: npm install && sdk install java\n"
  },
  {
    "path": ".npmignore",
    "chars": 58,
    "preview": "# shared with .gitignore\n# different than .gitignore\ntest\n"
  },
  {
    "path": ".npmrc",
    "chars": 38,
    "preview": "engine-strict=true\npackage-lock=false\n"
  },
  {
    "path": "LICENSE",
    "chars": 1080,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2015 Andrew Kelley\n\nPermission is hereby granted, free of charge, to any person obt"
  },
  {
    "path": "docs/.nojekyll",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "docs/CONTRIBUTING.md",
    "chars": 4578,
    "preview": "# Contribute\n\nMineflayer has originally been made mostly by [andrewrk](http://github.com/andrewrk)\nbut has since then be"
  },
  {
    "path": "docs/FAQ.md",
    "chars": 7232,
    "preview": "## FAQ\n\nThis Frequently Asked Question document is meant to help people for the most common things.\n\n### I get an error "
  },
  {
    "path": "docs/README.md",
    "chars": 16682,
    "preview": "# Mineflayer\n\n[![NPM version](https://img.shields.io/npm/v/mineflayer.svg?color=success&label=npm%20package&logo=npm)](h"
  },
  {
    "path": "docs/_sidebar.md",
    "chars": 221,
    "preview": "- Getting Started\n  - [Introduction](/)\n  - [API](api.md)\n  - [FAQ](FAQ.md)\n  - [Demos](demos.md)\n  - [Tutorial](tutoria"
  },
  {
    "path": "docs/api.md",
    "chars": 81901,
    "preview": "<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD "
  },
  {
    "path": "docs/br/CONTRIBUTING_BR.md",
    "chars": 4584,
    "preview": "# Contribuir\n\nO Mineflayer foi originalmente criado principalmente por [andrewrk](http://github.com/andrewrk), mas tem s"
  },
  {
    "path": "docs/br/FAQ_BR.md",
    "chars": 6834,
    "preview": "## Perguntas Frequentes\n\nEste documento de perguntas frequentes tem o objetivo de ajudar as pessoas com informações bási"
  },
  {
    "path": "docs/br/README_BR.md",
    "chars": 14436,
    "preview": "# Mineflayer\n\n[![NPM version](https://badge.fury.io/js/mineflayer.svg)](http://badge.fury.io/js/mineflayer)\n[![Build Sta"
  },
  {
    "path": "docs/br/api_br.md",
    "chars": 75235,
    "preview": "<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD "
  },
  {
    "path": "docs/br/unstable_api_br.md",
    "chars": 1013,
    "preview": "<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD "
  },
  {
    "path": "docs/demos.md",
    "chars": 775,
    "preview": "## mineflayer-navigate\n\n[navigate](https://github.com/andrewrk/mineflayer-navigate/) - get around\n   easily using A* pat"
  },
  {
    "path": "docs/es/CONTRIBUTING_ES.md",
    "chars": 4636,
    "preview": "# Contribuir\n\nMineflayer originalmente fue hecho mayormemente por [andrewrk](http://github.com/andrewrk)\npero ha sido ar"
  },
  {
    "path": "docs/es/FAQ_ES.md",
    "chars": 6358,
    "preview": "## FAQ\n\nEste documento sobre preguntas frecuentes es para ayudar la gente en cosas básicas\n\n## Como ocultar errores?\n\nEs"
  },
  {
    "path": "docs/es/README_ES.md",
    "chars": 14535,
    "preview": "# Mineflayer\n\n[![NPM version](https://badge.fury.io/js/mineflayer.svg)](http://badge.fury.io/js/mineflayer)\n[![Build Sta"
  },
  {
    "path": "docs/es/api_es.md",
    "chars": 76022,
    "preview": "<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD "
  },
  {
    "path": "docs/es/unstable_api_es.md",
    "chars": 1026,
    "preview": "<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD "
  },
  {
    "path": "docs/fr/FAQ_FR.md",
    "chars": 7804,
    "preview": "## FAQ\n\nCe document de foire aux questions a pour but d'aider les gens pour les choses les plus courantes.\n\n### Je reçoi"
  },
  {
    "path": "docs/fr/README_FR.md",
    "chars": 14789,
    "preview": "# Mineflayer\n\n[![NPM version](https://badge.fury.io/js/mineflayer.svg)](http://badge.fury.io/js/mineflayer)\n[![Build Sta"
  },
  {
    "path": "docs/history.md",
    "chars": 52610,
    "preview": "## 4.35.0\n* [🎈 1.21.11 (#3781)](https://github.com/PrismarineJS/mineflayer/commit/597745c7c061943620fcacba7254bccee05b7a"
  },
  {
    "path": "docs/index.html",
    "chars": 1270,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <title>mineflayer - create minecraft bots with a stab"
  },
  {
    "path": "docs/llm_contribute.md",
    "chars": 7502,
    "preview": "# Contributing to Mineflayer Tests as an LLM\n\nThis guide explains how to add and modify tests in Mineflayer, based on th"
  },
  {
    "path": "docs/mineflayer.ipynb",
    "chars": 38866,
    "preview": "{\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0,\n  \"metadata\": {\n    \"colab\": {\n      \"name\": \"mineflayer.ipynb\",\n      \"proven"
  },
  {
    "path": "docs/ru/CONTRIBUTING_RU.md",
    "chars": 4840,
    "preview": "# Вклад в проект\n\nИзначально Mineflayer создал [andrewrk](http://github.com/andrewrk), но с тех пор проект был улучшен и"
  },
  {
    "path": "docs/ru/FAQ_RU.md",
    "chars": 7636,
    "preview": "## FAQ\n\nЭто документ с часто задаваемыми вопросами, предназначен для помощи людям в самых распространенных вещах.\n\n### В"
  },
  {
    "path": "docs/ru/README_RU.md",
    "chars": 19142,
    "preview": "# Mineflayer\n\n[![Версия NPM](https://img.shields.io/npm/v/mineflayer.svg?color=success&label=npm%20package&logo=npm)](ht"
  },
  {
    "path": "docs/ru/_sidebar.md",
    "chars": 269,
    "preview": "- Первые шаги\n  - [Вступление](ru/README_RU.md)\n  - [API](ru/api_ru.md)\n  - [ЧаВо](ru/FAQ_RU.md)\n  - [Примеры](ru/demos_"
  },
  {
    "path": "docs/ru/api_ru.md",
    "chars": 83445,
    "preview": "<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD "
  },
  {
    "path": "docs/ru/demos_ru.md",
    "chars": 817,
    "preview": "## mineflayer-navigate\n\n[navigate](https://github.com/andrewrk/mineflayer-navigate/) - Лёгкое передвижение с помощью пои"
  },
  {
    "path": "docs/ru/index.html",
    "chars": 1310,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <title>Mineflayer - создавайте Майнкрафт ботов с помо"
  },
  {
    "path": "docs/ru/tutorial_ru.md",
    "chars": 24937,
    "preview": "# Туториал\n\n**Содержание**\n\n- [Вступление](#вступление)\n- [Основы](#основы)\n  - [Основы Javascript](#основы-javascript)\n"
  },
  {
    "path": "docs/ru/unstable_api_ru.md",
    "chars": 874,
    "preview": "<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD "
  },
  {
    "path": "docs/tr/README_TR.md",
    "chars": 14171,
    "preview": "# Mineflayer\n\n[![NPM version](https://badge.fury.io/js/mineflayer.svg)](http://badge.fury.io/js/mineflayer)\n[![Build Sta"
  },
  {
    "path": "docs/tutorial.md",
    "chars": 24733,
    "preview": "# Tutorial\n\n**Table of Contents**\n\n- [Basics](#basics)\n  - [Javascript basics](#javascript-basics)\n    - [Installing Nod"
  },
  {
    "path": "docs/unstable_api.md",
    "chars": 818,
    "preview": "<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD "
  },
  {
    "path": "docs/update_to_1_21_5.md",
    "chars": 14422,
    "preview": "# Mineflayer 1.21.5 Support Plan\n\n## 🚩 Latest Progress (July 2025)\n\n- ✅ **Chunk loading/parsing is now fixed** in both `"
  },
  {
    "path": "docs/zh/CONTRIBUTING.md",
    "chars": 3050,
    "preview": "# 贡献\n\nMineflayer 最初主要是由 [andrewrk](http://github.com/andrewrk) 制作的\n但自那以后,许多[贡献者](https://github.com/andrewrk/mineflayer/"
  },
  {
    "path": "docs/zh/FAQ.md",
    "chars": 4448,
    "preview": "## FAQ\n\n本文档旨在帮助人们解决常见问题\n\n### 如何隐藏报错 ?\n\n在createBot选项中使用`hideErrors:true`\n您也可以选择添加这些监听事件:\n\n```js\nclient.on('error', () => "
  },
  {
    "path": "docs/zh/README_ZH_CN.md",
    "chars": 11791,
    "preview": "# Mineflayer\n\n[![NPM version](https://badge.fury.io/js/mineflayer.svg)](http://badge.fury.io/js/mineflayer)\n[![Build Sta"
  },
  {
    "path": "docs/zh/_sidebar.md",
    "chars": 208,
    "preview": "- 入门手册\n  - [介绍](zh/README_ZH_CN.md)\n  - [API](zh/api.md)\n  - [FAQ](zh/FAQ.md)\n  - [演示](zh/demos.md)\n  - [教程](zh/tutorial"
  },
  {
    "path": "docs/zh/api.md",
    "chars": 70736,
    "preview": "<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD "
  },
  {
    "path": "docs/zh/demos.md",
    "chars": 717,
    "preview": "## mineflayer-navigate\n\n[navigate](https://github.com/andrewrk/mineflayer-navigate/) -  轻松使用A*寻路\n\n<iframe type=\"text/htm"
  },
  {
    "path": "docs/zh/history.md",
    "chars": 27010,
    "preview": "## 3.14.0\n\n* Make prismarine-entity versioned (@u9g)\n* fix(typings): Added OpenContainer (@SaubereSache)\n\n## 3.13.1\n\n* F"
  },
  {
    "path": "docs/zh/index.html",
    "chars": 1225,
    "preview": "<!DOCTYPE html>\n<html lang=\"zh-cmn-Hans\">\n<head>\n  <meta charset=\"UTF-8\">\n  <title>Mineflayer - 使用稳定的高级API创建Minecraft机器人"
  },
  {
    "path": "docs/zh/tutorial.md",
    "chars": 25519,
    "preview": "# 使用教程\n\n**目录**\n\n- [基础](#基础)\n  - [Javascript 基础](#Javascript 基础知识)\n    - [Installing Node](#installing-node)\n    - [Javas"
  },
  {
    "path": "examples/advanced/README.md",
    "chars": 104,
    "preview": "# Advanced examples\n\nThese are examples that have a very specific use-case, and most people won't need.\n"
  },
  {
    "path": "examples/advanced/chest_confirm.md",
    "chars": 508,
    "preview": "# Manual Chest Confirm\n\nThis code snippet will tell the bot not to wait for chest confirmations that some spigot plugins"
  },
  {
    "path": "examples/ansi.js",
    "chars": 525,
    "preview": "/*\n *\n * A simple bot that logs everything that is said to the console.\n *\n */\nconst mineflayer = require('mineflayer')\n"
  },
  {
    "path": "examples/anvil.js",
    "chars": 3687,
    "preview": "/**\n * This example demonstrates how to use anvils w/ mineflayer\n *  the options are: (<Option> are required, [<Option>]"
  },
  {
    "path": "examples/anvil_saver/.npmrc",
    "chars": 38,
    "preview": "engine-strict=true\npackage-lock=false\n"
  },
  {
    "path": "examples/anvil_saver/package.json",
    "chars": 184,
    "preview": "{\n  \"name\": \"mineflayer-example\",\n  \"version\": \"0.0.0\",\n  \"private\": true,\n  \"dependencies\": {\n    \"prismarine-provider-"
  },
  {
    "path": "examples/anvil_saver/saver.js",
    "chars": 869,
    "preview": "/*\n * This example demonstrates how to save a world with mineflayer and\n * https://github.com/PrismarineJS/prismarine-pr"
  },
  {
    "path": "examples/armor_stand.js",
    "chars": 1644,
    "preview": "/*\n * This script will apply armor onto an armor stand within 4 blocks of the bot\n */\nconst mineflayer = require('minefl"
  },
  {
    "path": "examples/attack.js",
    "chars": 1123,
    "preview": "/*\n *\n * A bot that attacks the player that sends a message or the nearest entity (excluding players)\n *\n */\nconst minef"
  },
  {
    "path": "examples/auto-eat.js",
    "chars": 836,
    "preview": "const mineflayer = require('mineflayer')\nconst autoeat = require('mineflayer-auto-eat')\n\nconst bot = mineflayer.createBo"
  },
  {
    "path": "examples/auto_totem.js",
    "chars": 848,
    "preview": "/*\n * This script will automatically set if a totem is in the inventory or the off-hand.\n * It checks for a totem every "
  },
  {
    "path": "examples/bee.js",
    "chars": 929,
    "preview": "const mineflayer = require('mineflayer')\n\nif (process.argv.length < 4 || process.argv.length > 6) {\n  console.log('Usage"
  },
  {
    "path": "examples/block_entity.js",
    "chars": 1144,
    "preview": "/*\n * This example demonstrates how easy it is to create a bot\n * that fetches monster spawners mob type\n */\nconst minef"
  },
  {
    "path": "examples/blockfinder.js",
    "chars": 1218,
    "preview": "/*\n * This simple bot will help you find any block\n */\nconst mineflayer = require('mineflayer')\n\nconst { performance } ="
  },
  {
    "path": "examples/book.js",
    "chars": 1865,
    "preview": "const mineflayer = require('mineflayer')\n\nif (process.argv.length < 4 || process.argv.length > 6) {\n  console.log('Usage"
  },
  {
    "path": "examples/bossbar.js",
    "chars": 1516,
    "preview": "const mineflayer = require('mineflayer')\n\nif (process.argv.length < 4 || process.argv.length > 6) {\n  console.log('Usage"
  },
  {
    "path": "examples/chat_parsing.js",
    "chars": 1475,
    "preview": "/*\nthis example is to show the different ways to parse chat messages\n\nExpected output in console:\n\nbot has just joined!\n"
  },
  {
    "path": "examples/chatterbox.js",
    "chars": 7254,
    "preview": "/*\n * This example demonstrates how easy it is to create a bot\n * that sends chat messages whenever something interestin"
  },
  {
    "path": "examples/chest.js",
    "chars": 11073,
    "preview": "/*\n * Watch out, this is a big one!\n *\n * This is a demonstration to show you how you can interact with:\n * - Chests\n * "
  },
  {
    "path": "examples/cli/readline.js",
    "chars": 1843,
    "preview": "/*\n * This example is an easy way to connect mineflayer to the node:readline module\n * See: https://nodejs.org/api/readl"
  },
  {
    "path": "examples/collectblock.js",
    "chars": 1498,
    "preview": "/**\n * A quick and easy implementation of the collect block plugin. (Requires mineflayer-pathfinder and mineflayer-colle"
  },
  {
    "path": "examples/command_block.js",
    "chars": 848,
    "preview": "/*\n * An example on how to set and read command blocks\n */\n\nconst mineflayer = require('mineflayer')\n\nif (process.argv.l"
  },
  {
    "path": "examples/crossbower.js",
    "chars": 2053,
    "preview": "// This example will shoot the player that said \"fire\" in chat, when it is said in chat.\nconst mineflayer = require('min"
  },
  {
    "path": "examples/crystal.js",
    "chars": 874,
    "preview": "const mineflayer = require('mineflayer')\n\nif (process.argv.length < 4 || process.argv.length > 6) {\n  console.log('Usage"
  },
  {
    "path": "examples/digger.js",
    "chars": 3287,
    "preview": "/*\n * Never spend hours mining from ground to bedrock again!\n *\n * Learn how to create a simple bot that is capable of d"
  },
  {
    "path": "examples/discord.js",
    "chars": 2377,
    "preview": "/*\n * This example is a very simple way how to connect a discord bot with a mineflayer bot.\n * For this example you will"
  },
  {
    "path": "examples/echo.js",
    "chars": 820,
    "preview": "/*\n * This is one of the simplest examples.\n *\n * We created a simple bot that echoes back everything that is said on ch"
  },
  {
    "path": "examples/elytra.js",
    "chars": 1658,
    "preview": "// This example will shoot the player that said \"fire\" in chat, when it is said in chat.\nconst mineflayer = require('min"
  },
  {
    "path": "examples/farmer.js",
    "chars": 1628,
    "preview": "const { Vec3 } = require('vec3')\nconst mineflayer = require('mineflayer')\n\nif (process.argv.length < 4 || process.argv.l"
  },
  {
    "path": "examples/fisherman.js",
    "chars": 1752,
    "preview": "const mineflayer = require('mineflayer')\n\nif (process.argv.length < 4 || process.argv.length > 6) {\n  console.log('Usage"
  },
  {
    "path": "examples/graffiti.js",
    "chars": 2003,
    "preview": "/*\n * What's better than a bot that knows how to read and understands art?\n *\n * Learn how easy it is to interact with s"
  },
  {
    "path": "examples/guard.js",
    "chars": 2329,
    "preview": "/**\n * This bot example shows the basic usage of the mineflayer-pvp plugin for guarding a defined area from nearby mobs."
  },
  {
    "path": "examples/inventory.js",
    "chars": 4319,
    "preview": "/*\n * Using the inventory is one of the first things you learn in Minecraft,\n * now it's time to teach your bot the same"
  },
  {
    "path": "examples/jumper.js",
    "chars": 2825,
    "preview": "/*\n * Jumping is fun. Riding pigs is even funnier!\n *\n * Learn how to make your bot interactive with this example.\n *\n *"
  },
  {
    "path": "examples/looker.js",
    "chars": 810,
    "preview": "/*\n * This script will automatically look at the closest entity.\n * It checks for a near entity every tick.\n */\nconst mi"
  },
  {
    "path": "examples/modular_mineflayer/index.js",
    "chars": 651,
    "preview": "const fs = require('fs')\nconst path = require('path')\nconst mineflayer = require('mineflayer')\n\nconst OPTIONS = {\n  user"
  },
  {
    "path": "examples/modular_mineflayer/modules/hello.js",
    "chars": 315,
    "preview": "const mineflayer = require('mineflayer') // eslint-disable-line\n\n/**\n * @param {mineflayer.Bot} bot // to enable intelli"
  },
  {
    "path": "examples/multiple.js",
    "chars": 473,
    "preview": "const mineflayer = require('mineflayer')\n\nif (process.argv.length < 3 || process.argv.length > 5) {\n  console.log('Usage"
  },
  {
    "path": "examples/multiple_from_file.js",
    "chars": 1496,
    "preview": "/*\n* This example is for people with multiple (mojang) minecraft accounts,\n* in a file in the format \"username:password\""
  },
  {
    "path": "examples/pathfinder/.npmrc",
    "chars": 38,
    "preview": "engine-strict=true\npackage-lock=false\n"
  },
  {
    "path": "examples/pathfinder/gps.js",
    "chars": 1166,
    "preview": "// This is an example that uses mineflayer-pathfinder to showcase how simple it is to walk to goals\n\nconst mineflayer = "
  },
  {
    "path": "examples/pathfinder/package.json",
    "chars": 213,
    "preview": "{\n  \"name\": \"mineflayer-example\",\n  \"version\": \"0.0.0\",\n  \"private\": true,\n  \"dependencies\": {\n    \"mineflayer-pathfinde"
  },
  {
    "path": "examples/perfectShotBow.js",
    "chars": 1900,
    "preview": "const mineflayer = require('mineflayer')\nconst minecraftHawkEye = require('minecrafthawkeye')\n\nconst bot = mineflayer.cr"
  },
  {
    "path": "examples/place_end_crystal/.npmrc",
    "chars": 38,
    "preview": "engine-strict=true\npackage-lock=false\n"
  },
  {
    "path": "examples/place_end_crystal/index.js",
    "chars": 3440,
    "preview": "// This example shows how to tell the bot to place an end crystal\n// Example commands:\n// \"place crystal near bot\" - fin"
  },
  {
    "path": "examples/place_end_crystal/package.json",
    "chars": 180,
    "preview": "{\n  \"name\": \"mineflayer-example\",\n  \"version\": \"0.0.0\",\n  \"private\": true,\n  \"dependencies\": {\n    \"mineflayer-pathfinde"
  },
  {
    "path": "examples/place_entity.js",
    "chars": 837,
    "preview": "const mineflayer = require('mineflayer')\nconst { Vec3 } = require('vec3')\nconst bot = mineflayer.createBot()\n\nbot.on('ch"
  },
  {
    "path": "examples/plugins/afk.js",
    "chars": 1077,
    "preview": "/*\r\n  Make a function that is exported, this will be the \"inject function\", which is called when loading the plugin into"
  },
  {
    "path": "examples/plugins/hello_world.js",
    "chars": 98,
    "preview": "module.exports = (bot, { version }) => {\n  bot.once('spawn', () => console.log('hello world!'))\n}\n"
  },
  {
    "path": "examples/python/README.md",
    "chars": 1494,
    "preview": "# Using mineflayer in Python\n\n* Checkout the tutorial on Google Colab 👉 [![Open In Colab](https://colab.research.google."
  },
  {
    "path": "examples/python/basic.py",
    "chars": 1060,
    "preview": "from javascript import require, On\nmineflayer = require('mineflayer')\npathfinder = require('mineflayer-pathfinder')\n\nRAN"
  },
  {
    "path": "examples/python/chatterbox.py",
    "chars": 8496,
    "preview": "# ==========================================================================\n# This example demonstrates how easy it is "
  },
  {
    "path": "examples/quitter.js",
    "chars": 688,
    "preview": "/*\n * This is one of the simplest examples.\n *\n * We created a simple bot that connects to a server and immediately quit"
  },
  {
    "path": "examples/raycast.js",
    "chars": 637,
    "preview": "const mineflayer = require('mineflayer')\n\nif (process.argv.length < 4 || process.argv.length > 6) {\n  console.log('Usage"
  },
  {
    "path": "examples/reconnector.js",
    "chars": 610,
    "preview": "/*\n * This example will automatically reconnect when it gets disconnected from the server.\n */\nconst mineflayer = requir"
  },
  {
    "path": "examples/repl.js",
    "chars": 528,
    "preview": "const mineflayer = require('mineflayer')\nconst repl = require('repl')\n\nif (process.argv.length < 4 || process.argv.lengt"
  },
  {
    "path": "examples/resourcepack.js",
    "chars": 559,
    "preview": "/*\n *\n * A simple bot that accepts a resource pack sent by a server\n *\n */\nconst mineflayer = require('mineflayer')\n\nif "
  },
  {
    "path": "examples/scoreboard.js",
    "chars": 921,
    "preview": "/*\n * A simple example to show the display board functionality\n */\nconst mineflayer = require('mineflayer')\n\nif (process"
  },
  {
    "path": "examples/screenshot-with-node-canvas-webgl/.dockerignore",
    "chars": 24,
    "preview": "screenshots\nnode_modules"
  },
  {
    "path": "examples/screenshot-with-node-canvas-webgl/.npmrc",
    "chars": 38,
    "preview": "engine-strict=true\npackage-lock=false\n"
  },
  {
    "path": "examples/screenshot-with-node-canvas-webgl/Dockerfile",
    "chars": 428,
    "preview": "FROM node:14\n\nRUN apt-get update -y\nRUN apt-get install -y xserver-xorg-dev libxi-dev xserver-xorg-dev libxext-dev xvfb\n"
  },
  {
    "path": "examples/screenshot-with-node-canvas-webgl/README.md",
    "chars": 1284,
    "preview": "### node-canvas-webgl example\n\n#### screenshot.js\nGenerates Screenshots of the bot world\n\n### Starting\n\nLinux:\n\n`\nxvfb-r"
  },
  {
    "path": "examples/screenshot-with-node-canvas-webgl/package.json",
    "chars": 265,
    "preview": "{\n  \"name\": \"mineflayer-example\",\n  \"version\": \"0.0.0\",\n  \"private\": true,\n  \"dependencies\": {\n    \"prismarine-viewer\": "
  },
  {
    "path": "examples/screenshot-with-node-canvas-webgl/screenshot.js",
    "chars": 2779,
    "preview": "/*\n *\n * A simple a simple Screenshot demo for https://github.com/PrismarineJS/prismarine-viewer\n *\n */\n\nconst mineflaye"
  },
  {
    "path": "examples/session.js",
    "chars": 889,
    "preview": "// This example describes how to login using a launcher_profiles folder instead of a usual minecraft username & password"
  },
  {
    "path": "examples/skin_blinker.js",
    "chars": 928,
    "preview": "/*\n * Since 1.8 the players skin can have a second layer over their whole skin.\n *\n * This example will toggle that laye"
  },
  {
    "path": "examples/skin_data.js",
    "chars": 704,
    "preview": "/*\n * This script will automatically set if a totem is in the inventory or the off-hand.\n * It checks for a totem every "
  },
  {
    "path": "examples/sleeper.js",
    "chars": 1356,
    "preview": "/*\n * Even bots need to rest sometimes.\n *\n * That's why we created an example that demonstrates how easy it is\n * to fi"
  },
  {
    "path": "examples/sound.js",
    "chars": 1071,
    "preview": "const mineflayer = require('mineflayer')\n\nif (process.argv.length < 4 || process.argv.length > 6) {\n  console.log('Usage"
  },
  {
    "path": "examples/tab_complete.js",
    "chars": 821,
    "preview": "const mineflayer = require('mineflayer')\n\nif (process.argv.length < 4 || process.argv.length > 6) {\n  console.log('Usage"
  },
  {
    "path": "examples/telegram.js",
    "chars": 1467,
    "preview": "/*\n* This example is a very simple way of connecting to a telegram group\n* For this example you'll need Telegraf install"
  },
  {
    "path": "examples/titles.js",
    "chars": 1317,
    "preview": "/*\n * An example of how to handle title events from the server.\n * Demonstrates title, subtitle, timing, and clearing fu"
  },
  {
    "path": "examples/trader.js",
    "chars": 5593,
    "preview": "/*\n * Even bots want to trade sometimes.\n *\n * That's why we created an example that demonstrates how easy it is\n * to f"
  },
  {
    "path": "examples/viewer/.npmrc",
    "chars": 38,
    "preview": "engine-strict=true\npackage-lock=false\n"
  },
  {
    "path": "examples/viewer/README.md",
    "chars": 155,
    "preview": "[<img src=\"https://prismarinejs.github.io/prismarine-viewer/test_1.16.1.png\" alt=\"viewer\" width=\"800\">](https://prismari"
  },
  {
    "path": "examples/viewer/package.json",
    "chars": 208,
    "preview": "{\n  \"name\": \"mineflayer-example\",\n  \"version\": \"0.0.0\",\n  \"private\": true,\n  \"dependencies\": {\n    \"prismarine-viewer\": "
  },
  {
    "path": "examples/viewer/viewer.js",
    "chars": 700,
    "preview": "/*\n *\n * A simple bot demo https://github.com/PrismarineJS/prismarine-viewer\n * Start it then open your browser to http:"
  },
  {
    "path": "index.d.ts",
    "chars": 23013,
    "preview": "import { EventEmitter } from 'events'\nimport TypedEmitter from 'typed-emitter'\nimport { Client, ClientOptions } from 'mi"
  },
  {
    "path": "index.js",
    "chars": 368,
    "preview": "if (typeof process !== 'undefined' && !process.browser && process.platform !== 'browser' && parseInt(process.versions.no"
  },
  {
    "path": "lib/bossbar.js",
    "chars": 2361,
    "preview": "const colors = ['pink', 'blue', 'red', 'green', 'yellow', 'purple', 'white']\nconst divisions = [0, 6, 10, 12, 20]\n\nfunct"
  },
  {
    "path": "lib/conversions.js",
    "chars": 1256,
    "preview": "const { Vec3 } = require('vec3')\nconst math = require('./math')\nconst euclideanMod = math.euclideanMod\nconst PI = Math.P"
  },
  {
    "path": "lib/loader.js",
    "chars": 5541,
    "preview": "const mc = require('minecraft-protocol')\nconst { EventEmitter } = require('events')\nconst pluginLoader = require('./plug"
  },
  {
    "path": "lib/location.js",
    "chars": 576,
    "preview": "const { Vec3 } = require('vec3')\nconst CHUNK_SIZE = new Vec3(16, 16, 16)\n\nclass Location {\n  constructor (absoluteVector"
  },
  {
    "path": "lib/math.js",
    "chars": 258,
    "preview": "exports.clamp = function clamp (min, x, max) {\n  return Math.max(min, Math.min(x, max))\n}\n\nexports.euclideanMod = functi"
  },
  {
    "path": "lib/painting.js",
    "chars": 160,
    "preview": "function Painting (id, pos, name, direction) {\n  this.id = id\n  this.position = pos\n  this.name = name\n  this.direction "
  },
  {
    "path": "lib/particle.js",
    "chars": 1298,
    "preview": "const { Vec3 } = require('vec3')\n\nmodule.exports = loader\n\nfunction loader (registry) {\n  class Particle {\n    construct"
  },
  {
    "path": "lib/plugin_loader.js",
    "chars": 1193,
    "preview": "const assert = require('assert')\n\nmodule.exports = inject\n\nfunction inject (bot, options) {\n  let loaded = false\n  const"
  },
  {
    "path": "lib/plugins/anvil.js",
    "chars": 4057,
    "preview": "const assert = require('assert')\nconst { sleep } = require('../promise_utils')\nconst { once } = require('../promise_util"
  },
  {
    "path": "lib/plugins/bed.js",
    "chars": 6664,
    "preview": "const { Vec3 } = require('vec3')\n\nmodule.exports = inject\n\nconst CARDINAL_DIRECTIONS = ['south', 'west', 'north', 'east'"
  },
  {
    "path": "lib/plugins/block_actions.js",
    "chars": 4156,
    "preview": "const { Vec3 } = require('vec3')\n\nmodule.exports = inject\n\nconst CARDINALS = {\n  north: new Vec3(0, 0, -1),\n  south: new"
  },
  {
    "path": "lib/plugins/blocks.js",
    "chars": 21674,
    "preview": "const { Vec3 } = require('vec3')\nconst assert = require('assert')\nconst Painting = require('../painting')\nconst { onceWi"
  },
  {
    "path": "lib/plugins/book.js",
    "chars": 2995,
    "preview": "const assert = require('assert')\nconst { once } = require('../promise_utils')\n\nmodule.exports = inject\n\nfunction inject "
  },
  {
    "path": "lib/plugins/boss_bar.js",
    "chars": 1889,
    "preview": "module.exports = inject\n\nfunction inject (bot, { version }) {\n  const BossBar = require('../bossbar')(bot.registry)\n  co"
  },
  {
    "path": "lib/plugins/breath.js",
    "chars": 746,
    "preview": "module.exports = inject\r\n\r\nfunction inject (bot) {\r\n  if (bot.supportFeature('mcDataHasEntityMetadata')) {\r\n    // this "
  },
  {
    "path": "lib/plugins/chat.js",
    "chars": 7957,
    "preview": "const { onceWithCleanup } = require('../promise_utils')\n\nconst USERNAME_REGEX = '(?:\\\\(.{1,15}\\\\)|\\\\[.{1,15}\\\\]|.){0,5}?"
  },
  {
    "path": "lib/plugins/chest.js",
    "chars": 1878,
    "preview": "const { Vec3 } = require('vec3')\n\nmodule.exports = inject\n\nfunction inject (bot) {\n  const allowedWindowTypes = ['minecr"
  },
  {
    "path": "lib/plugins/command_block.js",
    "chars": 3286,
    "preview": "const assert = require('assert')\nconst { ProtoDef } = require('protodef')\n\nmodule.exports = inject\n\nfunction inject (bot"
  },
  {
    "path": "lib/plugins/craft.js",
    "chars": 7709,
    "preview": "const assert = require('assert')\nconst { once } = require('../promise_utils')\n\nmodule.exports = inject\n\nfunction inject "
  },
  {
    "path": "lib/plugins/creative.js",
    "chars": 3463,
    "preview": "const assert = require('assert')\nconst { Vec3 } = require('vec3')\nconst { sleep, onceWithCleanup } = require('../promise"
  },
  {
    "path": "lib/plugins/digging.js",
    "chars": 9613,
    "preview": "const { performance } = require('perf_hooks')\nconst { createDoneTask, createTask } = require('../promise_utils')\nconst B"
  },
  {
    "path": "lib/plugins/enchantment_table.js",
    "chars": 3151,
    "preview": "const assert = require('assert')\nconst { once } = require('../promise_utils')\n\nmodule.exports = inject\n\nfunction inject "
  },
  {
    "path": "lib/plugins/entities.js",
    "chars": 31803,
    "preview": "const { Vec3 } = require('vec3')\nconst conv = require('../conversions')\n// These values are only accurate for versions 1"
  },
  {
    "path": "lib/plugins/experience.js",
    "chars": 349,
    "preview": "module.exports = inject\n\nfunction inject (bot) {\n  bot.experience = {\n    level: null,\n    points: null,\n    progress: n"
  },
  {
    "path": "lib/plugins/explosion.js",
    "chars": 3181,
    "preview": "const { Vec3 } = require('vec3')\n\nmodule.exports = inject\n\n// https://minecraft.wiki/w/Explosion\nfunction calcExposure ("
  },
  {
    "path": "lib/plugins/fishing.js",
    "chars": 2106,
    "preview": "const { Vec3 } = require('vec3')\nconst { createDoneTask, createTask } = require('../promise_utils')\n\nmodule.exports = in"
  },
  {
    "path": "lib/plugins/furnace.js",
    "chars": 3525,
    "preview": "const assert = require('assert')\n\nmodule.exports = inject\n\nfunction inject (bot) {\n  const allowedWindowTypes = ['minecr"
  },
  {
    "path": "lib/plugins/game.js",
    "chars": 4923,
    "preview": "const nbt = require('prismarine-nbt')\nmodule.exports = inject\n\nconst difficultyNames = ['peaceful', 'easy', 'normal', 'h"
  },
  {
    "path": "lib/plugins/generic_place.js",
    "chars": 3272,
    "preview": "const assert = require('assert')\nmodule.exports = inject\n\nfunction inject (bot) {\n  const Item = require('prismarine-ite"
  },
  {
    "path": "lib/plugins/health.js",
    "chars": 946,
    "preview": "module.exports = inject\n\nfunction inject (bot, options) {\n  bot.isAlive = true\n\n  bot._client.on('respawn', (packet) => "
  },
  {
    "path": "lib/plugins/inventory.js",
    "chars": 24703,
    "preview": "const assert = require('assert')\nconst { Vec3 } = require('vec3')\nconst { once, sleep, createDoneTask, createTask, withT"
  },
  {
    "path": "lib/plugins/kick.js",
    "chars": 341,
    "preview": "module.exports = inject\n\nfunction inject (bot) {\n  bot._client.on('kick_disconnect', (packet) => {\n    bot.emit('kicked'"
  },
  {
    "path": "lib/plugins/particle.js",
    "chars": 231,
    "preview": "module.exports = inject\n\nfunction inject (bot, { version }) {\n  const Particle = require('../particle')(bot.registry)\n\n "
  },
  {
    "path": "lib/plugins/physics.js",
    "chars": 15892,
    "preview": "const { Vec3 } = require('vec3')\nconst assert = require('assert')\nconst math = require('../math')\nconst conv = require('"
  },
  {
    "path": "lib/plugins/place_block.js",
    "chars": 1421,
    "preview": "const { onceWithCleanup } = require('../promise_utils')\n\nmodule.exports = inject\n\nfunction inject (bot) {\n  async functi"
  },
  {
    "path": "lib/plugins/place_entity.js",
    "chars": 3503,
    "preview": "const assert = require('assert')\n\nmodule.exports = inject\n\nfunction inject (bot) {\n  const Item = require('prismarine-it"
  },
  {
    "path": "lib/plugins/rain.js",
    "chars": 974,
    "preview": "module.exports = inject\nconst states = ['no_respawn_block_available', 'start_raining', 'stop_raining', 'change_game_mode"
  },
  {
    "path": "lib/plugins/ray_trace.js",
    "chars": 2511,
    "preview": "const { Vec3 } = require('vec3')\nconst { RaycastIterator } = require('prismarine-world').iterators\n\nmodule.exports = (bo"
  },
  {
    "path": "lib/plugins/resource_pack.js",
    "chars": 2800,
    "preview": "const UUID = require('uuid-1345')\n\nmodule.exports = inject\n\nfunction inject (bot) {\n  let uuid\n  let latestHash\n  let la"
  },
  {
    "path": "lib/plugins/scoreboard.js",
    "chars": 2302,
    "preview": "module.exports = inject\n\nfunction inject (bot) {\n  const ScoreBoard = require('../scoreboard')(bot)\n  const scoreboards "
  },
  {
    "path": "lib/plugins/settings.js",
    "chars": 3067,
    "preview": "const assert = require('assert')\n\nmodule.exports = inject\n\nconst chatToBits = {\n  enabled: 0,\n  commandsOnly: 1,\n  disab"
  },
  {
    "path": "lib/plugins/simple_inventory.js",
    "chars": 4137,
    "preview": "const assert = require('assert')\n\nmodule.exports = inject\n\nconst QUICK_BAR_COUNT = 9\nconst QUICK_BAR_START = 36\n\nfunctio"
  },
  {
    "path": "lib/plugins/sound.js",
    "chars": 1775,
    "preview": "const { Vec3 } = require('vec3')\n\nmodule.exports = inject\n\nfunction inject (bot) {\n  bot._client.on('named_sound_effect'"
  },
  {
    "path": "lib/plugins/spawn_point.js",
    "chars": 354,
    "preview": "const { Vec3 } = require('vec3')\n\nmodule.exports = inject\n\nfunction inject (bot) {\n  bot.spawnPoint = new Vec3(0, 0, 0)\n"
  },
  {
    "path": "lib/plugins/tablist.js",
    "chars": 914,
    "preview": "module.exports = inject\n\nconst escapeValueNewlines = str => {\n  return str.replace(/(\": *\"(?:\\\\\"|[^\"])+\")/g, (_, match) "
  },
  {
    "path": "lib/plugins/team.js",
    "chars": 2307,
    "preview": "module.exports = inject\n\n// TODO: apply this to all versions and rename scoreboard_team -> teams in minecraft-data\nconst"
  },
  {
    "path": "lib/plugins/time.js",
    "chars": 1142,
    "preview": "module.exports = inject\n\nfunction inject (bot) {\n  bot.time = {\n    doDaylightCycle: null,\n    bigTime: null,\n    time: "
  },
  {
    "path": "lib/plugins/title.js",
    "chars": 1692,
    "preview": "module.exports = inject\nfunction inject (bot) {\n  function parseTitle (text) {\n    try {\n      const parsed = JSON.parse"
  },
  {
    "path": "lib/plugins/villager.js",
    "chars": 8030,
    "preview": "const assert = require('assert')\nconst { once } = require('../promise_utils')\n\nmodule.exports = inject\n\nfunction inject "
  },
  {
    "path": "lib/promise_utils.js",
    "chars": 2868,
    "preview": "function sleep (ms) {\n  return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nfunction createTask () {\n  const task "
  },
  {
    "path": "lib/scoreboard.js",
    "chars": 1276,
    "preview": "const sortItems = (a, b) => {\n  if (a.value > b.value) return -1\n  if (a.value < b.value) return 1\n  return 1\n}\n\nmodule."
  },
  {
    "path": "lib/team.js",
    "chars": 2268,
    "preview": "function colorString (color) {\n  const formatting = [\n    'black',\n    'dark_blue',\n    'dark_green',\n    'dark_aqua',\n "
  },
  {
    "path": "lib/version.js",
    "chars": 445,
    "preview": "const testedVersions = ['1.8.8', '1.9.4', '1.10.2', '1.11.2', '1.12.2', '1.13.2', '1.14.4', '1.15.2', '1.16.5', '1.17.1'"
  },
  {
    "path": "package.json",
    "chars": 1519,
    "preview": "{\n  \"name\": \"mineflayer\",\n  \"version\": \"4.35.0\",\n  \"description\": \"create minecraft bots with a stable, high level API\","
  },
  {
    "path": "test/common/util.js",
    "chars": 290,
    "preview": "const net = require('net')\n\nconst getPort = () => new Promise(resolve => {\n  const server = net.createServer()\n  server."
  },
  {
    "path": "test/externalTest.js",
    "chars": 5303,
    "preview": "/* eslint-env mocha */\n\nconst assert = require('assert')\nconst mineflayer = require('../')\nconst commonTest = require('."
  },
  {
    "path": "test/externalTests/anvil.js",
    "chars": 5684,
    "preview": "const assert = require('assert')\nconst { once } = require('../../lib/promise_utils')\n\nmodule.exports = () => {\n  async f"
  },
  {
    "path": "test/externalTests/bed.js",
    "chars": 1642,
    "preview": "const assert = require('assert')\nconst { once } = require('../../lib/promise_utils')\n\nmodule.exports = () => async (bot)"
  },
  {
    "path": "test/externalTests/book.js",
    "chars": 1331,
    "preview": "const assert = require('assert')\n\nmodule.exports = () => async (bot) => {\n  const Item = require('prismarine-item')(bot."
  },
  {
    "path": "test/externalTests/bossBar.js",
    "chars": 2807,
    "preview": "const assert = require('assert')\nconst { once, onceWithCleanup } = require('../../lib/promise_utils')\n\nmodule.exports = "
  }
]

// ... and 39 more files (download for full content)

About this extraction

This page contains the full source code of the PrismarineJS/mineflayer GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 239 files (1.2 MB), approximately 361.4k tokens, and a symbol index with 322 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!