RoboKozo
RoboKozo

Reputation: 5062

How to stream tweets from specific accounts

I'm using the twitter npm package in an attempt to stream tweets from specified accounts.

I'm having trouble navigating the twitter api docs, so I'm a little confused.

I can hit the REST endpoint to get the specified user tweets info with:

    var client = new Twitter({});

    client.get('statuses/user_timeline', { screen_name: user }, function(error, tweets) {
      if(error) throw error;
      console.log(tweets);
    });

How do I stream the tweets? Is it even possible? If not, how else could I accomplish this? I would like this to be as responsive and immediate as possible.

Upvotes: 1

Views: 79

Answers (2)

RoboKozo
RoboKozo

Reputation: 5062

Figured it out...

    var stream = client.stream('statuses/filter', { follow: userId });

    stream.on('data', function(event) {
      console.log(event && event.text);
    });

This will client stream reader will display the tweets as they are made automatically.

Unfortunately, the screen_name of the user cannot be used, so you'll have to find that out beforehand.

Upvotes: 1

Damien
Damien

Reputation: 1600

I wrote the code below and was able to get last 20 tweets of a user and save them in a file log.txt.

var Twitter = require('twitter');
var fs = require("fs");

//Your keys go inside {}
var client = new Twitter({});

//These are the parameters for the API call
var params = {
    screen_name: 'damiengold', //use damiengold instead of @damiengold
    count: 20
};

//Perform the API call and return data
client.get('statuses/user_timeline.json', params, function(error, tweets, response) {
    var dataToFile;
    if (!error) {
        for (var i = 0; i < tweets.length; i++) {
            console.log(tweets[i].created_at + " " + tweets[i].text);
            console.log("-------------------------------");

            dataToFile = tweets[i].created_at + " " + tweets[i].text + "\n-----------\n";

            //This block of code will append tweets to the file called "log.txt".
            fs.appendFile("log.txt", dataToFile, function(err) {

                // If the code experiences any errors it will log the error to the console.
                if (err) {
                    return console.log(err);
                }
            })
        }
    }

    console.log("Last 20 tweets are now displayed on the screen and saved in log.txt.");

});

Upvotes: 0

Related Questions