Hey there, could you make my code more robust? It likes to throw a lot of false negatives. Remove the server caching, and make the commands not update the list. Whole code pretty please.
const axios = require('axios');
const fs = require('fs');
const { Client, GatewayIntentBits, Permissions } = require('discord.js');


const PING_INTERVAL = 60 * 60 * 1000;
const PLACE_ID = '2202352383';
const TRACKED_USERS_FILE = 'tracked_users.json';
const MESSAGE_ID_FILE = 'message_id.json';
const COMMAND_PREFIX = 'force';
let TRACKED_USERS = [];

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
    ],
});

const userStatus = {};
let statusMessageId = null;

let cachedPublicServers = [];
let cacheTimestamp = 0;
const CACHE_DURATION = 5 * 60 * 1000;

const loadTrackedUsers = () => {
    try {
        if (fs.existsSync(TRACKED_USERS_FILE)) {
            const data = fs.readFileSync(TRACKED_USERS_FILE, 'utf8');
            TRACKED_USERS = JSON.parse(data);
            console.log(`Loaded ${TRACKED_USERS.length} tracked users from ${TRACKED_USERS_FILE}`);
        } else {
            fs.writeFileSync(TRACKED_USERS_FILE, JSON.stringify(TRACKED_USERS, null, 4));
            console.log(`Initialized ${TRACKED_USERS.length} tracked users and created ${TRACKED_USERS_FILE}`);
        }
    } catch (error) {
        console.error('Error loading tracked users:', error);
    }
};

// Function to save tracked users to file
const saveTrackedUsers = () => {
    try {
        fs.writeFileSync(TRACKED_USERS_FILE, JSON.stringify(TRACKED_USERS, null, 4));
        console.log(`Saved ${TRACKED_USERS.length} tracked users to ${TRACKED_USERS_FILE}`);
    } catch (error) {
        console.error('Error saving tracked users:', error);
    }
};

// Load tracked users on startup
loadTrackedUsers();

// Event listener for when the bot is ready
client.once('ready', () => {
    console.log('Bot is ready!');
    loadMessageId();
    trackUsers();
});

// Function to load status message ID from file
const loadMessageId = () => {
    try {
        if (fs.existsSync(MESSAGE_ID_FILE)) {
            const data = fs.readFileSync(MESSAGE_ID_FILE, 'utf8');
            const json = JSON.parse(data);
            statusMessageId = json.messageId;
            console.log(`Loaded status message ID: ${statusMessageId}`);
        } else {
            console.log(`${MESSAGE_ID_FILE} does not exist. A new status message will be created.`);
        }
    } catch (error) {
        console.error('Error loading message ID:', error);
    }
};

// Function to save status message ID to file
const saveMessageId = (messageId) => {
    try {
        const data = JSON.stringify({ messageId }, null, 4);
        fs.writeFileSync(MESSAGE_ID_FILE, data);
        console.log(`Saved status message ID: ${messageId}`);
    } catch (error) {
        console.error('Error saving message ID:', error);
    }
};

// Command handling
client.on('messageCreate', async (message) => {
    if (message.author.bot || !message.content.startsWith(COMMAND_PREFIX)) return;

    const args = message.content.slice(COMMAND_PREFIX.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    switch (command) {
        case 'addkos':
            await handleForceAddKos(message, args);
            break;
        case 'removekos':
            await handleForceRemoveKos(message, args);
            break;
        case 'updatekos':
            await handleForceUpdateKos(message);
            break;
        case 'find':
            await handleForceFind(message, args);
            break;
        default:
            break;
    }
});

// Handler for adding a user to KOS
const handleForceAddKos = async (message, args) => {
    if (args.length !== 1) {
        return message.reply('No user to add');
    }

    const username = args[0];

    if (TRACKED_USERS.includes(username)) {
        return message.reply(`\`${username}\` is already on there`);
    }

    // Optionally, verify if the username exists on Roblox
    const userId = await getUserId(username);
    if (!userId) {
        return message.reply(`\`${username}\` wasnt found on roblox`);
    }

    TRACKED_USERS.push(username);
    saveTrackedUsers();
    message.reply(`\`${username}\` has been added to the list`);
};

const handleForceRemoveKos = async (message, args) => {
    if (args.length !== 1) {
        return message.reply('Who do i remove');
    }

    const username = args[0];

    const index = TRACKED_USERS.indexOf(username);
    if (index === -1) {
        return message.reply(`\`${username}\` is not in the list`);
    }

    TRACKED_USERS.splice(index, 1);
    saveTrackedUsers();
    message.reply(`\`${username}\` has been removed from the list`);
};

const handleForceUpdateKos = async (message) => {
    loadTrackedUsers();
};

const handleForceFind = async (message, args) => {
    if (args.length !== 1) {
        return message.reply('What');
    }

    const username = args[0];
    const userId = await getUserId(username);

    if (!userId) {
        return message.reply(`\`${username}\` was not found on roblox`);
    }

    try {
        // Fetch public servers with caching
        const allServers = await fetchAllPublicServersCached(PLACE_ID);

        if (allServers.length === 0) {
            return message.reply('You did this too early');
        }

        // Flatten player tokens
        const allPlayerTokens = allServers.flatMap(server => 
            server.playerTokens.map(token => ({ token, serverId: server.id }))
        );

        // Get thumbnail ID
        const thumbnailUrl = await getThumb(userId);
        if (!thumbnailUrl) {
            return message.reply(`error`);
        }

        const thumbnailIdMatch = thumbnailUrl.match(/([A-F0-9]{32})/i);
        if (!thumbnailIdMatch) {
            return message.reply(`error`);
        }

        const thumbnailId = thumbnailIdMatch[0].toUpperCase();

        // Find user in public servers
        const result = await findUserInPublicServers(allPlayerTokens, thumbnailId);

        if (result.found) {
            const userLink = `roblox://placeID=${PLACE_ID}&gameInstanceId=${result.serverId} [roblox.com/games/2202352383/SPTS-Classic#jobid=${result.serverId}]`;
            return message.reply(`\`${username}\` is in a public server (${userLink})`);
        } else {
            return message.reply(`\`${username}\` is offline`);
        }
    } catch (error) {
        console.error(`Error in forcefind for ${username}:`, error);
        return message.reply('Error');
    }
};

// Modified fetchAllPublicServers with caching
const fetchAllPublicServersCached = async (placeId) => {
    const now = Date.now();
    if (cachedPublicServers.length > 0 && (now - cacheTimestamp) < CACHE_DURATION) {
        console.log('Using cached public servers data.');
        return cachedPublicServers;
    }

    console.log('Fetching public servers data from Roblox...');
    const allServers = await fetchAllPublicServers(placeId);
    cachedPublicServers = allServers;
    cacheTimestamp = now;
    return allServers;
};

// Existing trackUsers function
const trackUsers = async () => {
    try {
        const allServers = await fetchAllPublicServers(PLACE_ID);
        const allPlayerTokens = allServers.flatMap(server => 
            server.playerTokens.map(token => ({ token, serverId: server.id }))
        );

        let statusChanged = false;
        let messageContent = "```diff\n";
        let usersToPing = [];

        for (let username of TRACKED_USERS) {
            const userId = await getUserId(username);
            if (!userId) {
                console.warn(`User ID not found for username: ${username}`);
                continue;
            }

            const isOnline = await checkOnlineStatus(userId);
            let isInPublicServer = false;
            let serverId = null;

            if (isOnline) {
                const thumbnailUrl = await getThumb(userId);
                if (thumbnailUrl) {
                    const thumbnailIdMatch = thumbnailUrl.match(/([A-F0-9]{32})/i);
                    if (thumbnailIdMatch) {
                        const thumbnailId = thumbnailIdMatch[0].toUpperCase();
                        const result = await findUserInPublicServers(allPlayerTokens, thumbnailId);
                        if (result.found) {
                            isInPublicServer = true;
                            serverId = result.serverId;
                        }
                    }
                }
            }

            const currentTime = Date.now();
            if (
                !userStatus[username] ||
                userStatus[username].isOnline !== isOnline ||
                userStatus[username].isInPublicServer !== isInPublicServer
            ) {
                statusChanged = true;
                
                if (isOnline && isInPublicServer) {
                    if (!userStatus[username] || !userStatus[username].lastPingTime || 
                        (currentTime - userStatus[username].lastPingTime >= PING_INTERVAL)) {
                        usersToPing.push(username);
                        userStatus[username] = { 
                            ...userStatus[username], 
                            lastPingTime: currentTime 
                        };
                    }
                }
            }

            userStatus[username] = { 
                ...userStatus[username], 
                isOnline, 
                isInPublicServer, 
                serverId 
            };

            if (isOnline && isInPublicServer) {
                messageContent += `+ ${username} (Online) - Server: roblox://placeID=${PLACE_ID}&gameInstanceId=${serverId}\n\n [roblox.com/games/2202352383/SPTS-Classic#jobid=${serverId}]`;
            } else {
                messageContent += `- ${username} (Offline)\n\n`;
            }
        }

        messageContent += "```";

        if (statusChanged) {
            const channel = await client.channels.fetch(DISCORD_CHANNEL_ID);
            if (!channel) {
                console.error(`Channel with ID ${DISCORD_CHANNEL_ID} not found.`);
                return;
            }

            if (statusMessageId) {
                try {
                    const oldMessage = await channel.messages.fetch(statusMessageId);
                    await oldMessage.edit(messageContent);
                } catch (error) {
                    console.error('Failed to edit existing message:', error);
                    statusMessageId = null;
                }
            }

            if (!statusMessageId) {
                const newMessage = await channel.send(messageContent);
                statusMessageId = newMessage.id;
                saveMessageId(statusMessageId);
            }

            // Ping for users who came online and meet the rate limit criteria
            if (usersToPing.length > 0) {
                const channel2 = await client.channels.fetch('1295508784592064583');

                if (channel2) {
                    const pingMessage = `@everyone - the following KOS users are now online: ${usersToPing.join(', ')}`;
                    await channel2.send(pingMessage);
                } else {
                    console.error('Ping channel not found.');
                }
            }
        }
    } catch (error) {
        console.error('Error in trackUsers:', error);
    } finally {
        // Schedule the next tracking run
        setTimeout(trackUsers, 30000); // Run every 30 seconds
    }
};

// Existing helper functions...

const getUserId = async (username) => {
    try {
        const response = await axios.post(
            'https://users.roblox.com/v1/usernames/users',
            {
                usernames: [username],
                excludeBannedUsers: false,
            },
            {
                headers: {
                    'Content-Type': 'application/json',
                },
            }
        );

        if (response.data && response.data.data && response.data.data.length > 0) {
            return response.data.data[0].id.toString();
        } else {
            console.warn(`No data returned for username: ${username}`);
            return null;
        }
    } catch (error) {
        console.error(`Error fetching user ID for ${username}:`, error);
        return null;
    }
};

const getThumb = async (userId) => {
    try {
        const response = await axios.get(
            `https://thumbnails.roblox.com/v1/users/avatar-headshot?userIds=${userId}&size=150x150&format=Png&isCircular=false`
        );
        if (response.data && response.data.data && response.data.data[0].imageUrl) {
            return response.data.data[0].imageUrl;
        } else {
            console.warn(`No thumbnail URL found for user ID: ${userId}`);
            return null;
        }
    } catch (error) {
        console.error(`Error fetching thumbnail for user ID ${userId}:`, error);
        return null;
    }
};

const checkOnlineStatus = async (userId) => {
    try {
        const response = await axios.post(
            'https://presence.roblox.com/v1/presence/users',
            {
                userIds: [parseInt(userId)],
            },
            {
                headers: {
                    'Content-Type': 'application/json',
                },
            }
        );

        const userPresence = response.data.userPresences[0];
        return userPresence && userPresence.userPresenceType === 2;
    } catch (error) {
        console.error(`Error checking online status for user ID ${userId}:`, error);
        return false;
    }
};

// Modified fetchAllPublicServers to include error handling
const fetchAllPublicServers = async (placeId) => {
    let cursor = null;
    let allServers = [];

    try {
        while (true) {
            const response = await getPublicServers(placeId, cursor);
            if (!response || !response.data) {
                break;
            }

            allServers.push(...response.data);

            if (!response.nextPageCursor) {
                break;
            }

            cursor = response.nextPageCursor;
        }
    } catch (error) {
        console.error('Error fetching public servers:', error);
    }

    return allServers;
};

const getPublicServers = async (placeId, cursor) => {
    try {
        let url = `https://games.roblox.com/v1/games/${placeId}/servers/Public?limit=25`;
        if (cursor) {
            url += `&cursor=${cursor}`;
        }

        const response = await axios.get(url);
        return response.data;
    } catch (error) {
        console.error(`Error fetching public servers for place ID ${placeId}:`, error);
        return null;
    }
};

const findUserInPublicServers = async (allPlayerTokens, thumbnailId) => {
    try {
        const chunkSize = 100;
        for (let i = 0; i < allPlayerTokens.length; i += chunkSize) {
            const chunk = allPlayerTokens.slice(i, i + chunkSize);

            const body = chunk.map((item) => ({
                requestId: `${item.token}:${item.serverId}`,
                type: 'AvatarHeadShot',
                targetId: 0,
                token: item.token,
                format: 'png',
                size: '150x150',
            }));

            const response = await axios.post('https://thumbnails.roblox.com/v1/batch', body, {
                headers: {
                    'Content-Type': 'application/json',
                    Accept: 'application/json',
                },
            });

            if (response.data && response.data.data) {
                for (let thumbnail of response.data.data) {
                    if (thumbnail && thumbnail.imageUrl) {
                        const imageIdMatch = thumbnail.imageUrl.match(/([A-F0-9]{32})/i);
                        if (
                            imageIdMatch &&
                            imageIdMatch[0].toUpperCase() === thumbnailId.toUpperCase()
                        ) {
                            const [token, serverId] = thumbnail.requestId.split(':');

                            return { found: true, serverId };
                        }
                    }
                }
            }
        }
    } catch (error) {
        console.error('Error in findUserInPublicServers:', error);
    }

    return { found: false };
};

// Login to Discord
client.login(DISCORD_TOKEN);