如何从Discord.js中的用户名中找到用户ID?

时间:2020-04-18 05:06:23

标签: javascript discord.js

我有一个带有Discord用户名(即JohnDoe#1234)的json文件(localJSON.json),需要从这些用户名中获取用户ID才能添加角色。我在网上查看过的每个地方的rMember值都为'undefined'或'null'。验证了在给用户ID作为字符串时添加角色的代码可以工作,但是找不到从用户名获取用户ID的方法。 如何使用Discord.js从用户名中获取用户的ID?

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

2 个答案:

答案 0 :(得分:1)

你想做

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

Discord.js v12现在使用.cache,因此您必须在缓存上运行find,并且v12还删除了Collection#find(key, value),而推荐使用Collection#find(data => data.key === value)

答案 1 :(得分:0)

您可以像这样通过用户名获取用户:

const guild = await client.guilds.cache.get('<GUILD ID>')

guild.members.fetch({
   query:'<SOMEUSERNAME>',
   limit: 1
})

const member = guildMember.first()