【问题标题】:Javascript - Posting Images to Twitter with No DuplicatesJavascript - 将图像发布到 Twitter 且不重复
【发布时间】:2020-03-14 11:35:48
【问题描述】:

我正在使用一个名为 Twit 的 NPM 包制作一个 Twitter 机器人,我想知道如何在不发布重复图像的情况下将图像发布到 Twitter。

目前是 image_path 变量

var image_path = path.join(__dirname, '/images/' + random_from_array(images))

正在查看我的图像目录,但我不希望它上传重复的图像。我尝试了多种方法,但被卡住了。任何建议,我都很难过。

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

var T = new Twit(config);

function random_from_array(images){
  return images[Math.floor(Math.random() * images.length)];
} 

function upload_random_image(images){
  console.log('Opening an image...');
  var image_path = path.join(__dirname, '/images/' + random_from_array(images)),
      b64content = fs.readFileSync(image_path, { encoding: 'base64' });

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

  T.post('media/upload', { media_data: b64content }, function (err, data, response) {
    if (err){
      console.log('ERROR:');
      console.log(err);
    }
    else{
      console.log('Image uploaded!');
      console.log('Now tweeting it...');

      T.post('statuses/update', {
        media_ids: new Array(data.media_id_string)
      },
        function(err, data, response) {
          if (err){
            console.log('ERROR:');
            console.log(err);
          }
          else{
            console.log('Posted an image!');
          }
        }
      );
    }
  });
}

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

    setInterval(function(){
      upload_random_image(images);
    }, 10000);
  }
});

我正在学习本教程

https://botwiki.org/resource/tutorial/random-image-tweet/#posting-images

【问题讨论】:

    标签: javascript node.js npm twitter bots


    【解决方案1】:

    您可以保留所有已上传图片的列表。有几种方法可以做到这一点:

    最简单的解决方案

    将上传的图片列表保存为全局变量。在上传新图像之前,请检查该图像是否在列表中。如果是,请尽早返回。如果不是,将图像放入列表并继续。

    const uploadedImages = []
    function upload_random_image(images){
      console.log('Opening an image...');
      const image = random_from_array(images)
      // check if image is in the list
      if (uploadedImages.includes(image) {
         return;
      }
      // image is not in the list - insert into the list and continue
      uploadedImages.push(image);
      const image_path = path.join(__dirname, '/images/', image)
      // ...
    

    这种方法的一个缺点是,您最终会在上传图像的时间上出现“间隙” - 如果图像已经上传,您的程序将不得不等到下一个间隔过去后才能重试。此外,我们无法知道文件夹中的所有图像何时都已上传。

    更优化的方法

    更好的方法(在我看来)是首先将图像随机化,然后一次将它们传递给upload_random_image 函数,该函数现在将变成一个upload_image 函数。为此,我们需要一个 shuffle 函数 - 有很多在线创建解决方案,或者您可以使用像 lodash 这样的实用程序库。假设存在shuffle 函数:

        // ...
        var images = [];
        files.forEach(function(f) {
          images.push(f);
        });
        const shuffled = shuffle(images)
        let index = 0;
        setInterval(function(){
          const image = shuffled[index]
          upload_image(image);
          index += 1; 
        }, 10000);
      }
    });
    
    function upload_image(image){
      console.log('Opening an image...');
      var image_path = path.join(__dirname, '/images/' + image)
      // ...
    }
    

    现在剩下的问题是我们将在某个时候到达shuffled 数组的末尾。这确实表明我们已经上传了该文件夹中的所有图像并且我们的工作已经完成。为了能够停止,我们需要使用setInterval的返回值,即intervalID。我们将setInterval的返回值保存到一个变量中,一旦我们想停止就调用clearInterval

        const shuffled = shuffle(images)
        let index = 0;
        const intervalId = setInterval(function(){
          const image = shuffled[index]
          upload_image(image);
          index += 1; 
          if (index === shuffled.length) {
            clearInterval(intervalId)
          }
        }, 10000);
    

    我已将使用shuffleclearInterval 的示例发布到此repl

    【讨论】:

    • 你就是那个人,我非常感谢所有的帮助。非常感谢!!!
    猜你喜欢
    • 2013-01-15
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 2015-07-06
    • 2015-04-24
    • 2015-09-03
    • 2013-06-10
    • 2023-03-06
    相关资源
    最近更新 更多