Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a User ID from a Username in Discord.js?

I have a json file (localJSON.json) with Discord usernames (i.e. JohnDoe#1234) and need to get the User IDs from these usernames in order to have a role added. Every place I have looked online has resulted with either an 'undefined' or 'null' value for rMember. Verified that the code to add a role works when given a User ID as a string, but can't find how to get a User ID from a username. How do I get a user's ID from their Username using Discord.js?

localJSON.json
[
  {
    "discordName": "JohnDoe#1234"
  },
  {
    "discordName": "MarySue#5678"
  }
]
function addRole(discordUsername, gameName, message){
  var roleName = "";
  //Switch statement to assign roleName to a valid guild role based on argument

  var userID = discordUsername.id; //Pseudo code, Need to accomplish this

  var rMember = message.guild.members.get(userID); //Needs UserID as string
  var gRole = message.guild.roles.find((role) => role.name == roleName); 
  if (!rMember) { //if member not in server
    message.channel.send(rMember + " is not in the server!");
  } else { //assign role
    rMember.addRole(gRole);
  }
}

async run(message, args){
  ...
  for (var i = 0; i < localJSON.length; i++) {
     var currentEntry = localJSON[i];
     var currrentUserName = currentEntry.discordName;
     addRole(currrentUserName, args, message); //addRole(discordUsername, gameName, message);
  }
}
like image 277
Conman 1161 Avatar asked Apr 18 '20 05:04

Conman 1161


People also ask

How do you get a user's ID in Discord?

To find a user's Discord ID (including your own), tap their profile picture to open their profile, then tap the three dots in the top-right corner and select Copy ID.

What is User ID in Discord?

Your Discord User ID is an eighteen digit number, and is not the same as your username. You can find your User ID by following the steps below: On Discord, go to Settings > Advanced. Scroll down and make sure that Developer Mode is on. Exit your settings and type a message in any channel on any server.

How do I find my Discord ID and name?

On Android press and hold the Server name above the channel list. You should see the last item on the drop-down menu: 'Copy ID'. Click Copy ID to get the ID. On iOS you'll click on the three dots next to the Server's name and select Copy ID.


1 Answers

You'll want to do

client.users.cache.find(u => u.tag === 'Someone#1234').id

Discord.js v12 uses .cache now, so you have to run find on the cache, and v12 also removes Collection#find(key, value) in favor of Collection#find(data => data.key === value).

like image 199
nova Avatar answered Oct 11 '22 07:10

nova