gpt4 book ai didi

javascript - 清除包含特定字符串的消息discord.js

转载 作者:行者123 更新时间:2023-12-02 23:00:08 25 4
gpt4 key购买 nike

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

编辑:我看过这篇文章:Search a given discord channel for all messages that satisfies the condition and delete ,但它的作用与我想要的相反;该帖子是如果消息中存在某个关键字,它将被删除。

最佳答案

让我们一步步找到解决方案。

  1. 收集CollectionMessage来自 channel 的,请使用 TextBasedChannel.fetchMessages()方法。

  2. Collection.filter() ,您只能返回 Collection 中满足特定条件的元素。

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

  4. 消息的发送者可以通过 Message.author 引用。属性(property)。要检查作者与其他用户,您应该比较他们的 ID(由 User.id 返回) .

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

到目前为止将其结合在一起......

channel.fetchMessages(...)
.then(fetchedMessages => {
const messagesToDelete = fetchedMessages.filter(msg => !(msg.author.id === 'someID' && msg.content.includes('keep')));
...
})
.catch(console.error);
  • 要批量删除消息,您可以使用 TextChannel.bulkDelete()方法,正如您所发现的。
  • 删除正确的消息后,您可以根据需要添加回复,使用 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 .

    关于javascript - 清除包含特定字符串的消息discord.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57827514/

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