Discord.js // Filtering message startsWith and work around DiscordAPIError for bulkDelete

感情迁移 提交于 2019-12-02 10:01:21

There are two issues with const botMessages = messages.filter(msg => msg.author.bot && msg.content.startsWith("!" || "." || ">"));:

  1. msg.content.startsWith("!" || "." || ">") is only going to evaluate against the first truthy statement: "!". String#startsWith only 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(">");
    
  2. 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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!