Discord.js bot assigning roles to users throws permission denied error - discord.js

I'm trying to make a discord bot (with js) that can assign roles to users.
Discord version: 14.3.0
Nodejs version: 16.17.0
Im using this function to assign role.
const client = new Discord.Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.DirectMessages
]
});
....
var role = message.guild.roles.cache.find(role => role.name == "Role_name")
guildMember.roles.add(role) // this line is causing the error
This is the exact error im getting
/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.cjs:293
throw new DiscordAPIError.DiscordAPIError(data, "code" in data ? data.code :
data.error, status, method, url, requestData);
^
DiscordAPIError[50013]: Missing Permissions
at SequentialHandler.runRequest ( /media/pranav/Storage/ie/programming/nodejs/project-l isabey/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.cjs:293:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest ( /media/pranav/Storage/ie/programming/nodejs/project-l isabey/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.cjs:99:14)
at async REST.request (/media/pranav/Storage/ie/programming/nodejs/project-l isabey/node_modules/#discordjs/rest/dist/lib/REST.cjs:52:22)
at async GuildMemberRoleManager.add ( /media/pranav/Storage/ie/programming/nodejs/project-l isabey/node_modules/discord.js/src/managers/GuildMemberRoleManager.js:129:7) {
rawError: { message: 'Missing Permissions', code: 50013 },
code: 50013,
status: 403,
method: 'PUT',
url: ' https://discord.com/api/v10/guilds/1011546412011507823/members/1021733308457041970/roles/1 021714244846223360',
requestBody: { files: undefined, json: undefined }
}
I tried giving the bot Mod permissions in the server
Invited bot to server with "discord.com/api/oauth2/authorize?client_id=xxxxxxxxxx&permissions=8&scope=bot%20applications.commands"
In developer portal all 3 "privileged gateway intents" are checked.
Still i'm getting the same error. How can I fix this ?
Thanks!

Make sure that the role you're trying to assign is lower to your highest bot role.
In server settings, literally drag the bots role above the roles it will be assigning.

Related

Amplify Admin Queries API addUserToGroup giving 403 with "User does not have permissions to perform administrative tasks" message

I am working on React + Amplify app and have implemented custom authentication. For Authorization, I have created different user groups in Cognito.
Once the user confirms the sign up process, I want to add him/her to a specific Cognito user pool group named 'applicant'. I have created this group and running the following code on Sign up:
const confirmRegister = async (e) => {
try {
e.preventDefault();
await Auth.confirmSignUp(user.email, user.authenticationCode);
console.log("User Signed up Successfully.");
addToGroup(user.email, "applicant");
navigate("/dashboard");
} catch (error) {
console.log("error confirming sign up", error);
}
};
const addToGroup = async (userEmail, groupName) => {
let apiName = "AdminQueries";
let path = "/addUserToGroup";
let myInit = {
body: {
username: userEmail,
groupname: groupName,
},
headers: {
"Content-Type": "application/json",
Authorization: `${(await Auth.currentSession())
.getAccessToken()
.getJwtToken()}`,
},
};
await API.post(apiName, path, myInit);
console.log(`${userEmail} added to the group ${groupName}`);
};
The user is signing up successfully with this but not adding to the Cognito group, giving me 403 "Request failed with status code 403". The network tab shows this:
message: "User does not have permissions to perform administrative tasks"
I have used the CLI to restrict API access to this particular group as well but not working. Please let me know how to resolve this. Thanks in advance.

Bot sends a embed when joins a server

Im trying to make my bot send a embed in the server that it joins (E.G a thank you for inviting and what the bot can do).This is the error that I am getting.
const channel = message.guild.channels.cache.find(channel => channel.type === 'text' && client.user.me.permissions.has("send_messages"))
^
TypeError: Cannot read properties of undefined (reading 'channels')
this is the code that i am using in the index.js file
client.on('guildCreate', message => {
const channel = message.guild.channels.cache.find(channel => channel.type === 'text' && client.user.me.permissions.has("send_messages"))
const embed = new MessageEmbed()
.setColor('GREEN')
.setTitle('Thank You')
.setDescription("Thank you for inviting Rynwin to your server. To get the command list please do /help.\n \n The default Bot prefix is ```<```")
.addFields([
{
name: "Our Support Server",
value: "If you require assistance or would like to get daily bot updates please join our support discord [here] ()"
},
{
name: "Commands",
value: "Try some of these commands; \n\n**/prefix <prefix>** - Sets the server prefix\n\n**/help** - Get the command list or information on a command \n\n**/botinfo** - Shows info on the bot"
},
channel.send({ embeds: [embed] })
])
There are a few things wrong on the first 2 lines. Firstly, guildCreate gives a Guild instance, not a message. Secondly, you aren't checking the correct channel type or permission. Here is the fixed code:
client.on('guildCreate', guild => {
const channel = guild.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && guild.me.permissions.has("SEND_MESSAGES"))
// GUILD_TEXT channel type, guild.me for client guild member, and uppercase permission
// rest of code...
}

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;
}

Discord.js client immediately crashing as soon as a member joins

I have a Discord bot that is supposed to check the user info of a server member as soon as they join. Yet, what happens as soon as a member joins is that the client immediately crashes.
Thank you in advance for reading this. If I am doing anything else wrong in this code, let me know!
This is the code where the event is:
Error:
/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Missing Permissions
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
at async GuildMemberManager.kick (/home/container/node_modules/discord.js/src/managers/GuildMemberManager.js:344:5) { method: 'delete', path: '/guilds/900147696902479942/members/817852730197671996', code: 50013, httpStatus: 403, requestData: { json: undefined, files: [] } }
Code:
client.on("guildMemberAdd", member => {
if (Date.now() - member.user.createdAt < 1000 * 60 * 60 * 24 * 10) {
const role = interaction.options.getRole('test');
member.roles.add(role)
}
else
member.kick()
});
Your bot doesnt have permission to manipulate that members roles, consider:
try{
await member.roles.add(role);
}
catch(e){
console.log(`Error adding role: ${e}`);
}

Discord.js. Reaction Roles

I'm trying to script a bot that gives people a role when they click on an emoji.
My problem is that people don't get the role when they click on the emoji. When I enter the first Command t!role the Message with the emoji is sent correctly. However, the people reacting will not receive the role. I tried everything that was suggested in the Comments. Unfortunatley nothing seems to work.
const bot = new Discord.Client( {
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
],
partials: ["MESSAGE", "CHANNEL", "REACTION"]
});
else if(parts[0].toLowerCase() == "t!role") {
let sendMessage = await message.channel.send('React with 👮to get the role')
sendMessage.react('👮')
bot.on('messageReactionAdd', async (reaction, user, channel) => {
if(reaction.message.partial) await reaction.message.fetch();
if(reaction.partial) await reaction.fetch();
if(user.bot) return;
if(!reaction.message.guild) return;
if(reaction.message.channel.id === '8786607442820137464') {
if(reaction.emoji.id === '8789972642138767364') {
reaction.message.guild.members.cache.get(user.id).roles.add('8779841244749004804')
}
}
})
Discord had added a few new features in their developer portal a few months ago and most of the documentation and tutorials skip over that but it is necessary for them to be active in order to have a functional reaction roles feature.
The process to turn these on is to go to the application page of your bot, go to the bot page under the application and activate Presence Intent and Server Members Intent. Hopefully after this your reaction roles should start working.
Enable partials in your client initialization. Discord.js requires you now to add partials and intent flags you actually gonna use. The messageReactionAdd event requires some partials as well: REACTION, MESSAGE, CHANNEL.
For example, this is how you should use partials.
const bot = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
],
partials: ["MESSAGE", "CHANNEL", "REACTION"]
});
I have used the same exact code in your post, only changed a few id's on my side, and it's working as intended. As my comment before:
Bots can only give roles below their own, even if they have Administrator permissions. Make sure the role is below the bot's role. Use .catch((error) => console.log(error.message)); to log any errors if giving out the roles has failed for some reason.
bot.on('messageReactionAdd', async (reaction, user, channel) => {
if(reaction.message.partial) await reaction.message.fetch();
if(reaction.partial) await reaction.fetch();
if(user.bot) return;
if(!reaction.message.guild) return;
if(reaction.message.channel.id === '8786607442820137464') {
if(reaction.emoji.id === '8789972642138767364') {
reaction.message.guild.members.cache.get(user.id).roles.add('8779841244749004804')
}
}
});

Resources