Я пытаюсь создать бот Minecraft Mineflayer, который загружает Ender Pearls в камеры Pearl Stasis, заставляя его взаимодействовать с люком в координатах, которые указаны в базе данных Postgres. Я много пробовал, но это не меняет состояние люка. Вот мой код. Есть предложения? < /P>
import mineflayer from 'mineflayer';
import pathfinderPkg from 'mineflayer-pathfinder';
const { pathfinder, Movements, goals } = pathfinderPkg;
import pg from 'pg';
import fetch from 'node-fetch';
import { Vec3 } from 'vec3';
import mcData from 'minecraft-data';
const { Client } = pg;
const { GoalNear } = goals;
const BOT_CONFIG = {
host: 'localhost',
port: 25565,
username: '33_x',
auth: 'microsoft',
version: '1.21.4',
dbConfig: {
user: 'postgres',
host: 'localhost',
database: 'remotepearl',
password: 'postgres',
port: 5432,
},
tableName: 'accounts',
columnUUID: 'uuid',
columnX: 'x',
columnY: 'y',
columnZ: 'z',
columnWorld: 'world',
TPLookupCommand: '?tp',
ActivationRetryCount: 3,
ActivationRetryDelay: 1500,
TrapdoorSearchRadius: 3,
AntiAFKSneakInterval: 10000,
AntiAFKSneakDuration: 500,
};
const taskQueue = [];
let isProcessingTask = false;
function addTask(task) {
taskQueue.push(task);
processQueue();
}
async function processQueue() {
if (isProcessingTask || taskQueue.length === 0) return;
isProcessingTask = true;
const task = taskQueue.shift();
try {
await task();
} catch (error) {
console.error('Task failed:', error);
} finally {
isProcessingTask = false;
processQueue();
}
}
async function getUuidFromUsername(username) {
try {
const response = await fetch(`https://api.mojang.com/users/profiles/m ... ${username}`);
if (!response.ok) return null;
const data = await response.json();
return data?.id;
} catch {
return null;
}
}
async function retryOperation(func, maxRetries, delayMs) {
for (let i = 0; i < maxRetries; i++) {
try {
return await func();
} catch (error) {
if (i < maxRetries - 1) {
await new Promise(resolve => setTimeout(resolve, delayMs));
} else {
throw error;
}
}
}
}
function getNearbyTrapdoor(center, range) {
for (let dx = -range; dx {
if (username === bot.username) return;
const args = message.trim().split(' ');
const command = args[0];
const targetPlayer = args[1];
if (command === BOT_CONFIG.TPLookupCommand && targetPlayer) {
addTask(() => handleTpCommand(username, targetPlayer));
}
});
function startAntiAFK() {
setInterval(() => {
if (!isProcessingTask) {
bot.setControlState('sneak', true);
setTimeout(() => bot.setControlState('sneak', false), BOT_CONFIG.AntiAFKSneakDuration);
}
}, BOT_CONFIG.AntiAFKSneakInterval);
}
async function handleTpCommand(requesterName, targetName) {
const dbClient = new Client(BOT_CONFIG.dbConfig);
try {
const uuid = await getUuidFromUsername(targetName);
if (!uuid) return;
await dbClient.connect();
const dbResult = await dbClient.query(
`SELECT "${BOT_CONFIG.columnX}", "${BOT_CONFIG.columnY}", "${BOT_CONFIG.columnZ}", "${BOT_CONFIG.columnWorld}"
FROM ${BOT_CONFIG.tableName}
WHERE "${BOT_CONFIG.columnUUID}" = $1`,
[uuid]
);
if (dbResult.rows.length === 0) return;
const { x, y, z, world } = dbResult.rows[0];
const dbCenterPos = new Vec3(x, y, z);
const targetDimension = world.toLowerCase().replace('minecraft:', '');
if (!bot.game.dimension.includes(targetDimension)) return;
const blockToClick = getNearbyTrapdoor(dbCenterPos, BOT_CONFIG.TrapdoorSearchRadius);
if (!blockToClick) throw new Error('Trapdoor not found');
const trapdoorPos = blockToClick.position;
const botStandPos = trapdoorPos.offset(0, 0, 1);
const pathfindingGoal = new GoalNear(botStandPos.x, botStandPos.y, botStandPos.z, 0);
bot.clearControlStates();
try {
await bot.pathfinder.goto(pathfindingGoal);
} catch {
if (bot.entity.position.distanceTo(botStandPos.offset(0.5, 0.5, 0.5)) > 1.5) throw new Error('Pathfinding failed');
}
bot.pathfinder.stop();
bot.clearControlStates();
await bot.waitForTicks(2);
await safeActivateBlock(blockToClick, targetName);
} catch (error) {
bot.pathfinder.stop();
bot.clearControlStates();
bot.setControlState('sneak', false);
console.error(error.message);
} finally {
if (dbClient) await dbClient.end();
}
}
< /code>
Я попытался изменить способ взаимодействия, но ничего не работает. Если он работает хорошо, он должен взаимодействовать с определенным блоком и сделать это состояниями этого блока, блок, который является люком, который он должен закрыть, что делает Ender Pearl Despawn и телепортируя игрока.
Подробнее здесь: https://stackoverflow.com/questions/797 ... teractions
Помощь миновых жителей с блочными взаимодействиями ⇐ Javascript
Форум по Javascript
-
Anonymous
1759359300
Anonymous
Я пытаюсь создать бот Minecraft Mineflayer, который загружает Ender Pearls в камеры Pearl Stasis, заставляя его взаимодействовать с люком в координатах, которые указаны в базе данных Postgres. Я много пробовал, но это не меняет состояние люка. Вот мой код. Есть предложения? < /P>
import mineflayer from 'mineflayer';
import pathfinderPkg from 'mineflayer-pathfinder';
const { pathfinder, Movements, goals } = pathfinderPkg;
import pg from 'pg';
import fetch from 'node-fetch';
import { Vec3 } from 'vec3';
import mcData from 'minecraft-data';
const { Client } = pg;
const { GoalNear } = goals;
const BOT_CONFIG = {
host: 'localhost',
port: 25565,
username: '33_x',
auth: 'microsoft',
version: '1.21.4',
dbConfig: {
user: 'postgres',
host: 'localhost',
database: 'remotepearl',
password: 'postgres',
port: 5432,
},
tableName: 'accounts',
columnUUID: 'uuid',
columnX: 'x',
columnY: 'y',
columnZ: 'z',
columnWorld: 'world',
TPLookupCommand: '?tp',
ActivationRetryCount: 3,
ActivationRetryDelay: 1500,
TrapdoorSearchRadius: 3,
AntiAFKSneakInterval: 10000,
AntiAFKSneakDuration: 500,
};
const taskQueue = [];
let isProcessingTask = false;
function addTask(task) {
taskQueue.push(task);
processQueue();
}
async function processQueue() {
if (isProcessingTask || taskQueue.length === 0) return;
isProcessingTask = true;
const task = taskQueue.shift();
try {
await task();
} catch (error) {
console.error('Task failed:', error);
} finally {
isProcessingTask = false;
processQueue();
}
}
async function getUuidFromUsername(username) {
try {
const response = await fetch(`https://api.mojang.com/users/profiles/minecraft/${username}`);
if (!response.ok) return null;
const data = await response.json();
return data?.id;
} catch {
return null;
}
}
async function retryOperation(func, maxRetries, delayMs) {
for (let i = 0; i < maxRetries; i++) {
try {
return await func();
} catch (error) {
if (i < maxRetries - 1) {
await new Promise(resolve => setTimeout(resolve, delayMs));
} else {
throw error;
}
}
}
}
function getNearbyTrapdoor(center, range) {
for (let dx = -range; dx {
if (username === bot.username) return;
const args = message.trim().split(' ');
const command = args[0];
const targetPlayer = args[1];
if (command === BOT_CONFIG.TPLookupCommand && targetPlayer) {
addTask(() => handleTpCommand(username, targetPlayer));
}
});
function startAntiAFK() {
setInterval(() => {
if (!isProcessingTask) {
bot.setControlState('sneak', true);
setTimeout(() => bot.setControlState('sneak', false), BOT_CONFIG.AntiAFKSneakDuration);
}
}, BOT_CONFIG.AntiAFKSneakInterval);
}
async function handleTpCommand(requesterName, targetName) {
const dbClient = new Client(BOT_CONFIG.dbConfig);
try {
const uuid = await getUuidFromUsername(targetName);
if (!uuid) return;
await dbClient.connect();
const dbResult = await dbClient.query(
`SELECT "${BOT_CONFIG.columnX}", "${BOT_CONFIG.columnY}", "${BOT_CONFIG.columnZ}", "${BOT_CONFIG.columnWorld}"
FROM ${BOT_CONFIG.tableName}
WHERE "${BOT_CONFIG.columnUUID}" = $1`,
[uuid]
);
if (dbResult.rows.length === 0) return;
const { x, y, z, world } = dbResult.rows[0];
const dbCenterPos = new Vec3(x, y, z);
const targetDimension = world.toLowerCase().replace('minecraft:', '');
if (!bot.game.dimension.includes(targetDimension)) return;
const blockToClick = getNearbyTrapdoor(dbCenterPos, BOT_CONFIG.TrapdoorSearchRadius);
if (!blockToClick) throw new Error('Trapdoor not found');
const trapdoorPos = blockToClick.position;
const botStandPos = trapdoorPos.offset(0, 0, 1);
const pathfindingGoal = new GoalNear(botStandPos.x, botStandPos.y, botStandPos.z, 0);
bot.clearControlStates();
try {
await bot.pathfinder.goto(pathfindingGoal);
} catch {
if (bot.entity.position.distanceTo(botStandPos.offset(0.5, 0.5, 0.5)) > 1.5) throw new Error('Pathfinding failed');
}
bot.pathfinder.stop();
bot.clearControlStates();
await bot.waitForTicks(2);
await safeActivateBlock(blockToClick, targetName);
} catch (error) {
bot.pathfinder.stop();
bot.clearControlStates();
bot.setControlState('sneak', false);
console.error(error.message);
} finally {
if (dbClient) await dbClient.end();
}
}
< /code>
Я попытался изменить способ взаимодействия, но ничего не работает. Если он работает хорошо, он должен взаимодействовать с определенным блоком и сделать это состояниями этого блока, блок, который является люком, который он должен закрыть, что делает Ender Pearl Despawn и телепортируя игрока.
Подробнее здесь: [url]https://stackoverflow.com/questions/79780529/mineflayer-assistance-with-block-interactions[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия