【问题标题】:Purge messages that contain a certain string discord.js清除包含特定字符串 discord.js 的消息
【发布时间】:2020-01-09 15:45:29
【问题描述】:

我是 javascript 新手,最近一直在修改名为 discord.js 的不和谐 API。我想在我的机器人中创建一个可以清除频道中所有消息的命令,除非它包含一个特定的字符串或表情符号,并且它是由一个特定的人。有谁知道我该怎么做?我查看了.bulkDelete() 方法,但没有办法告诉它不要删除一些包含特定字符串的消息。

编辑:我看过这篇文章:Search a given discord channel for all messages that satisfies the condition and delete,但这与我想要的相反;该帖子是如果消息中有特定关键字,则将其删除。

【问题讨论】:

    标签: javascript discord discord.js


    【解决方案1】:

    让我们一步一步地解决问题。

    1. 要从频道中收集 CollectionMessages,请使用 TextBasedChannel.fetchMessages() 方法。

    2. 使用Collection.filter(),您可以只返回集合中满足特定条件的元素。

    3. 您可以通过多种方式检查消息是否包含字符串,但最简单的方法可能是Message.contentString.includes() 的组合。

    4. 可以通过Message.author 属性引用消息的发件人。要将作者与其他用户核对,您应该比较他们的 ID,由 User.id 返回。

    5. 在过滤方法的谓词函数中,“除非”将转换为logical NOT operator!。我们可以将它放在一组条件之前,以便如果满足它们,则运算符将返回false。这样,符合您指定约束的消息将从返回的集合中排除

    到目前为止,将这些联系在一起......

    channel.fetchMessages(...)
      .then(fetchedMessages => {
        const messagesToDelete = fetchedMessages.filter(msg => !(msg.author.id === 'someID' && msg.content.includes('keep')));
        ...
      })
      .catch(console.error);
    
    1. 如您所见,要批量删除邮件,您可以使用TextChannel.bulkDelete() 方法。
    2. 删除正确的消息后,您可以根据需要添加回复,使用TextBasedChannel.send()

    总之……

    // Depending on your use case...
    // const channel = message.channel;
    // const channel = client.channels.get('someID');
    
    channel.fetchMessages({ limit: 100 })
    //                      ^^^^^^^^^^
    // You can only bulk delete up to 100 messages per call.
      .then(fetchedMessages => {
        const messagesToDelete = fetchedMessages.filter(msg => !(msg.author.id === 'someID' && msg.content.includes('keep')));
    
        return channel.bulkDelete(messagesToDelete, true);
    //                                              ^^^^
    //        The second parameter here represents whether or not to automatically skip messages
    //               that are too old to delete (14 days old) due to API restrictions.
      })
      .then(deletedMessages => channel.send(`Deleted **${deletedMessages.size}** message${deletedMessages.size !== 1 ? 's' : ''}.`))
    //                                                                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    //                                                                This template literal will add an 's' if the word 'message' should be plural.
      .catch(console.error);
    

    为了更好地保持代码流畅,请考虑使用async/await

    【讨论】:

    • 感谢您的解释!我现在就试试这个。
    猜你喜欢
    • 2016-10-30
    • 1970-01-01
    • 2021-04-21
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 2019-11-11
    相关资源
    最近更新 更多