提取超过100条消息

时间:2019-03-14 00:26:28

标签: javascript node.js discord discord.js

我正在尝试找到一种使用循环的方法,以使用fetchMesasges() before 在不和谐的情况下获取旧消息。我想使用循环获得超过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 个答案:

答案 0 :(得分:1)

您可以做的是使用async/await function和循环来发出顺序请求

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;
}

答案 1 :(得分:1)

这适用于我使用discord.js v 11.5.1和TypeScript。它是Jason's post的更新版本。

我之所以使用它,是因为:DiscordAPI的最大限制为100个用于提取消息,并且已弃用的TextChannel#fetchMessages()方法不再存在。

我对其进行了更新,以使用TextChannel#messages对象的fetch(options ?: ChannelLogsQueryOptions,cache ?: boolean)方法来获取100条以下消息的集合。

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
}