My kick command lets anyone in the server kick someone - javascript

I need my kick command for my discord bot only be able to work for moderators and admins. Does anyone have any more coding that could make it so only mods or admins could kick?
My coding for the kick command:
client.on('message', (message) => {
if (!message.guild) return;
if (message.content.startsWith('!kick')) {
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch((err) => {
message.reply('I was unable to kick the member');
console.error(err);
});
} else {
message.reply("That user isn't in this guild!");
}
} else {
message.reply("You didn't mention the user to kick!");
}
}
});

You can use GuildMember.hasPermission to check if a user has a certain permission. You can see the valid permission flags here, although I think you'll want to use KICK_MEMBERS in this case.
if (!message.member.hasPermission('KICK_MEMBERS'))
return message.channel.send('Insufficient Permissions');
You can also restrict access via the roles someone has, for which I urge you to read this existing answer

Related

Discord.js bot: How can I check if the person who pings has certain role

I was trying to create a warning about pinging staff, my current code is:
const roleId = "761874957705674762";
client.on("message", async message => {
if (message.author.bot) return false;
if (message.mentions.has(roleId)) {
await message.delete();
message.reply(`dont ping staff!`);
message.delete(5000);
};
});
I don't get any errors, but I also don't get the desired respond "don't ping staff"
You can check a user for roles by the role ID:
// assuming role.id is an actual ID of a valid role:
if(message.member.roles.cache.has(role.id)) {
console.log(`Yay, the author of the message has the role!`);
} else {
console.log(`Nope, noppers, nadda.`);
}
And if you want to check if he has one of multiple roles, you can do this:
// Check if they have one of many roles
if(message.member.roles.cache.some(r=>["Dev", "Mod", "Server Staff", "Proficient"].includes(r.name)) ) {
// has one of the roles
} else {
// has none of the roles
}

Is there a way for a bot to know when a guild member logs in on a discord server?

I want to know when a guild member logs in, not when the member joins, so guildMemberAdd does not work in this case. Perhaps there is another way of going about what I want to do, so I will explain here.
When users of my website upgrade to a standard or pro membership they are able to join my discord server among other things. I still have to sort out how to determine that the discord user is a Standard/Pro subscribing member on my website, but I think I can send a one time invite link or a password which the member has to enter send the discord bot after the bot sends a welcome message asking for the password or something, but that should be relatively straightforward to do.
My concern is after a user has joined the discord server, what should I do if, for example, that user decides to unsubscribe from the standard/pro membership on my website? I want to kick that user now, so I was thinking that I could just detect when a guild member starts a session on my discord server with the bot and test to see if the user is still a standard/pro member from my website, but there doesn't appear to be any event for this.
Perhaps I should be thinking of this in another way. Is there a method for just kicking members from my discord server outside of the event callback context?? I just started with the API this morning, so forgive me if what I'm asking is simple. I literally and shamefully just copy/pasted the discord.js example in their docs to see if simple message detection works and it thankfully does (code below)
const Discord = require("discord.js")
const client = new Discord.Client()
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
});
client.on("message", (msg) => {
if (msg.content === "ping") {
msg.reply("Pong!")
}
});
client.on("guildMemberAdd", (member) => {
member.send(
`Welcome on the server! Please be aware that we won't tolerate troll, spam or harassment.`
);
});
client.login(process.env.DISCORD_EVERBOT_TOKEN);
In order to track the users, I made an invite process which starts when a member of my website upgrades to a Pro or Standard account. I couldn't find a way to confirm the user connecting is in fact connecting with a specific invite to know which user it was other than sending a temporary discord server password. So I coded the bot to prompt a new user to input the temp password as a DM to the bot when the guildMemberAdd event is fired, this password points to the user on my website and then I store the discord member id during this transaction so if a member decides to cancel their subscription, I remove roles accordingly.
The solution below is working like a charm:
client.on("message", async (msg) => {
if(msg.author.id === client.user.id) { return; }
if(msg.channel.type == 'dm'){
try{
let user = await User.findOne({ discord_id: msg.member.id }).exec();
if(user)
await msg.reply("I know you are, but what am I?");
else {
user = await User.findOne({ discord_temp_pw: msg.content }).exec();
if(!user){
await msg.reply(`"${msg.content}" is not a valid password. Please make sure to enter the exact password without spaces.`)
}
else {
const role = user.subscription.status;
if(role === "Basic")
{
await msg.reply(`You have a ${role} membership and unfortunately that means you can't join either of the community channels. Please sign up for a Standard or Pro account to get involved in the discussion.
If you did in fact sign up for a Pro or Standard account, we're sorry for the mistake. Please contact us at info#mydomain.com so we can sort out what happened.`)
}
else{
const roleGranted = await memberGrantRole(msg.member.id, role);
const userId = user._id;
if(roleGranted){
let responseMsg = `Welcome to the team. With a ${role} membership you have access to `
if(role === "Pro")
await msg.reply(responseMsg + `both the Standard member channel and the and the Pro channel. Go and introduce yourself now!`);
else
await msg.reply(responseMsg + `the Standard member channel. Go and introduce yourself now!`);
}
else{
await msg.reply("Something went wrong. Please contact us at info#mydomain.com so we can sort out the problem.");
}
user = { discord_temp_pw: null, discord_id: msg.member.id };
await User.findByIdAndUpdate(
userId,
{ $set: user }
).exec();
}
}
}
}
catch(err){
console.log(err);
}
}
}
client.on("guildMemberAdd", (member) => {
member.send(
`Welcome to the server ${member.username}!
Please enter the password that you received in your email invitation below to continue.`
);
});
const memberGrantRole = async(member_id, role) => {
const guild = client.guilds.cache.get(process.env.DISCORD_SERVER_ID);
const member = guild.members.cache.get(member_id);
try{
await member.roles.add(role);
}
catch(err){
return {err, success: false};
}
return {err: null, success: true};
}

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)

Ban module, Discord bot error.. discord.js

1 day ago i publish an issue with for a discord bot that said that my id was not a property of null. Now its works. But it still not able to ban, and it gives me the error marked on the code: message.reply("I was unable to ban the member :(");
This is the code:
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports = {
name: 'ban',
description: "ban peoples ;D",
execute(message, args, client) {
if (!message.member.hasPermission("BAN_MEMBERS") ||
!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send("You don't have a permissions to do this, maybe later ;) ");
const user = message.mentions.users.first();
const member = message.guild.member(user);
if (!user) return message.channel.send("Please mention the user to make this action");
if (user.id === message.author.id) return message.channel.send("You can't ban yourself, I tried :(");
member.ban(() => {
message.channel.send('Successfully banned **${user.tag}**');
}).catch(err => {
message.reply("I was unable to ban the member :(");
})
}
}
i checked to see if the bot needs permissions, i gave it him but it still not working.
The issue is here
member.ban(() => {
message.channel.send('Successfully banned **${user.tag}**');
}).catch(err => {
message.reply("I was unable to ban the member :(");
})
You are passing an entire function into the ban method
Really you should be calling the function then using .then(() => {}) to handle the promise
It should look like this
member.ban()
.then(() => {
message.channel.send('Successfully banned **${user.tag}**');
})
.catch((err) => {
message.reply("I was unable to ban the member :(");
console.error(err);
});

Categories