【问题标题】:Purge messages that contain a certain string discord.js清除包含特定字符串 discord.js 的消息
【发布时间】:2020-01-09 15:45:29
【问题描述】:
【问题讨论】:
标签:
javascript
discord
discord.js
【解决方案1】:
让我们一步一步地解决问题。
要从频道中收集 Collection 或 Messages,请使用 TextBasedChannel.fetchMessages() 方法。
使用Collection.filter(),您可以只返回集合中满足特定条件的元素。
您可以通过多种方式检查消息是否包含字符串,但最简单的方法可能是Message.content 和String.includes() 的组合。
可以通过Message.author 属性引用消息的发件人。要将作者与其他用户核对,您应该比较他们的 ID,由 User.id 返回。
在过滤方法的谓词函数中,“除非”将转换为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。