PrismarineJS / mineflayer

Create Minecraft bots with a powerful, stable, and high level JavaScript API.
https://prismarinejs.github.io/mineflayer/
MIT License
4.75k stars 871 forks source link

Multiple Bots crash #3347

Closed nikitapro225 closed 2 months ago

nikitapro225 commented 2 months ago

`const mineflayer = require('mineflayer'); const { pathfinder, Movements, goals } = require('mineflayer-pathfinder') const GoalFollow = goals.GoalFollow const GoalBlock = goals.GoalBlock

let botArgs = { host: '94.198.54.132', port: 38744, version: '1.16.5' };

class MCBot {

// Constructor
constructor(username) {
    this.username = username;
    this.host = botArgs["host"];
    this.port = botArgs["port"];
    this.version = botArgs["version"];

    this.initBot();
}

// Init bot instance
initBot() {
    this.bot = mineflayer.createBot({
        username: this.username,
        password: '',
        host: this.host,
        port: this.port,
        version: this.version
    });

    this.initEvents()
}

// Init bot events
initEvents() {
    this.bot.loadPlugin(pathfinder)

    this.bot.on('login', () => {
        //let botSocket = this.bot._client.socket;
        //console.log(`[${this.username}] Logged in to ${botSocket.server ? botSocket.server : botSocket._host}`);
    });

    this.bot.on('end', (reason) => {
        //console.log(`[${this.username}] Disconnected: ${reason}`);

        if (reason == "disconnect.quitting") {
            return
        }

        setTimeout(() => this.initBot(), 1000);
    });

    function followPlayer() {
        const playerCI = this.bot.players['xvbx01cc']

        if (!playerCI || !playerCI.entity) {
            this.bot.chat("I can't see CI!")
            return
        }

        const mcData = require('minecraft-data')(this.bot.version)
        const movements = new Movements(this.bot, mcData)
        movements.scafoldingBlocks = []

        this.bot.pathfinder.setMovements(movements)

        const goal = new GoalFollow(playerCI.entity, 1)
        this.bot.pathfinder.setGoal(goal, true)
    }

    this.bot.once('spawn', async () => {
        this.bot.chat('/reg 12345op 12345op')
        await this.bot.waitForTicks(60);
        this.bot.chat('/l 12345op')
        setInterval(() => {
            const mobFilter = e => e.type === 'mob' && e.mobType === 'Zombie'
            const mob = this.bot.nearestEntity(mobFilter)

            if (!mob) return;

            const pos = mob.position;
            this.bot.attack(mob);
            /*bot.lookAt(pos, true, () => {

            });*/
        }, 1000);
    });

    this.bot.on('chat',(username,message)=>{
        if(username === this.bot.username) return
        console.log(`${username} send ${message}`)
        switch (message){
            case '-bot sleep':
                goToSleep()
                break
            case '-bot wakeup':
                wakeUp()
                break
            case '-bot leave':
                this.bot.quit()
                break
            case '-bot follow':
                followPlayer()
                break
            //case '-bot goal '
        }
    });

    this.bot.on('sleep',()=>{
        this.bot.chat('Спокойной ночи')
    });

    this.bot.on('wake',()=>{
        this.bot.chat('Доброе утро')
    });

    async function goToSleep() {
        const bed = this.bot.findBlock({
            matching: block => bot.isABed(block)
        })

        if (bed) {
            try {
                await this.bot.sleep(bed)
                this.bot.chat("Я сплю")
            } catch (err) {
                this.bot.chat(`Я не могу уснуть: ${err.message}`)
            }
    } else {
        this.bot.chat('Поблизости нет кровати')
    }
    }

    async function  wakeUp() {
        try {
            await this.bot.wake()
        } catch (err) {
            this.bot.chat(`Я не могу проснуться: ${err.message}`)
        }
    }

    this.bot.on('chat', function (username,message){
        if(message === "-bot ihp"){
            this.bot.chat('У меня ' + this.bot.health.toFixed(0) + ' здоровье')
        }
        if(message === "-bot ifood"){
            this.bot.chat(`У меня ` + this.bot.food + ` еды`)
        }
        if(message === "-bot iexp"){
            this.bot.chat("У меня " + this.bot.experience.points.toFixed(0) + " опыта" )
        }
        if(message === "-bot ilevel"){
             this.bot.chat('У меня ' + this.bot.experience.level.toFixed(0) + ' уровень')
        }
    });

    this.bot.on('error', (err) => {
        if (err.code == 'ECONNREFUSED') {
            //console.log(`[${this.username}] Failed to connect to ${err.address}:${err.port}`)
        }
        else {
            //console.log(`[${this.username}] Unhandled error: ${err}`);
        }
    });
}

}

let bots = []; for(var i = 0; i < 10; i++) { bots.push(new MCBot(RAB${i})) bots.push(new MCBot(RAB${i})) }`

C:\Users\Vova\node_modules\minecraft-protocol\src\transforms\framing.js:67 } else { throw e } ^

TypeError: Cannot read properties of undefined (reading 'bot') at followPlayer (C:\Users\Vova\Desktop\bot nikita\mimn.js:58:35) at EventEmitter. (C:\Users\Vova\Desktop\bot nikita\mimn.js:107:21) at EventEmitter.emit (node:events:531:35) at EventEmitter. (C:\Users\Vova\node_modules\mineflayer\lib\plugins\chat.js:85:13) at EventEmitter.emit (node:events:519:28) at Client. (C:\Users\Vova\node_modules\mineflayer\lib\plugins\chat.js:130:9) at Client.emit (node:events:519:28) at Client. (C:\Users\Vova\node_modules\minecraft-protocol\src\client\play.js:73:18) at Client.emit (node:events:519:28) at emitPacket (C:\Users\Vova\node_modules\minecraft-protocol\src\client.js:83:12)

Node.js v21.7.1

Bot crash when i input -bot follow

extremeheat commented 2 months ago

This is a problem with your code. The specific error is being triggered in followPlayer if you read the stack trace. this should only be directly used in class instance methods (creating a new function creates a new this scope which is outside the class instance scope). I'd recommend learning a bit more JS before working on a mineflayer bot and asking ChatGPT to rewrite your code to fix this error.