If I use a command like this, then it will not work:
!role #Nick#0000 #role
How can I fix it?
I tried to use
message.mentions.members.first()
,but i think i was doing it wrong
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("nope.");
let role = args.join(" #").slice(22);
if(!role) return message.reply("nope!");
let gRole = message.guild.roles.find(`name`, role);
if(!gRole) return message.reply("nope.");
if(rMember.roles.has(gRole.id)) return message.reply("nope.");
await(rMember.removeRoles(['id', 'id']));
await(rMember.addRole(gRole.id));
try{
await rMember.send(`nope ${gRole.name}!`)
}catch(e){
}
}
module.exports.help = {
name: "role"
}
So I don't have any result now.
Disclaimer: I am the author of the npm package used in this answer. I've included it to present the simplest and easiest solution I see. This answer does not intend to promote the package itself in any way.
To check if a certain argument or string is a mention and extract the member/role/channel, you can use discord-mentions.
const getMention = require('discord-mentions');
try {
if (!args[1]) return await message.reply('Please provide a user.');
if (!args[2]) return await message.reply('Please provide a role.');
let member;
if (getMention(args[1])) member = getMention(args[1], message.guild).member;
else member = message.guild.members.find(m => m.user.tag === args[1]);
if (!member) return await message.reply('Invalid user.');
let role;
if (getMention(args[2])) role = getMention(args[2], message.guild).role;
else role = message.guild.roles.find(r => r.name === args[2]);
if (!role) return await message.reply('Invalid role.');
// Continue on... 'member' is a GuildMember, 'role' is a Role.
} catch(err) {
console.error(err);
}
Related
I have a ban command where you can either mention a user or use their id.
When mentioning the user in the embed it comes up with undefined has been banned! I want it to come up with user#0001 that was banned when mentioning the user or by banning them by their id.
Current code:
const switchc = bot.emojis.cache.find((emoji) => emoji.name === "switchcancel");
const switche = bot.emojis.cache.find((emoji) => emoji.name === "switch");
if (!message.member.hasPermission(["BAN_MEMBERS", "ADMINISTRATOR"]))
return message.channel.send(
`${switchc} **You do not have the permissions to complete this command!**`
);
let banMember =
message.mentions.members.first() ||
(await bot.users.fetch(args[0]).catch((err) => console.log(err)));
if (!banMember)
return await message.channel.send(
`${switchc} **Please supply a user to be banned!**`
);
let reason = args.slice(1).join(" ");
if (!reason) reason = "No reason was provided!";
if (!message.guild.me.hasPermission(["BAN_MEMBERS", "ADMINISTRATOR"]))
return message.channel.send(
`${switchc} **I do not have permission to complete this command!**`
);
message.guild.members
.ban(banMember, { days: 1, reason: reason })
.catch((err) => console.log(err));
const bEmbed = new MessageEmbed()
.setColor("RANDOM")
.setDescription(`**${banMember.tag}** has been banned!`);
message.channel.send(bEmbed);
Is there something I am doing wrong?
As you do not need a member object, the simplest fix would be:
let banMember = message.mentions.users.first() || await bot.users.fetch(args[0]).catch(err => console.log(err))
Using users instead of members in the mention getter.
Okay, I figured out my own issue. What I did was instead of using
${banMember.tag}
I instead defined tag by doing
let tag = banMember.tag || banMember.user.tag
The new code is as follows
const switchc = bot.emojis.cache.find(emoji => emoji.name === "switchcancel");
const switche = bot.emojis.cache.find(emoji => emoji.name === "switch");
if(!message.member.hasPermission(["BAN_MEMBERS", "ADMINISTRATOR"])) return message.channel.send(`${switchc} **You do not have the permissions to complete this command!**`)
let banMember = message.mentions.members.first() || await bot.users.fetch(args[0]).catch(err => console.log(err))
if(!banMember) return await message.channel.send(`${switchc} **Please supply a user to be banned!**`)
let tag = banMember.tag || banMember.user.tag
let reason = args.slice(1).join(" ")
if(!reason) reason = "No reason was provided!"
if (!message.guild.me.hasPermission(["BAN_MEMBERS", "ADMINISTRATOR"])) return message.channel.send(`${switchc} **I do not have permission to complete this command!**`)
message.guild.members.ban(banMember, { days: 1 , reason: reason}).catch(err => console.log(err))
const bEmbed = new MessageEmbed()
.setColor("RANDOM")
.setDescription(`**${tag}** has been banned!`)
message.channel.send(bEmbed)
}
}
This will allow for the users tag to show up when baning by ID or mention.
ok so i made sure to check ids,
the user im trying to unban is banned.
the id is correct
i tried to console log what userBanned returns and it is undefined
like how?
const text = args.join(` `)
const bansCollection = await message.guild.fetchBans()
const userBanned = bansCollection.find(user => user.id == text)
if (!isNaN(text)) {
if (userBanned) {
await message.guild.members.unban(text)
message.channel.send(`<#${text}> has been unbanned`)
} else { message.channel.send(new Discord.MessageEmbed().setTitle(`**That user is not Banned!**`)) }
} else { message.channel.send(`You Need the user's ID!`) }
console.log(text , bansCollection, userBanned)}
I would fetch the audit logs nd filter them.
Example:
message.guild.fetchAuditLogs()
.then(logs => {
let ban = logs.entries.filter(e => e.action === 'MEMBER_BAN_ADD') //get all the bans
ban = ban.filter(e => e.target.id === text) //filter the bans from the user
if (!message.guild.members.cache.get(text)) return message.channel.send(`This user is not in this server.`);
if (userBanned) {
await message.guild.members.unban(text)
message.channel.send(`<#${text}> has been unbanned`);
} else {
let embed = new Discord.MessageEmbed();
embed.setTitle(`**That user is not Banned!**`);
message.channel.send(embed);
}
});
I was trying to make a ban command where you can ban a user with a reason.
Turns out user.ban is not a function in Discord.js V12 even though it should be.
Here is my code.
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'ban',
description: 'Bans a user.',
category: 'Moderation',
usage: '^ban <user> <reason>',
run: async (bot, message, args) => {
if (!message.member.hasPermission('BAN_MEMBERS')) {
return message.channel.send('You do not have permission to do this! ❌');
}
if (!message.guild.me.hasPermission('BAN_MEMBERS')) {
return message.channel.send('I do not have permission to do this! ❌');
}
const user = message.mentions.users.first();
if (!user) {
return message.channel.send('User was not specified. ❌');
}
if (user.id === message.author.id) {
return message.channel.send('You cannot ban yourself! ❌');
}
let reason = message.content
.split(' ')
.slice(2)
.join(' ');
if (!reason) {
reason = 'No reason provided.';
}
let Embed = new MessageEmbed()
.setTitle(`Justice! | Ban Action`)
.setDescription(`Banned \`${user}\` - Tag: \`${user.discriminator}\``)
.setColor('ORANGE')
.setThumbnail(user.avatarURL)
.addField('Banned by', `\`${message.author.username}\``)
.addField(`Reason?`, `\`${reason}\``)
.setTimestamp();
message.channel.send(Embed);
user.ban(reason);
},
};
Is there a way to fix this?
You're getting a User instead of a GuildMember. A User represents a person on discord, while a GuildMember represents a member of a server. You can get a GuildMember instead of a User by using mentions.members instead of mentions.users ex:
const user = message.mentions.members.first()
I have a command which worked, but at some point stopped, returning to the chat message that the role does not exist. An error "(node:12228) DeprecationWarning: Collection#find: pass a function instead" is sent to the console every time I use a command, but I always had it
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("nope.");
let role = args.join(" ").slice(22);
if(!role) return message.reply("nope!");
let gRole = message.guild.roles.find(`name`, role);
if(!gRole) return message.reply("role does not exist.");
const allowed = ['some id'];
if (!allowed.includes(gRole.id)) return;
if(rMember.roles.has(gRole.id)) return message.reply("nope.");
await(rMember.removeRoles(['some id']));
await(rMember.addRole(gRole.id));
if(gRole.id == 'id') rMember.addRole('id') && rMember.removeRoles(['some id']);;
try{
await rMember.send(`you got ${gRole.name}!`)
}catch(e){
}
}
module.exports.help = {
name: "role"
}
So I need the command to work.
In order of appearance, I see these mistakes in your code...
You're not catching any rejected promises.
MANAGE_MEMBERS is not a valid permission flag.
You should pass a function into Collection.find().
No idea what you're trying to do with the declaration of role.
Your use of the && logical operator in your if statement is incorrect. Use a block statement instead.
Your catch block in the try...catch statement has been left empty.
Combining the answers provided to your other questions about this code, this is a correct, much cleaner rewrite...
const getMention = require('discord-mentions'); // Don't forget to install.
module.exports.run = async (bot, message, args) => {
if (!message.guild) return;
try {
if (!message.member.hasPermission('MANAGE_ROLES')) return;
if (!args[1]) return await message.reply('Please provide a user.');
if (!args[2]) return await message.reply('Please provide a role.');
if (args[3]) return await message.reply('Too many arguments provided.');
let member;
if (getMention(args[1])) member = getMention(args[1], message.guild).member;
else member = message.guild.members.find(m => m.user.tag === args[1] || m.id === args[1]);
if (!member) return await message.reply('Invalid user provided.');
let role;
if (getMention(args[2])) role = getMention(args[2], message.guild).role;
else role = message.guild.roles.find(r => r.name === args[2] || r.id === args[2]);
if (!role) return await message.reply('Invalid role provided.');
const allowed = ['role1ID', 'role2ID', 'role3ID'];
if (!allowed.includes(role.id)) return await message.reply('That role is not allowed.');
if (member.roles.has(role.id)) return await message.reply('That user already has that role.');
await member.removeRoles(['someID', 'someOtherID']);
await member.addRole(role.id);
if (role.id === 'anAlternateRoleID') {
await member.removeRoles(['someID', 'someOtherID']);
await member.addRole('otherRoleID');
}
await member.send(`You got the ${role.name} role.`)
.catch(() => console.log(`Couldn't send message to ${member.user.tag}.`));
} catch(err) {
console.error(err);
}
};
module.exports.help = {
name: 'role'
};
Keep in mind, if you're removing just one role from a member, you should use the singular version of the method, GuildMember.removeRole().
I want the bot to change member permissions and set "send messages" to false if someone uses $done #user.
client.on('message', async message => {
if (message.author.bot) return;
if (message.content === prefix + "done") {
var user = message.guild.member(message.mentions.users.first());
message.channel.overwritePermissions(user, {
SEND_MESSAGES: false
});
}
});
You should either use:
const user = message.mentions.users.first();
or
const user = message.mentions.members.first();
and then add a
if(!user) return messsage.channel.send('You need to mention a user!'); below the `const user` line.