How Do I Add Roles via Discord.js? - javascript

I'm currently creating a bot through Discord.js, and I want someone to be able to state a command in order to gain a role. However, I can't figure this out for the life of me.
In my bot folder, I've created an addrole.js file with the following chunk of code:
const Discord = require("discord.js");
const roles = message.guild.roles.cache.map((role) => role);
const member = message.mentions.members.first();
const role = message.mentions.roles.first();
const colours = require("../colours.json");
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermission(["MANAGE_ROLES", "ADMINISTRATOR"]))
return message.channel.send(
"Sorry, frog lover! :disappointed: :broken_heart: You don't have permission to perform this command!"
);
let rMember =
message.mentions.members.first ||
message.guild.members.cache.find((m) => m.user.tag === args[0]) ||
message.guild.members;
let role =
message.guild.roles.cache.find((r) => r.name == args[1]) ||
message.guild.roles.cache.find((r) => r.id == args[1]) ||
message.mentions.roles.first();
if (!role)
return message.channel.send(
"Which role do I give to this user, frog lover? :point_right: :point_left:"
);
if (!message.guild.me.hasPermission(["MANAGE_ROLES", "ADMINISTRATOR"]))
return message.channel.send(
"Sorry, friend :broken_heart: :shrug: I don't have permission to perform this command!"
);
if (rMember.roles.has(role.id)) {
return message.channel.send(
`$rMember.displayName), already has this role!`
);
} else {
await rMember.roles.add(role.id).catch((e) => console.log(e.message));
message.channel.send(
`The role ${role.name} has been added to ${rMember.displayName}.`
);
}
let embed = new Discord.RichEmbed()
.setColor(colours.redlight)
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL)
.addField("Moderation:", "Addrole")
.addField("Mutee:", rMember.user.username)
.addField("Reason:", reason)
.addField("Date:", message.createdAt.toLocaleString());
letsChannel = message.guild.channels.cache.find(
(c) => c.name === "beans-the-frog"
);
sChannel.send(embedVariable);
};
module.exports.config = {
name: "addrole",
description: "Adds a role to a member of the guild!",
usage: "beans addrole",
accessableby: "Moderators",
aliases: ["ar", "roleadd"],
};
I followed THIS tutorial to get here: https://www.youtube.com/watch?v=GCSbZ2UbriU
I've given my bot the Manage_Roles permission and have attempted to state both "beans addrole (role) (user)" and "beans addrole (user) (role)". I'm expecting him to even specify error messages, or even better yet, add the role. However, he isn't even spitting out error messages, and neither is my console. Everything else works fine, it's just that this particular function won't work. Any input/feedback would help a LOT.

I found a lot of typos inside of your code, and also, it has some problem because you mixed discord.js^11.x with discord.js^12.x. I fixed your code below, but make sure your bot has the ADMINISTRATOR permission as well required by your command.
const Discord = require("discord.js");
// You defined the 3 lines here twice, which requires `message` to be defined.
const colours = require("../colours.json");
module.exports.run = async (bot, message, args) => {
// `Member.hasPermissions()` is deprecated
if (!message.member.permissions.has(["MANAGE_ROLES", "ADMINISTRATOR"]))
return message.channel.send(
"Sorry, frog lover! :disappointed: :broken_heart: You don't have permission to perform this command!"
);
let rMember =
message.mentions.members.first() || // `.first()` is a function.
message.guild.members.cache.find((m) => m.user.tag === args[0]) ||
message.guild.members;
let role =
message.guild.roles.cache.find((r) => r.name == args[1]) ||
message.guild.roles.cache.find((r) => r.id == args[1]) ||
message.mentions.roles.first();
if (!role)
return message.channel.send(
"Which role do I give to this user, frog lover? :point_right: :point_left:"
);
if (!message.guild.me.hasPermission(["MANAGE_ROLES", "ADMINISTRATOR"]))
return message.channel.send(
"Sorry, friend :broken_heart: :shrug: I don't have permission to perform this command!"
);
if (rMember.roles.has(role.id)) {
return message.channel.send(
`$rMember.displayName), already has this role!`
);
} else {
await rMember.roles.add(role.id).catch((e) => console.log(e));
message.channel.send(
`The role ${role.name} has been added to ${rMember.displayName}.`
);
}
let embed = new Discord.MessageEmbed()
.setColor(colours.redlight)
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.addField("Moderation:", "Addrole")
.addField("Mute:", rMember.user.username)
.addField("Reason:", reason)
.addField("Date:", message.createdAt); // `.toLocaleString()` isn't required, discord automatically coonverts it to string.
let sChannel = message.guild.channels.cache.find(
(c) => c.name === "beans-the-frog"
);
sChannel.send(embedVariable);
};
module.exports.config = {
name: "addrole",
description: "Adds a role to a member of the guild!",
usage: "beans addrole",
accessableby: "Moderators",
aliases: ["ar", "roleadd"],
};
To learn more, try visiting the links below:
Discordjs.guide - Guide - Updating from v11 to v12
Discordjs.guide - Guide - Permissions
Discordjs.guide - Guide - Handling Commands

if (rMember.roles.cache.has(role.id)) {
return message.channel.send(
`$rMember.displayName), already has this role!`
);
} else {
await rMember.roles.add(role.id).catch((e) => console.log(e));
message.channel.send(
`The role ${role.name} has been added to ${rMember.displayName}.`
);
}
I used this snippet to get my bot to add roles. Thanks to user above. I had to add cache though. in first line.

Your problem mainly appears from these lines:-
const roles = message.guild.roles.cache.map((role) => role);
const member = message.mentions.members.first();
const role = message.mentions.roles.first();
The problem happens because message is not defined until you define a function. Try moving the code inside the run function.

Related

How do I send a "too many roles to show" message when someone has too many roles to fit in an embed?

This is my whois command:
const Discord = require("discord.js")
const moment = require('moment');
const status = {
online: "Online",
idle: "Idle",
dnd: "Do Not Disturb",
offline: "Offline/Invisible"
};
module.exports = {
config: {
name: "whois",
description: "userinfo",
usage: "m/whois <mention a member/member id>",
aliases: ['ui', 'ifno']
},
run: async (bot, message, args) => {
var permissions = [];
var acknowledgements = 'None';
let whoisPermErr = new Discord.MessageEmbed()
.setTitle("**User Permission Error!**")
.setDescription("**Sorry, you don't have permissions to use this! ❌**")
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.member;
if(member.hasPermission("KICK_MEMBERS")){
permissions.push("Kick Members");
}
if(member.hasPermission("BAN_MEMBERS")){
permissions.push("Ban Members");
}
if(member.hasPermission("ADMINISTRATOR")){
permissions.push("Administrator");
}
if(member.hasPermission("MANAGE_MESSAGES")){
permissions.push("Manage Messages");
}
if(member.hasPermission("MANAGE_CHANNELS")){
permissions.push("Manage Channels");
}
if(member.hasPermission("MENTION_EVERYONE")){
permissions.push("Mention Everyone");
}
if(member.hasPermission("MANAGE_NICKNAMES")){
permissions.push("Manage Nicknames");
}
if(member.hasPermission("MANAGE_ROLES")){
permissions.push("Manage Roles");
}
if(member.hasPermission("MANAGE_WEBHOOKS")){
permissions.push("Manage Webhooks");
}
if(member.hasPermission("MANAGE_EMOJIS")){
permissions.push("Manage Emojis");
}
if(permissions.length == 0){
permissions.push("No Key Permissions Found");
}
if(member.user.id == message.guild.ownerID){
acknowledgements = 'Server Owner';
}
const embed = new Discord.MessageEmbed()
.setDescription(`<#${member.user.id}>`)
.setAuthor(`${member.user.tag}`, member.user.displayAvatarURL())
.setColor('#2F3136')
.setFooter(`ID: ${message.author.id}`)
.setThumbnail(member.user.displayAvatarURL())
.setTimestamp()
.addField('Joined at: ',`${moment(member.joinedAt).format("dddd, MMMM Do YYYY, HH:mm:ss")}`)
.addField('Created On', member.user.createdAt.toLocaleString())
.addField(`Roles [${member.roles.cache.filter(r => r.id !== message.guild.id).map(roles => `\`${roles.name}\``).length}]`,`${member.roles.cache.filter(r => r.id !== message.guild.id).map(roles => `<#&${roles.id }>`).join(" **|** ") || "No Roles"}`)
.addField("\nAcknowledgements: ", `${acknowledgements}`)
.addField("\nPermissions: ", `${permissions.join(` | `)}`);
message.channel.send({embed});
}
}
It does work, but when the member mentioned has too many roles it'll come out with an error because the length is too long and the issue is it has too many roles.
How do I make it so if the mentioned user has too many roles, it comes up with a "Too many roles" message?
I'm using Discord.js v12.
A discord embed can only hold a certain amount of characters (as mentioned in this question's answer). You can try to create the String with all the roles before building the embed, and then test the number of characters. If the number is too high, you can then return a "Too many roles" message.
The author of the answer I mentioned before had this solution :
you may want to do some checks before sending out the embed and then handle oversized embeds by either splitting them into multiple embed messages, or using reaction based pages maybe
Use a try/catch statement
//embed is instance of MessageEmbed with description as the member's roles
try {
await message.channel.send(embed)
} catch(err) {
embed.setDescription('Too many roles');
message.channel.send(embed)
}
Or use .catch
message.channel.send(embed).catch(() => {
embed.setDescription('Too many roles');
message.channel.send(embed)
})

discord.js the bot crash when there's no mention in my unmute command

so i made a mute and unmute command, the mute one works pretty well and i just gotta add some things, the unmute one also works well but when there's no mentioned person (for example q!unmute and not q!unmute [user]) the bot crashes, i tried catch and that stuff but i really don't understand how they work, i'm pretty new to js, this is the string that should send the "you have to mention a user" error:
if (!member) return message.channel.send("You have to mention a valid member");
this is the rest of the code:
module.exports = {
name: 'unmute',
description: 'unmutes a muted member',
execute(message, args, Discord) {
if (message.member.hasPermission('MANAGE_ROLES')) {
const role = message.guild.roles.cache.find(role => role.name === 'Muted');
const member = message.mentions.members.first();
var unmuteChannel = message.guild.channels.cache.find(channel => channel.name.includes("modlogs"));
const unmuteEmbed = new Discord.MessageEmbed()
.addField("Unmuted user", member)
.setFooter(`Unmuted by ${message.author.tag}`)
.setTimestamp();
member.roles.remove(role);
message.channel.send(`${member} Has Been Unmuted`);
unmuteChannel.send(unmuteEmbed);
if (!member) return message.channel.send("You have to mention a valid member");
}
}
}
i hope you can help
In your code you're checking if the user mentioned is null, but it is at the end of the function. I think that putting the if just after you get the value should work:
module.exports = {
name: 'unmute',
description: 'unmutes a muted member',
execute(message, args, Discord) {
if (message.member.hasPermission('MANAGE_ROLES')) {
const role = message.guild.roles.cache.find(role => role.name === 'Muted');
const member = message.mentions.members.first();
if (!member) return message.channel.send("You have to mention a valid member");
var unmuteChannel = message.guild.channels.cache.find(channel => channel.name.includes("modlogs"));
const unmuteEmbed = new Discord.MessageEmbed()
.addField("Unmuted user", member)
.setFooter(`Unmuted by ${message.author.tag}`)
.setTimestamp();
member.roles.remove(role);
message.channel.send(`${member} Has Been Unmuted`);
unmuteChannel.send(unmuteEmbed);
}
}
}
Move
if (!member) return message.channel.send("You have to mention a valid member");
Below where you define member.
const member = message.mentions.members.first();

discord.js Cant use command with user ID

I'm making a command that rickrolls the mentioned user by sending them a dm and when i try to use it by mentioning someone using their ID it dosent work and sends the error message i added saying: The mentioned user is not in the server
const { DiscordAPIError } = require('discord.js');
const Discord = require('discord.js');
const BaseCommand = require('../../utils/structures/BaseCommand');
module.exports = class RickrollCommand extends BaseCommand {
constructor() {
super('rickroll', 'fun', []);
}
async run(client, message, args) {
let mentionedMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!args[0]) return message.channel.send('You need to mention a member to rickroll.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
if (mentionedMember.user.id == client.user.id) return message.channel.send('You really thought i was boutta rickroll myself? AINT NO WAY CHEIF');
const rickrollEmbed = new Discord.MessageEmbed()
.setTitle("You've Been Rickrolled!")
.setThumbnail('https://i1.wp.com/my-thai.org/wp-content/uploads/rick-astley.png?resize=984%2C675&ssl=1')
.setDescription('Rick astley sends his regards')
.setColor('#FFA500');
await mentionedMember.send('https://tenor.com/view/dance-moves-dancing-singer-groovy-gif-17029825')
await mentionedMember.send(rickrollEmbed)
.then(() => {
message.channel.send("Successfully rickrolled the user.");
})
.catch(err => {
message.channel.send('I was unable to rickroll the user.');
});
}
}
The wierd part is it only works with my ID and not any other user's ID.
I think the problem is, that you are using the cache and not the guilds member manager. Therefore, when no other user is cached it will only work with your ID since you are the one sending the message => getting loaded into the cache.
Try this:
async run(client, message, args) {
let mentionedMember = message.mentions.members.first() || await message.guild.members.fetch(args[0]);
if (!args[0]) return message.channel.send('You need to mention a member to rickroll.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
...
}
I don't know for sure, but it might also be a bit more optimized if you still prefer the cache, but just use the member manager as an additional backup, like this:
async run(client, message, args) {
let mentionedMember = message.mentions.members.first()
|| message.guild.members.cache.get(args[0])
|| await message.guild.members.fetch(args[0]);
if (!args[0]) return message.channel.send('You need to mention a member to rickroll.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
...
}

Need Assistance With My unmute command for discord.js

Basically This command is giving one major issue and that the fact that when the user is muted he won't be unmuted because of the command not responding back to the mute command
const Discord = require('discord.js');
const fs = module.require('fs');
module.exports.run = async (client, message, args) => {
if (!message.member.hasPermission('MANAGE_MESSAGES')) return;
let unMute = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!unMute) {
let exampleEmbed = new Discord.MessageEmbed()
.setDescription("__UNMUTE INFO__")
.setColor(client.colors.success)
.setThumbnail(client.user.displayAvatarURL())
.addField(`Unmute Command`, `Unmutes a mentioned user.`)
.addField(`Unmute Command`, `Unmutes User By Id.`)
.addField("Example", `${client.config.prefix}Unmutes #user`)
.addField("Example", `${client.config.prefix}Unmutes #id`)
message.channel.send(exampleEmbed);
return;
}
let role = message.guild.roles.cache.find(r => r.name === 'Muted');
message.channel.send(`Please Check roles to be sure user was unmuted`);
if (!role || !unMute.roles.cache.has(role.id)) return message.channel.send(`That user is not muted.`);
if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send(`----`);
let guild = message.guild.id;
let member = client.mutes[unMute.id];
if (member) {
if (member === message.guild.id) {
delete client.mutes[unMute.id];
fs.writeFile("./mutes.json", JSON.stringify(client.mutes), err => {
if (err) throw err;
})
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
}
return;
}
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
message.delete();
}
module.exports.config = {
name: 'unmute',
description: 'Unmute a user.',
access: 'Manage Messages Permission',
usage: 'unmute #vision'
}
I'm Also getting an error message when manually unmuting the user
(node:6604) UnhandledPromiseRejectionWarning: ReferenceError: User is not defined
Any Form of help would be greatly appreciated and thank you for your time.
On the line if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send('----'), you reference the variable User, but you haven't definied it anywhere, and even if it was defined, you need a role not a member or user. I'm pretty sure it should instead be Role.id. Also, not 100% sure on this, but I tnink it should just be Role not Role.id.

How do I fix this to add a role mentioned in the command to the user?

I am coding a custom discord bot for my server and I ran into this issue. I want to add a role to a user that is not predefined. IE: I want to be able to &addrole #user anyrole and add that role to a user. Here is the code:
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
//!addrole #andrew anyrole
if(!message.member.hasPermission("MANAGE_MEMBERS")) return
message.reply("Sorry pal, you can't do that.");
let rMember = message.guild.member(message.mentions.users.first()) ||
message.guild.members.get(args[0]);
if(!rMember) return message.reply("Couldn't find that user, yo.");
let role = args.join(" ").slice(22);
if(!role) return message.reply("Specify a role!");
let gRole = message.guild.roles.find('name', any);
if(!gRole) return message.reply("Couldn't find that role.");
if(rMember.roles.has(gRole.id)) return message.reply("They already have
that role.");
await(rMember.addRole(gRole.id));
try{
await rMember.send(`Congrats, you have been given the role
${gRole.name}`)
}catch(e){
message.channel.send(`Congrats to <#${rMember.id}>, they have been given
the role ${gRole.name}. We tried to DM them, but their DMs are locked.`)
}
}
module.exports.help = {
name: "addrole"
}

Categories

Resources