gpt4 book ai didi

javascript - Discord.js//过滤消息startsWith并解决bulkDelete的DiscordAPIError

转载 作者:行者123 更新时间:2023-12-03 02:49:28 25 4
gpt4 key购买 nike

这是我当前的代码。感谢@André Dion 的帮助。

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

当用户输入“!clearMessages”时,它会运行此代码并仅删除来自机器人的消息。我想添加一个功能,该功能还会删除以 !/./> 开头的用户的消息(这些消息不仅可以来自用户,也可以来自机器人),所以我尝试使用 const botMessages 编辑该行: const botMessages = messages.filter(msg => msg.author.bot && msg.content.startsWith("!"|| "."|| ">")); 但这不起作用。您能指出我哪里出了问题以及如何解决这个问题吗?

我注意到的另一个问题是,当只有 1 条机器人消息时,机器人不会删除该消息,并会出现 DiscordAPIError,表示您必须提供至少 2-100 条消息才能删除。有解决这个问题的方法吗?

谢谢。

最佳答案

const botMessages = messages.filter(msg => msg.author.bot && msg.content.startsWith("!" || "." || ">")); 有两个问题:

  1. msg.content.startsWith("!" || "." || ">")只会根据第一个真实的陈述进行评估:"!" String#startsWith 仅采用单个模式,因此您必须将该调用拆分为三个调用。为了方便起见,我们将这些检查的结果分配给一个变量:

    const isCommand = msg.content.startsWith("!") || msg.content.startsWith(".") || msg.content.startsWith(">");
  2. 您想要过滤掉机器人用户发出的消息或看起来像命令的消息。目前,您编写的逻辑使得机器人发出的消息看起来像命令被过滤,这是错误的(机器人不会发出任何命令)。对上述添加的正确检查是:

    const botMessages = messages.filterArray(msg => {
    const isCommand = msg.content.startsWith("!") || msg.content.startsWith(".") || msg.content.startsWith(">");

    return msg.author.bot || isCommand;
    });

更正您的过滤器逻辑应该可以修复您的 DiscordAPIError异常(exception),但为了确保不会发出错误的调用,您应该保护 bulkDelete调用:

if (botMessages.length > 1) {
message.channel.bulkDelete(botMessages);
} else if (botMessages.length) {
botMessages[0].delete();
} else {
// nothing to delete
}

关于javascript - Discord.js//过滤消息startsWith并解决bulkDelete的DiscordAPIError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47952522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com