• Я зарабатываю 100 000 RUB / месяц на этом сайте!

    А знаешь как? Я всего-лишь публикую (создаю темы), а админ мне платит. Трачу деньги на мороженое, робуксы и сервера в Minecraft. А ещё на паль из Китая. 

    Хочешь так же? Пиши и узнавай условия: https://t.me/alex_redact
    Реклама: https://t.me/yougame_official

Прочее Minebot | Бот шахтер | Не супер умный | mineflayer

Начинающий
Начинающий
Статус
Оффлайн
Регистрация
5 Ноя 2022
Сообщения
70
Реакции
0
Выберите загрузчик игры
  1. Прочие моды
Язык nodejs библиотека mineflayer

Для того что бы бот работал нужно несколько грешков
1 - встать на нужное место в шахте (снизу шахты, на всех анках)
2 - включить на всех анках авто продажу (не обязательно)
3 - на 604 анке он выкидывает мусор (нужно его направить на пустоту)
4 - на 605 анке он чинится
5 - ОТДЕЛЬНЫЙ БОТ для парсинга шахт (т.к я имею бота для евентов и шахт мне не составило проблемм впихнуть в шахтера json с шахтами и парсить саму ближнию)

  • Бот умеет сам покупать опыт и чинить кирку
  • Бот умеет выбрасывать мусор
  • Продает алмазы скупщику
  • Код сырой, и делался на скорую руку
  • Точных анок не помню можете глянуть в коде
- Иногда теряет кирку (скорее всего из за свапов слотов при починки или при выкидывание)
- Данный пост идет как сурс для доработок а не для готовых решений
  • Бот использует прокси
  • Все данные берет из конфига
  • Так же делал телеграмм бота для обновления и просмотра статистики (можете вырезать info_of_bots.json)

source:
Expand Collapse Copy
const mineflayer = require('mineflayer');
const config = require('../configs/config.json');
const path = require('path');
const { exec } = require('child_process');
const socks = require('socks').SocksClient;
const fs = require('fs')
const configPath = path.join(__dirname, '../configs/info_of_bots.json');

const proxy1 = config.proxys.two_proxy;
const proxy2 = config.proxys.three_proxy;
const proxyHost1 = proxy1.host;
const proxyPort1 = proxy1.port;
const proxyLogin1 = proxy1.login;
const proxyPass1 = proxy1.pass;

const proxyHost2 = proxy2.host;
const proxyPort2 = proxy2.port;
const proxyLogin2 = proxy2.login;
const proxyPass2 = proxy2.pass;

async function my_bot(botName, number_bot, useProxy = false, proxyConfig = null) {
    let not_buying = true;
    let buy_pickaxe = false
    let buyed_exp = 0;
    let checkForDiamonds;
    let use_xp = false;
    let anarchy_Code = 0;
    const bot = mineflayer.createBot({
        host: 'mc.funtime.su',
        username: botName,
        version: '1.16.5',
        hideErrors: true,
        connect: (client) => {
            if (useProxy && proxyConfig) {
                console.log('Попытка подключения к прокси...');
                socks.createConnection({
                    proxy: {
                        host: proxyConfig.host,
                        port: proxyConfig.port,
                        type: 5,
                        userId: proxyConfig.login,
                        password: proxyConfig.pass
                    },
                    command: 'connect',
                    destination: {
                        host: 'mc.funtime.su',
                        port: 25565
                    },
                }, (err, info) => {
                    if (err) {
                        console.error('Ошибка соединения с прокси:', err);
                        return;
                    }
                    console.log('Соединение с прокси установлено.');
                    client.setSocket(info.socket);
                    client.emit('connect');
                });
            } else {
                // Подключение без прокси
                client.connect({
                    host: 'mc.funtime.su',
                    port: 25565
                });
            }
        }
    });

    bot.once('spawn', () => {
        inialization();
    });

    bot.on('kicked', (kicked) => {
        console.log([ICODE][БОТ - ${number_bot}] --> ${kicked}[/ICODE]);
        bot.quit();
        setTimeout(() => {
            my_bot(botName, number_bot, useProxy);
        }, 2000);
        return;
    });

    bot.on('error', (error) => {
        console.log([ICODE][БОТ - ${number_bot}] --> ${error}[/ICODE]);
        bot.quit();
        setTimeout(() => {
            my_bot(botName, number_bot, useProxy);
        }, 3000);
        return;
    });

    bot.on('message', async (message) => {
        const messageText = message.toString();
        //console.log(messageText)
        if (messageText.includes('Ваш баланс:')) {
            const balanceNumberString = messageText.match(/[\d,\.]+/)[0];
            const balanceInt = Math.floor(parseFloat(balanceNumberString.replace(/,/g, '')));
            const investAmount = balanceInt - 30000000;
            if (investAmount >= 1) {
                bot.chat([ICODE]/clan invest ${investAmount}[/ICODE]);
            }
        }
       
        const actions = {
            'Вы успешно купили Пузырек опыта': () => {
                buyed_exp++;
                console.log([ICODE][БОТ - ${number_bot}] -> ${messageText}[/ICODE])
                if (buyed_exp === 4) {
                    buyed_exp = 0;
                    not_buying = true;
                    use_xp = true;
                    useXpBottles();
                }
            },
            'Вы успешно купили Кирка Крушителя': () => {
                buy_pickaxe = false
                not_buying = true
                inialization()
            },
            'уже купили': () => {
                console.log([ICODE][БОТ - ${number_bot}] -> ${messageText}[/ICODE])
            },
            'Ваш баланс:': async () => {
                await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { balance: [ICODE]${messageText}[/ICODE] });
            },
            'Вы были кикнуты при подключении к серверу': () => {
                clearInterval(checkForDiamonds);
                inialization();
            },
            'Введите номер с картинки в чат': async () => {
                await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: 'Нужно[I]пройти[/I]каптчу' });
            },
            'После входа на режим необходимо немного подождать перед использованием аукциона': () => {
                buying_exp = true;
                const regex = /(\d+)\s*сек/;
                const match = messageText.match(regex);
                if (match) {
                    const sleep = parseInt(match[1], 10) + 1;
                    console.log([ICODE][БОТ - ${number_bot}] -> Время ожидания аукциона: ${sleep} сек[/ICODE]);
                    setTimeout(() => {
                        bot.chat(current_buy);
                    }, sleep * 1000);
                } else {
                    console.log([ICODE][БОТ - ${number_bot}] -> Время ожидания не найдено.[/ICODE]);
                }
            }
        };
   
        for (const [key, action] of Object.entries(actions)) {
            if (messageText.includes(key)) {
                await action();
                break;
            }
        }
    });
   
    setInterval(async () => {
        health = bot.health;
        if (health <= 5) {
            bot.quit();
            console.log([ICODE][БОТ - ${number_bot}] -> У бота мало хп[/ICODE]);
            await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Мало жизней у бота: ${health} ${anarchy_Code}[/ICODE] });
            return;
        }
        //console.log([ICODE]Жизней у бота: ${health} ${anarchy_Code}[/ICODE]);
    }, 1000);

    async function inialization() {
        setTimeout(async () => {
            bot.chat([ICODE]/an${config.miners.an_trash}[/ICODE]);
            await delay(2000);
            bot.chat('/bal');
            const itemInOffhand = bot.inventory.slots[45];
            if (itemInOffhand) {
                await bot.equip(itemInOffhand, 'hand', (err) => {
                    if (err) {
                        console.log('Ошибка при экипировке предмета:', err);
                    }
                });
            }
            const pickaxe = await bot.inventory.items().find(item => item.name.includes('netherite_pickaxe'));
            if (bot.heldItem && bot.heldItem.name === 'netherite_pickaxe') {
                console.log([ICODE][БОТ - ${number_bot}] -> Кирка уже в руке[/ICODE])
                await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]inialization[/ICODE] });
            } else {
                try {
                    await bot.equip(pickaxe, 'hand');
                    console.log([ICODE][БОТ - ${number_bot}] -> Взял кирку[/ICODE])
                    await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]inialization[/ICODE] });
                } catch (error) {
                    await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Нет кирки[/ICODE] });
                    inialization()
                    return
                }
            }
            if (pickaxe) {
                const item = await bot.entity.equipment[0];
                if (item && item.name.includes('netherite_pickaxe')) {
                    const maxDurability = item.maxDurability;
                    const damage = item.nbt.value.Damage.value;
                    const durability = maxDurability - damage;
                    console.log([ICODE][БОТ - ${number_bot}] -> Прочность кирки: ${durability} / ${maxDurability}[/ICODE]);
                    if (durability <= 350) {
                        bot.chat([ICODE]/an${config.miners.an_fix}[/ICODE]);
                        await delay(1000);
                        not_buying = false;
                        console.log([ICODE][БОТ - ${number_bot}] -> Мало прочности на кирке, начинаю чиниться[/ICODE]);
                        const pickaxe = bot.inventory.items().find(item => item.name === 'netherite_pickaxe');
                        try {
                            await bot.equip(pickaxe, 'off-hand', (err) => { console.log(err); });
                        } catch (error) {
                            console.log([ICODE][БОТ - ${number_bot}] -> Ошибка при экипировке кирки: ${error}[/ICODE]);
                        }
                        const xpBottles = bot.inventory.findInventoryItem('experience_bottle', null);
                        if (xpBottles) {
                            const blockUnderBot = bot.blockAt(bot.entity.position.offset(0, -1, 0));
                            const blockPosition = blockUnderBot.position;
                            await bot.lookAt(blockPosition.offset(0.5, 0.5, 0.5), true, (err) => {
                                if (err) {
                                    console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при повороте бота:[/ICODE], err);
                                } else {}
                            });
                            try {
                                await useXpBottles();
                                use_xp = true;
                            } catch (error) {
                                console.log([ICODE][БОТ - ${number_bot}] -> Ошибка при использовании пузырьков опыта: ${error}[/ICODE]);
                            }
                        } else {
                            console.log([ICODE][БОТ - ${number_bot}] -> Нет пузырьков опыта в инвентаре, начинаю их покупать[/ICODE]);
                            current_buy = '/ah search Пузырек опыта';
                            bot.chat('/ah search Пузырек опыта');
                            buying_exp = true;
                            return;
                        }
                        return;
                    } else {
                        await drop_trash();
                        const inventory = bot.inventory;
                        let index = 0;
                        inventory.items().forEach(item => {
                            index++;
                        });
                        if (index >= 32) {
                            await delay(1000)
                            console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь полный[/ICODE]);
                            bot.chat('/buyer');
                            return;
                        }
                        console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь: ${index}/36[/ICODE]);
                        start_mine();
                    }
                } else {
                    await drop_trash();
                    const inventory = bot.inventory;
                    let index = 0;
                    inventory.items().forEach(item => {
                        index++;
                    });
                    if (index >= 32) {
                        await delay(1000)
                        console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь полный[/ICODE]);
                        bot.chat('/buyer');
                        return;
                    }
                    console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь: ${index}/36[/ICODE]);
                    start_mine();
                }
            } else {}
        }, 1000);
    }

    bot.on('windowOpen', async (window) => {
        console.log([ICODE][БОТ - ${number_bot}] -> Аукцион открыт[/ICODE]);
        let title = String(window.title);
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Oppened_auction[/ICODE] });
        if (title.includes('Выберите секцию')) {
            await delay(2000);
            const items = window.slots;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (item && item.name === 'lapis_lazuli') {
                    try {
                        await bot.clickWindow(index, 0, 0); // Ожидание завершения клика
                    } catch (err) { }
                    return;
                }
            }
        }
        const experienceBottles = [];
        if (title.includes('Скупщик')) {
            await delay(2000);
            const items = window.slots;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (item && item.name === 'experience_bottle') {
                    const customLore = item.customLore;
                    customLore.forEach(lore => {
                        const parsedLore = JSON.parse(lore); // Парсим JSON строку
                        const textContent = parsedLore.extra.map(extra => extra.text).join(''); // Извлекаем текст
                        experienceBottles.push(textContent); // Сохраняем текст в массив
                    });
                    let level, progress, multiplier;

                    experienceBottles.forEach(text => {
                        if (text.includes('Уровень:')) {
                            level = text.match(/Уровень:\s*(\d+)/)[1]; // Извлекаем уровень
                        }
                        if (text.includes('Прогресс:')) {
                            progress = text.match(/Прогресс:\s*([\d.]+)\/(\d+)\s*Стаков/);
                            if (progress) {
                                progress = progress[0]; // Сохраняем весь текст прогресса
                            }
                        }
                        if (text.includes('Множитель:')) {
                            multiplier = text.match(/Множитель:\s*x([\d.]+)/)[1]; // Извлекаем множитель
                        }
                    });

                    // console.log([ICODE]Скупщик Уровень: ${level}[/ICODE]);
                    // console.log([ICODE]Скупщик Прогресс: ${progress}[/ICODE]);
                    // console.log([ICODE]Скупщик Множитель: ${multiplier}[/ICODE]);
                }
                if (item && item.name === 'diamond') {
                    check_buyer = [];
                    item.customLore.forEach(lore => {
                        const parsedLore = JSON.parse(lore);
                        if (parsedLore.extra) {
                            parsedLore.extra.forEach(element => {
                                check_buyer.push([ICODE]${element.color} ${element.text}[/ICODE]);
                            });
                        }
                    });
                    let buyerStatus = 'ОШИБКА: Выберите в баере скупку алмазов на (Продать ВСЁ)'; // По умолчанию
                    let passed = false;
                    check_buyer.forEach(txt => {
                        if (txt.includes('#1CFF00') && txt.includes('ВСЁ')) {
                            buyerStatus = [ICODE]С скупщиком все в порядке[/ICODE];
                            passed = true;
                        }
                    });
                    if (passed) {
                        try {
                            await bot.clickWindow(index, 0, 0); // Ожидание завершения клика
                        } catch (err) { }
                        await bot.closeWindow(window);
                        inialization();
                        return;
                    } else {
                        console.log([ICODE][БОТ - ${number_bot}] -> ${buyerStatus}[/ICODE]);
                    }
                }
            }
        }
        if (title.includes('Поиск')) {
            if (not_buying) {
                await bot.closeWindow(window);
                start_mine();
                return;
            }
            const items = window.slots;
            item_founded = false;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (index >= 49) {
                    return;
                }
                if (item) {
                    const item_lore = item.customLore;
                    const jsonString = [ICODE][${item_lore}][/ICODE];
                    try {
                        const loreArray = JSON.parse(jsonString);
                        let price = '';
                        let time = '';
                        let sellerName;
                        loreArray.forEach(item => {
                            if (item.extra) {
                                item.extra.forEach((extraItem, index, array) => {
                                    if (extraItem.text) {
                                        if (extraItem.text.includes('Прoдaвeц:')) {
                                            const nextItem = array[index + 1];
                                            sellerName = [ICODE]${nextItem.text.trim()}[/ICODE];
                                            seller = sellerName;
                                        }
                                        if (extraItem.text.includes('Ценa') || extraItem.text.includes('$')) {
                                            price += extraItem.text.trim() + ' ';
                                        }
                                        if (extraItem.text.match(/\d+\sч\.\s\d+\sмин\.\s\d+\sсек\./)) {
                                            time = extraItem.text.match(/\d+\sч\.\s\d+\sмин\.\s\d+\sсек\./)[0];
                                        }

                                        if (!time) {
                                            time = '9ч.';
                                        }
                                    }
                                });
                            }
                        });
                        price = parseInt(price.replace(/[^0-9]/g, '').trim(), 10);
                        if (item.name === 'experience_bottle') {
                            if (price <= 160000 && item.count >= 60) {
                                item_founded = true;
                                console.log([ICODE][БОТ - ${number_bot}] -> Цена: ${price} Кол-во: ${item.count} Продавец ${sellerName} Истечет: ${time}[/ICODE]);
                                await delay(600);
                                await click_slot(index);
                                return;
                            }
                        }
                    } catch (error) {
                        console.log([ICODE]Error ${error}[/ICODE]);
                    }
                } else {
                    try {
                        await delay(550);
                        await click_slot(49);
                        return;
                    } catch (error) {
                        console.log([ICODE]Error ${error}[/ICODE]);
                    }
                }
            }
            if (item_founded === false) {
                bot.closeWindow(window);
                await delay(900);
                bot.chat(current_buy);
            }
        } else if (title.includes('Подозрительная цена!')) {
            const items = window.slots;
            item_founded = false;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (index >= 49) {
                    return;
                }
                if (item) {
                    if (item.name.includes('glass')) {
                        await delay(500);
                        await click_slot(index);
                        return;
                    }
                }
            }
        }
    });

    async function get_anarchy() {
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]get_anarchy[/ICODE] });
        try {
            const fs = require('fs').promises;
            const data = await fs.readFile('event_mine_parser\\data\\data.json', 'utf8');
            const jsonData = JSON.parse(data);
            const mines = jsonData.mines;
            const sortedMines = mines.sort((a, b) => parseInt(a.time) - parseInt(b.time));
            const minTime = Math.min(...sortedMines.map(mine => parseInt(mine.time)));
            for (const mine of sortedMines) {
                if (parseInt(mine.time) >= 2 && mine.anarchy != config.miners.an_fix || mine.anarchy != config.miners.an_trash) {
                    //console.log([ICODE][БОТ - ${number_bot}] -> rare: ${mine.rare}, anarchy: ${mine.anarchy}, time: ${mine.time}[/ICODE]);
                    return [mine.anarchy, mine.time]; // Возвращаем массив
                }
            }
            console.log([ICODE][БОТ - ${number_bot}] -> Нет подходящих элементов.[/ICODE]);
            return null;
        } catch (err) {
            console.error('Ошибка при чтении файла:', err);
            inialization()
        }
    }

    async function start_mine() {
        if (use_xp) { return }
        if (buy_pickaxe) { return }
        let not_found = 0;
        const [an_code, time] = await get_anarchy();
        anarchy_Code = an_code;
        time_to_start = parseInt(time) - 1;
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Wait_mine[/ICODE] });
        startCountdown(parseInt(time_to_start));
        await delay(parseInt(time_to_start) * 1400);
        if (an_code) {
            bot.chat([ICODE]/an${an_code}[/ICODE]);
        } else {
            console.log([ICODE][БОТ - ${number_bot}] -> Не удалось получить код анархии[/ICODE]);
            return;
        }
        let checkCompleted = false;
        checkForDiamonds = setInterval(async () => {
            try {
                const blocksToDig = [];
                const radius = 5;
                for (let x = -radius; x <= radius; x++) {
                    for (let y = -radius; y <= radius; y++) {
                        for (let z = -radius; z <= radius; z++) {
                            try {
                                const block = bot.blockAt(bot.entity.position.offset(x, y, z));
                                if (block.name === 'diamond_ore') {
                                    blocksToDig.push(block);
                                }
                            } catch (error) {}
                        }
                    }
                }
                if (blocksToDig.length > 0) {
                    for (const block of blocksToDig) {
                        try {
                            await bot.dig(block, true);
                            await console.log([ICODE][БОТ - ${number_bot}] -> Сломал: ${block.position.x}, ${block.position.y}, ${block.position.z}[/ICODE]);
                        } catch (err) {
                            await console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при разрушении блока: ${err}[/ICODE]);
                        }
                    }

                    if (!checkCompleted) {
                        clearInterval(checkForDiamonds);
                        checkCompleted = true;
                        inialization();
                    }
                } else {
                    not_found++;
                }
                if (not_found >= 8) {
                    clearInterval(checkForDiamonds);
                    checkCompleted = true
                    inialization();
                }
            } catch (err) { console.log(err); }
        }, 500);
    }

    async function click_slot(index) {
        try {
            bot.clickWindow(index, 0, 1)
                .catch(() => { });
        } catch (err) { }
    }

    async function useXpBottles() {
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Fix_pickaxe[/ICODE] });
        let xpBottles = bot.inventory.findInventoryItem('experience_bottle');
       
        if (!xpBottles) {
            console.log([ICODE][БОТ - ${number_bot}] -> Весь опыт использован[/ICODE]);
            use_xp = false;
            buying_exp = false;
            inialization();
            return;
        }
   
        try {
            if (bot.heldItem && bot.heldItem.name === 'experience_bottle') {
                await bot.activateItem();
                console.log([ICODE][БОТ - ${number_bot}] -> Использовал пузырьки опыта[/ICODE]);
            } else {
                await bot.equip(xpBottles, 'hand');
            }
        } catch (error) {
            console.log([ICODE][БОТ - ${number_bot}] -> Ошибка при использовании пузырьков опыта: ${error}[/ICODE]);
            inialization();
            return;
        }
   
        // Используем пузырьки опыта с задержкой
        setTimeout(useXpBottles, 200);
    }
   

    async function drop_trash() {
        bot.chat([ICODE]/an${config.miners.an_trash}[/ICODE]);
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]drop_trash[/ICODE] });
        await delay(1000);
        const inventory = await bot.inventory.items();
        if (inventory.length === 0) {
            console.log('Инвентарь пуст.');
            return;
        }
        for (const item of inventory) {
            if (item.name === 'netherite_pickaxe' || item.name === 'diamond' || item.name === 'experience_bottle') {
                continue;
            }
            try {
                await bot.toss(item.type, null, item.count);
                console.log([ICODE][БОТ - ${number_bot}] -> Выбросил: ${item.name}[/ICODE]);
                if (item.name === 'netherite_pickaxe') {
                    console.log([ICODE][БОТ - ${number_bot}] -> ВЫБРОСИЛ: ${item.name}\n[БОТ - ${number_bot}] -> ВЫБРОСИЛ: ${item.name}\n[БОТ - ${number_bot}] -> ВЫБРОСИЛ: ${item.name}[/ICODE])
                }
            } catch (err) {
                console.log([ICODE][БОТ - ${number_bot}] -> Ошибка выбрасывании предмета ${item.name}[/ICODE]);
            }
            await delay(400)
        }
        return;
    }
    function updateJson(filePath, botName, updates) {
        try {
            const data = fs.readFileSync(filePath, 'utf8');
            let jsonData;
            try {
                jsonData = JSON.parse(data);
            } catch (parseErr) {
                console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при парсинге JSON:[/ICODE], parseErr);
                const data = {
                    "bot1_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot2_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot3_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot4_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot5_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot6_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot7_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot8_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot9_mine": {
                        "task": "",
                        "balance": "0"
                    }
                };
               
                fs.writeFileSync(filePath, JSON.stringify(data, null, 4), 'utf8');              
                return;
            }
            if (jsonData[botName]) {
                if (updates.balance !== undefined) {
                    jsonData[botName].balance = updates.balance;
                }
                if (updates.task !== undefined) {
                    jsonData[botName].task = updates.task;
                }
                fs.writeFileSync(filePath, JSON.stringify(jsonData, null, 4), 'utf8');
            } else {
                console.log([ICODE][БОТ - ${number_bot}] -> Бот не найден[/ICODE]);
            }
        } catch (err) {
            console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при чтении или записи файла:[/ICODE], err);
        }
    }  

    function startCountdown(seconds) {
        let remainingTime = seconds;
        const intervalId = setInterval(() => {
            console.log([ICODE][БОТ - ${number_bot}] -> До шахты - ${remainingTime}[/ICODE]);
            remainingTime--;

            if (remainingTime < 0) {
                clearInterval(intervalId);
            }
        }, 1000);
    }

    function delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}


async function startBots() {
    const bot1Name = config.miners.bot1_name;  
    const bot2Name = config.miners.bot2_name;
    await Promise.all([
        my_bot(bot1Name, 1, false),
        my_bot(bot2Name, 2, false),
    ]);
}

// Запускаем ботов
startBots().catch(err => console.error('Ошибка при запуске ботов:', err));
 
Последнее редактирование:
Язык nodejs библиотека mineflayer

Для того что бы бот работал нужно несколько грешков
1 - встать на нужное место в шахте (снизу шахты, на всех анках)
2 - включить на всех анках авто продажу (не обязательно)
3 - на 604 анке он выкидывает мусор (нужно его направить на пустоту)
4 - на 605 анке он чинится
5 - ОТДЕЛЬНЫЙ БОТ для парсинга шахт (т.к я имею бота для евентов и шахт мне не составило проблемм впихнуть в шахтера json с шахтами и парсить саму ближнию)

  • Бот умеет сам покупать опыт и чинить кирку
  • Бот умеет выбрасывать мусор
  • Продает алмазы скупщику
  • Код сырой, и делался на скорую руку
  • Точных анок не помню можете глянуть в коде
- Иногда теряет кирку (скорее всего из за свапов слотов при починки или при выкидывание)
- Данный пост идет как сурс для доработок а не для готовых решений
  • Бот использует прокси
  • Все данные берет из конфига
  • Так же делал телеграмм бота для обновления и просмотра статистики (можете вырезать info_of_bots.json)

source:
Expand Collapse Copy
const mineflayer = require('mineflayer');
const config = require('../configs/config.json');
const path = require('path');
const { exec } = require('child_process');
const socks = require('socks').SocksClient;
const fs = require('fs')
const configPath = path.join(__dirname, '../configs/info_of_bots.json');

const proxy1 = config.proxys.two_proxy;
const proxy2 = config.proxys.three_proxy;
const proxyHost1 = proxy1.host;
const proxyPort1 = proxy1.port;
const proxyLogin1 = proxy1.login;
const proxyPass1 = proxy1.pass;

const proxyHost2 = proxy2.host;
const proxyPort2 = proxy2.port;
const proxyLogin2 = proxy2.login;
const proxyPass2 = proxy2.pass;

async function my_bot(botName, number_bot, useProxy = false, proxyConfig = null) {
    let not_buying = true;
    let buy_pickaxe = false
    let buyed_exp = 0;
    let checkForDiamonds;
    let use_xp = false;
    let anarchy_Code = 0;
    const bot = mineflayer.createBot({
        host: 'mc.funtime.su',
        username: botName,
        version: '1.16.5',
        hideErrors: true,
        connect: (client) => {
            if (useProxy && proxyConfig) {
                console.log('Попытка подключения к прокси...');
                socks.createConnection({
                    proxy: {
                        host: proxyConfig.host,
                        port: proxyConfig.port,
                        type: 5,
                        userId: proxyConfig.login,
                        password: proxyConfig.pass
                    },
                    command: 'connect',
                    destination: {
                        host: 'mc.funtime.su',
                        port: 25565
                    },
                }, (err, info) => {
                    if (err) {
                        console.error('Ошибка соединения с прокси:', err);
                        return;
                    }
                    console.log('Соединение с прокси установлено.');
                    client.setSocket(info.socket);
                    client.emit('connect');
                });
            } else {
                // Подключение без прокси
                client.connect({
                    host: 'mc.funtime.su',
                    port: 25565
                });
            }
        }
    });

    bot.once('spawn', () => {
        inialization();
    });

    bot.on('kicked', (kicked) => {
        console.log([ICODE][БОТ - ${number_bot}] --> ${kicked}[/ICODE]);
        bot.quit();
        setTimeout(() => {
            my_bot(botName, number_bot, useProxy);
        }, 2000);
        return;
    });

    bot.on('error', (error) => {
        console.log([ICODE][БОТ - ${number_bot}] --> ${error}[/ICODE]);
        bot.quit();
        setTimeout(() => {
            my_bot(botName, number_bot, useProxy);
        }, 3000);
        return;
    });

    bot.on('message', async (message) => {
        const messageText = message.toString();
        //console.log(messageText)
        if (messageText.includes('Ваш баланс:')) {
            const balanceNumberString = messageText.match(/[\d,\.]+/)[0];
            const balanceInt = Math.floor(parseFloat(balanceNumberString.replace(/,/g, '')));
            const investAmount = balanceInt - 30000000;
            if (investAmount >= 1) {
                bot.chat([ICODE]/clan invest ${investAmount}[/ICODE]);
            }
        }
      
        const actions = {
            'Вы успешно купили Пузырек опыта': () => {
                buyed_exp++;
                console.log([ICODE][БОТ - ${number_bot}] -> ${messageText}[/ICODE])
                if (buyed_exp === 4) {
                    buyed_exp = 0;
                    not_buying = true;
                    use_xp = true;
                    useXpBottles();
                }
            },
            'Вы успешно купили Кирка Крушителя': () => {
                buy_pickaxe = false
                not_buying = true
                inialization()
            },
            'уже купили': () => {
                console.log([ICODE][БОТ - ${number_bot}] -> ${messageText}[/ICODE])
            },
            'Ваш баланс:': async () => {
                await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { balance: [ICODE]${messageText}[/ICODE] });
            },
            'Вы были кикнуты при подключении к серверу': () => {
                clearInterval(checkForDiamonds);
                inialization();
            },
            'Введите номер с картинки в чат': async () => {
                await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: 'Нужно[I]пройти[/I]каптчу' });
            },
            'После входа на режим необходимо немного подождать перед использованием аукциона': () => {
                buying_exp = true;
                const regex = /(\d+)\s*сек/;
                const match = messageText.match(regex);
                if (match) {
                    const sleep = parseInt(match[1], 10) + 1;
                    console.log([ICODE][БОТ - ${number_bot}] -> Время ожидания аукциона: ${sleep} сек[/ICODE]);
                    setTimeout(() => {
                        bot.chat(current_buy);
                    }, sleep * 1000);
                } else {
                    console.log([ICODE][БОТ - ${number_bot}] -> Время ожидания не найдено.[/ICODE]);
                }
            }
        };
  
        for (const [key, action] of Object.entries(actions)) {
            if (messageText.includes(key)) {
                await action();
                break;
            }
        }
    });
  
    setInterval(async () => {
        health = bot.health;
        if (health <= 5) {
            bot.quit();
            console.log([ICODE][БОТ - ${number_bot}] -> У бота мало хп[/ICODE]);
            await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Мало жизней у бота: ${health} ${anarchy_Code}[/ICODE] });
            return;
        }
        //console.log([ICODE]Жизней у бота: ${health} ${anarchy_Code}[/ICODE]);
    }, 1000);

    async function inialization() {
        setTimeout(async () => {
            bot.chat([ICODE]/an${config.miners.an_trash}[/ICODE]);
            await delay(2000);
            bot.chat('/bal');
            const itemInOffhand = bot.inventory.slots[45];
            if (itemInOffhand) {
                await bot.equip(itemInOffhand, 'hand', (err) => {
                    if (err) {
                        console.log('Ошибка при экипировке предмета:', err);
                    }
                });
            }
            const pickaxe = await bot.inventory.items().find(item => item.name.includes('netherite_pickaxe'));
            if (bot.heldItem && bot.heldItem.name === 'netherite_pickaxe') {
                console.log([ICODE][БОТ - ${number_bot}] -> Кирка уже в руке[/ICODE])
                await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]inialization[/ICODE] });
            } else {
                try {
                    await bot.equip(pickaxe, 'hand');
                    console.log([ICODE][БОТ - ${number_bot}] -> Взял кирку[/ICODE])
                    await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]inialization[/ICODE] });
                } catch (error) {
                    await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Нет кирки[/ICODE] });
                    inialization()
                    return
                }
            }
            if (pickaxe) {
                const item = await bot.entity.equipment[0];
                if (item && item.name.includes('netherite_pickaxe')) {
                    const maxDurability = item.maxDurability;
                    const damage = item.nbt.value.Damage.value;
                    const durability = maxDurability - damage;
                    console.log([ICODE][БОТ - ${number_bot}] -> Прочность кирки: ${durability} / ${maxDurability}[/ICODE]);
                    if (durability <= 350) {
                        bot.chat([ICODE]/an${config.miners.an_fix}[/ICODE]);
                        await delay(1000);
                        not_buying = false;
                        console.log([ICODE][БОТ - ${number_bot}] -> Мало прочности на кирке, начинаю чиниться[/ICODE]);
                        const pickaxe = bot.inventory.items().find(item => item.name === 'netherite_pickaxe');
                        try {
                            await bot.equip(pickaxe, 'off-hand', (err) => { console.log(err); });
                        } catch (error) {
                            console.log([ICODE][БОТ - ${number_bot}] -> Ошибка при экипировке кирки: ${error}[/ICODE]);
                        }
                        const xpBottles = bot.inventory.findInventoryItem('experience_bottle', null);
                        if (xpBottles) {
                            const blockUnderBot = bot.blockAt(bot.entity.position.offset(0, -1, 0));
                            const blockPosition = blockUnderBot.position;
                            await bot.lookAt(blockPosition.offset(0.5, 0.5, 0.5), true, (err) => {
                                if (err) {
                                    console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при повороте бота:[/ICODE], err);
                                } else {}
                            });
                            try {
                                await useXpBottles();
                                use_xp = true;
                            } catch (error) {
                                console.log([ICODE][БОТ - ${number_bot}] -> Ошибка при использовании пузырьков опыта: ${error}[/ICODE]);
                            }
                        } else {
                            console.log([ICODE][БОТ - ${number_bot}] -> Нет пузырьков опыта в инвентаре, начинаю их покупать[/ICODE]);
                            current_buy = '/ah search Пузырек опыта';
                            bot.chat('/ah search Пузырек опыта');
                            buying_exp = true;
                            return;
                        }
                        return;
                    } else {
                        await drop_trash();
                        const inventory = bot.inventory;
                        let index = 0;
                        inventory.items().forEach(item => {
                            index++;
                        });
                        if (index >= 32) {
                            await delay(1000)
                            console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь полный[/ICODE]);
                            bot.chat('/buyer');
                            return;
                        }
                        console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь: ${index}/36[/ICODE]);
                        start_mine();
                    }
                } else {
                    await drop_trash();
                    const inventory = bot.inventory;
                    let index = 0;
                    inventory.items().forEach(item => {
                        index++;
                    });
                    if (index >= 32) {
                        await delay(1000)
                        console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь полный[/ICODE]);
                        bot.chat('/buyer');
                        return;
                    }
                    console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь: ${index}/36[/ICODE]);
                    start_mine();
                }
            } else {}
        }, 1000);
    }

    bot.on('windowOpen', async (window) => {
        console.log([ICODE][БОТ - ${number_bot}] -> Аукцион открыт[/ICODE]);
        let title = String(window.title);
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Oppened_auction[/ICODE] });
        if (title.includes('Выберите секцию')) {
            await delay(2000);
            const items = window.slots;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (item && item.name === 'lapis_lazuli') {
                    try {
                        await bot.clickWindow(index, 0, 0); // Ожидание завершения клика
                    } catch (err) { }
                    return;
                }
            }
        }
        const experienceBottles = [];
        if (title.includes('Скупщик')) {
            await delay(2000);
            const items = window.slots;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (item && item.name === 'experience_bottle') {
                    const customLore = item.customLore;
                    customLore.forEach(lore => {
                        const parsedLore = JSON.parse(lore); // Парсим JSON строку
                        const textContent = parsedLore.extra.map(extra => extra.text).join(''); // Извлекаем текст
                        experienceBottles.push(textContent); // Сохраняем текст в массив
                    });
                    let level, progress, multiplier;

                    experienceBottles.forEach(text => {
                        if (text.includes('Уровень:')) {
                            level = text.match(/Уровень:\s*(\d+)/)[1]; // Извлекаем уровень
                        }
                        if (text.includes('Прогресс:')) {
                            progress = text.match(/Прогресс:\s*([\d.]+)\/(\d+)\s*Стаков/);
                            if (progress) {
                                progress = progress[0]; // Сохраняем весь текст прогресса
                            }
                        }
                        if (text.includes('Множитель:')) {
                            multiplier = text.match(/Множитель:\s*x([\d.]+)/)[1]; // Извлекаем множитель
                        }
                    });

                    // console.log([ICODE]Скупщик Уровень: ${level}[/ICODE]);
                    // console.log([ICODE]Скупщик Прогресс: ${progress}[/ICODE]);
                    // console.log([ICODE]Скупщик Множитель: ${multiplier}[/ICODE]);
                }
                if (item && item.name === 'diamond') {
                    check_buyer = [];
                    item.customLore.forEach(lore => {
                        const parsedLore = JSON.parse(lore);
                        if (parsedLore.extra) {
                            parsedLore.extra.forEach(element => {
                                check_buyer.push([ICODE]${element.color} ${element.text}[/ICODE]);
                            });
                        }
                    });
                    let buyerStatus = 'ОШИБКА: Выберите в баере скупку алмазов на (Продать ВСЁ)'; // По умолчанию
                    let passed = false;
                    check_buyer.forEach(txt => {
                        if (txt.includes('#1CFF00') && txt.includes('ВСЁ')) {
                            buyerStatus = [ICODE]С скупщиком все в порядке[/ICODE];
                            passed = true;
                        }
                    });
                    if (passed) {
                        try {
                            await bot.clickWindow(index, 0, 0); // Ожидание завершения клика
                        } catch (err) { }
                        await bot.closeWindow(window);
                        inialization();
                        return;
                    } else {
                        console.log([ICODE][БОТ - ${number_bot}] -> ${buyerStatus}[/ICODE]);
                    }
                }
            }
        }
        if (title.includes('Поиск')) {
            if (not_buying) {
                await bot.closeWindow(window);
                start_mine();
                return;
            }
            const items = window.slots;
            item_founded = false;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (index >= 49) {
                    return;
                }
                if (item) {
                    const item_lore = item.customLore;
                    const jsonString = [ICODE][${item_lore}][/ICODE];
                    try {
                        const loreArray = JSON.parse(jsonString);
                        let price = '';
                        let time = '';
                        let sellerName;
                        loreArray.forEach(item => {
                            if (item.extra) {
                                item.extra.forEach((extraItem, index, array) => {
                                    if (extraItem.text) {
                                        if (extraItem.text.includes('Прoдaвeц:')) {
                                            const nextItem = array[index + 1];
                                            sellerName = [ICODE]${nextItem.text.trim()}[/ICODE];
                                            seller = sellerName;
                                        }
                                        if (extraItem.text.includes('Ценa') || extraItem.text.includes('$')) {
                                            price += extraItem.text.trim() + ' ';
                                        }
                                        if (extraItem.text.match(/\d+\sч\.\s\d+\sмин\.\s\d+\sсек\./)) {
                                            time = extraItem.text.match(/\d+\sч\.\s\d+\sмин\.\s\d+\sсек\./)[0];
                                        }

                                        if (!time) {
                                            time = '9ч.';
                                        }
                                    }
                                });
                            }
                        });
                        price = parseInt(price.replace(/[^0-9]/g, '').trim(), 10);
                        if (item.name === 'experience_bottle') {
                            if (price <= 160000 && item.count >= 60) {
                                item_founded = true;
                                console.log([ICODE][БОТ - ${number_bot}] -> Цена: ${price} Кол-во: ${item.count} Продавец ${sellerName} Истечет: ${time}[/ICODE]);
                                await delay(600);
                                await click_slot(index);
                                return;
                            }
                        }
                    } catch (error) {
                        console.log([ICODE]Error ${error}[/ICODE]);
                    }
                } else {
                    try {
                        await delay(550);
                        await click_slot(49);
                        return;
                    } catch (error) {
                        console.log([ICODE]Error ${error}[/ICODE]);
                    }
                }
            }
            if (item_founded === false) {
                bot.closeWindow(window);
                await delay(900);
                bot.chat(current_buy);
            }
        } else if (title.includes('Подозрительная цена!')) {
            const items = window.slots;
            item_founded = false;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (index >= 49) {
                    return;
                }
                if (item) {
                    if (item.name.includes('glass')) {
                        await delay(500);
                        await click_slot(index);
                        return;
                    }
                }
            }
        }
    });

    async function get_anarchy() {
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]get_anarchy[/ICODE] });
        try {
            const fs = require('fs').promises;
            const data = await fs.readFile('event_mine_parser\\data\\data.json', 'utf8');
            const jsonData = JSON.parse(data);
            const mines = jsonData.mines;
            const sortedMines = mines.sort((a, b) => parseInt(a.time) - parseInt(b.time));
            const minTime = Math.min(...sortedMines.map(mine => parseInt(mine.time)));
            for (const mine of sortedMines) {
                if (parseInt(mine.time) >= 2 && mine.anarchy != config.miners.an_fix || mine.anarchy != config.miners.an_trash) {
                    //console.log([ICODE][БОТ - ${number_bot}] -> rare: ${mine.rare}, anarchy: ${mine.anarchy}, time: ${mine.time}[/ICODE]);
                    return [mine.anarchy, mine.time]; // Возвращаем массив
                }
            }
            console.log([ICODE][БОТ - ${number_bot}] -> Нет подходящих элементов.[/ICODE]);
            return null;
        } catch (err) {
            console.error('Ошибка при чтении файла:', err);
            inialization()
        }
    }

    async function start_mine() {
        if (use_xp) { return }
        if (buy_pickaxe) { return }
        let not_found = 0;
        const [an_code, time] = await get_anarchy();
        anarchy_Code = an_code;
        time_to_start = parseInt(time) - 1;
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Wait_mine[/ICODE] });
        startCountdown(parseInt(time_to_start));
        await delay(parseInt(time_to_start) * 1400);
        if (an_code) {
            bot.chat([ICODE]/an${an_code}[/ICODE]);
        } else {
            console.log([ICODE][БОТ - ${number_bot}] -> Не удалось получить код анархии[/ICODE]);
            return;
        }
        let checkCompleted = false;
        checkForDiamonds = setInterval(async () => {
            try {
                const blocksToDig = [];
                const radius = 5;
                for (let x = -radius; x <= radius; x++) {
                    for (let y = -radius; y <= radius; y++) {
                        for (let z = -radius; z <= radius; z++) {
                            try {
                                const block = bot.blockAt(bot.entity.position.offset(x, y, z));
                                if (block.name === 'diamond_ore') {
                                    blocksToDig.push(block);
                                }
                            } catch (error) {}
                        }
                    }
                }
                if (blocksToDig.length > 0) {
                    for (const block of blocksToDig) {
                        try {
                            await bot.dig(block, true);
                            await console.log([ICODE][БОТ - ${number_bot}] -> Сломал: ${block.position.x}, ${block.position.y}, ${block.position.z}[/ICODE]);
                        } catch (err) {
                            await console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при разрушении блока: ${err}[/ICODE]);
                        }
                    }

                    if (!checkCompleted) {
                        clearInterval(checkForDiamonds);
                        checkCompleted = true;
                        inialization();
                    }
                } else {
                    not_found++;
                }
                if (not_found >= 8) {
                    clearInterval(checkForDiamonds);
                    checkCompleted = true
                    inialization();
                }
            } catch (err) { console.log(err); }
        }, 500);
    }

    async function click_slot(index) {
        try {
            bot.clickWindow(index, 0, 1)
                .catch(() => { });
        } catch (err) { }
    }

    async function useXpBottles() {
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Fix_pickaxe[/ICODE] });
        let xpBottles = bot.inventory.findInventoryItem('experience_bottle');
      
        if (!xpBottles) {
            console.log([ICODE][БОТ - ${number_bot}] -> Весь опыт использован[/ICODE]);
            use_xp = false;
            buying_exp = false;
            inialization();
            return;
        }
  
        try {
            if (bot.heldItem && bot.heldItem.name === 'experience_bottle') {
                await bot.activateItem();
                console.log([ICODE][БОТ - ${number_bot}] -> Использовал пузырьки опыта[/ICODE]);
            } else {
                await bot.equip(xpBottles, 'hand');
            }
        } catch (error) {
            console.log([ICODE][БОТ - ${number_bot}] -> Ошибка при использовании пузырьков опыта: ${error}[/ICODE]);
            inialization();
            return;
        }
  
        // Используем пузырьки опыта с задержкой
        setTimeout(useXpBottles, 200);
    }
  

    async function drop_trash() {
        bot.chat([ICODE]/an${config.miners.an_trash}[/ICODE]);
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]drop_trash[/ICODE] });
        await delay(1000);
        const inventory = await bot.inventory.items();
        if (inventory.length === 0) {
            console.log('Инвентарь пуст.');
            return;
        }
        for (const item of inventory) {
            if (item.name === 'netherite_pickaxe' || item.name === 'diamond' || item.name === 'experience_bottle') {
                continue;
            }
            try {
                await bot.toss(item.type, null, item.count);
                console.log([ICODE][БОТ - ${number_bot}] -> Выбросил: ${item.name}[/ICODE]);
                if (item.name === 'netherite_pickaxe') {
                    console.log([ICODE][БОТ - ${number_bot}] -> ВЫБРОСИЛ: ${item.name}\n[БОТ - ${number_bot}] -> ВЫБРОСИЛ: ${item.name}\n[БОТ - ${number_bot}] -> ВЫБРОСИЛ: ${item.name}[/ICODE])
                }
            } catch (err) {
                console.log([ICODE][БОТ - ${number_bot}] -> Ошибка выбрасывании предмета ${item.name}[/ICODE]);
            }
            await delay(400)
        }
        return;
    }
    function updateJson(filePath, botName, updates) {
        try {
            const data = fs.readFileSync(filePath, 'utf8');
            let jsonData;
            try {
                jsonData = JSON.parse(data);
            } catch (parseErr) {
                console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при парсинге JSON:[/ICODE], parseErr);
                const data = {
                    "bot1_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot2_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot3_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot4_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot5_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot6_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot7_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot8_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot9_mine": {
                        "task": "",
                        "balance": "0"
                    }
                };
              
                fs.writeFileSync(filePath, JSON.stringify(data, null, 4), 'utf8');             
                return;
            }
            if (jsonData[botName]) {
                if (updates.balance !== undefined) {
                    jsonData[botName].balance = updates.balance;
                }
                if (updates.task !== undefined) {
                    jsonData[botName].task = updates.task;
                }
                fs.writeFileSync(filePath, JSON.stringify(jsonData, null, 4), 'utf8');
            } else {
                console.log([ICODE][БОТ - ${number_bot}] -> Бот не найден[/ICODE]);
            }
        } catch (err) {
            console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при чтении или записи файла:[/ICODE], err);
        }
    } 

    function startCountdown(seconds) {
        let remainingTime = seconds;
        const intervalId = setInterval(() => {
            console.log([ICODE][БОТ - ${number_bot}] -> До шахты - ${remainingTime}[/ICODE]);
            remainingTime--;

            if (remainingTime < 0) {
                clearInterval(intervalId);
            }
        }, 1000);
    }

    function delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}


async function startBots() {
    const bot1Name = config.miners.bot1_name; 
    const bot2Name = config.miners.bot2_name;
    await Promise.all([
        my_bot(bot1Name, 1, false),
        my_bot(bot2Name, 2, false),
    ]);
}

// Запускаем ботов
startBots().catch(err => console.error('Ошибка при запуске ботов:', err));
сделай для хв ботов
 
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Язык nodejs библиотека mineflayer

Для того что бы бот работал нужно несколько грешков
1 - встать на нужное место в шахте (снизу шахты, на всех анках)
2 - включить на всех анках авто продажу (не обязательно)
3 - на 604 анке он выкидывает мусор (нужно его направить на пустоту)
4 - на 605 анке он чинится
5 - ОТДЕЛЬНЫЙ БОТ для парсинга шахт (т.к я имею бота для евентов и шахт мне не составило проблемм впихнуть в шахтера json с шахтами и парсить саму ближнию)

  • Бот умеет сам покупать опыт и чинить кирку
  • Бот умеет выбрасывать мусор
  • Продает алмазы скупщику
  • Код сырой, и делался на скорую руку
  • Точных анок не помню можете глянуть в коде
- Иногда теряет кирку (скорее всего из за свапов слотов при починки или при выкидывание)
- Данный пост идет как сурс для доработок а не для готовых решений
  • Бот использует прокси
  • Все данные берет из конфига
  • Так же делал телеграмм бота для обновления и просмотра статистики (можете вырезать info_of_bots.json)

source:
Expand Collapse Copy
const mineflayer = require('mineflayer');
const config = require('../configs/config.json');
const path = require('path');
const { exec } = require('child_process');
const socks = require('socks').SocksClient;
const fs = require('fs')
const configPath = path.join(__dirname, '../configs/info_of_bots.json');

const proxy1 = config.proxys.two_proxy;
const proxy2 = config.proxys.three_proxy;
const proxyHost1 = proxy1.host;
const proxyPort1 = proxy1.port;
const proxyLogin1 = proxy1.login;
const proxyPass1 = proxy1.pass;

const proxyHost2 = proxy2.host;
const proxyPort2 = proxy2.port;
const proxyLogin2 = proxy2.login;
const proxyPass2 = proxy2.pass;

async function my_bot(botName, number_bot, useProxy = false, proxyConfig = null) {
    let not_buying = true;
    let buy_pickaxe = false
    let buyed_exp = 0;
    let checkForDiamonds;
    let use_xp = false;
    let anarchy_Code = 0;
    const bot = mineflayer.createBot({
        host: 'mc.funtime.su',
        username: botName,
        version: '1.16.5',
        hideErrors: true,
        connect: (client) => {
            if (useProxy && proxyConfig) {
                console.log('Попытка подключения к прокси...');
                socks.createConnection({
                    proxy: {
                        host: proxyConfig.host,
                        port: proxyConfig.port,
                        type: 5,
                        userId: proxyConfig.login,
                        password: proxyConfig.pass
                    },
                    command: 'connect',
                    destination: {
                        host: 'mc.funtime.su',
                        port: 25565
                    },
                }, (err, info) => {
                    if (err) {
                        console.error('Ошибка соединения с прокси:', err);
                        return;
                    }
                    console.log('Соединение с прокси установлено.');
                    client.setSocket(info.socket);
                    client.emit('connect');
                });
            } else {
                // Подключение без прокси
                client.connect({
                    host: 'mc.funtime.su',
                    port: 25565
                });
            }
        }
    });

    bot.once('spawn', () => {
        inialization();
    });

    bot.on('kicked', (kicked) => {
        console.log([ICODE][БОТ - ${number_bot}] --> ${kicked}[/ICODE]);
        bot.quit();
        setTimeout(() => {
            my_bot(botName, number_bot, useProxy);
        }, 2000);
        return;
    });

    bot.on('error', (error) => {
        console.log([ICODE][БОТ - ${number_bot}] --> ${error}[/ICODE]);
        bot.quit();
        setTimeout(() => {
            my_bot(botName, number_bot, useProxy);
        }, 3000);
        return;
    });

    bot.on('message', async (message) => {
        const messageText = message.toString();
        //console.log(messageText)
        if (messageText.includes('Ваш баланс:')) {
            const balanceNumberString = messageText.match(/[\d,\.]+/)[0];
            const balanceInt = Math.floor(parseFloat(balanceNumberString.replace(/,/g, '')));
            const investAmount = balanceInt - 30000000;
            if (investAmount >= 1) {
                bot.chat([ICODE]/clan invest ${investAmount}[/ICODE]);
            }
        }
      
        const actions = {
            'Вы успешно купили Пузырек опыта': () => {
                buyed_exp++;
                console.log([ICODE][БОТ - ${number_bot}] -> ${messageText}[/ICODE])
                if (buyed_exp === 4) {
                    buyed_exp = 0;
                    not_buying = true;
                    use_xp = true;
                    useXpBottles();
                }
            },
            'Вы успешно купили Кирка Крушителя': () => {
                buy_pickaxe = false
                not_buying = true
                inialization()
            },
            'уже купили': () => {
                console.log([ICODE][БОТ - ${number_bot}] -> ${messageText}[/ICODE])
            },
            'Ваш баланс:': async () => {
                await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { balance: [ICODE]${messageText}[/ICODE] });
            },
            'Вы были кикнуты при подключении к серверу': () => {
                clearInterval(checkForDiamonds);
                inialization();
            },
            'Введите номер с картинки в чат': async () => {
                await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: 'Нужно[I]пройти[/I]каптчу' });
            },
            'После входа на режим необходимо немного подождать перед использованием аукциона': () => {
                buying_exp = true;
                const regex = /(\d+)\s*сек/;
                const match = messageText.match(regex);
                if (match) {
                    const sleep = parseInt(match[1], 10) + 1;
                    console.log([ICODE][БОТ - ${number_bot}] -> Время ожидания аукциона: ${sleep} сек[/ICODE]);
                    setTimeout(() => {
                        bot.chat(current_buy);
                    }, sleep * 1000);
                } else {
                    console.log([ICODE][БОТ - ${number_bot}] -> Время ожидания не найдено.[/ICODE]);
                }
            }
        };
  
        for (const [key, action] of Object.entries(actions)) {
            if (messageText.includes(key)) {
                await action();
                break;
            }
        }
    });
  
    setInterval(async () => {
        health = bot.health;
        if (health <= 5) {
            bot.quit();
            console.log([ICODE][БОТ - ${number_bot}] -> У бота мало хп[/ICODE]);
            await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Мало жизней у бота: ${health} ${anarchy_Code}[/ICODE] });
            return;
        }
        //console.log([ICODE]Жизней у бота: ${health} ${anarchy_Code}[/ICODE]);
    }, 1000);

    async function inialization() {
        setTimeout(async () => {
            bot.chat([ICODE]/an${config.miners.an_trash}[/ICODE]);
            await delay(2000);
            bot.chat('/bal');
            const itemInOffhand = bot.inventory.slots[45];
            if (itemInOffhand) {
                await bot.equip(itemInOffhand, 'hand', (err) => {
                    if (err) {
                        console.log('Ошибка при экипировке предмета:', err);
                    }
                });
            }
            const pickaxe = await bot.inventory.items().find(item => item.name.includes('netherite_pickaxe'));
            if (bot.heldItem && bot.heldItem.name === 'netherite_pickaxe') {
                console.log([ICODE][БОТ - ${number_bot}] -> Кирка уже в руке[/ICODE])
                await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]inialization[/ICODE] });
            } else {
                try {
                    await bot.equip(pickaxe, 'hand');
                    console.log([ICODE][БОТ - ${number_bot}] -> Взял кирку[/ICODE])
                    await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]inialization[/ICODE] });
                } catch (error) {
                    await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Нет кирки[/ICODE] });
                    inialization()
                    return
                }
            }
            if (pickaxe) {
                const item = await bot.entity.equipment[0];
                if (item && item.name.includes('netherite_pickaxe')) {
                    const maxDurability = item.maxDurability;
                    const damage = item.nbt.value.Damage.value;
                    const durability = maxDurability - damage;
                    console.log([ICODE][БОТ - ${number_bot}] -> Прочность кирки: ${durability} / ${maxDurability}[/ICODE]);
                    if (durability <= 350) {
                        bot.chat([ICODE]/an${config.miners.an_fix}[/ICODE]);
                        await delay(1000);
                        not_buying = false;
                        console.log([ICODE][БОТ - ${number_bot}] -> Мало прочности на кирке, начинаю чиниться[/ICODE]);
                        const pickaxe = bot.inventory.items().find(item => item.name === 'netherite_pickaxe');
                        try {
                            await bot.equip(pickaxe, 'off-hand', (err) => { console.log(err); });
                        } catch (error) {
                            console.log([ICODE][БОТ - ${number_bot}] -> Ошибка при экипировке кирки: ${error}[/ICODE]);
                        }
                        const xpBottles = bot.inventory.findInventoryItem('experience_bottle', null);
                        if (xpBottles) {
                            const blockUnderBot = bot.blockAt(bot.entity.position.offset(0, -1, 0));
                            const blockPosition = blockUnderBot.position;
                            await bot.lookAt(blockPosition.offset(0.5, 0.5, 0.5), true, (err) => {
                                if (err) {
                                    console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при повороте бота:[/ICODE], err);
                                } else {}
                            });
                            try {
                                await useXpBottles();
                                use_xp = true;
                            } catch (error) {
                                console.log([ICODE][БОТ - ${number_bot}] -> Ошибка при использовании пузырьков опыта: ${error}[/ICODE]);
                            }
                        } else {
                            console.log([ICODE][БОТ - ${number_bot}] -> Нет пузырьков опыта в инвентаре, начинаю их покупать[/ICODE]);
                            current_buy = '/ah search Пузырек опыта';
                            bot.chat('/ah search Пузырек опыта');
                            buying_exp = true;
                            return;
                        }
                        return;
                    } else {
                        await drop_trash();
                        const inventory = bot.inventory;
                        let index = 0;
                        inventory.items().forEach(item => {
                            index++;
                        });
                        if (index >= 32) {
                            await delay(1000)
                            console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь полный[/ICODE]);
                            bot.chat('/buyer');
                            return;
                        }
                        console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь: ${index}/36[/ICODE]);
                        start_mine();
                    }
                } else {
                    await drop_trash();
                    const inventory = bot.inventory;
                    let index = 0;
                    inventory.items().forEach(item => {
                        index++;
                    });
                    if (index >= 32) {
                        await delay(1000)
                        console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь полный[/ICODE]);
                        bot.chat('/buyer');
                        return;
                    }
                    console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь: ${index}/36[/ICODE]);
                    start_mine();
                }
            } else {}
        }, 1000);
    }

    bot.on('windowOpen', async (window) => {
        console.log([ICODE][БОТ - ${number_bot}] -> Аукцион открыт[/ICODE]);
        let title = String(window.title);
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Oppened_auction[/ICODE] });
        if (title.includes('Выберите секцию')) {
            await delay(2000);
            const items = window.slots;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (item && item.name === 'lapis_lazuli') {
                    try {
                        await bot.clickWindow(index, 0, 0); // Ожидание завершения клика
                    } catch (err) { }
                    return;
                }
            }
        }
        const experienceBottles = [];
        if (title.includes('Скупщик')) {
            await delay(2000);
            const items = window.slots;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (item && item.name === 'experience_bottle') {
                    const customLore = item.customLore;
                    customLore.forEach(lore => {
                        const parsedLore = JSON.parse(lore); // Парсим JSON строку
                        const textContent = parsedLore.extra.map(extra => extra.text).join(''); // Извлекаем текст
                        experienceBottles.push(textContent); // Сохраняем текст в массив
                    });
                    let level, progress, multiplier;

                    experienceBottles.forEach(text => {
                        if (text.includes('Уровень:')) {
                            level = text.match(/Уровень:\s*(\d+)/)[1]; // Извлекаем уровень
                        }
                        if (text.includes('Прогресс:')) {
                            progress = text.match(/Прогресс:\s*([\d.]+)\/(\d+)\s*Стаков/);
                            if (progress) {
                                progress = progress[0]; // Сохраняем весь текст прогресса
                            }
                        }
                        if (text.includes('Множитель:')) {
                            multiplier = text.match(/Множитель:\s*x([\d.]+)/)[1]; // Извлекаем множитель
                        }
                    });

                    // console.log([ICODE]Скупщик Уровень: ${level}[/ICODE]);
                    // console.log([ICODE]Скупщик Прогресс: ${progress}[/ICODE]);
                    // console.log([ICODE]Скупщик Множитель: ${multiplier}[/ICODE]);
                }
                if (item && item.name === 'diamond') {
                    check_buyer = [];
                    item.customLore.forEach(lore => {
                        const parsedLore = JSON.parse(lore);
                        if (parsedLore.extra) {
                            parsedLore.extra.forEach(element => {
                                check_buyer.push([ICODE]${element.color} ${element.text}[/ICODE]);
                            });
                        }
                    });
                    let buyerStatus = 'ОШИБКА: Выберите в баере скупку алмазов на (Продать ВСЁ)'; // По умолчанию
                    let passed = false;
                    check_buyer.forEach(txt => {
                        if (txt.includes('#1CFF00') && txt.includes('ВСЁ')) {
                            buyerStatus = [ICODE]С скупщиком все в порядке[/ICODE];
                            passed = true;
                        }
                    });
                    if (passed) {
                        try {
                            await bot.clickWindow(index, 0, 0); // Ожидание завершения клика
                        } catch (err) { }
                        await bot.closeWindow(window);
                        inialization();
                        return;
                    } else {
                        console.log([ICODE][БОТ - ${number_bot}] -> ${buyerStatus}[/ICODE]);
                    }
                }
            }
        }
        if (title.includes('Поиск')) {
            if (not_buying) {
                await bot.closeWindow(window);
                start_mine();
                return;
            }
            const items = window.slots;
            item_founded = false;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (index >= 49) {
                    return;
                }
                if (item) {
                    const item_lore = item.customLore;
                    const jsonString = [ICODE][${item_lore}][/ICODE];
                    try {
                        const loreArray = JSON.parse(jsonString);
                        let price = '';
                        let time = '';
                        let sellerName;
                        loreArray.forEach(item => {
                            if (item.extra) {
                                item.extra.forEach((extraItem, index, array) => {
                                    if (extraItem.text) {
                                        if (extraItem.text.includes('Прoдaвeц:')) {
                                            const nextItem = array[index + 1];
                                            sellerName = [ICODE]${nextItem.text.trim()}[/ICODE];
                                            seller = sellerName;
                                        }
                                        if (extraItem.text.includes('Ценa') || extraItem.text.includes('$')) {
                                            price += extraItem.text.trim() + ' ';
                                        }
                                        if (extraItem.text.match(/\d+\sч\.\s\d+\sмин\.\s\d+\sсек\./)) {
                                            time = extraItem.text.match(/\d+\sч\.\s\d+\sмин\.\s\d+\sсек\./)[0];
                                        }

                                        if (!time) {
                                            time = '9ч.';
                                        }
                                    }
                                });
                            }
                        });
                        price = parseInt(price.replace(/[^0-9]/g, '').trim(), 10);
                        if (item.name === 'experience_bottle') {
                            if (price <= 160000 && item.count >= 60) {
                                item_founded = true;
                                console.log([ICODE][БОТ - ${number_bot}] -> Цена: ${price} Кол-во: ${item.count} Продавец ${sellerName} Истечет: ${time}[/ICODE]);
                                await delay(600);
                                await click_slot(index);
                                return;
                            }
                        }
                    } catch (error) {
                        console.log([ICODE]Error ${error}[/ICODE]);
                    }
                } else {
                    try {
                        await delay(550);
                        await click_slot(49);
                        return;
                    } catch (error) {
                        console.log([ICODE]Error ${error}[/ICODE]);
                    }
                }
            }
            if (item_founded === false) {
                bot.closeWindow(window);
                await delay(900);
                bot.chat(current_buy);
            }
        } else if (title.includes('Подозрительная цена!')) {
            const items = window.slots;
            item_founded = false;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (index >= 49) {
                    return;
                }
                if (item) {
                    if (item.name.includes('glass')) {
                        await delay(500);
                        await click_slot(index);
                        return;
                    }
                }
            }
        }
    });

    async function get_anarchy() {
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]get_anarchy[/ICODE] });
        try {
            const fs = require('fs').promises;
            const data = await fs.readFile('event_mine_parser\\data\\data.json', 'utf8');
            const jsonData = JSON.parse(data);
            const mines = jsonData.mines;
            const sortedMines = mines.sort((a, b) => parseInt(a.time) - parseInt(b.time));
            const minTime = Math.min(...sortedMines.map(mine => parseInt(mine.time)));
            for (const mine of sortedMines) {
                if (parseInt(mine.time) >= 2 && mine.anarchy != config.miners.an_fix || mine.anarchy != config.miners.an_trash) {
                    //console.log([ICODE][БОТ - ${number_bot}] -> rare: ${mine.rare}, anarchy: ${mine.anarchy}, time: ${mine.time}[/ICODE]);
                    return [mine.anarchy, mine.time]; // Возвращаем массив
                }
            }
            console.log([ICODE][БОТ - ${number_bot}] -> Нет подходящих элементов.[/ICODE]);
            return null;
        } catch (err) {
            console.error('Ошибка при чтении файла:', err);
            inialization()
        }
    }

    async function start_mine() {
        if (use_xp) { return }
        if (buy_pickaxe) { return }
        let not_found = 0;
        const [an_code, time] = await get_anarchy();
        anarchy_Code = an_code;
        time_to_start = parseInt(time) - 1;
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Wait_mine[/ICODE] });
        startCountdown(parseInt(time_to_start));
        await delay(parseInt(time_to_start) * 1400);
        if (an_code) {
            bot.chat([ICODE]/an${an_code}[/ICODE]);
        } else {
            console.log([ICODE][БОТ - ${number_bot}] -> Не удалось получить код анархии[/ICODE]);
            return;
        }
        let checkCompleted = false;
        checkForDiamonds = setInterval(async () => {
            try {
                const blocksToDig = [];
                const radius = 5;
                for (let x = -radius; x <= radius; x++) {
                    for (let y = -radius; y <= radius; y++) {
                        for (let z = -radius; z <= radius; z++) {
                            try {
                                const block = bot.blockAt(bot.entity.position.offset(x, y, z));
                                if (block.name === 'diamond_ore') {
                                    blocksToDig.push(block);
                                }
                            } catch (error) {}
                        }
                    }
                }
                if (blocksToDig.length > 0) {
                    for (const block of blocksToDig) {
                        try {
                            await bot.dig(block, true);
                            await console.log([ICODE][БОТ - ${number_bot}] -> Сломал: ${block.position.x}, ${block.position.y}, ${block.position.z}[/ICODE]);
                        } catch (err) {
                            await console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при разрушении блока: ${err}[/ICODE]);
                        }
                    }

                    if (!checkCompleted) {
                        clearInterval(checkForDiamonds);
                        checkCompleted = true;
                        inialization();
                    }
                } else {
                    not_found++;
                }
                if (not_found >= 8) {
                    clearInterval(checkForDiamonds);
                    checkCompleted = true
                    inialization();
                }
            } catch (err) { console.log(err); }
        }, 500);
    }

    async function click_slot(index) {
        try {
            bot.clickWindow(index, 0, 1)
                .catch(() => { });
        } catch (err) { }
    }

    async function useXpBottles() {
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Fix_pickaxe[/ICODE] });
        let xpBottles = bot.inventory.findInventoryItem('experience_bottle');
      
        if (!xpBottles) {
            console.log([ICODE][БОТ - ${number_bot}] -> Весь опыт использован[/ICODE]);
            use_xp = false;
            buying_exp = false;
            inialization();
            return;
        }
  
        try {
            if (bot.heldItem && bot.heldItem.name === 'experience_bottle') {
                await bot.activateItem();
                console.log([ICODE][БОТ - ${number_bot}] -> Использовал пузырьки опыта[/ICODE]);
            } else {
                await bot.equip(xpBottles, 'hand');
            }
        } catch (error) {
            console.log([ICODE][БОТ - ${number_bot}] -> Ошибка при использовании пузырьков опыта: ${error}[/ICODE]);
            inialization();
            return;
        }
  
        // Используем пузырьки опыта с задержкой
        setTimeout(useXpBottles, 200);
    }
  

    async function drop_trash() {
        bot.chat([ICODE]/an${config.miners.an_trash}[/ICODE]);
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]drop_trash[/ICODE] });
        await delay(1000);
        const inventory = await bot.inventory.items();
        if (inventory.length === 0) {
            console.log('Инвентарь пуст.');
            return;
        }
        for (const item of inventory) {
            if (item.name === 'netherite_pickaxe' || item.name === 'diamond' || item.name === 'experience_bottle') {
                continue;
            }
            try {
                await bot.toss(item.type, null, item.count);
                console.log([ICODE][БОТ - ${number_bot}] -> Выбросил: ${item.name}[/ICODE]);
                if (item.name === 'netherite_pickaxe') {
                    console.log([ICODE][БОТ - ${number_bot}] -> ВЫБРОСИЛ: ${item.name}\n[БОТ - ${number_bot}] -> ВЫБРОСИЛ: ${item.name}\n[БОТ - ${number_bot}] -> ВЫБРОСИЛ: ${item.name}[/ICODE])
                }
            } catch (err) {
                console.log([ICODE][БОТ - ${number_bot}] -> Ошибка выбрасывании предмета ${item.name}[/ICODE]);
            }
            await delay(400)
        }
        return;
    }
    function updateJson(filePath, botName, updates) {
        try {
            const data = fs.readFileSync(filePath, 'utf8');
            let jsonData;
            try {
                jsonData = JSON.parse(data);
            } catch (parseErr) {
                console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при парсинге JSON:[/ICODE], parseErr);
                const data = {
                    "bot1_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot2_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot3_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot4_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot5_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot6_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot7_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot8_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot9_mine": {
                        "task": "",
                        "balance": "0"
                    }
                };
              
                fs.writeFileSync(filePath, JSON.stringify(data, null, 4), 'utf8');             
                return;
            }
            if (jsonData[botName]) {
                if (updates.balance !== undefined) {
                    jsonData[botName].balance = updates.balance;
                }
                if (updates.task !== undefined) {
                    jsonData[botName].task = updates.task;
                }
                fs.writeFileSync(filePath, JSON.stringify(jsonData, null, 4), 'utf8');
            } else {
                console.log([ICODE][БОТ - ${number_bot}] -> Бот не найден[/ICODE]);
            }
        } catch (err) {
            console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при чтении или записи файла:[/ICODE], err);
        }
    } 

    function startCountdown(seconds) {
        let remainingTime = seconds;
        const intervalId = setInterval(() => {
            console.log([ICODE][БОТ - ${number_bot}] -> До шахты - ${remainingTime}[/ICODE]);
            remainingTime--;

            if (remainingTime < 0) {
                clearInterval(intervalId);
            }
        }, 1000);
    }

    function delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}


async function startBots() {
    const bot1Name = config.miners.bot1_name; 
    const bot2Name = config.miners.bot2_name;
    await Promise.all([
        my_bot(bot1Name, 1, false),
        my_bot(bot2Name, 2, false),
    ]);
}

// Запускаем ботов
startBots().catch(err => console.error('Ошибка при запуске ботов:', err));
кто сможет помочь запустить?
 
как спастить
 
Язык nodejs библиотека mineflayer

Для того что бы бот работал нужно несколько грешков
1 - встать на нужное место в шахте (снизу шахты, на всех анках)
2 - включить на всех анках авто продажу (не обязательно)
3 - на 604 анке он выкидывает мусор (нужно его направить на пустоту)
4 - на 605 анке он чинится
5 - ОТДЕЛЬНЫЙ БОТ для парсинга шахт (т.к я имею бота для евентов и шахт мне не составило проблемм впихнуть в шахтера json с шахтами и парсить саму ближнию)

  • Бот умеет сам покупать опыт и чинить кирку
  • Бот умеет выбрасывать мусор
  • Продает алмазы скупщику
  • Код сырой, и делался на скорую руку
  • Точных анок не помню можете глянуть в коде
- Иногда теряет кирку (скорее всего из за свапов слотов при починки или при выкидывание)
- Данный пост идет как сурс для доработок а не для готовых решений
  • Бот использует прокси
  • Все данные берет из конфига
  • Так же делал телеграмм бота для обновления и просмотра статистики (можете вырезать info_of_bots.json)

source:
Expand Collapse Copy
const mineflayer = require('mineflayer');
const config = require('../configs/config.json');
const path = require('path');
const { exec } = require('child_process');
const socks = require('socks').SocksClient;
const fs = require('fs')
const configPath = path.join(__dirname, '../configs/info_of_bots.json');

const proxy1 = config.proxys.two_proxy;
const proxy2 = config.proxys.three_proxy;
const proxyHost1 = proxy1.host;
const proxyPort1 = proxy1.port;
const proxyLogin1 = proxy1.login;
const proxyPass1 = proxy1.pass;

const proxyHost2 = proxy2.host;
const proxyPort2 = proxy2.port;
const proxyLogin2 = proxy2.login;
const proxyPass2 = proxy2.pass;

async function my_bot(botName, number_bot, useProxy = false, proxyConfig = null) {
    let not_buying = true;
    let buy_pickaxe = false
    let buyed_exp = 0;
    let checkForDiamonds;
    let use_xp = false;
    let anarchy_Code = 0;
    const bot = mineflayer.createBot({
        host: 'mc.funtime.su',
        username: botName,
        version: '1.16.5',
        hideErrors: true,
        connect: (client) => {
            if (useProxy && proxyConfig) {
                console.log('Попытка подключения к прокси...');
                socks.createConnection({
                    proxy: {
                        host: proxyConfig.host,
                        port: proxyConfig.port,
                        type: 5,
                        userId: proxyConfig.login,
                        password: proxyConfig.pass
                    },
                    command: 'connect',
                    destination: {
                        host: 'mc.funtime.su',
                        port: 25565
                    },
                }, (err, info) => {
                    if (err) {
                        console.error('Ошибка соединения с прокси:', err);
                        return;
                    }
                    console.log('Соединение с прокси установлено.');
                    client.setSocket(info.socket);
                    client.emit('connect');
                });
            } else {
                // Подключение без прокси
                client.connect({
                    host: 'mc.funtime.su',
                    port: 25565
                });
            }
        }
    });

    bot.once('spawn', () => {
        inialization();
    });

    bot.on('kicked', (kicked) => {
        console.log([ICODE][БОТ - ${number_bot}] --> ${kicked}[/ICODE]);
        bot.quit();
        setTimeout(() => {
            my_bot(botName, number_bot, useProxy);
        }, 2000);
        return;
    });

    bot.on('error', (error) => {
        console.log([ICODE][БОТ - ${number_bot}] --> ${error}[/ICODE]);
        bot.quit();
        setTimeout(() => {
            my_bot(botName, number_bot, useProxy);
        }, 3000);
        return;
    });

    bot.on('message', async (message) => {
        const messageText = message.toString();
        //console.log(messageText)
        if (messageText.includes('Ваш баланс:')) {
            const balanceNumberString = messageText.match(/[\d,\.]+/)[0];
            const balanceInt = Math.floor(parseFloat(balanceNumberString.replace(/,/g, '')));
            const investAmount = balanceInt - 30000000;
            if (investAmount >= 1) {
                bot.chat([ICODE]/clan invest ${investAmount}[/ICODE]);
            }
        }
      
        const actions = {
            'Вы успешно купили Пузырек опыта': () => {
                buyed_exp++;
                console.log([ICODE][БОТ - ${number_bot}] -> ${messageText}[/ICODE])
                if (buyed_exp === 4) {
                    buyed_exp = 0;
                    not_buying = true;
                    use_xp = true;
                    useXpBottles();
                }
            },
            'Вы успешно купили Кирка Крушителя': () => {
                buy_pickaxe = false
                not_buying = true
                inialization()
            },
            'уже купили': () => {
                console.log([ICODE][БОТ - ${number_bot}] -> ${messageText}[/ICODE])
            },
            'Ваш баланс:': async () => {
                await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { balance: [ICODE]${messageText}[/ICODE] });
            },
            'Вы были кикнуты при подключении к серверу': () => {
                clearInterval(checkForDiamonds);
                inialization();
            },
            'Введите номер с картинки в чат': async () => {
                await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: 'Нужно[I]пройти[/I]каптчу' });
            },
            'После входа на режим необходимо немного подождать перед использованием аукциона': () => {
                buying_exp = true;
                const regex = /(\d+)\s*сек/;
                const match = messageText.match(regex);
                if (match) {
                    const sleep = parseInt(match[1], 10) + 1;
                    console.log([ICODE][БОТ - ${number_bot}] -> Время ожидания аукциона: ${sleep} сек[/ICODE]);
                    setTimeout(() => {
                        bot.chat(current_buy);
                    }, sleep * 1000);
                } else {
                    console.log([ICODE][БОТ - ${number_bot}] -> Время ожидания не найдено.[/ICODE]);
                }
            }
        };
  
        for (const [key, action] of Object.entries(actions)) {
            if (messageText.includes(key)) {
                await action();
                break;
            }
        }
    });
  
    setInterval(async () => {
        health = bot.health;
        if (health <= 5) {
            bot.quit();
            console.log([ICODE][БОТ - ${number_bot}] -> У бота мало хп[/ICODE]);
            await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Мало жизней у бота: ${health} ${anarchy_Code}[/ICODE] });
            return;
        }
        //console.log([ICODE]Жизней у бота: ${health} ${anarchy_Code}[/ICODE]);
    }, 1000);

    async function inialization() {
        setTimeout(async () => {
            bot.chat([ICODE]/an${config.miners.an_trash}[/ICODE]);
            await delay(2000);
            bot.chat('/bal');
            const itemInOffhand = bot.inventory.slots[45];
            if (itemInOffhand) {
                await bot.equip(itemInOffhand, 'hand', (err) => {
                    if (err) {
                        console.log('Ошибка при экипировке предмета:', err);
                    }
                });
            }
            const pickaxe = await bot.inventory.items().find(item => item.name.includes('netherite_pickaxe'));
            if (bot.heldItem && bot.heldItem.name === 'netherite_pickaxe') {
                console.log([ICODE][БОТ - ${number_bot}] -> Кирка уже в руке[/ICODE])
                await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]inialization[/ICODE] });
            } else {
                try {
                    await bot.equip(pickaxe, 'hand');
                    console.log([ICODE][БОТ - ${number_bot}] -> Взял кирку[/ICODE])
                    await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]inialization[/ICODE] });
                } catch (error) {
                    await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Нет кирки[/ICODE] });
                    inialization()
                    return
                }
            }
            if (pickaxe) {
                const item = await bot.entity.equipment[0];
                if (item && item.name.includes('netherite_pickaxe')) {
                    const maxDurability = item.maxDurability;
                    const damage = item.nbt.value.Damage.value;
                    const durability = maxDurability - damage;
                    console.log([ICODE][БОТ - ${number_bot}] -> Прочность кирки: ${durability} / ${maxDurability}[/ICODE]);
                    if (durability <= 350) {
                        bot.chat([ICODE]/an${config.miners.an_fix}[/ICODE]);
                        await delay(1000);
                        not_buying = false;
                        console.log([ICODE][БОТ - ${number_bot}] -> Мало прочности на кирке, начинаю чиниться[/ICODE]);
                        const pickaxe = bot.inventory.items().find(item => item.name === 'netherite_pickaxe');
                        try {
                            await bot.equip(pickaxe, 'off-hand', (err) => { console.log(err); });
                        } catch (error) {
                            console.log([ICODE][БОТ - ${number_bot}] -> Ошибка при экипировке кирки: ${error}[/ICODE]);
                        }
                        const xpBottles = bot.inventory.findInventoryItem('experience_bottle', null);
                        if (xpBottles) {
                            const blockUnderBot = bot.blockAt(bot.entity.position.offset(0, -1, 0));
                            const blockPosition = blockUnderBot.position;
                            await bot.lookAt(blockPosition.offset(0.5, 0.5, 0.5), true, (err) => {
                                if (err) {
                                    console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при повороте бота:[/ICODE], err);
                                } else {}
                            });
                            try {
                                await useXpBottles();
                                use_xp = true;
                            } catch (error) {
                                console.log([ICODE][БОТ - ${number_bot}] -> Ошибка при использовании пузырьков опыта: ${error}[/ICODE]);
                            }
                        } else {
                            console.log([ICODE][БОТ - ${number_bot}] -> Нет пузырьков опыта в инвентаре, начинаю их покупать[/ICODE]);
                            current_buy = '/ah search Пузырек опыта';
                            bot.chat('/ah search Пузырек опыта');
                            buying_exp = true;
                            return;
                        }
                        return;
                    } else {
                        await drop_trash();
                        const inventory = bot.inventory;
                        let index = 0;
                        inventory.items().forEach(item => {
                            index++;
                        });
                        if (index >= 32) {
                            await delay(1000)
                            console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь полный[/ICODE]);
                            bot.chat('/buyer');
                            return;
                        }
                        console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь: ${index}/36[/ICODE]);
                        start_mine();
                    }
                } else {
                    await drop_trash();
                    const inventory = bot.inventory;
                    let index = 0;
                    inventory.items().forEach(item => {
                        index++;
                    });
                    if (index >= 32) {
                        await delay(1000)
                        console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь полный[/ICODE]);
                        bot.chat('/buyer');
                        return;
                    }
                    console.log([ICODE][БОТ - ${number_bot}] -> Инвентарь: ${index}/36[/ICODE]);
                    start_mine();
                }
            } else {}
        }, 1000);
    }

    bot.on('windowOpen', async (window) => {
        console.log([ICODE][БОТ - ${number_bot}] -> Аукцион открыт[/ICODE]);
        let title = String(window.title);
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Oppened_auction[/ICODE] });
        if (title.includes('Выберите секцию')) {
            await delay(2000);
            const items = window.slots;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (item && item.name === 'lapis_lazuli') {
                    try {
                        await bot.clickWindow(index, 0, 0); // Ожидание завершения клика
                    } catch (err) { }
                    return;
                }
            }
        }
        const experienceBottles = [];
        if (title.includes('Скупщик')) {
            await delay(2000);
            const items = window.slots;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (item && item.name === 'experience_bottle') {
                    const customLore = item.customLore;
                    customLore.forEach(lore => {
                        const parsedLore = JSON.parse(lore); // Парсим JSON строку
                        const textContent = parsedLore.extra.map(extra => extra.text).join(''); // Извлекаем текст
                        experienceBottles.push(textContent); // Сохраняем текст в массив
                    });
                    let level, progress, multiplier;

                    experienceBottles.forEach(text => {
                        if (text.includes('Уровень:')) {
                            level = text.match(/Уровень:\s*(\d+)/)[1]; // Извлекаем уровень
                        }
                        if (text.includes('Прогресс:')) {
                            progress = text.match(/Прогресс:\s*([\d.]+)\/(\d+)\s*Стаков/);
                            if (progress) {
                                progress = progress[0]; // Сохраняем весь текст прогресса
                            }
                        }
                        if (text.includes('Множитель:')) {
                            multiplier = text.match(/Множитель:\s*x([\d.]+)/)[1]; // Извлекаем множитель
                        }
                    });

                    // console.log([ICODE]Скупщик Уровень: ${level}[/ICODE]);
                    // console.log([ICODE]Скупщик Прогресс: ${progress}[/ICODE]);
                    // console.log([ICODE]Скупщик Множитель: ${multiplier}[/ICODE]);
                }
                if (item && item.name === 'diamond') {
                    check_buyer = [];
                    item.customLore.forEach(lore => {
                        const parsedLore = JSON.parse(lore);
                        if (parsedLore.extra) {
                            parsedLore.extra.forEach(element => {
                                check_buyer.push([ICODE]${element.color} ${element.text}[/ICODE]);
                            });
                        }
                    });
                    let buyerStatus = 'ОШИБКА: Выберите в баере скупку алмазов на (Продать ВСЁ)'; // По умолчанию
                    let passed = false;
                    check_buyer.forEach(txt => {
                        if (txt.includes('#1CFF00') && txt.includes('ВСЁ')) {
                            buyerStatus = [ICODE]С скупщиком все в порядке[/ICODE];
                            passed = true;
                        }
                    });
                    if (passed) {
                        try {
                            await bot.clickWindow(index, 0, 0); // Ожидание завершения клика
                        } catch (err) { }
                        await bot.closeWindow(window);
                        inialization();
                        return;
                    } else {
                        console.log([ICODE][БОТ - ${number_bot}] -> ${buyerStatus}[/ICODE]);
                    }
                }
            }
        }
        if (title.includes('Поиск')) {
            if (not_buying) {
                await bot.closeWindow(window);
                start_mine();
                return;
            }
            const items = window.slots;
            item_founded = false;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (index >= 49) {
                    return;
                }
                if (item) {
                    const item_lore = item.customLore;
                    const jsonString = [ICODE][${item_lore}][/ICODE];
                    try {
                        const loreArray = JSON.parse(jsonString);
                        let price = '';
                        let time = '';
                        let sellerName;
                        loreArray.forEach(item => {
                            if (item.extra) {
                                item.extra.forEach((extraItem, index, array) => {
                                    if (extraItem.text) {
                                        if (extraItem.text.includes('Прoдaвeц:')) {
                                            const nextItem = array[index + 1];
                                            sellerName = [ICODE]${nextItem.text.trim()}[/ICODE];
                                            seller = sellerName;
                                        }
                                        if (extraItem.text.includes('Ценa') || extraItem.text.includes('$')) {
                                            price += extraItem.text.trim() + ' ';
                                        }
                                        if (extraItem.text.match(/\d+\sч\.\s\d+\sмин\.\s\d+\sсек\./)) {
                                            time = extraItem.text.match(/\d+\sч\.\s\d+\sмин\.\s\d+\sсек\./)[0];
                                        }

                                        if (!time) {
                                            time = '9ч.';
                                        }
                                    }
                                });
                            }
                        });
                        price = parseInt(price.replace(/[^0-9]/g, '').trim(), 10);
                        if (item.name === 'experience_bottle') {
                            if (price <= 160000 && item.count >= 60) {
                                item_founded = true;
                                console.log([ICODE][БОТ - ${number_bot}] -> Цена: ${price} Кол-во: ${item.count} Продавец ${sellerName} Истечет: ${time}[/ICODE]);
                                await delay(600);
                                await click_slot(index);
                                return;
                            }
                        }
                    } catch (error) {
                        console.log([ICODE]Error ${error}[/ICODE]);
                    }
                } else {
                    try {
                        await delay(550);
                        await click_slot(49);
                        return;
                    } catch (error) {
                        console.log([ICODE]Error ${error}[/ICODE]);
                    }
                }
            }
            if (item_founded === false) {
                bot.closeWindow(window);
                await delay(900);
                bot.chat(current_buy);
            }
        } else if (title.includes('Подозрительная цена!')) {
            const items = window.slots;
            item_founded = false;
            for (let index = 0; index < items.length; index++) {
                const item = items[index];
                if (index >= 49) {
                    return;
                }
                if (item) {
                    if (item.name.includes('glass')) {
                        await delay(500);
                        await click_slot(index);
                        return;
                    }
                }
            }
        }
    });

    async function get_anarchy() {
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]get_anarchy[/ICODE] });
        try {
            const fs = require('fs').promises;
            const data = await fs.readFile('event_mine_parser\\data\\data.json', 'utf8');
            const jsonData = JSON.parse(data);
            const mines = jsonData.mines;
            const sortedMines = mines.sort((a, b) => parseInt(a.time) - parseInt(b.time));
            const minTime = Math.min(...sortedMines.map(mine => parseInt(mine.time)));
            for (const mine of sortedMines) {
                if (parseInt(mine.time) >= 2 && mine.anarchy != config.miners.an_fix || mine.anarchy != config.miners.an_trash) {
                    //console.log([ICODE][БОТ - ${number_bot}] -> rare: ${mine.rare}, anarchy: ${mine.anarchy}, time: ${mine.time}[/ICODE]);
                    return [mine.anarchy, mine.time]; // Возвращаем массив
                }
            }
            console.log([ICODE][БОТ - ${number_bot}] -> Нет подходящих элементов.[/ICODE]);
            return null;
        } catch (err) {
            console.error('Ошибка при чтении файла:', err);
            inialization()
        }
    }

    async function start_mine() {
        if (use_xp) { return }
        if (buy_pickaxe) { return }
        let not_found = 0;
        const [an_code, time] = await get_anarchy();
        anarchy_Code = an_code;
        time_to_start = parseInt(time) - 1;
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Wait_mine[/ICODE] });
        startCountdown(parseInt(time_to_start));
        await delay(parseInt(time_to_start) * 1400);
        if (an_code) {
            bot.chat([ICODE]/an${an_code}[/ICODE]);
        } else {
            console.log([ICODE][БОТ - ${number_bot}] -> Не удалось получить код анархии[/ICODE]);
            return;
        }
        let checkCompleted = false;
        checkForDiamonds = setInterval(async () => {
            try {
                const blocksToDig = [];
                const radius = 5;
                for (let x = -radius; x <= radius; x++) {
                    for (let y = -radius; y <= radius; y++) {
                        for (let z = -radius; z <= radius; z++) {
                            try {
                                const block = bot.blockAt(bot.entity.position.offset(x, y, z));
                                if (block.name === 'diamond_ore') {
                                    blocksToDig.push(block);
                                }
                            } catch (error) {}
                        }
                    }
                }
                if (blocksToDig.length > 0) {
                    for (const block of blocksToDig) {
                        try {
                            await bot.dig(block, true);
                            await console.log([ICODE][БОТ - ${number_bot}] -> Сломал: ${block.position.x}, ${block.position.y}, ${block.position.z}[/ICODE]);
                        } catch (err) {
                            await console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при разрушении блока: ${err}[/ICODE]);
                        }
                    }

                    if (!checkCompleted) {
                        clearInterval(checkForDiamonds);
                        checkCompleted = true;
                        inialization();
                    }
                } else {
                    not_found++;
                }
                if (not_found >= 8) {
                    clearInterval(checkForDiamonds);
                    checkCompleted = true
                    inialization();
                }
            } catch (err) { console.log(err); }
        }, 500);
    }

    async function click_slot(index) {
        try {
            bot.clickWindow(index, 0, 1)
                .catch(() => { });
        } catch (err) { }
    }

    async function useXpBottles() {
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]Fix_pickaxe[/ICODE] });
        let xpBottles = bot.inventory.findInventoryItem('experience_bottle');
      
        if (!xpBottles) {
            console.log([ICODE][БОТ - ${number_bot}] -> Весь опыт использован[/ICODE]);
            use_xp = false;
            buying_exp = false;
            inialization();
            return;
        }
  
        try {
            if (bot.heldItem && bot.heldItem.name === 'experience_bottle') {
                await bot.activateItem();
                console.log([ICODE][БОТ - ${number_bot}] -> Использовал пузырьки опыта[/ICODE]);
            } else {
                await bot.equip(xpBottles, 'hand');
            }
        } catch (error) {
            console.log([ICODE][БОТ - ${number_bot}] -> Ошибка при использовании пузырьков опыта: ${error}[/ICODE]);
            inialization();
            return;
        }
  
        // Используем пузырьки опыта с задержкой
        setTimeout(useXpBottles, 200);
    }
  

    async function drop_trash() {
        bot.chat([ICODE]/an${config.miners.an_trash}[/ICODE]);
        await updateJson(configPath, [ICODE]bot${number_bot}_mine[/ICODE], { task: [ICODE]drop_trash[/ICODE] });
        await delay(1000);
        const inventory = await bot.inventory.items();
        if (inventory.length === 0) {
            console.log('Инвентарь пуст.');
            return;
        }
        for (const item of inventory) {
            if (item.name === 'netherite_pickaxe' || item.name === 'diamond' || item.name === 'experience_bottle') {
                continue;
            }
            try {
                await bot.toss(item.type, null, item.count);
                console.log([ICODE][БОТ - ${number_bot}] -> Выбросил: ${item.name}[/ICODE]);
                if (item.name === 'netherite_pickaxe') {
                    console.log([ICODE][БОТ - ${number_bot}] -> ВЫБРОСИЛ: ${item.name}\n[БОТ - ${number_bot}] -> ВЫБРОСИЛ: ${item.name}\n[БОТ - ${number_bot}] -> ВЫБРОСИЛ: ${item.name}[/ICODE])
                }
            } catch (err) {
                console.log([ICODE][БОТ - ${number_bot}] -> Ошибка выбрасывании предмета ${item.name}[/ICODE]);
            }
            await delay(400)
        }
        return;
    }
    function updateJson(filePath, botName, updates) {
        try {
            const data = fs.readFileSync(filePath, 'utf8');
            let jsonData;
            try {
                jsonData = JSON.parse(data);
            } catch (parseErr) {
                console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при парсинге JSON:[/ICODE], parseErr);
                const data = {
                    "bot1_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot2_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot3_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot4_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot5_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot6_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot7_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot8_mine": {
                        "task": "",
                        "balance": "0"
                    },
                    "bot9_mine": {
                        "task": "",
                        "balance": "0"
                    }
                };
              
                fs.writeFileSync(filePath, JSON.stringify(data, null, 4), 'utf8');             
                return;
            }
            if (jsonData[botName]) {
                if (updates.balance !== undefined) {
                    jsonData[botName].balance = updates.balance;
                }
                if (updates.task !== undefined) {
                    jsonData[botName].task = updates.task;
                }
                fs.writeFileSync(filePath, JSON.stringify(jsonData, null, 4), 'utf8');
            } else {
                console.log([ICODE][БОТ - ${number_bot}] -> Бот не найден[/ICODE]);
            }
        } catch (err) {
            console.error([ICODE][БОТ - ${number_bot}] -> Ошибка при чтении или записи файла:[/ICODE], err);
        }
    } 

    function startCountdown(seconds) {
        let remainingTime = seconds;
        const intervalId = setInterval(() => {
            console.log([ICODE][БОТ - ${number_bot}] -> До шахты - ${remainingTime}[/ICODE]);
            remainingTime--;

            if (remainingTime < 0) {
                clearInterval(intervalId);
            }
        }, 1000);
    }

    function delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}


async function startBots() {
    const bot1Name = config.miners.bot1_name; 
    const bot2Name = config.miners.bot2_name;
    await Promise.all([
        my_bot(bot1Name, 1, false),
        my_bot(bot2Name, 2, false),
    ]);
}

// Запускаем ботов
startBots().catch(err => console.error('Ошибка при запуске ботов:', err));
годно
 
700 строчек говно-кода
 
Я не говорил что он идеален, он скорее как для помощи начинающим и разобраться с логикой и методами
Твой код не просто не идеален, он имеет не правильные реализации функций и типичные ошибки.
const proxy1 = config.proxys.two_proxy; const proxy2 = config.proxys.three_proxy; const proxyHost1 = proxy1.host; const proxyPort1 = proxy1.port; const proxyLogin1 = proxy1.login; const proxyPass1 = proxy1.pass; const proxyHost2 = proxy2.host; const proxyPort2 = proxy2.port; const proxyLogin2 = proxy2.login; const proxyPass2 = proxy2.pass;
Например здесь, нет необходимости инициализировать столько переменных.

async function startBots() { const bot1Name = config.miners.bot1_name; const bot2Name = config.miners.bot2_name; await Promise.all([ my_bot(bot1Name, 1, false), my_bot(bot2Name, 2, false), ]); }
Как и здесь.
 
Помоги пожалуйста с ботом, я не понимаю как его сделать.
Мне нужно что бы он зашел в определенный портал из лобби , как на проекте MasedWorld
и начал писать определенный текст , интервал между сообщениями должен быть 5 минут.
Но у меня получается только запустить его в лобби, и больше не чего. Долго голову ломаю по этой задаче .
 
Назад
Сверху Снизу