discord.js 终端关闭后机器人下线

discord.js bot goes offline after terminal being closed

我的 discord 机器人遇到这个问题已经有一段时间了,即使进程仍在 运行。

我试过使用 nohup node index.js & 然后 disown -a 最后 exit,但机器人仍然死机。

请注意,它不会立即消失,而是在我关闭终端后大约 30 分钟到一个小时,并且 nohup.out 中没有错误消息。但是当我用top的时候,过程还是运行.

我在 Ubuntu-20.04 使用 Google 云服务虚拟机,discord.js 13.6.0,Node.js v17.9.0

我的代码如下所示:

index.js

const discord = require(“discord.js”);

const allIntents = new discord.Intents(32767);
const client = new discord.Client({intents: [allIntents]});

const sleep = (ms) => new Promise(r => setTimeout(r, ms));

require(“dotenv”).config();

client.on(“ready”, async () => {
    console.log(`Logged in as ${client.user.tag}!`);
    client.user.setStatus(“idle”);
    createSlashCommands(client);
    
    var stats = [“hi”, “hello”];
    const length = stats.length;
    for (let i = 0, true, i = (i+1)%length) {
         client.user.setActivity(stats[i], {type: 3});
         await sleep(10000);
    }
});

message.on(“messageCreate”, async (message) => {
    if (client.isReady() && !message.author.bot) {
        if (message.content === “t!ping”) {
            message.reply({content: `Pong! ${Date.now() - message.createdTimestamp}ms`});
        }
    }
});

client.on(“interactionCreate”, async (interaction) => {
    if (client.isReady() && !message.author.bot) {
        if (interaction.commandName === “ping”) {
            interaction.reply({content: `Pong! ${Date.now() - interaction.createdTimestamp}ms`});
        }
    }
});

client.login(process.env.mybot);

有没有其他方法可以防止我的机器人离线?还是我做错了什么?

我找到并使用(而且是免费的)的最佳解决方案是 pm2

https://pm2.keymetrics.io/

npm i pm2 -g

// navigate to the folder with your main bot.js file (in this example it is called index.js)

pm2 start index.js

// followed by

pm2 save

// Optionally you can monitor the whole server as well with

pm2-server-monit

还有一个免费的仪表板

至于你的代码,我会做一些修改

// change:
client.on(“ready”, async () => {

// to:
client.once("ready", async () => {

另外,这些实际上永远都不需要,因为如果客户端没有准备好,它就不会捕获事件

到处刮这个

client.isReady() && 
// Lastly, this needs to be 
client.on("messageCreate"
 
// rather than
message.on("messageCreate"

编辑: 不要让代码中的调试一直处于活动状态,除非你只是想这样做。 将其放入您的代码中,如图所示

// prev code
require(“dotenv”).config();

// Error Logging
client.on('error', (e) => {
    console.log(e)
})
client.on('warn', (e) => {
    console.log(e)
})
// comment the below one out when not using it to debug
client.on('debug', (e) => {
    console.log(e)
})
process.on('unhandledRejection', (error) => {
    console.log('Unhandled promise rejection:', error)
})

client.once(“ready”, async () => {
// code following