【问题标题】:My discord.js bot seems to be running multiple instances at the same time我的 discord.js 机器人似乎同时运行多个实例
【发布时间】:2019-09-23 00:14:45
【问题描述】:

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

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

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

我做了一个“!停止”命令来破坏客户端,但它没有按预期工作:机器人已断开连接(在我的控制台中说“停止”),但几乎立即在我的服务器上重新连接(我没有'在我的本地控制台中看不到日志了)。

关于消息的数量似乎有点“随机”。有些机器人消息有时也根本不会被删除,也不会被记录。

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

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

【问题讨论】:

  • 您是在使用 Heroku 或其他服务来托管机器人,还是在您的计算机上运行节点?
  • @slothiful 我在我的电脑上运行“npm run start”(其中 start 运行“node index.js”)

标签: javascript node.js discord discord.js


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你不需要做一个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);
    

    【讨论】:

    • 是的,我知道,只有我想使用函数,因为我更习惯 Java,这让我很不安 x) 它真的会影响性能吗?
    • @GuillaumeVDN 我只是不习惯按照你的方式去做,我认为这是你的问题.. 但如果它仍然执行 onready 和 onmessage 我猜应该没问题
    猜你喜欢
    • 2020-07-19
    • 2018-06-18
    • 1970-01-01
    • 2020-12-04
    • 2022-10-18
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    相关资源
    最近更新 更多