Can you mass kick people from a server using discord.js - node.js

So I want to have a moderation bot that kicks all members with a certain role e.g. "unverified" from the server.
1, is this possible?
2, is this allowed, or would it possibly be a Discord API Breach?
I have a normal kick/ ban command and despite searching the web for ages I can't find any answers. Any help would be hugely appreciated. Thanks in advance.

Yes it is possible, you would just have to be able to group them somehow, (say the role you mentioned for instance) and then run a forEach() on it and kick.
Is it allowed, yes.
Is it a breach: unclear depends on how many you are kicking but these commands will only kick in small groups (5 per 5 seconds).
Example below:
regular command:
(prefix)purge RoleName Reason
const { Discord, Permissions } = require('discord.js')
module.exports.run = async (client, message, args) => {
if (!message.member.Permissions.has("ADMINISTRATOR")) {
//handle however if they are not admin
} else {
let kicked = []
const role = message.guild.roles.cache.find(r => r.name === args[0])
args.shift()
const kickReason = args.join(' ') || 'No Reason'
message.guild.members.forEach(member => {
if (member.roles.has(role)) {
kicked.push(member)
member.kick({
reason: kickReason
})
}
})
const completeEmbed = new Discord.MessageEmbed()
.setTitle('Purge')
.setDescription(`Members with the following role have been purged "${role.name}".`)
.addField({
name: `The members kicked were:`,
value: `${kicked.join('\n')}`
})
message.channel.send({
embeds: [completeEmbed],
ephemeral: true
})
}
}
module.exports.help = {
name: "purge",
description: "Kick members with a certain role",
usage: "(prefix)purge [RoleName] [Reason]"
}
And as a slash command (interaction): and can be built differently if needed.
/purge role: Rolename reason: reason
const { Discord, Permissions, SlashCommandBuilder } = require('discord.js')
module.exports = {
data: new SlashCommandBuilder()
.setName('purge')
.setDescription('Purge server of role')
.addRoleOption(option =>
option
.setName('role')
.setDescription('Which role to purge')
.setRequired(true))
.addStringOption(option =>
option
.setName('reason')
.setDescription('Reason for purge.')
.setRequired(true)),
async execute(client, interaction) {
const reason4Kick = interaction.options.getString('reason')
const role2Kick = interaction.options.getRole('role')
if (!interaction.member.Permission.has('ADMINISTRATOR')) {
// handle if user doesn't have permission to run
return
} else {
let kicked = []
interaction.guild.members.forEach(member => {
if (member.roles.has(role2Kick)) {
kicked.push(member)
member.kick({
reason: reason4Kick
})
}
})
const completeEmbed = new Discord.MessageEmbed()
.setTitle('Purge')
.setDescription(`Members with the following role have been purged "${role.name}".`)
.addField({
name: `The members kicked were:`,
value: `${kicked.join('\n')}`
})
interaction.channel.reply({
embeds: [completeEmbed],
ephemeral: true
})
}
}
}

Related

How can I set a button as disabled after the 15s has passed without any interaction?? Discord v14

const config = require('../../botconfig');
module.exports = {
name: 'invite',
description: 'Crimson and Server invites',
run: async (client, interaction, args) => {
try {
const inviteEmbed = new EmbedBuilder()
.setDescription('**__Invite • Support__**\n\n<a:Arrow:735141069033046106> Want to invite Crimson to your server? Feel free to click on the **"Invite"** button.\n\n<a:Arrow:735141069033046106> Need additional help with Crimson? Come join us in our humble abode by clicking on the **"Support"** button.')
.setColor('#EE1C25')
.setFooter({ text: `Command Requested by: ${interaction.user.tag}`, iconURL: interaction.user.displayAvatarURL() })
.setTimestamp()
.setThumbnail(client.user.displayAvatarURL());
let botInvite = new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setURL(`https://discord.com/`)
.setLabel('Invite');
let support = new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setURL('https://discord.gg/')
.setLabel('Support');
let del = new ButtonBuilder()
.setLabel(`Close`)
.setCustomId(`delete`)
.setEmoji(`❌`)
.setStyle(ButtonStyle.Danger);
const inviteMsg = await interaction.reply({ embeds: [inviteEmbed], components: [new ActionRowBuilder().addComponents(botInvite, support, del)], fetchReply: true });
const collector = inviteMsg.createMessageComponentCollector({ componentType: ComponentType.Button, time: 15000 });
collector.on('collect', async i => {
if (i.user.id === interaction.user.id) {
console.log(`${i.user.tag} clicked on the ${i.customId} button.`);
} else {
await i.reply({ content: `This button is not for you!`, ephemeral: true });
}
if (i.id === 'delete') {
inviteMsg.delete();
interaction.delete();
await i.reply.defer();
}
});
collector.on('end', collected => {
console.log(`Collected ${collected.size} interactions.`);
});
} catch (err) {
console.log(err);
return interaction.reply(`\`${err}\`.`);
}
}
};
I’ve been trying to mess around with it to see if i can but I’m running out of options to try 😂
I don’t know if I can do the same thing as the embed and set it as disabled through the components thing but not sure if that’s the correct way to do it.
You can do that easily by disabling the buttons once your collector ends.
collector.on('end', collected => {
botInvite.setDisabled(true);
support.setDisabled(true);
del.setDisabled(true);
// edit the message with the components disabled
inviteMsg.edit({embeds: [inviteEmbed], components: [new ActionRowBuilder().addComponents(botInvite, support, del)]});
console.log(`Collected ${collected.size} interactions.`);
});
If you have multiple buttons that need to be disabled, this can get a little annoying to add in your code.
What you can do is creating a row with your components, adding it to your message, and then looping through the buttons.
const row = new ActionRowBuilder().addComponents(botInvite, support, del);
const inviteMsg = await interaction.reply({ embeds: [inviteEmbed], components: [row], fetchReply: true });
// when your collector ends:
collector.on('end', collected => {
row.components.forEach(c => c.setDisabled(true));
// edit message
inviteMsg.edit({embeds: [inviteEmbed], components: [row]});
console.log(`Collected ${collected.size} interactions.`);
});

How to send a message to all members who have a role from person with role, that have permission to use this cmd (discord.js)

I'm coding a bot using discord.js. I would like to send a <message> to all members who have <role> when person with role, that have permission to use command:
/send <role> <message>
in a channel.
How can I do this?
I copied and slightly remade this topic, because in the original one the answer was irrelevant at the moment
I tried a similar theme, but it is not relevant at the moment
related question
Try this
const {
SlashCommandBuilder
} = require('#discordjs/builders')
module.exports = {
data: new SlashCommandBuilder()
.setName('newsletter')
.setDescription('Send a message to members by role')
.addRoleOption(option =>
option
.setName('role')
.setDescription('What role')
.setRequired(true))
.addStringOption(option =>
option
.setName('message')
.setDescription('What is the message.')
.setRequired(true)),
async execute(client, interaction) {
const guild = client.guilds.cache.get('959899135258026055')
const role2have = [
'54654546545645656',
'65465456465456465456'
]
if (interaction.member.roles.cache.some(role => role2have.includes(role.id))) {
const role = guild.roles.cache.get(interaction.options.getRole('role').id)
console.log(role)
role.members.forEach(member => {
member.send({
content: `${interaction.options.getString('message')}`
}).catch((err) => {
console.log(`Unable to DM ${member.user.username} - received error:\n${err}`)
})
})
return interaction.reply({
content: 'Message sent',
ephemeral: true
})
} else {
return interaction.reply({
content: 'You do not have permission to use this command',
ephemeral: true
})
}
}
}
This command is then executed:
/newsletter role: #role message: message content

Discord.js maximum number of webhooks error

Have this slash command code and turned it into webhook. It worked when I used it once but it stopped working after that. I got this error DiscordAPIError: Maximum number of webhooks reached (10). Does anyone have any idea on how to fix this?
Code:
run: async (client, interaction, args) => {
if(!interaction.member.permissions.has('MANAGE_CHANNELS')) {
return interaction.followUp({content: 'You don\'t have the required permission!', ephemeral: true})
}
const [subcommand] = args;
const embedevent = new MessageEmbed()
if(subcommand === 'create'){
const eventname = args[1]
const prize = args[2]
const sponsor = args[3]
embedevent.setDescription(`__**Event**__ <a:w_right_arrow:945334672987127869> ${eventname}\n__**Prize**__ <a:w_right_arrow:945334672987127869> ${prize}\n__**Donor**__ <a:w_right_arrow:945334672987127869> ${sponsor}`)
embedevent.setFooter(`${interaction.guild.name}`, `${interaction.guild.iconURL({ format: 'png', dynamic: true })}`)
embedevent.setTimestamp()
}
await interaction.followUp({content: `Event started!`}).then(msg => {
setTimeout(() => {
msg.delete()
}, 5000)
})
interaction.channel.createWebhook(interaction.user.username, {
avatar: interaction.user.displayAvatarURL({dynamic: true})
}).then(webhook => {
webhook.send({content: `<#&821578337075200000>`, embeds: [embedevent]})
})
}
}
You cannot fix that error, discord limits webhooks per channel (10 webhooks per channel).
However, if you don't want your code to return an error you can just chock that code into a try catch or add a .catch
Here is an example of how to handle the error:
try {
interaction.channel.createWebhook(interaction.user.username, {
avatar: interaction.user.displayAvatarURL({dynamic: true})
}).then(webhook => {
webhook.send({content: `<#&821578337075200000>`, embeds: [embedevent]})
})
} catch(e) {
return // do here something if there is an error
}

Discord.js DM User kicked

Okay so I am having trouble trying to DM a user who was kicked from the server right now it DM's the person who kicked the member. I don't know what I did wrong but I want the bot to DM the user who was kicked so they know why they were kicked frokm the server
const { RichEmbed } = require("discord.js")
const { red_dark } = require("../../colors.json");
module.exports = {
name: "kick",
description: "Kick a user from the guild!",
usage: "!kick",
category: "moderation",
accessableby: "Moderator",
aliases: ["k"],
run: async (bot, message, args, user) => {
try{
if (message.member.hasPermission("KICK_MEMBERS")) {
if (message.mentions.users.size != 0) {
if (message.mentions.members.first().kickable) {
let reason = args.slice(1).join(" ")
if(!reason) return message.channel.send("No reason was provided!")
else {
message.member.send("This is a test message")
message.mentions.members.first().kick().then(m => {
message.channel.send(`**${m.user.username}** has been kicked from **${message.guild.name}**. Bye bye!`)
});
}
} else {
message.channel.send(`:x: **${message.mentions.user.first().username}** is too priveledged for me to kick.`);
}
} else {
message.channel.send(':x: Please tag the user you would like to kick.')
}
} else {
message.channel.send(`:x: **${message.author.username}**, You do not have permission to kick. You must have the \`Kick Members\` permission.`);
}
} catch (err) {
message.channel.send(`:x: Either I am unable to kick **${message.mentions.users.first().username},** or I do not have permission to kick members.`);
}
}
}
You currently send a the DM to message.member. What you would need to do it to send it to the same person you actually kick, which you currently do with message.mentions.members.first().kick().
So with that clarified, you need to do message.mentions.members.first().send("This is a test message")

How to create a voice channel by reacting on embed?

I'm trying to use this code to create an embed, if you react on it a specific voice channel will be created on the server.
That's very similar to roles menu, but it will not give you a role, it will create a channel.
The code is working, but when you react on the embed the bot do nothing.
module.exports = {
name: 'cc',
description: 'Help!',
execute(message) {
const embed = {"image": {"url": `${message.author.displayAvatarURL}`}}
message.channel.send({embed})
.then((message) => { message.react("❤") })
.then(() => {
const filter = (reaction, user) => reaction.emoji.name === "❤" && user.id === message.author.id;
const collectorForU = message.createReactionCollector(filter, {time: 1000/*time in ms*/});
collectorForU.on("collect", () => {message.guild.createChannel("╔═════ஜ۞ஜ═════╗", "voice")})
})
}
};
There is no error on the console.
The reaction collector expires before anything can be collected; the time option is set to 1 second.

Resources