DiscordJS 获取超过 100 条消息

时间:2021-02-19 17:03:49

标签: javascript node.js discord discord.js

我正在尝试在 DiscordJS 中获取 100 多条消息。我找到了此代码 here,但它不起作用:

const addArg = (g, f) => (...args) => 
  g (...args, f (...args))

const f = (a, b) => `f (${a}, ${b})`
const g = (a, b, d) => `g (${a}, ${b}, ${d})`

const h = addArg (g, f) 

console .log (h ('a', 'b'))

它给了我这个错误:

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.fetch(options); sum_messages.push(...messages.array()); last_id = messages.last().id; if (messages.size != 100 || sum_messages >= limit) { break; } } return sum_messages; } client.on("message", async message => { const channel = client.channels.cache.get("12345"); if (message.content.startsWith(prefix+"random")){ console.log(lots_of_messages_getter()); } });

如何解决这个问题?我对 Node.js 有点陌生。

2 个答案:

答案 0 :(得分:0)

以下适用于 discord.js v12。与您从中获取代码的 older answers 不同,它返回一个 collection,因此您可以使用 .first().last().find()、{{1 }}、.get()

.filter()

示例用法:

async function fetchMore(channel, limit = 250) {
  if (!channel) {
    throw new Error(`Expected channel, got ${typeof channel}.`);
  }
  if (limit <= 100) {
    return channel.messages.fetch({ limit });
  }

  let collection = new Collection();
  let lastId = null;
  let options = {};
  let remaining = limit;

  while (remaining > 0) {
    options.limit = remaining > 100 ? 100 : remaining;
    remaining = remaining > 100 ? remaining - 100 : 0;

    if (lastId) {
      options.before = lastId;
    }

    let messages = await channel.messages.fetch(options);

    if (!messages.last()) {
      break;
    }

    collection = collection.concat(messages);
    lastId = messages.last().id;
  }

  return collection;
}

答案 1 :(得分:-1)

如果您的程序在 nodeJS 上运行,您可能需要在文件顶部使用 node fetch string

相关问题