简体   繁体   English

如何将 node.js 脚本作为多个脚本运行? 互不影响

[英]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.我有一个 node.js 应用程序,它获取一些机器人电报令牌并将它们作为机器人运行。
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);

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.uncaughtException处理程序来处理错误。

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.如果您想进一步 go 并为每个要运行的机器人创建子进程。使用 Node 提供的child_process模块。

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

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

Here, the bot.js can have all the bot related code.在这里, bot.js可以包含所有与 bot 相关的代码。

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM