UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions / setNickname - discord.js

I got an error when trying to set the nickname of a user
UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
I tested all variables with console log they're set as expected and the [prefix + "rename"] is recognize... Am I doing it wrong? ^^'
bot.on("message", msg => {
var renameID=[ChannelID]
var userID= msg.author;
var message = msg.content.split(' ');
var args = message.length
if (message[0] === prefix + "rename") {
if (msg.channel.id === RenameID){
if (args === 2){
msg.guild.member(userID).setNickname(message[1]);
msg.reply(" some text " + message[1]);
}
}
}
edit: the bot has admin rights on the server

In the guild's role settings, your bot's role is not above the role of the user you want to edit.
Once you change that, your code should work.

Related

I am making a bot hat gives a role to a user but it get's error that the bot doesn't have permissions

(the code)
const Command = require("../Structures/Command.js");
module.exports = new Command({
name: "give-role",
description: "gives you the role",
permission: "ADMINISTRATOR",
async run(message, arguments, client) {
const targetUser = message.mentions.users.first();
if (!targetUser) {
message.reply("Tag the user that you want to give the role to");
return;
}
arguments.shift();
const roleName = arguments[1];
const { guild } = message;
const role = guild.roles.cache.find((role) => {
return role.name === roleName;
});
if (!role) {
message.reply(`There is no role called: ${roleName}`);
return;
}
const member = guild.members.cache.get(targetUser.id);
member.roles.add(role);
message.reply(`That user now has the role : ${roleName}`);
}
});
(error message)
/home/runner/Discord-manager/node_modules/discord.js/src/rest/RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Missing Permissions
at RequestHandler.execute (/home/runner/Discord-manager/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/runner/Discord-manager/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async GuildMemberRoleManager.add (/home/runner/Discord-manager/node_modules/discord.js/src/managers/GuildMemberRoleManager.js:124:7) {
method: 'put',
path: '/guilds/911548130917498901/members/854133415364263976/roles/924275494810165259',
code: 50013,
httpStatus: 403,
requestData: { json: undefined, files: [] }
}
The error is DiscordAPIError: 50013, the error is getting because the prompt says the bot do not have permissions but I added administrator but it still says it doesn't have permissions and I do not know why. Please help me (sorry if my english is bad :() )
The bot may be trying to give a role higher than the one your bot has. To fix this, drag the bot's highest positioned role over the role you are trying to give.
Credit: Reddit Comment
You need to check the position of the role before trying to add it to the user, for example:
if (message.guild.me.roles.highest.position <= role.position) {
message.reply(`${role.name} is higher than or equal to my highest role.`);
return;
}

Command is giving the bot role

I'm trying to make a command that gives a user a role. It was working before, but not it just gives the bot a role.
module.exports = {
name: "addevent",
description: "Add the event ping role to a user",
async run(client, message, args) {
const { member } = message;
if (message.member.roles.cache.has('793222158981529621')) {
const { member } = message;
message.channel.send(`${member} You already have this role.`)
}
if (message.channel.id !== '793224633759432755') return;
member.roles.add('793222158981529621')
message.channel.send(`${member} Added the event ping role.`)
}
}
This is also happening to my level command that's supposed to check a user's level. It checks the bot's level, not the user's.
let role = message.guild.roles.cache.find(r => r.name === "Role Name Here");
if (message.channel.id !== 'Channel ID Here') return;
if (message.member.roles.cache.has(role.id)) {
return message.channel.send(`${message.member} You already have this role.`)
}
message.member.roles.add(role);
message.channel.send(`${message.member} Added the event ping role.`);
My example has a variable called role which finds the role by its name, so you have to provide the name of the role there. Your if-statement with the message.channel.id was understandable and is a nice way to get the role in only one channel. The second if-statement just asks if a user already has that role (dont forget: in .has() you have to provide an ID, in this case it is easily done with role.id). Anyways if the user has that role it will send a message and return. Otherwise it will add the role to the user and also send a message.

Make admins not kick each other

Making a kick command.
I am trying to make a command so that the admins cannot kick each other.
if(message.author.hasPermission('KICK_MEMBER', 'ADMINISTRATOR') && message.member.hasPermission('KICK_MEMBER', 'ADMINISTRATOR'))
return ('You cant kick another admin!')
But I get an error.
TypeError: message.author.hasPermission is not a function
So basically you are trying to use message.author.hasPermission('permission'). The property author of the message object is a User, which is a Discord user. You need to reference the GuildMember, using message.member.hasPermission('permission').
Also, it looks like you are trying to compare the same person (message.author and message.member are the same person, only one is a User and the other is a GuildMember). You need to compare message.member.hasPermission() with otherMember.hasPermission().
if you don't want an admin to kick other admins then you should check like
if(user.member.hasPermission("KICK_MEMBERS")) { return message.channel.send("msg here"); }
assuming you have "user" defined if not then you can do
let user = message.mentions.users.first() || message.guild.members.cache.get(args[0]);
if you have that defined then you can check for the user using
if(!user) { return message.channel.send("member not found") }
and if you want to add a reason then you can do
let user = message.mentions.users.first() || message.guild.members.cache.get(args[0]);
let reason = args.slice(1).join(' ')
if(message.member.hasPermission("KICK_MEMBERS") { return message.channel.send("You do not have permission to kick members") }
if(!user) { return message.channel.send("member not found") }
if(!reason) { return reason = "No reason supplied" }
if(user.member.hasPermission("KICK_MEMBERS")) { return message.channel.send("You cannot kick that member") }
if(user.id = message.author.id) { return message.channel.send("you should not kick yourself")
message.mentions.users(user).kick()
message.mentions.users(user).send("You were kicked from " + message.guild + ", Reason: " + reason)
message.channel.send(`${message.author.username} Kicked ${user}#{user.discriminator}`)
this is assuming that you have "message" defined and "args" defined but this is a quick example of how you could stop admins from kicking each other if you use "Discord.JS V12" it will work perfectly

How can I add specific role to user who react to the message

I'm trying do create a bot that can add specific role to the user who react to the message with the emoji listed.
With the code below, I can check who reacted to the message and i can also check what emoji they react with, but when I am trying to add role to them, error pops up say user.addRole is not a function is there any way to solve this problem? Thanks a lot!
Code that create an embed message for user to react
let args = message.content.substring(PREFIX.length).split(" ");
if(message.content.toLowerCase() === '?roles' && message.author.id === 'adminId' && message.channel.id === 'channel id'){
const role = new Discord.MessageEmbed()
.setTitle("ROLES")
.setColor('#6a0dad')
.setDescription('🥕 - ROLE1\n⚔️ - ROLE2\n🧊 - ROLE3')
message.channel.send(role).then(re => {re.react('🥕'),re.react('⚔️'),re.react('🧊')});
message.awaitReactions().then(collected=>{
const reaction = collected.first();
})
}
Code that get the react user and trying to add role
const bot = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });
bot.on('messageReactionAdd', async (reaction, user) => {
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
console.log('Something went wrong when fetching the message: ', error);
return;
}
}
if(reaction.message.id === 'id of that embed message sent'){
if(reaction.emoji.name === "🥕"){
//console.log('ROLE1');
user.addRole('id of role 1');
}
if(reaction.emoji.name === '⚔️')
//console.log('ROLE2');
user.addRole('id of role 2');
if(reaction.emoji.name === '🧊')
//console.log('ROLE3');
user.addRole('id of role 3');
}
});
Looks like you're trying to add a role to a User. When you should be adding the role to a GuildMember. As you can see here: messageReactionAdd returns a User. However Users don't have a .roles only GuildMembers do. However you have two ways you can get the GuildMember easily:
This way you have to make sure the message is from a TextChannel not a DMchannel.
if(reaction.message.type === "text") let member = reaction.message.member;
OR
This way allows the user to react to ANY message the bot has cached.
let member = bot.guilds.get('<id of the server>').members.get(user.id);
Then you do what #Syntle said: member.roles.resolve('<id of role>');
The choice of how to get the member is up to you.
user.addRole() needs to be replaced with member.roles.add.

How to add role to a user based on DM message in DIscord bot

I want to write a discord bot. This bot assign a role to a user when he DM to the bot. The code looks like below. But message.member is null.
bot.on('message', async msg => {
if (msg.channel.type != "dm") {
return;
}
let message = msg.content;
if (message.substring(0, 1) == '!') {
var args = message.substring(1).split(' ');
var cmd = args[0];
switch (cmd) {
case 'role':
const guildMember = message.member; (message.member is null)
guildMember.addRole('<#&439191493169643521>');
}
}
Your first issue is that you're using the wrong message. You declared message as a variable to be equaled to msg.content, so i believe you mistaken it to be msg.
Second, the addRole method takes in an ID or a snowflake. So you can simply just paste the ID of the role in quotation marks inside the method.
Even if you were to make those changes you would still get an error. Why? Because your bot is reading DM channels, not Guild channels. So doing something like this would not work.
const guildMember = msg.member;
guildMember.addRole('<#&439191493169643521>');
I've made some adjustments to your switch statement to make it work.
switch (cmd) {
case 'role':
const guild = client.guilds.get('GUILD_ID');
// grabs the id of the user who messaged the bot
var dmUser = msg.author.id;
// this looks for the users id in the guild
var isMember = guild.members.get(dmUser)
// if true
if (isMember) {
// then add the role
isMember.addRole('ROLE_ID');
} else {
// if not true. send the user this message
msg.reply('You are not part of ___ guild')
}
}

Resources