Create Twitter Bot using NodeJs and Deploy on Heroku
Twitter! We all know what Twitter is and most of us are familiar with its “microblogging” feature. We use the features like status posting, retweeting, liking, commenting and so on.
This article is to learn how to automate these features using a twitter bot
There are many things you can do with your bot, they are only limited to our own imagination.
We are going to create a twitter bot which will do two things
- Post a joke on a daily basis.
- Follow certain hastags, like the tweets containing those hashtags and retweet them.
Step 1: Apply for Twitter Developer Account
Duh! Of course we will need a developer account. How else are we going to create the bot? 😅
- Login into Twitter
- Go to developers.twitter.com and click on ‘Apply for a Developer account’
- Select the type of application i.e. student/business/hobbyist, etc. Choose student or hobbyist. ( It doesn’t really matter unless its a business account. There are different rules for the business account )
- Mention the purpose of your application. Try to be specific w.r.t what you are going to do with your Bot, in my case I added “I am going to post random jokes daily. Follow some hashtags, like & retweet them”.
The more specific you are, the better are your chances of getting the approval.
Important! Read all the guidelines before applying
Make sure you have read the Developer Agreement and Policy, Automation Rules and The Twitter Rules before applying
We are getting there….
Step 2: Create your app on Twitter
Create your app after your developer account has been approved. Now a days, it doesn’t really take much time.
- Follow this create app url. Fill in the required details.
- Hit next after you enter your app name. This will show you your keys & tokens.
- Now go to App Permissions and hit Edit, select Read and Write option from the options, as we want our app to be able to Read and Write.
- Hitting Save button will ask your for confirmation, say “Yes”.
- Now, on the Overview, select your App and you will see a key 🔑 icon next to the app name. Go ahead and click it.
- You should now see your Consumer keys and Authentication Tokens
- Generate The Access Token and Secret, store them somewhere secured as we will be needing them for the our operations.
Almost there…
Step 3: Setting up the development environment
Make sure you have NodeJs, npm installed on your machine
For Ubuntu, install using the following commands
For Mac or Windows, click here for the installation instructions
Create a directory named <your-bot-name>
In my case, I have named lazy-twitter-bot
We are going to use twit
npm package. Its a Twitter API client for NodeJs.
Enter the below commands inside the <your-bot-name>
directory.
Your Node.js dev environment setup is now complete 🎉
Step 4: Development the bot
Before we start with the development, we need to authenticate twit
. To do this, we will be using our API keys, Access Token, etc we saved in the earlier steps.
- Create folder name
config
in your root. - Add a file name
config.env
and enter the follow code in it.
config.env
- Add this file in your
.gitignore
file as we don’t the secrets to be pushed to our git repo. - Install
dotenv
npm package, this will help us load the environment vairables.
- Add
axios
npm package. We will be using this to fetch the joke and post it using our bot.
Now that we have added our .env
file, installed our dependencies, let’s go ahead and create index.js
which will be our entry point to our bot.
In my case, I am using
index.js
to write my bot code. You can name it anything you want based on your idea. I will be writing all code in file as this code is just for the demo purposes. I think each feature should have its dedicated .js file provided you’re building multiple features
Below is the code for our bot
index.js
Let’s understand the code
- Import our
config
from./config
folder - Import
Twit
fromtwit
package - Import
axios
fromaxios
package - Initialize the T instance using
Twit
with the config we imported fromconfig.env
- postStatusUpdate method
- This function will basically run every day ( 86400000 being in ms ), we have done this with a simple
setInterval
API. - Do a GET call to this website. This is pretty cool website which I found which generates jokes. It has multiple params by which you can fetch the joke. I have done a simple call which returns a single joke on a random basis.
- Once we have the joke object we post it using
T.post(‘statuses/tweet’, { status: joke }, responseCallback );
- responseCallback is our common method to handle the response of the Twitter APIs.
- Run
node index.js
- This will post our tweet! 🎉🎉 This is so simple isn’t it? To verify please login to twitter and check if the tweet has been posted
- LikeAndRetweet method
- This function will run every hour, follow these hastags
`#JavaScript, #nodejs, #mongoDB, #vuejs, #reactjs, #expressjs`
- We will be creating a
stream
which will observe/scan tweets containing these hashtags. - With on
tweet
event, we get the tweet object. We then usefavorite/create
property to like the tweet andstatuses/retweet/:id
to retweet the update. - Now again run the file using
node index.js
- You should now see multiple tweets being liked and retweeted 🎉
To understand more about the APIs, properties please visit this.
Step 5: Deploy the bot on Heroku
- Create an account on Heroku
- Create and app with
<your-bot-name>
on Heroku
- This will open up a form, enter the required details. The app name should be the name of your local project directory
- Now install heroku-cli on your machine using the below command
- For windows, Linux or other installation methods please follow this link.
- For heroku to understand our bot start command, we create a Procfile having the below code
- Procfile
- Let’s login to heroku using below CLI command
- This will open a login link in your browser, enter your password. After successful login you can now close the tab.
- Deploy the bot on Heroku using these commands
We are almost there..
Now that our bot is deployed on Heroku, we need to start it so that it do the job we have coded it for.
Start the worker on Heroku
- Go to https://dashboard.heroku.com/apps and click your bot app
- Then click on the configure Dynos
- Switch off the
web npm start
and start theworker node index.js
and confirm
And the bot is Ready! 🍾🎊
The randomBot
You can you follow this link see the bot in work
Source Code for the Bot
And we are done!
Feedback is always appreciated!
Thank you for reading! 🙌