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

Discord.js 14.1.2:如何获取服务器所有/指定频道的归档线程

解决Discord.js 14获取服务器所有/指定频道归档线程的问题

指定频道获取归档线程

不用依赖message.channel,直接从服务器中获取目标文本频道就能调用线程查询方法。具体实现如下:

  1. 通过message.guild直接获取当前服务器实例(不用手动写服务器ID更方便)
  2. 用目标频道ID拿到频道实例,验证是否为文本/新闻频道(只有这类频道支持线程)
  3. 调用频道的threads.fetchArchived()方法获取归档线程

修改后的代码示例:

client.on('messageCreate', async function (message) {
    if (message.content === "!test") {
        const guild = message.guild;
        if (!guild) return; // 确保命令在服务器内发送

        // 替换为你要查询的目标频道ID
        const targetChannelId = "CHANNEL_ID_HERE";
        const targetChannel = guild.channels.cache.get(targetChannelId);
        
        // 检查频道是否有效
        if (!targetChannel || !targetChannel.isTextBased()) {
            console.log("指定频道不存在或非文本频道");
            return;
        }

        // 可通过type参数指定获取公开/私有线程,默认获取所有类型
        const archivedThreads = await targetChannel.threads.fetchArchived();
        console.log(`指定频道归档线程:`, archivedThreads);
    }
});

获取服务器所有频道的归档线程

需要遍历服务器内所有文本频道,逐个查询归档线程并汇总结果,同时处理可能的权限错误:

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

        // 过滤出服务器内所有支持线程的文本/新闻频道
        const textChannels = guild.channels.cache.filter(channel => channel.isTextBased());
        
        const allArchivedThreads = [];

        // 遍历频道并收集归档线程
        for (const [channelId, channel] of textChannels) {
            try {
                const archivedThreads = await channel.threads.fetchArchived();
                allArchivedThreads.push({
                    频道名称: channel.name,
                    频道ID: channelId,
                    归档线程: archivedThreads.threads // 线程集合,可按需提取具体数据
                });
                console.log(`已获取频道 ${channel.name} 的归档线程`);
            } catch (err) {
                console.log(`无法获取频道 ${channel.name} 的归档线程:${err.message}`);
            }
        }

        console.log("服务器所有归档线程汇总:", allArchivedThreads);
    }
});

注意事项

  • 机器人需要拥有VIEW_CHANNEL和READ_MESSAGE_HISTORY权限,否则无法查询对应频道的归档线程
  • fetchArchived()支持传入参数,比如{ type: 'PUBLIC_THREADS' }或{ type: 'PRIVATE_THREADS' },可单独获取公开或私有归档线程
  • Discord.js 14中用isTextBased()判断文本/新闻频道,替代了旧版本的类型值判断

内容的提问来源于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 01:45:35