Discord.js V13 Adding role when using a slash command - discord.js

I am trying to code a bot that when you use a certain slash command, it gives you a role. I have looked for a solution but haven't been able to find one. Nothing is seeming to work for me, i keep getting errors about the code, like "message not found, did you mean Message"
This is my first time trying to code a bot so if its a dumb issue, please bear with me.
Here is my code:
import DiscordJS, { Intents, Message, Role } from 'discord.js'
import dotenv from 'dotenv'
dotenv.config()
const client = new DiscordJS.Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
],
})
// Slash Commands
//ping pong command
client.on('ready', () => {
console.log('BOT ONLINE')
//bot test server
const guildId = '868857440089804870'
const guild = client.guilds.cache.get(guildId)
const role = client.guilds.cache.find(r => r.name == "Test Role to
give")
let commands
if (guild) {
commands = guild.commands
} else {
commands = client.application?.commands
}
commands?.create({
name: 'ping',
description: 'says pong'
})
commands?.create({
name: "serverip",
description: 'Gives user the server IP'
})
commands?.create({
name: "giverole",
description: 'Gives user the role'
})
})
client.on('interactionCreate', async (interaction) => {
if(!interaction.isCommand()) {
return
}
const { commandName, options } = interaction
//This is the role id that i want to give
const role = '884231659552116776'
//these are the users that i want to give the role to
const sniper = '725867136232456302'
const josh = '311981346161426433'
if (commandName === 'ping') {
interaction.reply({
content: 'pong',
ephemeral: true,
})
} else if (commandName === 'serverip') {
interaction.reply({
content: 'thisisserverip.lol',
ephemeral: true,
})
} else if (commandName === 'giverole') {
interaction.reply({
content: 'Role given',
ephemeral: true,
})
}
})
client.login(process.env.test)

You can just simply retrieve the Interaction#Member and add the role to them using GuildMemberRoleManager#add method!
const role = client.guilds.cache.find(r => r.name == "Test Role to
give");
await interaction.member.roles.add(role); // and you're all set! welcome to stackoverflow 😄

if (commandName === 'giverole') {
const role = client.guilds.cache.find(r => r.name == "Ahmed1Dev")
await user.roles.add(role)
message.channel.send("Done Added Role For You") // Fixed By Ahmed1Dev
}

Related

DiscordJS Roles Won't Add

const { SlashCommandBuilder } = require("#discordjs/builders");
const { Permissions } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("mute")
.setDescription("Mute a user on the server")
.addUserOption((option) =>
option
.setName("user")
.setDescription("The user you want to mute")
.setRequired(true)
),
execute: async (interaction) => {
const user = interaction.options.getUser("user");
if (!interaction.member.permissions.has(Permissions.FLAGS.MANAGE_ROLES)) {
return interaction.editReply({
content: `:x: | Manage Roles Permission is required to perform that action!`,
ephemeral: true,
});
}
user.roles.add(member.guild.roles.cache.get("958443243836702859"));
return interaction.editReply("Muted!")
},
};
TypeError: Cannot read properties of undefined (reading 'add')
It won't let me add a roles to a user please help!
You are calling user.roles.add() in the middle of the hash definition of module_exports.
Read through your code again. It's a syntax error.
The issue stems from this, roles is an element of a member which is the parent of a user. user does not contain the element of roles. The code was trying to add roles to a user rather than a member.
This will help you out.
const { SlashCommandBuilder } = require("#discordjs/builders");
const { Permissions } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("mute")
.setDescription("Mute a user on the server")
.addUserOption((option) =>
option
.setName("user")
.setDescription("The user you want to mute")
.setRequired(true)
),
execute: async (interaction) => {
const user = interaction.options.getUser("user");
if (!interaction.member.permissions.has(Permissions.FLAGS.MANAGE_ROLES)) {
return interaction.editReply({
content: `:x: | Manage Roles Permission is required to perform that action!`,
ephemeral: true,
});
}
//adding the below line
const member2mute = interaction.guild.members.cache.get(user.id)
//changing the below line
member2mute.roles.add("958443243836702859");
return interaction.editReply("Muted!")
},
};

DiscordAPIError: Cannot send an empty message (discord.js v13)

I am coding a bot with the below command and it throws an error, but i don't know where is the error
i tried my best
const Discord = require("discord.js");
const client = new Discord.Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR")) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if(!reason) reason = "No reason given."
if(!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if(!member) return message.channel.send("❌ You didn't mention a member!")
if(member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then (() => {
const embed = new Discord.MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
embed.setFooter(`Requested by ${message.author.username}`)
message.channel.send(embed)
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(error => {
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}
If I have made a mistake, please help me out
Sorry I don't speak English well
Try the below code out, I made notes along the way to explain as well as improved a small bit of code. I assume this is a collection of 2 separate files which is why they are separated. If they aren't 2 separate files, you do not need the top section, just the bottom.
const {
Client,
Intents,
MessageEmbed
} = require("discord.js");
const client = new Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
const {
MessageEmbed,
Permissions
} = require("discord.js");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has(Permissions.FLAGS.ADMINISTRATOR)) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if (!reason) reason = "No reason given."
if (!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if (!member) return message.channel.send("❌ You didn't mention a member!")
if (member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then(() => {
const embed = new MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
.setFooter({
text: `Requested by ${message.author.username}`
})
// author and footer are now structured like this
// .setAuthor({
// name: 'Some name',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// url: 'https://discord.js.org',
// })
// .setFooter({
// text: 'Some footer text here',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// })
message.channel.send({
embeds: [embed]
}) //embeds must be sent as an object and this was the actual line that was causing the error.
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(() => { // if error is not used, it is not required to be stated
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}

I want users not to be able to hand out higher privileges than they have themselves

A moderator who has manage_roles permissions can even give the owner role to anyone. Is there a way that it can give out no higher role than to his own role?
So if he is admin, he can give at most admin, so not everyone can give random roles to anyone.
const { MessageEmbed } = require('discord.js');
const config = require('../../configs/config.json');
module.exports = {
config: {
name: "give-roles",
},
run: async (client, message, args) => {
message.delete();
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send({
embed: {
title: `You dont have permission to use this command`
}
})
if (!args[0] || !args[1]) return message.channel.send({
embed: {
title: "Incorrect usage, It's `<username || user id> <role name || id>"
}
})
try {
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
const roleName = message.guild.roles.cache.find(r => (r.name === args[1].toString()) || (r.id === args[1].toString().replace(/[^\w\s]/gi, '')));
const alreadyHasRole = member._roles.includes(roleName.id);
if (alreadyHasRole) return message.channel.send({
embed: {
title: "User already has the role defined"
}
})
const embed = new MessageEmbed()
.setTitle(`Role Name: ${roleName.name}`)
.setDescription(`${message.author} has successfully given the role ${roleName} to ${member.user}`)
.setColor('f3f3f3')
.setThumbnail(member.user.displayAvatarURL({ dynamic: true }))
.setFooter(new Date().toLocaleString())
return member.roles.add(roleName).then(() => message.channel.send(embed));
} catch (e) {
return message.channel.send({
embed: {
title: "Try to give a role that exists next time"
}
})
}
}
}
You're able to use roles.highest.position:
let taggedMember = ... //(guildMember)
if (message.member.roles.highest.position < taggedMember.roles.highest.position) {
//code...
}
Docs: https://discord.js.org/#/docs/main/stable/class/RoleManager?scrollTo=highest

Discord.js-commando how would I check if a mentioned user has a role, like a muted role for example?

So I have been trying to figure out how to check if the mentioned user has the muted role before attempting to add it, and if they do, say they are already muted, and I can't figure it out. Here is my code for my mute command, any help is appreciated.
const { Command } = require('discord.js-commando');
const { MessageEmbed } = require('discord.js');
module.exports = class MuteCommand extends Command {
constructor(client) {
super(client, {
name: 'mute',
aliases: ['mute-user'],
memberName: 'mute',
group: 'guild',
description:
'Mutes a tagged user (if you have already created a Muted role)',
guildOnly: true,
userPermissions: ['MANAGE_ROLES'],
clientPermissions: ['MANAGE_ROLES'],
args: [
{
key: 'userToMute',
prompt: 'Please mention the member that you want to mute them.',
type: 'member'
},
{
key: 'reason',
prompt: 'Why do you want to mute this user?',
type: 'string',
default: message =>
`${message.author.tag} Requested, no reason was given`
}
]
});
}
run(message, { userToMute, reason }) {
const mutedRole = message.guild.roles.cache.find(
role => role.name === 'Muted'
);
if (!mutedRole)
return message.channel.send(
':x: No "Muted" role found, create one and try again.'
);
const user = userToMute;
if (!user)
return message.channel.send(':x: Please try again with a valid user.');
user.roles
.add(mutedRole)
.then(() => {
const muteEmbed = new MessageEmbed()
.addField('Muted:', user)
.addField('Reason', reason)
.setColor('#420626');
message.channel.send(muteEmbed);
})
.catch(err => {
message.reply(
':x: Something went wrong when trying to mute this user.'
);
return console.error(err);
});
}
};
To see if a mentioned user has a role you can do:
member = message.mentions.first();
if (member._roles.includes('<role ID>') {
//code
}
and obviously, replace <role ID> with the role id of the muted role.
This works because members objects have a _roles array that contains all the IDs of the roles they have.

user.ban is Not a function?

I was trying to make a ban command where you can ban a user with a reason.
Turns out user.ban is not a function in Discord.js V12 even though it should be.
Here is my code.
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'ban',
description: 'Bans a user.',
category: 'Moderation',
usage: '^ban <user> <reason>',
run: async (bot, message, args) => {
if (!message.member.hasPermission('BAN_MEMBERS')) {
return message.channel.send('You do not have permission to do this! ❌');
}
if (!message.guild.me.hasPermission('BAN_MEMBERS')) {
return message.channel.send('I do not have permission to do this! ❌');
}
const user = message.mentions.users.first();
if (!user) {
return message.channel.send('User was not specified. ❌');
}
if (user.id === message.author.id) {
return message.channel.send('You cannot ban yourself! ❌');
}
let reason = message.content
.split(' ')
.slice(2)
.join(' ');
if (!reason) {
reason = 'No reason provided.';
}
let Embed = new MessageEmbed()
.setTitle(`Justice! | Ban Action`)
.setDescription(`Banned \`${user}\` - Tag: \`${user.discriminator}\``)
.setColor('ORANGE')
.setThumbnail(user.avatarURL)
.addField('Banned by', `\`${message.author.username}\``)
.addField(`Reason?`, `\`${reason}\``)
.setTimestamp();
message.channel.send(Embed);
user.ban(reason);
},
};
Is there a way to fix this?
You're getting a User instead of a GuildMember. A User represents a person on discord, while a GuildMember represents a member of a server. You can get a GuildMember instead of a User by using mentions.members instead of mentions.users ex:
const user = message.mentions.members.first()

Resources