If a player have a role (discord.js) - javascript

So i made a discord bot, and i want to make a command that works only if the person who used the command have a role called "colorm"
this is this code
client.on('message', msg => {
if (msg.content === '!setupcolors'){
if(msg.guild.roles.find(role => role.name === "colorm")){
console.log("cmd: !setupcolors >> Command used.");
msg.reply(String('Hi! this command is under constuction'));
}
else{
msg.reply(String('Hi! you need to have a rank called "colorm" to acces this command.'));
console.log("Error[cmd: !setupcolors] >> No perms.");
}
}
});
thanks! :D

You can check whether a member has a specific role as follows:
msg.member.roles.find(r => r.name === "colorm")
Alternatively, you can use the ID of the role to check:
// First you need to retrieve the role:
const role = guild.roles.cache.find(r => r.name === "colorm")
// You can now check if the user has the role with:
member.roles.cache.has(role.id)
// (Optional)
// If 'role' isn't undefined and the user has the appropriate role you can continue
if (role && member.roles.cache.has(role.id)) {
// Do your stuff here, if the user has the role
}

Try using this - if(!msg.member.roles.cache.some(role => role.name === 'colorm'))

Related

Find user role from DM DiscordJS

I'm currently working on a bot where I need to go into DM's with a user, answer questions and update roles in the server.
My current problem is that it gives the role fine, but after the user has been given the role, the bot don't update the roles in it's memory.
So after the user has been given the first role, he needs to send a message in the server for the bot to knows his new roles, and I want to avoid that.
Example : Send message in server -> Bot DM's, answers the questions, bot gives role and send second question -> User answers the new question but bot don't see the user's new role.
function restart(msg, member, memberRole1){
if(msg.content == "!start"){
msg.author.send("Riddle1" )
member.roles.add(memberRole1)
}
}
function test(msg, memberRole,memberRole2,memberRole3,memberRole4, member){
console.log(client.guilds.cache.get('ServerID').members.cache.get(msg.author.id).roles)
if (client.guilds.cache.get('ServerID').members.cache.get(msg.author.id).roles.cache.some(role => role.name === 'Role1')){
try {
if(msg.channel.type == 'DM'){
if(msg.content == 'Answer1'){
member.roles.add(memberRole)
msg.author.send("Riddle2")
}
}
} catch (error) {
console.log(error)
}
}
else if(client.guilds.cache.get('ServerID').members.cache.get(msg.author.id).roles.cache.some(role => role.name === 'Role2')){
try {
if(msg.channel.type == 'DM'){
if(msg.content == 'Answer2'){
member.roles.add(memberRole2)
msg.author.send("Riddle3")
}
}
} catch (error) {
console.log(error)
}
}
else if(client.guilds.cache.get('ServerID').members.cache.get(msg.author.id).roles.cache.some(role => role.name === 'Role3')){
try {
if(msg.channel.type == 'DM'){
if(msg.content == 'Answer3'){
member.roles.add(memberRole3)
msg.author.send("Riddle4")
}
}
} catch (error) {
console.log(error)
}
}
else if(client.guilds.cache.get('ServerID').members.cache.get(msg.author.id).roles.cache.some(role => role.name === 'Role4')){
try {
if(msg.channel.type == 'DM'){
if(msg.content == 'Answer4'){
member.roles.add(memberRole4)
}
}
} catch (error) {
console.log(error)
}
}
}
client.on('messageCreate', (msg) => {
let server = client.guilds.cache.get('ServerID')
let memberRole1= server.roles.cache.find(role => role.name === "role1")
let memberRole= server.roles.cache.find(role => role.name === "role2")
let memberRole2= server.roles.cache.find(role => role.name === "role3")
let memberRole3= server.roles.cache.find(role => role.name === "role4")
let memberRole4= server.roles.cache.find(role => role.name === "FinalRole")
let member = server.members.cache.get(msg.author.id)
restart(msg, member, memberRole1)
test(msg, memberRole,memberRole2,memberRole3,memberRole4, member)
}
);
I've already tried to use the same function that is used in the IF, but as said, the bot don't update it's infos until the user send a message in the server.
Thanks for the help.
You can always force-update the member by doing:
member.fetch(true);
https://discord.js.org/#/docs/main/stable/class/GuildMember?scrollTo=fetch
I would not recommend doing this often, though. Instead, you should probably do this once per user if you don't know what riddle they're on, and then locally store state of what riddle they're on in an object. For example:
const userToRiddleNum = {};
const roleToRiddleNum = {
role1: 1,
role2: 2,
role3: 3,
'final role': 4,
};
// Later, in test() or 'messageCreate' or what not
if (!(member.user.id in userToRiddleNum)) {
// Make sure roles are up to date
await member.fetch(true);
// Set the user's riddle num to the highest
// riddle num of all their roles
userToRiddleNum[member.user.id] = Math.max(
...member.roles.cache.map((role) => roleToRiddleNum[role.name] || 0),
);
}
// Later
userToRiddleNum[member.user.id] // Up to date!
// Now the user solved a riddle:
userToRiddleNum[member.user.id]++
As you mentioned you use roles as the way to indicate what question the user is on currently, I would recommend doing something "easier", and that is using quick.db
With that, you can just keep track of peoples questions doing for example something like:
db.set(`${message.member.id}.question`, 1);
and then just check what question they are in
if(`${message.member.id}.question`) == 1){
//They are on question 1 do stuff -->
db.set(`${message.member.id}.question`, 2);
}
You can get familiar with quick.db documentation and play around with it.

I'm trying to make a set role command and a set channel command. I've attempted to do it but it doesn't work

So what's going on is that I'm trying to make a set role/set channel command for logs and a mute role to mute people with and I'm wondering how to do this. I have looked at the docs and other stackoverflow threads and it still doesn't work.
if(!args[1]) return message.channel.send('Please specify a arg')
let roleName = args.slice(2).join(" ");
var role = message.guild.roles.cache.find(role => role.name === roleName)
if(!role){
message.channel.send("Thats not a role!")
}
if(role){
await GuildConfigSchema.update({ Guild: message.guild.id }, { MuteRole: role })
message.channel.send(`The mute role is now ${role}`)
}
First you can use if(role){ } else { } something like that and second on comments you said when I ping it for your code ping will not work because you use role.name if you want to catch role with ping then use let role = message.mentions.roles.first();

How would I bypass a cetian role on a cooldown script discord.js/ command that restricts a certain command to a certain channel

This is the current code that I have, I would like to make it where if you have a certain role then you can bypass the cooldown, also if anyone knows how to make a command that restricts a certain command to a certain channel, instead of having this really long message.channel.id.
const Discord = require('discord.js');
const fetch = require('node-fetch');
const talkedRecently = new Set();
module.exports.run = async(client, message, args, queue, searcher, ) => {
if (talkedRecently.has(message.author.id)) {
message.channel.send("Wait 1 minute before getting typing this again. " +'<#'+ message.author.id + '>');
} else {
switch(args[0].toLowerCase()){
case 'neko':
if(message.channel.id === '739002385531404288'||
message.channel.id === '646849145289834506'||
message.channel.id === '785079847763574794'||
message.channel.id === '782891383361896469'||
message.channel.id === '784417039425994772'){
fetch('https://nekos.life/api/v2/img/lewd')
.then(res => res.json())
.then(json => {
let nekoEmbed = new Discord.MessageEmbed()
.setTitle('Lewd Nekos! (=^・ω・^=)')
.setImage(json.url)
message.channel.send(nekoEmbed)
})
}else{
return}}
talkedRecently.add(message.author.id);
setTimeout(() => {
talkedRecently.delete(message.author.id);
}, 60000);
}
}
module.exports.config = {
name: "hentai",
aliases: ['ht']
}
```
Answering Your First Question:
Simply check if the member has a certain role. If they do, construct your if statement so that it will not fire if they have that role
Make sure to use message.member when checking roles
if (talkedRecently.has(message.author.id) && !message.member.roles.cache.has('bypass role id here')) {
// Your cooldown message
}
Learn more about Roles#has
Answering your 2nd question:
You can have an array of channel id's then use includes to check if any of the id's in the array match the current channel id
const ids = ['id1', 'id2', 'id3', 'id4'] // And so on
if (ids.includes(message.channel.id)) {
// Your Code
}
Learn more about Array.prototype.includes

Discord.js Assign a role based off a certain message reaction

I Want it so if a member does a certain reaction to a certain message. it will give them a role.
i know how to add a role
let role6 = member.guild.roles.cache.find(role => role.name == "Member");
if(!role6) return;
user.roles.add(role6);
but I'm not sure who to get it to be triggered by a :white_check_mark: reaction to a certain message in a channel. any ideas?
You can use the messageReactionAdd event, which will emit when someone reacts to a message.
client.on('messageReactionAdd', (reaction, user) => {
if (reaction.message.id !== 'Message ID') return;
const role6 = member.guild.roles.cache.find((role) => role.name == 'Member');
if (!role6) return;
reaction.guild.member(user).roles.add(role6);
});

How to fix: roles is not defined (Discord.js)

I'm trying to add a role to a member when they join my server, here is the code I have:
The problem I'm getting is "ReferenceError: roles is not defined" can someone please help me solve this?
client.on("guildMemberAdd", (member) => {
console.log("User " + member.user.username + " has joined the server!");
var role = member.guild.roles.cache.find((role) => role.name === "Javjajjaj");
roles.add(role);
});
The problem is that the roles variable is never defined within your piece of code.
client.on("guildMemberAdd", GuildMember => {
// Logging when a GuildMember enters the Guild.
console.log(`${GuildMember.user.tag} joined ${GuildMember.guild.name}!`);
const Role = GuildMember.guild.roles.cache.find(role => role.name == "Javjajjaj"); // Finding the Role by name in the GuildMember's Guild.
// Checking if the role exists.
if (!Role) return console.error("Couldn't find the role!");
// Trying to add the Role to the GuildMember and catching any error(s).
GuildMember.roles.add(Role).catch(error => console.error(`Couldn't add the Role to the GuildMember. | ${error}`));
});

Categories

Resources