【问题标题】:How to fix code to have Twitter Bot tweet randomized word and image如何修复代码以使 Twitter Bot 推文随机单词和图像
【发布时间】:2021-05-18 21:50:06
【问题描述】:

尝试制作一个 twitter 机器人,它使用该图像(包含 word1 - word4 的列表)从下面的列表中发布一张图片和一个随机单词。到目前为止,它会正确发布图像,不会弹出错误,只是单词部分也不会发推文,我不确定下一步该尝试什么。我正在使用节点



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 );```

【问题讨论】:

    标签: javascript node.js twitter bots


    【解决方案1】:

    我认为问题出在tweeter 函数中,特别是在Math.floor 函数中。

    let word = ['word1', 'word2', 'word3', 'word4'];
    console.log(Math.floor(Math.random() * word));

    现在看到它返回NaN。您应该将其更新为下面的代码

    let word = ['word1', 'word2', 'word3', 'word4'];
    console.log(word[Math.floor(Math.random() * word.length)]);

    您需要使用word.lengthword[]根据随机数生成的索引来查找单词。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-29
      相关资源
      最近更新 更多