How to use the Twitter API to create a Twitter Bot
Tags: twitter, node, api, tutorial
Published: 2022-02-08 16:34:08

---
title: How to use the Twitter API to create a Twitter Bot
published: true
description: Use the Twitter API to create a bot which tweets every morning
tags: twitter, node, api, tutorial
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/208w0sk7hzcky2z333ro.jpg
---

In this tutorial, I will show how to create a Twitter Bot with NodeJS using the Twitter API.

GitHub Files: https://github.com/dom-the-dev/doms-bot-youtube

> [Subscribe to my YouTube Channel](https://www.youtube.com/domthedeveloper?sub_confirmation=1)


I also made a step by step [video](#video)

#### List of contents
- [Create Twitter App](#create-twitter)
- [Setup Project](#setup-project)
- [Twitter Client](#twitter-client)
- [First tweet](#first-tweet) 
- [The Cron](#cronjob) 



### Create Twitter App <a name="create-twitter"></a>

At First, we need to create a Twitter Application at the Twitter developer portal.
For that, you need to log in at https://developer.twitter.com/en/portal/dashboard.

In the left panel under Projects & Apps, click on Overview. Here, you can click on "Create App" to create a new application.

You have to give your application a name and confirm by clicking on next. On the next screen, you get the application's key and secrets displayed, which we won't be needing now.

We first have to make some other changes before we can use them properly. On the bottom right of your screen, click on app settings.

Here, we can change the authentication settings of our app.
Under "User authentication settings" click on "set up".

- Turn on both OAuth 1.0 & 2.0.
- As "Type of App" choose Automated App or Bot from the dropdown.
- App permissions set to "read and write"

The "Callback URI / Redirect URL" can't be set to localhost, so we need to paste in our local IP address. You can get it from your terminal

Windows
```bash
ipconfig
```

Linux/Mac
```bash
ifconfig
```

As Website URL, you can paste your personal website.
Hit save and we are ready to continue.
The Client ID and Client Secret which are displayed now are not needed in our case. Click on done to return to the dashboard.

Now we are ready to start coding.

Setup Project
Before we can start to create a node application, we have to make sure that node is installed.

Run node --version in your terminal. If you get a node version number printed, node is installed. If not, you need to go to the homepage and download the installer.

Once node is installed, we can create a new node application.
Create a new directory and switch into it.

```CLI 
mkdir twitter-bot && cd twitter-bot
```
Then run the following command to initialize a new npm project.
This will create a package.json inside the project directory.

```CLI 
npm init -y 
```

In the next step we are going to add a npm module to our app which will help us to communicate with the Twitter API. This module is called twitter-api-v2 and can be found [here](https://www.npmjs.com/package/twitter-api-v2)

To install it run the following command in your terminal

```CLI
npm i twitter-api-v2
```

Once the installation is done, we can open up the project in our text-editor/IDEA.

### Twitter Client <a name="twitter-client"></a>

Now we are going to create a twitter client. This client allows us to perform actions like tweets in our node application.
Create a new file, twitterClient.js.

Inside it, we need to require that Twitter API module and create our client by instantiate a new object of it. There we need to pass our keys, which we get from the [Twitter Developer Portal](https://developer.twitter.com/en/portal/dashboard).

On the overview page of your created application, select the "keys and tokens" tab.
Important: There you need to regenerate all tokens which we are going to use to make the auth settings take effect.
Copy and paste them into the twitter client, and export the client with readWrite permission.

You file should then look similar to this:

```javascript
const {TwitterApi} = require("twitter-api-v2");

const client = new TwitterApi({
    appKey: "<your-appKey>",
    appSecret: "<your-appSecret>",
    accessToken: "<your-accessToken>",
    accessSecret: "<your-accessSecret>"
})

const rwClient = client.readWrite

module.exports = rwClient
``` 


### First tweet <a name="first tweet"></a>

Now create a new file and name it index.js, here is where everything comes together.

At the top of the file, require the twitter client

```javascript
const rwClient = require("./twitterClient.js");
```

Now we can create the function which will create a tweet from our Twitter profile. Notice: The function needs to be asynchronous. Then we can call and await the tweet method of our client. To the method pass any string which will then be our tweet.

The function could look like this:

```javascript
const tweet = async () => {
    try {
        await rwClient.v1.tweet("Good Morning Friends!")
        console.log("tweet successfully created")
    } catch (e) {
        console.error(e)
    }
}
```

Then we need to call our function and test it.
```javascript
tweet()
``` 

In your terminal run node index.js. If everything works properly, you should get the successfully created tweet message in your terminal prompted.

Check your Twitter profile!


### The Cron <a name="cronjob"></a>

In order to make this tweet to be created again after a certain time, we need to create a cronjob.

For that we are going to install another package called cron which you can find [here](https://www.npmjs.com/package/cron).

Run `npm i cron` in your terminal to install it.

Require that module in your `index.js`
```javascript 
const CronJob = require("cron").CronJob;
```

The last step: Create a new job from your CronJob class and let it run every certain time.


```javascript
const job = new CronJob("0 5 * * *", () => {
    console.log('cron job starting!')
    tweet()
})

job.start();
```
Explanation: We create a new object from the CronJob class, we pass two params. The first one is a string and declares, when the job has to run.
A great tool to set up the time is [CronTab Guru](https://crontab.guru/#5_4_2_*_*).
The second parameter is the callback function which we want to be called. In our case, we log when the job starts and our tweet function.

And that's it. When you run node index.js the cron will start.
---

Thanks for reading! I hope you liked this article. Please leave me some feedback! :)

---


### Step-by-Step Video <a name="video"></a>

{% youtube fD-GRCH_tks %}