简体   繁体   中英

How can I get the last 1000 messages sent by a certain user?

I've tried channel.fetchMessages() , but the limit is 100 messages. It's for a bot supposed to simulate users using machine learning.

Taking into account what @jsejcksn is mentioning about the rate limits and how you can fetch the channel messages, here is a working implementation of it:

Example Implementation Run in Fusebit
let messagesCounter = 0;
const channel = await findChannel(discordClient);
// Channel messages are limited up to 100 messages per request.
const channelMessages = await getMessages(discordClient, channel.id);
// Accumulate fetched messages
let fetchedMessages = channelMessages;
// Fetch discord until you get MAX_NUMBER_OF_MESSAGES (1000)
let newMessages = channelMessages;
// If messages are returned, keep getting more until having 1000 messages
while (newMessages.length && messagesCounter < MAX_NUMBER_OF_MESSAGES) {
  // Keep a counter to prevent an infinite loop
  messagesCounter += channelMessages.length;
  // Using the before filter, you can get oldest messages by using the last returned message
  const oldestMessage = newMessages[channelMessages.length - 1];
  newMessages = await getMessages(discordClient, channel.id, oldestMessage.id);
  fetchedMessages = fetchedMessages.concat(newMessages);
}
// Return all the channel messages (up to 1000 messages!)
ctx.body = `There are ${fetchedMessages.length} messages in the ${DISCORD_CHANNEL_NAME} channel`;

Based on the returned messages, you can easily filter by user id

The limit of returned messages is 100 , with the default being 50 . See the actual API docs for details.

By default, you get the most recent messages, but you can specify additional query criteria when fetching messages . You'll need to repeat your fetch requests, adjusting the query criteria each time, in order to collect successively older messages. After each request, you can analyze what you've collected so far to determine if you need to keep fetching or not.

Beware of the rate limits .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM