簡體   English   中英

如何在Node.js中將圖像發布到Twitter

[英]How to post an image to Twitter in Node.js

當我嘗試將PNG圖像上傳到Node中的Twit庫時,出現錯誤。

我正在嘗試在Node.js中創建一個生成隨機rgb顏色的Twitter機器人,創建這種顏色的圖片並發布它。 另一個問題的幫助下,我現在知道如何在Node中創建一個PNG作為PNG,但我不知道如何將它放入Twit庫中。 使用下面的代碼我收到一個錯誤: 44, message: 'media_ids parameter is invalid.' 它似乎來自Twitter API。

Twitter的官方文檔說:

您可以上傳文件的原始二進制文件或其base64編碼的內容。

我不知道該怎么做。 如何讓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);

Twitter 文檔說這是關於使用media/upload

參數

media - 正在上載的原始二進制文件內容。 不能與media_data一起使用。

media_data - 正在上載的base64編碼文件內容。 不能與media一起使用。

您在此處向media_data參數提供原始數據: media_data: canvas.toBuffer()

要修復此上傳圖像base64編碼:

T.post('media/upload', { media_data: canvas.toBuffer().toString('base64') }, function (err, data, response) {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM