DiscordJS Roles Won't Add - discord

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!")
},
};

Related

How do I use #discordjs/voice AudioPlayer methods across modules?

I am adding a music-playing feature to my bot using #discordjs/voice, following the voice guide on discordjs.guide. My slash commands are all stored on different files. I want to use the pause method of the AudioPlayer class outside of play.js.
The relevant parts of play.js are:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { StreamType, createAudioPlayer, createAudioResource, joinVoiceChannel } = require('#discordjs/voice');
module.exports = {
data: new SlashCommandBuilder()
.setName('play')
.setDescription('An example of the play command.'),
async execute(interaction) {
const connection = joinVoiceChannel({ channelId: interaction.member.voice.channel.id, guildId: interaction.guild.id, adapterCreator: interaction.guild.voiceAdapterCreator });
const stream = ytdl('https://www.youtube.com/watch?v=jNQXAC9IVRw', { filter: 'audioonly' });
const resource = createAudioResource(stream, { inputType: StreamType.Arbitrary });
const player = createAudioPlayer();
player.play(resource);
connection.subscribe(player);
await interaction.reply('Playing.');
},
};
and of pause.js are:
const { SlashCommandBuilder } = require('#discordjs/builders');
module.exports = {
data: new SlashCommandBuilder()
.setName('pause')
.setDescription('An example of the pause command.'),
async execute(interaction) {
player.pause();
await interaction.reply('Paused.');
},
};
My console got the following error when I ran the /pause command after I tried to export player from player.js and require it in pause.js:
TypeError: Cannot read properties of undefined (reading 'pause')
What do I need to do to use player.pause() outside of play.js?
You should take a look at this part of the Discord.js guide, in the Access part. The getVoiceConnection method serves this purpose.
It allows you to use the connection created in play.js anywhere in your code. Then, you just need to change the state of the player with connection.state.subscription.player.pause().
I did my pause.js by checking whether the member using the pause command is in a channel and if he is, whether the bot is in it or not:
if (!interaction.member.voice.channelId) {
return interaction.reply('not in a channel.');
}
const connection = getVoiceConnection(interaction.member.voice.channel.guildId);
if (!connection || (connection.joinConfig.channelId != interaction.member.voice.channelId)) {
return interaction.reply('The bot is not in this channel.');
}
connection.state.subscription.player.pause();
await interaction.reply('Paused.');
discord.js

Discord.js V13 Adding role when using a slash command

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
}

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.

A code to add a role to all members of the server

const { MessageEmbed } = require('discord.js')
module.exports = {
name: "addrole",
aliases: ["role", "P!role"],
category: "moderation",
description: "Add role to any user",
run: async (client, message, args) => {
if (!message.member.hasPermission("MANAGE_ROLES")) {
return message.channel.send("sorry you need permission to mute someone");
}
if (!message.guild.me.hasPermission("MANAGE_ROLES")) {
return message.channel.send("I do not have the permissions");
}
const targets = message.mentions.members;
if(!targets.first()) return message.reply(`<:no:677902165859237894>please mention user!`)
let arole = message.mentions.roles.first();
if(!arole) return message.reply(`<:no:677902165859237894>please mention role for add!`)
const embed = new MessageEmbed()
.setColor("RANDOM")
.setDescription(`<a:ok_:731369076315652167>role added ${arole}`)
await message.channel.send(embed)
targets.forEach(target => target.roles.add(arole));
}
}
This adds role to the mentioned users.
Instead is there a way to alter
const targets = message.mentions.members
Such that the targets are all server members? And then by foreach, I can give the role to all the targets.
You could access all guild members from message.guild.members.cache and use .forEach().

Resources