Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
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( arr ){
/* Helper function for picking a random item from an array. */
return arr[Math.floor( Math.random() * arr.length )];
}
function tweetRandomImage(){
/* Then pick a random image from the images object. */
const image = randomFromArray( images );
console.log( 'opening an image...', image );
const imagePath = path.join( __dirname, '/images/'+ image.file );
const imageSource = image.source
const imageData = fs.readFileSync( imagePath, { encoding: 'base64' } );
/* Upload the image to Twitter. */
console.log( 'uploading an image...', imagePath );
T.post( 'media/upload', { media_data: imageData }, function ( err, data, response ){
if ( err ){
console.log( 'error:', err );
}
else{
/* Add image description. */
const image = data;
console.log( 'image uploaded, adding description...' );
T.post( 'media/metadata/create', {
media_id: image.media_id_string,
alt_text: {
text: 'Describe the image'
}
}, function( err, data, response ){
/* And finally, post a tweet with the image. */
T.post( 'statuses/update', {
status: `Image source: ${ imageSource }`,
media_ids: [image.media_id_string]
},
function( err, data, response){
if (err){
console.log( 'error:', err );
}
else{
console.log( 'posted an image!' );
}
} );
} );
}
} );
}
setInterval( function(){
tweetRandomImage();
}, 10000 );
@jimmyeao
Copy link

jimmyeao commented Apr 12, 2021

Thanks for this. I've created a Powershell script to help create the images.js file (because typing manually is tedious :) )
https://github.com/jimmyeao/twitterbotimgcreator

@fourtonfish
Copy link
Author

fourtonfish commented Apr 14, 2021

Nice, thank you for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment