[英]Getting username with user id in Discord.js TypeError: Cannot read property 'tag' of undefined
I currently have a leaderboard set up, but I'm trying to get the username of top 10 users in a server, but I'm having trouble converting a user ID to the username.我目前设置了排行榜,但我正在尝试获取服务器中前 10 位用户的用户名,但是我在将用户 ID 转换为用户名时遇到了问题。
Firstly, I use a for loop to loop through each user within my database:首先,我使用 for 循环遍历数据库中的每个用户:
for(let userID of Object.keys(userdata[message.guild.id].users)){
My JSON file looks something like this:我的 JSON 文件如下所示:
"83xxxxxxxxxx90": { //server ID
"users": {
"24xxxxxxxxxxxx64": { //user ID
"count": [
16,
5,
2,
10,
10
],
"username": "username#0001"
},
"70xxxxxxxxxxxxxx63": { //second user ID
"count": [
15,
4,
4,
1,
12
],
"username": "username#0002"
},
The problem is when I use client.user.cache.get()
, the .get() part is not recognized, and I get a TypeError: Cannot read property 'tag' of undefined
error.问题是当我使用
client.user.cache.get()
,无法识别 .get() 部分,并且我收到TypeError: Cannot read property 'tag' of undefined
错误。
For comparison, I ran these two lines of code side by side, but only the second line gave an error:为了比较,我并排运行了这两行代码,但只有第二行出现错误:
console.log(client.users.cache.get(message.author.id).tag);
console.log(client.users.cache.get(userID).tag);
Has anyone ever encountered this issue?有没有人遇到过这个问题? Help is much appreciated.
非常感谢帮助。 Thanks!
谢谢!
Edit: I did some more testing and figured out the error was because client.user.cache.get(userID)
would return an undefined user, while client.user.cache.get(message.author.id)
would not.编辑:我做了一些更多的测试并发现错误是因为
client.user.cache.get(userID)
会返回一个未定义的用户,而client.user.cache.get(message.author.id)
不会。 Anyone know the reason for this?有谁知道这是什么原因?
您可以直接从author
那里获取.tag
只需执行message.author.tag
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.