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

上传文件至Discord论坛线程时遇TypeError错误求助

Discord机器人上传CSV到论坛线程的错误修复

错误原因分析

  1. 初始错误TypeError: this.options.files?.map is not a function
    Discord.js的message.files参数要求传入数组类型,你最初直接传了字符串fileName,数组的map方法无法在字符串上调用,导致报错。

  2. 修改为[dirPath/fileName]后仍出错

  • 路径拼接语法错误,应该用模板字符串${dirPath}/${fileName}或path.join处理跨系统路径分隔符问题;
  • fileName是字符串类型,你用fileName.name获取线程名称完全错误,直接使用fileName即可。

其他需修复的问题

  • fs模块在函数内部重复导入,应移至代码顶部;
  • 通过频道名称查找论坛频道易出错,建议优先用频道ID,同时需判断是否找到频道;
  • threads.create是异步方法,未加await会导致并发操作异常;
  • 存在未使用的冗余变量(如thread、GuildForumMessageRequired);
  • 最终的console.log(thread.name)会报错,因为thread只是字符串ID,无name属性。

修复后的完整代码

const fs = require('fs');
const path = require('path');

client.on('messageCreate', async message => {
    if (message.author.bot) return;

    if (message.content.startsWith('!upload')) {
        const [_, dirPath] = message.content.split(' ');
        
        // 校验是否传入目录路径
        if (!dirPath) {
            return message.reply('请指定要上传的目录路径!');
        }

        // 校验目录有效性
        if (!fs.existsSync(dirPath) || !fs.lstatSync(dirPath).isDirectory()) {
            return message.reply('指定的目录不存在或不是有效目录!');
        }

        // 查找目标论坛频道(建议替换成频道ID,如channel.id === '你的频道ID')
        const forumChannel = message.guild.channels.cache.find(channel => channel.name === 'test');
        if (!forumChannel) {
            return message.reply('未找到名为"test"的论坛频道!');
        }

        // 获取目录下所有CSV文件
        const csvFiles = fs.readdirSync(dirPath).filter(file => file.endsWith('.csv'));
        if (csvFiles.length === 0) {
            return message.reply('指定目录下没有CSV文件!');
        }

        // 循环创建线程并上传文件
        for (const fileName of csvFiles) {
            try {
                const filePath = path.join(dirPath, fileName);
                const newThread = await forumChannel.threads.create({
                    name: fileName,
                    autoArchiveDuration: 60,
                    type: 'GUILD_PUBLIC_THREAD',
                    message: {
                        content: `新线程已创建,附带文件:`,
                        files: [filePath]
                    }
                });
                console.log(`已上传文件 ${fileName} 到线程 ${newThread.name}`);
            } catch (error) {
                console.error(`上传文件 ${fileName} 失败:`, error);
                message.reply(`文件 ${fileName} 上传失败,请查看控制台日志。`);
            }
        }

        message.reply(`所有CSV文件上传完成,共处理 ${csvFiles.length} 个文件。`);
    }
});

关键修复说明

  • 使用path.join拼接文件路径,避免Windows/Linux路径分隔符冲突;
  • files参数传入包含完整路径的数组,符合Discord.js的参数要求;
  • 为threads.create添加await,确保异步操作顺序执行;
  • 增加try/catch捕获单个文件的上传错误,提升代码健壮性;
  • 完善前置校验逻辑,提前拦截无效输入或异常场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:42:51