BH0's Blog

Twitter Bot - Tweet A Heart Image

In this tutorial we will learn how to make a simple Twitter bot which tweets an image and using the Twit package.

Prequisites: Basic Node & NPM (command line), Javascript usage, and some familiarity with “get” and “post” requests to a server.

Firstly, create a folder then inside that folder run “npm init” with the following data (and feel free to modify this). Ensure the following is inside your “package.json” then run “npm install” as well as “npm install twit –save”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"name": "twitterbot",
"version": "1.0.0",
"description": "",
"main": "bot.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"twit": "^2.2.9"
}
}

The “bot.js” is our main file, and will be contain the code for our bot. First time I tried making a Twitter bot without Twit I couldn’t even get it working due to server connectivity + communication issues. Thanks to the Twit package, we aren’t likely to suffer from the problems I suffered from. The tutorial is split into two parts: setting up our Twitter bot and ensuring it works, then we will produce the code to make it more interesting.

The Setup

First we have to set our application up to work with Twitter - this is essentially just some configuration to ensure Twitter is aware of our application, and will help us authenticate otherwise when we try communicating with Twitter’s API it will be like “I don’t know you and I don’t talk to strangers”. It might help to make a new Twitter account for testing and messing around. Once you have a Twitter account (I assume you know how to make one) go to https://apps.twitter.com then clicked “create new app” - make sure you have a phone number associated with your account, you can use a service like Twillio or any suitable mobile number.

To create an application, fill in the following form input fields with the appropriate values: name - the name of your application (such as “heartbot”), description - a short description of your application, website - a website associated with your application such as “https://bh0.github.io“, and callback-url can remain empty. Check the box for the Developer Agreement (might help to read it first). Then click “create your Twitter application”.

Keep this web-page open, we will need it. Inside “bot.js” put the following code. Give the “consumer_key”, “consumer_secret”, “access_token” and “access_token_secret” their appropriate values, this information is provided in the “keys and access tokens” page that you were told to keep open. This information is private so make sure it stays that way, if for whatever reason it is no longer private you can simply generate new values. This stuff is basically just so Twitter knows we are legitimate. The “require” stuff are our dependancies: “filesystem” and the “twit” - they are constants as our dependencies should not change for what I hope is an obvious reason.

1
2
3
4
5
6
7
8
const Twit = require("twit");
const fs = require("fs");
const twit = new Twit({
consumer_key: 'Consumer Key (API Key)',
consumer_secret: 'Consumer Secret (API Secret)',
access_token: 'Access Token',
access_token_secret: 'Access Token Secret'
});

Now create a folder called images inside the root of your bot’s folder and inside it put a “.png” image-file (you can use other image formatas but I’m not sure what ones are supported).

The Fun Stuff

Once our applciation has connected to the Twitter API (thanks to Twit), we will make the following function which will, grab our image, do some stuff to ensure it can successfully be sent, configure our tweet with the data we want it to contain, attempt to send our tweet, and lastly, if we weren’t able to send our tweet - tell us why. The last two lines are optional and will make our application tweet every so often.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
function bot() {
/// Grab Image
let image = 'images/heart.png';
/// Do some stuff to ensure our image is good to go
let params = {
encoding: 'base64'
}
let b64 = fs.readFileSync(image, params);
/// Upload our image
twit.post('media/upload', {media_data: b64}, uploaded);
function uploaded(error, data, response) {
let id = data.media_id_string;
/// Configure Tweet Data
let tweet = {
// Associate a status (some text) with our tweet
status: "Hearts are lovely. ",
// The media (image) we want our tweet to contain
media_ids: [id]
}
/// Tweet our image and call function which tells us if tweet was successfully sent
twit.post('statuses/update', tweet, tweeted);
}
}
/// Tell us if the tweet was sent and if not, tell us why
function tweeted(error, data, response) {
if (error) {
console.log(`Issue upon Tweet ${error} ${response}`);
} else {
console.log("Tweet posted");
}
}
/// Call Our Bot Function (every so often)
let wait = 3000;
setInterval(bot, wait);

I hope that code is well commented and thus understandable - the stuff that isn’t so well commented is stuff that you don’t need to know in depth. And to run our application (locally) simply make sure your inside the project’s folder via the command line and type “node bot.js”. Then go to the Twitter account associated with your bot and there you should see an image and some text (the status). And if everything went well; congratulations we just “spoke” to Twitter’s API and told it to tweet (post) content for us.

This post was heavily inspired by “The Coding Train’s” Youtube playlist: “Twitter Bot Tutorial - Node.js and Processing” and I highly recommend you check it out if you enjoyed this.

The Future

You can do all sorts of cool things with Twitter bots, you could make a chat-bot, and in the future I may update this blog post (or make a new one) which teaches us how to make a front-end webpage which allows the user to upload their own image and make our bot Tweet it. Obviously, I assume you will use the information I provide appropriately.