'how do I make a setNickname command in discord.js

I created a Change Nickname command in discord.js v13, and It's not working. I am not getting any errors. My code:

        const target = message.mentions.members.first();
        const nickname = args.slice(1).join(' ');
        if(!target) return message.channel.send('Please specify a target to change nickname');
        if(!nickname) return message.channel.send('Please specify a nickname to change');


        target.setNickname(nickname);

I am using node.js v16

The Commands

This user's nickname should chnage to oskol



Solution 1:[1]

Your code is working for me, but make sure your bot has the following Permissions and the bot's role is above the role of the users who want to edit his nick: Change this: https://i.stack.imgur.com/lKP9h.png To this: https://i.stack.imgur.com/xX8GF.png Also make sure your command is lowercase because uppercase characters are not allowed in command names.

Solution 2:[2]

I'm going to throw a guess that the nickname you are trying to set is null or empty, this will cause discord to just reset the nickname to the users normal discord username.

Make sure to debug the values that are being passed on and providing such information when making a question on here as it will help people more easily help you.



With that said, the below code worked fine for me

    const target = msg.mentions.members.first();
    if (!target) return msg.reply('Please mention a user');
    const nick = args[1];
    if (!nick) return msg.reply('Please provide a nickname');
    const oldNick = target.nickname;
    if (oldNick === nick) return msg.reply('That user already has that nickname');
    console.log(`Changing ${target.user.tag}'s nickname from ${oldNick} to ${nick}`);
    target.setNickname('');

Solution 3:[3]

The code you provided seems to work correctly. The error might be your bot's intents. Make sure that you enabled/requested all intents you need for this command (guild members if I remember correctly). Make sure that you also gave your bot the required permissions: MANAGE_NICKNAMES in the server settings (roles).

Good luck!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FirephoenixX02
Solution 2 KibbeWater
Solution 3 loom