Discord.js ban command ban reason - javascript

Im trying to get a ban command and im using my pervious kick command as a sort of template, i cant quite get the ban reason to work, im assuming thats the only issue the code is below.
const Discord = require('discord.js')
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('**No permission**')
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.ban('no reason')
.then(() => {
message.channel.send(`${user.tag} Has been banned`)
})
.catch(err => {
message.reply('Unable');
console.error(err);
});
} else {
message.reply("Error");
}
} else {
message.reply("You forgot to mention someone");
}
};
module.exports.help = {
name: "ban"
}

You must supply the correct parameters for .ban()
in this case .ban({reason: 'no reason'})
so your corrected code is
if (!message.member.hasPermission("BAN_MEMBERS"))
return message.reply("**No permission**");
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.ban({ reason: "no reason" })
.then(() => {
message.channel.send(`${user.tag} Has been banned`);
})
.catch((err) => {
message.reply("Unable");
console.error(err);
});
} else {
message.reply("Error");
}
} else {
message.reply("You forgot to mention someone");
}
also, please supply errors in future and look for Other information beforehand.

Adding on, a lot of that will not work in V13
if (!message.member.permissions.has("BAN_MEMBERS"))
return message.reply("**You do not have the proper permissions.**");
const user = message.mentions.users.first();
if (user) {
const member = message.guild.members.cache.get(user.id);
if (member) {
member
.ban({ reason: "no reason" })
.then(() => {
message.channel.send(`${user.tag} Has been banned`);
})
.catch((err) => {
message.reply(`Unable to ban User. \`\`\`${err}\`\`\` `);
console.error(err);
});
} else {
message.reply("Error");
}
} else {
message.reply("You forgot to mention someone, <#${message.author.id}>");
}

// © Ahmed1Dev
const Discord = require('discord.js')
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('**No permission**')
const user = message.mentions.users.first();
let reason = args.slice(2).join(' ');
if (user) {
const member = message.guild.member(user);
if (member) {
member
.ban('no reason')
.then(() => {
message.channel.send(`${user.tag} Has been banned`)
})
.catch(err => {
message.reply('Unable');
console.error(err);
});
} else {
message.reply("Error");
}
} else {
message.reply("You forgot to mention someone");
}
};
module.exports.help = {
name: "ban"
}
// © Ahmed1Dev

Related

how do i unban user with discord.js

hey i need my code which i wrote fixed because it wont work here it is the terminal shows the args arent defined if there is some how a different way to do this its accepted too thanks in advance. <3
const Discord = require('discord.js');
const { Client, MessageEmbed } = require('discord.js');
const bot = new Client();
const token = 'tokengoeshere';
bot.on('message', message => {
if (!message.guild) return;
const ubWords = ["!unban", "?unban", ".unban","-unban","!ub","?ub",".ub","-ub"];
if (ubWords.some(word => message.content.toLowerCase().includes(word)) )
if(!message.member.hasPermission("BAN_MEMBERS")) {
return message.reply(`, You do not have perms to unban someone`)
}
if(!message.guild.me.hasPermission("BAN_MEMBERS")) {
return message.reply(`, I do not have perms to unban someone`)
}
let userID = args[0]
message.guild.fetchBans().then(bans=> {
if(bans.size == 0) return
let bUser = bans.find(b => b.user.id == userID)
if(!bUser) return
message.guild.members.unban(bUser.user)
})
});
bot.login(token);
let userID = args[0]
if (!userID) return message.reply("Please specify the user ID you wish to unban!")
try {
message.guild.fetchBans().then(bans => {
if(bans.size === 0) {
return message.reply("There is no users banned!")
} else {
message.guild.members.unban(userID)
}
})
} catch (err) {
console.log(err)
}
You can simply define args like this:
const args = message.content.slice('?'.length).trim().split(/ +/g)
Put it after the message.guild check

MongoDb update statment

I'm currently trying to update a document in mongoDb. I'm new to mongo and reading the documentation didn't help me at all + I'm not getting any errors
My code
const Guild = require('../schemas/GuildSchema')
module.exports = {
name: 'whitelist',
description: "whitelist",
async execute(bot, message, args, PREFIX, Discord, settings, fs) {
if (message.author.id != "173347297181040640") {
return message.channel.send("Sorry only Bacio001 can whitelist!")
}
if (!args[1]) {
return message.channel.send("No guild id given!")
}
try {
Guild.findOneAndUpdate(
{ guildid: args[1]},
{ $set: { whitelisted : true } }
)
} catch (e) {
console.log(e);
}
let guild = bot.guilds.cache.get(args[1]);
message.channel.send(`Whitelisted ${guild.id} with the name ${guild.name} !`)
}
}
https://gyazo.com/a58a9d8175a8a38674b32a2776fa48cb
So I ended up finding the issue I had to await the Guild.findOneAndUpdate
const Guild = require('../schemas/GuildSchema')
module.exports = {
name: 'whitelist',
description: "whitelist",
async execute(bot, message, args, PREFIX, Discord, settings, fs) {
if (message.author.id != "173347297181040640") {
return message.channel.send("Sorry only Bacio001 can whitelist!")
}
if (!args[1]) {
return message.channel.send("No guild id given!")
}
try {
await Guild.findOneAndUpdate(
{ guildid: args[1]},
{ whitelisted : true }
)
} catch (e) {
console.log(e);
}
let guild = bot.guilds.cache.get(args[1]);
message.channel.send(`Whitelisted ${guild.id} with the name ${guild.name} !`)
}
}

Error [BAN_RESOLVE_ID]: Couldn't resolve the user ID to unban

I am trying to create my own discord bot and creating an unban command now. My code is below. I banned a friend and tried to unban by typing -unban 271375814384287744 testing. It then gives me an error saying Error [BAN_RESOLVE_ID]: Couldn't resolve the user ID to unban. Any help would be appreciated.
const Discord = require('discord.js');
const client = new Discord.Client();
const embed = new Discord.MessageEmbed()
.setColor('#39de33')
module.exports = {
name: 'unban',
description: "This unbans a user",
execute(message, args){
if (message.member.permissions.has("BAN_MEMBERS")){
if (!isNaN(args[0])) {
const bannedMember = client.users.fetch(args[0]);
var reason = args.slice(1).join(" ");
if(!reason) {
reason = "No reason given!"
}
if (bannedMember) {
bannedMember
message.guild.members.unban(bannedMember, reason)
.then(() => {
embed.setDescription(`Successfully unbanned **${user.tag}**`);
message.channel.send(embed);
})
.catch(err => {
embed.setDescription('I was unable to unban the member');
message.channel.send(embed);
console.error(err);
});
} else {
embed.setDescription("That user isn't in this guild!");
message.channel.send(embed);
}
} else {
embed.setDescription("You need to provide an user ID to unban");
message.channel.send(embed);
}
} else {
embed.setDescription("You do not have `BAN_MEMBERS` permissions to unban this member");
message.channel.send(embed);
}
}
}
I tried this out and got the same error.
Promise {
<rejected> Error [BAN_RESOLVE_ID]: Couldn't resolve the user ID to unban.
at GuildMemberManager.unban (/home/kayuimineko/Arc-Neko/node_modules/discord.js/src/managers/GuildMemberManager.js:240:36)
at eval (eval at <anonymous> (/home/kayuimineko/Arc-Neko/cmdhandler/eval.js:49:26), <anonymous>:1:23)
at /home/kayuimineko/Arc-Neko/cmdhandler/eval.js:49:26
at /home/kayuimineko/Arc-Neko/node_modules/mongoose/lib/model.js:4838:16
at /home/kayuimineko/Arc-Neko/node_modules/mongoose/lib/model.js:4838:16
at /home/kayuimineko/Arc-Neko/node_modules/mongoose/lib/helpers/promiseOrCallback.js:24:16
at /home/kayuimineko/Arc-Neko/node_modules/mongoose/lib/model.js:4861:21
at /home/kayuimineko/Arc-Neko/node_modules/mongoose/lib/query.js:4407:11
at /home/kayuimineko/Arc-Neko/node_modules/kareem/index.js:135:16
at processTicksAndRejections (internal/process/task_queues.js:79:11) {
[Symbol(code)]: 'BAN_RESOLVE_ID'
}
}
While running
message.guild.members.unban(client.users.fetch(config.admin.owner.id), "reason")
// Ignore the config part it's fine
Turns out, you should just unban the people by their IDs instead of their user property.
So, to unban the banned member use this code instead:
const Discord = require('discord.js');
const client = new Discord.Client();
const embed = new Discord.MessageEmbed()
.setColor('#39de33')
module.exports = {
name: 'unban',
description: "This unbans a user",
execute(message, args){
if (message.member.permissions.has("BAN_MEMBERS")){
if (!isNaN(args[0])) {
const bannedMember = message.guild.members.cache.get(args[0]) // Get the `member` property instead to recall later.
var reason = args.slice(1).join(" ");
if(!reason) {
reason = "No reason given!"
}
if (bannedMember) {
bannedMember
message.guild.members.unban(bannedMember.id, reason)
.then(() => {
embed.setDescription(`Successfully unbanned **${bannedMember.user.tag}**`); // `user` is undefined.
message.channel.send(embed);
})
.catch(err => {
embed.setDescription('I was unable to unban the member');
message.channel.send(embed);
console.error(err);
});
} else {
embed.setDescription("That user isn't in this guild!");
message.channel.send(embed);
}
} else {
embed.setDescription("You need to provide an user ID to unban");
message.channel.send(embed);
}
} else {
embed.setDescription("You do not have `BAN_MEMBERS` permissions to unban this member");
message.channel.send(embed);
}
}
}

Discord bot kick

I started building a Discord bot and the first function I made was kicking members. This is the code
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");
const client = new Discord.Client();
client.once("ready", () => {
console.log("Ready!");
});
client.on("message", (message) => {
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
}
});
client.login(token);
If someone without the kick and ban permission tries it nothing happens so this part is working. If an admin types eg. :kick #someone then someone will be kicked. But if an Admin types :kick (without someone's username) I get an error and the bot stops working until I restart it manually. This is the error:TypeError: Cannot read property 'kick' of undefined. What can I do to make this fully working?
You'll need to check if that user exists.
Try is like this:
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
if(!member) return message.channel.send('Cannot find this member');
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
}
And if you want to handle even more possible errors you'll need to use a try-catch block:
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
if(!member) return message.channel.send('Cannot find this member');
try {
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
} catch (error) {
console.log(error);
message.channel.send('An error has occured');
}
}
}
Check if the user mentioned another user before kicking the member:
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");
const client = new Discord.Client();
client.once("ready", () => {
console.log("Ready!");
});
client.on("message", (message) => {
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
if (!member)
return;
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
}
});
client.login(token);
You can't kick undefined.

Working on Discord bot kick + ban perms; it returns with error everytime

I am working on my ban and kick perms. I need to know how I would make it so that only this admin role can ban them. I want it to check with an if statement if they have the role, and if they do it would go along with the code, if not it would say: "You don't have permission to do this."
// ban
bot.on('message', message => {
let args = message.content.substring(config.prefix.length).split(" ");
switch (args[0]) {
case 'ban':
if (!args[1]) message.channel.send("No person included.")
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member.ban({ ression: 'I don\'t make the rules.' }).then(() => {
message.reply(`I just banned #${user.tag}.`)
})
} else {
message.reply("That user isn\`t in this server!");
}
}
break;
}
})
And my kick code:
bot.on('message', message => {
let args = message.content.substring(config.prefix.length).split(" ");
switch (args[0]) {
case 'kick':
if (!args[1]) message.channel.send("No person included.")
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member.kick('You were kicked.').then(() => {
message.reply(`Sucessfully kicked #${user.tag}.`);
}).catch(err => {
message.reply(`I can\'t kick the member. (perms?)`);
console.log(err);
});
} else {
message.reply("That user isn\`t in this server!");
}
}
break;
}
})
And my admin role numbers: 713787463331741726
You can check whether the author has a role by checking the role id.
For example:
if(!message.member.roles.cache.has('insert_ID_of_the_AdminRole')) return message.channel.send(`You can't use this command`)
Edit: (For v12 of discord.js)

Categories

Resources