Discord.js bot, how to purge without pins? - javascript

This is my purge command, I want my purge to ignore pins, anyone knows how could I do it?
This is what I got for now:
} else if (message.content.toLowerCase().startsWith(`${PREFIX}purge`)) {
if (!message.member.hasPermission('MANAGE_MESSAGES')) return message.channel.send("You don\'t have permissions to do this command")
if (!message.guild.me.hasPermission('MANAGE_MESSAGES')) return message.channel.send("I don\'t have permissions to do this command")
if (!args[1]) return message.channel.send("You need to specify a number of messages to purge")
if (isNaN(args[1])) return message.channel.send("That isn\'t a valid amount of messages to purge")
if (args[1] > 100 || args[1] < 2) return message.channel.send("Make sure that your amount is ranging 2 - 100")
try {
await message.channel.bulkDelete(fetch(message).filter(message => !message.pinned)).size
} catch {
return message.channel.send("You can only bulk delete messages within 14 days of age")
}
var embed = new Discord.MessageEmbed()
.setAuthor(`${message.author.username} - (${message.author.id})`, message.author.displayAvatarURL())
.setThumbnail(message.author.displayAvatarURL())
.setColor('#FFAE00')
.setDescription(`
**Deleted:** ${args[1]}
**Action:** Purge
**Channel:** ${message.channel}
**Time:** ${moment().format('llll')}
`)
const channel = message.guild.channels.cache.find(c => c.name === "audit-log")
channel.send(embed)
}
})
await message.channel.bulkDelete(fetch(message).filter(message => !message.pinned)).size
BTW this last line doesn't work but it is what I think I need to modify

Use this:
await message.channel.bulkDelete(
(await message.channel.messages.fetch({limit: args[1]}))
.filter(m => !m.pinned)
)
Note that if there are pinned messages, it will delete less messages than args[1].

Related

Try to add a row of emojis to discord server using discord.js

I can add an emoji to a discord server by this code
but how can i add a row of emojis at once to this discord server?
const emoticon = require('discord.js').Util.parseEmoji("EMOJI");
if(emoticon.id == null) return message.channel.send('I could not find this emoji!');
if(message.guild.emojis.cache.has(emoticon.id)) return message.reply("That emoji is already on the server")
const emoji = `https://cdn.discordapp.com/emojis/${emoticon.id}.${emoticon.animated ? 'gif' : 'png'}`
try {
message.guild.emojis.create(emoji, emoticon.name || 'Emoji')
await message.reply(`Successfully added \`${emoticon.name}\` emoji to this server!`)
}catch(error){
return message.channel.send(`An error has occurred ${error}`)
like what if this EMOJI is EMOJI_1 EMOJI_2 EMOJI_3
As ACGaming said, you can do it by creating an array and looping through it:
const emojiArray = ["EMOJI_1", "EMOJI_2", "EMOJI_3"];
emojiArray.forEach(emoji => {
try {
message.guild.emojis.create(emoji, emoticon.name || 'Emoji');
await message.reply(`Successfully added \`${emoticon.name}\` emoji to this server!`);
}catch(error){
return message.channel.send(`An error has occurred ${error}`);
}
}
)}

Receiving massive latency on a recursive function(s) for awaiting input

I have the following code
const Discord = require("discord.js"),
{ MessageEmbed } = Discord,
ms = require("ms"),
module.exports.run = async (client, message) => {
async function awaitMessages(func) {
let output;
const m = await message.channel.awaitMessages({ filter: m => m.author.id === message.author.id, time: 60000 });
if (m.content !== "cancel") output = await func(m);
else return await message.channel.send("cancelled") && null;
if (typeof output === "function") return await output() && awaitMessages(func);
else return output;
}
function makeWaitArg(argName, description) {
const embeds = [new MessageEmbed()
.setTitle(`Giveaway ${argName}`)
.setDescription(description + " within the next 60 seconds.")
.setColor("#2F3136")
.setTimestamp()
.setFooter("Create A Giveaway! | Type cancel to cancel.", message.author.displayAvatarURL())];
return () => message.channel.send({ embeds: embeds })
};
function makeError(title, desc) {
const embeds = [new MessageEmbed().setFooter("type cancel to cancel")];
return () => message.channel.send({ embed: embeds })
}
const channel = await awaitMessages(makeWaitArg("Channel", "Please type the channel you want the giveaway to be in."), ({content}) => {
if (message.guild.channels.cache.has(content) || message.guild.channel.cache.get(content)) return content;
else return makeError("Channel", "That channel doesn't exist. Try Again.");
}),
prize = await awaitMessages(makeWaitArg("Prize.", "Please send what you would like the giveaway prize to be"), ({ content }) => {
if (content.length > 256) return makeError("Giveaway Prize Too Long.", "Please ensure the giveaway prize is less than 256 characters. Try again.");
else return content;
}),
// ill do those just be quick with logic
winnerCount = await awaitMessages(makeWaitArg("Winner Count.","Please send how many winners you would like the giveaway to have"), ({ content }) => {
if (isNaN(content)) return makeError("Invalid Winner Count.", "Please provide valid numbers as the winner count. Try again.");
else if (parseInt(content) > 15) return makeError("You can not have more than 15 winners per giveaway!")
else return content;
}),
time = await awaitMessages(makeWaitArg("Time.", "Please send how long you would like the giveaway to last"), ({ content }) => {
if (!ms(content)) return makeError("Invalid Time.", "Please provide a valid time. Try again.");
else return ms(content);
})
if (!channel || !prize || !winnerCount || !time) return;
// Start the giveaway
};
Recursion is being used to appropriately ask for multiple inputs upon failure to provide a correct input, according to my logic everything should work fine and from what I observe is that I face a massive latency between two of the steps which might be due to unnecessary load on the system while performing recursion, I need to know where that is originating and would like to rectify it.

Bot assigns user a role, even if user doesn't own role

Sorry for the confusing title, I'll clarify. I'm trying to make the bot check if a user has a certain role in their quick.db inventory, and if they do, it'll equip that role. The problem I'm having is that even with the role in the inventory, it returns the error that the role isn't owned. I have a feeling that the problem is the if (db.has(message.author.id + '.hot rod red')) line, as I'm not too sure how to format checking for a role with quick.db. Sorry for the messy code, if anyone knows how to fix this let me know, thanks!
if (db.has(message.author.id + '.hot rod red')) {
if (message.member.roles.cache.some(role => role.name === 'hot rod red')) {
let embed = new Discord.MessageEmbed().setDescription('You already have this role equipped!');
return message.channel.send(embed);
} else {
await message.guild.members.cache.get(user.id).roles.add('733373020491481219');
let embed = new Discord.MessageEmbed().setDescription(`You now have the ${message.guild.roles.cache.get('733373020491481219')} role!`);
message.channel.send(embed);
user.roles.remove(user.roles.highest);
}
} else {
let embed = new Discord.MessageEmbed().setDescription('You do not own this role!'); // ERROR HERE; GIVES ROLE EVEN WITHOUT OWNING
return message.channel.send(embed);
}
Probably try something like
let check = db.get(message.author.id+'.hot rod red')
and check if it is true/false, I'd say to use string rather then boolean as you can use if(check === 'false/true'){}. You can also do
if(!check || check === 'false'){ return
let embed = new Discord.MessageEmbed().setDescription('You do not own this role!');
return message.channel.send(embed);
}
So the final code would be:
let check = await db.get(message.author.id + '.hot rod red');
let rejectEmbed = new Discord.MessageEmbed()
.setDescription('You do not own this role!');
if(!check){
return message.channel.send(rejectEmbed)
}
if(check === 'true'){
if (message.member.roles.cache.some(role => role.name === 'hot rod red')) {
let embed = new Discord.MessageEmbed().setDescription('You already have this role!');
return message.channel.send(embed);
} else {
await message.guild.members.cache.get(user.id).roles.add('733373020491481219');
let embed = new Discord.MessageEmbed().setDescription(`You now have the ${message.guild.roles.cache.get('733373020491481219')} role!`);
message.channel.send(embed);
user.roles.remove(user.roles.highest); // I'm unsure why this is here, this could be causing a potential error
}
}
If there are any more questions, please comment!! I hope this has helped.

Discord Bot js reactions

Coding a discord bot trying to get it to react to a user adding a reaction and then remove that user's reaction, I managed to get that working but if there is more than one message with the reactions on it, it will run that reaction as well. For reference I'm trying to make a dice rolling bot that reacts to a users reaction and then re-rolls a previously entered roll. I do apologise if there is already a question like this but I could not find it when looking.
Here is an example:
example of bot in action
This is the code
Get command
Client.on('message', message=> {
if(!message.content.startsWith(PREFIX) || message.author.bot) return;
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0].toLowerCase())
{
case "roll": case "r":
if(!args[1] || args[1].indexOf("d") == -1) return message.channel.send('Invalid Roll');
Client.commands.get('torg').RollDice(message, args, Client);
break;
}});
This is then the code it gets.
Run command
module.exports = {
name: 'torg',
description: 'Die roller for Trog',
async RollDice(message, args, client)
{
const channel = 'XXXXXXXXXXXXXXXXXXXXX';
const reRoll = '🔄';
if(!args[2])//untrained
{
var roll = DieRoller(args[1]);
}
else if (args[2] == "t" || args[2] == "T")
{
var roll = DieRoller(args[1], true);
}
let rollEmbed = await message.channel.send(roll);
rollEmbed.react(reRoll);
client.on('messageReactionAdd', async (reaction, user) =>
{
if(reaction.message.partial) await reaction.message.fetch();
if(reaction.partial) await reaction.fetch();
if(user.bot) return;
if(!reaction.message.guild) return;
if(reaction.message.channel.id == channel)
{
if(reaction.emoji.name === reRoll)
{
var newRoll = DieRoller(args[1]);
await message.channel.send(newRoll);
await reaction.users.remove(user);
}
else
{
return;
}
}
});
}
What should I do to make sure that the bot doesn't react twice when it sees two messages with reactions?
Thanks in advance to anyone who reads this and can help, I've only recently tried my hand and coding discord bots.

I need help creating a warning command in Discord.JS

I did this command to warn members and send a message in the DM, but I want the bot to tell the members in which server they were warned.
if (command === "warn") {
let dUser = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0]);
if (!message.member.hasPermission("ADMINISTRATOR")) return message.reply("You can't use that command!")
if (!dUser) return message.channel.send("Can't find user!")
let dMessage = args.join(" ").slice(22);
if (dMessage.length < 1) return message.reply('what is the reason???')
dUser.send(`${dUser}, You have been warned for doing ${dMessage}`)
message.channel.send(`${dUser} has been warned for doing ${dMessage} :thumbsdown:`)
Message has a property Guild, which is the guild in which the message was sent. You can just use message.guild.name to get the guild name.
if (command === "warn") {
let dUser = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0]);
if (!message.member.hasPermission("ADMINISTRATOR")) return message.reply("You can't use that command!")
if (!dUser) return message.channel.send("Can't find user!")
let dMessage = args.join(" ").slice(22);
if (dMessage.length < 1) return message.reply('what is the reason???')
dUser.send(`${dUser}, You have been warned for doing ${dMessage} in the server ${message.guild.name}`)
message.channel.send(`${dUser} has been warned for doing ${dMessage} :thumbsdown:`)

Categories