Giter VIP home page Giter VIP logo

node-twitter's Introduction

Twitter for Node.js

An asynchronous client library for the Twitter REST and Streaming API's.

Build Status NPM

var Twitter = require('twitter');

var client = new Twitter({
  consumer_key: '',
  consumer_secret: '',
  access_token_key: '',
  access_token_secret: ''
});

var params = {screen_name: 'nodejs'};
client.get('statuses/user_timeline', params, function(error, tweets, response) {
  if (!error) {
    console.log(tweets);
  }
});

Installation

npm install twitter

Quick Start

You will need valid Twitter developer credentials in the form of a set of consumer and access tokens/keys. You can get these here. Do not forgot to adjust your permissions - most POST request require write permissions.

var Twitter = require('twitter');

For User based authentication:

var client = new Twitter({
  consumer_key: '',
  consumer_secret: '',
  access_token_key: '',
  access_token_secret: ''
});

Add your credentials accordingly. I would use environment variables to keep your private info safe. So something like:

var client = new Twitter({
  consumer_key: process.env.TWITTER_CONSUMER_KEY,
  consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
  access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
  access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});

For Application Only based authentication:

You will need to fetch a bearer token from Twitter as documented Here, once you have it you can use it as follows.

var client = new Twitter({
  consumer_key: '',
  consumer_secret: '',
  bearer_token: ''
});

Add your credentials accordingly. I would use environment variables to keep your private info safe. So something like:

var client = new Twitter({
  consumer_key: process.env.TWITTER_CONSUMER_KEY,
  consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
  bearer_token: process.env.TWITTER_BEARER_TOKEN
});

NB - You will not have access to all endpoints whilst using Application Only authentication, but you will have access to higher API limits.

Requests

You now have the ability to make GET and POST requests against the API via the convenience methods.

client.get(path, params, callback);
client.post(path, params, callback);
client.stream(path, params, callback);

REST API

You simply need to pass the endpoint and parameters to one of convenience methods. Take a look at the documentation site to reference available endpoints.

Example, lets get a list of favorites:

client.get('favorites/list', function(error, tweets, response) {
  if(error) throw error;
  console.log(tweets);  // The favorites.
  console.log(response);  // Raw response object.
});

How about an example that passes parameters? Let's tweet something:

client.post('statuses/update', {status: 'I Love Twitter'},  function(error, tweet, response) {
  if(error) throw error;
  console.log(tweet);  // Tweet body.
  console.log(response);  // Raw response object.
});

Promises

The REST API convenience methods will also return Promises if:

  1. A callback is omitted
  2. Promise's are available.

If those two conditions are met, the above example becomes:

client.post('statuses/update', {status: 'I Love Twitter'})
  .then(function (tweet) {
    console.log(tweet);
  })
  .catch(function (error) {
    throw error;
  })

Note, the raw response object returned by the Request module is not passed through the fulfilled promise. If you require this, please use the callback pattern.

Streaming API

Using the stream convenience method, you to open and manipulate data via a stream piped directly from one of the streaming API's. Let's see who is talking about javascript:

var stream = client.stream('statuses/filter', {track: 'javascript'});
stream.on('data', function(event) {
  console.log(event && event.text);
});

stream.on('error', function(error) {
  throw error;
});

// You can also get the stream in a callback if you prefer.
client.stream('statuses/filter', {track: 'javascript'}, function(stream) {
  stream.on('data', function(event) {
    console.log(event && event.text);
  });

  stream.on('error', function(error) {
    throw error;
  });
});

Note twitter stream several types of events, see the docs for more info. There is no canonical way of detecting tweets versus other messages, but some users have had success with the following strategy.

_ = require('lodash')
const isTweet = _.conforms({
  contributors: _.isObject,
  id_str: _.isString,
  text: _.isString,
})

Examples

Contributors

Originally authored by @technoweenie and maintained by @jdub

Currently maintained by @desmondmorris

And we cannot forget the community

node-twitter's People

Contributors

alaaattya avatar barrycarlyon avatar chmac avatar chrisweb avatar desmondmorris avatar freeslave avatar gazzer82 avatar gnomus avatar greenkeeper[bot] avatar haruair avatar jdub avatar jmalonzo avatar juhq avatar k0t0fey avatar lyzadanger avatar medhir avatar miql avatar mulderp avatar oesmith avatar omarchehab98 avatar petitchevalroux avatar reconbot avatar rneilson avatar romaintb avatar roncli avatar ryantenney avatar sergiocrisostomo avatar technoweenie avatar tim-smart avatar utgwkk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-twitter's Issues

resource URL and method of home_timeline resource were updated

When retrieving home_timeline in streaming API, node-twitter use this.options.stream_base a.k.a. https://sitestream.twitter.com/1.1 and POST method in lib/twitter.js. However Twitter Dev document describes that https://api.twitter.com/1.1/statuses/home_timeline.json and GET method should be used now. Can you update the logic?

Thank you.

ReferenceError: query is not defined

My data being passed to twit.search callback has the value:

ReferenceError: query is not defined

It seems like the twit.search is getting fired twice for some reason. The first time I get the twitter JSON data, the 2nd time I get the error.

    twit.search(query, options, function(data) {
        c.log('twit.search', data);
        this.getTwitterSearch(data, options);
    }.bind(this));

in my log I see twit.search [json object] and then right after I also see: twit.search ReferenceError: query is not defined

I definitely am not calling it twice. I wonder if the module is firing it twice.

index.js program not running

I have Twitter installed via npm and created the index.js file below. When I run node index.js in the console I'm not getting any response. I've filled in the proper keys and tokens.

var Twitter = require('twitter');

var client = new Twitter({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
});

client.stream('statuses/filter', {track: 'nyc'}, function(stream){
stream.on('data', function(tweet) {
console.log(tweet.text);
});

stream.on('error', function(error) {
console.log(error);
});
});

Image Upload Issue

Image upload not working on the actual domain ..
Same code works fine in localhost / 127.0.0.1, but starts throwing 400 error while trying image upload on the actual server. Everything else works fine(like fetching profile, updating profile pics etc), except this :(

Here is my code.

authoVariable.post('media/upload', 
                      {'media': fs.readFileSync(req.files[file].path, { encoding: 'base64' })}, 
                       function(error, params, response){
                              if(error) console.log("media/upload error 1 "+error);
 });
am getting error media/upload error 1 Error: Status Code: 400

Stream Example

Can you give a stream example please.

I've treid client.get('statuses/sample', function(error, params, response){}); etting a "page not found" error frequenty.

Image posting?

Is it possible to post images with the current system?

twit.search -- does it use REST or stream?

Does this example use REST api or stream? Because I'm still getting disconnected when having more than one connection to the api. I thought that limitation was only for stream api.

twit.search('nodejs OR #node', function(data) {
    console.log(util.inspect(data));
});

diffrence search result from twitter.com search list

Ye~ nice module thank you.

the result from node-twitter search api have no data. but twitter.com 's search result have many tweets.

how can i solve this problem?

env : most used language is Korean(ko), nodejs 0.10.x

Noob Question - Search API

Hey! Apologies for the noob question here. At the minute I have this code and it's working well:

    twit.get('/search/tweets.json', {
        count: 50,
        q: '#hashtag -RT',
        result_type: 'popular'
    }

What I'd like to do is make use of the query parameters like 'since' and 'until' but I'm really not sure how to add this in. I thought it would be as simple as q: '#hashtag -RT since:2010-12-27' but I have come to no such luck.

If someone could point me in the right direction that would be superb!

No 'Access-Control-Allow-Origin' header is present on the requested resource.

Hello,
I am using node-twitter-api module in node js.I am facing cross domain issue while redirecting from Localhost to twiter login page .

Issues in details below :

XMLHttpRequest cannot load https://twitter.com/oauth/authenticate?oauth_token=. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1' is therefore not allowed access.

Bad Authentication data Code: 215

Hi,

I'm hitting a "Bad Authentication data" (Error code 215) and both consumer and access tokens are Ok and with the correct rights. Any idea?

[ { code: 215, message: 'Bad Authentication data.' } ]

var Twitter = require('twitter');

var client = new Twitter({
    consumer_key: 'xxx',
    consumer_secret: 'xxx',
    access_token_key: ' yyy',
    access_token_secret: 'yyy'
});

client.get('favorites/list', function(error, tweets, response){
    if (error) console.error(error);

    if (!error)
        console.log(tweets);  // The favorites.
});

var params = {screen_name: 'name'};
client.get('statuses/user_timeline', params, function(error, tweets, response){
    if (error) console.error(error);

    if (!error)
        console.log(tweets);
});

trends (new addition) not working

I'm trying to add functionality for closest trends in your api but im getting following error.

{ [Error: HTTP Error 400: Bad Request]
statusCode: 400,
data: '{"errors":[{"code":3,"message":"Invalid coordinates."}]}' }

Example of calling it :

twit.trends('lat=40.21777&long=-74.759361', function(data) {
console.log(util.inspect(data));
});

Implementation in twitter.js :

added this on line 46: trend_base: 'https://api.twitter.com/1.1/trends/closest.json',

and added following code,
Twitter.prototype.trends = function(q, params, callback) {
if (typeof params === 'function') { // is params = function
callback = params;
params = null;
}
if ( typeof callback !== 'function' ) {
throw "trends~: FAIL: INVALID CALLBACK.";
}
var url = this.options.trend_base;
console.log(' url :1 = ', url);
params = merge(params, {q:q});
console.log(' prams = ', params);
console.log(' callback = ', callback);
this.get(url, params, callback);
return this;
};

Socket hang up

Hi,

I'm using the Streaming API, and got this error a couple of times:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: socket hang up
  at createHangUpError (http.js:1472:15)
  at CleartextStream.socketCloseListener (http.js:1522:23)
  at CleartextStream.EventEmitter.emit (events.js:117:20)
  at tls.js:696:10
  at process._tickCallback (node.js:415:13)

I'm handling the stream.on 'error' event, so I'm unsure if I'm missing something on my end or if there's an error not being handled by the library. The error happens sporadically, so it's hard to debug/reproduce.
I tried looking in the code, but didn't yet find anything that might be causing this, any ideas?

Break update statuses when upgrading to 1.x

When I use pre 1.x with updateStatus, status length greater than 140 that contains URL automatically parsing with t.co

But now, I can't update status with status greater than 140 with URL

Breaks when called from 'use strict' file

When I try to use the api from 'use strict' and make the:
client.get('favorites/list', function(error, params, response) {}

I get the below error:
TypeError: Illegal access to a strict mode caller function.

the line (161) that checks for callee.caller.name breaks the api.
if (typeof Twitter.prototype[arguments.callee.caller.name] !== 'undefined') {

NOTE: If I remove that check, api works.

Error stacktrace:
TypeError: Illegal access to a strict mode caller function.
at Twitter.get (/Users/rraodv/Desktop/rin/node_modules/twitter/lib/twitter.js:161:48)
at exports.addTwitterFriends (/Users/rraodv/Desktop/rin/app/controllers/users/users.profile.server.controller.js:179:12)
at Layer.handle as handle_request
at next (/Users/rraodv/Desktop/rin/node_modules/express/lib/router/route.js:100:13)
at exports.requiresLogin (/Users/rraodv/Desktop/rin/app/controllers/users/users.authorization.server.controller.js:37:2)
at Layer.handle as handle_request
at next (/Users/rraodv/Desktop/rin/node_modules/express/lib/router/route.js:100:13)
at Route.dispatch (/Users/rraodv/Desktop/rin/node_modules/express/lib/router/route.js:81:3)
at Layer.handle as handle_request
at /Users/rraodv/Desktop/rin/node_modules/express/lib/router/index.js:227:24

Stream get disconnected somehow without any errors

I have a node.js app which is listening while the application is alive. Somehow it seems like the stream get disconnected but I can't seem to find any reason, neither an error. Any suggestion about how to manage this?

twit.stream('user', {track:'pcolazurdo'}, function(stream) {
stream.on('data', function(data) {
console.log(util.inspect(data));
if (typeof data.id_str !== 'undefined') insert_doc(data);
});
stream.on('error', function(data) {
console.log(util.inspect(data));
});
});

(No error is logged either)

Thanks in advance,
Pablo

Is a limit message a error?

I'm not sure if this i really a issue. I experience that limit notices submitted by the streaming API are emitted as 'error' event. But my interpretation of Twitter's docs is, that those messages are more like a 'warning'. Assuming that i am right with that, i believe that the implementation of the stream parser is somehow problematic, when using public streams API. The switch statement checks for json.event, which is only present in user streams. I assume that some error occurs during JSON.parse of the limit notice, but for now i cannot figure out why.

SyntaxError: Unexpected token U

Not entirely sure why, but statuses/firehose seems to be broken when using stream().

Other endpoints work fine, but this one isn't.

I'll work on a pull request but if someone has insight in the meantime it'd be appreciated.

TypeError: Illegal access to a strict mode caller function

When I am trying to use this module in strict mode:

node_modules\twitter\lib\twitter.js 161
if (typeof Twitter.prototype[arguments.callee.caller.name] !== 'undefined')
^
TypeError: Illegal access to a strict mode caller function.
at Twitter.get (c:\Users\Alexander\node_projects\xxx\node_modules\twtter\lib\twitter.js:161:48)
at getLists (c:\Users\Alexander\node_projects\xxx\lib\jobs\getCountresFromLists.js:27:14)
at getCountriesFromLists (c:\Users\Alexander\node_projects\xxx\lib\jbs\getCountriesFromLists.js:23:5)
at Object. (c:\Users\Alexander\node_projects\xxx\test\getCountriesFromListsTest.js:11:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)

Automatically Generating URL with oauth_token

Is there a way to generate oauth_token to point to Twitter app authentication?
Example:
https://api.twitter.com/oauth/authenticate?oauth_token=jju7hm7XCXzssASJP5w1g2779aHvL7AO
https://api.twitter.com/oauth/authenticate?oauth_token=VCbFzYbMxjF1YwnkEeJ80JWAEIUwqL41
https://api.twitter.com/oauth/authenticate?oauth_token=Vttjw9doS4Wn8JTj9vXgrpNofwXQbCmV

How to generate these oautho_token dynamically. And does node-twitter package support this?
If not, can anyone please let me know the best package to accomplish this.

I'm using node.js and angular.js

Inapropriate callback style

try {
      var json = JSON.parse(data);
      callback(json, response);
} catch(err) {
     callback(err, response);
}

callback(json, response);
should be
callback(null, json, response);

Use tweet.id_str instead of tweet.id when replying to a tweet

I don't know if it's a bug but when replying to a tweet, the in_reply_to_status_id value must be tweet.id_str and not tweet.id.

var s = '@'+tweet.user.screen_name+ ' the answer...';
client.post('statuses/update', {in_reply_to_status_id: tweet.id_str, status: s}, function(error, tweet, response){...});

If you do not do this, the new tweet will not be a reply, the tweet.id is not taken into account.
And do not forget to include the '@'+tweet.user.screen_name in the status as explained in Twitter documentation.

Issue with the twitter API and ntwitter package

I am trying to execute the below simple code. Yet the code isnt working. It shows 401 error.

What am i missing? I have loaded the ntwitter package and is present in one folder on my local machine. the same folder contains the below twitter.js file.

I am running this on Mac.

Not sure why its not returning me any data. Please suggest.

var http= require('http').createServer(),
util = require('util'),
twitter=require('ntwitter');
console.log(twitter);

http.listen(3000);

var twit= new twitter({

consumer_key: 'key',
consumer_secret: 'consumer_seceret',
access_token_key: 'access_token_key,
access_token_secret: 'access_token_secret'
});

twit.stream('statuses/filter',{track:['beiber']},function(stream){

stream.on('error', function(error, code) {
console.log("My error: " + error + ": " + code);
});

stream.on('data',function(data){

console.log(data.user.screen_name+ ' : ' +data.text);

});

});

Async Twitter

I'm using this module, and I need it to be asynchronous (for example: on Search) , there's a way to do this ?

Tracking all tweets

Hello, Its possible to track all tweets ? something like ...{track:'*'} ?

twit.search returns 404

Getting a 404 running the sample search bellow:

client.search('node OR #node', function(data) {
      console.log(util.inspect(data));
    });

data passed to callback was:

{ [Error: HTTP Error 404: Not Found]
  statusCode: 404,
  data: '{"errors":[{"message":"Sorry, that page does not exist","code":34}]}' }

twitter api version?

What version of the twitter API does this support?

Also, does the stream support searching? I want to get a stream of #node.js hashtag among all users.

How to format search queries

Hi there. Love this package.

I'm not sure how to include multiple parameters to the REST API.
I would like to search a particular users twitter feed for soundcloud and youtube links,
so I believe I should include these parameters:

from:user_name
filter:links
soundcloud OR youtube

But then I'm not surely exactly where to put these parameters

should it be in the "q" key object like this?

client.get('search/tweets', {q: "from:" +user_name " filter:links soundcloud OR youtube"},
function(error, userObject, response){
 console.log(response); 
});

Would you suggest achieving this goal a different way at all? thanks.

How to fetch users in a batch request?

Hi,

not sure if I am doing something wrong.

I am trying to request the profile information of my "friends". From

https://dev.twitter.com/docs/api/1.1/get/users/lookup

it looks like I need to make 2 requests. From the request to '/users/friends', I get IDs. Then, I need to pass an Array of IDs to fetch the profile information. The idea would be to pass an Array of IDs to:

twit.get('/friends/ids.json', function(d) {
  d.ids.slice(1, MAX).forEach(function(id) {
    twit.lookupUser(id, function(user) {
      // ... could be batch
    });
  });
});

Any idea how to do this?

Thanks!

track/untrack

Hi,

I need to manage in my app, adding track words, and untrack others, according to the user interactions.
Is there a way to handle my request?

Regards,
Vincent

Problem in Streaming API behind proxy

Hello Guys.

i am troubling in one issue from last 2 week. kindly some one help me to get out from these issue.

i want to use streaming on linux server under corporate proxy.

When i use following code for get favorate it will work fine

      var Twitter = require('../lib/twitter');

      var client = new Twitter({
        consumer_key: process.env.TWITTER_CONSUMER_KEY,
        consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
        access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
        access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
        request_options: {
          proxy: 'http://myproxyserver.com:1234'
        }
      });

      /**
       * Grab a list of favorited tweets
       **/
      client.get('favorites/list', function(error, tweets, response){
        if (!error) {
          console.log(tweets);
        }
      });

but when i replace get to stream it will get error ( Error 401 unauthorized )
i make sure my all keys and proxy is correct. following code i use.

      var Twitter = require('../lib/twitter');

      var client = new Twitter({
        consumer_key: process.env.TWITTER_CONSUMER_KEY,
        consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
        access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
        access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
        request_options: {
          proxy: 'http://myproxyserver.com:1234'
        }
      });

      /*
            Streaming "Mongo".
      */
        client.stream('statuses/filter', {track: 'mango'}, function(stream) {     
            stream.on('data', function(tweet) {
              console.log(tweet.text);
            });
          });

My server Time is also correct .
Thanks in advance.

Add friendships/lookup

Hi there

There doesn't seem to be an implementation of the friendships/lookup endpoint (i.e. querying up to a hundred relationships at a time), which happens to be important for my current project.

The endpoint takes either a bunch of screen names (the screen_name parameter) OR a bunch of user ID's (user_id), but it probably makes sense for the client's method to take an array of one or the other, and work it out for itself. So I guess you could do something this:

Twitter.prototype.lookupFriendships = function(users, callback) {
    var params = {};

    if (!isNaN(users[0])) { 
        params.user_id = users.join(',');
    } else {
        params.screen_name = users.join(',');
    }

    var url = '/friendships/lookup.json';
    this.get(url, params, callback);
    return this;
}; 

It's not very elegant - and would baulk if you passed it an empty array - but it works.

Add a timeout for the request

Hello!

I have been testing the library with a horrible Internet connection. The result is that the library blocks the application process waiting for a response from twitter (that never comes...)

Could you add a timeout option to stop the request if there is no response?

Thanks

Streaming options

Hi, I', using the streaming part of your package, and I got working the track option, but I can't seem to find any more options in the streaming api.

client.stream('statuses/filter', {track: 'keyword'}, function(stream) {

instead of track, what other options can i use? stream all tweets from someone, or maybe get all tweets in a specific location...

throw er; // Unhandled 'error' event

Here is my current code after require and create the twit object

twit.stream('statuses/filter', {track:"love"}, function(stream) {
    stream.on('data', function(data) {
        console.log(data.entities.media[0].media_url)
    });
});

I should be getting many ´undefined´ however all I get is the error in the title.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.