How to use Twitter API using Node.js


Today We will be learning How to talk to ‘Twitter’ using Twitter API. With ‘Twit Package’ of NPM(Node Package Manager), It got easier to directly talk to Twitter i.e Post tweets, read tweets, post multimedia and do other stuff, Sounds interesting to you, but wondering How to do it?
Come let’s do it.

The very first thing you need to install is Node into your system.
You can download node from here Click here to download Node
Once you have downloaded Node, 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 will have all the files. Now using the command line we will go the folder and type ‘npm init’. The moment you say npm init , It will ask a few questions like
name
version
description
entry point
test command
git repository
keywords
author
license
Once it is 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 Twitter API.Now we will make a js file inside our project
For example twitter-example.js

Inside our js file, we will write the code to connect to the Twitter API. Now how 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 script like this

package-json

Alright, Now 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 are these keys and tokens for, they are secret keys and access tokens which give access to use the twitter 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.

Step 1. Goto dev.twitter.com
Step2. Scroll down to the bottom and find Tools under this find ‘Manage my apps’
Step 3. On top right you will find ‘Create new app’
Step 4. Fill in your details Name, Description, website and agree to the Agreement
Step5 . Create your twitter Application
Step 6. Goto keys and access token, find your keys there
Step 7. Hit Create my access token and generate access token
If you are having trouble creating one please follow the link below
Generate Keys and tokens
Now you will have all the above-said keys and tokens with you. We will make use of those keys in out js file.

1.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 to run just type in
node searchTweets.js
You will have details related to your search.

2.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.

3.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.
4.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 complete source code, Plese click here

If you find any challenge, Do let me know in the comments.
If you enjoyed this post, I’d be very grateful if you’d help it spread.Keep smiling, Keep coding!

Advertisements

About deepak028

There is nothing much to describe me.However, I am a very ordinary person who believes in sharing knowledge.
This entry was posted in Scala. Bookmark the permalink.

One Response to How to use Twitter API using Node.js

  1. SUBHAM SAHU says:

    Hii, I need to authenticate the User with facebook & twitter, then i need their pages data into my project in node. Can you help me with the Code??

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s