Discord.js maximum number of webhooks error - node.js

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
}

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

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

Lockdown Channel command and Unlock channel

It's a strange question about lockdown channel but why this is not working?
This is the script of my lock command msg.channel.guild.roles.everyone if that everyone define as #everyone? I've seen this script in documents of discord permissions. I tried it but it's not working. And there's no error too.
client.on('messageCreate', msg => {
if(msg.content.toLowerCase().startsWith(`${prefix}lock`)){
msg.channel.permissionOverwrites.create(msg.channel.guild.roles.everyone, { SEND_MESSAGES: false });
msg.channel.send('Channel Locked')
}else if(msg.content.toLowerCase().startsWith(`${prefix}unlock`)){
msg.channel.permissionOverwrites.create(msg.channel.guild.roles.everyone, { SEND_MESSAGES: true });
msg.channel.send('Channel Unlocked')
}
});
message.channel.updateOverwrite(message.guild.id, {
SEND_MESSAGES: false
});
Unlocked the channel use
message.channel.updateOverwrite(message.guild.id, {
SEND_MESSAGES: null
});
for example
client.on("message", async message => {
if (message.content.startsWith(prefix + "lock")) {
if (!message.member.hasPermission("MANAGE_CHANNELS")) return;
if (!message.guild.member(client.user).hasPermission("MANAGE_CHANNELS"))
return;
message.channel.updateOverwrite(message.guild.id, {
SEND_MESSAGES: false
});
const lock = new Discord.MessageEmbed()
.setColor("#00000")
.setDescription(
`🔒 | Locked Channel
❯ **Channel Name :** <#${message.channel.id}>
❯ **Locked By :** <#${message.author.id}>
`
)
.setThumbnail(message.author.avatarURL())
.setFooter(`${message.author.tag}`, message.author.avatarURL())
.setTimestamp()
message.chaneel.send(lock);
}
});
This is embed

bulkDelete does not exist on channel

A little note to start with, this is a typescript file. I am having trouble with a purge/clear command. This command worked on discord v11 however is having an issue on v12. the issue I am seeing is bulkDelete does not exist on type 'TextChannel | DMChannel | NewsChannel' I don't know where it is going wrong. I am not looking for just a fix, an explanation of why it doesn't work would be appreciated. Thanks in advance!
import * as Discord from "discord.js";
import { IBotCommand } from "../api";
export default class purge implements IBotCommand {
private readonly _command = "purge"
help(): string {
return "(Admin only) Deletes the desired numbers of messages.";
}
isThisCommand(command: string): boolean {
return command === this._command;
}
async runCommand(args: string[], msgObject: Discord.Message, client: Discord.Client): Promise<void> {
//converts args into a number
let numberOfMessagesToDelete = parseInt(args[0],10);
//make sure number is interger
numberOfMessagesToDelete = Math.round(numberOfMessagesToDelete + 1);
//clean up msgs
msgObject.delete()
.catch(console.error);
if(!msgObject.member.hasPermission("KICK_MEMBERS")) {
msgObject.channel.send(`${msgObject.author.username}, AH! AH! AH! You didn't say the magic word!`)
.then(msg => {
(msg as Discord.Message).delete({timeout:10000})
});
return;
}
//message amount
if(!args[0]){
msgObject.channel.send(`Improper format! Proper format is "-purge 12"`)
.then(msg => {
(msg as Discord.Message).delete({timeout:10000})
.catch(console.error);
});
return;
}
//verifies args[0] actual number
if(isNaN(numberOfMessagesToDelete)){
msgObject.channel.send(`Improper number! Pick a number between 1 and 99!`)
.then(msg => {
(msg as Discord.Message).delete({timeout:10000})
.catch(console.error);
});
return;
}
//delete desired number of messages
let auditLog = client.channels.cache.find(channel => channel.id === "623217994742497290") as Discord.TextChannel;
const bdEmbed = new Discord.MessageEmbed()
.setTitle(`**Message Purge**`)
.setDescription(`${numberOfMessagesToDelete} messages were deleted in ${msgObject.channel.toString()} by ${msgObject.author.username}`)
.setTimestamp()
.setColor([38,92,216])
.setThumbnail(msgObject.author.displayAvatarURL())
msgObject.channel.bulkDelete(numberOfMessagesToDelete)
auditLog.send(bdEmbed)
.catch(console.error);
}
}

Resources