简体   繁体   中英

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.

Firstly, I use a for loop to loop through each user within my database:

for(let userID of Object.keys(userdata[message.guild.id].users)){

My JSON file looks something like this:

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

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. Anyone know the reason for this?

您可以直接从author那里获取.tag只需执行message.author.tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM