无法将消息时间戳与 x 天数进行比较

cannot compare message timestamp with x amount of days

您好,我正在尝试删除 7 天前的消息,我正在使用 cron 来安排何时发生。在我的代码中,我试图从一个名为 log_channel 的频道获取消息,然后将消息时间戳与 const days = moment().add(7, 'd'); 进行比较,但是我被困在 if 语句 if (msgs - days) 上,因为这似乎不是return 任何事情。

这是我的代码供参考:

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")
            }
            
        })
    })

首先,我注意到您的函数不是异步函数。我们需要使用异步函数,因为我们将在您的代码中使用异步的、基于承诺的行为。 log_channel.messages.fetch 应该是 await log_channel.messages.fetch 根据 Message#fetch() docs 在这种情况下,fetch() 方法只是 returns 异步消息对象。答应。

下一部分是你遗漏的ForEach(),forEach() 为每个数组元素执行一次 callbackFn 函数。

最后,您还将时间戳(雪花)与无效的时刻对象进行比较,这也是您的 if 不 return 正确的原因。如果你想在 7 天前收到消息,你可以这样做 moment.utc(msg.createdTimestamp).add( -7, 'd') 这将 return 所有时间戳都在最后 100 条消息之前的 7 天。请注意,Discord API 将您限制为 14 天,因此请记住这一点。

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;
                }

            })