skip to Main Content

I am unable to use the same instance of an object in another java-script file using nodejs.

I’m working on a bot for telegram. Because the file gets large and chaotic, i would like to split the functions of my bot into a few extra js files. But i don’t know any way how to share the same instance of an object between multiple javascript files.

///////////////////////8Ball File
const {eightBall} = require("./main");
const ballBot = myAwseomeBot;

function eightBall() {

    ballBot.onText(//8ball/, (msg, callback) => {
        let ranNum = Math.floor(Math.random() * 15) + 1;
        const chatId = msg.chat.id;
        const reply_to_message_id = msg.message_id;
        console.log(ranNum);
        switch (ranNum) {
            case 1:
                ballBot.sendMessage(chatId, "Ja");
                break;
      }
    })
}


//main file

let myAwesomeBot  = new TelegramBot(botToken, {polling:true});
exports.myAwesomeBot = myAwesomeBot;










ballBot.onText(//8ball/, (msg, callback) => {
        ^
TypeError: Cannot read property 'onText' of undefined

3

Answers


  1. Could it be that there is a typo on line 2? Should be
    myAwesomeBot not myAwseomeBot.

    const ballBot = myAwseomeBot;
    
    
    Login or Signup to reply.
  2. Did you check that ballBot was defined?
    Try to remove the brackets when requiring the main file. I would also suggest using the Singleton pattern if you want to share the same instance across your code.

    Login or Signup to reply.
  3. It isn’t shown in your code here, but you probably have a cyclic dependency, where A requires B, and B requires A.

    The simplest solution relevant to your use case is to define and implement commands for your bot in additional files, and let your bot file attach / consume them:

    8ball.js

    import { telegram stuff } from 'wherever';
    
    export myCommand1 = {
      pattern: //8ball/,
      eventName: 'ontext',
      callback: (msg, msgCallback) => { /* use "this" as if it were the bot instance */};
    };
    

    main.js

    import .... from ....;
    import { myCommand1 } from '8ball';
    
    ...
    bot.onText(myCommand1.pattern, myCommand1.callback.bind(bot));
    ...
    

    There are probably other bot class methods more suited for attaching generic event handlers/listeners, and also other methods of specifying your module exports, but the idea is that your command files don’t need to import the bot file. I have not researched the telegram bot API so it may have some manner of delegating the bot instance when attaching an event handler. If so, use it!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search