我的 discord.js 机器人似乎同时 运行 多个实例

My discord.js bot seems to be running multiple instances at the same time

所以我想做的是一个可以检测命令的简单机器人。我做了一个 '!test' 命令来做一些事情(回复消息,删除它,然后稍后删除答案,但也在频道中记录命令)。

它似乎工作得很好,但是它会发送垃圾邮件并多次执行一系列操作:http://prntscr.com/nkgj8m(每次重新启动机器人时越来越多)。

我尝试删除该应用程序并重新创建它,它运行良好:消息只出现一次,直到我重新启动机器人。

我发出了一个“!stop”命令来破坏客户端,但它没有按预期工作:机器人已断开连接(在我的控制台中显示 "stop"),但几乎立即在我的服务器上重新连接(而且我在本地控制台中再也看不到日志了)。

不过关于消息的数量似乎有点"random"。一些机器人消息有时也根本没有被删除,也没有被记录下来。

这是我的代码(我以前从未在 js 中真正做过任何事情,所以我可能会误用某些东西,或者某些东西可能不是最佳的,对此感到抱歉 - 我做了一些研究,我认为大多数东西都很好,或者不错至少)。

// Require libs
require('dotenv').config()
const Discord = require('discord.js');

// Get discord client
var client = new Discord.Client();
initialize();

// --------------------------------------------------
//      INITIALIZE
// --------------------------------------------------

function initialize() {
    // On ready
    client.on("ready", function() {
        console.log(`Logged in as ${client.user.tag}! Yup, this is the default message.`);
    });

    // On message
    client.on("message", function(input) {
        // server message
        if (input.guild.available) {
            // get the message content
            var command = input.content.toLowerCase();
            // stop command
            if (command.startsWith("!stop")) {
                client.destroy();
                console.log("Stopped");
            }
            // test command
            else if (command.startsWith("!test")) {
                input.reply(`This is my answer to your test !`)
                    .then(function(output) {
                        consumeCommand(input, output, 5000);
                    })
                    .catch(console.error);
            }
        }
    });

    // login bot client
    client.login(process.env.BOT_TOKEN);
}

// --------------------------------------------------
//      CONSULE AND LOG COMMANDS
// --------------------------------------------------

// Log the output of a command, delete the input message and delete the output soon
// input, message, the user message
// output, string, is the bot output
// outputTimeout, int, is the time we should wait until deleting the bot's output
function consumeCommand(input, output, outputTimeout) {
    // delete input
    input.delete(0)
        .then(function() {
            console.log(`Deleted message ${input.content}`)
        })
        .catch(console.error);
    // log
    var logChannel = input.guild.channels.find(channel => channel.name === 'guiguibot-commands');
    if (logChannel != null) {
        logCommand(input, output, logChannel);
    } else {
        console.log("Trying to log bot command but there's no guiguibot-commands channel");
    }
    // delete output later if not null
    if (output != null && outputTimeout != null) {
    }
}

// Log the output of a command
// input, message, the user message
// msg, message, the user message
// output, string, is the bot output
function logCommand(input, output, logChannel) {
    // has output
    if (output != null) {
        logChannel.send(`@${input.author.username} sent a command`, {
          embed: {
            fields: [
              {
                name: ":keyboard: Input :",
                value: `\`${input.content}\``
              },
              {
                name: ":robot: Output :",
                value: `\`${output.content}\``
              }
            ]
          }
        })
            .then(() => console.log('Logged user action'))
            .catch(console.error);
    }
    // no ouput
    else {
        logChannel.send(`@${input.author.id} sent a command (no output was found)`, {
          embed: {
            fields: [
              {
                name: ":keyboard: Input :",
                value: `\`${input.content}\``
              }
            ]
          }
        })
            .then(function() {
                console.log('Logged user action')
            })
            .catch(console.error);
    }
}

所以,我的问题是:如何确保我的代码只有一个实例 运行? (如果我正确地扣除了问题)。任何帮助表示赞赏。谢谢!

你不需要创建一个 initialize() 方法,就像这样:

// Require libs
require('dotenv').config()
const Discord = require('discord.js');

// Get discord client
var client = new Discord.Client();

// On ready
client.on("ready", function() {
    console.log('Logged in as ${client.user.tag}! Yup, this is the default message.');
});

// On message
client.on("message", function(input) {
    // server message
    if (input.guild.available) {
        // get the message content
        var command = input.content.toLowerCase();
        // stop command
        if (command.startsWith("!stop")) {
            client.destroy();
            console.log("Stopped");
        }
        // test command
        else if (command.startsWith("!test")) {
            input.reply('This is my answer to your test !')
                .then(function(output) {
                    consumeCommand(input, output, 5000);
                })
                .catch(console.error);
        }
    }
});

// --- CONSOLE AND LOG COMMANDs go here ---

// login bot client
client.login(process.env.BOT_TOKEN);

按照@slothiful 的建议,通过简单地将其托管在 Heroku 上来修复它!我想我的脚本只是一次又一次地重新启动,并且与不和谐服务器的连接成倍增加?完全正确。事实上现在它工作正常,只有一个实例正在处理我的命令。