Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yohannawaliya/16eb97764b5376868e5d167d6b3a8d8f to your computer and use it in GitHub Desktop.
Save yohannawaliya/16eb97764b5376868e5d167d6b3a8d8f to your computer and use it in GitHub Desktop.
/*
A simple Twitter bot that posts random images.
Tutorial: https://botwiki.org/resource/tutorial/random-image-tweet/
*/
const fs = require( 'fs' ),
path = require( 'path' ),
Twit = require( 'twit' ),
config = require( path.join( __dirname, 'config.js' ) ),
images = require( path.join( __dirname, 'images.js' ) );
/*
Your config.js file should have the following format:
const config = {
consumer_key: 'XXXXX',
consumer_secret: 'XXXXX',
access_token: 'XXXXX',
access_token_secret: 'XXXXX'
}
module.exports = config;
Here's a tutorial on how to get the API keys: https://botwiki.org/resource/tutorial/how-to-create-a-twitter-app/
And this is an example of an image.js file:
const images = [
{
file: '01.jpg',
source: 'http://www.example.com/01.jpg'
},
{
file: '02.jpg',
source: 'http://www.example.com/02.jpg'
},
{
file: '03.jpg',
source: 'http://www.example.com/03.jpg'
}
];
module.exports = images;
*/
const T = new Twit( config );
function randomFromArray( images ){
/* Helper function for picking a random item from an array. */
return images[Math.floor( Math.random() * images.length )];
}
function uploadRandomImage(){
/* Function for uploading a random image to Twitter and posting it. */
console.log( 'picking a random image...' );
const image = randomFromArray( images );
console.log( image );
const imagePath = path.join( __dirname, '/images/'+ image.file );
const imageSource = image.source
b64content = fs.readFileSync( imagePath, { encoding: 'base64' } );
console.log( 'uploading an image...' );
T.post( 'media/upload', { media_data: b64content }, function ( err, data, response ) {
if ( err ){
console.log( 'error:', err );
}
else{
console.log( 'image uploaded, now tweeting it...' );
T.post( 'statuses/update', {
media_ids: new Array( data.media_id_string )
},
function( err, data, response) {
if (err){
console.log( 'error:', err );
}
else{
console.log( 'posted an image!' );
/* After successfully posting an image, we can delete it.
Keep this part commented out if you want to keep the image and reuse it later. */
// fs.unlink( imagePath, function( err ){
// if ( err ){
// console.log( 'error: unable to delete image ' + imagePath );
// }
// else{
// console.log( 'image ' + imagePath + ' was deleted' );
// }
// } );
}
}
);
}
});
}
fs.readdir( __dirname + '/images', function( err, files ) {
/* Read the content of the images folder, and tweet a random image from it. */
if ( err ){
console.log( 'error:', err );
}
else{
let images = [];
files.forEach( function( f ) {
images.push( f );
} );
setInterval( function(){
uploadRandomImage( images );
}, 10000 );
}
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment