我试图建立一个可以发送猫图片的Facebook聊天机器人。我使用RESTful API来获取猫图片。它们作为原始png返回。下一步也是最后一步是将该图像转换为可读流,以便Facebook Chat API可以将其作为附件发送。
我使用request.js
来抓取图片。请求文档仅提及将图像保存为文件并将文件读入stream.Readable
。我想知道是否有办法绕过该临时文件,并将图像直接传送到Facebook Chat API。
到目前为止,这是我的代码:
var request = require("request");
var stream = require("stream");
module.exports = function getCatPicture(api, threadID, body) {
var options = {
url: 'http://thecatapi.com/api/images/get?type=png',
encoding: 'base64'
}
var picStream = new stream.Readable;
request.get(options, function (error, response, body) {
picStream.push(body, 'base64');
var catPic = {
attachment: picStream
};
api.sendMessage(catPic, threadID);
return;
});
}
我收到错误:
Error in uploadAttachment Error: form-data: not implemented
Error in uploadAttachment at Readable._read (_stream_readable.js:457:22)
Error in uploadAttachment at Readable.read (_stream_readable.js:336:10)
Error in uploadAttachment at flow (_stream_readable.js:751:26)
Error in uploadAttachment at resume_ (_stream_readable.js:731:3)
Error in uploadAttachment at nextTickCallbackWith2Args (node.js:442:9)
Error in uploadAttachment at process._tickCallback (node.js:356:17)
Error in uploadAttachment { [Error: form-data: not implemented]
Error in uploadAttachment cause: [Error: form-data: not implemented],
Error in uploadAttachment isOperational: true }
答案 0 :(得分:1)
这里有一些问题:
._read()
流实例上实现Readable
的主要问题。即将推出的节点版本将有更好的错误消息。因此,目前,您可以在创建picStream._read = function(n){};
后添加picStream
。encoding: null
对象中设置options
,body
将成为回调中的Buffer
个实例。然后你就可以picStream.push(body);
。picStream.push(null);
picStream.push(body);
醇>
最后,这有点偏离主题,但当form-data
使用的基础request
模块支持许多不同类型的值时,模块会强制使用流,这有点愚蠢(包括用作文件内容的原始Buffer
实例)。