Twitter bot in 17 lines of code
Tags: node, learning, bot, javascript
Published: 2018-03-27 14:15:44

---
title: Twitter bot in 17 lines of code
published: True
description: how to create a bot that would auto like all tweets with specific keywords.
tags: node, learning, bot, javascript
---
![alt text](https://thepracticaldev.s3.amazonaws.com/i/shrt9f0psvek1kemo38p.png "Image of terminal with tweet id message")

A few months ago I posted how to ["create a twitter bot in 3 minutes"](https://dev.to/notfakedev/create-a-twitter-bot-in-3-minutes). Since then Twitter API changed so I decided that its time for an update. I also saw a post by @omarhashimoto - ["How to build a simple Twitter bot in 17 lines of code"](https://dev.to/omarhashimoto/how-to-build-a-simple-twitter-bot-in-17-lines-ofcode-2aan) which motivated me to reduce my code to maximum 17 lines, I could archive 13 lines of code by not displaying error messages but the truth is that sometimes more code is actually better. Alright, time to start!

#### What we are coding?
We want to create a Twitter bot that would automatically like all tweets that include keywords specified by us. We will be using Stream API which means that all the likes and listening will be happening in real time.

#### What you need?
* [Node.js](https://nodejs.org/en/)
* [Twitter for Node.js](https://github.com/desmondmorris/node-twitter)
* [Twitter APP](https://apps.twitter.com)

#### Setup
After you finish installing Node.js, open terminal and navigate to your project folder. 

Type `npm init` and complete the setup. Next step is to install our dependences, we are using Twitter for Node.js so type in `npm i twitter --save`. The last thing we need is Twitter app, you can create your Twitter app by visiting https://apps.twitter.com. Once you create your app, all you need is 4 keys that you are going to use for connection between the app and your code:
* Consumer Key
* Consumer Secret
* Access Token Key
* Access Token Secret

now create new JavaScript file, `touch bot.js`

#### Coding
First we want to import our Twitter library, then we have to set up connection with our app. You should enter the keys from your Twitter app.
```js
const Twitter = require('twitter');
const client = new Twitter({
  consumer_key: '',
  consumer_secret: '',
  access_token_key: '',
  access_token_secret: ''
});
```

Now we need to specify our stream listening preferences, as you can see I added two keywords that I want to track "#IlikeBots" and "keyword2". You can add as many as you like, you can also use hashtags or just normal words it doesn't really matter. It's good to know that Twitter will limit your likes per hour so adding extremely popular keywords would exhaust your limit really quick. 
```js
const stream = client.stream('statuses/filter', {track:'#IlikeBots, keyword2'});
```

All the magic happens here, we are receiving 'data' object from the stream, every single 'data' object consists of all informations about the tweet that matches our keyword. The middle part is where we do the Like action, all we need is the tweet id which we are taking from our 'data' object. Once the like happens we are printing ID of the tweet and the content. If something goes wrong we are going to throw the error. 
```js
stream.on('data', (event) => {

  client.post('favorites/create', {id:event.id_str}, (error, response) => {
    if(error) throw error;
    console.log('Tweet ID: '+response.id_str+' Liked! - "'+response.text+'"')
  });

});
```

Before we start reading and liking the tweets, we want to make sure that we can read error codes, this is very important because fixing something without knowing what the problem is would be pure waste of our time. If we get for example error CODE 429 we would know that our app works just fine and the real problem is just Twitter API limit. You can take a look at all error codes in the [Twitter API documentation.](https://developer.twitter.com/en/docs/basics/response-codes).
```js
stream.on('error', (error) => {
  throw error;
});
```
Update by @mrm8488 from comment section:
*It would be good to handle the error on: "stream.on('error'...". If you throw the error as it is the upper function, the error will reach the event loop and the application will crash.
A quick solution would be:*
```js
stream.on("error", error => console.error(error));
```

Time to run our code, type `node bot.js` in the terminal. Tweet something using your keywords, you should be able to see feedback in the terminal.

![alt text](https://thepracticaldev.s3.amazonaws.com/i/9os29nnd1h4ykoj6ficn.jpg "Image of terminal with tweet id message")

![alt text](https://thepracticaldev.s3.amazonaws.com/i/shrt9f0psvek1kemo38p.png "Image of terminal with tweet id message")

![alt text](https://thepracticaldev.s3.amazonaws.com/i/dz2hdkpjor0i90habdpo.jpg "Image of terminal with tweet id message")

#### Final Code
```js
const Twitter = require('twitter');
const client = new Twitter({
  consumer_key: '',
  consumer_secret: '',
  access_token_key: '',
  access_token_secret: ''
});

const stream = client.stream('statuses/filter', {track:'#IlikeBots, #keyword2'});

stream.on('data', (event) => {
  client.post('favorites/create', {id:event.id_str}, (error, response) => {
    if(error) throw error;
    console.log('Tweet ID: '+response.id_str+' Liked! - "'+response.text+'"')
  });
});

stream.on('error', (error) => {
  throw error;
});
```