Getting "Missing Access" error in console - javascript

I'm working on an add role command in discord.js v13 and this is the error I am getting:
Error
const { MessageEmbed } = require("discord.js");
const Discord = require("discord.js")
const config = require("../../botconfig/config.json");
const ee = require("../../botconfig/embed.json");
const settings = require("../../botconfig/settings.json");
module.exports = {
name: "addrole",
category: "Utility",
permissions: ["MANAGE_ROLES"],
aliases: ["stl"],
cooldown: 5,
usage: "addrole <user> <role>",
description: "Add a role to a member",
run: async (client, message, args, plusArgs, cmdUser, text, prefix) => {
/**
* #param {Message} message
*/
if (!message.member.permissions.has("MANAGE_ROLES")) return message.channel.send("<a:mark_rejected:975425274487398480> **You are not allowed to use this command. You need `Manage Roles` permission to use the command.**")
const target = message.mentions.members.first();
if (!target) return message.channel.send(`<a:mark_rejected:975425274487398480> No member specified`);
const role = message.mentions.roles.first();
if (!role) return message.channel.send(`<a:mark_rejected:975425274487398480> No role specified`);
await target.roles.add(role)
message.channel.send(`<a:mark_accept:975425276521644102> ${target.user.username} has obtined a role`).catch(err => {
message.channel.send(`<a:mark_rejected:975425274487398480> I do not have access to this role`)
})
}
}

What your error means is that your bot doesn't have permissions to give a role to a user. It might be trying to add a role which has a higher position than the bot's own role. One way to stop the error is to give the bot the highest position. The bot will also require the MANAGE_ROLES permission in the Discord Developers page to successfully add roles in the first place. If you want to learn more about role permissions, I suggest you go here => Roles and Permissions. Also, when you are using .catch() at the end, all it is checking for is if the message.channel.send() at the end worked and if not, then send a message to channel telling that the bot was not able to add the role. Instead you need to use .then() after adding the role and then use .catch() to catch the error. Then, your code might look like this:
target.roles.add(role).then(member => {
message.channel.send(`<a:mark_accept:975425276521644102> ${target.user.username} has obtined a role`)
}).catch(err => {
message.channel.send(`<a:mark_rejected:975425274487398480> I do not have access to this role`)
})

Related

How do I get the user of a mentioned user in an option? discord.js v13

I have a bot that's trying to kick a mentioned user in the slash command but when I mention a user in the "user" option it says User not found and gives an error of x is not a valid function (x is whatever I'm trying). I'm trying to find a valid function to actually define the user mentioned but can't seem to find one. Any help is appreciated since I am new to javascript and discord.js
const { SlashCommandBuilder, OptionType } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('tkick')
.setDescription('Kicks the specified user by tag (Moderation)')
.addMentionableOption((option) =>
option
.setName('user')
.setDescription('The user to be kicked')
.setRequired(true),
),
async execute(interaction, client) {
if (!interaction.member.permissions.has(['KICK_MEMBERS']))
return interaction.reply(
'You do not have permission to use this command.',
);
// Get the user from the interaction options
const user = interaction.user;
if (!user) return interaction.reply('User not found.');
// Kick the user
await interaction.option.('user').kick(); // This is where I am having the issue
// Reply with the text
await interaction.reply({
content: 'User has been kicked.',
});
},
};
I tried looking at different questions I looked up but it's either in an older version where it isn't there or got removed. Discord.js v13 got released in December 2022 but I can only find posts before that.
interaction.option.('user').kick() is not a valid syntax and interaction.user is not a GuildMember, but a User object. To be able to kick someone, you need a GuildMember object which can be obtained by using the interaction.options.getMentionable method if you use addMentionableOption.
However, it accepts roles and users. If you don't want your bot to accept mentions of roles, which would make your life a bit more difficult, it's better to use the addUserOption instead of addMentionableOption. With addUserOption, you can get the GuildMember object by using the interaction.options.getMember method:
module.exports = {
data: new SlashCommandBuilder()
.setName('tkick')
.setDescription('Kicks the specified user by tag (Moderation)')
. addUserOption((option) =>
option
.setName('user')
.setDescription('The user to be kicked')
.setRequired(true),
),
async execute(interaction) {
if (!interaction.member.permissions.has(['KICK_MEMBERS']))
return interaction.reply(
'You do not have permission to use this command.',
);
try {
await interaction.options.getMember('user').kick();
interaction.reply('User has been kicked.');
} catch (err) {
console.error(error);
interaction.reply('⚠️ There was an error kicking the member');
}
},
};

.addArgument is not a function Discord bot

Here is my Discord command module code, for some reason this is spitting out that .addArgument is not a function.
const Discord = require('discord.js');
const { SlashCommandBuilder } = require('#discordjs/builders');
data = new SlashCommandBuilder()
.setName('purge')
.setDescription('Purges a number of messages from the channel.')
.addArgument('number', 'The number of messages to purge.')
.addArgument('channel', 'The channel to purge messages from.')
.setExecute(async (interaction, args) => {
const channel = interaction.guild.channels.cache.find(c => c.name === args.channel);
if (!channel) return interaction.reply('Channel not found.');
const messages = await channel.messages.fetch({ limit: args.number });
await channel.bulkDelete(messages);
interaction.reply(`Purged ${messages.size} messages.`);
}
);
It just gives me this:
TypeError: (intermediate value).setName(...).setDescription(...).addArgument is not a function
The reason you are getting this error is because there is nothing called .addArgument() in the SlashCommandBuilder. If you want to add arguments like numbers or channels, you need to use .addNumberOption() or .addChannelOption(). The way you will need to use to add a channel and number option is like this:
.addNumberOption(option => {
return option
.setName('number') // Set the name of the argument here
.setDescription('The number of messages to purge.') // Set the description of the argument here
.setRequired() // This is optional. If you want the option to be filled, you can just pass in true inside the .setRequired() otherwise you can just remove it
})
.addChannelOption(option => {
return option
.setName('channel')
.setDescription('The channel to purge messages from.')
.setRequired()
})
You can learn more about slash commands and options here => Options | discord.js

Discord.js mod bot ban command not working

My discord bot's ban command isn't working and is currently giving me this error. My rols id is 853527575317708820
I don't know what I am doing wrong so please help me out
Here is the command :
Server is ready.
TigerShark Community#3557 Has logged in
(node:204) UnhandledPromiseRejectiontarning: DiscordAPTError: T
AEE RS
user_id: Value "<#!856413967595012127>" is not snowflake.
at RequestHandler.execute (/home/Tunner/TSC/node_modules/di
scoxd. js/src/rest/RequestHandler. js:154:13)
at processTicksAndRejections (internal/process/task
§5:97:5) :!
at async RequestHandler.push (/home/zunner/TSC/node
/discord. js/s1c/rest/RequestHandler. js:39:14)
Here is my code :
module.exports = {
name: 'ban',
description: "Used to ban members from a server",
async execute(client, message, args, Discord) {
if (!(message.member.roles.cache.some(r => r.id === "853527575317708820"))) return
let reason;
const user = await client.users.fetch(args[0])
if (!args[1])
{
reason = "Not specified"
} else {
reason = args[1]
}
const embed = new Discord.MessageEmbed()
.setTitle(`${user.username} was banned!`)
.setDescription(`${user.username} was banned by ${message.author.username} for: ${reason}`)
.setColor("#f0db4f")
.setFooter("Ban Command")
.setTimestamp()
message.channel.send(embed)
message.guild.members.ban(user)
}
}
Your command has few issues in it.
The first being that it does not allow banning users with command if the user is mentioned, it only allows banning by user ID. To fix that simply do:
const user = message.mentions.members.first() || await client.users.fetch(args[0])
You should also add check if the user is found, so right after you declare value for user
const user = message.mentions.members.first() || await client.users.fetch(args[0])
if(!user) return message.reply(`No user found`);
Now if you allow banning both mentions and user IDs there might be a different user value. So I recommend editing your embed aswell to something like:
const embed = new Discord.MessageEmbed()
.setTitle(`${user.user.username} was banned!`)
.setDescription(`${user.user.username} was banned by ${message.author.username} for: ${reason}`)
.setColor("#f0db4f")
.setFooter("Ban Command")
.setTimestamp()
This should fix majority of your issues, I recommend that if something is undefined in future or you come across any bugs in your code. Do some debugging by sending messages to console console.log(variable) or console.log("This works?")
if you are using discord.js v12 you can do what the other answer said and get the user by mention message.mentions.members.first() but if you are using v13 that wont work anymore
the reason its giving that error is because you need to fetch the user by their id alone, so you can do this client.users.fetch(args[0].replace('<#!', '').replace('>', '')) to remove the <#! and > (mention prefix) from it.

invite Created event

so I'm making a Discord Bot, with auto logging capabilities, until now I managed due to do most of the code, these include the command for setting a mod-log channel and the event code, here's the code for the command:
let db = require(`quick.db`)
module.exports = {
name: "modlog",
aliases: ["modlogs", "log", "logs"],
description: "Change the modlogs channel of the current server",
permission: "MANAGE_CHANNELS",
usage: "modlog #[channel_name]",
run: async (client, message, args) => {
if(!message.member.hasPermission(`MANAGE_CHANNELS`)) {
return message.channel.send(`:x: You do not have permission to use this command!`)
} else {
let channel = message.mentions.channels.first();
if(!channel) return message.channel.send(`:x: Please specify a channel to make it as the modlogs!`)
await db.set(`modlog_${message.guild.id}`, channel)
message.channel.send(`Set **${channel}** as the server's modlog channel!`)
}
}
}
And the inviteCreate event:
client.on("inviteCreate", async invite => {
const log = client.channels.cache.get(`${`modlog_${message.guild.id}`}`)
let inviteCreated = new Discord.MessageEmbed()
log.send(`An invite has been created on this server!`)
})
The issue is that since the inviteCreate event only accepts one parameter (I think that's what they are called) which is invite, there is no message parameter, so message becomes undefined, does anyone have a solution?
Thanks!
You don't need message in this case. See the documentation of invite.
Your message.member can be replaced with invite.inviter
Your message.channel can be replaced with invite.channel
Your message.guild can be replaced with invite.guild
Invites also have a guild property, that's the guild the invite is for, so you can use that instead of the message.guild:
client.on('inviteCreate', async (invite) => {
const log = client.channels.cache.get(`${`modlog_${invite.guild.id}`}`);
let inviteCreated = new Discord.MessageEmbed();
log.send(`An invite has been created on this server!`);
});

Discord.js add custom role to a mentioned user

I have a problem adding a custom role to a user. The command should look like this: ${prefix}addrole #user <role name>. The user should receive a custom role and the bot should send a confirmation message. This is my code:
client.on('message', (message) => {
if (message.content.startsWith(`${prefix}addrole`)) {
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermissions('MANAGE_MEMBERS'))
return message.reply("You don't have acces!");
const rMember =
message.guild.member(message.mentions.user.first()) ||
message.guild.members.get(args[0]);
if (!rMember) return message.reply("I couldn't find that user!");
const role = args.join(' ').slice(22);
if (!role) return message.reply('Please type a role!');
const gRole = message.guild.roles.find(`name`, role);
if (!gRole) return message.reply("I couldn't find that role!");
if (nMember.roles.has(gRole.id));
await nMember.addRole(gRole.id);
try {
nMember.send(`You received ${gRole.name}`);
} catch (e) {
message.channel.send(
`The user <#${rMember.id}>, received the role ${gRole.name}. We tried to dm him but he disabled them.`
);
}
};
module.exports.help = {
name: 'addrole',
};
}
});
The first problem I found comes from these two lines:
if(nMember.roles.has(gRole.id));
await(nMember.addRole(gRole.id));
First of all:
await is not a function, and thus you don't need parentheses. If you do put parentheses, you will get an error. Instead, just use:
await nMember.addRole(gRole.id)
Second of all:
GuildMember.roles.has is deprecated. discord.js v12+ uses Managers, so you will have to add the cache property. Write:
if (nMember.roles.cache.has(gRole.id))
This also applies to a line further up in the code:
let gRole=message.guild.roles.find(`name`, role);
Replace that with
let gRole = message.guild.roles.cache.find(r => r.name = role)
Third of all:
This issue is also seen in the second line of code I quoted:
await nMember.addRole(gRole.id)
addRole() is also deprecated, instead use:
await nMember.roles.cache.add(gRole.id)
Fourth of all, and I barely caught this:
MANAGE_MEMBERS is no longer a permission flag. Instead, use MANAGE_ROLES.
Overall the code could be cleaned up a bit, but I think that's all the errors I found.

Categories

Resources