My goal is to have a file run every few minutes on a schedule(cron). The cron isn't the issue, the issue is when I try and retrieve the members, I get Collection(0) [Map] {} Which is odd, there are members and my intents are set correctly.
const dotenvFlow = require('dotenv-flow');
const { Client, Partials, GatewayIntentBits } = require('discord.js');
dotenvFlow.config();
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildIntegrations, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessages, GatewayIntentBits.DirectMessageTyping, GatewayIntentBits.DirectMessages], partials: [Partials.Channel] });
// Get the guild object
async function updateMembers() {
console.log("Starting...")
const guild = await client.guilds.fetch(process.env.hostDiscordServer);
// Get the members of the guild
const members = guild.members.cache;
// Insert or update each member in the database
members.forEach(member => {
// Check if the member belongs to the specified guild
if (member.guild.id === guild.id) {
// Get the member's premium role
const pRole = member.roles.cache.find(role => [process.env.pPremiumRole1, process.env.pPremiumRole2, process.env.pPremiumRole3].includes(role.name))?.name;
console.log("Inserting into DB")
// Insert or update the member's record in the database
console.log(member.id)
console.log(pRole)
}
});
}
// Log in to Discord with your client's token
client.login(process.env.DISCORD_TOKEN);
// Start the code
updateMembers();
You are iterating through the cached members of the guild. If you want to iterate through all members (even the uncached) you need to fetch them first.
You just need to replace
const members = guild.members.cache;
with
const members = await guild.members.fetch();
EDIT: I would also recommend changing
updateMembers();
to
client.once("ready", updateMembers);
so that the code only runs when the bot ready.
(Thanks to @Zsolt Meszaros for correcting me on that one)