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

时间:2019-05-04 21:21:35

标签: javascript node.js discord discord.js

所以我想做的是一个可以检测命令的简单机器人。我做了一个“!test”命令,该命令可以执行一些操作(回复消息,将其删除,然后在以后删除答案,还将命令记录在一个通道中)。

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

我试图删除该应用程序并重新创建它,但效果很好:该消息仅显示一次,直到重新启动机器人为止。

我执行了一个“!stop”命令,该命令破坏了客户端,但是没有按预期工作:僵尸程序已断开连接(在控制台中表示“停止”),但是几乎立即在服务器上重新连接(我没有再也无法在本地控制台中看到日志了。

尽管消息数量似乎有点“随机”。某些漫游器消息有时也根本不会被删除,也不会被记录。

这是我的代码(我以前从未真正在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);
    }
}

因此,我的问题是:如何确保我的代码仅运行一个实例? (如果我正确推断了问题)。任何帮助表示赞赏。谢谢!

2 个答案:

答案 0 :(得分:1)

您不需要创建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);

答案 1 :(得分:0)

通过像@slothiful建议一样简单地将其托管在Heroku上即可解决该问题!我猜我的脚本一次又一次地重新启动,并且与不和谐服务器的连接成倍增加了?完全是Idk。事实是,它现在工作正常,只有一个实例正在处理我的命令。