【发布时间】:2017-06-13 22:35:26
【问题描述】:
我正在尝试构建一个小型机器人,它根据硬编码的类别(目前)将随机 GIF 发布到 Twitter。
我正在使用 Twit 库通过 Twitter API 在 Twitter 上发帖。如何在 Twitter 上发布 GIF?
代码如下:
var twit = require('twit');
var config = require('./config');
var request = require('request');
var fs = require('fs');
var path = require('path');
const GIPHY_API_KEY = 'API-KEY';
const GIPHY_API_URL = 'http://api.giphy.com/v1/gifs/random? api_key='+GIPHY_API_KEY+'&tag=study';
var T = new twit(config);
getAndPostGifImg();
function getAndPostGifImg() {
request(GIPHY_API_URL,function (error,response,body) {
var resp = JSON.parse(body);
var img_url = resp.data.image_url;
console.log(img_url);
// post the image to twitter
postImg(img_url);
});
function postImg(img_url) {
request(img_url).pipe(fs.createWriteStream('images/imgpost.gif'));
var filename = path.join(__dirname,'/images/','imgpost.gif');
var params = { encoding: 'base64' };
var img = fs.readFileSync(filename,params);
T.post('media/upload', { media_data: img }, onUpload);
function onUpload(err,data,response) {
var id = data.media_id_string; console.log(id);
// post a tweet /hashtag along with image
var tweet = { status: 'random Study Tweet #giphyBotTweets', media_ids: [id] };
T.post('statuses/update',tweet, tweeted);
}
function tweeted(err,data,response){
if(err)
{
var errors = data.errors;
var i = 0;
for(i = 0 ; i < errors.length; i++)
console.log("Error Message(s) : "+errors[i].message);
}
else
{ console.log(data.text); }
}
}
}
提前致谢。
【问题讨论】:
-
您遇到了什么错误?你的代码哪里出错了?
-
代码显示为
null,消息显示为media type unrecognized -
我还使用了
console.log作为media_id,它显示为undefined -
代码可能在
T.post()和readFileAsync()方法上失败。我检查了文档,他们没有上传 GIF 图像的示例