Discord.Js - making a bot that creates custom roles - discord

I'm someone who just got into coding recently.
I'm trying to create a Discord bot that can do custom roles that can allow a user of that custom role to edit its hex or name.
There's also the creation of a role creator that also assigns the mentioned user the role.
My problem is that I've encountered an issue with the role creation + assignment and the commands that allow the user to edit their role.
Here are the problems:
(node:6288) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'get' of undefined for the role creator command
When I try to use the commands that allow the user to customize their roles, the commands don't work, or to be more specific, they don't activate.
I do believe that the codes I'm using could be outdated, therefore if that is the case, please give me the exact location and the right code.
Here are some pictures of the codes. I've pasted the codes below, but I'm a bit new to this forum, so please pay attention to the separating pieces like "Role Customization Code:" to distinguish which one's which. For some reason, the module.exports aren't going in there. Please describe and let me know a solution to these problems in a specific way since I am a newbie at this topic.
Role creation command + assignment error.
Role creation command + assignment code part 1.
Role creation command + assignment code part 2.
Role customization code part 1.
Role customization code part 2.
Role customization code part 3.
Role creation + assignment code:
const Discord = module.require("discord.js");
const guild = require("./config.json");
module.exports.run = async (bot, message, args) => {
const query = bot.db;
function embedFail(text) {
let embed = new Discord.RichEmbed().setColor("#ff0000").setDescription(text);
return embed;
}
function embedSuccess(text) {
let embed = new Discord.RichEmbed().setColor("#7CFC00").setDescription(text);
return embed;
}
if (!args[0]) return message.channel.send("Please specify a user to add!");
let toAdd = message.guild.members.get(args[0]) || message.guild.members.get(message.mentions.users.first().id);
let rolejoin = args.slice(1).join(" ");
let myRole = message.guild.roles.cache.get((val) => val.name.toLowerCase() === rolejoin.toLowerCase());
if (!toAdd) return message.channel.send("User not found!");
if (!rolejoin) return message.channel.send("Please specify a role to add!");
let botRole = message.guild.members.get(bot.user.id).highestRole;
let isPosition = botRole.comparePositionTo(myRole);
if (isPosition <= 0) return message.channel.send(embedFail("This role is higher than me, I cannot add this role!"));
let res = await query(`SELECT * FROM user_roles WHERE role_id='${myRole.id}'`);
if (res[0]) {
await query(`DELETE FROM user_roles where role_id='${myRole.id}'`);
toAdd.removeRole(myRole);
message.channel.send(embedSuccess(`Removed role ${myRole.name} from ${toAdd.user.username}`));
} else if (!res[0]) {
await query(`INSERT INTO user_roles (guild_id, user_id, role_id) VALUES ('${message.guild.id}',${toAdd.id},'${myRole.id}')`);
toAdd.addRole(myRole);
message.channel.send(embedSuccess(`Adding role ${myRole.name} to ${toAdd.user.username}`));
}
};
Role Customization Code:
const Discord = module.require("discord.js");
const guild = require("./config.json");
module.exports.run = async (bot, message, args, db) => {
const query = bot.db;
function embedFail(text) {
let embed = new Discord.RichEmbed().setColor("#ff0000").setDescription(text);
return embed;
}
function embedSuccess(text) {
let embed = new Discord.RichEmbed().setColor("#7CFC00").setDescription(text);
return embed;
}
let res = await query(`SELECT * FROM user_roles WHERE guild_id = '${message.guild.id}' AND user_id = '${message.author.id}'`);
if (!args[0]) {
if (!res[0]) return message.channel.send(embedFail("You do not have a role!"));
let myRole = message.guild.roles.cache.find(res[0].role_id);
let assignNames = "";
let embed = new Discord.RichEmbed()
.setAuthor(`Current role assigned to ${message.author.username}`, message.guild.iconURL)
.setColor(myRole.hexColor)
.addField(`Name`, `${myRole.name}`, true)
.addField(`Colour`, `${myRole.hexColor}`, true);
message.channel.send(embed);
} else {
if (!res[0]) return message.channel.send(embedFail("You do not have a role!"));
let myRole = message.guild.roles.cache.find(res[0].role_id);
if (!myRole) {
await query(`DELETE FROM user_roles where guild_id = '${message.guild.id}' AND role_id = '${res[i].role_id}' and user_id = '${res[i].user_id}'`);
return message.channel.send(embedFail("You do not have a role!"));
}
switch (args[0]) {
case "name":
let name = args.slice(1).join(" "),
oldName = myRole.name;
await myRole.setName(name);
await message.channel.send(embedSuccess(`You have changed ${oldName}'s name to ${name}!`));
break;
case "color":
case "color":
let hexCode = args[1],
oldHex = myRole.hexColor;
await myRole.setColor(hexCode);
await message.channel.send(embedSuccess(`You have changed ${myRole.name}'s color from ${oldHex} to #${hexCode}!`));
break;
}
}
};

Related

discord.js#12.5.3 add role command

I'm trying to make a add role and remove role command, I've tried before and given up since I could never get my head around it. I want the command to allow someone to mention a user then mention a role and give/take that role to/from the user. The command doesn't give the role and it seems like content.replace doesnt work either. Here is my code for the give role command:
module.exports = {
name: "addrole",
description: "Give a role to a user",
aliases: ["+role", "giverole", "give-role"],
cooldown: 3,
permissions: "MANAGE_ROLES",
execute(msg, args){
const Discord = require('discord.js');
require("discord-reply")
const { colour } = require('../config.json')
const { version } = require('../config.json')
const { prefix } = require('../config.json')
let user = msg.mentions.users.first() || msg.author
//v e.g $ addrole #user test role = test role
let r1 = msg.content.replace(`${prefix} ${args[2]} ${user} `, ``)//removes everything before role name
//^ content.replace doesn't seem to work
let role = msg.guild.roles.cache.find(r => r.name === r1);
if (!r1) { //checks for anything after the user
msg.channel.send("You need to give a role name")
} else if (!role) {
msg.channel.send("That role doesn't exist")
} else return
user.roles.add(role).catch(console.error);
console.log(`Made it this far`)
}
}
In my modest experience I think your args[2] does not exist because, according to your snippet, you should've already created a messageCreate event and defined command. So try using:
let r1 = msg.content.replace(`${prefix}role ${user}`, ``)
// Or ${prefix}addrole/+role ${user}
let role = msg.guild.roles.cache.find(r => r.name === r1);

How do I compare the ID of the new members with the ones in the database?

I am trying to make a jail command when the members who has this role leave the server and rejoin again the role stay with them ,i want when new members enter the server to compare their ID with the one in the database, if is it true it gives a role again. my code:
client.on("guildMemberAdd",async (member)=>{
let injail = await db.fetch(`ja_${member.guild.id}`)
let role = msg.guild.roles.cache.find(n => n.name === 'Jail');
if(member.guild.id = injail){
member.roles.remove(user.roles.cache)
member.roles.add(role)
}
});
client.on('message', msg => {
if(msg.content.startsWith(prefix + 'jail')){
if(!owners.includes(msg.author.id)) return msg.channel.send("**You Dont Have Perms 📛**")
if(!msg.channel.guild) return;
var logChannel = msg.guild.channels.cache.find(channel => channel.id === logID)//LOG
let jailRole = msg.guild.roles.cache.find(n => n.name === 'Jail');
let user = msg.mentions.members.first() //You can change this to an ID
let args = msg.content.split(" ").slice(1).join(" ")
if(!args[0]) return msg.channel.send('**:x: Please Mention A User**')
if(user.hasPermission("ADMINISTRATOR")) return msg.channel.send("**Im NOT Allowed To Do This 📛**")
let there = db.get(`jl_${msg.guild.id}_${user}`, user.id)
if (there) return msg.channel.send('**This User AlREADY In Jail â›”**')
msg.channel.send(`**ADDED ${user} to the Jail! ✅**`)
db.set(`jl_${msg.guild.id}_${user}`, user.id)
user.roles.remove(user.roles.cache)
user.roles.add(jailRole)
let embed = new Discord.MessageEmbed()
.setTitle('Jail System')
.setAuthor(msg.author.tag,msg.author.avatarURL({dynamic:true}))
.addField("Status",`JOINED THE JAIL 🔴`)
.addField("User",`<#${user.id}> (ID: ${user.id})`)
.addField("By",`<#${msg.author.id}> (ID: ${msg.author.id})`)
.setTimestamp()
logChannel.send(embed)
}
});
Whenever people gets "jail" role, save "yes" to database.
and check condition as you did above.
here I'll give sample code:
// when people gets jail role, add following code:
db.set(`ja_${msg.guild.id}_${user}`, "yes") // or you can simply use boolean operator
// when guildMemberAdd event triggers check condition:
let condition = db.fech(`ja_${member.guild.id}_${member.user.id}`)
if(condition === "yes"){
// write code to add "jail" role to the member
}
else{
// your other code
}
Also don't forget to set "no" in the database whenever you remove jail role from member.

How to know if a user already has a role in an addrole command

I want to send an error message saying that the user already has the role if they do in an addrole command.My current command is:
const { MessageEmbed } = require("discord.js");
module.exports = {
name: "addrole",
description: "adds a role to a member",
execute: async (message , args) => {
if (!message.member.hasPermission("MANAGE_ROLES")) return message.channel.send("Invalid Permissions")
let member = message.mentions.members.first();
let role = message.mentions.roles.first();
if (!member)
return message.reply("Please mention a valid member of this server");
if (!role) return message.reply("please mention a valid role of this server");
const highest = message.member.roles.highest;
if(highest.comparePositionTo(role) <= 0)
return message.channel.send(`You cannot add roles equal/higher to that member's highest role`)
let addroleembed = new MessageEmbed()
.setTitle(`:white_check_mark: ${role.name} has been added to ${member.user.tag}`)
.setFooter(`Action performed by ${message.author.tag}`)
.setColor('77B255')
addroleembed.setTimestamp();
member.roles.add(role);
message.channel.send(addroleembed)
}}
I have tried using
if(!message.member.roles.cache.some(r=>[`${role.name}`].includes(r.name)))
and
if (member.roles.has(role.id) {
But neither of these seem to work, Anyone know the reason behind this? If I can't use either of these methods, Can you suggest me a solution?
You are so close!
All you need is cache when using has()
member.roles.cache.has(<RoleID>);
Learn More Here
You need to combine your two tries.
if(message.member.roles.cache.has("role ID") {
//rest of your code
}

Bot Crashed When you dont mention

I have this command on my bot where you can mute someone using the command g!mute where the 'user' is mentioned using #. However, if you don't mention e.g GeoGeo instead of #GeoGeo, it causes the bot to crash. I know you need to put .catch(console.error); somewhere, but I'm not sure where. Thanks in advance. The Error is
let person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]))
^
TypeError: message.guild.members.get is not a function
Code:
const Discord = require('discord.js');
const ms = require('ms');
module.exports = {
name: 'mute',
description: "this is mute command",
execute(message, args){
if(!message.member.roles.cache.find(r => r.name ==="Staff", "Head Staff", "Owner", "Co-Owner")) return message.channel.send(`YOU DO NOT HAVE PERMISSION TO DO THAT`)
let members = args[0];
if(!members) return message.reply("g!mute <user> <time>")
let person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]))
if(!person) return message.reply("That person is not in the server!");
let mainrole = message.guild.roles.cache.find(role => role.name === "Fans");
let muterole = message.guild.roles.cache.find(role => role.name === "muted");
if(!muterole) return message.reply("That role does not exist");
let time = args[1];
if(!time){
return message.reply("g!mute <user> <time>");
}
person.roles.remove(mainrole.id);
person.roles.add(muterole.id);
const embed = new Discord.MessageEmbed()
.setTitle ("Muted:")
.setDescription (`${person.user.tag} has now been muted for ${ms(ms(time))}`)
.setColor(0x01B8FF)
message.channel.send(embed);
setTimeout(function(){
person.roles.add(mainrole.id)
person.roles.remove(muterole.id)
const embed = new Discord.MessageEmbed()
.setTitle ("Muted:")
.setDescription (`${person.user.tag} has been unmuted`)
.setColor(0x01B8FF)
message.channel.send(embed);
}, ms(time));
}
}
When faced with an error like: TypeError: message.guild.members.get is not a function
The logical thing to do is check the docs to see that message.guild.members really has a function named get. Here's the docs: https://discord.js.org/#docs/main/stable/class/GuildMemberManager
No get. But there is a cache like you use elsewhere in the code. Just by checking over the docs you can tell that your existing code is wrong (it's outdated) and you need to use cache like you do elsewhere in your code:
message.guild.members.cache.get(args[1])

How can I prohibit the use of the command on certain roles

I want to write code that will check if the roles are in the list. If yes, then they can be issued, and if not, then no. I'm new in discord js.
if(!rMember.roles.has((['00000000000000', '00000000000000, '00000000000000', '00000000000000', '00000000000000']))) return message.reply("nope.");
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if(!message.member.hasPermission("MANAGE_MEMBERS")) return message.reply();
let rMember = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0]);
if(!rMember) return message.reply("I can't find player.");
let role = args.join(" ").slice(22);
if(!role) return message.reply("specify rang!");
let gRole = message.guild.roles.find(`name`, role);
if(!gRole) return message.reply("I can't find this rang!.");
if(rMember.roles.has(gRole.id)) return message.reply("I can't do it.");
if(!rMember.roles.has((['00000000000000', '00000000000000, '00000000000000', '00000000000000', '00000000000000']))) return message.reply("nope.");
await(rMember.removeRoles(['00000000000000', '00000000000000, '00000000000000', '00000000000000', '00000000000000']));
await(rMember.addRole(gRole.id));
try{
await rMember.send(`Your rang was changed to ${gRole.name}!`)
}catch(e){
}
}
module.exports.help = {
name: "role"
}
It works without check code, but if I add it, all times, when I will try to change role of user, it gives out "nope".
You could check whether the given role is in the list of allowed roles using Array.includes().
const allowed = ['id', 'anotherID', 'andAnother'];
if (!allowed.includes(gRole.id)) return;
// Returns if the role is *not* in the 'allowed' array.

Resources