我正在制作一个带有NPM软件包的Twitter机器人,名为Twit,它想知道如何在不发布重复图像的情况下将图像发布到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
您可以保留所有已上传图像的列表。您可以通过几种方法执行此操作:
将上传图像列表保留为全局变量。在上传新图像之前,请检查该图像是否在列表中。如果是这样,请尽早返回。如果不是,请将图像放入列表中并继续。
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);
我已经在此shuffle
上发布了一个使用clearInterval
和repl的示例。