A command that ban multiple people at once - discord

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);
})

Related

I keep getting an error in my !giverole command

When the owner of the server runs the command, it works but whenever any other admin/person with admin privileges uses it, the bot replies with "You do not have the required permissions"
Here is the code:
module.exports = {
commands: ['giverole', 'addrole', 'ar','gr'], // The command names/aliases
permissions: 'ADMINISTRATOR', //required permissions
requiredRoles: ['Admins'], // required roles
callback: (message, arguments) => {
const targetUser = message.mentions.users.first()
if (!targetUser) {
message.channel.send('Please specify someone to give a role to.')
return
}
arguments.shift()
const roleName = arguments.join(' ')
const { guild } = message
const role = guild.roles.cache.find((role) => {
return role.name === roleName
})
if (!role) {
message.channel.send(`There is no role with the name "${roleName}"`)
return
}
const member = guild.members.cache.get(targetUser.id)
member.roles.add(role)
message.channel.send(`That user now has the "${roleName}" role`)
},
}
Edit: Here is the command base since it was asked for by #Caladan
const validatePermissions = (permissions) => {
const validPermissions = [
'CREATE_INSTANT_INVITE',
'KICK_MEMBERS',
'BAN_MEMBERS',
'ADMINISTRATOR',
'MANAGE_CHANNELS',
'MANAGE_GUILD',
'ADD_REACTIONS',
'VIEW_AUDIT_LOG',
'PRIORITY_SPEAKER',
'STREAM',
'VIEW_CHANNEL',
'SEND_MESSAGES',
'SEND_TTS_MESSAGES',
'MANAGE_MESSAGES',
'EMBED_LINKS',
'ATTACH_FILES',
'READ_MESSAGE_HISTORY',
'MENTION_EVERYONE',
'USE_EXTERNAL_EMOJIS',
'VIEW_GUILD_INSIGHTS',
'CONNECT',
'SPEAK',
'MUTE_MEMBERS',
'DEAFEN_MEMBERS',
'MOVE_MEMBERS',
'USE_VAD',
'CHANGE_NICKNAME',
'MANAGE_NICKNAMES',
'MANAGE_ROLES',
'MANAGE_WEBHOOKS',
'MANAGE_EMOJIS',
]
for (const permission of permissions) {
if (!validPermissions.includes(permission)) {
throw new Error(`Unknown permission node "${permission}"`)
}
}
}
module.exports = (client, commandOptions) => {
let {
commands,
expectedArgs = '',
permissionError = 'You do not have permission to run this command.',
minArgs = 0,
maxArgs = null,
cooldown = -1,
requiredChannel = '',
permissions = [],
requiredRoles = [],
callback,
} = commandOptions
// Ensure the command and aliases are in an array
if (typeof commands === 'string') {
commands = [commands]
}
console.log(`Registering command "${commands[0]}"`)
// Ensure the permissions are in an array and are all valid
if (permissions.length) {
if (typeof permissions === 'string') {
permissions = [permissions]
}
validatePermissions(permissions)
}
Hope it helps in figuring out the issue.

DiscordAPIError: Cannot send an empty message (discord.js v13)

I am coding a bot with the below command and it throws an error, but i don't know where is the error
i tried my best
const Discord = require("discord.js");
const client = new Discord.Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR")) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if(!reason) reason = "No reason given."
if(!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if(!member) return message.channel.send("❌ You didn't mention a member!")
if(member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then (() => {
const embed = new Discord.MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
embed.setFooter(`Requested by ${message.author.username}`)
message.channel.send(embed)
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(error => {
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}
If I have made a mistake, please help me out
Sorry I don't speak English well
Try the below code out, I made notes along the way to explain as well as improved a small bit of code. I assume this is a collection of 2 separate files which is why they are separated. If they aren't 2 separate files, you do not need the top section, just the bottom.
const {
Client,
Intents,
MessageEmbed
} = require("discord.js");
const client = new Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
const {
MessageEmbed,
Permissions
} = require("discord.js");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has(Permissions.FLAGS.ADMINISTRATOR)) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if (!reason) reason = "No reason given."
if (!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if (!member) return message.channel.send("❌ You didn't mention a member!")
if (member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then(() => {
const embed = new MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
.setFooter({
text: `Requested by ${message.author.username}`
})
// author and footer are now structured like this
// .setAuthor({
// name: 'Some name',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// url: 'https://discord.js.org',
// })
// .setFooter({
// text: 'Some footer text here',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// })
message.channel.send({
embeds: [embed]
}) //embeds must be sent as an object and this was the actual line that was causing the error.
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(() => { // if error is not used, it is not required to be stated
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}

Discord.js v12 How to get total number on reactions from fetched embed

So i've been trying to count the reactions statistic after it was accepted or rejected, i'd try to find a solution but i can't here's my code
module.exports = {
name: 'accept-suggestion',
cooldown: 3,
description: 'Accept a sugegstion',
permissions: 'MANAGE_ROLES',
usage: '[suggestion id] [reason]',
async run(client, message, args, cmd, Discord){
message.delete()
const messageID = args[0];
const acceptMsg = args.slice(1).join(" ");
if(!messageID) return message.reply('Please specify a suggestion Id!').then(msg => {
msg.delete({ timeout: 3000 })
})
if(!acceptMsg) return message.reply('Please specify a reason!').then(msg => {
msg.delete({ timeout: 3000})
})
try {
const suggestionChannel = message.guild.channels.cache.get(
'SuggestionChannel_ID'
);
const moderator = message.author.tag
const suggestedEmbed = await suggestionChannel.messages.fetch(messageID);
console.log(suggestedEmbed)
const data = suggestedEmbed.embeds[0];
const dataStats = suggestedEmbed[0];
let upVote = dataStats.reactions.cache.get('✅').count;
let downVote = dataStats.reactions.cache.get('❌').count;
const acceptEmbed = new Discord.MessageEmbed()
.setTitle("Suggestion (Accepted)")
.setColor('#1dc44a')
.setAuthor(data.author.name, data.author.iconURL)
.setDescription(data.description)
.addFields(
{name: `Accepted by ${moderator}`, value: ` > ${acceptMsg}`},
{name: 'Statistic', value: `${upVote}\n${downVote}`}
)
.setFooter(`${data.author.name}'s suggestion`, data.author.iconURL)
suggestedEmbed.edit(acceptEmbed).then(msg => msg.reactions.removeAll())
const user = await client.users.cache.find(
(u) => u.tag === data.author.name
);
user.send("Your suggestion has been accepted!")
} catch(err) {
console.log(err)
}
}
}
you maybe wondering why i put .reactions after dataStats, i put it because i thought it would work by seeing the output off the suggestedEmbed(the output: https://pastebin.com/yEhDecur) i hope someone could fix this :)
Running the fetch() method with a id parameter only returns a single Message so accessing it like a array/collection won't work
const dataStats = suggestedEmbed[0];
this needs to change to
const dataStats = suggestedEmbed;
https://discord.js.org/#/docs/discord.js/stable/class/MessageManager?scrollTo=fetch

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
}

TypeError: Cannot read property '0' of undefined (discord.js)

const data = suggestedEmbed.embeds[0];
Hi, I'm having this error and I don't know why it is saying that the code above is the problem. Any solutions for this problem? Thank you for reading.
Code:
module.exports = {
category: "Utility",
description: "Accept valid suggestions!",
expectedArgs: "<messageID> <Reason>",
minArgs: 2,
guildOnly: true,
ownerOnly: true,
callback: ({message, args}) => {
const messageID = args[0]
const acceptQuery = args.slice(1).join(" ");
try{
const suggestionChannel = message.guild.channels.cache.get('834459599699443782');
const suggestedEmbed = suggestionChannel.messages.fetch(messageID);
console.log(suggestedEmbed)
const data = suggestedEmbed.embeds[0];
const acceptEmbed = new Discord.MessageEmbed()
.setAuthor(data.author.name, data.author.iconURL())
.setColor('GREEN')
.setDescription(data.description)
.addField("📊 Status ✅ Accepted! Expect this coming soon!", acceptQuery);
suggestedEmbed.edit(acceptEmbed);
const user = client.users.cache.find((u) => u.tag === data.author.name);
user.send("Your suggestion has been accepted! Thank you for this suggestion, expect this coming soon!")
} catch(err) {
console.log(err)
}
}
}

Resources