Discord机器人Node.js接口JSON转TXT报错TypeError求助
问题解决:将JSON数据转TXT并在Discord发送
错误原因
你调用jsonToTxt({ filePath: asa })时参数使用错误:json-to-txt的filePath参数要求传入本地JSON文件的路径字符串,但你直接把从接口获取的JSON对象asa传了进去,导致Node.js的fs模块收到不符合要求的参数,触发ERR_INVALID_ARG_TYPE错误。
解决方案
方案1:手动转换JSON为文本(无需第三方依赖)
直接用JSON.stringify()将JSON对象转为格式化字符串,写入TXT文件后发送到Discord,这是最简洁的实现方式。修改后的run函数代码如下:
run: async (client, interaction) =>{ try { const ad = interaction.options.getString('adı'); const soyad = interaction.options.getString('soyadı'); // 合并查询参数,避免拼接错误 const queryParams = new URLSearchParams({ ad, soyad, auth: 'propenthia' }); const dictResult = await request(`http://141.11.127.168/ucretsizapi/adsoyad.php?${queryParams}`); const asa = await dictResult.body.json(); // 将JSON转为格式化文本 const txtContent = JSON.stringify(asa, null, 2); // 缩进2个空格,提升可读性 const txtFilePath = './sonuclar.txt'; // 写入TXT文件 await fs.promises.writeFile(txtFilePath, txtContent, 'utf8'); // 在Discord发送文件 await interaction.reply({ content: 'Sonuçlar:', files: [txtFilePath] }); } catch (error) { console.error(error); await interaction.reply({ content: 'İşlem sırasında bir hata oluştu!', ephemeral: true }); } }
方案2:正确使用json-to-txt包(若坚持依赖该工具)
如果一定要用json-to-txt,需要先把JSON对象写入本地临时JSON文件,再让工具读取该文件转换为TXT:
run: async (client, interaction) =>{ try { const ad = interaction.options.getString('adı'); const soyad = interaction.options.getString('soyadı'); const queryParams = new URLSearchParams({ ad, soyad, auth: 'propenthia' }); const dictResult = await request(`http://141.11.127.168/ucretsizapi/adsoyad.php?${queryParams}`); const asa = await dictResult.body.json(); // 写入临时JSON文件 const tempJsonPath = './temp.json'; await fs.promises.writeFile(tempJsonPath, JSON.stringify(asa), 'utf8'); // 使用json-to-txt转换格式 jsonToTxt({ filePath: tempJsonPath, output: './sonuclar.txt' }); // 发送TXT文件到Discord await interaction.reply({ content: 'Sonuçlar:', files: ['./sonuclar.txt'] }); // 清理临时文件 await fs.promises.unlink(tempJsonPath); } catch (error) { console.error(error); await interaction.reply({ content: 'İşlem sırasında bir hata oluştu!', ephemeral: true }); } }
额外优化建议
- 异步操作优先:使用
fs.promises系列方法代替同步方法,避免阻塞机器人事件循环,提升并发处理能力。 - 错误捕获:添加
try/catch块处理网络请求、文件操作可能出现的异常,避免机器人崩溃并给用户友好提示。 - 参数校验:可以对接口返回的JSON数据做简单校验,确保数据格式符合预期再转换。
内容的提问来源于stack exchange,提问作者cdr
相关产品推荐
相关产品推荐

