I wonder if you can help (I search it and nothing...) I am learning how to work with discord.js node and I want to change my user nickname (not the username itself)
My code is
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', message => {
if (message.content.includes('changeNick')) {
client.setNickname({nick: message.content.replace('changeNick ', '')});
}
});
client.login('token');
Discord.js implements changing nicknames by getting the GuildMember from the message, and using the GuildMember#setNickname method. Here's a simple example of setting the nickname of the user who ran the message:
if (message.content.includes('changeNick')) {
message.member.setNickname(message.content.replace('changeNick ', ''));
}
But this simply won't do in the case of your bot not having permission to set a user's nickname. If you want to set a user's nickname, the bot itself will have to have permission to set nicknames. This requires a little more trickery, but you can do this using Guild#me to get the GuildMember, and then use GuildMember#hasPermission to check for the MANAGE_NICKNAMES permission found in Permissions#Flags. I know this can be a lot to take in, so here's an example of doing everything I just said put together.
if (message.content.includes('changeNick')) {
if (!message.guild.me.hasPermission('MANAGE_NICKNAMES')) return message.channel.send('I don\'t have permission to change your nickname!');
message.member.setNickname(message.content.replace('changeNick ', ''));
}
And this will work to set the user who ran the command's nickname. But what if we want to change the BOT'S nickname, not the user's? Well that's simple. We can just replace message.member.setNickname
with message.guild.me.setNickname
, similarly to how we checked permissions. This will change the bot's nickname instead of the user who ran the command's. Happy coding!