Creating a Twitter Bot
Tags: bot, twitter, node, typescript
Published: 2020-02-20 20:25:35

Hello 💁‍♂️, this is my second post on this platform and my first post written in english. Excuse me if I make mistakes with the language 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/iy37qa7kckozd2sc2cg6.gif)

⚠️ Warning: this post have many gifs⚠️


Today We´re going to do it a **Typescript Twitter Bot** that retweet tweets that contains the hastag #100DaysOfCode. 100DaysOfCode it´s a coding challenge. It has two main rules: Code minimum an hour every day for the next 100 days and tweet your progress every day with the #100DaysOfCode hashtag. You can visit his website for more information: [100DaysOfCode](https://www.100daysofcode.com/)


Before start, we need 3️⃣ important things:
 
1. **Nodejs and yarn**: to download click here [Node](https://nodejs.org/en/) and install it. Then, install yarn: npm i yarn. For more informationl, click here [Yarn](https://yarnpkg.com/).

2. **Your favourite code editor**. My favourite and my recommendation **is Visual Studio Code**. You can download it here: [VsCode](https://code.visualstudio.com/) 

3. **Twitter Developer Account**. First, you must have a working twitter acount. Now go to [Twitter Developers](https://developer.twitter.com/en/apply-for-access). In my case, I am going to use my personal account

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ys7m0d08yvuady10pvpw.PNG)



You have to click on apply for a developer account and select "Making a bot". Then, complete with your personal data. In the next step, you have to explain in english how you plan to use Twitter data and/or API. It´s easy. With respect to the following options, select these like the picture: 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/x329g6331j10j4veqdry.PNG)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6nhnsypqrmmm9xh6l06u.gif)

In this area, explain what are you going to rt, mg or whatever you want. Read (or not🙄, as you prefer🤣) and accept the conditions. Next, you have to confirm your email. 

⚠️ **WARNING: look at the spam folder❗️❗️❗️**⚠️ 

AND...... *YES!!!!* 🤗🤗🤗
At this moment, We have a development account

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/skwd59kyfc61080clqk7.PNG)


At this moment, we have to create an app. Write your personal information in the fields. When you finish, you have to see a screen like this. If not, but you have created the app succesfully, click in your profile name and go to apps.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/okcq2uii5c3i0ynggw1a.PNG)

Click on details and go to **Keys and tokens**. Take a txt 📝 and copy **Api key**, **Api secret key**, **access token** and **access token secret**. We will use it later.

When you finish these steps, **Congratulations** We configure our developer twitter account.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1u473idrh4uo1r1bjxat.gif)

We are going to start with the main reason for this post: **creating a twitter bot**. In this case, we are going to use a node/typescript starter that one friend did it some days ago: [Node/Typescript starter](https://github.com/HorusGoul/node-ts-starter) and her post about the starter: [Post Starter](https://dev.to/horusgoul/node-js-typescript-starter-for-your-next-project-mea)

**Assuming we have git installed** (if not [Install Git](https://www.linode.com/docs/development/version-control/how-to-install-git-on-linux-mac-and-windows/)), we are going to follow the steps that appears in the readme of my friend post.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/z0hd8czzhotvviq461ns.PNG)

Open the project in your IDE and you have to see something like this: 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7ihhylhf2ne8eqxg1c8o.PNG)

We are going to create **two files** in src folder: **bot.ts** and **config.ts**. You can delete index.ts. When you created it, select the file who is named **package.json**. In this file, node administrate our dependencies. You have to change it and it should be like this (your name, license and personal data can be changed): 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4rtc5qbsutcjkwm4t3ex.PNG)

We are lucky because things like babel o eslint are **preconfigured by Horus**, the creator of the starter. 

The next step consist on modify the file **config.ts**. In this file, we have to put our Twitter developers keys that we saved some minutes ago. This keys are the "passwords" for the Twitter API and without them, it´s impossible to make a Twitter bot. The config.ts should be as follows: 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rkr3q4606i07f5gufour.PNG)

Maybe you are at home or in a café and you are asking yourself what is the commented lines, and it´s normal. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/eogf2xnuj07ji8x1rymg.gif)

This is because EsLint is a static code analysis tool for identyfing problematic patterns and warnings in Javascript code. Basically, ESLint ask us to use camel case, but for Twitter API, these names have to be like that. 

For the next steps, **I recommend you to enable terminal inside VsCode**. 

The First and the more important step, we have to **import a twitter package for nodejs**. His name is Twit and you must install like that: 
```bash

yarn add twit
```

When you import install and code the import in bot.ts, will be appear a type error. We have to **install the types** module for twit: 
```bash
yarn add @types/twit
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jfotzwayv8uypimzvuei.PNG)

Next, we have to create a new **instance of twit**. In this case, his name are going to be twitter and it´s required to import the config.ts

```javascript
const Twitter = new twit(require('./config'));
```

We are going to create an **object named twitterOptions**, for example. In this object, we have to indicate to twitter some parameters that are essential. Again, add a comment line to skip EsLint. This object is **Twit.Params type**:

```javascript
const twitterOptions: twit.Params = {
  q: '#100DaysOfCode',
  count: 100,
  // eslint-disable-next-line @typescript-eslint/camelcase
  result_type: 'recent',
};
```
**The parameter "q"** indicate the hastag we want to retweet. You can change it for another hastag.

If you want to know more about these parameters, click here: [Parameters Twitter API](https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vn0nschg2th9y1qd4c6x.gif)

Create an arrow function with a name, in my case, **retweetLatest**.
Inside this function, we are going to make a **Get request**. This request GET any of the REST API endpoints. There are three parameters. 

**T.get(path, [params], callback)**. 

**path** is the endpoint to hit, **params** (Optional) parameters for the request and **callback**: function (err, data, response) data is the parsed data received from Twitter and response is the message received from Twitter.

```javascript
Twitter.get('search/tweets', twitterOptions, (error: Error, data: any) => {});
```

Inside, we are to put an **if** structure to discrminate if there is an error or not:

```javascript
if (!error) {
} else { 
console.log('There was an error with your hashtag search:', error);
}
```
Inside the **if** , we have to pick the id of the tweet we picked. 

```javascript
With the id saved in a const, we are going to make a post request. Same usage as Twitter.post(
    'statuses/retweet/' + retweetId,
    {},
    (error: Error, response:Response) => {

    },
);
```

Import the Response type in the Twit initial import as you can see in the picture: 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mmeiqx93bpsapyn74epj.PNG)

To finish the retweet bot, you have to put **two if** structures discriminating by **response** and **error** and bot.ts is like that: 


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/s3vekqeqce8a6t09n5z8.PNG)


To finish, call the function and add one **setInterval** to call the same function every so often: 

```javascript
retweetLatest();
setInterval(retweetLatest, 1000 * 20);
```

To run the bot, put this command in the terminal: 
```bash
yarn dev
```
When you run this command in your terminal, see your Bot account in Twitter. You have to see a retweet (if there are any) in your feed.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/9x9cqxhb78pju8apdlhg.gif)


First, thanks you for reading this post. Comment if you liked it 😁, or if not😢.

To say goodbye, I put my repo of this [bot]
(https://github.com/alvarotorresc/bot_twitter_ts) on github. The repo of the [starter](https://github.com/HorusGoul/node-ts-starter) that we use in this tutorial and last but not least, **FOLLOW ME ON TWITTER** [Alvaro Torres Carrasco](https://twitter.com/torresc_alvaro)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/70etm8aakq9a0g26wnvo.gif)