Search code examples
mongodbdiscord.jswhitelist

Send message and leave server on ready event if not whitelisted (Discord.JS + MongoDB)


I'm coding a whitelist system for my discord bot that, on ready event (and after a 3 seconds delay), checks if every server it is in has it's ID added to the whitelist database on MongoDB. If not, the bot sends an embed and leaves the server. I managed to get it working on the guildCreate event, but on ready event it performs the message and leave actions on every single server without filtering conditions, even though those are added to the list. I cannot figure out why. Also, I'm still new to JavaScript, so it could be just a minor mistake.

//VARIABLES
const { Client, MessageEmbed } = require("discord.js")
const config = require('../../Files/Configuration/config.json');
const DB = require("../../Schemas/WhitelistDB");

//READY EVENT
module.exports = {
  name: "ready",
  once: false,
  async execute(client) {

//[ ... ]     <--- OTHER UNNECESSARY CODE IN BETWEEN

    setTimeout(function() {    // <--- 3 SECONDS DELAY

      client.guilds.cache.forEach(async (guild) => {    // <--- CHECK EVERY SERVER

        await DB.find({}).then(whitelistServers => {    // <--- CHECK MONGODB ID LIST

          if(!whitelistServers.includes(guild.id)) {
            const channel = guild.channels.cache.filter(c => c.type === 'GUILD_TEXT').random(1)[0];    // <--- SEND MESSAGE TO RANDOM TEXT CHANNEL (It is sending to every server, when it should be sending only to the not whitelisted ones)
              if(channel) {
                const WhitelistEmbed = new MessageEmbed()
                WhitelistEmbed.setColor(config.colors.RED)
                WhitelistEmbed.setDescription(`${config.symbols.ERROR} ${config.messages.SERVER_NOT_WHITELISTED}`)
                channel.send({embeds: [WhitelistEmbed]});
              }
            client.guilds.cache.get(guild.id).leave();    // <--- LEAVE SERVER (It is leaving every server, when it should be leaving only the not whitelisted ones)
          } else { return }
        });

      });

    }, 1000 * 3);

  }
}

Solution

  • I found the solution myself!

    Instead of finding the array of whitelisted ID's for each guild, find one at a time and instead of checking the content of the array, check if the array exists. This is the updated code:

    //WHITELIST
    setTimeout(function() {
    
      client.guilds.cache.forEach(async (guild) => {
    
        await DB.findOne({ GuildID: guild.id }).then(whitelistServers => {
          if(!whitelistServers) {
            const channel = guild.channels.cache.filter(c => c.type === 'GUILD_TEXT').random(1)[0];
              if(channel) {
                const WhitelistEmbed = new MessageEmbed()
                WhitelistEmbed.setColor(config.colors.RED)
                WhitelistEmbed.setDescription(`${config.symbols.ERROR} ${config.messages.SERVER_NOT_WHITELISTED}`)
                channel.send({embeds: [WhitelistEmbed]});
              }
            client.guilds.cache.get(guild.id).leave();
          } else { return }
        });
    
      });
    
    }, 1000 * 3);