Skip to content

Instantly share code, notes, and snippets.

@stefanbohacek
Last active January 1, 2023 09:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save stefanbohacek/58005106e1507369bbf0ed5f3e69b952 to your computer and use it in GitHub Desktop.
Save stefanbohacek/58005106e1507369bbf0ed5f3e69b952 to your computer and use it in GitHub Desktop.
/*
A simple Twitter bot that posts random images.
Tutorial: https://botwiki.org/resource/tutorial/random-image-tweet/
*/
const fs = require('fs'),
path = require('path'),
Twit = require('twit'),
config = require(path.join(__dirname, 'config.js')),
images = require(path.join(__dirname, 'images.js'));
/*
Your config.js file should have the following format:
const config = {
consumer_key: 'XXXXX',
consumer_secret: 'XXXXX',
access_token: 'XXXXX',
access_token_secret: 'XXXXX'
}
module.exports = config;
Here's a tutorial on how to get the API keys: https://botwiki.org/resource/tutorial/how-to-create-a-twitter-app/
And this is an example of an image.js file:
const images = [
{
file: '01.jpg',
source: 'http://www.example.com/01.jpg'
},
{
file: '02.jpg',
source: 'http://www.example.com/02.jpg'
},
{
file: '03.jpg',
source: 'http://www.example.com/03.jpg'
}
];
module.exports = images;
*/
const T = new Twit(config);
const randomFromArray = (arr) => {
/* Helper function for picking a random item from an array. */
return arr[Math.floor(Math.random() * arr.length)];
}
const tweetRandomImage = () => {
/* Then pick a random image from the images object. */
const image = randomFromArray(images);
console.log('opening an image...', image);
const imagePath = path.join(__dirname, '/images/'+ image.file);
const imageSource = image.source
const imageData = fs.readFileSync(imagePath, { encoding: 'base64' });
/* Upload the image to Twitter. */
console.log('uploading an image...', imagePath);
T.post('media/upload', { media_data: imageData }, function (err, data, response){
if (err){
console.log('error:', err);
} else {
/* Add image description. */
const image = data;
console.log('image uploaded, adding description...');
T.post('media/metadata/create', {
media_id: image.media_id_string,
alt_text: {
text: 'Describe the image'
}
}, (err, data, response) => {
/* And finally, post a tweet with the image. */
T.post('statuses/update', {
status: `Image source: ${ imageSource }`,
media_ids: [image.media_id_string]
},
(err, data, response) => {
if (err){
console.log('error:', err);
} else {
console.log('posted an image!');
}
});
});
}
});
}
setInterval(() => {
tweetRandomImage();
}, 10000);
@jimmyeao
Copy link

Thanks for this. I've created a Powershell script to help create the images.js file (because typing manually is tedious :) )
https://github.com/jimmyeao/twitterbotimgcreator

@stefanbohacek
Copy link
Author

Nice, thank you for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment