Dom the dev
Posted on February 8, 2022
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
I also made a step by step video
List of contents
Create Twitter App
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
ipconfig
Linux/Mac
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.
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.
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
To install it run the following command in your terminal
npm i twitter-api-v2
Once the installation is done, we can open up the project in our text-editor/IDEA.
Twitter Client
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.
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:
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
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
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:
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.
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
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.
Run npm i cron
in your terminal to install it.
Require that module in your index.js
const CronJob = require("cron").CronJob;
The last step: Create a new job from your CronJob class and let it run every certain time.
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.
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
Posted on February 8, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.