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".
Related
I am making a discord bot and I have a few dev only commands. However, the system I use to detect if someone is a bot developer doesn't work.
My code:
const { MessageEmbed } = require("discord.js");
exports.execute = async (client, message, args) => {
if (!client.config.admins.includes(message.author.id)) return message.channel.send("Slow down, poke. This is devs only, poke?"); // return if author isn't bot owner
let user = message.mentions.users.first();
if (!user) return message.channel.send("Send money to who?");
let amount = args[1];
if (!amount || isNaN(amount)) return message.reply("That isn't a valid amount.");
let data = client.eco.addMoney(user.id, parseInt(amount));
const embed = new MessageEmbed()
.setTitle(`You'll be rich! The money has been added.`)
.addField(`User`, `<#${data.user}>`)
.addField(`Balance Given`, `${data.amount} 💸`)
.addField(`Total Amount`, data.after)
.setColor("#f54242")
.setThumbnail(user.displayAvatarURL)
.setTimestamp();
return message.channel.send(embed);
}
exports.help = {
name: "addmoney",
aliases: ["addbal"],
usage: `addmoney #user <amount>`
}
I shouldn't have received the devs only message, but when I tested in discord, I did.
Thought I'd just make this an answer than a comment, as I've had time to test.
This works, but it may be related to how you store your IDs in the admin array.
.includes() is type sensitive, so a string wont match a number. Discord IDs are a string, so your array has to match it.
Example:
const admins = [96876194712018944];
console.log(admins.includes("96876194712018944")); // false
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.
module.exports = {
name: 'ban',
description: "This command bans a member!",
execute(message, args){
const member = message.mentions.users.first();
if(member){
const memberTarget = message.guild.members.cache.get(member.id)
memberTarget.ban();
message.channel.send("User has been banned");
}else{
message.channel.send('you couldnt ban that member');
}
}
}
module.exports = {
name: 'kick',
description: "This command kicks a member!",
execute(message, args){
const member = message.mentions.users.first();
if(member){
const memberTarget = message.guild.members.cache.get(member.id)
memberTarget.kick();
message.channel.send("User has been kicked");
}else{
message.channel.send('you couldnt kick that member');
}
}
}
We could simply check for a user's permission using the .hasPermission() function of the GuildMember object. We could simply integrate it with a simple if statement, that would include the permissions you want to check for:
if (!message.member.hasPermission('BAN_MEMBERS') return; // Would return if the message author does not have permission to Ban Members
if (!message.member.hasPermission('KICK_MEMBERS') return; // Same thing for the Kick Members permission.
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
I am trying to make it so when my bot is added to another server, it will send an embed saying how many servers it's in now and the guild name and also the guild owner. I am also trying to make another embed so it tells me when it leaves a server and tells me when it joined the server first and then when it was removed and the guild name and guild owner. I use discord.js. Could someone help, please? This is my current script:
bot.on("guildCreate", guild => {
const joinserverembed = new Discord.MessageEmbed()
.setTitle("Joined a server!")
.addField("Guild name:", `${guild.name}`)
.addField("Time of join:", `${Discord.Guild.createdTimestamp()}`)
.setColor("GREEN")
.setThumbnail(guild.displayAvatarURL())
if (guilds.channel.id = 740121026683207760) {
channel.send(joinserverembed)
}
guild.channel.send("Thank you for inviting Ultra Bot Premium! Please use up!introduction and up!help for the new perks and more!")
})
bot.on("guildDelete", guild => {
const leftserverembed = new Discord.MessageEmbed()
.setTitle("Left a server!")
.addField("Guild name:", `${guild.name}`)
.addField("Time of removal:", `${createdTimestamp()}`)
.setColor("RED")
.setThumbnail(guild.displayAvatarURL())
if (guilds.channel.id = 740121026683207760) {
channel.send(leftserverembed)
}
})
I have resolved your first issue for you in the code below.
You were doing guild.channel.send(), in this case, guild represents a Discord.Guild however you're using it like it represents an instance of Message, which it does not.
You can use guild.channels.cache.find(x => x.name == 'general').send("Thanks for inviting me to this server¬!") will send a message to a channel named general in that server.
bot.on("guildCreate", (guild) => {
const joinserverembed = new Discord.MessageEmbed()
.setTitle("Joined a server!")
.addField("Guild name:", guild.name)
.addField("Time of join:", Date.now())
.setColor("GREEN")
.setThumbnail(guild.iconURL({ dynamic: true }));
bot.channels.cache.get("740121026683207760").send(joinserverembed);
guild.channels.cache
.filter((c) => c.type === "text")
.random()
.send(
"Thank you for inviting Ultra Bot Premium! Please use up!introduction and up!help for the new perks and more!"
);
});
I filter the channels in the guild, ensuring that they are not categories or voice channels, then send the welcome message to a random one.
As for your second query, you need to use a database, store the Date.now timestamp of when it was added, then once the bot has left the guild it must get the value and display its time. I haven't done this for you, but I have fixed your code:
bot.on("guildDelete", (guild) => {
const leftserverembed = new Discord.MessageEmbed()
.setTitle("Left a server!")
.addField("Guild name:", guild.name)
.addField("Time of removal:", Date.now())
.setColor("RED")
.setThumbnail(guild.iconURL({ dynamic: true }));
bot.channels.cache.get("740121026683207760").send(leftserverembed);
});