You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Discord.js获取服务器所有Thread数据并解决数量限制

解决Discord.js获取服务器全量线程数据的问题

问题说明

我是Discord.js新手,想开发机器人把服务器里所有Thread的名称、创建成员、创建时间戳打印到控制台。之前试过从审计日志拿数据,但审计日志45天后会删除,没法拿到今年以来的全部Thread数据。现在用缓存只能输出5-10条,审计日志最多100条,都满足不了需求,当前代码如下:

const { Client, GatewayIntentBits } = require('discord.js'); 
const client = new Client({ 
    intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages, 
    GatewayIntentBits.MessageContent
] 
});

client.on('ready', () =>{
    console.log(`${client.user.tag}` + ' is online!');
  })

    // should be more specific with message, (so it can be like "!audit")
    client.on('messageCreate',  async function (message) {
        const fetchedLogs = await message.guild.fetchAuditLogs({
            limit: 100,
            type: 110, // THREAD_CREATE
            action_type: 110 // THREAD_CREATE
        });

        //const fetchedChannels = await message.guild.channels.fetch();
    
        // Checks which command was done; message.content gets the message that the user sent to trigger this:
        if(message.content === "!test"){
            // get the guild
            const guild = client.guilds.cache.get("694998889358557297");
            // filter all the channels
            const threads = guild.channels.cache.sort((a, b) => a.createdAt - b.createdAt).filter(x => x.isThread());
    
              // Title of the Thread
              const threadTitle = threads.map(info => `${info.name}`);
    
              // ID of the Thread Creator
              const threadUser = threads.map(info => `${info.ownerId}`);
    
              // Date the Thread was Created
              const threadDate = threads.map(info => `${info.createdAt}`);
    
              // ALL INFO, if you want an array just remove the ".join()"
              const threadInfo = threads.map(info => `Name: ${info.name}\nCreator: ${info.ownerId}\nCreated at: ${info.createdAt}\n`).join("");
              console.log(threadTitle);
              //console.log(threadUser);
              //console.log(threadDate);
              //console.log(threadInfo);
          } 
          else {
                console.log ("target doesn't exist");
          }
    });

解决方案

缓存只存储最近活跃的线程,要获取全量数据(包括归档线程),需要主动遍历服务器所有支持线程的频道,调用fetchThreads()接口获取每个频道下的所有线程:

修改后的代码

const { Client, GatewayIntentBits, ChannelType } = require('discord.js'); 
const client = new Client({ 
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages, 
        GatewayIntentBits.MessageContent
    ] 
});

client.on('ready', () => {
    console.log(`${client.user.tag} is online!`);
});

client.on('messageCreate', async (message) => {
    if (message.content !== "!test") return;

    const guild = client.guilds.cache.get("694998889358557297");
    if (!guild) {
        console.log("目标服务器不存在");
        return;
    }

    // 获取服务器所有频道
    const allChannels = await guild.channels.fetch();
    const allThreads = [];

    // 遍历每个支持线程的频道(文本频道、论坛频道)
    for (const channel of allChannels.values()) {
        if ([ChannelType.GuildText, ChannelType.GuildForum].includes(channel.type)) {
            try {
                // 获取该频道下的所有线程(包括归档的)
                const fetchedThreads = await channel.threads.fetch({
                    fetchAll: true, // 关键:获取所有线程,不止活跃的
                });

                // 把线程数据加入总列表
                fetchedThreads.threads.forEach(thread => {
                    allThreads.push(thread);
                });
                fetchedThreads.archived.forEach(thread => {
                    allThreads.push(thread);
                });
            } catch (err) {
                console.log(`获取频道 ${channel.name} 的线程失败:`, err);
            }
        }
    }

    // 按创建时间排序
    allThreads.sort((a, b) => a.createdAt - b.createdAt);

    // 整理并打印线程信息
    const threadInfo = allThreads.map(thread => 
        `名称: ${thread.name}\n创建者ID: ${thread.ownerId}\n创建时间: ${thread.createdAt.toLocaleString()}\n`
    ).join("-------------------------\n");

    console.log("服务器所有线程信息:\n", threadInfo);
});

// 记得替换成你的机器人Token
client.login('你的机器人Token');

关键说明

  • fetchAll: true:这个参数会让接口获取频道下所有线程,包括已归档的,而不是只返回活跃线程
  • 遍历支持线程的频道:只有文本频道(GuildText)和论坛频道(GuildForum)能创建线程,所以只需要处理这两类频道
  • 权限要求:机器人需要拥有ManageThreads、ViewChannel权限,才能正常获取线程数据
  • 筛选今年的线程:如果只需要今年创建的线程,可在收集后添加过滤逻辑:
    const thisYearThreads = allThreads.filter(thread => thread.createdAt.getFullYear() === new Date().getFullYear());
    

内容的提问来源于stack exchange,提问作者Eevee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 07:48:15