當我嘗試將PNG圖像上載到Node中的Twit庫時,出現錯誤。如何在Node.js中將圖像發佈到Twitter
我想在Node.js中生成一個隨機RGB顏色的Twitter機器人,創建一個這種顏色的圖片,併發布它。在another question的幫助下,我現在知道如何在Node中創建一個PNG畫布,但我不知道如何將它放入Twit庫。使用下面的代碼,我得到一個錯誤:44, message: 'media_ids parameter is invalid.'
似乎來自Twitter API。
Twitter官方文件說:
You may either upload the raw binary of the file or its base64-encoded contents.
我不知道該怎麼做這一點。如何讓Twitter API將我的畫布作爲PNG圖像接受?
我的代碼是:
var Twit = require('twit')
var Canvas = require('canvas');
var Image = Canvas.Image;
var T = new Twit({
consumer_key: '###'
, consumer_secret: '###'
, access_token: '###'
, access_token_secret: '###'
})
//Generate the canvas
var canvas = new Canvas(800, 800);
var context = canvas.getContext('2d');
function tweet() {
//Generate a random colour
var r = Math.floor((Math.random() * 256));
var g = Math.floor((Math.random() * 256));
var b = Math.floor((Math.random() * 256));
var color = "rgb("+r+","+g+","+b+")";
// draw box
context.beginPath();
context.moveTo(0, 00);
context.lineTo(0, 800);
context.lineTo(800, 800);
context.lineTo(800, 0);
context.closePath();
context.lineWidth = 5;
context.fillStyle = color;
context.fill();
var fs = require('fs')
, out = fs.createWriteStream(__dirname + '/text.png')
, stream = canvas.pngStream();
var dataUrl = canvas.pngStream().pipe(out);
//I'm not sure if this bit is really necessary
// first we must post the media to Twitter
T.post('media/upload', { media_data: canvas.toBuffer() }, function (err, data, response) {
// now we can reference the media and post a tweet (media will attach to the tweet)
var mediaIdStr = data.media_id_string
var params = { status: color, media_ids: [mediaIdStr] }
T.post('statuses/update', params, function (err, data, response) {
console.log(data)
})
})
}
setTimeout(tweet, 30000);
感謝@chrki我的機器人工程!如果任何人有興趣,你可以[在Twitter上找到它](https://twitter.com/rgb_bot)。謝謝你的幫助! –