paint-brush
Build a simple Twitter Bot with Node.js Part 2: DO MOREby@bmorelli25
1,385 reads
1,385 reads

Build a simple Twitter Bot with Node.js Part 2: DO MORE

by Brandon MorelliJune 2nd, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In case you missed it, recently I published <a href="https://hackernoon.com/build-a-simple-twitter-bot-with-node-js-in-just-38-lines-of-code-ed92db9eb078"><strong><em>Build a simple Twitter Bot with Node.js in just 38 lines of code</em></strong></a><strong><em>. </em></strong>A lot of readers reached out to me on <a href="https://twitter.com/BrandonMorelli">Twitter</a> asking how they could add functionality to their bot: following, replying, tweeting, unfollowing, etc. The answer is very easily — and in this article I will show you&nbsp;how.

People Mentioned

Mention Thumbnail

Company Mentioned

Mention Thumbnail
featured image - Build a simple Twitter Bot with Node.js Part 2: DO MORE
Brandon Morelli HackerNoon profile picture

In case you missed it, recently I published Build a simple Twitter Bot with Node.js in just 38 lines of code. A lot of readers reached out to me on Twitter asking how they could add functionality to their bot: following, replying, tweeting, unfollowing, etc. The answer is very easily — and in this article I will show you how.

Before we get started, you need to have followed the Create an Application and Configuration chapters in my Build a simple Twitter Bot with Node.js in just 38 lines of code article. This will show you how to set up a Twitter Application, and create our file structure. You should have a directory named twitter-bot with multiple files: app.js, config.js, and a package.json file. We will be using this same directory for this tutorial.

Ready to start? Before we do, something important:

You can already do this

Yup, you can — and that’s kind of the entire point of this article. If you followed along with my first tutorial, and understood what we were doing, then adding this new functionality will be easy.

Think about it like this. In the initial tutorial we search for tweets using a query, then like the corresponding tweet. The act of liking a tweet was only about 12 lines of code (including my commenting). In this tutorial, we’ll be searching for tweets using a query, then following the user that did the tweeting. Everything should be the same in this tutorial except those 12 lines of code.

See, the hard part is already done. We’ve already determined what dependencies to use, passed in our configuration, set up our params object, searched for Tweets, and looped through the results. Now, we just have to determine what to do with the results…

Documentation

Ah yes, read the docs. The Twitter Rest API Reference Documentation can be found here. This link outlines everything we can do with our Twitter API.

In the first tutorial we looked at the POST favorites/create route which allows us to favorite a tweet. But there are almost 50 POST requests in the documentation! Things like:

It doesn’t matter which POST request we are trying to make, there are three pieces of information we need: The route, the parameters object, and the callback.

When working with the Twitter API and npm Twitter package, every post request looks like this:

T.post('route', {params}, function(err, response){
  // Test for Errors
  // If no errors, log success
});

That’s why documentation is so important. We have the template, we just need the data to put into it. The documentation has everything we need. We can use the route and parameters listed in the docs to build our get requests and make them happen!

Lets build another bot

In this example, we’ll follow users who tweeted using the #nodejs hashtag. Using the documentation, we can find that the POST friendships/create route is used for following users.

All of the code for this tutorial can be found in my GitHub Repository

Create a file named follow.js and copy over the entire app.js file. Again, all we care about is what happens inside our for loop while we loop through our returned tweets. Remove the following from our follow.js code:

// Get the tweet Id from the returned data
let id = { id: data.statuses[i].id_str }
  // Try to Favorite the selected Tweet
  T.post('favorites/create', id, function(err, response){
    // If the favorite fails, log the error message
    if(err){
      console.log(err[0].message);
    }
     // If the favorite is successful, log the url of the tweet
     else{
       let username = response.user.screen_name;
       let tweetId = response.id_str;
       console.log('Favorited: ', `https://twitter.com/${username}/status/${tweetId}`)
     }
   });

Perfect, now we have an empty for loop that loops through our array of returned tweets:

for(let i = 0; i < data.statuses.length; i++){
  // THE FOLLOWING MAGIC GOES HERE
}

We know we’re using the friendships/create route, and according to the documentation, this post route requires the username of the person we want to follow. Luckily, this is returned to us when we run our initial tweet search. We can access the username with the following code:

for(let i = 0; i < data.statuses.length; i++){
  let screen_name = data.statuses[i].user.screen_name;
}

With the screen name saved, we can type out our friendships/create POST route:

for(let i = 0; i < data.statuses.length; i++){
  let screen_name = data.statuses[i].user.screen_name;
  
  T.post('friendships/create', {screen_name}, function(err, res){
    if(err){
      console.log(err);
    } else {
      console.log(screen_name, ': **FOLLOWED**');
    }
  });
}

Remember, our POST request returns a callback function which we need to check for an error in. If there was an error (we couldn’t follow the user) then the error is logged to the console. If we successfully followed the new user, we log the users screen_name along with a ‘**FOLLOWED** message.

Now just type into the console to run the bot:

node follow.js

BOOM.

Pretty cool huh? Change the route, adjust the parameters, and five minutes later the original favorite bot is now a follow bot!

Go explore the Twitter documentation and see what other cool things you can buid!

❤ If this post was helpful, please hit the little green heart!

If tutorials like this interest you and you want to learn more, check out my 5 Best Courses for Learning Full Stack Web Development. If bots are more your thing, check out Three awesome courses for learning Node.js.

Please also consider following me on Twitter