Retrieving The Tweets

Now that the Twitter application associated with the Bitcoin Sentiment Analyzer is created, we will be able to move on to retrieving tweets within our program. To do this, we will rely on the Twitter4J code library.

Twitter4J has as its entry point the TwitterFactory and Twitter classes.

The TwitterFactory class takes as input a Configuration object instance that contains the connection information to the Twitter API:

Consumer API Key

Consumer API Secret Key

Access Token

Access Token Secret

I will then retrieve an instance of a Twitter object instance from the TwitterFactory by calling its getInstance method. With this object, we will be able to launch queries on the Twitter API. We will use its search method to retrieve tweets matching certain criteria.

A query is modeled within the Query object which takes as input a string corresponding to the query that you want to execute via the Twitter API. In the case of the Bitcoin Sentiment Analyzer, I want to retrieve tweets containing the keyword bitcoin while not being retweets, links, answers or images.

This query is represented with the following string:

bitcoin -filter:retweets -filter:links -filter:replies -filter:images

The setCount method of the Query class allows you to define the number of results you want to retrieve. In the case of the free developer API, this number is limited to 100 results.

Finally, it remains to execute this query by passing it from the search method of the Twitter object instance. A QueryResult object is returned on which it remains to call the getTweets method to retrieve a list of Status objects. Each Status object represents a tweet. It is finally possible to access its textual content via the getText method of the latter object.

All this gives the following searchTweets method: