D. *_*ton 7 javascript node.js discord discord.js
我试图找出一种方法来使用循环来获取使用fetchMesasges()和之前不和谐的旧消息。我想使用循环获得超过 100 个限制,但我无法弄清楚,我能找到的每篇文章都只讨论如何使用循环删除超过 100 个限制,我只需要检索它们。
我是编码和 javascript 的新手,所以我希望有人能给我一个正确的方向。
这是我能够设法检索超过 100 条消息的唯一方法(在多次尝试使用循环失败后):
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;
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
您可以做的是使用async/await 函数和循环来发出顺序请求
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;
}
Run Code Online (Sandbox Code Playgroud)