Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Use Twitter API With Node.js

DZone's Guide to

How to Use Twitter API With Node.js

A step-by-step tutorial of using Node.js to communicate with Twitter via the Twit NPM package, including setup.

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Today, we will learn how to integrate with Twitter using the Twitter API. With the Twit package of NPM (Node Package Manager). This makes it easier to directly talk to Twitter, i.e post tweets, read tweets, post multimedia, and do other stuff. Sounds interesting, right? So, how do we do it?

I'll show you...

The very first thing you need to do is install Node on your system. Click here to download Node,
and once you have it installed, check the version you are using by typing 'node –version'.

Now, to start a new project, we will make a new folder called 'Twit' or any other of your choice. This will be the project folder which contains all of the files. Now, using the command line, we will go the folder and type ‘npm init’. The moment you pass on npm init, you'll be prompted to provide:

name
version
description
entry point
test command
git repository
keywords
author
license

Once you're done, you will have a package.json file inside the project folder. A package.json file is a JSON file which is a settings or config file and contains dependencies.

After this, we will install the Twit package from npm using the following command 'npm install twit – -save'. Using — -save as an argument to npm install means save this as a reference to your package.json file ie. The dependency will be added to your package.json file.

Below is my package.json file which has ‘twit’ dependency.

package-json

Now we are done with installing the dependency.

Let’s set up our project to use the Twitter API. Now, we will make a JS file inside our project,
e.g. twitter-example.js.

Inside our JS file, we will write the code to connect to the Twitter API. Now, in order to run this file, all you need to do is type 'node twitter-example.js'. The moment you write this, the code inside the JS file will start to execute. You can also run your JS file like this: 'npm start'—but for that, you will have to make changes to your package.json.

Add a line:
"start" : "node twitter-example.js" inside the script like this:

package-json

Alright, we are done setting up the dependencies. Now, we will go to dev.twitter.com to generate:
1. consumer_key
2. consumer_secret
3. access_token
4. access_token_secret

If you are wondering what these keys and tokens are for, they are secret keys and access tokens which give access to use theTwitter API and let you play around with your account through your application/project. So, now we will generate them first. Let’s see how it is done:

  1. Go to dev.twitter.com

  2. Scroll down to the bottom and find 'Tools' under this find 'Manage my apps'

  3. On top right you will find 'Create new app'

  4. Fill in your details: Name, Description, Website, and agree to the agreement

  5. Create your Twitter application

  6. Go to the keys and access token, find your keys there

  7. Hit create my access token and generate the access token. (If you are having trouble creating one please follow this link: Generate Keys and tokens — Now you will have all of the above-said keys and tokens with you. We will make use of those keys in our JS file.

Search Post Using the Twitter API

Now that we have everything set up we will search for the particular post. Now, how do we do that?

We will create a new JS file inside the project and name it search.js and put our code like below.

console.log(“Example is up now..”) // just a console print to show example is up and running

var Twit = require('twit'); // this is how we import the twit package

var config = require('./config') //this is we import the config 
file which is a js file which contains the keys ans tokens

var T = new Twit(config); //this is the object of twit which 
will help us to call functions inside it

var params = {

q: 'akshay',

count: 100

} // this is the param variable which will have key and value 
,the key is the keyword which we are interested in searching and count 
is the count of it

T.get('search/tweets', params,searchedData); // get is the 
function to search the tweet which three paramaters 'search/tweets'
,params and a callback function.

function searchedData(err, data, response) {

console.log(data);

} // searchedData function is a callback function which 
returns the data when we make a search


Now, in order to ru,n just type in node search Tweets.js. You will have details related to your search.

Post the Tweets Using the Twitter API

Now that we have already seen how to search post and tweets, we will now post a Tweet using the API.

We will create a new JS file inside the project and name it post-tweet.js and put our code like below.

console.log(“Example is up now..”)

var Twit = require('twit');

var config = require('./config')

var T = new Twit(config);

var tweet = {

status: 'hello world!!' } // this is the tweet message

T.post('statuses/update', tweet, tweeted) // this is how we 
actually post a tweet ,again takes three params 'statuses/update' , 
tweet message and a call back function

function tweeted(err, data, response) {

if(err){

console.log("Something went wrong!");

}

else{

console.log("Voila It worked!");

}

} // this is the call back function which does something if 
the post was successful or unsuccessful.


Now to run just type in node post-tweet.js. You will have details related to your post.

Schedule a Tweet Using SetInterval Function

Now that we have seen how to post a tweet, let’s see how can we schedule a tweet every x seconds or every x minutes or x hours.

We will create a new JS file inside the project and name it schedule-tweet.js and put our code like below.

console.log("Example is up now..")

var Twit = require('twit');

var config = require('./config')

var T = new Twit(config);

setInterval(tweetScheduler,1000*20); // setinterval 
function to schdule posting of a tweet ,it is every 20 seconds,
1000 is the milliseconds which is equal to 1 seconds

tweetScheduler(); // function which posts a tweet

function tweetScheduler(){

var randomNumber = Math.floor(Math.random()*1000);

var tweet = {

status: randomNumber+'#hiii!!' }

T.post('statuses/update', tweet, tweeted)

function tweeted(err, data, response) {

if(err){

console.log("Something went wrong!");

}

else{

console.log("Voila It worked!");

}

}

} // this is the function which makes post to the twitter


Now to run just type in node schedule-tweet.js. You will have details related to your scheduled tweets.

Streaming Example on Follow Event

Now that we have seen search, post, and schedule a tweet. Let’s see what all we can do if somebody follows us.

We will create a new JS file inside the project and name it stream.js and put our code like below.

console.log("Example is up now..")

var Twit = require('twit');

var config = require('./config')

var T = new Twit(config);

var stream = T.stream('user'); //open a stream object

stream.on('follow',followed); // stream on follow event

function followed(eventMsg){

console.log('FOllow event');

var name = eventMsg.source.name;

var screenName = eventMsg.source.screen_name;

tweetMessage('@'+screenName+"Thank you for following me!")

} // callback function for follow event

function tweetMessage(txt){

var tweet = {

status: txt }

T.post('statuses/update', tweet, tweeted)

function tweeted(err, data, response) {

if(err){

console.log("Something went wrong!");

}

else{

console.log("Voila It worked!");

}

}

}


Now to run just type in node stream.js.

For the complete source code, please click here.

If you come across any issues, please let me know in the comments. If you enjoyed this post, I’d be very grateful if you’d share it. Keep smiling, keep coding!

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
new ,twitter ,file ,package

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}