Discord.js:机器人执行离线命令时无法发送预定义通知消息问题
Hey there! I can spot exactly what's going wrong here. Your bot is shutting down before it gets a chance to send the message because of how asynchronous operations work in JavaScript, plus a duplicate server.close() call.
Let me break it down:
client.channels.fetch()andchannel.send()are asynchronous operations (they return Promises). That means they run in the background while the rest of your code keeps executing.- In your original code, right after starting the fetch/send process, you immediately call
server.close()again. This shuts down the bot's connection to Discord before the message ever gets sent successfully.
Here's how to fix it – we need to make sure server.close() only runs after the message has been sent (or if sending fails, still clean up):
Option 1: Using Promise chaining (keeping your original style)
if(message.content == config.goesOff){ client.channels.fetch(channelId.toString()) .then(channel => channel.send("The bot is shutting down")) .then(() => { console.log("Shutdown message sent, closing server..."); server.close(); }) .catch(error => { console.error("Failed to send shutdown message:", error); // Even if the message fails, we still want to shut down the server server.close(); }); return; }
Option 2: Using async/await (cleaner and easier to read)
If you convert your message handler to an async function, you can write this in a more straightforward way:
// Make sure your messageCreate handler is marked as async client.on('messageCreate', async (message) => { if(message.content == config.goesOff){ try { // Wait for the channel to be fetched const channel = await client.channels.fetch(channelId.toString()); // Wait for the message to be sent await channel.send("The bot is shutting down"); // Now close the server server.close(); } catch (error) { console.error("Error during shutdown:", error); // Fallback to closing the server even if something goes wrong server.close(); } return; } // Rest of your bot's command logic... });
The key change here is removing the extra server.close() outside the Promise chain/async block. This ensures the bot only disconnects after it's finished communicating with Discord's API to send the message.
内容的提问来源于stack exchange,提问作者Fusca

