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

人盡茶涼 提交于 2021-01-27 13:47:21

问题


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);
  }
}

回答1:


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).



来源:https://stackoverflow.com/questions/61284468/how-to-find-a-user-id-from-a-username-in-discord-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!