skip to Main Content

Is there a way to check if a specific user id exists within the server? without using cache
I couldn’t find a working code, whether or not the user had never chatted

commands.add('test3', (arg) =>{
    
var exists = bot.users.cache.has(arg);
    
    if (exists == true) { msg.channel.send('1'); }else { msg.channel.send('2');} //msg.sme{e
}); 

This is a temporary command for testing. When user send a command with @anyuser, the bot needs to make sure the user is on the server first (otherwise it could be crashed) but nothing I tried worked properly…

Is there a better way than this?

2

Answers


  1. Try to fetch the member through the guild member manager. An error will be thrown if the member does not exist. Use a try/catch block to handle the possible error.

    async function exists(guild, arg) {
       try {
          const member = await guild.members.fetch(arg);
          return !!member;
       } catch (err) {
          console.error(err);
          return false;
       }
    }
    
    Login or Signup to reply.
  2. You can use guild.members.fetch(userID) to fetch a member from the server by their user ID. If the user exists, it will return the member otherwise, it will throw an error.

    
      commands.add('test3', async (arg) => {
            try {
                const member = await msg.guild.members.fetch(arg);
                
               msg.channel.send(`User ID found: ${member.id}`);
               
            } catch (error) {
            
                 msg.channel.send('User not found on the server.');
            }
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search