developer
developer

Reputation: 220

How can I run a node.js script as multiple scripts? no impact on each other

I've a node.js application that get some bot telegram token and run them as a bot.
I use telegraf module.
But when a bot receive too many request or throw an error and then crashed, this happen for the others bot.
What can i do to solve this problem.
I want the bots to be separate from each other.
A way is Copying my code and run the bots as multi script separately.
But i have many bot so it's impossible.

Here is my code to run the bots:

const Telegraf = require('telegraf');
var {Robots} = require('./model/models/robots');



var botsList = [];
setInterval(() => {
    Robots.find({bot_type: 'group manager'}).then((res) => {
        if(res.length > 0){
            var tokens = [];
            for(var i = 0 ; i < res.length ; i++){
                var newToken = res[i].token;
                tokens.push(newToken);
            }

            var bot = [];

            tokens.map(token => {
                if(!botsList.includes(token)){
                    botsList.push(token);
                    var botUserId = token.split(':')[0];

                    bot[botUserId] = new Telegraf(token);

                    module.exports = {
                        bot
                    };

                    const Commands = require('./controller/commands/commands.js');

                    bot[botUserId].on('text', (ctx) => {
                        Commands.executeCommand(bot[botUserId], ctx);
                    });

                    bot[botUserId].startPolling();
                }
            });
        }
    }).catch(console.log);
}, 5000);

Upvotes: 0

Views: 146

Answers (1)

tbking
tbking

Reputation: 9056

If you just want the error in one broker to not affect the script as whole, you can just handle the error using process.uncaughtException handler for the script.

process.on('uncaughtException', console.log);

If you want to go a step further and create child process for each bot to run in. Use child_process module provided by Node.

const fork = require('child_process').fork;

fork('./bot.js', token);

Here, the bot.js can have all the bot related code.

Hope this helps!

Upvotes: 1

Related Questions