Check if user with a specific ID exists

Viewed 185

I know you can get server member using let user = guild.members.cache.get('ID') and then check if member exists using if(!user) return, but how can I get a user with specific ID and check if this user exist at all if my bot doesn't share any servers with them?

1 Answers

This would be more suited as a comment to another answer but I can't yet add them so;

The second method in the answer I'm referencing is the best way, however is incorrect. client.users.fetch() does not return undefined. If no user exists, it errors, so instead you must do

let user;
try {
    user = await client.users.fetch("id", { force: true, cache: true }); // force skips cache checking so they don't need to be cached by the bot, cache will cache the user
} catch(err) {
    user = undefined;
}

// or
client.users.fetch("id", { force: true, cache: true })
.then(user => {
    // do something
})
.catch(err => {
    // user doesn't exist or another error occurred 
})
Related