How to fix code to have Twitter Bot tweet randomized word and image

Trying to make a twitter bot that tweets an image and a random word from the list below with that image (the list that has word1 – word4). So far it will post an image correctly with no errors popping up, it’s just the word part that wont tweet as well and I’m not sure what to try next. I am using node



dir = 'images'

const fs = require( 'fs' ),
      path = require( 'path' ),
      Twit = require( 'twit' ),
      config = require( path.join( __dirname, 'config.js' ) );



const T = new Twit( config );


function tweeter() {
  var word = [
        'word1',
        'word2',
        'word3',
        'word4'
        ];
  var name = Math.floor(Math.random()*word);
  var tweet = name;

  T.post('statuses/update', { status: tweet }, tweeted);
    
    
}

function randomFromArray( images ){
  /* Helper function for picking a random item from an array. */
  return images[Math.floor( Math.random() * images.length )];
  
  
  
}

function tweetRandomImage(){
  /* First, read the content of the images folder. */

  fs.readdir( __dirname + '/images', function( err, files ) {
    if ( err ){
      console.log( 'error:', err );
      return;
    }
    else{
      let images = [];
      files.forEach( function( f ) {
        images.push( f );
      } );

      /* Then pick a random image. */

      console.log( 'opening an image...' );

      const imagePath = path.join( __dirname, '/images/' + randomFromArray( images ) ),
            b64content = fs.readFileSync( imagePath, { encoding: 'base64' } );

      /* Upload the image to Twitter. */

      console.log( 'uploading an image...', imagePath );

      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...' );

          /* And finally, post a tweet with the image. */

          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!' );

              
  
              }
            }
          );
        }
      } );
    }
  } );
}

setInterval( function(){
  tweetRandomImage();
}, 20000 );```

43 thoughts on “How to fix code to have Twitter Bot tweet randomized word and image”

Leave a Comment