使用discord.js发送JSON文件时触发TypeError错误求助
问题:使用discord.js发送JSON文件时触发TypeError错误
我尝试用discord.js将JavaScript对象以JSON文件形式发送,但操作不像发图片那样简单。我试过用AttachmentBuilder搭配/不搭配JSON.stringify、设置/不设置文件名,代码如下:
const jsonFile = new AttachmentBuilder(JSON.stringify(data), { name: embedName + ".json", }); message.reply({ content: "Data:", files : [jsonFile]})
但无论怎么传递数据,都会触发如下错误:
TypeError: Cannot read properties of undefined (reading 'Symbol(Symbol.asyncIterator)') at DataResolver.resolveFile (C:\Users\___\node_modules\discord.js\src\util\DataResolver.js:117:24) at MessagePayload.resolveFile (C:\Users\___\node_modules\discord.js\src\structures\MessagePayload.js:260:54) at C:\Users\___\node_modules\discord.js\src\structures\MessagePayload.js:225:85 at Array.map (<anonymous>) at MessagePayload.resolveFiles (C:\Users\___\node_modules\discord.js\src\structures\MessagePayload.js:225:56) at StringSelectMenuInteraction.reply (C:\Users\___\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:109:70) at module.exports.run (C:\Users\___\interactions\StringSelectMenu\select-embed.js:38:20) at async Object.run (C:\Users\___\events\interactionCreate.js:24:11) at async SkeeBot.<anonymous> (C:\Users\___\classes\SkeeBot.js:96:11)
解决方法
问题出在AttachmentBuilder的参数类型上——它不接受直接传入JSON字符串,需要把字符串转换成Buffer(Node.js环境)或者Blob(浏览器环境)。修正后的代码如下:
const jsonString = JSON.stringify(data); const jsonBuffer = Buffer.from(jsonString); const jsonFile = new AttachmentBuilder(jsonBuffer, { name: `${embedName}.json`, }); message.reply({ content: "Data:", files: [jsonFile] });
原因是discord.js的AttachmentBuilder仅识别Buffer、Blob或本地文件路径作为文件内容来源。直接传字符串的话,内部解析逻辑无法将其处理为可迭代的文件流,因此抛出了Symbol.asyncIterator相关的错误。转换成Buffer后,discord.js就能正确解析并发送这个JSON文件了。
内容的提问来源于stack exchange,提问作者Bimo
相关产品推荐
相关产品推荐

