Kick command access to everyone - javascript

So the code below is my Kick.js but I want it so that the mod role can only use the kick command
module.exports = {
name: 'kick', //command name run : async(client,
message, args) => {
if (!message.guild.me.hasPermission('KICK_MEMBER')) return message.channel.send('I do not have permission to use this command
:joy: ');
// Basically checks if the bot has permission to kick a member or not
//Lets define the guildmember to kick!
const Member = message.mentions.members.first() //checking for member mentions
if (!Member) return message.channel.send('Please specify a member to kick.....');
// if there is no user then it will return with that message
await Member.kick({ reason: args.slice(1).join(" ")})
// args.slice(1).join(" ") means it slices the Member Variable and takes the text after it.
message.channel.send(`${ Member.user.tag}
was kicked from the server!`)
// above message will be sent when the member is kicked from the server.
}
}

Check for the message.member permissions
if(!message.member.hasPermission("KICK_MEMBERS"))
return message.reply("You don't have enough permissions for kick")
If you want to check for specific role
if(!message.member.roles.cache.has(modRole))
return message.reply("You aren't a Mod")

Related

Send user that got kicked the reason why they got kick

The only code I have is this:
module.exports = {
name: "kick",
description: "This command kicks a member!",
execute(message, args) {
const target = message.mentions.users.first();
if (target) {
const memberTarget = message.guild.members.cache.get(target.id);
memberTarget.kick();
message.channel.send("User has been kicked");
} else {
message.channel.send(`You coudn't kick that member!`);
}
},
};
Good Morning. So I'm trying to get it to message the person that got kicked the reason why they got kicked. (!kick user reason) I want it so the bot DMs the person what the reason was but I don't know how to do that.
You would only need to add the following:
const reason = args.splice(1).join(` `) || 'Not specified';
memberTarget.send(`You have been kicked: \nReason: ${reason}`)
module.exports = {
name: "kick",
description: "This command kicks a member!",
execute(message, args) {
const target = message.mentions.users.first();
if (target) {
const memberTarget = message.guild.members.cache.get(target.id);
const reason = args.splice(1).join(` `) || 'Not specified';
memberTarget.kick();
message.channel.send("User has been kicked");
memberTarget.send(`You have been kicked: \nReason: ${reason}`)
} else {
message.channel.send(`You coudn't kick that member!`);
}
},
};
The const reason = args.splice(1).join( ) || 'Not specified'; defines the 'reason' property, if there isn't a reason, it defaults to 'Not specified'.
memberTarget.send(You have been kicked: \nReason: ${reason})
Just sends the message to the targeted member.
Right off the bat, I see that you are getting the target using message.mentions.users and getting the memberTarget from the guild's cache. You should avoid this and use message.mentions.members.
You'll have to use the send method of GuildMember, but since it returns a Promise, you'll have to catch any errors. (e.g: the bot cannot DM the member)
// You should do some sanity checks in case you haven't. You don't want everyone to be able to kick members using the bot.
// Getting the first member in message.mentions.members.
const target = message.mentions.members.first();
// Making sure that target is defined.
if (!target) return message.channel.send('Please mention a member to kick.');
// Making sure a reason is provided. (args[0] is the mention)
if (!args[1]) return message.channel.send('Please provide a reason.');
// Making sure the bot can kick the target.
if (!target.kickable) return message.channel.send('Couldn\'t kick the target.');
// Trying to send a message to the target, notifying them that they got kicked, and catching any errors.
target.send(`You have been kicked from ${message.guild.name} for ${args.slice(1, 2000).join(' ')}`).catch(console.error).finally(() => {
// After the message was sent successfully or failed to be sent, we kick the target and catch any errors.
target.kick(`Kicked by ${message.author.tag} for ${args.slice(1, 2000).join(' ')}}.`).then(() => {
message.channel.send(`${target.user.tag} has been kicked for ${args.slice(1, 2000).join(' ')}.`);
}).catch(error => {
console.error(error)
message.channel.send(`Something went wrong...`);
});
});
This is working kick command with reason made by me (you can try it):-
It has every validation you should have in a kick command
const Discord = require('discord.js')
exports.kick = async(message , prefix , client) => {
if(!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send('Missing Permission! You need to have `KICK_MEMBERS` permissions in order kick this member.')
if(!message.guild.me.hasPermission("KICK_MEMBERS")) return message.channel.send('Missing Permission! I need to have `KICK_MEMBERS` permissions to kick this member.')
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
let member = message.mentions.members.first();
if(!member){
let err = "```css\n[ Agrument Error : You Have not mentioned the user on first args. ]\n```\n\n"
let embed = new Discord.MessageEmbed()
.setAuthor(`${client.user.username} Help Manual` , client.user.displayAvatarURL({format : "png"}))
.setTitle(`${message.guild.name}`)
.setDescription(err)
.addField('Help Command:' , `\`\`\`\n${prefix}kick #user#0001 Reason\n\`\`\``)
.setTimestamp()
.setColor('RED')
return message.channel.send(embed)
}
if(args[0] != `<#!${member.id}>`){
let err = "```css\n[ Agrument Error : You Have not mentioned the user on first args. ]\n```"
let embed = new Discord.MessageEmbed()
.setAuthor(`${client.user.username} Help Manual` , client.user.displayAvatarURL({format : "png"}))
.setTitle(`${message.guild.name}`)
.setDescription(err)
.addField('Help Command:' , `\`\`\`\n${prefix}kick #user#0001 Reason\n\`\`\``)
.setTimestamp()
.setColor('RED')
return message.channel.send(embed)
}
if(member.id === message.author.id) return message.channel.send(`Why? No Just Say Why Do you want to kick yourself?`)
let reason = args.slice(1).join(' ');
if(!reason || reason.length <= 1){
reason = "No Reason Was Provided."
}
if(!member.kickable){
return message.channel.send(`I Don't Have Permissions to Kick ${member.user.username}`)
}
member.kick().then(() => {
return message.channel.send(`Successfully Kicked ${member.user.username} for Reason ==> \`${reason}\``)
}).catch(() => {
return message.channel.send(`I Don't Have Permissions to Kick ${member.user.username}`)
})
}

discord.js Banning users outside server

I was able to ban users outside the servers easily but I'm facing trouble in banning members outside or not in the server, here is my code:
const Discord = require('discord.js');
module.exports = {
name: "ban",
description: "Kicks a member from the server",
async run (client, message, args) {
if(!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send('You can\'t use that!')
if(!message.guild.me.hasPermission("BAN_MEMBERS")) return message.channel.send('I don\'t have the right permissions.')
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if(!args[0]) return message.channel.send('Please specify a user');
if(!member) return message.channel.send('Can\'t seem to find this user. Sorry \'bout that :/');
if(!member.bannable) return message.channel.send('This user can\'t be banned. It is either because they are a mod/admin, or their highest role is higher than mine');
if(member.id === message.author.id) return message.channel.send('Bruh, you can\'t ban yourself!');
let reason = args.slice(1).join(" ");
if(!reason) reason = 'Unspecified';
member.ban(`${reason}`).catch(err => {
message.channel.send('Something went wrong')
console.log(err)
})
const banembed = new Discord.MessageEmbed()
.setTitle('Member Banned')
.setThumbnail(member.user.displayAvatarURL())
.addField('User Banned', member)
.addField('Kicked by', message.author)
.addField('Reason', reason)
.setFooter('Time kicked', client.user.displayAvatarURL())
.setTimestamp()
message.channel.send(banembed);
}
}
I couldn't find out how to do son. Can you help me? Thanks in advance
The reason why your code will not work and run into errors is that the user is not a member, while you are trying to stick them into a GuildMember object, which is not possible.
The way to fix this is to use a user object instead.
guild.members.ban() is a method that accepts a user as a parameter.
Another thing to note is that getting msg.mentions.members.first() will create an error because you are not mentioning a member of your server. (again)
Therefore member needs to be changed to message.mentions.users.first() or client.users.cache.get(args[0])
And your ban code needs to be changed to:
message.guild.members.ban(member).then(user => {
message.channel.send(`Banned ${user.id}`);
}).catch(console.error);

Discord bot gives me a false message and I dont know how to fix it

I am making my first discord bot, and I asked my friend to test kick/ban commands, I jokingly, tried banning him, now he had admin privileges so he couldn't get banned but the bot still sent the message confirming the ban, both of us are confused and I want to fix this so I don't get this message in the future.
module.exports = {
name: "kick",
description: "kick command",
execute(message, args) {
if (!message.member.hasPermission("KICK_MEMBERS")) {
message.channel.send("You do not have the permission to execute this command");
return;
}
const member = message.mentions.users.first();
if (member) {
const memberTarger = message.guild.members.cache.get(member.id);
memberTarger.kick();
message.channel.send("User has been kicked!");
} else {
message.channel.send("You could not kick that member");
}
},
};
Replace
const memberTarger = message.guild.members.cache.get(member.id);
memberTarger.kick();
message.channel.send("User has been kicked!");
With
const memberTarger = message.guild.members.cache.get(member.id);
if(!memberTarger.hasPermission('KICK_MEMBERS')){
memberTarger.kick();
message.channel.send("User has been kicked!");
}
You can check if the bot can kick/ban a member with the .kickable or .bannable properties of a GuildMember.
See the example below and give it a try:
const memberToKick; // Should hold the value of the GuildMember you want to kick.
if (memberToKick.kickable) {
memberToKick.kick()
.then(() => {
message.channel.send('Member successfully kicked!');
}).catch((e) => {
message.channel.send(`I couldn't kick the member for some reason. Here is the error: ${e}`);
});
} else {
message.channel.send('Sorry, I don\'t have permission to kick this member...');
}
your code is not perfect but it should work
if you go to the discord developer portal, go to OAuth2 and then click bot and scroll down and select administrator or kick members
then kick the bot and invite it again
This is to make sure your bot has permission to kick
and finally go to your server settings and make sure that your bot's role is above the role you want to kick (i always fall for that)

Discord bot mute command by mention

I want to add few moderation commands to the bot, but I get stuck with "mute" command:
module.exports = {
name: 'mute',
description: 'command to mute members',
execute(message, args){
if(message.member.roles.cache.some(r => r.name === "Siren")){
const role = message.guild.roles.cache.find(r => r.name === "Muted");
const user = message.mentions.members.first().id;
user.roles.add(role);
}
}
}
I keep getting error:
TypeError: Cannot read property 'add' of undefined
I've been reading various guides and going through documentation and I keep failing on finding where I have made a mistake or what even causes this error.
At the first you try add role to member id, not a member. If no members mention in message, you will get empty mention collection and try get id of undefined, because message.mentions.members.first() of empty collection return undefined.
Second, try not use role names, use role ID for this, its more secure. And change your if code from if (statment) then do something to if (!statment) return reject reason this will help avoid unnecessary nesting of code.
module.exports = {
name: 'mute',
description: 'command to mute members',
execute(message, args){
if(!message.member.roles.cache.has('2132132131213')) return message.reply('You can`t use mute command')
const role = message.guild.roles.cache.get('21321321312');
if (!role) return message.reply('can`t get a role')
const member = message.mentions.members.first()
if (!member) return message.reply('Pls mention a member')
member.roles.add(role).then(newMember => {
message.channel.send(`successfully muted member ${member.user}`)
})
}
}

How to fix a complex Discord command in JS based off of webhooks and roles

I'm working on a command where when you do the command, d!woa the following happens
A webhook gets created with a certain name, Then a role gets created with the channel name, after that the bot watches if there's a webhook with that certain name for the channel, and just sees if anyone sends a message in that channel. If it does, then the bot will add that role with the certain name.
The problem is that there's this error : TypeError: Cannot read property 'guild' of undefined
The error will most likely appear at the end of the code provided.
I've tried rearranging the code, defining guild, and defining message. It does not seem to work even after trying all of this. I only want it to rely off of the ID instead of Name to be accurate for this command.
const Discord = require('discord.js');
const commando = require('discord.js-commando');
class woa extends commando.Command
{
constructor(client) {
super(client, {
name: 'watchoveradd',
group: 'help',
memberName: 'watchoveradd',
description: 'placeholder',
aliases: ['woa'],
})
}
async run(message, args){
if (message.channel instanceof Discord.DMChannel) return message.channel.send('This command cannot be executed here.')
else
if(!message.member.guild.me.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('I don\'t have the permissions to make webhooks, please contact an admin or change my permissions!')
if(!message.member.guild.me.hasPermission(['MANAGE_ROLES'])) return message.channel.send('I don\'t have the permissions to make roles, please contact an admin or change my permissions!')
if (!message.member.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('You need to be an admin or webhook manager to use this command.')
if (!message.member.hasPermission(['MANAGE_ROLES'])) return message.channel.send('You need to be an admin or role manager to use this command.')
const avatar = `...`;
const name2 = "name-1.0WOCMD";
let woaID = message.mentions.channels.first();
if(!woaID) return message.channel.send("Channel is nonexistant or command was not formatted properly. Please do s!woa #(channelname)");
let specifiedchannel = message.guild.channels.find(t => t.id == woaID.id);;
specifiedchannel.send('test');
const hook = await woaID.createWebhook(name2, avatar).catch(error => console.log(error))
await hook.edit(name2, avatar).catch(error => console.log(error))
message.channel.send("Please do not tamper with the webhook or else the command implied before will no longer function with this channel.")
setTimeout(function(){
message.channel.send('Please wait...');
}, 10);
setTimeout(function(){
var role = message.guild.createRole({
name: `Name marker ${woaID.name} v1.0`,
color: 0xcc3b3b,}).catch(console.error);
if(role.name == "name marker") {
role.setMentionable(false, 'SBW Ping Set.')
role.setPosition(10)
role.setPermissions(['CREATE_INSTANT_INVITE', 'SEND_MESSAGES'])
.then(role => console.log(`Edited role`))
.catch(console.error)};
}, 20);
var sbwrID = member.guild.roles.find(`Synthibutworse marker ${woaID} v1.0`);
let specifiedrole = message.guild.roles.find(r => r.id == sbwrID.id)
setTimeout(function(){
message.channel.send('Created Role... Please wait.');
}, 100);
message.guild.specifiedchannel.replacePermissionOverwrites({
overwrites: [
{
id: specifiedrole,
denied: ['SEND_MESSAGES'],
allowed: ['VIEW_CHANNEL'],
},
],
reason: 'Needed to change permissions'
});
var member = client.user
var bot = message.client
bot.on('message', function(message) { {
if(message.channel.id == sbwrID.id) {
let bannedRole = message.guild.roles.find(role => role.id === specifiedrole);
message.member.addRole(bannedRole);
}
}})
}};
module.exports = woa;
I expect a command without the TypeError, and the command able to create a role and a webhook (for a marker), and the role is automatically set so that the user that has the role won't be able to speak in the channel, and whoever speaks in the channel will get the role.
The actual output is a TypeError: Cannot read property 'guild' of undefined but a role and webhook are created.
You have var sbwrID = member.guild...
You did not define member. Use message.member.guild...
You can setup a linter ( https://discordjs.guide/preparations/setting-up-a-linter.html ) to find these problems automatically.

Categories