Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

node.js - Function that gets past messages stopped working. Any way to fix?

I got this function from another stackoverflow question. I fixed it to work with Discord.js v12 by changing channel.fetchMessages to channel.messages.fetch. The function worked at first and everything was fine, but then one time when I started up my program it started showing this error: "TypeError: Cannot read property 'id' of undefined" This error occurs at line 55 which is last_id = messages.last().id; I did not change the function at all and it just stopped working. Any ideas?

    async function lots_of_messages_getter(channel, limit = 6000) {
        const sum_messages = [];
        let last_id;

        while (true) {
            const options = { limit: 100 };
            if (last_id) {
                options.before = last_id;
            }

            const messages = await channel.messages.fetch(options);
            sum_messages.push(...messages.array());
            last_id = messages.last().id;

            if (messages.size != 100 || sum_messages >= limit) {
                break;
            }
        }

        return sum_messages;
    }
question from:https://stackoverflow.com/questions/65934662/function-that-gets-past-messages-stopped-working-any-way-to-fix

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

becuase sum_messages will never be greater or same as limit because it's not a number, it must be sum_messages.length and a check after getting the messages if(messages.size === 0) would also not hurt

async function lots_of_messages_getter(channel, limit = 6000) {
    const sum_messages = [];
    let last_id;

    while (true) {
        const options = { limit: 100 };
        if (last_id) {
            options.before = last_id;
        }

        const messages = await channel.messages.fetch(options);
        if (messages.size === 0) {
            break;
        }
        sum_messages.push(...messages.array());
        last_id = messages.last().id;

        if (messages.size != 100 || sum_messages.length >= limit) {
            break;
        }
    }

    return sum_messages;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...