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().
Related
My issue here is when I execute the command the owner is only undefined instead of the actual owner of the server. How can I fix this issue?
module.exports.run = async (client, message, args) => {
const { MessageEmbed } = require('discord.js');
message.delete();
const guild = message.guild;
const Emojis = guild.emojis.cache.size || "No Emoji!";
const Roles = guild.roles.cache.size || "No Roles!";
const Members = guild.memberCount;
const Humans = guild.members.cache.filter(member => !member.user.bot).size;
const Bots = guild.members.cache.filter(member => member.user.bot).size;
const owner = guild.owner.user.tag
const embed = new MessageEmbed()
.setTitle(guild.name + " Information!")
.setColor("2F3136")
.setThumbnail(guild.iconURL())
.addField(`Name`, `${guild.name}`, true)
.addField(`Owner`, `${owner}`, true)
.addField(`ID`, `${guild.id}`, true)
.addField(`Roles Count`, `${Roles}`, true)
.addField(`Emojis Count`, `${Emojis}`, true)
.addField(`Members Count`, `${Members}`, true)
.addField(`Humans Count`, `${Humans}`, true)
.addField(`Bots Count`, `${Bots}`, true)
.addField(`Server Created At`, guild.createdAt.toDateString())
.setFooter(`Requested by ${message.author.username}`)
.setTimestamp();
message.channel.send({ embeds: [embed] });
}
module.exports.config = {
name: "serverinfo",
aliases: [""]
}
I'm pretty sure that there isn't an owner property in a Guild. To get the owner you have two methods:
Method 1 is using the .fetchOwner() method of a Guild
const owner = await message.guild.fetchOwner().user.tag
Method 2 is getting the owner id and then fetching the user from guild.members:
const owner = message.guild.members.cache.get(message.guild.ownerId)
You can choose which method is better for you
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!")
},
};
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
}
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
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()