Autorole using role defined by user - discord.js

i'm trying to do an Autorole command, then it gives the role the user wants to every new members.
my code :
main.js :
const mentionedRole = require("./cmds/autorole")
bot.on('guildMemberAdd', member => {
member.roles.add(mentionedRole);
})
autorole command :
module.exports.run = async (bot, message, args) => {
const mentionedRole = message.mentions.roles.first();
if (!mentionedRole) return message.channel.send(`I cannot to use the role: ${mentionedRole}`);
message.channel.send(`Autorole successfully added (${mentionedRole}).`);
}
the error it gives :
Supplied roles is not an Role, Snowflake or Array or Collection of Roles or Snowflakes.

To give a role by mention message.mentions.roles.first() you need to #testRole
So I'd recommend doing it like this:
const mentionedRole = message.guild.roles.cache.find(r => r.name === args.slice(1).join(" "));
if (!mentionedRole) return message.channel.send(`I cannot to use the role: ${mentionedRole}`);
message.channel.send(`Autorole successfully added (${mentionedRole}).`);
Now when it should look like this:
ex. ?autorole testRole
not ?autorole #testRole

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);

Discord.js Add / Remove role in 1 command

V12 Code
I want to make this command can be used by anyone having a specific role or manage channel perm but it not works, it only allows people having manage channel perm not the people having specific role.
Problem Code
if (!message.member.roles.cache.has('845453361008476190') || !message.member.hasPermission('MANAGE_CHANNELS')) return message.channel.send("sorry, you do not have permission to use command.")
Complete Code
const prefix = process.env.PREFIX;
module.exports = {
name: 'vip',
category: 'moderation',
aliases: ['v'],
description : 'Used give VIP to a User ',
usage: `${prefix}vip <#user>`,
run : async(client, message, args) => {
if (!message.member.roles.cache.has('845453361008476190') || !message.member.hasPermission('MANAGE_CHANNELS')) return message.channel.send("sorry, you do not have permission to use command.")
const guild = client.guilds.cache.get("842019142118014996");
const role = guild.roles.cache.get("845453369564856361");
const aUser = message.mentions.users.first();
if (!aUser) return message.channel.send("Can't find user!");
const member = await guild.members.fetch(aUser.id);
if (member.roles.cache.get(role.id)) {
return (
member.roles.remove(role),
message.channel.send(`Removed VIP role from ${aUser.tag}`)
);
} else {
await member.roles.add(role),
message.channel.send(`${aUser.tag} Sucessfully got VIP role.`);
}
}
};
This checks if the user doesn't have the required role, or doesn't have the required perms. Change the OR operator (||) to an AND operator (&&) so that if checks if the user doesn't have the required role, and doesn't have the required perms, return early
if (!message.member.roles.cache.has('845453361008476190') && !message.member.hasPermission('MANAGE_CHANNELS'))

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.

Discord.Js - making a bot that creates custom roles

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;
}
}
};

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
}

Resources