Discord.js mod bot ban command not working - javascript

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.

Related

How do I get the user of a mentioned user in an option? discord.js v13

I have a bot that's trying to kick a mentioned user in the slash command but when I mention a user in the "user" option it says User not found and gives an error of x is not a valid function (x is whatever I'm trying). I'm trying to find a valid function to actually define the user mentioned but can't seem to find one. Any help is appreciated since I am new to javascript and discord.js
const { SlashCommandBuilder, OptionType } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('tkick')
.setDescription('Kicks the specified user by tag (Moderation)')
.addMentionableOption((option) =>
option
.setName('user')
.setDescription('The user to be kicked')
.setRequired(true),
),
async execute(interaction, client) {
if (!interaction.member.permissions.has(['KICK_MEMBERS']))
return interaction.reply(
'You do not have permission to use this command.',
);
// Get the user from the interaction options
const user = interaction.user;
if (!user) return interaction.reply('User not found.');
// Kick the user
await interaction.option.('user').kick(); // This is where I am having the issue
// Reply with the text
await interaction.reply({
content: 'User has been kicked.',
});
},
};
I tried looking at different questions I looked up but it's either in an older version where it isn't there or got removed. Discord.js v13 got released in December 2022 but I can only find posts before that.
interaction.option.('user').kick() is not a valid syntax and interaction.user is not a GuildMember, but a User object. To be able to kick someone, you need a GuildMember object which can be obtained by using the interaction.options.getMentionable method if you use addMentionableOption.
However, it accepts roles and users. If you don't want your bot to accept mentions of roles, which would make your life a bit more difficult, it's better to use the addUserOption instead of addMentionableOption. With addUserOption, you can get the GuildMember object by using the interaction.options.getMember method:
module.exports = {
data: new SlashCommandBuilder()
.setName('tkick')
.setDescription('Kicks the specified user by tag (Moderation)')
. addUserOption((option) =>
option
.setName('user')
.setDescription('The user to be kicked')
.setRequired(true),
),
async execute(interaction) {
if (!interaction.member.permissions.has(['KICK_MEMBERS']))
return interaction.reply(
'You do not have permission to use this command.',
);
try {
await interaction.options.getMember('user').kick();
interaction.reply('User has been kicked.');
} catch (err) {
console.error(error);
interaction.reply('⚠️ There was an error kicking the member');
}
},
};

Getting "Missing Access" error in console

I'm working on an add role command in discord.js v13 and this is the error I am getting:
Error
const { MessageEmbed } = require("discord.js");
const Discord = require("discord.js")
const config = require("../../botconfig/config.json");
const ee = require("../../botconfig/embed.json");
const settings = require("../../botconfig/settings.json");
module.exports = {
name: "addrole",
category: "Utility",
permissions: ["MANAGE_ROLES"],
aliases: ["stl"],
cooldown: 5,
usage: "addrole <user> <role>",
description: "Add a role to a member",
run: async (client, message, args, plusArgs, cmdUser, text, prefix) => {
/**
* #param {Message} message
*/
if (!message.member.permissions.has("MANAGE_ROLES")) return message.channel.send("<a:mark_rejected:975425274487398480> **You are not allowed to use this command. You need `Manage Roles` permission to use the command.**")
const target = message.mentions.members.first();
if (!target) return message.channel.send(`<a:mark_rejected:975425274487398480> No member specified`);
const role = message.mentions.roles.first();
if (!role) return message.channel.send(`<a:mark_rejected:975425274487398480> No role specified`);
await target.roles.add(role)
message.channel.send(`<a:mark_accept:975425276521644102> ${target.user.username} has obtined a role`).catch(err => {
message.channel.send(`<a:mark_rejected:975425274487398480> I do not have access to this role`)
})
}
}
What your error means is that your bot doesn't have permissions to give a role to a user. It might be trying to add a role which has a higher position than the bot's own role. One way to stop the error is to give the bot the highest position. The bot will also require the MANAGE_ROLES permission in the Discord Developers page to successfully add roles in the first place. If you want to learn more about role permissions, I suggest you go here => Roles and Permissions. Also, when you are using .catch() at the end, all it is checking for is if the message.channel.send() at the end worked and if not, then send a message to channel telling that the bot was not able to add the role. Instead you need to use .then() after adding the role and then use .catch() to catch the error. Then, your code might look like this:
target.roles.add(role).then(member => {
message.channel.send(`<a:mark_accept:975425276521644102> ${target.user.username} has obtined a role`)
}).catch(err => {
message.channel.send(`<a:mark_rejected:975425274487398480> I do not have access to this role`)
})

invite Created event

so I'm making a Discord Bot, with auto logging capabilities, until now I managed due to do most of the code, these include the command for setting a mod-log channel and the event code, here's the code for the command:
let db = require(`quick.db`)
module.exports = {
name: "modlog",
aliases: ["modlogs", "log", "logs"],
description: "Change the modlogs channel of the current server",
permission: "MANAGE_CHANNELS",
usage: "modlog #[channel_name]",
run: async (client, message, args) => {
if(!message.member.hasPermission(`MANAGE_CHANNELS`)) {
return message.channel.send(`:x: You do not have permission to use this command!`)
} else {
let channel = message.mentions.channels.first();
if(!channel) return message.channel.send(`:x: Please specify a channel to make it as the modlogs!`)
await db.set(`modlog_${message.guild.id}`, channel)
message.channel.send(`Set **${channel}** as the server's modlog channel!`)
}
}
}
And the inviteCreate event:
client.on("inviteCreate", async invite => {
const log = client.channels.cache.get(`${`modlog_${message.guild.id}`}`)
let inviteCreated = new Discord.MessageEmbed()
log.send(`An invite has been created on this server!`)
})
The issue is that since the inviteCreate event only accepts one parameter (I think that's what they are called) which is invite, there is no message parameter, so message becomes undefined, does anyone have a solution?
Thanks!
You don't need message in this case. See the documentation of invite.
Your message.member can be replaced with invite.inviter
Your message.channel can be replaced with invite.channel
Your message.guild can be replaced with invite.guild
Invites also have a guild property, that's the guild the invite is for, so you can use that instead of the message.guild:
client.on('inviteCreate', async (invite) => {
const log = client.channels.cache.get(`${`modlog_${invite.guild.id}`}`);
let inviteCreated = new Discord.MessageEmbed();
log.send(`An invite has been created on this server!`);
});

Discord.js Ban Command with Command Handler

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".

Discord.js v12 Ban Command

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

Categories

Resources