提问者:小点点

获取超过100条消息


我正在尝试找到一种方法,使用fetchmesasges()和之前使用循环获取discord上的旧消息。我想获得超过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;
                            });
                    });
            });
    });

共2个答案

匿名用户

您可以使用一个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;
}

匿名用户

使用discord.js v11.5.1和Typescript,这对我来说是可行的。这是Jason帖子的更新版本。

我使用这个方法的原因是:DiscordAPI的最大取消息限制为100,并且不推荐使用的textChannel#fetchMessages()方法已不复存在。

我将它更新为使用TextChannel#Messages对象的fetch(options?:ChannelLogqueryOptions,cache?:boolean)方法来获取100条或更少消息的集合。

null

async function getMessages(channel: TextChannel, limit: number = 100): Promise<Message[]> {
  let out: Message[] = []
  if (limit <= 100) {
    let messages: Collection < string, Message > = await channel.messages.fetch({ limit: limit })
    out.push(...messages.array())
  } else {
    let rounds = (limit / 100) + (limit % 100 ? 1 : 0)
    let last_id: string = ""
    for (let x = 0; x < rounds; x++) {
      const options: ChannelLogsQueryOptions = {
        limit: 100
      }
      if (last_id.length > 0) {
        options.before = last_id
      }
      const messages: Collection < string, Message > = await channel.messages.fetch(options)
      out.push(...messages.array())
      last_id = messages.array()[(messages.array().length - 1)].id
    }
  }
  return out
}