【发布时间】: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