Connecting a Node App to Twitter
To connect to Twitter from Node, use the wonderful module called ntwitter (which was forked from node-twitter, which was inspired by twitter-node). The ntwitter module makes it easy to interact with Twitter but, more importantly, it has support for Twitter’s stream API, which means that you can get tweets sent to you in real time as opposed to polling Twitter on a regular basis.
Sending Your First Tweet
While you install the module via NPM, for reference the source code for the ntwitter module is up on GitHub at https://github.com/AvianFlu/ntwitter.
To start, create a new directory called hangman for the application and put the customary package.json file in it to pull in ntwitter as a dependency (see Listing 22-1).
Listing 22-1: Package.json
{
"name": "twitter-hangman"
, "version": "0.0.1"
, "private": true
, "dependencies": {
"ntwitter": "0.3.0"
}
}
Run npm install to install the ntwitter dependency.
Next, try out tweeting via the API; open a new app.js file and fill in the code from Listing 22-2. You need to replace the configuration values for the keys and secrets in uppercase with the values from the previous section. Run the code by running node app.js from the command line.
Listing 22-2: App.js sending your first tweet
var twitter = require("ntwitter"); var client = new twitter({ consumer_key: "YOUR_CONSUMER_KEY", consumer_secret: "YOUR_CONSUMER_SECRET", access_token_key: "YOUR_ACCESS_TOKEN_KEY", access_token_secret: "YOUR_ACCESS_TOKEN_SECRET" ...
Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.