Error fetching guild on client ready event

I have a function that will check for all guilds that have member count enabled
However this specific group of code seems to always fail to fetch the guild, even tho when evaluating the same code it succeeds.

This specific line const guild = await client.guilds.fetch(g.guild).catch(() => {}); always returns void or undefined. Even tho the provided guild ID is valid.
This function is called from the ClientReady event.

import Client from '@/app';
import Guild from '@/models/Guild';
import { ChannelType } from 'discord.js';
import { schedule } from 'node-cron';

export default async (client: Client) => {
    schedule('*/5 * * * *', async () => {
        const guilds = await Guild.find({ 'memberCount.enabled': true });
        for (const g of guilds) {
            if (!g.memberCount.channel) return;
            const guild = await client.guilds.fetch(g.guild).catch(() => {});
            if (!guild) return;
            const channel = await client.channels.fetch(g.memberCount.channel).catch(() => {});
            if (!channel) return;
            const members = await guild.members.fetch();
            const filtered = members.filter((m) => !m.user.bot);
            const ch = await channel.fetch();
            if (ch.type !== ChannelType.GuildVoice) return;
            await ch.edit({ name: g.memberCount.name ? g.memberCount.name.replace('{members}', filtered.size.toString()) : `Members: ${filtered.size}`, reason: 'Automated Action: Member Count Updated' });
        }
    });
};
Was this page helpful?