How to Build a Twitter Bot using Node.js

I built a Node.js Twitter bot! I’m super excited to share with you all the details of how to build a Twitter bot using Node.js for your own personal benefit.

Last Thursday night, I was pretty tired. After a week of grinding, I had hit a wall. I took work off Friday to sleep in and relax.

Friday morning, this was me:

At the same time, this was my Twitter account:

I didn’t tweet this out using Buffer or some other Twitter automation tool. I sent it out using my own Node.js application.

One of the reasons I didn’t get much sleep over the last 2 weeks was because I have been working on fully automating my Twitter game. I was sick of the lack of customization of the Twitter share plug-ins I was using, and wanted to learn a new technology.

I’ve had an absolute blast these last two weeks, and am very excited to continue to build cool applications like the Twitter bot I’m going to share with you in this post.

In this post, I’m going to be sharing with you what Node.js is, how you can build a twitter bot using Node.js, and finally how you can deploy it on a virtual machine.

How to Build a Twitter Bot using Node.js

The rest of this post is going to be laid out in the following way:

  • Why I wanted to build a Twitter bot
  • What is Node.js?
  • Using the Twitter API
  • What are the actions possible with Node.js and the Twitter API?
  • Building a Twitter Bot for Yourself to Tweet out the Most Recent article of an RSS Feed

    • I’m going from start to finish: from installing Node.js and a text editor, to writing the code, to running the code.
  • Deploying your application on a virtual machine to run 24/7

Why did I want to build a Twitter bot?

With any project or action, we should start with why. Why did I want to build a Twitter bot? For a couple reasons:

  • I wanted to learn a new technology and programming language to add to my repertoire
  • I’ve been disappointed in the “free” tools around the web
  • I’m of the mindset that I can create something as good or better than other free solutions

About 3 weeks ago, I started learning Node.js. I had never heard of it before, and was suggested by a good friend to take a look if I was interested in building web applications.

This set off a very fun 3 week… over the last 3 weeks, through YouTube, Googling, and doing tutorials, and finally, doing different things on my own, I’ve created something awesome.

To comment on the “free” tools around the web, I’ve employed 3 different tools and plug-ins which my blog interacted with: Buffer, Revive Old Post, and a standard Jetpack sharing tool. Buffer was fine, but the free version only allows 10 scheduled tweets – which required manual input on my part at the end of the day. I’m trying to decrease the time I spend on things like this, not increase them!

The Revive Old Post and standard Jetpack sharing tools were too rigid for me. The old posts were nearly the same every time it seems, and were never the ones I really wanted to share.

All of these are limited for what I was looking to do with my Twitter account. I wanted to be completely automated: tweeting out various quotes, old posts, and sharing other people’s posts, all without my involvement. For me, I wanted to send out about 60 tweets a week at specific times. To do so in Buffer would have taken quite some time, and possibly some money.

There is probably something out there that can do this, but I wanted to create something myself – I wanted to create something awesome.

With that said, let’s get into it.

First, what is Node.js?

What is Node.js?

This next sentence might be a little alarming.

Node.js is an open-source JavaScript run-time environment for executing JavaScript code server-side.

Okay, let’s try to break that down a little bit for you if you are not a coder.

  • Open-source code is code that any programmer can contribute to, making it community-based.
  • Javascript is one of the core web programming languages.
  • Run-time environment for executing code server-side is saying there has to be a space or location where the Javascript is being performed. You can think of it like a pan on a stove. The pan is Node.js – it allows us to be able to cook safely over a gas flame.

Putting it all together, we get a language which is highly capable, flexible, and easy to use with many technologies on the web.

How Can Node.js and Twitter interact?

At some point, we have to connect to Twitter.

For developers, the company, Twitter, created an application program interface (API) which provides numerous endpoints to build programs and solutions using Twitter.

What kinds of actions can we perform programmatically with the Twitter API?

There are a number of actions we can perform programmatically with the Twitter API.

I won’t list them all here, but you can do almost anything you could think of:

  • Tweet
  • Follow or unfollow a user
  • Send direct messages
  • Change your profile picture

With these simple actions in mind, we can go to the next step and actually learn how to build a Twitter bot with Node.js.

Getting started with our Twitter Bot

Okay, now we know what is possible with Node.js and the Twitter bot. – let’s get to the coding.

First though, we need to prepare our computer to be able to write the code and run our programs.

Step 1: Download and Install Node.js

Go to the Node.js website and download the LTS (long term support) option.

After downloading and installing Node.js, we can begin writing code.

Step 2: Download and Install a Text Editor of your Choice

Next, we need some software to help us write code: we need a text editor. There are a number of text editors out there, from Notepad (the most basic and simple text editor) to other solutions which are specifically used for programming.

I’m using VS Code, because it’s free and supports many different computer programming languages. Again, you may have your own favorite text editor, VS Code is just the one I use.

Step 3: Opening our Text Editor

At this point, we are ready to go. Our computer is able to run and execute Node.js code, and we have a place to write our code. I created a folder called “twitter_bot_example”, and opened that folder in VS Code. Here’s what our screen looks like at this point:

We are almost to the part where we connect to Twitter, but not quite there. The first thing we should talk about is Node.js packages.

Remember in our Node.js definition when it said something about being open-source?

Node.js packages are pieces of code which are created by various community members. These packages can be installed through the Node.js package ecosystem called npm and are completely free to use.

This is the beauty of open-source programming languages. We are going to use a number of packages for our Twitter bot.

Step 4: Getting Ready to Connect to the Twitter API

Let’s connect to Twitter.

First, we need to do 2 things. Let’s bring up the integrated terminal in VS Code (View -> Integrated Terminal).

The first thing is initializing our project with npm init. In the terminal at the bottom of the screen, type “npm init” and press enter.

npm init initializes the project and creates a package file for our program which will contain a bunch of information.

The command prompt asks for a few pieces of information:

  • package name: (twitter_bot_example)
  • version: (1.0.0)
  • description:
  • entry point: (index.js)
  • test command:
  • git repository:
  • keywords:
  • author:
  • license: (ISC)

At this point, a lot of this doesn’t matter since we are just testing. You don’t need to enter in anything if you don’t want to, using npm init is just good practice for creating a Node.js program.

Now, we are finally ready to go.

For the second thing we need to do, let’s install the Twitter Node.js open-source package we are going to use.

At the command line, enter in “npm install twit”. This will install the twit package. We are almost ready to go!

Step 5: Getting Access to the Twitter API

Okay, we need one more thing. We need our config file.

Go to the Twitter Apps page, create an account, and find the following pieces of information: consumer key, consumer secret, access token, and access token secret.

In the same folder as your program, put these pieces of information into a json object and save it as a .json file like so:

{
    "consumer_key":"xxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "consumer_secret":"xxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "access_token":"xxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "access_token_secret":"xxxxxxxxxxxxxxxxxxxxxxxxxxx"
}

We do this for security and flexibility reasons. We don’t want to hard code these values in.

Step 6: Connecting to the Twitter API

Okay, we are finally at the point where we can actually start coding and get tweeting!

Open a new file and save it as a Javascript file. I’ve called my file “index.js”.

In your file, we can now connect to Twitter and tweet. Let’s connect to Twitter through the Twit package. The following code will allow us to connect to Twitter:


const Twit = require('twit');
const options = Object.assign({'timeout_ms':60*1000}, require('./credentials_example.json'));
const client = new Twit(options);

Let’s walk through this code to get a little bit of an understanding of what’s going on. (also, as an aside, for non coders who want to learn how to code, I’d recommend Code Academy – it’s free)

The first line, we are telling our program we want to require that it uses the “twit” package we installed earlier.

The second line is reading in our credentials we got from the Twitter Applications website.

The third line is creating the connection between Twitter and our program.

It’s as simple as that! Now, let’s tweet from our program!

Step 7: Sending a Tweet

Sending a tweet with the Twit Node.js package is very easy. I’ve written a function which takes in a message, and will send a tweet with that message in it!

Here’s the code, and we will go through it in the paragraph after:

function sendTweet(message) {
    client.post('statuses/update', {status: message }, function(err, data,response) {
        if (err) {
            console.log(err);
        } else {
            console.log('Tweeted: ' + statusUpdate);
        }
    });
}
sendTweet("Hello World!");

First, I’m defining a function called sendTweet which takes in a variable called message. I can use this function later on in my code (and I do – in the example, I have a tweet which sends “Hello World!”)

In the Twit package that we installed before, there are functions (or also called methods) called post, get and delete. Computer science people are fairly simplistic: you use the get method to get information, you use the post method to send information, and the delete method to delete information (You can learn more about HTTP methods here, as going into these is beyond the scope of this article.)

To send a tweet, we want to use the post function, as we are going to be sending information to our Twitter account to create our tweet.

In the post function, we specify, in the first argument, that we want to send a status with the ‘statuses/update’ variable, and then we say in the second argument we want to use the user defined variable called ‘message’ for our status.

The rest of the function (the part inside the curly brackets { }) is something specific to Node.js – a callback function which can capture any data sent back to use. For our tweet, we will receive back a confirmation that the tweet has successfully been added to our account.

To run this code, in the terminal, type “node index.js” and you’ll send a Tweet saying “Hello World!”

Step 8: Reading a Website’s RSS Feed

The goal of this tutorial was not to just be able to send a tweet from the terminal. While that’s cool, let’s go another step. We are going to read a website’s RSS feed and tweet out a link to the most recent article.

We are going to install another Node.js package which will allow us to easily interact with the RSS feed of any site.

In the terminal, type “npm install feed-read-parser” and press enter. This will install the package.

Next, let’s make sure our program will use this package by including the require package statement at the top of our code:

const Twit = require('twit');
const rss = require('feed-read-parser');

Now, we want to use this rss feed parser to read a site’s rss feed and extract that information. At the end of the next step, we will be sending out the most recent RSS entry.

Step 9: Tweeting out the most recent RSS entry

Let’s put our RSS package to work.

Here’s the code to get the RSS entries from The Mastermind Within, select the most recent one, and then send a tweet with the title and link.


function tweetArticle() {
    rss("https://personalfinanceblogs.com/feed/", function(err,articles) {
        if(err) {
            throw new Error(err.message);
        } else {
            statusUpdate = "Check out this awesome post! " + articles[0].title + ' ' + articles[0].link;
            sendTweet(statusUpdate);
        }
    });
}

Again, I’ve created a function called tweetArticle, so we can use this over and over if we so choose. Inside the function, we are using the RSS package object (Object is the correct word to use here – the package is the actual code, and the object is the use of that code in the program).

The RSS object takes in the RSS Feed URL of whatever site you are looking for (https://personalfinanceblogs.com/feed/) and then returns the articles in that RSS feed.

Inside the callback function (the function which returns any data back to us), we get back the articles from the RSS feed. This articles data object contains things such as the content, publish date, title, author, and link. This articles object has a number of articles.

We want the most recent article. How can we get it? In Javascript, we can access the first entry of our article list by typing articles[0] (some programming languages start at 0).

Let’s create our message. We want to create a message which has the title and the link, and then send it out. We have the most recent article (articles[0]), and to get the title and the link, we do articles[0].title.

After storing our message in a variable called statusUpdate, we call the sendTweet function. Congrats on sending a Tweet with dynamic information!

Step 10: Scheduling Tweets for Certain Times

Congratulations! We are almost done automating this thing completely. At this point, if you want to run your application, like I mentioned above, type in the terminal “node index.js” (or whatever your file is called), and you will send a tweet.

Unfortunately, this will only send 1 tweet, and then the program will terminate. What if we want to do a certain action at 3 PM Every Monday? What if we want to tweet something out at 9 AM every day? We can use a scheduler!

Let’s install another package: node-schedule. node-schedule allows us to schedule things simply based on the time or day of week. In the terminal, type “npm install node-schedule” and then in our code, we will require(‘node-schedule’).

Let’s schedule our tweet to go out on Monday at 8 AM. This is as simple as the following line of code:


var tweet = schedule.scheduleJob({hour: 8, minute: 0, dayOfWeek: 1},tweetArticle);

As long as our program is running, we will be sending tweets out on Monday at 8 AM! We tell our node-schedule object (called schedule) to schedule a job at 8 AM, Monday, and this job executes the function “tweetArticle” at that time.

I scheduled the code we have written above to tweet at 2:30 PM this past Sunday. Here was the result:

rss twitter api example

There’s still one problem. What if I don’t want to run my program all day long on my computer? That’s where a virtual machine comes in.

Step 11: Setting up a Virtual Machine and Running the application continuously

At this point, we are 99% of the way there. This is where most tutorials stop online, as it’s almost like the writer knows you know can get to this next step.

It took me a week to realize this was the next step. I was running my application on my desktop and just keep my computer open. For security reasons, I don’t think this was the best idea, but I did it because I wanted to test my code.

It worked, but this past weekend, I went to visit a friend and wanted to bring my computer… if I shut down my laptop, then I’d have to terminate my program, and I wouldn’t want to do that!

Enter virtual machines.

What’s a virtual machine? A virtual machine is a server or computer you can remotely connect to and have running all the time. Microsoft Azure and Amazon Web Services are two of the leaders in this space.

For my application, I went with Microsoft Azure and got a $200 credit. My virtual machine is one of the lowest tier ones, and will end up costing about $13 per month. With a $200 credit, I will be running for free for the next 15 months – not bad!

I’m not going to go into the details here, because that would be another 1,000 words, and there are plenty of great resources on the Microsoft site.

After setting up your virtual machine, you can then go through the above steps (or just send your code to yourself via email) and run it continuously! Here’s my terminal (on my virtual machine) now running my Twitter bot!

twitter bot virtual machine

Next Steps

For me, I’ve done a couple more things for my Twitter bot, and now am running the application continuously with Microsoft Azure.

For you, it’s really dependent on what your goals are with the project. You are able to do a lot with the Twitter API: following, unfollowing, creating lists, analyzing the engagement of your tweets, and the list goes on and on! There is just so much!

As I’ve recommended a few other times on this site, check out Code Academy for free interactive Javascript interactive tutorials.

Also, Google is amazing for information. As you gain more experience, you will become better at this, but a simple google search of “how to read text files with node.js” (or whatever you want) will give you plenty of resources to check out.

Conclusion

I’m really excited to see where this takes my Twitter account. I’m learning so much about web development and absolutely loving it.

I think web development is my true calling. Hours pass without a care in the world. I’m creating some amazing things, and I’m really just getting started.

I hope you’ve enjoyed this tutorial and I’m looking forward to sharing with you the next application I build.

Readers: Did you find this tutorial on how to build a twitter bot using Node.js useful?What could I have done better explaining? Are you interested in programming?

Erik

P.S. here’s the full code from our example above:


const Twit = require('twit');
const rss = require('feed-read-parser');
const schedule = require('node-schedule');

const options = Object.assign({'timeout_ms':60*1000}, require('./credentials_example.json'));
const client = new Twit(options);

function sendTweet(message) {
    client.post('statuses/update', {status: message }, function(err, data,response) {
        if (err) {
            console.log(err);
        } else {
            console.log('Tweeted: ' + statusUpdate);
        }
    });
}
function tweetArticle() {
    rss("https://personalfinanceblogs.com/feed/", function(err,articles) {
        if(err) {
            throw new Error(err.message);
        } else {
            statusUpdate = "Check out this awesome post! " + articles[0].title + ' ' + articles[0].link;
            sendTweet(statusUpdate);
        }
    });
}

var cf = schedule.scheduleJob({hour: 16, minute: 30, dayOfWeek: 0},tweetArticle);