How to find a User ID from a Username in Discord.js?(如何从 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 Discord.js 中的用户名中查找用户 ID?


基础教程推荐
- Chart.js 在线性图表上拖动点 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01