You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoClient与DiscordClient连接不稳定,运行表现异常求助

Fixing Unstable MongoDB Atlas & Discord.js Connections for Your Discord Bot

Hey there, let's tackle those frustrating random connection timeouts and failures you're facing. I've spotted a few key issues in your code and some configuration tweaks that should stabilize things.

1. Critical Discord.js Intent Issue (Likely Causing Random Login Failures)

If you're using Discord.js v13 or newer, creating a Client without specifying intents will almost certainly cause login failures or incomplete functionality. Discord's API now requires explicit permission to access guild data, messages, and other resources.

Add the necessary intents when initializing your Discord client:

const client = new Discord.Client({
  intents: [
    Discord.Intents.FLAGS.GUILDS, // Required for guild/server access
    Discord.Intents.FLAGS.GUILD_MESSAGES // Required for message-related commands
    // Add other intents based on your bot's features (e.g., GUILD_VOICE_STATES for voice commands)
  ]
});

2. Improve MongoDB Connection Stability

Your current Mongo connection lacks retry logic and has a long default timeout (30 seconds). Let's adjust the connection options to reduce wait times and add automatic retries for better reliability:

const mongoOptions = {
  useUnifiedTopology: true,
  serverSelectionTimeoutMS: 10000, // Shorten timeout to 10 seconds for faster feedback
  retryWrites: true, // Automatically retry failed write operations
  retryReads: true, // Automatically retry failed read operations
  heartbeatFrequencyMS: 5000 // Check server health more frequently
};

Pass this mongoOptions object to MongoClient.connect() instead of just { useUnifiedTopology: true }.

3. Fix Connection Flow & Error Handling

Right now, you're calling client.login() outside the Mongo connection promise chain. This means Discord and Mongo are connecting in parallel, and if one fails, the other might run without proper cleanup. Let's sync the flow and add detailed error logging to debug issues faster:

Here's the revised full code with all fixes applied:

const path = require('path');
const fs = require('fs');
const config = require('./config.json');
const Discord = require('discord.js');
const client = new Discord.Client({
  intents: [
    Discord.Intents.FLAGS.GUILDS,
    Discord.Intents.FLAGS.GUILD_MESSAGES
  ]
});
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const connectionURL = config.connectionURL;

const mongoOptions = {
  useUnifiedTopology: true,
  serverSelectionTimeoutMS: 10000,
  retryWrites: true,
  retryReads: true,
  heartbeatFrequencyMS: 5000
};

console.log('Starting up Mongo Client...');
MongoClient.connect(connectionURL, mongoOptions)
 .then((dbclient) => {
    console.log('Established connection with MongoDB...\n');
    console.log('Starting up Discord Client...');
    
    // Login to Discord only after Mongo connects successfully
    client.login(config.token)
      .then(() => {
        console.log('Established connection with Discord...');
        console.log(`Logged in as ${client.user.tag}!\n`);

        const baseFile = 'command-base.js';
        const commandBase = require(`./commands/${baseFile}`);

        const readCommands = (dir) => {
          const files = fs.readdirSync(path.join(__dirname, dir));
          for (const file of files) {
            const stat = fs.lstatSync(path.join(__dirname, dir, file));
            if (stat.isDirectory()) {
              readCommands(path.join(dir, file));
            } else if (file !== baseFile) {
              const options = require(path.join(__dirname, dir, file));
              commandBase(dbclient, client, options);
            }
          }
        };

        readCommands('commands');
      })
      .catch(discordErr => {
        console.error('Failed to connect to Discord:', discordErr);
        dbclient.close(); // Clean up Mongo connection if Discord fails
      });
 })
 .catch((err) => {
    console.error('Unable to connect to MongoDB:', err); // Log full error details for debugging
    return;
 });

4. Additional Troubleshooting Steps

If you still see issues after applying the above fixes:

  • Check your network: Even with Atlas's 0.0.0.0/0 whitelist, some networks (like corporate or school firewalls) block outbound traffic on port 27017. Test connectivity to your Atlas cluster using tools like telnet or nc.
  • Update dependencies: Run rm -rf node_modules package-lock.json && npm install to refresh your dependencies—old versions of the Mongo driver or Discord.js can cause compatibility issues.
  • Verify your Atlas connection string: Ensure it includes your correct username, password, and cluster address (double-check for typos!).

内容的提问来源于stack exchange,提问作者Vrishin Vigneshwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:59:06