First name mentions in a text using discord.js - javascript

I am trying to make some sort of kick system. I would like to know how I would get the first name mentioned in a text.
client.on("message", (message) => {
if (message.member.hasPermission(["KICK_MEMBERS"],["BAN_MEMBERS"])){
if(message.content == "!kick"){
let member = message.mentions.members();
console.log(member)
member.kick("You have been kicked").then ((member) => {
message.channel.send( member.displayName + " has been Kicked!");
})
}
}
});
No error is thrown that I know of.

First off, if you want to check multiple permissions in GuildMember.hasPermission(), you need to pass an array. The way your code is written now, you're passing an array with "KICK_MEMBERS" as the permissions to check and an array with "BAN_MEMBERS" for the explicit parameter.
Solution: message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMEBRS"])
Secondly, you're declaring member as a Collection, when it should be a GuildMember.
Solution: const member = message.mentions.members.first()
client.on("message", async message => {
if (message.content === "!kick" && message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
try {
const member = message.mentions.members.first();
if (!member) return await message.channel.send(`No user mentioned.`);
await member.kick(`Kicked by ${message.author.tag}`);
await message.channel.send(`${member.user.tag} has been kicked.`);
} catch(err) {
console.error(err);
}
}
});

Related

Check if the message sender has a specific role

I'm new in Discord bot coding and I want to create a command where the bot only replies if the message sender has a specific role.
According to the discord.js documentation I have to use GuildMemberRoleManager.cache. Sadly, it isn't working.
The whole command looks like this:
client.on('messageCreate', (message) => {
if (
message.content.toLowerCase() === prefix + 'test' &&
GuildMemberRoleManager.cache.has(AdminRole)
)
message.reply('test');
});
You should get the author's roles. Only members have roles, so you will need to get the author as a member using message.member. message.member returns a GuildMember and GuildMembers have a roles property that returns a GuildMemberRoleManager (the one you mentioned in your original post).
Its cache property is a collection of the roles of this member, so you can use its has() method to check if the user has the admin role:
client.on('messageCreate', (message) => {
let adminRole = 'ADMIN_ROLE';
let isAdmin = message.member.roles.cache.has(adminRole);
if (message.content.toLowerCase() === prefix + 'test' && isAdmin)
message.reply('test');
});
Define the variables which will make you easy to understand as you are new
const guild = message.guild.id;
const role = guild.roles.cache.get("role id");
const cmduser = message.author;
const member = await guild.members.fetch(cmduser.id);
and make if statement like
if(member.roles.cache.has(role.id)) {
return message.channel.send("test")
}
if you want bot to check if user have administrator perm than
message.member.hasPermission('ADMINISTRATOR')
Check all perm flags on Discord Perm Flags
So according to your code it will be
const guild = message.guild.id;
const role = guild.roles.cache.get("role id");
const cmduser = message.author;
const member = await guild.members.fetch(cmduser.id);
client.on("messageCreate",(message) => {
if(message.content.toLowerCase() === prefix + "test" && member.roles.cache.has(role.id))
message.reply("test")
})

Why does role.permissions.remove() not work?

I tried to make a command to remove the MENTION_EVERYONE permission from all roles. It didn't work for some reason. I tried console logging which roles have the permission, and it did, but the only thing is that the permission isn't being taken away. I get no error but here is my code.
client.on('message', msg => {
if(msg.content === 'checkroleperms' && msg.author.id === 'xxxxxxxxxx') {
var roles = msg.guild.roles.cache.array()
var all = '{Placeholder}'
roles.forEach(role => {
if(role.permissions.has('MENTION_EVERYONE')) {
all+= ', ' + role.name;
//RIGHT HERE IS THE WHERE THE PROBLEM IS!!
//Changed this to msg.guild.role.cache.get(role.id).permissions.re...
role.permissions.remove('MENTION_EVERYONE');
console.log(role.name);
}
})
setTimeout(() => msg.channel.send(all), 500);
}
})
Was there something I did wrong? Also, the bot has Admin perms and is the second highest role in the server (right under me). The point is that the command is running but the perms are not being removed.
EDIT: I realized I was only modifying the array, but nothing is happening even when I get it from msg.guild.roles.cache
You were pretty close, the problem is you remove the permission but you never update the role itself.
role.permissions.remove() removes bits from these permissions and returns these bits or a new BitField if the instance is frozen. It doesn't remove or update the role's permissions though.
To apply these changes, you need to use the setPermissions() method that accepts a PermissionResolvable, like the bitfield returned from the permissions.remove() method.
It's probably also better to use roles.fetch() to make sure roles are cached.
Check the working code below:
client.on('message', async (msg) => {
if (msg.content === 'checkroleperms' && msg.author.id === 'xxxxxxxxxx') {
try {
const flag = 'MENTION_EVERYONE';
const roles = await msg.guild.roles.fetch();
const updatedRoles = [];
roles.cache.each(async (role) => {
if (role.permissions.has(flag)) {
const updatedPermissions = role.permissions.remove(flag);
await role.setPermissions(updatedPermissions.bitfield);
updatedRoles.push(role.name);
}
});
const roleList = updatedRoles.join(', ') || `No role found with \`${flag}\` flag`;
setTimeout(() => msg.channel.send(roleList), 500);
} catch (error) {
console.log(error);
}
}
});

How do I make a user answer a question using reactions in Discord.js?

I want the user to answer a "yes or no" question using reactions. Here is my code below.
var emojiArray = ['πŸ”₯', 'πŸ‘', 'πŸ‘Ž', 'βœ…', '❌'];
client.on('message', (negotiate) => {
const listen = negotiate.content;
const userID = negotiate.author.id;
var prefix = '!';
var negotiating = false;
let mention = negotiate.mentions.user.first();
if(listen.toUpperCase().startsWith(prefix + 'negotiate with '.toUpperCase()) && (mention)) {
negotiate.channel.send(`<#${mention.id}>, do you want to negotiate with ` + `<#${userID}>`)
.then(r => r.react(emojiArray[3], emojiArray[4]));
negotiating = true;
}
if(negotiating == true && listen === 'y') {
negotiate.channel.send('Please type in the amount and then the item you are negotiating.');
} else return;
})
As you can see, the code above allows the user to tag someone and negotiate with them (the negotiating part doesn't matter). When the user tags someone else, it asks them if they want to negotiate with the user that tagged them. If the user says yes, they negotiate.
I want to do this in a cleaner way using reactions in discord. Is there any way to just add a yes or no reaction emoji and the user will have to click yes or no in order to confirm?
First of all, you kinda messed up while getting the user object of the mentioned user, so just so you know it's negotiate.mentions.users.first()!
While wanting to request user input through reactions, we'd usually want to use either one of the following:
awaitReactions()
createReactionCollector
Since I personally prefer awaitReactions(), here's a quick explanation on how to use it:
awaitReactions is a message object extension and creates a reaction collector over the message that we pick. In addition, this feature also comes with the option of adding a filter to it. Here's the filter I usually like to use:
const filter = (reaction, user) => {
return emojiArray.includes(reaction.emoji.name) && user.id === mention.id;
// The first thing we wanna do is make sure the reaction is one of our desired emojis!
// The second thing we wanna do is make sure the user who reacted is the mentioned user.
};
From there on, we could very simply implement our filter in our awaitReactions() function as so:
message.awaitReactions(filter, {
max: 1, // Accepts only one reaction
time: 30000, // Will not work after 30 seconds
errors: ['time'] // Will display an error if using .catch()
})
.then(collected => { // the reaction object the user reacted with
const reaction = collected.first();
// Your code here! You can now use the 'reaction' variable in order to check certain if statements such as:
if (reaction.emoji.name === 'πŸ”₯') console.log(`${user.username} reacted with Fire emoji!`)
Finally, your code should look like this:
const filter = (reaction, user) => {
return emojiArray.includes(reaction.emoji.name) && user.id === mention.id;
};
message.awaitReactions(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === 'πŸ”₯') console.log(`${user.username} reacted with Fire emoji!`)
you should use a ReactionCollector:
var emojiArray = ['πŸ”₯', 'πŸ‘', 'πŸ‘Ž', 'βœ…', '❌'];
const yesEmoji = 'βœ…';
const noEmoji = '❌';
client.on('message', (negotiate) => {
const listen = negotiate.content;
const userID = negotiate.author.id;
var prefix = '!';
var negotiating = false;
let mention = negotiate.mentions.user.first();
if(listen.toUpperCase().startsWith(prefix + 'negotiate with '.toUpperCase()) && (mention)) {
negotiate.channel.send(`<#${mention.id}>, do you want to negotiate with ` + `<#${userID}>`)
.then(async (m) => {
await m.react(yesEmoji);
await m.react(noEmoji);
// we want to get an answer from the mentioned user
const filter = (reaction, user) => user.id === mention.id;
const collector = negotiate.createReactionCollector(filter);
collector.on('collect', (reaction) => {
if (reaction.emoji.name === yesEmoji) {
negotiate.channel.send('The mentioned user is okay to negotiate with you!');
// add your negotiate code here
} else {
negotiate.channel.send('The mentioned user is not okay to negotiate with you...');
}
});
});
negotiating = true;
}
})
This allows you to listen for new reactions added to a message. Here is the documentation: https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=createReactionCollector

Trying to add a role to a mentioned user

I am trying to make a bot for a game of tag. I am making it so you can mention a user and it adds the 'IT' role to them, but when they don't mention a member, it's added to them. My code is here:
const args = message.content.slice(prefix.length).trim().split(/ +/g);
if (message.content.startsWith(`${prefix}tag`)) {
if (!message.mentions.users.size) {
let roleenter = message.guild.roles.get("555947490315075600");
let member = message.member;
member.addRole(roleenter).catch(console.error);
message.reply("you are now it!")
client.channels.get("555943069271457792").send(member + " is now in!")
await message.guild.fetchMembers();
const role = message.guild.roles.get("555947490315075600");
for (const member of role.members.array()) {
await member.removeRole(role);
}} else {
let member = message.mentions.users.first();
let roleenter = message.guild.roles.get("555947490315075600");
member.addRole(roleenter).catch(console.error);
message.reply("you are now it!")
client.channels.get("555943069271457792").send(member + " is now in!")
await message.guild.fetchMembers();
const role = message.guild.roles.get("555947490315075600");
for (const member of role.members.array()) {
await member.removeRole(role);
Whenever I try #tag #user, it says member.addRole is not a function when I use it earlier on and it works.
Change this line:
let member = message.mentions.users.first();
To this line:
let member = message.mentions.members.first();
You used the user Object of the mentioned user, but you have to use the guildMember Object because you canβ€˜t assign a role to an user.

Applying a role if users do not have other roles

Users are still getting the public role regardless of the role they have
I'm sorry if the answer here is fairly obvious but I'm learning javascript as I write this bot. I'm aiming for users to be able to do !name and gain a role called "public" as long as they don't have a role listed in the code (General, Captain, etc.).
client.on('message', async message => {
if (message.channel.id === '535226845654810624'); {
if(message.content.startsWith('!name')) {
if (message.member.roles.some(role => role.name === 'General', 'Captain', 'Lieutenant', 'Sergeant', 'Corporal', 'Recruit'));
const newname = message.content.split(' ').slice(1).join(' ');
message.member.setNickname(newname);
}
else {(message.content.startsWith('!name'));} {
if(message.channel.id === '535226845654810624') {
const newname = message.content.split(' ').slice(1).join(' ');
message.member.setNickname(newname);
const newrole = message.guild.roles.find(x => x.name === 'Public');
message.member.addRole(newrole);
message.delete();
}
}
I'm sure the code is completely ugly. I'm still learning. Right now regardless of if they have the Gen/Capt/Lieutenant/etc roles they still gain the public role.
client.on('message', async message => {
if(message.channel.id === '535226845654810624') {
if (message.content.startsWith('!name')) {
const newname = message.content.split(' ').slice(1).join(' ');
message.member.setNickname(newname);
const newrole = message.guild.roles.find(x => x.name === 'Public');
message.member.addRole(newrole);
message.delete();
}
}
This is the code I had before adding in the attempt to ignore the role add if they have the other roles. I'm not sure how to change this to what I'm looking for.
Take a look at the below code, give it a try and let me know what the result is. There were several errors with your code which I'm quite surprised your editor didn't pick up (or atleast didn't error out the code), such as having a semicolon right after defining an if statement, the extra curly brackets after your else statement, etc.
Anyway, the code below checks if the command entered is !name and if so, it assigns the new nickname to the user. After that it checks if the user has any of the specified roles, and if he does not, he gets a new role 'Public'.
client.on('message', async message => {
if (message.channel.id === '535226845654810624') {
if(message.content.startsWith('!name')) {
// Users are allowed to change their nicknames no matter their roles
const newname = message.content.split(' ').slice(1).join(' ');
message.member.setNickname(newname);
// Define the roles which need to be checked
const roleNames = ['General', 'Captain', 'Lieutenant', 'Sergeant', 'Corporal', 'Recruit'];
// If the user does not have any of the roles above, assign them the role 'Public'
if (!message.member.roles.some(role => roleNames.includes(role.name))) {
const newrole = message.guild.roles.find(x => x.name === 'Public');
message.member.addRole(newrole);
message.delete();
}
}
}
});

Categories