Search code examples
javascriptnode.jsnode-telegram-bot-api

Why is a new instance of a object undefined?


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

Solution

  • 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!