Role exclusive commands not working // Discord.js - javascript

My code is currently:
if (message.content == ",test") {
if (message.member.roles.find("name", "images")) {
message.channel.send( {
file: "http://www.drodd.com/images14/black11.jpg" // Or replace with FileOptions object
});
}
if (!message.member.roles.find("name", "images")) { // This checks to see if they DONT have it, the "!" inverts the true/false
message.reply('You need the \`images\` role to use this command.')
.then(msg => {
msg.delete(5000)
})
}
message.delete(100); //Supposed to delete message
return; // this returns the code, so the rest doesn't run.
}
If the user has the role 'images' I want the bot to send the image when they say ",test" and I want the user's ",test" message to be deleted after some seconds. However, this doesn't seem to be working.
I have tried to send the image without the role checking and that works.
How can I fix this?

This is because message.member.roles.find("name", "images") checks if the roles EXISTS in the guild. In order to find if someone has a role, you would use message.member.roles.has(myRole). To find the ID of a role dynamically, you would use this:
let myRole = message.guild.roles.find("name", "Moderators").id;.

Related

Discord bot reacts when specific user is tagged

I'm new to programming and i'm trying to make a Discord bot for me and my friends, for now I have set up two commands, the first works fine, but the second one is the problem.
client.on('message', msg => {
if (msg.content === `#usertag#0001`) {
msg.channel.send(`<#${msg.author.id}> <#${msg.author.id}> <#${msg.author.id}> <#${msg.author.id}> don't tag me`);
}
});
So what it should do is when a specific user is tagged it sends a message, the message sent from the bot is working (it tags the user who sent the message 3 times and then it says something else), but the part where the bot recognizes the tag doesn't work.
I tried by putting the Discord id, using the full #, and other stuff, but it doesn't seem to work.
For this you could use the message.mentions method, and here is how you could use it for example:
// For Discord V13 'message' is deprecated and
// will be removed in the future, use 'messageCreate' instead.
client.on("message", msg => {
// Disable messages from bot to avoid endless loops / replies
if(msg.author.bot === true) return;
// Check if anyone is mentioned.
// Skip #everyone mentions to be checked.
if(msg.mentions.users.size > 0 && msg.mentions.everyone === false) {
if(msg.mentions.users.find(user => user.id === "ENTER USER ID HERE")) {
msg.channel.send(`<#${msg.author.id}> <#${msg.author.id}> <#${msg.author.id}> <#${msg.author.id}> don't tag me!`);
}
}
});
Hope this will help you! ! I have tested this with Discord V13, i'm not 100% sure if this will work on Discord V12 as well.

How to make Discord Bot make sure your pinging someone in a command

I'm trying to make the bot say the name of someone I pinged and give that person a role. Right now, if you don't ping someone, the whole bot breaks.
Here is my code:
const taggedUser0 = msg.mentions.members.first();
if (!args.length) {
msg.author.send(`You didn't ping, ${msg.author}!`);
msg.delete(); // Deletes command
} else if (msg.member.roles.holds(role)) {
// checks if the person mentioned already has a role
return;
} else {
taggedUser0.roles.add(role); // adds role
}
msg.author.send(`${taggedUser0}.`);
msg.delete(); // Deletes command
}
I see a few problems with your code:
First of all, else if() will always return an error.
if (false) console.log(false)
else if () console.log(true) // wrong usage
if (false) console.log(false)
else console.log(true) // correct usage
Second of all, you should switch this if statement:
if (!args.length)
// to:
if (!taggedUser0)
Someone could have added an arg and still not have mentioned anyone.
Third of all, GuildMember.roles returns a Manager, not a Collection, so make sure you pass through the cache property:
taggedUser0.roles.cache.holds()
Also, Collection.holds() is not a function. Instead, use Collection.has() (and make sure the passed parameter is the role ID, not the role object):
taggedUser0.roles.cache.has('ID Here');
Lastly, to ping someone, you should use this format:
message.channel.send(`<#${taggedUser0.id}>`);

Trying to make an AFK command using change nickname

I want to make a command that changes the nickname of the person when they type afk on then the bot adds AFK to there nickname. When they type afk off its removes AFK from there name.
client.on('message', message => {
if (message.content.includes('changeNick')) {
client.setNickname({nick: message.content.replace('changeNick', '')});
}
});
I reffered to this code however it doesn't work. Also is there anyway you can reset nickname back when a user types changenickoff?
Yes, you need to use Member#setNickname:
client.on('message', message => {
if (message.content.includes('start-afk')) {
message.member.setNickname(`${message.author.username} [AFK]`);
}
if (message.content.includes('end-afk')) {
message.member.setNickname('');
}
});
Here's what you need to do:
Does the user's nickname already start with [AFK] ?
IF yes, remove it.
notify user
end
ELSE: add [AFK] to their nickname
notify user
end
You were doing client.setNickname, which, to my knowledge, wouldn't work since the client is not a GuildMember instance.
It's worth noting that a GuildMember is verry different to a Discord User. GuildMembers have access to roles and permissions; users do not.
You can view exactly what a User structure is by doing console.log(client.users.cache.get(message.author.id))
Here's the amended code.
Additionally, I have included a function that trims a string to ensure it does not exceed X chars in length.
client.on('message', message => {
//function to trim strings, ensuring they don't exceed X chars in length
trimStr = (str, max) => ((str.length > max) ? `${str.slice(0, max - 3)}...` : str);
if (message.guild) /* Ensure message is in a server; */ {
if (message.content.toLowerCase().startsWith('!afk')) {
const nick = message.member.nickname;
if (nick.startsWith('[AFK]')) {
//remove nick and notify user:
message.member.setNickname(null);
message.reply("Welcome back, I've removed your AFK status.");
} else { //If above condition is false:
//add [AFK] to the new nick along with the nickname
//trim new string to ensure it's not longer than 32 characters since Discord limits this.
const newNickname = trimStr(`[AFK] ${nick.length ? nick : message.author.username}`, 32);
message.member.setNickname(newNickname);
message.reply("Ight mate, I've set your AFK!");
};
};
};
});
If there are any errors, please provide them in full detail (stacktrace and error itself) in the comments so I can be of further assistance to you.
NOTE - You'll need to type !afk in order to trigger this code.

How can I make a bot send a message, then the bot reacts to it then detects when some reacted to it?

So I'm making this thing where you can do this command and it checks if you purchased a thing or not (it gets sent to staff). So I have that bit working but I'm stuck on how to do something like where the bot says, "Are you done with this?" and it reacts to that message with the ❎ and ✅. And when you press one of them, it does the code.
Or make it so it only reacts with the tick and detects when someone reacted to it.
Currently I have:
message.channel.send(new Discord.RichEmbed().setTitle("Rank-Up Application:").setDescription(`**If you wish to send an application to get Ranked-Up in the Discord & ROBLOX Group, this is the right place to do it! **`).setFooter("When you have done that, say done.").setColor("#ff4757")).then(() => {
message.channel.awaitMessages(filter, { maxMatches: 1, time: 90000, errors: ['time']})
.then(collected => {
message.channel.send(":grey_exclamation: **Sending...**")
client.channels.get(`622386044914106388`).send(new Discord.RichEmbed().setTitle("New Rank-Up!").addField(`**The user ${username} has sent in an application to get ranked. Please check the following links to see if you should rank him. Remember: True = Owns Class, False = Doesn't own Class.**`).addField(`Plus: ${plus}`).addField(`Advanced: ${advanced}`).setTimestamp().setFooter("When you have done that, say done.").setColor("#ff4757"))
So that last line of code is the bit it should say the message under. I'm quite stuck on this and don't even know what start code I should put.
Maybe something like this is what you're looking for. I use it on tickets for people to close them. Works fine for me.
message.channel.send(`Message that will have reactions on it.`).then(msg => {
msg.react('❌');
// Wait 300ms to make sure the tick emoji is made after the first reaction. Just incase the API is on the slow side.
setTimeout(function(){msg.react('✅');},300);
// Create a filter to collect, making sure it only checks for non bot users.
// If you want to check for the message author use user.id == message.author.id
const filterEmojis = (reaction, user) => {
return ['❌', '✅'].includes(reaction.emoji.name) && user.bot == false;
};
// Await for a user to react as per our filter above.
msg.awaitReactions(filterEmojis, {time: 60000}).then(collected => {
const reaction = collected.first();
// Check if the reaxtion is an X.
if(reaction.emoji.name === '❌') {
// Do something when this is reacted too.
}
// Check if the reaxtion is a tick.
if(reaction.emoji.name === '✅') {
// Do something when this is reacted too.
}
}).catch(() => {
// Catch errors.
});
}).catch(console.error);

Is there a way to bind a bot to one specific channel?

I am making a Discord bot, and want to make it only be able to post on 1 specific channel. I can not make it have a lower role than a regular member, or it will not be able to give them roles.
I have tried an if/else statement based on the channel's ID.
case 'start':
if (message.channel === 615842616373805067) {
//somewhat unimportant command
return message.member.addRole('615166824849604619'),
message.channel.send(` ${message.author} has been given the role.)`,
message.delete);
//unimportant command ends here
} else {
console.log('Wrong channel, no role.')
}
I expect the bot to only be able to post in this one channel.
Instead of checking for the message.channel Class, try checking for the id property of that class
if(message.channel.id != "615842616373805067") return console.log('Wrong channel, no role.');
//rest of your code
Make sure to check the official documentation for detailed descriptions of each Class, Method, Property, etc.

Categories

Resources