node.jsdiscord.jsfivem

Impossible to rename a member from its id


I am merging a bot under discord.js v12 to a newer bot with discord.js v14.

However it's my first experience on the node and I don't understand everything, I'm doing well in lua but I don't understand...

The events return me errors either it does not find the guild or it is impossible to rename a player, or a player is not found...

Here is how it is, I comment you the events according to the return of log that I have

on("DiscordBot:RenameMember", (guild, discordid, fullname) => {
let targetguild = client.guilds.cache.first(); // I got on log the name of GUILD
    if (targetguild) {
        let target = targetguild.members.fetch(discordid); // I got on log : [object Promise]
        if (target) {
            target.setNickname(fullname); // I got on log : TypeError: target.setNickname is not a function
            target.member.setNickname(fullname); // I got on log : TypeError: Cannot read properties of undefined (reading 'setNickname')
        }
    }
});

I made a multitude of tests with cache, without cache but nothing makes it all I find is similar and does not work here...

Here you will find the launch of the bot : https://hastebin.com/ovipelopam.js

And here is the file I made separately to find my way around : https://hastebin.com/azaraqituh.js

Do you have an idea ?


Solution

  • In your case targetguild.members.fetch(discordid) seems to return a Promise, which is an async operation. Therefore target has no value right away, but instead, has to either be awaited, or the rest of the code has to be put in the then function, that can be set to the promise.

    Here is an example where you await the promise to resolve. In order to achieve this you have to define your function as async, so that it itself returns a Promise:

    on("DiscordBot:RenameMember", async (guild, discordid, fullname) => {
    let targetguild = client.guilds.cache.first(); // I got on log the name of GUILD
        if (targetguild) {
            let target = await targetguild.members.fetch(discordid); // I got on log : [object Promise]
            if (target) {
                target.setNickname(fullname); // I got on log : TypeError: target.setNickname is not a function
                target.member.setNickname(fullname); // I got on log : TypeError: Cannot read properties of undefined (reading 'setNickname')
            }
        }
    });