我正在尝试编写代码,以检查通道中的所有消息是否包含某些单词,如果包含某些单词,则将其删除。像这样:
if(msg.content.startsWith(prefix+'clean') {
let check = msg.content.split(prefix+'clean')[1]; // Condition, in this case if it containts a certain string
msg.channel.fetchMessages().then(msgs => { // Get messages to check
let msglog = msgs.array() // Make an array with all the messages fetched
for(var i = 0; i < msglog.size; i++) { // Loop to check all messages in array
if (check in msglog[i]) {
// Code to delete that message
};
};
});
};
我知道这不会检查整个频道,而只会检查最近的50条消息,但是我不知道如何检查整个频道,因此在我确定如何做之前将如此。
但是什么代码将删除通过检查的消息?还是我可以采用其他方式?
编辑:
似乎我还不够清楚,所以假设某个频道进行了以下对话:
人员A:嗨,大家好!
乙:嗨
人员C:再见
假设我要通过我的机器人删除其中所有带有“ Hi”的消息,该怎么办?注意:我不希望在邮件发送后立即删除它,我只想在要删除时删除它。
答案 0 :(得分:1)
好吧,这是我意识到fetchMessages()的2周限制后解决问题的方法
else if(msg.content.startsWith(`${prefix}clean`}) { // Check for command
let check = msg.content.split(`${prefix}clean`)[1] // Defines a check
msg.channel.fetchMessages({ limit: 100 }).then(msgs => { // Fetches the last 100 messages of the channel were the command was given
const msgstodelete = msgs.filter(del => del.content.includes(check)) // Filters the messages according to the check
msg.delete() // Deletes the original message with the command
for (var i = 0; i<Array.from(msgstodelete.keys()).length; i++) {
msg.channel.fetchMessage(Array.from(msgstodelete.keys())[i]).then(deldel => deldel.delete())
} // Loop to delete all messages that passed the filter
})
}
答案 1 :(得分:0)
bulkDelete函数会删除给定的消息,这些消息要早于两周。
if(msg.content.startsWith(prefix+'clean') {
let check = msg.content.split(prefix+'clean')[1]; // Condition, in this case if it containts a certain string
msg.channel.fetchMessages().then(msgs => { // Get messages to check
let msgDel = msgs.filter(msgss => msgss.content.includes(check)) // Finds all messages with 'check'
msg.channel.bulkDelete(msgDel) // Deletes all messages that got found
});
};
要删除超过2周的邮件,您必须手动遍历邮件以将其删除:
async function deleteReturnLast(chan, option, prevMsg, cond) {
return chan.fetchMessages(option)
.then(async msgs => {
if (msgs.size === 0){
if (cond(prevMsg)) {
prevMsg.delete()
.then(d => console.log('last message deleted: ' + d.content))
.catch(err => console.log('ERR>>', err, prevMsg.content, option.before)); }
return prevMsg;
};
let last = msgs.last();
for (const[id, msg] of msgs) {
let tmp = (id === last.id) ? prevMsg : msg;
if (cond(tmp)) {
tmp.delete()
.then(d => console.log('Message deleted: ' + d.content))
.catch(err => console.log('ERR>>', err));
}
};
return last;
})
.catch(err => console.log('ERR>>', err));
}
function cond(msg) {
return !msg.content.includes('a');
}
client.on('message', async function(msg) {
let chan = msg.channel;
let last = chan.lastMessage;
while (last !== (last = await deleteReturnLast(chan, {limit: 2, before: last.id}, last, cond))){
};
});