How to correctly transfer an object created by a module in another js file to a class

40 Views Asked by At

I have an object that is created based on modules

const mineflayer = require('mineflayer');
const {pathfinder, Movements, goals : {GoalNear, GoalFollow}} = require('mineflayer-pathfinder');

const bot = mineflayer.createBot({
    host: '127.0.0.1', //localhost or 127.0.0.1 
    port: 5000,
    username: 'bot',
 });

And I need to somehow use this object in another file that has a class

class Walk {
    constructor(bot) {
        this.bot = bot
    }
    //Ко мне
    goToMe(username) {
        try {
            const player = bot.players[username].entity.position;

            bot.pathfinder.setMovements(new Movements(bot, mcData));
            bot.pathfinder.setGoal(new GoalNear(player.x, player.y, player.z, 0), 1);

            bot.chat('Иду на позицию'); 
        } catch (error) {
            console.log(error);
            bot.chat('error');
        }
    }


    //Следуй за мной
    followMe(username) {
        try {
            const player = bot.players[username].entity

            bot.pathfinder.setMovements(new Movements(bot, mcData));
            bot.pathfinder.setGoal(new GoalFollow(player, 1), 1);

            bot.chat('Следую за вами');   
        } catch (error) {
            console.log(error);
            bot.chat('error');
        }
    }


    //Стоп
    stopWalk() {
        try {
            bot.pathfinder.setGoal(null, 1);
            bot.chat('Стою');
        } catch (error) {
            console.log(error);
            bot.chat('error');
        }
    }
}

This is the code of a simple walking bot. but it gives an error: ReferenceError: bot is not defined

the bot will execute commands

1

There are 1 best solutions below

1
On

You can try something like this :

bot.js :

const mineflayer = require('mineflayer');
const {pathfinder, Movements, goals : {GoalNear, GoalFollow}} = require('mineflayer-pathfinder');
    
function botCreater() {
                        
        let bot = mineflayer.createBot({
            host: '127.0.0.1', //localhost or 127.0.0.1 
            port: 5000,
            username: 'bot',
         });
     return bot;
}

cat.js :

import { botCreater } from "/bot.js";
const botcreator = botCreater();

    class Walk {
      var bot={};
        constructor() {
            this.bot = botcreator 
        }
        
    }