I made a ban command for my discord.js v12 bot. However whenever I run the command I get an error.
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);
}
}
This is the error I get whenever I run the command
DiscordAPIError: Invalid Form Body
DICT_TYPE_CONVERT: Only dictionaries may be used in a DictType
at RequestHandler.execute (/home/runner/SweatyBeautifulHelpfulWorker/node_modules/discord.js/src/rest/RequestHandler.js:170:25)
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
method: 'put',
path: '/guilds/751424392420130907/bans/155149108183695360',
code: 50035,
httpStatus: 400
}
I could'nt understand how to correct the problem in the code. I'm a bit new to coding. Can you please help me out!. Thanks in advance
This is pretty easy to solve, all you have to to is pass the right amount of Parameters in the right way to the .ban function.
.ban({ days: 7, reason: 'your reason here' })
https://discord.js.org/#/docs/main/stable/class/GuildMember?scrollTo=ban
This looks like code from my video. It is a very simple error I made in the code. The .ban part should actually look like this:
.ban({ reason: 'your reason here' })
-thesportstacker
Related
My discord bot's ban command isn't working and is currently giving me this error. My rols id is 853527575317708820
I don't know what I am doing wrong so please help me out
Here is the command :
Server is ready.
TigerShark Community#3557 Has logged in
(node:204) UnhandledPromiseRejectiontarning: DiscordAPTError: T
AEE RS
user_id: Value "<#!856413967595012127>" is not snowflake.
at RequestHandler.execute (/home/Tunner/TSC/node_modules/di
scoxd. js/src/rest/RequestHandler. js:154:13)
at processTicksAndRejections (internal/process/task
§5:97:5) :!
at async RequestHandler.push (/home/zunner/TSC/node
/discord. js/s1c/rest/RequestHandler. js:39:14)
Here is my code :
module.exports = {
name: 'ban',
description: "Used to ban members from a server",
async execute(client, message, args, Discord) {
if (!(message.member.roles.cache.some(r => r.id === "853527575317708820"))) return
let reason;
const user = await client.users.fetch(args[0])
if (!args[1])
{
reason = "Not specified"
} else {
reason = args[1]
}
const embed = new Discord.MessageEmbed()
.setTitle(`${user.username} was banned!`)
.setDescription(`${user.username} was banned by ${message.author.username} for: ${reason}`)
.setColor("#f0db4f")
.setFooter("Ban Command")
.setTimestamp()
message.channel.send(embed)
message.guild.members.ban(user)
}
}
Your command has few issues in it.
The first being that it does not allow banning users with command if the user is mentioned, it only allows banning by user ID. To fix that simply do:
const user = message.mentions.members.first() || await client.users.fetch(args[0])
You should also add check if the user is found, so right after you declare value for user
const user = message.mentions.members.first() || await client.users.fetch(args[0])
if(!user) return message.reply(`No user found`);
Now if you allow banning both mentions and user IDs there might be a different user value. So I recommend editing your embed aswell to something like:
const embed = new Discord.MessageEmbed()
.setTitle(`${user.user.username} was banned!`)
.setDescription(`${user.user.username} was banned by ${message.author.username} for: ${reason}`)
.setColor("#f0db4f")
.setFooter("Ban Command")
.setTimestamp()
This should fix majority of your issues, I recommend that if something is undefined in future or you come across any bugs in your code. Do some debugging by sending messages to console console.log(variable) or console.log("This works?")
if you are using discord.js v12 you can do what the other answer said and get the user by mention message.mentions.members.first() but if you are using v13 that wont work anymore
the reason its giving that error is because you need to fetch the user by their id alone, so you can do this client.users.fetch(args[0].replace('<#!', '').replace('>', '')) to remove the <#! and > (mention prefix) from it.
I made a Discord.js Ban Command with reason and stuff however i overcome an error whenever i try to use it. Here is my code :
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'ban',
description: 'Ban a user from the server by using mentioning them!',
guildOnly: true,
aliases: ['ban', 'banbanban'],
usage: `-ban <USER_MENTION> <OPTIONAL_REASON>`,
cooldown: 5,
async execute(message, args, client) {
const daidinevermantion = new MessageEmbed()
daidinevermantion.setTitle('Incorrect arguments provided!')
daidinevermantion.setDescription('Please Mention a user to ban ;-;. Make sure it a mention. The bot may not be able to ban users not in the server')
daidinevermantion.addField('Usage','``;ban <USER_MENTION> <OPTIONAL REASON>``')
daidinevermantion.addField('Example Usage', ';ban <#760773438775492610> Good Bot')
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(daidinevermantion);
if(!member) return message.channel.send('Can\'t seem to find this user. Sorry \'bout that :/. Make sure you are mentioning the user and the user is in the server!');
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({ days: 7, reason: 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('Banned by', message.author)
.addField('Reason', reason)
.setFooter('Banned On:', client.user.displayAvatarURL())
.setTimestamp()
message.channel.send(banembed);
}
}
Here whenever i send this command I this message in return "This user can't be banned. It is either because they are a mod/admin, or their highest role is higher than mine" regardless of whatever the case is whether its position is higher or lower. I'm a bit new to Discord.js please help me out thanks a lot!
You are getting that message because member.bannable is always false, and the reason for that is your bot doesn't have the required permissions to ban a user. Use this permission calculator and reinvite the bot to the server with required permissions i.e "Ban Members" or "Administrator".
I'm working on my ban command and it's fully functional, but I was wondering, how I would log the ban reason into the ban section of discord (example in the attachment)? My code looks like this:
const { DiscordAPIError } = require("discord.js");
const Discord = require('discord.js');
module.exports = {
name: 'ban',
description: "Mentioned user will be banned",
execute(message, args){
if (!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send("Invalid Permissions")
let User = message.guild.member(message.mentions.members.first()) || message.guild.members.cache.get(args[0])
if (!User) return message.channel.send("Invalid User")
if (User.hasPermission("BAN_MEMBERS")) return message.reply("Invalid Permissions a")
let banReason = args.join(" ").slice(22);
if (!banReason) {
banReason = "None"
}
console.log(`USER = ${User}`)
User.ban
console.log(`Ban reason = ${banReason}`)
var UserID = User.id
console.log(`USER ID = ${UserID}`)
}
}
Any help? Thanks :)
It's actually quite easy, just add ({reason: banReason}) after the User.ban part, making it:
User.ban({reason: banReason})
That should log it there properly :)
You can use the reason property of the options parameter in the GuildMember.ban() method:
User.ban({ reason: 'real life danger' })
.then(member => console.log(`${member.name} was banned.`))
.catch(console.error)
Also, in your code, there's no reason for using the Guild.member() method when defining User. Guild.member(user) is used to turn a User object into a GuildMember object.
However, MessageMentions.members.first() already returns a GuildMember object, making it obsolete.
Yesterday I could run this scrip.
Today I get the error
(node:29568) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'kickable' of undefined
I'm running version "discord.js": 12.1.1 - I hope someone can spot what I'm doing wrong here... because it's drive me nuts.
Bellow you can find my kickuser.js - script
+ my index.js script -> https://pastebin.com/7tLkuU5p
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if (message.member.hasPermission("KICK_MEMBERS")) {
if (!message.mentions.users) return message.reply('You must tag 1 user.');
else {
const channel = message.guild.channels.cache.get(696692048543088691);
const member = message.mentions.members.first();
let reason = message.content.split(" ").slice(2).join(' ');
if (member.kickable == false) return message.channel.send("That user cannot be kicked!")
else {
if (!reason) reason = (`No reason provided.`);
await member.send(`You have been kicked from **${message.guild.name}** with the reason: **${reason}**`)
.catch(err => message.channel.send(`⚠ Unable to contact **${member}**.`));
await member.kick(reason);
const kickEmbed = new MessageEmbed()
.setAuthor(member.user.tag, member.user())
.setThumbnail(member.user.avatarURL())
.setColor("#ee0000")
.setTimestamp()
.addField("Kicked By", message.author.tag)
.addField("Reason", reason);
await channel.send(kickEmbed);
console.log(`${message.author.tag} kicked ${member.user.tag} from '${message.guild.name}' with the reason: '${reason}'.`);
}
}
} else {
message.channel.send("You do not have permission to use kick.");
return;
}
}
module.exports.help = {
name: "kickuser"
}
I hope someone can help me.
Thanks in advance.
message.mentions.users always evaluates to true because it is an object, and to check if the message has any mentions, you can do:
if(!message.mentions.members.first()) return message.reply('You must tag 1 user.');
instead of:
if(!message.mentions.users) ...
I am trying to make a Discord bot and I want to make a !nick command and I keep getting the same error, could someone help me:
ERROR:
{ DiscordAPIError: Missing Permissions
at item.request.gen.end (/rbd/pnpm-volume/76d7cd6d-9602-4908-bb55-ccc4f8de8537/node_modules/.registry.npmjs.org/discord.js/11.4.2/node_modules/discord.js/src/client/rest/RequestHandlers/Sequential.js:79:15)
at then (/rbd/pnpm-volume/76d7cd6d-9602-4908-bb55-ccc4f8de8537/node_modules/.registry.npmjs.org/snekfetch/3.6.4/node_modules/snekfetch/src/index.js:215:21)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:189:7)
name: 'DiscordAPIError',
message: 'Missing Permissions',
path: '/api/v7/guilds/485921672013283339/members/469227202345697280',
code: 50013,
method: 'PATCH' }
CODE:
const Discord = require("discord.js");
exports.run = (client, message, args, member) => {
const arg = args.join(" ")
if (arg === null || arg === "" || arg === undefined || arg == " ") {
var embed = new Discord.RichEmbed()
embed.setColor(0x00AE86);
embed.addField("USAGE", "!nick (nickname)", false);
message.channel.send(embed);
}
else {
var embed = new Discord.RichEmbed()
embed.setColor(0x00AE86);
embed.addField("NICKNAME", "You have set your nickname to **" + arg + "**", false);
message.channel.send(embed);
message.member.setNickname("["+ member.highestRole.name + "]" + member.displayName)
.then(console.log)
.catch(console.error);
}
}
Does anyone know why I am getting this error, if so please tell me HOW to fix it. Thank you!
From message: 'Missing Permissions' we can conclude that your bot is missing the required permissions.
To fix the issue go to your Discord Developer Portal and get the PERMISSIONS INTEGER that contains the permissions you need. The most common is 8, which is the integer for Administrator permissions.
If that doesn't work, ensure that your bot's role is above others in your Discord Server
as shown here