From d89e7b2f96bdf450cd3dfdb24d825eb89592db5c Mon Sep 17 00:00:00 2001 From: Hcat Date: Fri, 21 Jan 2022 00:25:20 +0800 Subject: [PATCH] Add and revise simplified Chinese language documents (#2374) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 翻译简体中文语言文件 * fix lint Co-authored-by: Romain Beaumont --- docs/zh/CONTRIBUTING.md | 93 ++ docs/zh/FAQ.md | 169 ++++ docs/zh/README_ZH_CN.md | 10 +- docs/zh/_sidebar.md | 9 + docs/zh/api.md | 2132 +++++++++++++++++++++++++++++++++++++++ docs/zh/demos.md | 18 + docs/zh/history.md | 914 +++++++++++++++++ docs/zh/index.html | 38 + docs/zh/tutorial.md | 718 +++++++++++++ 9 files changed, 4096 insertions(+), 5 deletions(-) create mode 100644 docs/zh/CONTRIBUTING.md create mode 100644 docs/zh/FAQ.md create mode 100644 docs/zh/_sidebar.md create mode 100644 docs/zh/api.md create mode 100644 docs/zh/demos.md create mode 100644 docs/zh/history.md create mode 100644 docs/zh/index.html create mode 100644 docs/zh/tutorial.md diff --git a/docs/zh/CONTRIBUTING.md b/docs/zh/CONTRIBUTING.md new file mode 100644 index 000000000..008976c81 --- /dev/null +++ b/docs/zh/CONTRIBUTING.md @@ -0,0 +1,93 @@ +# 贡献 + +Mineflayer 最初主要是由 [andrewrk](http://github.com/andrewrk) 制作的 +但自那以后,许多[贡献者](https://github.com/andrewrk/mineflayer/graphs/contributors)对其进行了改进和修复 +所以知道如何为mineflayer做出贡献的最佳方式很重要 + +## Issue organization + +我们有3个阶段标签来尝试组织Issue: + +* Stage 1: 只是由项目新手创建的,我们还不知道它是否值得实现/修复 +* Stage 2: 有希望的想法,但在实施前需要更多思考 +* Stage 3: 想法被精确地指定了,就剩写代码了 + +链接如 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 + +## 创建测试 +Mineflayer 有两种测试 : + + * [internal tests](test/internalTest.js) : 针对使用node-minecraft-protocol创建的简单服务器进行的测试 + * [external tests](test/externalTests/) : 针对原版服务器进行的测试 + +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. + +### 创建外部测试 + +In order to add an external test now you only need to create a file in [test/externalTests](test/externalTests) + +一个例子 : [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. + + +## 创建第三方插件 +Mineflayer 是可扩展的插件化的; 任何人都可以创建一个插件,在 Mineflayer 之上添加更高级别的 API。 + +已经开发了几个这样的第三方插件 [查看](https://github.com/andrewrk/mineflayer#third-party-plugins) + +为了创建一个新的,您需要 : + +1. 创建一个新的 repo +2. 在你的 index.js 文件中, 导出一个接受参数 mineflayer 的 init 函数 ([查看例子](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) + +参考 [全部示例](https://github.com/andrewrk/mineflayer-navigate/tree/e24cb6a868ce64ae43bea2d035832c15ed01d301) + +## 反馈Bug +Mineflayer 在大多数情况下都能很好地工作,但有时仍然存在bug. + +找到一个问题时,最好报告一个提供这些信息的问题 : + +* 你想做什么 (英语目标) +* 你尝试过什么 (代码) +* 发生了什么事 +* 你期望会发生什么 + +## Mineflayer 代码 +提交请求或提交提交时需要考虑的一些事情 : + +### 错误处理 +在大多数情况下,mineflayer不会让机器人崩溃。即使有些东西失败了,机器人也可以选择另一条路线来达到它的目标。 + +这意味着我们不应该使用 `throw(new Error("error"))` 而是使用node.js约定在回调中传递错误。 + +例如 : + +```js +function myfunction (param1, callback) { + // do stuff + let toDo = 1 + toDo = 2 + if (toDo === 2) { // 一切正常 + callback() + } else { + callback(new Error('什么东西出错了')) + } +} +``` + +请参考另一个例子 [mineflayer code](https://github.com/andrewrk/mineflayer/blob/a8736c4ea473cf1a609c5a29046c0cdad006d429/lib/plugins/bed.js#L10) + +### 更新文档 +docs/api.md 的内容是用doctoc制作的。更新该文件后,应运行 `doctoc docs/api.md` 以更新目录。 + +没有doctoc命令使用下面的命令安装 + +``` +npm install -g doctoc +``` diff --git a/docs/zh/FAQ.md b/docs/zh/FAQ.md new file mode 100644 index 000000000..da2f1ef92 --- /dev/null +++ b/docs/zh/FAQ.md @@ -0,0 +1,169 @@ +## FAQ + +本文档旨在帮助人们解决常见问题 + +### 如何隐藏报错 ? + +在createBot选项中使用`hideErrors:true` +您也可以选择添加这些监听事件: + +```js +client.on('error', () => {}) +client.on('end', () => {}) +``` + +### 我无法在自定义服务器上获取聊天事件,如何解决? + +Spigot 服务器, 特别是一些插件, 使用的是自定义聊天格式,您需要使用自定义正则表达式/解析器对其进行解析。 +阅读并改编[chat_parsing.js](https://github.com/PrismarineJS/mineflayer/blob/master/examples/chat_parsing.js)使其适用于您的特定聊天插件. 或者阅读 http://mineflayer.prismarine.js.org/#/tutorial?id=custom-chat + +### 如何用自定义插件在聊天中收集信息 ? + +大多数定制的Minecraft服务器都有插件支持,很多插件会在聊天中说一些事情. 如果只是一条信息, 最好使用上述解决方案中讨论的解决方案, 但是当这些消息被分成许多小消息时, 另一个选择是使用 `"messagestr"` 事件 因为它允许轻松解析多行消息. + +**例子:** + +聊天栏中的信息看起来像: +``` +(!) 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 = {} + } +}) +``` +### 如何发送命令 ? + +使用 `bot.chat()`. + +**例子:** + +```js +bot.chat('/give @p minecraft:diamond_sword') +``` + +### 是否可以使用bot = mineflayer.createbot登录多个帐户 同时分别控制它们 ? + +通过调用createBot创建不同的bot实例,然后为每个实例执行不同的操作,请参考 multiple.js + +### 如何让机器人丢出它的全部背包物品? + +bot.inventory.items() 返回机器人的物品数组. 您可以使用递归函数循环遍历它们,并使用 `bot.toss()`. [点这里](https://gist.github.com/dada513/3d88f772be4224b40f9e5d1787bd63e9) 查看例子 + +### 如何检查发送/接收的数据包 ? + +启用调试模式 https://github.com/PrismarineJS/mineflayer#debug + +### 我希望即使在服务器有延迟的情况下也能避免断开连接,如何实现这一点 ? + +一种方法是增加 [checkTimeoutInterval](https://github.com/PrismarineJS/node-minecraft-protocol/blob/master/docs/API.md#mccreateclientoptions) 选项的值(在createBot中设置) (例如 `300*1000` 这是5分钟,而不是默认的30秒). 如果仍然断开连接,可以使用类似于此示例的方法自动重新连接 https://github.com/PrismarineJS/mineflayer/blob/master/examples/reconnector.js + +### 如何获取物品的 lore / text? + +你可以使用 `item.nbt` 属性. 此外建议使用 `prismarine-nbt` 库. `nbt.simplify()` 方法可能有用 + +**例子:** + +```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 +} +``` + +### 如何从控制台发送消息到服务器? + +您可以使用类似`repl`的库来读取控制台输入的内容并用`bot.chat()`发送它。 你可以在这查看例子 [点这里](https://github.com/PrismarineJS/mineflayer/blob/master/examples/repl.js) + +### 创建插件时,如何将另一个插件指定为依赖项? + +在插件的`inject()`函数中,您可以安全地调用`bot.loadPlugin(anotherPlugin)`确保已加载该插件。如果插件之前已经加载,则不会发生任何事情。 + +请注意,加载插件的顺序是动态的, 因此,永远不要在`inject()`函数中调用其他插件. + +### 如何使用socks5代理? + +在对象的选项中 `mineflayer.createBot(options)`,从选项对象中删除你的 `host` 选项,声明以下变量 `PROXY_IP, PROXY_PORT, PROXY_USERNAME, PROXY_PASSWORD, MC_SERVER_IP, MC_SERVER_PORT` 并将其添加到选项对象中: +```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') + }) +} +``` + `socks` 用 `const socks = require('socks').SocksClient` 声明 使用的是[这个](https://www.npmjs.com/package/socks) 包. + +# 常见错误 + +### `UnhandledPromiseRejectionWarning: Error: Failed to read asymmetric key` + +当你给 mineflayer 设定了错误的服务器版本,或者 mineflayer 检测到错误的服务器版本时会发生这种情况 + +### `TypeError: Cannot read property '?' of undefined` + +您可能正在尝试在 bot 对象上使用尚不存在的内容,请尝试在 `spawn` 事件之后调用该语句 + +### `SyntaxError: Unexpected token '?'` + +更新node版本 + +### The bot can't break/place blocks or open chests + +检查出生点保护是否阻止了机器人的操作 + diff --git a/docs/zh/README_ZH_CN.md b/docs/zh/README_ZH_CN.md index 3a4ee8f79..35b3aeb2d 100644 --- a/docs/zh/README_ZH_CN.md +++ b/docs/zh/README_ZH_CN.md @@ -19,7 +19,7 @@ ## 特点 -* 支持版本:Minecraft 1.8, 1.9, 1.10, 1.11, 1.12, 1.13, 1.14, 1.15 and 1.16 +* 支持版本:Minecraft 1.8, 1.9, 1.10, 1.11, 1.12, 1.13, 1.14, 1.15 1.16 1.17 * 实体感知与追踪 * 方块感知,你可以在几毫秒内查找到bot周围的任何方块 * 物理和运动引擎 - 支持所有的碰撞箱 @@ -31,9 +31,9 @@ * 激活方块和使用物品 * 输入输出聊天信息 -### 路标 +### 路线图 -点击这个页面,看看目前我们有哪些 [实用项目](https://github.com/PrismarineJS/mineflayer/wiki/Big-Prismarine-projects). + [点这里](https://github.com/PrismarineJS/mineflayer/wiki/Big-Prismarine-projects) 看看目前我们有哪些实用的项目 ## 安装 @@ -85,8 +85,8 @@ const bot = mineflayer.createBot({ username: 'email@example.com', // minecraft 用户名 password: '12345678' // minecraft 密码, 如果你玩的是不需要正版验证的服务器,请注释掉。 // port: 25565, // 默认使用25565,如果你的服务器端口不是这个请取消注释并填写。 - // version: false, // 当你需要指定使用一个版本或快照时,请取消注释并手动填写(如:"1.8.9 " 或 "1.16.5"),否则会自动设置。 - // auth: 'mojang' // 当你需要使用微软账号登录时,请取消注释,然后将值设置为 'microsoft',否则会自动设置为 'mojang'。 + // version: false, // 如果需要指定使用一个版本或快照时,请取消注释并手动填写(如:"1.8.9 " 或 "1.16.5"),否则会自动设置。 + // auth: 'mojang' // 如果需要使用微软账号登录时,请取消注释,然后将值设置为 'microsoft',否则会自动设置为 'mojang'。 }) bot.on('chat', (username, message) => { diff --git a/docs/zh/_sidebar.md b/docs/zh/_sidebar.md new file mode 100644 index 000000000..5a1c2507a --- /dev/null +++ b/docs/zh/_sidebar.md @@ -0,0 +1,9 @@ +- 入门手册 + - [介绍](/) + - [API](api.md) + - [FAQ](FAQ.md) + - [演示](demos.md) + - [教程](tutorial.md) + - [不稳定的API](unstable_api.md) + - [贡献](CONTRIBUTING.md) + - [更新历史](history.md) \ No newline at end of file diff --git a/docs/zh/api.md b/docs/zh/api.md new file mode 100644 index 000000000..98376435d --- /dev/null +++ b/docs/zh/api.md @@ -0,0 +1,2132 @@ + + +**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) + - [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.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) + - [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.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.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 - 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.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.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)](#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) + - ["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) + - ["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) + - ["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) + - [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.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, 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.getExplosionDamages(entity, position, radius, [rawDamages])](#botgetexplosiondamagesentity-position-radius-rawdamages) + - [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, 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, [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) + + + +# 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 + +实体表示玩家、怪物和对象. + +它们在许多事件中被触发, 您可以使用 `bot.entity`.访问自己的实体 +见 [prismarine-entity](https://github.com/PrismarineJS/prismarine-entity) + +### Block + +See [prismarine-block](https://github.com/PrismarineJS/prismarine-block) + +Also `block.blockEntity` is additional field with block entity data as `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 + +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, [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + + * `itemType` - numerical item id + * `metadata` - numerical value. `null` means match anything. + * `count` - how many to deposit. `null` is an alias to 1. + * `callback(err)` - (optional) - called when done depositing + +#### window.withdraw(itemType, metadata, count, [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + + * `itemType` - numerical item id + * `metadata` - numerical value. `null` means match anything. + * `count` - how many to withdraw. `null` is an alias to 1. + * `callback(err)` - (optional) - called when done withdrawing + +#### window.close() + +### Recipe + +See [prismarine-recipe](https://github.com/PrismarineJS/prismarine-recipe) + +### mineflayer.Container + +Extends windows.Window for chests, dispensers, etc... +See `bot.openChest(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([callback]) + +This function also returns a `Promise`, with `item` as its argument upon completion. + + * `callback(err, item)` + +#### furnace.takeFuel([callback]) + +This function also returns a `Promise`, with `item` as its argument upon completion. + + * `callback(err, item)` + +#### furnace.takeOutput([callback]) + +This function also returns a `Promise`, with `item` as its argument upon completion. + + * `callback(err, item)` + +#### furnace.putInput(itemType, metadata, count, [cb]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +#### furnace.putFuel(itemType, metadata, count, [cb]) + +This function also 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, [callback]) + +This function also returns a `Promise`, with `item` as its argument upon completion. + + * `choice` - [0-2], the index of the enchantment you want to pick. + * `callback(err, item)` - (optional) called when the item has been enchanted + +#### enchantmentTable.takeTargetItem([callback]) + +This function also returns a `Promise`, with `item` as its argument upon completion. + + * `callback(err, item)` + +#### enchantmentTable.putTargetItem(item, [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + + * `callback(err)` + +#### enchantmentTable.putLapis(item, [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + + * `callback(err)` + +### mineflayer.anvil + +Extends windows.Window for anvils +See `bot.openAnvil(anvilBlock)`. + +#### anvil.combine(itemOne, itemTwo[, name, callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + + * `callback(err)` - in order to use callback, pass an empty string ('') for name + +#### anvil.combine(item[, name, callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + + * `callback(err)` + +#### 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], [cb]) +Is the same as [bot.trade(villagerInstance, tradeIndex, [times], [cb])](#bottradevillagerinstance-tradeindex-times-cb) + +### mineflayer.ScoreBoard + +#### ScoreBoard.name + +记分牌的名称 + +#### ScoreBoard.title + +记分牌的标题 (does not always equal the name) + +#### ScoreBoard.itemsMap + +记分板中包含所有项目的对象 +```js +{ + wvffle: { name: 'wvffle', value: 3 }, + dzikoysk: { name: 'dzikoysk', value: 6 } +} +``` + +#### ScoreBoard.items + +记分板中包含所有已排序项的数组 +```js +[ + { name: 'dzikoysk', value: 6 }, + { name: 'wvffle', value: 3 } +] +``` + +### mineflayer.Team + +#### Team.name + +队伍名称 + +#### Team.friendlyFire + +#### Team.nameTagVisibility + +`always`, `hideForOtherTeams`, `hideForOwnTeam` 其中一个 + +#### Team.collisionRule + + `always`, `pushOtherTeams`, `pushOwnTeam ` 其中一个 + +#### Team.color + +Color (or formatting) name of team, 如 `dark_green`, `red`, `underlined` + +#### Team.prefix + +一个聊天组件,包含队伍前缀 + +#### Team.suffix + +一个聊天组件,包含队伍后缀 + +#### Team.members + +Array of team members. Usernames for players and UUIDs for other entities. + +### mineflayer.BossBar + +#### BossBar.title + +boss 栏标题, ChatMessage 有例子 + +#### BossBar.health + +boss 生命百分比, 从`0` 到`1` + +#### BossBar.dividers + +Number of boss bar dividers, one of `0`, `6`, `10`, `12`, `20` + +#### BossBar.entityUUID + +Boss 栏实体 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, `pink`, `blue`, `red`, `green`, `yellow`, `purple`, `white `之中的一个 + +## Bot + +### mineflayer.createBot(options) + +创建并返回bot类的实例。 +`options` 是包含可选属性的对象 : + + * username : 用户名,默认为 'Player' + * port : 端口,默认为 25565 + * password : 可以省略 (如果token也被省略,那么它将尝试以离线模式连接) + * host : 默认为 localhost + * version : 默认为自动猜测服务器的版本。值示例:“1.12.2” + * auth : 默认为“mojang”,也可以是“microsoft” + * clientToken : 如果给定密码,则生成 + * accessToken : 如果给定密码,则生成 + * logErrors : 默认情况下为true,捕获错误并记录它们 + * hideErrors : 默认情况下为true,不记录错误(即使logErrors为true) + * keepAlive : 发送保持活动的数据包:默认为true + * checkTimeoutInterval : 默认 `30*1000` (30s), 检查是否在此期间收到keepalive,否则断开连接。 + * loadInternalPlugins : 默认为true + * storageBuilder : 可选功能,将version和worldName作为参数,并返回与prismarine-provider-anvil具有相同API的某个对象的实例 ,将被用来保存世界 + * client : node-minecraft-protocol 实例, 如果未指定,mineflayer将创建自己的客户端.这可用于通过许多客户端的代理或普通客户端和mineflayer客户端来启用mineflayer + * plugins : object : 默认为{} + - pluginName : false : don't load internal plugin with given name ie. `pluginName` + - pluginName : true : load internal plugin with given name ie. `pluginName` 即使loadInternalplugins设置为false + - pluginName : 外部插件注入函数: 加载外部插件, overrides internal plugin with given name ie. `pluginName` + * physicsEnabled : 默认为true, 机器人应该受到物理的影响吗? 以后可以通过 bot.physicsEnabled 修改 + * [chat](#bot.settings.chat) + * [colorsEnabled](#bot.settings.colorsEnabled) + * [viewDistance](#bot.settings.viewDistance) + * [difficulty](#bot.settings.difficulty) + * [skinParts](#bot.settings.skinParts) + * chatLengthLimit : 单个消息中可以发送的最大字符数. 如果没有设置, 那么游戏版本在 < 1.11 为100 在 >= 1.11 为256 + * defaultChatPatterns: 默认为true, 设置为false不添加聊天和私信等模式 + +### Properties + +#### bot.world + +A sync representation of the world. 查看以下位置的文档: http://github.com/PrismarineJS/prismarine-world + +##### world "blockUpdate" (oldBlock, newBlock) + +当方块更新时触发. Both `oldBlock` and `newBlock` provided for +comparison. + +注意 `oldBlock` 可能是 `null`. + +##### world "blockUpdate:(x, y, z)" (oldBlock, newBlock) + +Fires for a specific point. Both `oldBlock` and `newBlock` provided for +comparison. + +注意: `oldBlock` 可能为 `null` + + +#### bot.entity + +Bot自己的实体. 见 `Entity`. + +#### bot.entities + +所有附近的实体。 This object is a map of entityId to entity. + +#### bot.username + +机器人自己的名字 + +#### bot.spawnPoint + +到主出生点的坐标, 所有指南针指向的地方。 + +#### bot.heldItem + +机器人手中的物品, represented as a [prismarine-item](https://github.com/PrismarineJS/prismarine-item) instance specified with arbitrary metadata, nbtdata, etc. + +#### bot.usingHeldItem + +机器人是否正在使用其持有的物品,例如吃食物或使用盾牌。 + +#### bot.game.levelType + +#### bot.game.dimension + +#### bot.game.difficulty + +#### bot.game.gameMode + +#### bot.game.hardcore + +#### bot.game.maxPlayers + +#### bot.game.serverBrand + +### bot.physicsEnabled + +启用物理,默认为true。 + +### bot.player + +机器人的玩家对象 +```js +{ + username: 'player', + displayName: { toString: Function }, // ChatMessage object. + gamemode: 0, + ping: 28, + entity: entity // 如果距离太远,则为空 +} +``` + +一个玩家的ping值从0开始,您可能需要等待服务器发送实际的ping + +#### bot.players + +Map of username to people playing the game. + +#### bot.isRaining + +#### bot.rainState + +指示当前降雨量的数字。不下雨的时候,这个 +将等于0。 当开始下雨时,该值将增加 +逐渐上升到1。当雨停时,该值逐渐减小回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 + +选项: + + * `enabled` (默认) + * `commandsOnly` + * `disabled` + +#### bot.settings.colorsEnabled + +默认为true,无论您是否从服务器接收聊天中的颜色代码。 + +#### bot.settings.viewDistance + +选项: + * `far` (默认) + * `normal` + * `short` + * `tiny` + +#### bot.settings.difficulty + +Same as from server.properties. + +#### bot.settings.skinParts + +这些boolean设置控制玩家皮肤上的额外皮肤细节是否可见 + +##### bot.settings.skinParts.showCape - boolean + +如果您有披风,可以将其设置为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.experience.level + +#### bot.experience.points + +总经验点数 + +#### bot.experience.progress + +Between 0 and 1 - amount to get to the next level. + +#### bot.health + +[0,20]范围内的数字,表示半颗心的数量。 + +#### bot.food + + [0, 20] 范围内的数字,表示半个鸡腿的数量。 + +#### 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] respresenting the number of water-icons known as oxygen level. + +#### bot.physics + +编辑这些数字以调整重力、跳跃速度、终点速度等。 +这样做的风险由你自己承担。 + +#### 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 + +一天中的时间,单位为Tick + +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 + +世界中的一天 + +#### bot.time.isDay + +Whether it is day or not. + +Based on whether the current time of day is between 13000 and 23000 ticks. + +#### bot.time.moonPhase + +月相 + +0-7,其中0表示满月 + +#### bot.time.bigAge + +世界的年龄以tick为单位 + +此值为BigInt类型,即使在非常大的值下也准确。 (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 + +选择了哪个物品栏位 (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://wiki.vg/Protocol#Display_Scoreboard) + +#### bot.teams + +机器人已知的所有队伍 + +#### 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) + +仅在玩家公开聊天时触发 + + * `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) + +仅当玩家私下与您聊天时触发 + + * `username` - 谁发的消息 + * `message` - 去除所有颜色和控制字符 + * `translate` - 聊天信息类型. 大多数bukkit聊天信息为空 + * `jsonMsg` - 来自服务器的未修改的JSON消息 + * `matches` - 返回从正则表达式的匹配项数组。可能为空 + +#### "actionBar" (jsonMsg) + +Emitted for every server message which appears on the Action Bar. + + * `jsonMsg` - 来自服务器的未修改的JSON消息 + +#### "message" (jsonMsg, position) + +Emitted for every server message, including chats. + + * `jsonMsg` - unmodified JSON message from the server + + * `position` - (>= 1.8.1): 聊天信息的position可以是 + * chat + * system + * game_info + +#### "messagestr" (message, messagePosition, jsonMsg) + +`message`事件的别名,但它调用消息对象上的toString(),以在发出前获取消息的字符串。 + +#### "inject_allowed" +加载索引文件后触发,您可以在此处加载mcData和插件,但最好等待`spawn`事件。 + +#### "login" + +成功登录到服务器后触发。 +在做任何事情之前 您可能要等待"spawn"事件。 + +#### "spawn" + +在您首次登录和出生后触发一次然后在你死后重生时触发。 + +这通常是您想要监听的事件在服务器上执行任何操作之前. + +#### "respawn" + +在改变维度时和出生之前触发。 +一般忽略此事件并等待"spawn"事件。 + +#### "game" + +服务器更改任何游戏属性时触发。 + +#### "resourcePack" (url, hash) + +当服务器发送资源包时触发 + +#### "title" + +当服务器发送标题时触发 + + * `text` - 标题文本 + +#### "rain" + +开始或停止下雨时触发. 如果你加入已在下雨的服务器上,将触发此事件。 + +#### "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" + +当服务器发送时间更新时触发. 见 `bot.time` + +#### "kicked" (reason, loggedIn) + +当bot从服务器被踢出时触发 + + `reason`是一条解释你被踢的原因的聊天信息. + +`loggedIn` + 如果客户端在成功登录后被踢出则为`true` +如果kick发生在登录阶段则为 `false` + +#### "end" (reason) + +当您不再连接到服务器时触发 +`reason` 是一个字符串,用于解释客户端断开连接的原因。 (默认为 'socketClosed') + +#### "error" (err) + +发生错误时触发 + +#### "spawnReset" + +当你不能在床上出生并且出生点重置时触发 + +#### "death" + +当你死亡时触发 + +#### "health" + +当你的血量或饥饿发生变化时触发 + +#### "breath" + +当你的氧气水平改变时触发 + +#### "entityAttributes" (entity) + +当实体的属性更改时触发 + +#### "entitySwingArm" (entity) +#### "entityHurt" (entity) + +实体被攻击(指被攻击不是受到伤害 + +#### "entityDead" (entity) +#### "entityTaming" (entity) +#### "entityTamed" (entity) +#### "entityShakingOffWater" (entity) +#### "entityEatingGrass" (entity) + +实体吃草 + +#### "entityWake" (entity) + +实体睡醒 + +#### "entityEat" (entity) + +实体进食 + +#### "entityCriticalEffect" (entity) + +实体暴击效果 + +#### "entityMagicCriticalEffect" (entity) +#### "entityCrouch" (entity) +#### "entityUncrouch" (entity) +#### "entityEquip" (entity) +#### "entitySleep" (entity) +#### "entitySpawn" (entity) +#### "itemDrop" (entity) +#### "playerCollect" (collector, collected) + +某实体拾取一个物品 + + * `collector` - 拾取物品的实体 + * `collected` - 地面上的物品所在的实体 + +#### "entityGone" (entity) +#### "entityMoved" (entity) + +已移动的实体 + +#### "entityDetach" (entity, vehicle) +#### "entityAttach" (entity, vehicle) + +实体乘骑在交通工具上, 例如矿车和船 + + * `entity` - 搭便车的实体 + * `vehicle` - 作为车辆的实体 + +#### "entityUpdate" (entity) +#### "entityEffect" (entity, effect) + +实体获得buff效果 + +#### "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. + +注意: `oldBlock` 可能为 `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. + +注意: `oldBlock` 可能为 `null` + +#### "blockPlaced" (oldBlock, newBlock) + +当机器人放置方块时触发. Both `oldBlock` and `newBlock` provided for +comparison. + +注意: `oldBlock` 可能为 `null` + +#### "chunkColumnLoad" (point) +#### "chunkColumnUnload" (point) + +当区块已更新时触发. `point` is the coordinates to the corner of the chunk with the smallest x, y, and z values. + +#### "soundEffectHeard" (soundName, position, volume, pitch) + +当客户端听到指定的音效时触发 + + * `soundName`: 音效名称 + * `position`: Vec3 实例,声音从哪里发出(译者注:vec3即 x,y,z坐标 + * `volume`: 浮点数音量, 1.0 为100% + * `pitch`: 整数音高,63为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) + +当一个音符块在某处响起时触发 + + * `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://www.minecraftwiki.net/wiki/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) + +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) + +#### "blockBreakProgressEnd" (block) + +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 + +#### "diggingCompleted" (block) + + * `block` - 方块不再存在 + +#### "diggingAborted" (block) + + * `block` - 方块仍然存在 + +#### "move" + +当机器人移动时触发. 如果需要当前位置,请使用 +`bot.entity.position` 对于正常移动,如果您想要上一个位置,请使用 +`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" + +乘骑实体(如矿车)时触发 + +要访问实体,请使用 `bot.vehicle`. + +要乘骑实体, 请使用 `mount`. + +#### "dismount" (vehicle) + +实体从坐骑上下马时触发 + +#### "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" + +睡觉时触发 + +#### "wake" + +当你醒来的时候触发 + +#### "experience" + +当 `bot.experience.*` 经验点数变化时触发 + +#### "scoreboardCreated" (scoreboard) + +记分牌被添加时触发 + +#### "scoreboardDeleted" (scoreboard) + +记分板被删除时触发 + +#### "scoreboardTitleChanged" (scoreboard) + +当记分牌标题更新时触发 + +#### "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) + +添加队伍时触发 + +#### "teamRemoved" (team) + +队伍被移除触发 + +#### "teamUpdated" (team) + +更新队伍触发 + +#### "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) + +新boss栏创建时触发 + +#### "bossBarDeleted" (bossBar) + +新boss栏删除时激发。 + +#### "bossBarUpdated" (bossBar) + +更新新boss栏时触发 + +#### "heldItemChanged" (heldItem) + +手持物品变动时触发 + +#### "physicsTick" () + +如果 bot.physicsEnabled 设为true则每tick触发一次 + +#### "chat:name" (matches) + +Fires when the all of a chat pattern's regexs have matches + +### 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 informations about signs, paintings and block entities (slower). +See `Block`. + +#### bot.waitForChunksToLoad(cb) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +The cb gets called 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.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 aproach + - **function** - Creates two stage maching, 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 wether 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. + +示例: +```js +const cow = bot.nearestEntity(entity => entity.name.toLowerCase() === 'cow') // 我们使用 .toLowercase() 因为在1.8版本中,cow是大写的,这样可以适用于新版本 +``` + +### 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, cb, [assumeCommand], [sendBlockInSight]) + +This function also returns a `Promise`, with `matches` as its argument upon completion. + +Requests chat completion from the server. + * `str` - String to complete. + * `callback(matches)` + - `matches` - Array of matching strings. + * `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. + +#### 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 ". 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 recieved +* `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 compatability, likely to be removed + +returns a number which can be used with bot.removeChatPattern() to only delete this pattern + +#### bot.addChatPatternSet(name, patterns, chatPatternOptions) + +make an event that is called every time all patterns havee 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 recieved +* `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 + +#### 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(' hello world') // resolves on "hello world" in chat by flatbot + await bot.awaitMessage([' hello', ' world']) // resolves on "hello" or "world" in chat by flatbot + await bot.awaitMessage([' hello', ' world'], [' im', ' batman']) // resolves on "hello" or "world" or "im" or "batman" in chat by flatbot + await bot.awaitMessage(' hello', ' world') // resolves on "hello" or "world" in chat by flatbot + await bot.awaitMessage(/ (.+)/) // 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, [cb]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +Sleep in a bed. `bedBlock` should be a `Block` instance which is a bed. `cb` can have an err parameter if the bot cannot sleep. + +#### bot.isABed(bedBlock) + +Return true if `bedBlock` is a bed + +#### bot.wake([cb]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +Get out of bed. `cb` can have an err parameter if the bot cannot wake up. + +#### 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], [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + + * `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` + * `callback()` optional, called when you are looking at `point` + +#### bot.look(yaw, pitch, [force], [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +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. + * `callback()` optional, called when you are looking at `yaw` and `pitch` + +#### bot.updateSign(block, text) + +Changes the text on the sign. + +#### bot.equip(item, destination, [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +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 + * `callback(error)` - optional. called when you have successfully equipped + the item or when you learn that you have failed to equip the item. + +#### bot.unequip(destination, [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +Remove an article of equipment. + +#### bot.tossStack(item, [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + + * `item` - the stack of items you wish to toss + * `callback(error)` - optional, called when tossing is done. if error is + truthy, you were not able to complete the toss. + +#### bot.toss(itemType, metadata, count, [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + + * `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`. + * `callback(err)` - (optional) called once tossing is complete + +#### bot.dig(block, [forceLook = true], [digFace], [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +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 it's 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. + * `callback(err)` - (optional) called when the block is broken or you + are interrupted. + +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, cb) + +This function also returns a `Promise`, with `void` as its argument upon completion. + + * `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. + * `cb` will be called when the server confirms that the block has indeed been placed + +The new block will be placed at `referenceBlock.position.plus(faceVector)`. + +#### bot.placeEntity(referenceBlock, faceVector) + +This function also 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, [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +Punch a note block, open a door, etc. + + * `block` - the block to activate + * `callback(err)` - (optional) called when the block has been activated + +#### bot.activateEntity(entity, [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +Activate an entity, useful for villager for example. + + * `entity` - the entity to activate + * `callback(err)` - (optional) called when the entity has been activated + +#### bot.activateEntityAt(entity, position, [callback]) + +This function also 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 + * `callback(err)` - (optional) called when the entity has been activated + +#### bot.consume(callback) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +Eat / drink currently held item + + * `callback(error)` - called when consume ends + +#### bot.fish(callback) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +Use fishing rod + + * `callback(error)` - called when fishing ends + +#### bot.activateItem(offHand=false) + +Activates the currently held item. This is how you eat, shoot bows, throw an egg, 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 `true`. If false the bot does not swing is arm when attacking. + +#### bot.swingArm([hand], showHand) + +Play an arm swing animation. + + * `hand` can take `left` or `right` which is 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, [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + + * `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. + * `callback` - (optional) Called when the crafting is complete and your + inventory is updated. + +#### bot.writeBook(slot, pages, [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + + * `slot` is in inventory window coordinates (where 36 is the first quickbar slot, etc.). + * `pages` is an array of strings represents the pages. + * `callback(error)` - optional. called when the writing was successfully or an error occurred. + +#### bot.openContainer(containerBlock or containerEntity) + +Returns a promise on a `Container` instance which represents the container you are opening. + +#### bot.openChest(chestBlock or minecartchestEntity) + +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], [cb]) + +This function also 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. + +### 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, cb) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +Click on the current window. See details at https://wiki.vg/Protocol#Click_Window + +#### bot.putSelectedItemRange(start, end, window, slot) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +Put the item at `slot` in the specified range. + +#### bot.putAway(slot) + +This function also 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, cb) + +This function also 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` : the window where the item will be moved + * `itemType` : the type of the moved items + * `metadata` : the metadata of the moved items + * `sourceStart` and `sourceEnd` : the source range + * `destStart` and `destEnd` : the dest Range + * `count` : the amount of items to transfer. Default: `1` + * `nbt` : nbt data of the item to transfer. Default: `nullish` (ignores nbt) + +#### bot.openBlock(block) + +Open a block, for example a chest, returns a promise on the opening `Window`. + + * `block` is the block the bot will open + +#### 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, cb) + +This function also 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, [callback]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +Gives the bot the specified item in the specified inventory slot. +If called twice on the same slot before first callback exceeds, first callback will have an error parameter + + * `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. + * `callback(err)` (optional) is a callback which gets fired when the servers sets the slot + +If this method changes anything, you can be notified via `bot.inventory.on("updateSlot")`. + +#### bot.creative.flyTo(destination, [cb]) + +This function also returns a `Promise`, with `void` as its argument upon completion. + +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. + +When the bot arrives at the destination, `cb` is called. + +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 it's original value. diff --git a/docs/zh/demos.md b/docs/zh/demos.md new file mode 100644 index 000000000..b1054354f --- /dev/null +++ b/docs/zh/demos.md @@ -0,0 +1,18 @@ +## mineflayer-navigate + +[navigate](https://github.com/andrewrk/mineflayer-navigate/) - 轻松使用A*寻路 + + + +## rbot + +[rom1504/rbot](https://github.com/rom1504/rbot) 基于mineflayer的智能机器人 + + + +## chaoscraft + +[Chaoscraft](https://github.com/schematical/chaoscraft) 基于genetic算法的Minecraft机器人 + + + \ No newline at end of file diff --git a/docs/zh/history.md b/docs/zh/history.md new file mode 100644 index 000000000..0c27171b6 --- /dev/null +++ b/docs/zh/history.md @@ -0,0 +1,914 @@ +## 3.14.0 + +* Make prismarine-entity versioned (@u9g) +* fix(typings): Added OpenContainer (@SaubereSache) + +## 3.13.1 + +* Fix bug with force lastSentPitch in bot.look (@KadaverBrutalo10) +* Fix typo harming type safety (@Eagle-Anne) + +## 3.13.0 + +* 动态计算记分板显示名称displayName (@U9G) +* 修复 SkinsRestorer(@U5B) +* 修复机器人放置方块时不摆臂 (@IceTank) + +## 3.12.0 + +* Bypass anticheats that detect sensitivity (@mat-1) +* 修复了一次从tab列表中删除多个玩家的问题 (@mat-1) +* Added blockAtEntityCursor function (@DatArnoGuy) +* add option to disable default chat patterns (@U5B) +* Fixed wrong arm swinging (@IceTank) +* Add pitch speed to look (@IceTank) +* 修复控制台垃圾信息 (@IceTank) +* Update openVillager function to return a promise (@amoraschi) +* Send arm_animation before use_entity (@aesthetic0001) +* Add reason for the end of a mineflayer bot (@U5B) +* added rejection of invalid transaction packets (anticheat fix) (@U5B) + +## 3.11.2 +* Remove unnecessary and buggy inventory check in place block (@Karang) +* Make all events allow async cb typings (@u9g) + +## 3.11.1 +* Get rid of nowaiting (@nickelpro) +* 更新readme文件 (@inthmafr) +* 修复打字相关(@link-discord, @IceTank, @u9g) + +## 3.11.0 +* 优化聊天, 装备和消耗错误 (@u9g) +* 增加 bot.usingHeldItem (@mat1) +* 支持 1.17.1 (主要工作是 @nickelpro 和 @u9g 完成的, 还有 @Archengius @extremeheat @imharvol @willocn @rom1504) + +## 3.10.0 +* 添加中文翻译 (@Nyaasu66) +* Fix bot.equip failing with off-hand (@IceTank) +* window.withdraw no longer will drop items if it takes too many items (@Zn10plays) +* No longer have to await ready for enchanting (@u9g) +* Remove polling, recursive calling, rechecks for bot.waitForChunksToLoad (@u9g) +* Add crystal placing example (@u9g) +* Fixes physicsEnabled check for knockback (@u9g) +* Default swingArm to left hand (@u9g) +* Add support for teams (@builder-247) +* Add missing bot.transfer documentation (@IceTank) + +## 3.9.0 +* Fix crash on blocks without registered blockId (@Furry) +* Move when hit by an explsion (@u9g) +* Add getExplosionDamages() function (@Karang) +* doc of get explosion (@link-discord) + +## 3.8.0 +* 改进 index.d.ts (@DrMoraschi) +* 增加资源包支持 (@kaffinpx) +* 修复 bot.dig 错误(@MoneyMakingTornado) +* Added timeout to #consume (@SeanmcCord) +* 增加资源包示例 (@u9g) +* 改进工作流程 (@u9g) +* Linted JS in md files (@u9g) +* Added bot oxygen Level management (@kaffinpx) +* Improved links (@satyamedh) +* Improved links (@AwesomestCode) +* Improved typing (@u9g) +* Refactored chat.js (@u9g) +* Expanded placeBlockWith Options to offhand (@aestetic) +* Added anvil test (@u9g) +* Added placeEntity() (@u9g) +* Improved oxygen typings (@DrMoraschi) +* Improved socket snippet (@iceTank) +* Improved placeEntity (@u9g) +* Renamed bot.quit to end (@u9g) +* Updated Spanish readme (@DrMoraschi) +* Added French Translations (@creeper09) +* Corrected java version in gitpod (@rom) +* Improved readme lint (@rom) +* Added container and dropper to allowWindowTypes (@IceTank) + + +## 3.7.0 +* Add bot.removeChatPattern() (@BlueBurgersTDD) +* Add events to typings (@DrMoraschi) +* Add TR translation (@KaffinPX) +* Create plugin example (@Zn10plays) +* Revise readme (@IceTank) +* Revise chat_parsing example comments (@U5B) +* Revise raycast example (@IceTank) +* allow passing nmpclient as an option in createbot (@u9g) +* Add bot.awaitMessage() (@u9g) +* Add modular example (@u9g) +* Fix bug with chat patterns (@u9g) +* Fix bug with game event (@u9g) + +## 3.6.0 +* add bot.addChatPattern() & bot.addChatPatternSet() & deprecate bot.chatAddPattern() (@U9G) + +## 3.5.0 +* Add common errors to FAQ (@U9G) +* Move mosts of index.js to lib/loader.js (@U9G) +* Improve packet_info handling (@Karang) +* Add getControlState function (@Camezza) + +## 3.4.0 +* fix once leak in placeBlock (@Karang) +* allow sleeping during rain/thunderstorms (@qrvd) +* Change transaction apology packet to match vanilla client (@FeldrinH) + +## 3.3.3 +* fix world switch leak + +## 3.3.2 +* 修复实体名称 + +## 3.3.1 +* 修复停止挖掘 (@Karang) + +## 3.3.0 +* 修复交易相关 (@validgem) +* 修复附魔相关 (@goncharovchik) +* fix newListener and removeListener stacking on world change (@U5B) +* 增加 'messagestr' 事件(@U9G) +* Add an option forceLook for place block similar to the digging one (@CyberPatrick) +* Can see block add intersect match (@sefirosweb) +* Add ability to use an anvil fully (@U9G) + +## 3.2.0 +* Fix position in getBlock() + +## 3.1.0 +* Fix typings of findBlock and findBlocks (@csorfab) +* place block improvements (@Karang) +* add face option to dig (@IceTank) +* trading fixes (@validgem) +* world events exposed by pworld (@u9g) +* fix wait for ticks and expose physicsEnabled (@Karang) + +## 3.0.0 +* added null or undefined check in inventory (@u9g) +* Removed broken use of "this" in physics.js (@TheDudeFromCI) +* Promisify testCommon (@ArcticZeroo) +* Fixed Bot not skipping end credits (@IceTank) +* BREAKING: Simplify windows API and promisify tests (@Karang) : several methods and events from window API were changed: + * Removed Chest, EnchantmentTable, Furnace, Dispenser and Villager classes (they all are Windows now) + * Dispensers are now handled by the same code as other containers, hopper too (they were missing) + * There is now only 2 events signaling a slot update ("updateSlot" and "updateSlot:slotId" of the Window class) (before there was: "setSlot", "setSlot:windowId", "windowUpdate", "updateSlot", on 3 different eventEmitter (and not all of them were working properly)) + * All windows (present and future) now have a withdraw and deposit function + +## 2.41.0 +* Fix Time type definition (@hivivo) +* Add face for block in sight result (@Karang) +* Fix skin restorer bug (@TheDudeFromCI) +* Improve enchantment table info (@Karang) +* 支持 1.16.5 (@rom1504) + +## 2.40.1 +* Fix for not handling negative numbers in time plugin (@Naomi) +* Fix typescript Bot definition (@rom1504) + +## 2.40.0 +* fix for dig ignore (@TheDudeFromCI) +* better calculation of digging range (@goncharovchik) +* emit death once (@extremeheat) +* add waitForTicks function (@TheDudeFromCI) +* add null check for sign text (@u9g) + +## 2.39.2 +* explicit node 14 support + +## 2.39.1 +* add null check in bot.dig (@rom1504) +* Fix deprecation warning for block in sight (@Karang) + +## 2.39.0 +* Add number support to bot.chat (@BlueBurgersTDD) +* Fixed && Improved blockFind function with useExtraInfo = true (@magicaltoast) +* Added option to allow the bot to keep it's head in place when mining. (@TheDudeFromCI) + +## 2.38.0 +* Add bot.game.serverBrand property (@Karang) +* set extraInfos to false in blockIsNotEmpty (@mat-1) +* make the ChatMessage.toAnsi:lang argument optional (@Antonio32A) +* Fixed message types (@TheDudeFromCI) +* by default hideErrors is now true (@rom1504) + +## 2.37.1 +* Optimize lookAt promise behavior (@ph0t0shop) + +## 2.37.0 +* Promisify villager & Trader (thanks @ph0t0shop) +* protect against action id going over 32767 (@rom1504) +* fix incorrect handling of username definition (@rom1504) + +## 2.36.0 +* all async method now both return promises and take a callback (thanks @ph0t0shop for this great improvement) + +## 2.35.0 +* Extra position packet after TP +* Add blockAtCursor +* Deprecate blockInSight +* TS typing fixes + +## 2.34.0 +* 支持 1.16.4 + +## 2.33.0 +* block_actions fix (thanks @SpikeThatMike) +* typescript fixes (thanks @TheDudeFromCI and @NotSugden) +* add uuid by objectUUID handling (thanks @Rob9315) +* fix bed packet (thanks @imharvol) +* better plugin handling (thanks @TheDudeFromCI) + +## 2.32.0 +* 支持 1.16.3 (感谢@GroobleDierne 和 @TheDudeFromCI) +* fix bug with entity width (thanks @TheDudeFromCI) +* Add ability to call openChest on shulker boxes (thanks @efunneko) + +## 2.31.0 +* Fix furnace and add tests (thanks @ImHarvol) +* Add offhand param to d.ts (thanks @TheDudeFromCI) +* Add hasAttackCooldown feature (thanks @TheDudeFromCI) +* Add type validation for bot.chat (thanks @BlueBurgersTDD) +* Add chat position to message event (thanks @larspapen) + +## 2.30.0 +* Add support for Barrel (#1344) (thanks @ImHarvol) +* Fix attack cooldown bug (thanks @TheDudeFromCI) +* Exposed getDestSlot (thanks @TheDudeFromCI) +* Simplify setCommandBlock arguments (thanks @ImHarvol) +* hide unknown transaction warning if hideErrors option is enabled + +## 2.29.1 +* fix findblock typescript def (thanks @TheDudeFromCI) +* fix setCommandBlock for recent versions (thanks @ImHarvol) + +## 2.29.0 +* Add hand parameter to activateItem (thanks @Karang) +* remove _chunkColumn from the api (bot.world should now be used) +* Handle MC|AdvCmd misspelling (thanks @ImHarvol) + +## 2.28.1 +* 修复 findBlocks (感谢 @Karang) + +## 2.28.0 +* 增加 nearestEntity function (感谢 @Karang) + +## 2.27.0 +* add heldItemChanged + +## 2.26.0 +* use and expose prismarine-world as bot.world +* add itemDrop event (thanks @ImHarvol) +* fix bot.fish callback (thanks @GroobleDierne) +* parse entity metadata for crouching (thanks @IdanHo) +* fix bot.time.day (thanks @Naomi-alt) +* improve find blocks options (thanks @Karang) + +## 2.25.0 +* emit chestLidMove (thanks @imharvol) +* add options for main hand selection (thanks @Colten-Covington) +* fix respawning columns issues (thanks @Karang) + +## 2.24.0 +* Fix getBlockAt when outside bounds +* Improve documentation and examples +* Add ability to change the skin parts of a bot (thanks @Naomi-alt) + +## 2.23.0 +* 1.16 support +* fix noteheard (thanks @Naomi-alt) + +## 2.22.1 +* better typedef (thanks @Konstantin) +* fix off by 1 error in findBlocks (thanks @Karang) +* physics.js look fix (thanks @thesourceoferror) +* fix chat message bracketing (thanks @Nurutomo) +* use prismarine-physics + +## 2.22.0 +* Improve digTime computation (thanks @Karang) +* expose blockEntity.raw (thanks @SiebeDW) +* improve typedef for find block options (thanks @TheDudeFromCI) + +## 2.21.0 +* don't log errors if hideErrors is true + +## 2.20.0 +* add extra infos option in find block + +## 2.19.2 +* fix ground up for 1.13->1.15 + +## 2.19.1 +* 修复 find block (感谢 @Karang) +* improve sign parsing (thanks @cookiedragon234) + +## 2.19.0 +* much faster findBlock (thanks @Karang) + +## 2.18.0 +* fix bugs in lookAt and setQuickBarSlot +* add auto_totem example (thanks @AlexProgrammerDE) +* improve blockAt speed + +## 2.17.0 +* physics engine refactor (thanks @Karang) +* mcdata update for better 1.14 and 1.15 support + +## 2.16.0 +* use protodef compiler (thanks @Karang) +* off-hand support (thanks @Karang) +* fix type definitions (thanks @dada513) + +## 2.15.0 +* fix transfer bugs (thanks @Karang) +* add typescript definitions (thanks @IdanHo) + +## 2.14.1 +* fix openVillager + +## 2.14.0 +* 1.15 support +* russian translation (thanks @shketov) + +## 2.13.0 +* 1.14 support : more tests, refactored pwindows, feature flags (thanks @Karang) +* Look at the center of the face when placing block +* improve bot.sleep : don't sleep if mob are present (thanks @ImHarvol) + +## 2.12.0 +* 1.13 support (thanks @Karang, @hornta, @SiebeDW) +* better fishing support (thanks @hutu13879513663) + +## 2.11.0 +* Expose columns & blockEntities (thanks @SiebeDW) +* Create discord.js (thanks @SiebeDW) +* change amount of slots based on version (thanks @IdanHo) +* Fix 'respawn' event (thanks @ImHarvol) +* Add callback to creative set block (thanks @wvffle) + +## 2.10.0 +Lot of fixes from @wvffle in this release : +* more checks when digging +* expose a bot.swingArgm() function +* better toString to chat message +* fix handling of empty signs +* correct handling of entity metadata change +And some others : +* new tps plugin by @SiebeDW +* correct handling of chunk unloading by @IdanHo + +## 2.9.6 +* fix logErrors option + +## 2.9.5 +* fix logErrors + +## 2.9.4 +* enable catching and logging of errors by default + +## 2.9.3 +* fix typo in variable name actionId + +## 2.9.2 +* improve pushback (thanks @Vap0r1ze) +* more robust handling of tablist (thanks @wvffle) +* ignore (with a warning) transaction without previous click + +## 2.9.1 +* improve boss bar +* add checks in scoreboard implementation + +## 2.9.0 + +* add universal chat patterns to support more chat plugins + +## 2.8.1 + +* fix error on scoreboard removal + +## 2.8.0 + +lot of new features from @wvffle : + +* support for block entities +* improved block bars support +* add block in sight +* fix scoreboard support +* add eating support +* add tab complete support +* add fishing support +* better sign text support +* repl example + +## 2.7.5 + +* improve basic find block a bit + +## 2.7.4 + +* start the bot alive in all cases +* correct run speed and use it to limit the speed properly (thanks @CheezBarger) +* emit error instead of throwing when loading a chunk (thanks @ArcticZeroo) + +## 2.7.3 + +* use docsify for docs + +## 2.7.2 + +* don't do anything if transaction.action < 0 (fix for some non-vanilla plugins) + +## 2.7.1 + +* include fixes from pchunk, protodef and mcdata + +## 2.7.0 + +* fix cannot jump repeatedly +* fix spaces in chatmessage (thanks @Gjum) +* add bot.getControlStates (thanks @ArcticZeroo) +* Support end dimension (thanks @iRath96) +* Added sneaking option to controll states (thanks @Meldiron) +* add title event (thanks @yario-o) +* Update sound.js to include hardcoded sound effects (thanks @jeresuikkila) +* Support for the new launcher_profiles.json format (thanks @Amezylst) +* update api about checkTimeoutInterval + +## 2.6.1 + +* fix chatmessage +* add plugins to bot options to be able to disable an internal plugin + +## 2.6.0 + +* improve ChatMessage translation functionality (thanks @plexigras) +* added eslint +* es6 +* fix autoversion in online mode + +## 2.5.0 + +* don't swing arm when activating an entity +* new plugin loading api + +## 2.4.1 + +* better 1.12 support + +## 2.4.0 + +* auto version detection (thanks @plexigras) + +## 2.3.0 + +* support version 1.12 (thanks @jonathanperret) +* add example to use minecraft session file for auth (thanks @plexigras) + +## 2.2.0 + +* added book writing plugin (thanks @plexigras) +* Make sure bot.time.day is between 0 and 24000 (thanks @roblabla) +* Pass skyLightSent to Chunk.load (thanks @iRath96) + +## 2.1.1 + +* use protodef aliases to properly define channels + +## 2.1.0 + +* add bot.canSeeBlock (thanks @Nixes) +* handle unknown entities and entities sent with their internal id +* add bloodhound to plugin list +* fix chat hoverEvent for 1.9 + +## 2.0.0 + +* added support for minecraft chests (thanks @plexigras) +* cross version support : 1.8, 1.9, 1.10 and 1.11 now supported +* [BREAKING] prismarine classes (Block, Entity, Recipe, ...) are now available only by requiring them, not in mineflayer.X. It was required to make cross version possible. minecraft-data is also to be required directly and not available as mineflayer.blocks. The code depending on this should be updated, hence the major version. + +## 1.8.0 + +* add actionBar event (thanks @ArcticZeroo) +* added support for villager trading (thanks @plexigras) + +## 1.7.5 + +* bump dependencies + +## 1.7.4 + +* update minecraft-data + +## 1.7.3 + +* add callback to activateBlock + +## 1.7.2 + +* update dependencies + +## 1.7.1 + + * update minecraft-protocol, minecraft-data and protodef + +## 1.7.0 + + * listen for disconnect in login phase (thanks @deathcap) + * fix multi_block_change (thanks @Corgano) + * remove chat filter : fix utf8 in chat + * add extra tolerance for malformed sign packets (thanks @G07cha) + * adapt to new minecraft data entities format + * update minecraft-protocol to 0.17.2 + + +## 1.6.0 + + * add functionalities to use scoreboard (thanks @jakibaki) + * update to minecraft-data 0.16.3 + * 50 -> 20 tps for physics + * Remove requireindex, for browserify support + * add bot.setCommandBlock + +## 1.5.3 + + * fix entity_status + +## 1.5.2 + + * use prismarine-recipe and prismarine-windows + * use require-self to be able to do require('mineflayer') in the examples + * fix viewDistance sending + +## 1.5.1 + + * add checkTimeoutInterval to createBot + +## 1.5.0 + + * fix achievements parsing in toString() + * update to nmp 0.16 + * use prismarine-item + * add example to run multiple bots + * uuid is now a dashed string + * remove digging interruption : this doesn't happen in 1.8 servers (and caused problem in some spigot servers) + +## 1.4.0 + + * improve placeBlock : now use lookAt before placing and has a callback + * fix soulsand speed + * use new multi-version version of (node-)minecraft-data + +## 1.3.0 + + * swing arm on placing a block, look at center of block when activating a block (thanks gipsy-king) + * refactor examples (thanks Pietro210) + * add clickWindow support to ContainerWindow (thanks Gnomesley) + * fix skylight in the nether + * update node-mojangson to display unparsed text in case of error + +## 1.2.1 + + * Prevent crash when an unknown entity is spawned + * add createBot to api.md + +## 1.2.0 + + * update minecraft-protocol to 0.14.0 : several fixes (error are now catchable, packets are in-order, packets fixes, etc.) + * add ContainerWindow to support non-Vanilla plugins and add /invsee example (thanks Pietro210) + * add a callback to bot.look and bot.lookAt + * when receiving a remove effect packet : if the corresponding effect doesn't exist yet, emit an event with just the id of the effect (thanks Pietro210) + * swing arm immediately when digging (thanks gipsy-king) + * now updates bot.entity.heldItem when bot.heldItem is updated + * fix cli args in examples + * add forcedMove event + * fix equipment api + * new minecraft data version : better metadata handling + +## 1.1.2 + + * a small fix in chat.js + * add a licence file + +## 1.1.1 + + * bot.transfer is faster + * fix arm_animation + * using mojangson parser for chat hoverevent + * add chat patterns for unidentified chat messages + * fix player leaving + +## 1.1.0 + +Lot of fixes and improvements in this version in order to support mineflayer 1.8.3, including : + + * minecraft 1.8.3 support + * update minecraft protocol to 0.13.4 + * move enums data to minecraft-data + * add automatic testing with a vanilla minecraft server on circle ci + * add argv arguments to examples + * refactor inventory.js + * use new recipe format handling metadata better + * fix lot of things to support 1.8.3 including : + * block format change + * position change : y is now always at the feet of the bot + +## 1.0.0 + + * updated minecraft protocol to 0.11 (Minecraft 1.6.2 support). + * small changes in the arguments of some events: `chat`, `whisper` and `message`. See [doc/api.md](https://github.com/andrewrk/mineflayer/blob/master/doc/api.md). + +## 0.1.1 + + * updated minecraft protocol to 0.10 (Minecraft 1.5.2 support). + +## 0.1.0 + +Huge thanks to [zuazo](https://github.com/zuazo) for debugging and +eliminating the problems with 1.5.1 protocol update and node 0.10 update! + + * update minecraft-protocol to 0.9.0 - includes many fixes + * blocks: fix buffer length assertion error (thanks zuazo) + * physics: fix assertion error (thanks zuazo) + +## 0.0.35 + + * inventory: window clicking waits a bit if you have just dug + fixes a rejected transaction race condition. + +## 0.0.34 + + * inventory: equipping makes the quick bar a basic LRU cache. + This can alleviate some race conditions when trying to equip a + different tool immediately after digging. + +## 0.0.33 + + * crafting: fix shapeless recipe support + * inventory: fix several instances which could cause transaction rejected + * add missing recipes (thanks rom1504) + * `recipe.delta` data structure changed. + +## 0.0.32 + + * digging: fix crash when not holding a tool + +## 0.0.31 + + * only stationary water has a negative effect on digging + * digging: if you dig while already digging, instead of crashing, + mineflayer will cancel the in progress dig and start the new one. + * digging: in creative mode dig time is 0 + * digging interruption error has a code so you can check for it + +## 0.0.30 + + * expose the materials enum as `mineflayer.materials` + +## 0.0.29 + + * digging is faster and has less bugs + * you can stop digging with `bot.stopDigging()`. + * `bot.dig(block, [timeout], [callback])` changed to `bot.dig(block, [callback])`. + * add `bot.digTime(block)` + * add `block.material` + * add `block.harvestTools` + * add `window.emptySlotCount()` + * block and item enums are cleaned up. Every block and item has an + unambiguous `name` and `displayName`. + +## 0.0.28 + + * add missing recipe for wooden planks + * fix various crafting and inventory bugs + * unequip works with hand as a destination + +## 0.0.27 + + * add `mineflayer.Location` which can help you locate chunk boundaries + * `entity.metadata` is formatted as an object instead of an array for + easier access + * `canDigBlock` returns `false` if `block` is `null` instead of crashing. + +## 0.0.26 + + * fix `bot.heldItem` being wrong sometimes + * water and lava are not solid + +## 0.0.25 + + * `bot.equip` - wait at least a tick before calling callback + +## 0.0.24 + + * fix digging leaves not calling callback. + +## 0.0.23 + + * add enchantment table support. See `examples/chest.js` for an example. + * rename `bot.tell` to `bot.whisper` to be consistent with 'whisper' event. + (thanks Darthfett) + +## 0.0.22 + + * update vec3 to 0.1.3 + * add "whisper" chat event + +## 0.0.21 + +This release is feature-complete with the old +[C++/Qt based version of mineflayer](https://github.com/andrewrk/mineflayer/blob/cpp-qt-end). + + * add `bot.activateItem()` + * add `bot.deactivateItem()` + * add `bot.useOn(targetEntity)` + +## 0.0.20 + + * add dispenser support + - add `mineflayer.Dispenser` + - add `bot.openDispenser(dispenserBlock)` + +## 0.0.19 + + * add furnace support + - add `mineflayer.Furnace` + - add `bot.openFurnace(furnaceBlock)` + * `mineflayer.Chest`: "update" event renamed to "updateSlot" + * `bot.equip(itemType, destination, [callback])` changed to + `bot.equip(item, destination, [callback])`. Use `bot.inventory.items()` + to get a list of what items you can choose from to equip. + * fix `bot.openChest` not working for ender chests + * fix incorrectly scaled fuel percentage + * upgrade to minecraft-protocol 0.7.0 + - `mineflayer.createBot` no longer takes a `email` argument. + - The `username` and `password` arguments are used to authenticate with the + official minecraft servers and determine the case-correct username. If + you have migrated your user account to a mojang login, `username` looks + like an email address. + - If you leave out the `password` argument, `username` is used to connect + directly to the server. In this case you will get kicked if the server is + in online mode. + +## 0.0.18 + + * fix crash for some block updates + +## 0.0.17 + +recalled + +## 0.0.16 + + * add chest support + - add `mineflayer.Chest` + - add `bot.openChest(chestBlock)` + * `block.meta` renamed to `block.metadata` + * `item.meta` renamed to `item.metadata` + * fix crash when player causes entityGone message + * update to minecraft-protocol 0.6.6 + +## 0.0.15 + + * fix `bot.sleep` not working at all + * add `bot.isSleeping` + * add "sleep" event + * add "wake" event + * `bot.sleep(bedPoint)` changed to `bot.sleep(bedBlock)` + * fix `mineflayer.Recipe` not exposed + +## 0.0.14 + + * add crafting support + - add `mineflayer.windows` + - add `mineflayer.Recipe` + - `bot.inventory` is now an instance of `InventoryWindow` + - `bot.inventory.count` is no longer a map of id to count. + `Window` instances have a `count(itemType, [metadata])` method. + - `bot.inventory.quickBarSlot` moved to `bot.quickBarSlot`. + - add `'windowOpen' (window)` event + - add `'windowClose' (window)` event + - add `bot.craft(recipe, count, craftingTable, [callback])` + - add `bot.recipesFor(itemType, metadata, minResultCount, craftingTable)` + * `block.pos` renamed to `block.position`. + * `'blockUpdate' (point)` event signature changed to + `'blockUpdate' (oldBlock, newBlock)` + * `'blockUpdate:(x, y, z)'` event signature changed to + `'blockUpdate:(x, y, z)' (oldBlock, newBlock)` + * add `'diggingAborted' (block)` event + * add `bot.unequip(destination, [callback])` + * add `bot.toss(itemType, metadata, count, [callback])` + * `bot.startDigging(block)` changed to `bot.dig(block, [timeout], [callback])`. + * add `bot.activateBlock(block)` + +## 0.0.13 + + * fix `bot.equip` when already equipping the item + * fix some incorrect block physics + * add `mineflayer.recipes` enum + * fix crash when digging at a high elevation + +## 0.0.12 + + * add inventory support + - add `Item` class which is exposed on `mineflayer` + - add `bot.inventory` (see docs for more details) + - add `bot.equip(itemType, destination, [callback])` + - add `bot.tossStack(item, [callback])` + * add digging support + - add `bot.startDigging(block)` + - add `bot.canDigBlock(block)` + * blocks: add `blockUpdate:(x, y, z)` event. + * add building support + - add `bot.placeBlock(referenceBlock, faceVector)` + * add `block.painting` + * add `Painting` class which is exposed on `mineflayer` + * add experience orb support + - `entity.type` can be `orb` now + - `entity.count` is how much experience you get for collecting it + +## 0.0.11 + + * physics: skip frames instead of glitching out + * default bot name to Player - `createBot` can take no arguments now. + +## 0.0.10 + + * physics: fix bug: walking too slowly on Z axis + +## 0.0.9 + + * ability to sprint (thanks ruan942) + * fix color code stripping (thanks rom1504) + * event "onNonSpokenChat" deleted + * new event "message" which fires for all messages + * `bot.chat` no longer checks for "/tell" at the beginning + * add `bot.tell(username, message)` method + * fix crash when an entity effect occurs + +## 0.0.8 + + * chat: no longer suppress "chat" events for your own chat (thanks Darthfett). + * ability to mount / dismount vehicles and attack + * physics: fix tall grass and dead bushes treated as solid + * fix "respawn" event firing twice sometimes + * remove `bot.spawn()` and `autoSpawn` option. auto spawn is now mandatory. + * fix sending spawn packet twice on init + * fix bots spawning with their heads on backwards + * fix bots jumping when they get hit + * update player heights when they crouch + * add support for signs: `block.signText` and `bot.updateSign(block, text)` + +## 0.0.7 + + * add `bot.time.day` and `bot.time.age` and "time" event + * add `bot.entities` which is a map of the entities around you + * add `bot.look(yaw, pitch, force)` and `bot.lookAt(point, force)` + +## 0.0.6 + + * add a physics engine which understands gravity + * add jumper example, jumps whenever you chat + * add `respawn` event which fires when you die or change dimensions + * Block instances have a `boundingBox` property, which is currently either + `solid` or `empty`. + * fix `game` event to fire correctly + * `bot.game.spawnPoint` moved to `bot.spawnPoint`. + * `bot.game.players` moved to `bot.players`. + * `bot.quit` has a default reason of "disconnect.quitting" (thanks Darthfett) + +## 0.0.5 + + * unload chunks when changing dimensions + * blocks: handle all forms of block changing so that `blockAt` is always + accurate. + +## 0.0.4 + + * expose Block, Biome, and Entity + +## 0.0.3 + + * add `bot.blockAt(point)` which returns a `Block` + * add `mineflayer.blocks`, `mineflayer.biomes`, and `mineflayer.items` + * 添加机器人 `chunk` 事件 + * 修复`spawn` 事件和 `settings.showCape` + * added chatterbox example + * changed `entityDetach` event to have a vehicle argument + * changed `entityEffectEnd` event to have an effect argument + instead of `effectId` + * fix prefixes in pseudos in chat. (thanks rom1504) + * update vec3 to 0.1.0 which uses euclidean modulus + +## 0.0.2 + + * 增加 bot.game.spawnPoint + * 增加 spawn 支持 + * 增加 rain 支持 + * 增加 support for getting kicked + * 增加 settings 支持 + * 增加experience support + * 增加 bed 支持 + * health status knowledge + * 增加实体跟踪API diff --git a/docs/zh/index.html b/docs/zh/index.html new file mode 100644 index 000000000..f3cba7222 --- /dev/null +++ b/docs/zh/index.html @@ -0,0 +1,38 @@ + + + + + Mineflayer - 使用稳定的高级API创建Minecraft机器人 + + + + + + + + + + +
+ + + + diff --git a/docs/zh/tutorial.md b/docs/zh/tutorial.md new file mode 100644 index 000000000..60f73bec4 --- /dev/null +++ b/docs/zh/tutorial.md @@ -0,0 +1,718 @@ +# 使用教程 + +**目录** + +- [基础](#基础) + - [Javascript 基础](#Javascript 基础知识) + - [Installing Node](#installing-node) + - [Javascript variables](#javascript-variables) + - [Show output](#show-output) + - [Javascript functions](#javascript-functions) + - [Javascript 数据类型](#Javascript 数据类型) + - [If-statements](#if-statements) + - [Loops](#loops) + - [Node 包管理器](#Node 包管理器) + - [Creating a bot](#creating-a-bot) + - [Javascript objects](#javascript-objects) + - [Logging in](#logging-in) + - [Passing along functions](#passing-along-functions) + - [Listening for an event](#listening-for-an-event) + - [Callbacks](#callbacks) + - [Correct and incorrect approach](#correct-and-incorrect-approach) +- [高级](#高级) + - [Asynchronousy](#asynchronousy) + - [Loop over an object](#loop-over-an-object) + - [Creating an event from chat](#creating-an-event-from-chat) + - [Answer Hello Bot](#answer-hello-bot) + - [Custom Chat](#custom-chat) +- [FAQ](#faq) + - [How to run a bot on android](#how-to-run-a-bot-on-android) + - [Install Termux](#install-termux) + - [Setup](#setup) + - [Start your bot](#start-your-bot) + +## 介绍 + +This tutorial will help you get started with Mineflayer, even if you know nothing about coding. +If you already know some things about Node and NPM, you can go to the [Create a bot](#creating-a-bot) section, otherwise start here. + +## 基础 + +以下几节是关于开始使用Mineflayer需要知道的基本概念。 + +### Javascript 基础知识 + +#### Installing Node + +In this section you will learn the basics about Javascript, Node and NPM. + +Javascript, often abbreviated to JS, is a programming language designed for the web. It is what makes most interactivity on the web possible. +Node.js, often just Node, makes it possible to use Javascript outside of web browsers. + +So the first thing you have to do to get started is to install Node. You can get it [here](https://nodejs.org/en/download/). +After it is installed, open a command prompt (also known as a terminal) and then type `node -v` +If you have installed Node correctly, it should return a version number. If it says it can't find the command, try installing it again. + +Now you have Node, you could start writing code, but we need to do 1 more thing. +Javascript can be written in any basic text editor, but it is much easier if you use what is called an [Integrated development environment](https://en.wikipedia.org/wiki/Integrated_development_environment)(IDE) +An IDE will help you write code because it can give you suggestions, or tell you if your code has potential problems. A good IDE to start with is [Visual Studio Code](https://code.visualstudio.com/)(VSCode) +Once you have installed and set-up VSCode, create a new file and then save it somewhere with a name ending with `.js`, e.g. `bot.js` +This will let VSCode know we are working with Javascript, and give you the correct suggestions. + +#### Javascript variables + +首先输入以下内容: + +```js +const test = 5 +``` + +This will create a new variable named `test` and assign it the value `5` +Variable are used to save data and use it later in the code. + +Now save the file so we can run the code. Open a terminal again (or a new terminal in VSCode) and navigate to the same folder the file is saved in. This can be done using the `cd` command, for example: `cd Documents\javascript` +Once your terminal is in the same folder as your Javascript file, you can run `node filename.js` +If you have done everything correctly, you should see nothing. +In the next chapter we will show you how you can 'print' things to the terminal. + +In general, it is good practice to use the `const` keyword instead of the `let` keyword when defining a variable. A variable defined with `const` can't be modified later and thus is a constant. +Javascript is then able to make your code run more efficiently because it knows it doesn't have to account for value changes for that variable. +If you want a modifiable variable, you will still have to use `let` of course. + +```js +const test = 5 +// eslint-disable-next-line +test = 10 // This line is invalid. +``` + +The second line is invallid because you can't reassign the `test` variable. + +If you want to help yourself and other people understand your code better, you can use comments. +Comments can be created using `//` and everything after that is completely ignored by Javascript. + +#### 显示输出 + +A lot of times you want to see the current value of a variable, to make sure your program is running correctly. +您可以通过将变量打印到终端来实现这一点. +在Javascript中,我们可以使用 `console.log()` 函数 + +```js +const test = 5 + +console.log(test) +``` + +现在,当您保存并运行此代码时,您最终应该会看到: + +```txt +5 +``` + +#### Javascript functions + +Next you will learn about functions. Functions are a piece of code that can be used multiple times throughout your code. +These can be useful because you don't have to type something multiple times. + +```js +const addition = (a, b) => { + return a + b +} + +const test1 = addition(5, 10) +const test2 = addition(1, 0) + +console.log(test1) +console.log(test2) +``` + +The `=>` is used to define a function, called the arrow operator. +Before the arrow operator is the parameter list, everything between the round brackets `()` are parameters, separated by a comma. +Parameters are variables you can give to your function so that your function can work with them. +Then after the arrow operator comes the function body, this is everything between the curly brackets `{}` +This is where you put the code of the function. +Now that the function is complete, we assign it to a variable to give it a name, in this case `addition` + +As you can see, this code takes the parameters `a` and `b` and adds them together. +Then the function will return the result. +When a function is defined, the code in the function body is not yet executed. To run a function you have to call it. +You can call a function by using the name of a function followed by round brackets. In this case `addition()` +However, the `addition` function requires 2 parameters. These can be passed along by putting them inside the round brackets, comma separated: `addition(1, 2)` +When the function is done, you can imagine that the function call is replaced by whatever the function has returned. So in this case `let test1 = addition(5, 10)` will become `let test1 = result` (You will not actually see this, but this can help you understand the concept) + +Sometimes you will come across the following: `function addition() {}` This means the same thing, although `() => {}` is preferred. (If you really want to know why, look up 'javascript function vs arrow function') + +The above should output the following: + +```txt +15 +1 +``` + +#### Javascript 数据类型 + +So far we have only worked with numbers, but Javascript can work with more variable types: + +- A string is a piece of text that can contain multiple characters. Strings are defined by using the quotes `''` + +```js +const string = 'This is a string' // string type +``` + +- An array is a type that can hold multiple variables inside itself. Arrays are defined by using the square brackets `[]` + +```js +const array = [1, 2, 3] // array type +``` +- Object are basically advanced arrays, you will learn more about it later in this tutorial. Their defined by curly brackets `{}` + +```js +const object = {} // object type +``` + +- Functions are also their own type. + +```js +const adder = (a, b) => { return a + b } // function type +``` + +- A boolean is a type that can only be `true` or `false` + +```js +const boolean = true // boolean type +``` + +- When something is not (yet) defined, its type is `undefined` + +```js +let nothing // undefined type +const notDefined = undefined // undefined type +``` + +#### If-statements + +Sometimes you want to do different things based on a certain condition. +This can be achieved using if-statements. + +```js +const name = 'Bob' + +if (name === 'Bob') { + console.log('你的名字是 Bob') +} else if (name === 'Alice') { + console.log('你的名字是 Alice') +} else { + console.log('你的名字不是Bob或Alice') +} +``` + +An if-statement is created using the `if` keyword. After that you have a condition between the round brackets `()` followed by the body between the curly brackets `{}` +A condition has to be something that computes to a boolean. +In this case it uses an equal operator `===` which will be `true` if the value in front is the same as the value after. Otherwise it will be `false` +If the condition is `true` the code in the body will be executed. +You can chain an if-statement with an else-if-statement or an else-statement. +You can have as many else-if-statements as you want, but only 1 if and else statement. +If you have an else-statement, it will be called only if all the chained statements before it are `false` + +#### Loops + +Loops are used to repeat certain code until a certain conditional is met. + +```js +let countDown = 5 + +while (countDown > 0) { + console.log(countDown) + countDown = countDown - 1 // 从1递减 +} + +console.log('已完成!') +``` + +上述代码将打印以下内容 + +```txt +5 +4 +3 +2 +1 +已完成! +``` + +The `while` loop has a condition `()` and a body `{}` +When the code reaches the loop, it will check the condition. If the condition is `true`, the code in the body will be executed. +After the end of the body is reached, the condition is checked again, and if `true`, the body executed again. +This will happen for as long as the condition check is still `true` +Each loop, this code prints the current `countDown` number, and then decrements it by 1. +After the 5th loop, the condition `0 > 0` will be `false`, and thus the code will move on. + +A `for` loop is also often used, and differs slightly from a `while` loop. + +```js +for (let countDown = 5; countDown > 0; countDown = countDown - 1) { + console.log(countDown) +} +``` + +Instead of only a condition, the for loops has 3 different parts +These parts are separated by a semi-column. +The first parts `let countDown = 5` is only executed once, at the start of the loop. +The second part `countDown > 0` is the condition, this is the same as the while loop. +The third part `countDown = countDown - 1` is executed after each loop.: + +If you want to do something for every item in an array, a `for of` loop can be useful. + +```js +const array = [1, 2, 3] + +for (const item of array) { + console.log(item) +} +``` + +A `for of` loop needs to have a variable before the `of`, this is the variable that can be used to access the current item. +The variable after the `of` needs to be something that contains other variable. These are mostly arrays, but also some objects. +The loop will execute the body for each item in the `array` and each loop the `item` variable will be the current item of the `array` + +#### Node 包管理器 + +The last thing you need to know is how to use the [Node Package Manager](https://www.npmjs.com/). +NPM is automatically installed when you install Node. +NPM is used to get useful packages that other people created that can do useful things for you. +You can search for packages on [their website](https://www.npmjs.com/), and then install them using the `npm install` command in your terminal. +To install Mineflayer for example, run `npm install mineflayer` + +Then, Node can access installed modules by using the `require()` function. + +```js +const mineflayer = require('mineflayer') +``` + +After this, the `mineflayer` variable can be used to access all the features of Mineflayer. + +### 创建机器人 + +Now that you know the basics of Javascript, Node and NPM, you're ready to start creating your first bot! +If you don't know any of the terms above, you should go back to the [previous section](#javascript-basics) + +下面是创建Mineflayer机器人所需的绝对最少代码 + +```js +const mineflayer = require('mineflayer') + +const bot = mineflayer.createBot() +``` + +If you run this example, you'll notice that your program will not stop. If you want to stop your currently running program, press `Ctrl` + `c` +However, this bot isn't quite useful, as by default this will connect to a Minecraft server running on your machine with the port 25565. +If you want to choose which server you want your bot to connect to, you have to pass along a few options. + + +```js +const mineflayer = require('mineflayer') + +const options = { + host: 'localhost', // 将此项更改为所需的ip + port: 25565 // 将此项更改为所需的端口 +} + +const bot = mineflayer.createBot(options) +``` + +#### Javascript objects + +The curly brackets `{}` are used to create an object. +Objects contain what is called a key-value pair. +A key-value pair consist of a colon `:` and a key before the colon, and the value of that key after the colon. +The keys can then be used to retrieve their value. +You can have multiple key-value pairs by separating them by commas. + +```js +const object = { + number: 10, + another: 5 +} + +console.log(object.number) // 这将打印值10 +``` + +This concept is often used to create what is named 'named parameters' +The advantage of this is that you don't have to use all the options available, and their position does not matter. +The value can be anything, even other object. If the value is a function, that function is often called a method for that object. +You can also create the object in-line. + +```js +const bot = mineflayer.createBot({ host: 'localhost', port: 25565 }) +``` + +#### 登录 + +Without any parameters, the bot will have the name `Player` and can only log into offline servers. (Cracked & open-to-lan) +If you supply the `createBot` with an `username` option, it will log in with that username. (Still only in offline server) +To log into a specific account, you have to supply both the `username` and the `password` + +```js +const bot = mineflayer.createBot({ + host: 'localhost', + port: 25565, + username: 'Player', + password: 'password' +}) +``` + +#### Command line arguments + +What if somebody else likes your bot and wants to use it, but uses it on a different server and with a different account? +This means that everyone has to change the server address and login settings to their preference. (And it's of course also a bad idea to share your password) +To counter this, a lot of people use command line arguments. + +```js +const bot = mineflayer.createBot({ + host: process.argv[2], + port: parseInt(process.argv[3]), + username: process.argv[4], + password: process.argv[5] +}) +``` + +As you can see, no more sensitive data in your code! But now, how do you run it? +Now, instead of starting your program with just `node filename.js` you start it with `node filename.js host port username password` +Node will automatically split the whole command line into an array, separated by spaces. +This array is `process.argv` +The data in an array can be accessed using the index of each item. The index always start at 0, so the first item can be accessed with `[0]` and in this case will be `node` etc. + +| | First item | Second item | Third Item | Fourth item | Fifth item | Sixth item | +| --- | :---: | :---: | :---: | :---: | :---: | :---: | +| Value | `node` | `filename.js` | `host` | `port` | `username` | `password` | +| Index | `[0]` | `[1]` | `[2]` | `[3]` | `[4]` | `[5]` + +### Passing along functions + +Not only basics variables like numbers and strings can be given as an argument. +Functions can also be passed as a variable. + +```js +const welcome = () => { + bot.chat('你好!') +} + +bot.once('spawn', welcome) +``` + +As you can see, the `bot.once()` method takes 2 parameters. +The first parameter is an event name, the second parameter is the function to call when that event happens. +Remember, when passing along a function, only use the name and not the round brackets `()` + +`bot.chat()` is the method for sending message to the chat. + +You can also simplify this code by using a anonymous function. +An anonymous function doesn't have a name, and is created at the position where the function name used to go. +They still have to have a parameter list `()` and a function body `{}`, even if it isn't used. + +```js +bot.once('spawn', () => { + bot.chat('你好!') +}) +``` + +### Listening for an event + +The bot object has many useful [events](http://mineflayer.prismarine.js.org/#/api?id=events). +You can listen for an event by using either `bot.on()` method or `bot.once()` method of the bot object, which takes the name of an event and a function. +To remove specific listener you can use `bot.removeListener()` method. + +- `bot.on(eventName, listener)` + Execute the `listener` function for each time the event named `eventName` triggered. +- `bot.once(eventName, listener)` + Execute the `listener` function, only once, the first time the event named `eventName` triggered. +- `bot.removeListener(eventName, listener)` + Removes the specified `listener` for the event named `eventName`. In order to use this you either need to define your function with `function myNamedFunc() {}` or put your function in a variable with `const myNamedFunc = () => {}`. You can then use `myNamedFunc` in the listener argument. + +Not only bot object, [`Chest`](http://mineflayer.prismarine.js.org/#/api?id=mineflayerchest), [`Furnace`](http://mineflayer.prismarine.js.org/#/api?id=mineflayerfurnace), [`Dispenser`](http://mineflayer.prismarine.js.org/#/api?id=mineflayerdispenser), [`EnchantmentTable`](http://mineflayer.prismarine.js.org/#/api?id=mineflayerenchantmenttable), [`Villager`](http://mineflayer.prismarine.js.org/#/api?id=mineflayervillager) object also have their own events! + +### Callbacks +A [callback](https://en.wikipedia.org/wiki/Callback_(computer_programming)) is a function that you can give to another function, that is expected to be *called back*, generally when that function ends. +In Mineflayer, callbacks are often used to handle errors. + +```js +bot.consume((error) => { + if (error) { // 这将检查是否发生错误 + console.log(error) + } else { + console.log('Finished consuming') + } +}) +``` + +The above code will try to consume what the bot is currently holding. +When the consuming ends, the function that is passed along is called. +We can then do other things that we want to do after. +The function could also be called when an error occurs. + +#### Correct and incorrect approach + +Below is an example of a bot that will craft oak logs into oak planks and then into sticks. + +Incorect approach ❌: + +```js +const plankRecipe = bot.recipesFor(5)[0] // Get the first recipe for item id 5, which is oak planks. +bot.craft(plankRecipe, 1) // ❌ start crafting oak planks. + +const stickRecipe = bot.recipesFor(280)[0] // Get the first recipe for item id 5, which is sticks. +bot.craft(stickRecipe, 1) // ❌ start crafting sticks. +``` + +回调的正确方法 ✔️: + +```js +const plankRecipe = bot.recipesFor(5)[0] + +bot.craft(plankRecipe, 1, null, (error) => { + // After bot.craft(plankRecipe, ...) is finished, this callback is called and we continue. ✔️ + if (error) { // 检查是否发生了错误 + console.log(error) + } else { + const stickRecipe = bot.recipesFor(280)[0] + + bot.craft(stickRecipe, 1, null, (error) => { + // After bot.craft(stickRecipe, ...) is finished, this callback is called and we continue. ✔️ + if (error) { // Check if an error happened. + console.log(error) + } else { + bot.chat('Crafting Sticks finished') + } + }) + } +}) +``` + +The reason the incorrect approach is wrong is because when `bot.craft()` is called, the code will continue below while the bot is crafting. +By the time the code reaches the second `bot.craft()`, the first probably hasn't finished yet, which means the wanted resource is not available yet. +Using callbacks can fix this because they will only be called after the `bot.craft()` is finished. + +More on the [bot.craft()](https://mineflayer.prismarine.js.org/#/api?id=botcraftrecipe-count-craftingtable-callback) method. + +## 高级 + +The following concepts aren't necessary to create a Mineflayer bot, but they can be useful to understand and create more advanced bots. +We assume you have understood the [Basics](#basics) tutorial. + +### Asynchronousy +In Javascript, asynchronousy is an important concept. +By default, Javascript will run everything line by line, and only go to the next line if the current line is done. This is called blocking. +However, sometimes you have to do something that takes a relatively long time, and you don't want your whole program to block and wait for it to finish. + +Interacting with the filesystem is often done using asynchronousy, because reading and writing large files can take a long time. + +```js +const myPromise = new Promise((resolve, reject) => { + setTimeout(() => { + resolve('Success!') // 耶!一切都很顺利! + }, 1000) +}) + +myPromise.then((successMessage) => { + console.log(successMessage) +}) + +myPromise.catch((error) => { + console.log(error) +}) +``` + +The above codes uses what is called a Promise. A promise promises it will eventually complete. +The function given you a promise always has 2 parameters, a `resolve` function and a `reject` function. +If the promise is successful, it will call the `resolve` function, otherwise it will call the `reject` function. +The above code uses a `setTimeout`, which calls the given function after the set amount of milliseconds, 1000 in this case. +You can then tell the promise what it should do when it succeeds with `.then(function)` or when it fails with `.catch(function)` + +The `.then` and `.catch` function can also be chained together with the promise to simplify the code. + +```js +const myPromise = new Promise((resolve, reject) => { + setTimeout(() => { + resolve('Success!') // Yay! Everything went well! + }, 1000) +}).then((successMessage) => { + console.log(successMessage) +}).catch((error) => { + console.log(error) +}) +``` + +### Loop over an object + +The `for of` loop described in the [loops](#loops) chapter can also be used to loop over an object. + +If we have the following object: + +```js +const obj = { + a: 1, + b: 2, + c: 3 +} +``` + +The following will loop over all the values of the object. + +```js +for (const value of Object.values(obj)) { + console.log(value) +} +``` + +```txt +1 +2 +3 +``` + +This will loop over all the keys of the object. + +```js +for (const key of Object.keys(obj)) { + console.log(key) +} +``` + +```txt +a +b +c +``` + +You can also loop over the keys and values at the same time. You will have to destructure the variables first, explained [here.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) + +```js +for (const [key, value] of Object.entries(obj)) { + console.log(key + ', ' + value) +} +``` + +```txt +a, 1 +b, 2 +c, 3 +``` + +These loops are possible because `Object.values(obj)` and `Object.keys(obj)` both return an array of the objects values and keys respectively. +`Object.entries(obj)` returns an array where each item is an array with 2 items: a key and its corresponding value. +It's important to know that, unlike the `Object.values()` and `Object.keys()` functions, the `Object.entries()` function does not guarantee that the order is the same as the order when the object was defined. + +There is also a `for in` loop. However, you will most often want to use `for of` instead of `for in` because there are key differences. +The `for in` loop loops over the keys of an object instead of the values. (The index in case it is an array) +However, it doesn't loop only over its own keys, but also keys from other object it 'inherits' from, which can be confusing or unwanted. More on this [here.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) +In general, you'll want to use `for of` instead of `for in` so make sure you don't confuse the two. + +### 从聊天中创建事件 + +You can create your own event from chat using [`bot.chatAddPattern()`](http://mineflayer.prismarine.js.org/#/api?id=botchataddpatternpattern-chattype-description) method. Useful for Bukkit servers where the chat format changes a lot. +[`bot.chatAddPattern()`](http://mineflayer.prismarine.js.org/#/api?id=botchataddpatternpattern-chattype-description) method takes three arguments : + +- `pattern` - regular expression (regex) to match chat +- `chatType` - the event the bot emits when the pattern matches. e.g. "chat" or "whisper" +- `description` - Optional, describes what the pattern is for + +You can add [Groups and Range](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges) into the `pattern`, then the listener will spread the captured groups into arguments of your callback sequentially. + +阅读有关[正则表达式](https://en.wikipedia.org/wiki/Regular_expression)的更多信息 + +例子 : + +#### 回答你好 机器人 + +在这里,我们创建一个机器人,从另一个玩家那里回答“你好”。 + +```js +bot.chatAddPattern( + /(helo|hello|Hello)/, + 'hello', + 'Someone says hello' +) + +const hi = () => { + bot.chat('Hi!') +} + +bot.on('hello', hi) +``` + +#### 自定义聊天 + +基于自定义聊天格式创建事件 +自定义聊天示例: + +```txt +[Player] 路人甲 > 你好 +[Admin] 李四 > Hi +[Player] 法外狂徒张三 > 焯!我卡住了 +[Mod] Jim > 我马上到 +``` + +```js +bot.chatAddPattern( + /^\[(.+)\] (\S+) > (.+)$/, + 'my_chat_event', + 'Custom chat event' +) + +const logger = (rank, username, message) => { + console.log(`${username} 说 ${message}`) +} + +bot.on('my_chat_event', logger) +``` + +关于 `^\[(.+)\] (\S+) > (.+)$` 正则表达式的解释可在[此处](https://regex101.com/r/VDUrDC/2)找到 + +## FAQ + +### 如何在Android上运行机器人 + +下面是在Android设备上用 [Termux](https://termux.com/)运行bot的快速设置教程 + +#### 安装Termux + +安装[Termux](https://termux.com/) 并启动 + +#### Setup + +安装 `Node.js`: + +```bash +pkg update -y +pkg install nodejs -y +``` + +❗️ 允许应用程序设置上Termux的存储权限. +在内部存储上创建新文件夹: + +```bash +cd /sdcard +mkdir my_scripts +cd my_scripts +``` + +安装 `mineflayer`: + +```bash +npm install mineflayer +``` + +现在,您可以将所有脚本复制/存储到内部存储器中的`my_scripts`文件夹中。 + +#### 启动你的机器人 + +要启动机器人,请使用Node运行脚本名称 + +```bash +node script_name.js +``` + +❗️ 每次打开 Termux 时,您都必须在启动机器人之前将 cwd 更改为 `/sdcard/my_scripts`: + +```bash +cd /sdcard/my_scripts +```