only accept number discord.js - node.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!')

Related

Discord.js bot random presence and status not showing nor changing when the bot starts

I've been trying to make a random bot presence/status change using Discord.js v13 that changes every 15 minutes. The problem I'm facing with my code is that the custom status and presence don't show when I first start the bot, I have to wait 15 minutes for it to show up and start changing.
Here is the code:
client.on("ready", async () => {
let servers = await client.guilds.cache.size
let servercount = await client.guilds.cache.reduce((a,b) => a+b.memberCount, 0 )
const statusArray = [
{
type: 'WATCHING',
content: `${servers} servers`,
status: 'online'
},
{
type: 'PLAYING',
content: `with my ${servercount} friends`,
status: 'online'
}
];
async function pickPresence() {
const option = Math.floor(Math.random() * statusArray.length);
try {
await client.user.setPresence({
activities: [
{
name: statusArray[option].content,
type: statusArray[option].type,
url: statusArray[option].url
},
],
status: statusArray[option].status
});
} catch (error) {
console.error(error);
}
}
setInterval(pickPresence, 1000*60*15);
});
Any ideas as to why it doesn't work instantly when I start the bot?
setInterval actually waits for the specified delay (15 minutes) before executing the code in the function for the first time. So all you need to do is simply add pickPresence() on the line before the setInterval.
pickPresence();
setInterval(pickPresence, 1000*60*15);

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

Discord.js delete all bot and user message when trigger

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

(discord.js) how to mention the user who react to the bot message?

How can I mention the user who reacted to my bot message?I want to send message like, "#user reacted to my message!", here is my code:
msg.awaitReactions((reaction, user) => user.id == user.id && (reaction.emoji.name == '👍'), { max: 1, time: 30000 }).then(collected => {
if (collected.first().emoji.name == '👍') {
//here I want to send the message with the mention
} else {
//I added it for case that I going to use yes or no react question
}
}).catch(() => {
//maybe I will add here message that says the time passed.
});
After reading articles and troubleshooting I came up with the following solution:
msg.awaitReactions((reaction, user) => user.id == user.id && (reaction.emoji.name == '👍'),
{ max: 1, time: 30000 }).then(collected => {
const reaction = collected.first();
if (collected.first().emoji.name == '👍') {
const member = reaction.users.cache.find((user) => !user.bot);
message.channel.send(`test is ${member}`)
} else {
//I added it for case that I gonna use yes or no react question
}
}).catch(() => {
//maybe I will add here message that says the time passed.
});

Resources