我正在尝试通过某个Discord频道发送图片将其上传到Twitter。这是我正在使用的代码:
var number = 0;
function downloadJPG(url) { //This function downloads the image in jpg format
request.get(url).on('error', console.error).pipe(fs.createWriteStream('image.jpg'));
}
if (message.attachments.every(attachIsImageJPG)) {
downloadJPG(message.attachments.first().url);
var imageToPostJPG = fs.readFileSync('image.jpg');
client.post('media/upload', {media: imageToPostJPG}, function(err, data, res) {
if (err) console.log(err);
console.log(data);
number = number+1
client.post('statuses/update', {status: 'Success Cop #'+number, media_ids: data.media_id_string}, function(err, params, res) {
if (err) console.log(err);
console.log(params);
});
});
}
该图片应该以状态上传到Twitter,但是只有状态才能上传,这就是我在控制台中看到的内容:
Error: HTTP Error: 400 Bad Request at Request._callback (C:\Users\Silvano\Desktop\Twitter\node_modules\twitter\lib\twitter.js:221:9) at Request.self.callback (C:\Users\Silvano\Desktop\Twitter\node_modules\request\request.js:185:22) at Request.emit (events.js:200:13) at Request.<anonymous> (C:\Users\Silvano\Desktop\Twitter\node_modules\request\request.js:1161:10) at Request.emit (events.js:200:13) at IncomingMessage.<anonymous> (C:\Users\Silvano\Desktop\Twitter\node_modules\request\request.js:1083:12) at Object.onceWrapper (events.js:288:20) at IncomingMessage.emit (events.js:205:15) at endReadableNT (_stream_readable.js:1154:12) at processTicksAndRejections (internal/process/task_queues.js:84:9) { request: '/1.1/media/upload.json', error: 'media type unrecognized.' }
我该如何解决此错误并使图像也上传?
答案 0 :(得分:2)
我认为问题在于流必须在readFileSync
读取之前完成。
// modified to indicate completion by calling callback
function downloadJPG(url, callback) { //This function downloads the image in jpg format
let stream = request.get(url).on('error', console.error).pipe(fs.createWriteStream('image.jpg'));
stream.on('finish', callback);
}
// modified to do the twtr work in the callback
if (message.attachments.every(attachIsImageJPG)) {
downloadJPG(message.attachments.first().url, function() {
var imageToPostJPG = fs.readFileSync('image.jpg');
client.post('media/upload', {media: imageToPostJPG}, function(err, data, res) {
if (err) console.log(err);
console.log(data);
number = number+1
client.post('statuses/update', {status: 'Success Cop #'+number, media_ids: data.media_id_string}, function(err, params, res) {
if (err) console.log(err);
console.log(params);
});
});
});
}
旁注:我发现在经过一两个步骤之后,回调样式很难编写和读取,并且允诺是可取的。