Discord.js v13 Slash Command Ban Command not working - discord.js

It does not ban the person I mention.
My code:
const Discord = require('discord.js')
const fs = require('fs');
//Ban.js
module.exports = {
name: "ban",
description: "This command ban's someone",
category: "moderation",
example: ["!ban #member"],
callback: async ({ message, args }) => {
try {
const member = message.mentions.members.first();
const permission = message.member.permissions.has(Discord.Permissions.FLAGS.BAN_MEMBERS)
if (!permission)
return message.reply({
contents: ":failed:1050462335556386846> | You don't have permission to use this command"
});
if (!args[0]) return message.reply({ content: `:failed:1050462335556386846> | Please specify someone` });
if (!member) return message.reply({ content: `πŸ’€ | Cannot find that member...` } );
if (member.id === message.author.id)
return message.reply({ content: `:failed:1050462335556386846> | You cannot ban yourself!` });
if (message.member.roles.highest.position < member.roles.highest.position)
return message.reply({
content: `:failed:1050462335556386846> | You cannot ban user who have higher role than you...`
});
if (!member.bannable) return message.reply({ content: `:failed:1050462335556386846> | I cannot ban that member `});
return (
(await member.ban()) +
message
.reply({
content: `:anger: | User ${member} has been banned`
})
.then((msg) => {
setTimeout(() => msg.delete(), 5000);
})
);
} catch(err) {
message.reply({ content: `:failed:1050462335556386846> There was an ${err}` })
}
}, };

Instead of using command.execute(message, args) to execute your command, you should use command.callback({ message, args }). This is why it does not work, your core function is not executed.

Related

How to send Server Region in Embed Discord JS v13?

I have a Server Info command which worked in v12 but I updated to v13. In v12 when I send the Command it Responds with the correct region but in v13 when I send the command, responds at server region with undefined, help!
This is server info command:
const Discord = require('discord.js');
module.exports = {
name: "serverinfo",
aliases: ["si"],
description: "Shows all Info about the Server!",
execute: async (message, args, client) => {
let region;
switch (message.guild.region) {
case "europe":
region = 'πŸ‡ͺπŸ‡Ί europe';
break;
case "russia":
region = 'πŸ‡·πŸ‡Ί russia';
break;
case "us-east":
region = 'πŸ‡ΊπŸ‡Έ us-east'
break;
case "us-west":
region = 'πŸ‡ΊπŸ‡Έ us-west';
break;
case "us-south":
region = 'πŸ‡ΊπŸ‡Έ us-south'
break;
case "us-central":
region = 'πŸ‡ΊπŸ‡Έ us-central'
break;
}
const embed = new Discord.MessageEmbed()
.setThumbnail(message.guild.iconURL({dynamic : true}))
.setColor('#dd6fb9')
.setTitle(`**Bot Command**`)
.setFooter("#" + message.author.tag, message.author.displayAvatarURL({dynamic : true}))
.addFields(
{
name: `Region: `,
value: `${region}`,
inline: true
}
await message.channel.send( { embeds: [embed] }).then(setTimeout(() => message.delete())).then(msg =>{
setTimeout(() => msg.delete(), 120000)});
},
};
A guild no longer has the attribute region. You can however get the preferredLocale of the server:
const Discord = require('discord.js');
module.exports = {
name: "serverinfo",
aliases: ["si"],
description: "Shows all Info about the Server!",
execute: async (message, args, client) => {
const embed = new Discord.MessageEmbed()
.setThumbnail(message.guild.iconURL({dynamic : true}))
.setColor('#dd6fb9')
.setTitle(`**Bot Command**`)
.setFooter("#" + message.author.tag, message.author.displayAvatarURL({dynamic : true}))
.addFields(
{
name: `Region: `,
value: `${message.guild.preferredLocale}`,
inline: true
}
await message.channel.send( { embeds: [embed] }).then(setTimeout(() => message.delete())).then(msg =>{
setTimeout(() => msg.delete(), 120000)});
},
};

Discord.js V13 Adding role when using a slash command

I am trying to code a bot that when you use a certain slash command, it gives you a role. I have looked for a solution but haven't been able to find one. Nothing is seeming to work for me, i keep getting errors about the code, like "message not found, did you mean Message"
This is my first time trying to code a bot so if its a dumb issue, please bear with me.
Here is my code:
import DiscordJS, { Intents, Message, Role } from 'discord.js'
import dotenv from 'dotenv'
dotenv.config()
const client = new DiscordJS.Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
],
})
// Slash Commands
//ping pong command
client.on('ready', () => {
console.log('BOT ONLINE')
//bot test server
const guildId = '868857440089804870'
const guild = client.guilds.cache.get(guildId)
const role = client.guilds.cache.find(r => r.name == "Test Role to
give")
let commands
if (guild) {
commands = guild.commands
} else {
commands = client.application?.commands
}
commands?.create({
name: 'ping',
description: 'says pong'
})
commands?.create({
name: "serverip",
description: 'Gives user the server IP'
})
commands?.create({
name: "giverole",
description: 'Gives user the role'
})
})
client.on('interactionCreate', async (interaction) => {
if(!interaction.isCommand()) {
return
}
const { commandName, options } = interaction
//This is the role id that i want to give
const role = '884231659552116776'
//these are the users that i want to give the role to
const sniper = '725867136232456302'
const josh = '311981346161426433'
if (commandName === 'ping') {
interaction.reply({
content: 'pong',
ephemeral: true,
})
} else if (commandName === 'serverip') {
interaction.reply({
content: 'thisisserverip.lol',
ephemeral: true,
})
} else if (commandName === 'giverole') {
interaction.reply({
content: 'Role given',
ephemeral: true,
})
}
})
client.login(process.env.test)
You can just simply retrieve the Interaction#Member and add the role to them using GuildMemberRoleManager#add method!
const role = client.guilds.cache.find(r => r.name == "Test Role to
give");
await interaction.member.roles.add(role); // and you're all set! welcome to stackoverflow πŸ˜„
if (commandName === 'giverole') {
const role = client.guilds.cache.find(r => r.name == "Ahmed1Dev")
await user.roles.add(role)
message.channel.send("Done Added Role For You") // Fixed By Ahmed1Dev
}

I want users not to be able to hand out higher privileges than they have themselves

A moderator who has manage_roles permissions can even give the owner role to anyone. Is there a way that it can give out no higher role than to his own role?
So if he is admin, he can give at most admin, so not everyone can give random roles to anyone.
const { MessageEmbed } = require('discord.js');
const config = require('../../configs/config.json');
module.exports = {
config: {
name: "give-roles",
},
run: async (client, message, args) => {
message.delete();
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send({
embed: {
title: `You dont have permission to use this command`
}
})
if (!args[0] || !args[1]) return message.channel.send({
embed: {
title: "Incorrect usage, It's `<username || user id> <role name || id>"
}
})
try {
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
const roleName = message.guild.roles.cache.find(r => (r.name === args[1].toString()) || (r.id === args[1].toString().replace(/[^\w\s]/gi, '')));
const alreadyHasRole = member._roles.includes(roleName.id);
if (alreadyHasRole) return message.channel.send({
embed: {
title: "User already has the role defined"
}
})
const embed = new MessageEmbed()
.setTitle(`Role Name: ${roleName.name}`)
.setDescription(`${message.author} has successfully given the role ${roleName} to ${member.user}`)
.setColor('f3f3f3')
.setThumbnail(member.user.displayAvatarURL({ dynamic: true }))
.setFooter(new Date().toLocaleString())
return member.roles.add(roleName).then(() => message.channel.send(embed));
} catch (e) {
return message.channel.send({
embed: {
title: "Try to give a role that exists next time"
}
})
}
}
}
You're able to use roles.highest.position:
let taggedMember = ... //(guildMember)
if (message.member.roles.highest.position < taggedMember.roles.highest.position) {
//code...
}
Docs: https://discord.js.org/#/docs/main/stable/class/RoleManager?scrollTo=highest

A command that ban multiple people at once

I'm trying to make a command that ban mutliple people at once, using their ID. Here is my code :
const { MessageEmbed } = require("discord.js");
const { MESSAGES } = require("../../util/constants");
module.exports.run = (client, message, args) => {
args.forEach(async id => {
const users = await client.users.fetch(id);
message.guild.member(users).ban;
console.log(users);
})
};
And here is my console output :
User {
id: '409046637948829697',
bot: false,
username: 'NYRIANYRIANYRIA',
discriminator: '4198',
avatar: 'b7f3aed6450d28bbf5b4b1b24809edcb',
flags: UserFlags { bitfield: 64 },
lastMessageID: null,
lastMessageChannelID: null
}
There's no error and nothing append when I run the command. Thanks for your help :)
.ban is a function: GuildMember.ban()
args.forEach(async id => {
const user = await client.users.fetch(id);
const member = message.guild.member(user);
if (member.bannable) member.ban();
else message.channel.send("Cannot ban " + id);
})

Discord.js | Cannot read property 'displayName' of undefined

I am making a discord bot for a friend and everything worked until i tried to make an unban command. when i tried to unban someone it did not work. then i looked at the error. it displayed:
TypeError: Cannot read property 'displayName' of undefined
at C:\Users\user\folder_name\commands\unban.js:37:67
at processTicksAndRejections (internal/process/task_queues.js:97:5)
Unhandled promise rejection: TypeError: Cannot read property 'displayName' of undefined
at C:\Users\user\folder_name\commands\unban.js:37:67
at processTicksAndRejections (internal/process/task_queues.js:97:5)
this is my code
const Discord = require('discord.js');
module.exports = {
name: 'unban',
description: 'unban user',
aliases: [],
cooldown: 0,
args: true,
usage: '<mention> [reason]',
guildOnly: true,
execute(message, args, client) {
console.log(message.content);
const embedMsg = new Discord.RichEmbed()
.setColor('#0000ff')
.setAuthor(message.author.username, message.author.displayAvatarURL)
.setThumbnail(message.author.displayAvatarURL)
.setTimestamp()
.setFooter('botname', client.user.displayAvatarURL);
let member = message.mentions.members.first();
if (!message.member.hasPermission('BAN_MEMBERS')) {
embedMsg.setDescription(`You don't have permission to unban!`);
return message.channel.send(embedMsg);
}
if (!args.length >= 1) {
embedMsg.setDescription('^unban takes at least one argument! the proper usage is ^unban <mention> [reason]');
message.channel.send(embedMsg);
}
if (args.length < 2) {
message.guild.unban(member).then(() => {
embedMsg.setDescription(`${member.displayName} has been succesfully unbanned`);
return message.channel.send(embedMsg);
}).catch((err) => {
embedMsg.setDescription(`Could not unban ${member.displayName}`);
console.log(err);
return message.channel.send(embedMsg);
});
return;
}
newargs = "";
for (var i = 1; i < args.length; i++) {
newargs += (args[i] + " ");
}
message.guild.unban(member).then(() => {
embedMsg.setDescription(`${member.displayName} has been succesfully unbanned for reason ${newargs}`);
return message.channel.send(embedMsg);
}).catch((err) => {
embedMsg.setDescription(`Could not unban ${member.displayName}`);
console.log(err);
return message.channel.send(embedMsg);
});
return;
}
}
does anyone know what i am doing wrong?
It says in the discord.js's official docs that the unban method returns a member object https://discord.js.org/#/docs/main/stable/class/Guild?scrollTo=unban
The reason why it says 'undefined' is because the member object you are trying to access is not in the server/guild. So, therefore you need add a reference to the member object that the method returns:
message.guild.unban('some user ID').then((member) => {
embedMsg.setDescription(`${member.username} has been succesfully unbanned for reason ${newargs}`);
return message.channel.send(embedMsg);
}
Unbun method return a user promise, so user dont have property displayName, you need use .username
And you can use user.id for unban, so right way will be let member = message.mentions.members.first() || args[0]
This check doing wrong, because its not stop code execute
if (!args.length < 2) {
embedMsg.setDescription('^unban takes at least one argument! the proper usage is ^unban <mention> [reason]');
return message.channel.send(embedMsg);
}
Amm and whats this part code doing? Why its duplicate?
if (args.length < 2) {
message.guild.unban(member)
.then(() => {
embedMsg.setDescription(`${member.username} has been succesfully unbanned`);
return message.channel.send(embedMsg);
})
.catch((err) => {
embedMsg.setDescription(`Could not unban ${member.username}`);
console.log(err);
return message.channel.send(embedMsg);
});
return;
}
The edited code
const Discord = require('discord.js');
module.exports = {
name: 'unban',
description: 'unban user',
aliases: [],
cooldown: 0,
args: true,
usage: '<mention> [reason]',
guildOnly: true,
execute(message, args, client) {
const embedMsg = new Discord.RichEmbed()
.setColor('#0000ff')
.setAuthor(message.author.username, message.author.displayAvatarURL)
.setThumbnail(message.author.displayAvatarURL)
.setTimestamp()
.setFooter('botname', client.user.displayAvatarURL);
let member = message.mentions.members.first() || args[0]
if (!message.member.hasPermission('BAN_MEMBERS')) {
embedMsg.setDescription(`You don't have permission to unban!`);
return message.channel.send(embedMsg);
}
if (!args.length < 2) {
embedMsg.setDescription('^unban takes at least one argument! the proper usage is ^unban <mention> [reason]');
return message.channel.send(embedMsg);
}
let newargs = args.splice(1,args.length).join(' ')
message.guild.unban(member)
.then(() => {
embedMsg.setDescription(`${member.username} has been succesfully unbanned for reason ${newargs}`);
return message.channel.send(embedMsg);
})
.catch((err) => {
embedMsg.setDescription(`Could not unban ${member.username}`);
console.log(err);
return message.channel.send(embedMsg);
});
}
}

Resources