我正在尝试在 DiscordJS 中获取超过 100 条消息.我在 here 找到了这段代码,但它不起作用:
I'm trying to fetch more than 100 messages in DiscordJS. I've found this code here but it doesn't work:
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:6312) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'fetch' of undefined
如何解决这个问题?我对 Node.js 有点陌生.
How can this be fixed? I'm kinda new to Node.js.
以下适用于 discord.js v12 和 v13.与您从中获取代码的 旧答案 不同,它返回一个 collection,所以可以使用.first()、等方法.last()、.find()、.get()、.filter()等
The following works in discord.js v12 and v13. Unlike the older answers where you got your code from, it returns a collection, so you can use methods like .first(), .last(), .find(), .get(), .filter(), etc.
const { Collection } = require('discord.js');
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;
}
示例用法:
client.on('message', async (message) => {
if (message.author.bot) return;
try {
const list = await fetchMore(message.channel, 120);
console.log(
list.size,
list.filter((msg) => msg.content.includes('something')),
);
} catch (err) {
console.log(err);
}
});
这篇关于DiscordJS 获取超过 100 条消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
discord.js v12:我如何等待 DM 频道中的消息?discord.js v12: How do I await for messages in a DM channel?(discord.js v12:我如何等待 DM 频道中的消息?)
如何让我的机器人提及发出该机器人命令的人how to make my bot mention the person who gave that bot command(如何让我的机器人提及发出该机器人命令的人)
如何修复必须使用导入来加载 ES 模块 discord.jsHow to fix Must use import to load ES Module discord.js(如何修复必须使用导入来加载 ES 模块 discord.js)
如何列出来自特定服务器的所有成员?How to list all members from a specific server?(如何列出来自特定服务器的所有成员?)
Discord bot:修复“找不到 FFMPEG"Discord bot: Fix ‘FFMPEG not found’(Discord bot:修复“找不到 FFMPEG)
使用 discord.js 加入 discord 服务器时的欢迎消息Welcome message when joining discord Server using discord.js(使用 discord.js 加入 discord 服务器时的欢迎消息)