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
325 views
in Technique[技术] by (71.8m points)

javascript - Fetch more than 100 messages

I'm trying to figure out a way to use loops to get old messages on discord using fetchMesasges() and before. I'd like to get more than the 100 limit using a loop but I cannot figure it out, and every post I can find only discuss how to use loops to DELETE more than the 100 limit, I just need to retrieve them.

I'm new to coding and javascript in particular so I'm hoping someone can give me a nudge in the right direction.

Here is the only way I could manage to retrieve messages that are farther than 100 back(after many failed attempts at using loops):

channel.fetchMessages({ limit: 100 })
    .then(msg => {
        let toBeArray = msg;
        let firstLastPost = toBeArray.last().id;

        receivedMessage.channel
            .fetchMessages({ limit: 100, before: firstLastPost })
            .then(msg => {
                let secondToBeArray = msg;
                let secondLastPost = secondToBeArray.last().id;

                receivedMessage.channel
                    .fetchMessages({ limit: 100, before: secondLastPost })
                    .then(msg => {
                        let thirdArray = msg;
                        let thirdLastPost = thirdArray.last().id;

                        receivedMessage.channel
                            .fetchMessages({ limit: 100, before: thirdLastPost })
                            .then(msg => {
                                let fourthArray = msg;
                            });
                    });
            });
    });
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

What you can do is use an async/await function and a loop to make sequntial requests

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

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

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

        if (messages.size != 100 || sum_messages >= 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

...