This is my current code. Credit goes to @André Dion for the help.
if (message.channel.type == 'text') {
message.channel.fetchMessages().then(messages => {
const botMessages = messages.filter(msg => msg.author.bot)
message.channel.bulkDelete(botMessages);
messagesDeleted = botMessages.array().length; // number of messages deleted
// Logging the number of messages deleted on both the channel and console
message.channel.send("Deletion of messages successful. Total messages deleted: " + messagesDeleted);
console.log('Deletion of messages successful. Total messages deleted: ' + messagesDeleted)
}).catch(err => {
console.log('Error while doing Bulk Delete');
console.log(err);
});
}
When the user enters "!clearMessages" it runs this code and deletes only messages from bots. I would like to add a feature where this also deletes messages from users that starts with !/./> (these messages can be from users not only bots), so I tried editing the line with the const botMessages to this: const botMessages = messages.filter(msg => msg.author.bot && msg.content.startsWith("!" || "." || ">")); but that didn't work. Can you please point out where I'm going wrong and how I can fix this?
Another issue I noticed is that when there is only 1 bot message the bot doesn't delete the message and comes up with an DiscordAPIError, saying that you must provide at least 2-100 messages to delete. Is there a work around this?
Thanks.
There are two issues with const botMessages = messages.filter(msg => msg.author.bot && msg.content.startsWith("!" || "." || ">"));:
msg.content.startsWith("!" || "." || ">")is only going to evaluate against the first truthy statement:"!".String#startsWithonly takes a single pattern, so you'll have to split that call into three calls. Let's assign the result of these checks into a single variable for convenience:const isCommand = msg.content.startsWith("!") || msg.content.startsWith(".") || msg.content.startsWith(">");You want to filter out messages that are issued by bot users or that look like a command. Currently your logic is written so that messages that are issued by bots and look like a command are filtered, which is wrong (bots won't be issuing any commands). The correct check with the above additions would be:
const botMessages = messages.filterArray(msg => { const isCommand = msg.content.startsWith("!") || msg.content.startsWith(".") || msg.content.startsWith(">"); return msg.author.bot || isCommand; });
Correcting your filter logic should fix your DiscordAPIError exception but to ensure no bad calls are being issued, you should guard the bulkDelete invocation:
if (botMessages.length > 1) {
message.channel.bulkDelete(botMessages);
} else if (botMessages.length) {
botMessages[0].delete();
} else {
// nothing to delete
}
来源:https://stackoverflow.com/questions/47952522/discord-js-filtering-message-startswith-and-work-around-discordapierror-for-b