How to split long list of commands to different files

1k Views Asked by At

I'm making telegram bot with node-telegram-bot-api and everything is fine until the command list become very long. It's not comfortable to serve many commands in single .js file where bot was initialized.

I'm understand one basic thing with module.exports, using which I can move serving functions to different files, but it still not what I'm thinking about.

When you building html page (basic), you add your javascript files via tag, and that's how you get few scripts loaded on page as one big thing. When you using PHP, you can use require or include to insert other script into the main one. Finally Express.js allow to make external router module, and use it in main script just as expressApp.use(myRouterModule).

That's what I'm trying to find how to. Making some structure, when few commands grouped by any category will be placed into different .js file and used something like mybot.useCommands(CommandGroup1,CommandGroup2)

I.e. CommandGroup1.js will contain:

bot.onText(/\/start/,function(msg){...})
bot.onText(/\/echo/,function(msg){...})

another one TestGroup.js will contain

bot.onText(/\/test1/,function(msg){...})
bot.onText(/\/AnotherTest/,function(msg){...})

and main app.js will use these both files with event listeners inside

var bot = new TelegramBot(token, { polling: true });

includeHere('./CommandGroup1.js')
includeHere('./TestGroup.js')

I've checked APIs of node-telegram-bot-api but didn't found anything like that, but

  • may be my search was incorrect (incorrect keywords, misunderstanding of descriptions)
  • may be NodeJS runtime allow JavaScript to include external .js files as part of code, but not as value of variable

P.S.: Yes, I'm newbee in NodeJS and understand that this question may sounds stupid. Yes I know only basics of javascript. But I don't know how to and not sure if my question is formulated correctly, so thanks to all who will help with correction if it's needed.

1

There are 1 best solutions below

2
On BEST ANSWER

You can create a separate module (e.g. bot.js) that exports the bot object as a singleton and in each of your other files containing the commands/listeners/handlers, you just need to import the same instance of the bot.

For example, in bot.js:

const TelegramBot = require('node-telegram-bot-api');
const bot = new TelegramBot(token, { polling: true });
module.exports = bot;

in CommandGroup1.js:

const bot = require('./bot');
bot.onText(/\/start/,function(msg){...});
bot.onText(/\/echo/,function(msg){...});

in TestGroup.js:

const bot = require('./bot');
bot.onText(/\/test1/,function(msg){...});
bot.onText(/\/AnotherTest/,function(msg){...});

in app.js:

require('./CommandGroup1');
require('./TestGroup');