mineflayer 4.32.0 → 4.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ {
2
+ "dependencies": {
3
+ "gh-helpers": "^1.0.0"
4
+ }
5
+ }
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Updator script triggered from minecraft-data repository to auto generate PR
4
+ */
5
+ const fs = require('fs')
6
+ const cp = require('child_process')
7
+ const assert = require('assert')
8
+ const github = require('gh-helpers')()
9
+ const { join } = require('path')
10
+ const exec = (cmd) => github.mock ? console.log('> ', cmd) : (console.log('> ', cmd), cp.execSync(cmd, { stdio: 'inherit' }))
11
+
12
+ console.log('Starting update process...')
13
+ // Sanitize and validate environment variables all non alpha numeric / underscore / dot
14
+ const newVersion = process.env.NEW_MC_VERSION?.replace(/[^a-zA-Z0-9_.]/g, '_')
15
+ const triggerBranch = process.env.MCDATA_BRANCH?.replace(/[^a-zA-Z0-9_.]/g, '_')
16
+ const mcdataPrURL = process.env.MCDATA_PR_URL
17
+ console.log({ newVersion, triggerBranch, mcdataPrURL })
18
+
19
+ assert(newVersion)
20
+ assert(triggerBranch)
21
+
22
+ async function main () {
23
+ const currentSupportedPath = require.resolve('../../lib/version.js')
24
+ const readmePath = join(__dirname, '../../docs/README.md')
25
+ const ciPath = join(__dirname, '../../.github/workflows/ci.yml')
26
+
27
+ // Update the version.js
28
+ const currentSupportedVersion = require('../../lib/version.js')
29
+ const currentContents = fs.readFileSync(currentSupportedPath, 'utf8')
30
+ console.log('Current supported version:', currentContents)
31
+ const latestV = currentSupportedVersion.testedVersions.at(-1)
32
+ const newContents = currentContents.includes(newVersion)
33
+ ? currentContents
34
+ : currentContents
35
+ .replace(`, '${latestV}'`, `, '${latestV}', '${newVersion}'`)
36
+
37
+ // Update the README.md
38
+ const currentContentsReadme = fs.readFileSync(readmePath, 'utf8')
39
+ if (!currentContentsReadme.includes(newVersion)) {
40
+ const newReadmeContents = currentContentsReadme
41
+ .replace(/Minecraft 1\.8 to [0-9A-Za-z._-]+ \(/, `Minecraft 1.8 to ${newVersion} (`)
42
+ .replace(') <!--version-->', `, ${newVersion}) <!--version-->`)
43
+ fs.writeFileSync(readmePath, newReadmeContents)
44
+ console.log('Updated README with new version:', newVersion)
45
+ }
46
+ fs.writeFileSync(currentSupportedPath, newContents)
47
+
48
+ // Update the CI workflow
49
+ const currentContentsCI = fs.readFileSync(ciPath, 'utf8')
50
+ if (!currentContentsCI.includes(newVersion)) {
51
+ const newCIContents = currentContentsCI.replace(
52
+ 'run: npm install', `run: npm install
53
+ - run: cd node_modules && cd minecraft-data && mv minecraft-data minecraft-data-old && git clone -b ${triggerBranch} https://github.com/PrismarineJS/minecraft-data --depth 1 && node bin/generate_data.js
54
+ - run: curl -o node_modules/protodef/src/serializer.js https://raw.githubusercontent.com/extremeheat/node-protodef/refs/heads/dlog/src/serializer.js && curl -o node_modules/protodef/src/compiler.js https://raw.githubusercontent.com/extremeheat/node-protodef/refs/heads/dlog/src/compiler.js
55
+ `)
56
+ fs.writeFileSync(ciPath, newCIContents)
57
+ console.log('Updated CI workflow with new version:', newVersion)
58
+ }
59
+
60
+ const branchName = 'pc' + newVersion.replace(/[^a-zA-Z0-9_]/g, '_')
61
+ exec(`git checkout -b ${branchName}`)
62
+ exec('git config user.name "github-actions[bot]"')
63
+ exec('git config user.email "41898282+github-actions[bot]@users.noreply.github.com"')
64
+ exec('git add --all')
65
+ exec(`git commit -m "Update to version ${newVersion}"`)
66
+ exec(`git push origin ${branchName} --force`)
67
+ // createPullRequest(title: string, body: string, fromBranch: string, intoBranch?: string): Promise<{ number: number, url: string }>;
68
+ const pr = await github.createPullRequest(
69
+ `🎈 ${newVersion}`,
70
+ `This automated PR sets up the relevant boilerplate for Minecraft version ${newVersion}.
71
+
72
+ Ref: ${mcdataPrURL}
73
+
74
+ * You can help contribute to this PR by opening a PR against this <code branch>${branchName}</code> branch instead of <code>master</code>.
75
+ `,
76
+ branchName,
77
+ 'master'
78
+ )
79
+ console.log(`Pull request created`, pr)
80
+ }
81
+
82
+ main().catch(err => {
83
+ console.error('Error during update process:', err)
84
+ process.exit(1)
85
+ })
@@ -0,0 +1,54 @@
1
+ name: Update from minecraft-data
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ inputs:
6
+ new_mc_version:
7
+ description: New minecraft version number
8
+ required: true
9
+ type: string
10
+ mcdata_branch:
11
+ description: minecraft-data branch for this version
12
+ required: true
13
+ type: string
14
+ mcdata_pr_url:
15
+ description: minecraft-data PR number to open a PR here against
16
+ required: false
17
+ default: ''
18
+ type: string
19
+ nmp_branch:
20
+ description: minecraft-protocol branch for this version
21
+ required: true
22
+ type: string
23
+ nmp_pr_url:
24
+ description: minecraft-protocol PR number to open a PR here against
25
+ required: false
26
+ default: ''
27
+ type: string
28
+
29
+ jobs:
30
+ update:
31
+ runs-on: ubuntu-latest
32
+
33
+ steps:
34
+ - name: Checkout repository
35
+ uses: actions/checkout@v4
36
+ with:
37
+ token: ${{ secrets.PAT_PASSWORD }}
38
+
39
+ - name: Use Node.js 22.x
40
+ uses: actions/setup-node@v1.4.4
41
+ with:
42
+ node-version: 22.x
43
+
44
+ - run: npm install PrismarineJS/node-minecraft-protocol#${{ github.event.inputs.nmp_branch }}
45
+
46
+ - name: Run updator script
47
+ run: cd .github/helper && npm install && node updator.js
48
+ env:
49
+ GITHUB_TOKEN: ${{ secrets.PAT_PASSWORD }}
50
+ NEW_MC_VERSION: ${{ github.event.inputs.new_mc_version }}
51
+ MCDATA_BRANCH: ${{ github.event.inputs.mcdata_branch }}
52
+ MCDATA_PR_URL: ${{ github.event.inputs.mcdata_pr_url }}
53
+ NMP_BRANCH: ${{ github.event.inputs.nmp_branch }}
54
+ NMP_PR_URL: ${{ github.event.inputs.nmp_pr_url }}
package/README.md CHANGED
@@ -17,7 +17,7 @@ First time using Node.js? You may want to start with the [tutorial](tutorial.md)
17
17
 
18
18
  ## Features
19
19
 
20
- * Supports Minecraft 1.8 to 1.21 (1.8, 1.9, 1.10, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19, 1.20, and 1.21)
20
+ * Supports Minecraft 1.8 to 1.21.9 (1.8, 1.9, 1.10, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19, 1.20, 1.21, 1.21.9) <!--version-->
21
21
  * Entity knowledge and tracking.
22
22
  * Block knowledge. You can query the world around you. Milliseconds to find any block.
23
23
  * Physics and movement - handle all bounding boxes
package/docs/README.md CHANGED
@@ -17,7 +17,7 @@ First time using Node.js? You may want to start with the [tutorial](tutorial.md)
17
17
 
18
18
  ## Features
19
19
 
20
- * Supports Minecraft 1.8 to 1.21 (1.8, 1.9, 1.10, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19, 1.20, and 1.21)
20
+ * Supports Minecraft 1.8 to 1.21.9 (1.8, 1.9, 1.10, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19, 1.20, 1.21, 1.21.9) <!--version-->
21
21
  * Entity knowledge and tracking.
22
22
  * Block knowledge. You can query the world around you. Milliseconds to find any block.
23
23
  * Physics and movement - handle all bounding boxes
package/docs/history.md CHANGED
@@ -1,3 +1,15 @@
1
+ ## 4.34.0
2
+ * [🎈 1.21.9/1.21.10 support (#3754)](https://github.com/PrismarineJS/mineflayer/commit/f0afaf73061c15b67e5d3457b60ed543e711acb6) (thanks @rom1504bot)
3
+ * [Update russian docs (#3762)](https://github.com/PrismarineJS/mineflayer/commit/887b52b933d943c8d605d7835d6d55d198208fee) (thanks @fungoza)
4
+ * [Swap out deprecated bot.chatAddPattern() in tutorial.md (#3709)](https://github.com/PrismarineJS/mineflayer/commit/e5fcf1f022656c7432ef11b4e458ca9b2e08c1ee) (thanks @TheSharkyOfficial)
5
+ * [Add missing uuid-1345 dep](https://github.com/PrismarineJS/mineflayer/commit/464000aa05fc44cc6da236fc370bce6911648a75) (thanks @extremeheat)
6
+ * [Update README.md](https://github.com/PrismarineJS/mineflayer/commit/9d7ea28c3321170f9958f54dfe24cedf48f1113f) (thanks @extremeheat)
7
+ * [Resolved type mismatch (#3748)](https://github.com/PrismarineJS/mineflayer/commit/266af6786edc78d17e7afad77a3e89fc7649e0e0) (thanks @BF5258)
8
+
9
+ ## 4.33.0
10
+ * [Add update workflow (#3727)](https://github.com/PrismarineJS/mineflayer/commit/9c335366d435b58cfe45bbfbbc534b99ee669dc2) (thanks @extremeheat)
11
+ * [Add support for Minecraft 1.21.8 (#3732)](https://github.com/PrismarineJS/mineflayer/commit/ec8220d7c63b72acb4bf16f30cdf4ba346b83f98) (thanks @rom1504)
12
+
1
13
  ## 4.32.0
2
14
  * [1.21.6 (#3713)](https://github.com/PrismarineJS/mineflayer/commit/01f537c394fc78bf2e765b28a8b24a30c1d1fd2e) (thanks @extremeheat)
3
15
  * [Fix knockback physics crash (#3715)](https://github.com/PrismarineJS/mineflayer/commit/e3f89d17418ece9e9fac4b111d8243dfe1a5d376) (thanks @Omena0)
@@ -21,6 +21,20 @@ Mineflayer имеет 2 вида тестов :
21
21
 
22
22
  Цель этих тестов - автоматически определить, что работает, а что нет в mineflayer, чтобы было проще заставить mineflayer работать.
23
23
 
24
+ ## Запуск тестов
25
+ Вы можете запустить тесты для разных версий Minecraft, используя флаг `-g` в npm run mocha_test. Например:
26
+
27
+ ```bash
28
+ # Запуск всех тестов для всех поддерживаемых версий
29
+ npm run test
30
+
31
+ # Запуск определённого теста для Minecraft 1.20.4
32
+ npm run mocha_test -- -g "mineflayer_external 1.20.4v.*exampleBee"
33
+
34
+ # Запуск всех тестов только для версии 1.20.4
35
+ npm run mocha_test -- -g "mineflayer_external 1.20.4v"
36
+ ```
37
+
24
38
  ### Создание внешних тестов
25
39
 
26
40
  Для внешних тестов вам просто нужно создать файл в [test/externalTests](../../test/externalTests)
package/docs/ru/FAQ_RU.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  Это документ с часто задаваемыми вопросами, предназначен для помощи людям в самых распространенных вещах.
4
4
 
5
+ ### Выдаёт ошибку (например, protocol/data) когда бот пытается подключиться к серверу Minecraft.
6
+
7
+ Убедитесь, что версия сервера Minecraft поддерживается (см. README), иначе попробуйте ещё раз, используя [тестовые версии mineflayer](../../lib/version.js).
8
+
5
9
  ### Выдаёт ошибку при попытке войти в систему через аккаунт Microsoft.
6
10
 
7
11
  Убедитесь, что адрес электронной почты, который вы ввели в поле username в createBot, можно использовать для входа на `minecraft.net` используя кнопку «Войти с помощью Microsoft».
@@ -17,7 +17,7 @@
17
17
 
18
18
  ## Возможности
19
19
 
20
- * Поддержка 1.8, 1.9, 1.10, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19 и 1.20.
20
+ * Поддержка с Minecraft 1.8 до 1.21.8 (1.8, 1.9, 1.10, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19, 1.20, 1.21.8)
21
21
  * Поддержка энтити и их отслеживание.
22
22
  * Вы можете полностью взаимодействовать с миром. Миллисекунды на поиск любого блока.
23
23
  * Физика и управление.
@@ -39,7 +39,10 @@
39
39
 
40
40
  `npm install mineflayer`
41
41
 
42
- Чтобы обновить пакет mineflayer (или любой Node.js) и его зависимости, используйте `npm update --depth 9999`
42
+ Чтобы обновить пакет mineflayer (или любой Node.js) и его зависимости, используйте
43
+ ```bash
44
+ npm update
45
+ ```
43
46
 
44
47
  ## Документация
45
48
 
@@ -97,6 +100,27 @@ bot.on('kicked', console.log)
97
100
  bot.on('error', console.log)
98
101
  ```
99
102
 
103
+ Если в `auth` установлен `microsoft`, вам предложит войти в microsoft.com с кодом в вашем браузере. После входа через браузер
104
+ бот автоматически получит и сохранит в кэш токен аутентификации (для вашего ника), чтобы потом вам опять не пришлось входить.
105
+
106
+ Чтобы сменить аккаунт, обновите `username`. По умолчанию кэшированые токены храняться в вашей папке .minecraft или в `profilesFolder`, если это указано.
107
+ Для большей информации о настройках бота смотрите [API документацию](https://github.com/PrismarineJS/node-minecraft-protocol/blob/master/docs/API.md#mccreateclientoptions) по node-minecraft-protocol.
108
+
109
+ #### Подключение к Realm
110
+
111
+ Чтобы зайти в Realm, куда ваш аккаунт был приглашён, вы можете вписать объект `realms` с функцией, как показано ниже.
112
+
113
+ ```js
114
+ const client = mineflayer.createBot({
115
+ username: 'email@example.com', // майнкрафт ник
116
+ realms: {
117
+ // Эта функция вызывается с массивом доступных для аккаунта Realm'ов. Оно должно возвращать то, куда оно хочет зайти.
118
+ pickRealm: (realms) => realms[0]
119
+ },
120
+ auth: 'microsoft'
121
+ })
122
+ ```
123
+
100
124
  ### Смотрите, что делает бот
101
125
 
102
126
  Спасибо репозиторию [prismarine-viewer](https://github.com/PrismarineJS/prismarine-viewer), с помощью которого можно через браузер увидеть, что делает бот.
@@ -131,7 +155,13 @@ bot.once('spawn', () => {
131
155
 
132
156
  Большая часть разработки происходит внутри небольших пакетов npm, которые используются mineflayer.
133
157
 
134
- Модули, из которых состоит Mineflayer:
158
+ #### The Node Way&trade;
159
+
160
+ > "Когда приложения сделаны правильно, они представляют собой лишь ту самую специфичную, "солоноватую" прослойку логики, которую нельзя так просто абстрагировать. Все изящные, переиспользуемые компоненты возносятся на github и npm, где все могут совместно работать на общее благо." — substack из ["как я пишу модули"](https://gist.github.com/substack/5075355)
161
+
162
+ #### Модули
163
+
164
+ Здесь основная часть пакетов, которые используются в mineflayer:
135
165
 
136
166
  | Модуль | Описание |
137
167
  | ----------------------------------------------------------------------------- |---------------------------------------------------------------------------------------- |
@@ -172,6 +202,7 @@ Mineflayer поддерживает сторонние плагины. Любо
172
202
 
173
203
  Наиболее обновлённые и полезные:
174
204
 
205
+ * [minecraft-mcp-server](https://github.com/yuniko-software/minecraft-mcp-server) Сервер MCP для mineflayer, позволяющий использовать mineflayer из LLM
175
206
  * [pathfinder](https://github.com/Karang/mineflayer-pathfinder) - Продвинутый A* поиск пути с множеством настраиваемых функций
176
207
  * [prismarine-viewer](https://github.com/PrismarineJS/prismarine-viewer) - Простой web клиент для просмотра чанков
177
208
  * [web-inventory](https://github.com/ImHarvol/mineflayer-web-inventory) - Веб клиент для взаимодействия с инвентарём
@@ -201,6 +232,7 @@ Mineflayer поддерживает сторонние плагины. Любо
201
232
  ## Проекты, созданные с помощью Mineflayer
202
233
 
203
234
  * [Voyager](https://github.com/MineDojo/Voyager) - Открытый агент с большими языковыми моделями
235
+ * [mindcraft](https://github.com/kolbytn/mindcraft) - Библиотека для использования mineflayer с LLM
204
236
  * [rom1504/rbot](https://github.com/rom1504/rbot)
205
237
  - [YouTube - постройка спиральной лестницы](https://www.youtube.com/watch?v=UM1ZV5200S0)
206
238
  - [YouTube - дублирование постройки](https://www.youtube.com/watch?v=0cQxg9uDnzA)
@@ -211,8 +243,9 @@ Mineflayer поддерживает сторонние плагины. Любо
211
243
  * [Cheese Bot](https://github.com/Minecheesecraft/Cheese-Bot) - Плагин с чистым GUI. Создан с помощью Node-Webkit. http://bot.ezcha.net/
212
244
  * [Chaoscraft](https://github.com/schematical/chaoscraft) - Бот Minecraft, использующий генетические алгоритмы, посмотрите [эти видео](https://www.youtube.com/playlist?list=PLLkpLgU9B5xJ7Qy4kOyBJl5J6zsDIMceH)
213
245
  * [hexatester/minetelegram](https://github.com/hexatester/minetelegram) - Мост между Minecraft и Telegram, созданный при помощи Mineflayer & Telegraf
214
- * [PrismarineJS/mineflayer-builder](https://github.com/PrismarineJS/mineflayer-builder) - Строит схемы в режиме выживания, сохраняя направление
215
- * [и многие другие](https://github.com/PrismarineJS/mineflayer/network/dependents) - Все проекты, обнаруженные GitHub, в которых используется Mineflayer
246
+ * [PrismarineJS/mineflayer-builder](https://github.com/PrismarineJS/mineflayer-builder) - Строит схемы в режиме выживания, сохраняя направление
247
+ * [SilkePilon/OpenDeliveryBot](https://github.com/SilkePilon/OpenDeliveryBot) - Minecraft бот на Python для переноса вещей с места на место.
248
+ * [и многие другие](https://github.com/PrismarineJS/mineflayer/network/dependents) - Все проекты, обнаруженные GitHub, в которых используется Mineflayer
216
249
 
217
250
 
218
251
  ## Тестирование
package/docs/ru/api_ru.md CHANGED
@@ -170,6 +170,8 @@
170
170
  - ["game"](#game)
171
171
  - ["resourcePack" (url, hash)](#resourcepack-url-hash)
172
172
  - ["title" (title, type)](#title-title-type)
173
+ - ["title_times" (fadeIn, stay, fadeOut)](#title_times-fadein-stay-fadeout)
174
+ - ["title_clear"](#title_clear)
173
175
  - ["rain"](#rain)
174
176
  - ["weatherUpdate"](#weatherupdate)
175
177
  - ["time"](#time)
@@ -225,7 +227,7 @@
225
227
  - ["blockBreakProgressEnd" (block, entity)](#blockbreakprogressend-block-entity)
226
228
  - ["diggingCompleted" (block)](#diggingcompleted-block)
227
229
  - ["diggingAborted" (block)](#diggingaborted-block)
228
- - ["usedFirework"](#usedfirework)
230
+ - ["usedFirework" (fireworkEntityId)](#usedfirework-fireworkentityid)
229
231
  - ["move"](#move)
230
232
  - ["forcedMove"](#forcedmove)
231
233
  - ["mount"](#mount)
@@ -270,7 +272,7 @@
270
272
  - [Methods](#methods)
271
273
  - [bot.end(reason)](#botendreason)
272
274
  - [bot.quit(reason)](#botquitreason)
273
- - [bot.tabComplete(str, [assumeCommand], [sendBlockInSight])](#bottabcompletestr-assumecommand-sendblockinsight)
275
+ - [bot.tabComplete(str, [assumeCommand], [sendBlockInSight], [timeout])](#bottabcompletestr-assumecommand-sendblockinsight-timeout)
274
276
  - [bot.chat(message)](#botchatmessage)
275
277
  - [bot.whisper(username, message)](#botwhisperusername-message)
276
278
  - [bot.chatAddPattern(pattern, chatType, description)](#botchataddpatternpattern-chattype-description)
@@ -291,7 +293,7 @@
291
293
  - [bot.getExplosionDamages(entity, position, radius, [rawDamages])](#botgetexplosiondamagesentity-position-radius-rawdamages)
292
294
  - [bot.lookAt(point, [force])](#botlookatpoint-force)
293
295
  - [bot.look(yaw, pitch, [force])](#botlookyaw-pitch-force)
294
- - [bot.updateSign(block, text, back = false)](#botupdatesignblock-text)
296
+ - [bot.updateSign(block, text, back = false)](#botupdatesignblock-text-back--false)
295
297
  - [bot.equip(item, destination)](#botequipitem-destination)
296
298
  - [bot.unequip(destination)](#botunequipdestination)
297
299
  - [bot.tossStack(item)](#bottossstackitem)
@@ -331,6 +333,7 @@
331
333
  - [bot.setCommandBlock(pos, command, [options])](#botsetcommandblockpos-command-options)
332
334
  - [bot.supportFeature(name)](#botsupportfeaturename)
333
335
  - [bot.waitForTicks(ticks)](#botwaitforticksticks)
336
+ - [bot.respawn()](#botrespawn)
334
337
  - [Lower level inventory methods](#lower-level-inventory-methods)
335
338
  - [bot.clickWindow(slot, mouseButton, mode)](#botclickwindowslot-mousebutton-mode)
336
339
  - [bot.putSelectedItemRange(start, end, window, slot)](#botputselecteditemrangestart-end-window-slot)
@@ -1271,6 +1274,26 @@ UUID существа, который определяется боссом.
1271
1274
  * `title` - Текст на экране.
1272
1275
  * `type` - Тип текста "subtitle" или "title"
1273
1276
 
1277
+ #### "title_times" (fadeIn, stay, fadeOut)
1278
+
1279
+ Срабатывает, когда сервер отправляет пакет с временем для текста по центру экрана (например, когда устанавливается или обновляется время для появления, отображения и исчезновения надписи).
1280
+
1281
+ * `fadeIn` - время появления в тиках (число)
1282
+ * `stay` - время отображения в тиках (число)
1283
+ * `fadeOut` - время исчезновения в тиках (число)
1284
+
1285
+ Пример:
1286
+
1287
+ ```js
1288
+ bot.on('title_times', (fadeIn, stay, fadeOut) => {
1289
+ console.log(`Время для надписей: fadeIn=${fadeIn}, stay=${stay}, fadeOut=${fadeOut}`)
1290
+ })
1291
+ ```
1292
+
1293
+ #### "title_clear"
1294
+
1295
+ Срабатывает, когда сервер очищает все надписи по центру экрана.
1296
+
1274
1297
  #### "rain"
1275
1298
 
1276
1299
  Срабатывает, когда начинается или прекращается дождь. Если вы присоединитесь к
@@ -1454,10 +1477,12 @@ UUID существа, который определяется боссом.
1454
1477
 
1455
1478
  * `block` - Блок, который не был разрушен.
1456
1479
 
1457
- #### "usedfirework"
1480
+ #### "usedFirework" (fireworkEntityId)
1458
1481
 
1459
1482
  Срабатывает при использовании фейерверка во время полёта на элитрах.
1460
1483
 
1484
+ * `fireworkEntityId` - айди существа фейерверка.
1485
+
1461
1486
  #### "move"
1462
1487
 
1463
1488
  Срабатывает при движении бота. Если вы хотите узнать текущее положение, используйте `bot.entity.position`, если вы хотите узнать предыдущее положение, используйте `bot.entity.position.minus(bot.entity.velocity)`.
@@ -1635,7 +1660,7 @@ UUID существа, который определяется боссом.
1635
1660
 
1636
1661
  #### bot.recipesFor(itemType, metadata, minResultCount, craftingTable)
1637
1662
 
1638
- Возвращает список рецептов(`Recipe`), которые вы можете использовать для крафта
1663
+ Возвращает список рецептов(`Recipe`), которые вы можете использовать для крафта
1639
1664
  предмета(`itemType`) с мета-данными(`metadata`).
1640
1665
 
1641
1666
  * `itemType` - Числовой ID предмета, который вы хотите создать.
@@ -1667,7 +1692,7 @@ const cow = bot.nearestEntity(entity => entity.name.toLowerCase() === 'cow') //
1667
1692
 
1668
1693
  Принудительно завершает соединение по собственной причине (по умолчанию `'disconnect.quitting'`).
1669
1694
 
1670
- #### bot.tabComplete(str, [assumeCommand], [sendBlockInSight])
1695
+ #### bot.tabComplete(str, [assumeCommand], [sendBlockInSight], [timeout])
1671
1696
 
1672
1697
  Эта функция возвращает `Promise` с `matches` в качестве аргумента при завершении.
1673
1698
 
@@ -1676,6 +1701,7 @@ const cow = bot.nearestEntity(entity => entity.name.toLowerCase() === 'cow') //
1676
1701
  * `str` - Строка для завершения через подсказки.
1677
1702
  * `assumeCommand` - Поле отправляемое серверу, по умолчанию `false`.
1678
1703
  * `sendBlockInSight` - Поле отправляемое серверу, по умолчанию `true`. Установите для этого параметра значение `false`, если вы хотите повысить производительность.
1704
+ * `timeout` - Время в миллисекундах, после которого функция вернёт пустой массив, по умолчанию 5000.
1679
1705
 
1680
1706
  #### bot.chat(message)
1681
1707
 
@@ -1711,6 +1737,8 @@ const cow = bot.nearestEntity(entity => entity.name.toLowerCase() === 'cow') //
1711
1737
 
1712
1738
  Возвращает число, которое используется методом `bot.removeChatPattern()` лишь для того, чтобы можно было удалить этот шаблон.
1713
1739
 
1740
+ - :eyes: см. [examples/chat_parsing](https://github.com/PrismarineJS/mineflayer/blob/master/examples/chat_parsing.js#L17-L36)
1741
+
1714
1742
  #### bot.addChatPatternSet(name, patterns, chatPatternOptions)
1715
1743
 
1716
1744
  Создаёт событие, который вызывается каждый раз, когда сообщения совпадают с шаблонами.
@@ -1723,6 +1751,8 @@ const cow = bot.nearestEntity(entity => entity.name.toLowerCase() === 'cow') //
1723
1751
 
1724
1752
  Возвращает число, которое используется методом `bot.removeChatPattern()` лишь для того, чтобы можно было удалить этот шаблон.
1725
1753
 
1754
+ - :eyes: см. [examples/chat_parsing](https://github.com/PrismarineJS/mineflayer/blob/master/examples/chat_parsing.js#L17-L36)
1755
+
1726
1756
  #### bot.removeChatPattern(name)
1727
1757
 
1728
1758
  Удаляет шаблон(ы) чата.
@@ -2110,6 +2140,10 @@ bot.once('login', () => {
2110
2140
 
2111
2141
  Это функция основана на промисе. Она ожидает определённое количество игровых тиков перед продолжением. Может быть полезно для быстрых таймеров, который требуют особых задержек, независимо от заданной физической скорости тиканья бота. Это похоже на стандартную функцию Javascript `setTimeout`, но выполняется специально по физическому таймеру бота.
2112
2142
 
2143
+ #### bot.respawn()
2144
+
2145
+ Когда выключена настройка `respawn`, вы можете вызвать этот метод для ручного возрождения.
2146
+
2113
2147
  ### Методы инвентаря низкого уровня
2114
2148
 
2115
2149
  Эти методы могут быть иногда полезны, но мы рекомендуем использовать методы, описанные выше.
@@ -2117,8 +2151,20 @@ bot.once('login', () => {
2117
2151
  #### bot.clickWindow(slot, mouseButton, mode)
2118
2152
 
2119
2153
  Эта функция возвращает `Promise` с `void` в качестве аргумента при завершении.
2120
-
2121
- Единственное действительное значение для `mode` - 0. Нажатие с шифтом или перемещение через мышь не реализовано.
2154
+
2155
+ Поддержка mode:
2156
+ - стабильно:
2157
+ - клик мышью (0)
2158
+
2159
+ - экспериментально:
2160
+ - клик с шифтом (1)
2161
+ - клик цифрой (2)
2162
+ - клик колёсиком (3)
2163
+ - выкидывающий клик (4)
2164
+
2165
+ - не реализовано:
2166
+ - драг клик (5)
2167
+ - двойной клик (6)
2122
2168
 
2123
2169
  Нажимает на текущее окно. Подробнее - https://minecraft.wiki/w/Protocol#Click_Container
2124
2170
 
package/docs/tutorial.md CHANGED
@@ -557,8 +557,8 @@ In general, you'll want to use `for of` instead of `for in` so make sure you don
557
557
 
558
558
  ### Creating an event from chat
559
559
 
560
- You can create your own event from chat using [`bot.chatAddPattern()`](http://prismarinejs.github.io/mineflayer/#/api?id=botchataddpatternpattern-chattype-description) method. Useful for Bukkit servers where the chat format changes a lot.
561
- [`bot.chatAddPattern()`](http://prismarinejs.github.io/mineflayer/#/api?id=botchataddpatternpattern-chattype-description) method takes three arguments :
560
+ You can create your own event from chat using [`bot.addChatPattern()`](http://prismarinejs.github.io/mineflayer/#/api?id=botaddchatpatternname-pattern-chatpatternoptions) method. Useful for Bukkit servers where the chat format changes a lot.
561
+ [`bot.addChatPattern()`](http://prismarinejs.github.io/mineflayer/#/api?id=botaddchatpatternname-pattern-chatpatternoptions) method takes three arguments :
562
562
 
563
563
  - `pattern` - regular expression (regex) to match chat
564
564
  - `chatType` - the event the bot emits when the pattern matches. e.g. "chat" or "whisper"
@@ -575,7 +575,7 @@ Examples :
575
575
  Here we're creating a bot that answer 'hello' from the other player.
576
576
 
577
577
  ```js
578
- bot.chatAddPattern(
578
+ bot.addChatPattern(
579
579
  /(helo|hello|Hello)/,
580
580
  'hello',
581
581
  'Someone says hello'
@@ -601,7 +601,7 @@ Custom chat example:
601
601
  ```
602
602
 
603
603
  ```js
604
- bot.chatAddPattern(
604
+ bot.addChatPattern(
605
605
  /^\[(.+)\] (\S+) > (.+)$/,
606
606
  'my_chat_event',
607
607
  'Custom chat event'
package/lib/loader.js CHANGED
@@ -47,6 +47,8 @@ const plugins = {
47
47
 
48
48
  const minecraftData = require('minecraft-data')
49
49
  const { testedVersions, latestSupportedVersion, oldestSupportedVersion } = require('./version')
50
+ const latestSupportedProtocolVersion = minecraftData.versionsByMinecraftVersion.pc[latestSupportedVersion].version
51
+ if (!latestSupportedProtocolVersion) throw new Error(`Version '${latestSupportedVersion}' not supported by minecraft-data - is it up to date?`)
50
52
 
51
53
  module.exports = {
52
54
  createBot,
@@ -118,7 +120,7 @@ function createBot (options = {}) {
118
120
  if (!bot.registry?.version) throw new Error(`Server version '${serverPingVersion}' is not supported, no data for version`)
119
121
 
120
122
  const versionData = bot.registry.version
121
- if (versionData['>'](latestSupportedVersion)) {
123
+ if (versionData['>'](latestSupportedVersion) && (versionData.version !== latestSupportedProtocolVersion)) {
122
124
  throw new Error(`Server version '${serverPingVersion}' is not supported. Latest supported version is '${latestSupportedVersion}'.`)
123
125
  } else if (versionData['<'](oldestSupportedVersion)) {
124
126
  throw new Error(`Server version '${serverPingVersion}' is not supported. Oldest supported version is '${oldestSupportedVersion}'.`)
@@ -271,7 +271,12 @@ function inject (bot) {
271
271
  entity.pitch = conv.fromNotchianPitchByte(packet.pitch)
272
272
  entity.headPitch = conv.fromNotchianPitchByte(packet.headPitch)
273
273
 
274
- const notchVel = new Vec3(packet.velocityX, packet.velocityY, packet.velocityZ)
274
+ let notchVel
275
+ if (bot.supportFeature('entityVelocityIsLpVec3')) {
276
+ notchVel = new Vec3(packet.velocity.x, packet.velocity.y, packet.velocity.z)
277
+ } else {
278
+ notchVel = new Vec3(packet.velocityX, packet.velocityY, packet.velocityZ)
279
+ }
275
280
  entity.velocity.update(conv.fromNotchVelocity(notchVel))
276
281
  entity.metadata = parseMetadata(packet.metadata, entity.metadata)
277
282
 
@@ -281,7 +286,12 @@ function inject (bot) {
281
286
  bot._client.on('entity_velocity', (packet) => {
282
287
  // entity velocity
283
288
  const entity = fetchEntity(packet.entityId)
284
- const notchVel = new Vec3(packet.velocityX, packet.velocityY, packet.velocityZ)
289
+ let notchVel
290
+ if (bot.supportFeature('entityVelocityIsLpVec3')) {
291
+ notchVel = new Vec3(packet.velocity.x, packet.velocity.y, packet.velocity.z)
292
+ } else {
293
+ notchVel = new Vec3(packet.velocityX, packet.velocityY, packet.velocityZ)
294
+ }
285
295
  entity.velocity.update(conv.fromNotchVelocity(notchVel))
286
296
  })
287
297
 
@@ -348,7 +358,7 @@ function inject (bot) {
348
358
  bot._client.on('sync_entity_position', (packet) => {
349
359
  const entity = fetchEntity(packet.entityId)
350
360
  entity.position.set(packet.x, packet.y, packet.z)
351
- entity.velocity.update(packet.dx, packet.dy, packet.dz)
361
+ entity.velocity.set(packet.dx, packet.dy, packet.dz)
352
362
  entity.yaw = packet.yaw
353
363
  entity.pitch = packet.pitch
354
364
  bot.emit('entityMoved', entity)
@@ -5,7 +5,8 @@ module.exports = inject
5
5
  function inject (bot) {
6
6
  bot.spawnPoint = new Vec3(0, 0, 0)
7
7
  bot._client.on('spawn_position', (packet) => {
8
- bot.spawnPoint = new Vec3(packet.location.x, packet.location.y, packet.location.z)
8
+ const pos = bot.supportFeature('spawnPositionIsGlobal') ? packet.globalPos.location : packet.location
9
+ bot.spawnPoint = new Vec3(pos.x, pos.y, pos.z)
9
10
  bot.emit('game')
10
11
  })
11
12
  }
package/lib/version.js CHANGED
@@ -1,4 +1,4 @@
1
- const testedVersions = ['1.8.8', '1.9.4', '1.10.2', '1.11.2', '1.12.2', '1.13.2', '1.14.4', '1.15.2', '1.16.5', '1.17.1', '1.18.2', '1.19', '1.19.2', '1.19.3', '1.19.4', '1.20.1', '1.20.2', '1.20.4', '1.20.6', '1.21.1', '1.21.3', '1.21.4', '1.21.5', '1.21.6']
1
+ const testedVersions = ['1.8.8', '1.9.4', '1.10.2', '1.11.2', '1.12.2', '1.13.2', '1.14.4', '1.15.2', '1.16.5', '1.17.1', '1.18.2', '1.19', '1.19.2', '1.19.3', '1.19.4', '1.20.1', '1.20.2', '1.20.4', '1.20.6', '1.21.1', '1.21.3', '1.21.4', '1.21.5', '1.21.6', '1.21.8', '1.21.9']
2
2
  module.exports = {
3
3
 
4
4
  testedVersions,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mineflayer",
3
- "version": "4.32.0",
3
+ "version": "4.34.0",
4
4
  "description": "create minecraft bots with a stable, high level API",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -21,8 +21,8 @@
21
21
  },
22
22
  "license": "MIT",
23
23
  "dependencies": {
24
- "minecraft-data": "^3.76.0",
25
- "minecraft-protocol": "^1.60.0",
24
+ "minecraft-data": "^3.98.0",
25
+ "minecraft-protocol": "^1.63.0",
26
26
  "prismarine-biome": "^1.1.1",
27
27
  "prismarine-block": "^1.22.0",
28
28
  "prismarine-chat": "^1.7.1",
@@ -37,6 +37,7 @@
37
37
  "prismarine-world": "^3.6.0",
38
38
  "protodef": "^1.18.0",
39
39
  "typed-emitter": "^1.0.0",
40
+ "uuid-1345": "^1.0.2",
40
41
  "vec3": "^0.1.7"
41
42
  },
42
43
  "devDependencies": {