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

How to find a User ID from a Username in Discord.js?(如何从 Discord.js 中的用户名中查找用户 ID?)
本文介绍了如何从 Discord.js 中的用户名中查找用户 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个包含 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).

这篇关于如何从 Discord.js 中的用户名中查找用户 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Using discord.js to detect image and respond(使用 discord.js 检测图像并响应)
Check if user ID exists in Discord server(检查 Discord 服务器中是否存在用户 ID)
Guild Member Add does not work (discordjs)(公会成员添加不起作用(discordjs))
Creating my first bot using REPLIT but always error Discord.JS(使用 REPLIT 创建我的第一个机器人,但总是错误 Discord.JS)
How do I code event/command handlers for my Discord.js bot?(如何为我的 Discord.js 机器人编写事件/命令处理程序?)
DeprecationWarning: Collection#find: pass a function instead(DeprecationWarning: Collection#find: 传递一个函数)