Hi I'm trying to delete messages that are 7 days old I'm using cron to schedule when this should happen. Here in my code I'm trying to fetch messages from a channel called log_channel then comparing the message timestamps to const days = moment().add(7, 'd'); However I'm stuck at the if statement if (msgs - days) as this does not seem to return anything.
Here is my code for reference:
const cron = require('node-cron');
const moment = require('moment');
module.exports = new Event("ready", client => {
try{
const log_channel = client.channels.cache.find(c => c.name == "log")
cron.schedule("0 18 22 * * *", function(){
console.log("Attempting to purge log messages...");
const days = moment().add(7, 'd'); // use moment the set how many days to compare timestamps with //
log_channel.messages.fetch({ limit: 100 }).then(messages => {
const msgs = Date.now(messages.createdTimestamp)
if (msgs < days){
log_channel.bulkDelete(100)
console.log("messages deleted")
}
})
})
First of all, I noticed your function wasn't an asynchronous function. We need to use a asynchronous function because we'll be using asynchronous, promise-based behavior your code. log_channel.messages.fetch should be await log_channel.messages.fetch According to the Message#fetch() docs The fetch() method in this case simply returns asynchronous message object. Promise.
The next part is that you missed out ForEach(), forEach() executes the callbackFn function once for each array element.
Finally, you are also comparing the timestamp (a snowflake) with a moment object which will not work and the reason your if doesn't return true. If you want to get messages 7 days prior you can do something like this moment.utc(msg.createdTimestamp).add( -7, 'd') this will return all timestamps 7 days prior the last 100 messages. Note that Discord API limits you to 14 days so keep that in mind.
cron.schedule("* 18 22 * * *", async function(){
console.log("Attempting to purge mod log messages...");
await log_channel.messages.fetch({ limit: 100 })
.then(messages => {
messages.forEach(msg => {
const timestamp = moment.utc(msg.createdTimestamp).add( -7, 'd');
if (timestamp) {
log_channel.bulkDelete(5);
} else {
return;
}
})