Skip to content

Instantly share code, notes, and snippets.

@apexys
Created December 13, 2016 11:48
Show Gist options
  • Save apexys/5240521e93801691e2079c096e2ce1db to your computer and use it in GitHub Desktop.
Save apexys/5240521e93801691e2079c096e2ce1db to your computer and use it in GitHub Desktop.
Quickly hacked-together solution for retweeting images from a private account
var Twit = require('twit')
var fs = require('fs');
var request = require('request');
var credentials = JSON.parse(fs.readFileSync('secrets.json'));
var T = new Twit({
consumer_key: credentials.consumer_key,
consumer_secret: credentials.consumer_secret,
access_token: credentials.access_token_key,
access_token_secret: credentials.access_token_secret
});
function fixTweetText(text){
text = text.replace(/\&amp\;/g, '&');//Replace ampersands with *real* ampersands
text = text.replace(/http(s?):\/\/.+/, ''); //Strip links
return text;
}
var cachedTweets = [];
var MAX_CACHED_TWEETS = 20;
var cachedImages = [];
var MAX_CACHED_IMAGES = 10;
var cacheFull = false;
var trump = 0;
var hillary = 0;
var twfn = function(tweet){
//console.log(tweet);
if(tweet.retweeted_status || tweet.possibly_sensitive){
return; //No retweets;
}
var tw = {
'text': fixTweetText(tweet.text),
'name': tweet.user.name,
'handle': tweet.user.screen_name,
'profileimg': tweet.user.profile_image_url
};
if(tweet.entities.media){
tweet.entities.media.forEach(function(media){
if(media.type == 'photo'){
tw.image_url = media.media_url;
var request = require('request');
request(tw.image_url, function (error, response, body) { //Download image
if (!error && response.statusCode == 200) {
var b64content = new Buffer(body).toString('base64'); //Encode as base64
// first we must post the media to Twitter
T.post('media/upload', { media_data: b64content }, function (err, data, response) {
// now we can assign alt text to the media, for use by screen readers and
// other text-based presentations and interpreters
var mediaIdStr = data.media_id_string;
var altText = tw.text;
var meta_params = { media_id: mediaIdStr, alt_text: { text: altText } }
T.post('media/metadata/create', meta_params, function (err, data, response) {
if (!err) {
// now we can reference the media and post a tweet (media will attach to the tweet)
var params = { status: tw.text, media_ids: [mediaIdStr] }
T.post('statuses/update', params, function (err, data, response) {
console.log(data)
})
}
})
})
}
})
}else{
console.log('different media: ' + media.type + " url = " + media.media_url);
}
});
}else{
//Tweet status text
T.post('statuses/update', { status: tw.text }, function(err, data, response){console.log(data)})
}
};
var tags = ['#sewmarsi'];
var stream = T.stream('statuses/filter', {track: tags});
console.log('Stream connected');
stream.on('tweet', twfn);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment