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
Could it be that there is a typo on line 2? Should be
myAwesomeBot not myAwseomeBot.
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.
It isn’t shown in your code here, but you probably have a cyclic dependency, where A
require
s B, and Brequire
s 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
main.js
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!