Discord Bot Clear Commands Eror - javascript

I took a small break from coding my bot, and I've been playing around with adding modules to make an economy type thing. I was having some issues with that, so I went to check if the 'clear' command worked still. I originally wrote the code without the async function, but now I am using it and I think maybe that has caused a problem? Wondering if anyone knows how to fix it, thanks for checking this out.
The ban/kick commands also aren't working at all, so if anyone could take a look at those?
For the code, I've used bits and pieces of tutorials and guides from around the internet and I think some of that may have interfered with what's already been written.
ErrorCode:
(node:16360) UnhandledPromiseRejectionWarning: DiscordAPIError: You can only bulk delete messages that are under
module.exports = {
name: "clear",
description: "Clears messages",
async run (client, message, args) {
const amount = args.join(" ");
if(!amount) return message.reply('please provide an amount of messages for me to delete')
if(amount > 100) return message.reply(`you cannot clear more than 100 messages at once`)
if(amount < 1) return message.reply(`you need to delete at least one message`)
await message.channel.messages.fetch({limit: amount}).then(messages => {
message.channel.bulkDelete(messages
)});
}
}

As Tyler2P pointed out in the comments, you can only bulk-delete messages under 2 weeks old. If you'd like to keep your command running smoothly, you can filter out messages sent before that time.
// as a general tip, you don't need to use `await` and `.then()`
// use only one at a time
message.channel.messages.fetch({ limit: amount }).then(messages => {
// filter out all messages sent more than two weeks ago
messages = messages.filter((msg) => msg.createdTimestamp < new Date(Date.now() - 12096e5).getTime())
message.channel.bulkDelete(messages)
messages.size !== amount
? message.channel.send(`Unfortunately, ${amount - messages.size} messages were sent more than two weeks ago, but we deleted the other ${messages.size}.`)
: message.channel.send(`${messages.size} messages were deleted`);
});

Related

Discord.js Message Collector not working properly, can someone recommend an other way to collect messages or how to make this work?

I made a discord bot using discord.js.
This bot should ask questions about a game when someone uses !rank [rank name]
and if the user answers correctly he/she receives the rank.
I found a way to collect messages, but this method does not want to work, it send the message multiple times and also ignores the time given to the collector, I tried multiple things but neither of them worked, I am very new to creating discord bots so can someone recommend me any other solution to make this bot work?
CODE:
client.on('messageCreate', message => {
if (message.content == '!rank r6') {
message.channel.send('Is Frost an attacker?')
const collector = new Discord.MessageCollector(message.channel, m => m.author.id == message.author.id, {max: 1, time: 8000})
collector.on('collect', message => {
if (message.content == 'no'){
message.channel.send('Role added')
message.member.roles.add('775660517053562900')
}
})
}
})
I'm not sure how you formatted your code to look like that, as the official docs & guide suggest different ways of implementing Collectors. I personally suggest following the guides carefully.
Specifically I see that you try making a new Discord.MessageCollector whereas the guide suggests using a function on message.channel to instate a message collector.
Here are some resources to help you out (assuming you're using Discord.js v12):
https://v12.discordjs.guide/popular-topics/collectors.html#message-collectors
https://v12.discordjs.guide/additional-info/async-await.html#how-do-promises-work

How make a bot delete Discord channel messages that start with or are from a bot

I have a bot in my Discord server for playing music. As it works with commands, and it answers if there is something like a playlist the channel is spammed with songs or messages that later on are meaningless. So I want the bot that each time it leaves a voice channel, it clears the command messages that were sent to it and the answer messages that it sent.
So I have looked around a bit and came to this code but it doesnt work. I added some console logs to see up where it goes in, and it reaches FLAG 1 but not FLAG 2. So what is wrong in that condition? PREFIX is the "!" that commands start with, and 0123456789 is the bot ID
else if (msg.content.trim().toLowerCase() == _CMD_LEAVE) {
const channel = msg.channel;
const messageManager = channel.messages;
messageManager.fetch({ limit: 100 }).then((messages) => {
messages.forEach((message) => {
console.log("FLAG 1: "+ util.inspect(message))
if ( (message.content.startWith(PREFIX)) || (message.author.id == 0123456789)) {
console.log("FLAG 2: "+ util.inspect(message))
message.delete();
}
});
});
}
Thanks in advance
Two things here: startWith should actually be startsWith since you didn't mention any errors I'll assume this is just a typo from the example code.
Second, message.author.id == 0123456789 won't work since IDs should be strings, not numbers.

Logging message.author from one command and pulling it to another

I am creating a discord bot that does tickets which are used as applications and I have most of it done except I want the bot when the -close command is used to log the ticket that was closed.
I've tried a few things such as calling a .then to send a message to the logging channel of the specific channel being deleted then calling another .then when it was deleted except it would still send the message saying #deleted-channel. I tried this in a few ways but I couldn't figure it out.
Another solution I tried was creating a variable in the -apply command that would log the name of the person that created the message but I realized that after many people used the command apply if I attempted to close one it would log the most recent applicant's name, not the application I was closing
-apply command
const reason = message.content.split(" ").slice(1).join(" ");
var tAuthor = message.author.tag
if (!message.guild.roles.exists("name", "[ยป] Helpers")) return message.channel.send(`Server does not have role set correctly., This error has been logged. \nPlease contact bot developer <#251557870603075586>`);
if (message.guild.channels.exists("name", "t-staff-" + message.author.tag)) return message.reply(`You already have an application open.`);
message.guild.createChannel(`t-staff-${message.author.tag}`, "text").then(c => {
let role = message.guild.roles.find("name", `${config.role}`);
let role2 = message.guild.roles.find("name", "#everyone");
c.overwritePermissions(role, {
SEND_MESSAGES: true,
READ_MESSAGES: true
});
c.overwritePermissions(role2, {
SEND_MESSAGES: false,
READ_MESSAGES: false
});
c.overwritePermissions(message.author, {
SEND_MESSAGES: true,
READ_MESSAGES: true
});
c.setParent(message.guild.category.exists("name", "t-staff-"))
message.reply(`:white_check_mark: Your application has been created, #${c.name}.`);
const embed = new Discord.RichEmbed()
.setColor(0xCF40FA)
.setTitle(`Staff Application`)
.setDescription(`<#${message.author.id}>`)
.addField(`Requirements`, `You must meet all the requirements:\n\n1. Professional attitude and grammar\n2. Working Microphone\n3. No severe punishments on the server. (Racial Slurs, DDos Threats, etc..)\n4. You must be over the age of 14`)
.addBlankField()
.addField(`Note:`, `Please check in announcements for open staff positions`)
.addField(`Note:`, `Please paste the format with your answers`)
.addField(`Note:`, `If your previous application was denied you must wait one week to sumbit a new one`)
.addBlankField()
.addField('Format', `\nWhat position are you applying for: \n\nMinecraft username: \n\nPrevious Minecraft usernames: \n\nWhat is your age: \n\nTimezone: \n\nAbility to record Minecraft video: \n\nHow much time do you have to contribute a week? \n\nWhat do you consider to be your biggest weaknesses?\n\nWhat's your dream job? \n\nHow do you deal with pressure or stressful situations? \n\nAny previous staff skills or experience? \n\nHave you ever been banned or punished for your actions on this server? If so, please include details. \n\nTell us about a time you made a mistake within the last year? How did you deal with it? What did you learn? \n\nAre you currently staff on any other servers? \n\nWhere did you hear about nodepvp? \n\nHave you made any previous applications, if so how many and what is the date of your last one? \n\nWhat would be your daily tasks for the rank you are applying for \n\nAnything else we should know? `)
.addBlankField()
.setTimestamp();
c.send({ embed: embed });
client.channels.get(`568210811009499136`).send(`:white_check_mark: !!!Ticket Created ${message.author} at **${current_date}**`);
-close command
if (!message.channel.name.startsWith(`ticket-`)) return message.channel.send(`You can't use the close command outside of a ticket channel.`);
if(!message.member.hasPermission("MANAGE_MESSAGES")) return message.channel.send(`${message.author} Do not have permission to close this application`);
// Confirm delete - with timeout (Not command)
message.channel.send(`Are you sure? Once confirmed, you cannot reverse this action!\nTo confirm, type \`/confirm\`. This will time out in 10 seconds and be cancelled.`)
.then((m) => {
message.channel.awaitMessages(response => response.content === '/confirm', {
max: 1,
time: 10000,
errors: ['time'],
})
.then((collected) => {
message.channel.delete();
})
.catch(() => {
m.edit('Ticket close timed out, the ticket was not closed.').then(m2 => {
m2.delete();
}, 3000);
});
});
When I tried to log this by using a .then function in the close command right before
.then((collected) => {
message.channel.delete();
It still sends the message to the channel saying #deleted-channel even though I'm sending the command before the channel is deleted.
If you send a message with a channel mention, such as #test, it will stay as a clickable link to the test channel, as long as that channel exists. If you delete that channel, all links will seize and become a dull #deleted-channel.
One solution would be to log Closed ${channel.name}, then deleting the channel.
You cannot make it so it keeps the linked message (unless you make it so no one can see the deleted channel by denying read access to closed tickets for everyone except staff for logging purposes).

How do I add multiple reactions?

I've looked everywhere for answers and I can't figure this out.
Here's what I want to do:
I want to run some command initially for my bot to send an embed to a specific channel only admins have access to. Done.
Then the bot will immediately react to its own message with the number emojis 1, 2, and 3. Problem.
I don't want the bot to await a reaction to the message from an admin. This embed is meant to stay there UNTIL an admin reacts to it. That could be within 1 minute, or 3 days, but if I have to reboot the bot for any reason then it will stop awaiting the reaction. So I have an event that triggers when someone reacts with a given emoji, this works. It can be improved, but it functions:
bot.on("messageReactionAdd", (messageReaction, user) => {
console.log(messageReaction);
if(reaction.emoji.name === "\u0031\u20E3") {
message.channel.send('one'); //This is temporary to test it out. There will be other code here eventually.
}
else if(reaction.emoji.name === "\u0032\u20E3") {
message.channel.send('two');
}
else if(reaction.emoji.name === "\u0033\u20E3") {
message.channel.send('three');
}
});
My problem is that when I run this code:
let cmdEmbed = new discord.RichEmbed()
.setTitle('**Command Menu Test**')
.setDescription("Type commands")
.setAuthor('InfernoBot', 'https://cdn.discordapp.com/avatars/533089334224617474/17ddec7cb178601d17964040ed8dc32d.png?size=2048')
.setColor(0xD41519);
message.channel.sendEmbed(cmdEmbed).then(function (message) {
message.react('\u0031\u20E3')
message.react('\u0032\u20E3') //This doesn't run
message.react('\u0033\u20E3') //This doesn't run
});
It only ever reacts with the '1' emoji.
How do I make it react with emoji numbers 1, 2, and 3, without awaiting for a reaction?
PS: I'm going to implement some code that will resend the exact same embed with the same reactions once the existing embed has been reacted to, to reset it.
EDIT: The bot doesn't always react with 1. However, it only ever adds one reaction. It's not consistent.
.
Found the answer about 30 mins after posting this. I'll share for anyone who was having the same issue.
My first chunk of code in the original post was causing the bot to break and reboot.
I replaced the first chunk of code with:
bot.on("messageReactionAdd", (reaction, user) => {
if(user.toString() !== '<#533089334224617474>' /*InfernoBot ID*/) {
console.log('User is not InfernoBot')
if(reaction.emoji.name === "\u0031\u20E3") {
//code here
}
}
});
And I replaced the second chunk of code with:
let cmdEmbed = new discord.RichEmbed()
.setTitle('**Command Menu Test**')
.setDescription("Type commands")
.setAuthor('InfernoBot', 'https://cdn.discordapp.com/avatars/533089334224617474/17ddec7cb178601d17964040ed8dc32d.png?size=2048')
.setColor(0xD41519);
message.channel.sendEmbed(cmdEmbed).then(function (message) {
message.react('\u0031\u20E3').then(() => message.react('\u0032\u20E3')).then(() => message.react('\u0033\u20E3'));
});

Making a verification system with reactions

I have spotted some posts regarding the same topic, but not the exact problem.
I have also referred to javascript discords, where they were unable to assist me with my problem.
So to inform you,
The purpose of this verification system is to make sure the user understood the rules and can proceed to have the rest of the discord unlocked after he adds a checkmark reaction.
I have made a bot that has the command |message and it works fine and all, but I then want the bot to react to its own message once sent, and then wait for a user to also add a reaction, which will trigger a function, in this case. Triggering the bot to send a PM to the user and giving him a rank.
The bot adds his reaction fine, and upon reacting from me as an example it sends me a PM, but in the PM between me and the bot, the bot reacts once again to his message. And this might be because of the code checking if the message author is the bot.
I was told in the JS Discord that the messageReactionAdd function has a Message Property, however upon searching I couldn't find a way to implement this into my code. How would I do so? Also trying to give the user a rank also spits out an error, and I am simply stuck between understanding and making stuff work. I am getting confused with my own code, and I have minimal understanding of what I am doing, so with that said, Can anyone assist me doing this change, so I can get it in my head? Giving me links to the discord.js documentation is just making me more confused, and the only way for me to learn is by creating, and successfully making it work. Any help is appreciated of course.
So, here is the code for the messageReactionAdd:
bot.on('messageReactionAdd', (reaction, user) => {
if(reaction.emoji.name === "โœ…") {
if(user === bot.user) return;
// if(bot.channel === "dm") return;
// let role = bot.guild.roles.find("name", "C - Verified");
// let role1 = bot.guild.roles.find("name", "C - Unverified");
//if(user.roles.has(role.id));
//await(user.addRole(role.id) && user.removeRole(role1.id));
user.send("Thank you for being apart of the community! As a thanks for accepting the rules, you have been awarded the verified role!");
return;
}
});
And here is the code for the react function itself:
513769507907567628 is the bots' ID.
bot.on("message", async message => {
if(message.author.id != "513769507907567628") return;
message.react("โœ…");
});
So, if you have any input that'd be great! If you can join a Discord Call please message me, That'd be the easiest and quickest.
Regards, Marius.
If your problem occured here:
await(user.addRole(role.id) && user.removeRole(role1.id));
then it is because:
1) await only exists inside async functions.
2) you cannot just chain promises with &&, a && b will result in b and that gets then awaited, so in your case you only wait for the removal.
bot.on('messageReactionAdd', async (reaction, user) => {
if(reaction.emoji.name === "โœ…") return;
if(user === bot.user) return;
let role = bot.guild.roles.find("name", "C - Verified");
let role1 = bot.guild.roles.find("name", "C - Unverified");
await user.addRole(role.id);
await user.removeRole(role1.id);
});

Categories