Discord.js delete all bot and user message when trigger - node.js

as I said in the title, I would like the bot to delete all the messages used after activating the command, leaving only the embed as a result, but I can't do it. Any clue to do so?
const { Command } = require("discord.js-commando");
const Discord = require("discord.js");
module.exports = class PruebaCommand extends Command {
constructor(client) {
super(client, {
name: "prueba",
aliases: ["test"],
group: "general",
memberName: "prueba",
guildOnly: true,
description: " - ",
});
}
run(message, args) {
let embed1 = new Discord.MessageEmbed();
const filter = (m) => m.author.id == message.author.id;
message.channel.send(
`Proporciona el nombre del jugador al cual te gustaría añadir a la DODGE LIST`
);
message.channel
.awaitMessages(filter, { time: 30000, max: 1 })
.then((msg) => {
let msg1 = msg.first().content;
message.channel.send(`Link de tu Imagen`).then((msg) => {
msg.channel
.awaitMessages(filter, { time: 30000, max: 1 })
.then((msg) => {
let msg2 = msg.first().content;
message.channel.send(`Correcto, creando tu embed`).then((msg) => {
embed1.setAuthor("˜”*°•.˜”*°• DODGE LIST •°*”˜.•°*”˜");
embed1.setDescription(
"Un nuevo jugador ha sido añadido a la Dodge List"
);
embed1.addFields(
{ name: "__NOMBRE:__", value: msg1 },
{ name: "__SERVIDOR:__", value: "LAS" }
);
embed1.setImage(msg2);
embed1.setColor("RANDOM");
message.channel.send(embed1);
});
});
});
});
}
};
Sorry if the code is somewhat strange, or executed the way it shouldn't be, I am new to this and have never used awaitMessages to make a command

If I understand correctly, you want to delete all the messages that came from the user, and the bot, which would be the command, the response, the extra info you waited for, and but not that response? Well here you go, this just came quickly to my head, there could be a better way:
//...
var messages = [message];
//...
<channel>.awaitMessages(filter, options)
.then(msgs => messages.push(msgs.first())) //keep in mind this would only work if it’s 1 message max
//... at the end of all the awaitMessages, put this:
messages.forEach(m => m.delete())

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

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
}

Can you mass kick people from a server using discord.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
})
}
}
}

only accept number discord.js

What I would like to eliminate in this code is that the program only reacts to numbers, not other characters, then it says "Not an appropriate value"
Can anyone help me with this?
e.g:
User: -clearr
Bot: How many messages do you want to delete?
User: asd
Bot: asd message successfully deleted!
This code:
module.exports = {
name: 'clearr',
description: "Clear messages!",
async execute(client, message, args) {
if(!args[0]) {
let filter = m => m.author.id === '365113443898097666'
message.channel.send(`How many messages do you want to delete?`).then(() => {
message.channel.awaitMessages(filter, {
max: 1,
time: 10000,
errors: ['time']
})
.then(message => {
message = message.first()
message.channel.bulkDelete(message);
message.channel.send (`\`${message} message\` successfully deleted!`)
.then(message => {
message.delete({ timeout: 5000 })
})
.catch(console.error);
})
})
}
}
}
Thank you very much in advance for your replies!
You have to use Number.isNaN(+var):
if(Number.isNaN(+args[0])) return message.reply('Please, specify how many messages do you want to delete!')

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

Resources