[英]Purge messages that contain a certain string discord.js
我是新來的JavaScript,並reccently一直與不和諧API稱為擺弄周圍discord.js 。 我想在我的機器人程序中執行一個命令,該命令可以清除通道中的所有消息, 除非它包含certian字符串或表情符號, 並且由certian人編寫。 有人知道我該怎么做嗎? 我.bulkDelete()
方法,但是沒有辦法告訴它不要刪除某些包含certian字符串的消息。
編輯:我看過這篇文章: 搜索給定的不和諧頻道,查找所有滿足條件的郵件並刪除 ,但是這樣做與我想要的相反; 該帖子是,如果消息中有certian關鍵字,則該帖子將被刪除。
讓我們逐步解決問題。
要從通道收集Message的集合 ,請使用TextBasedChannel.fetchMessages()
方法。
使用Collection.filter()
,您只能返回Collection中滿足特定條件的元素。
您可以通過多種方式檢查消息是否包含字符串,但最簡單的方法可能是Message.content
和String.includes()
的組合。
可以通過Message.author
屬性引用消息的發件人。 要針對另一個用戶檢查作者,您應該比較他們的ID(由User.id
返回)。
在filter方法的謂詞函數中,“除非”將轉換為邏輯NOT運算符 !
。 我們可以把它放在一組條件之前,所以,如果他們得到滿足,操作員將返回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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.