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

2022-01-10 00:00:00 javascript discord.js

我有一个包含 Discord 用户名(即 JohnDoe#1234)的 json 文件 (localJSON.json),并且需要从这些用户名中获取用户 ID 才能添加角色.我在网上查看的每个地方都导致 rMember 的值为未定义"或空".验证添加角色的代码在给定用户 ID 作为字符串时有效,但找不到如何从用户名获取用户 ID.如何使用 Discord.js 从用户名中获取用户 ID?

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

推荐答案

你会想做的

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

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

相关文章