繁体   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