Since mid June this year, Twitter has forced users to use OAuth to authenticate and access its API. You can no longer access its data in a trivial way like the GitHub example before. You must get 4 keys from Twitter’s developer page: Consumer key
, Consumer secret
, Access token
and Access secret
– don’t need to know what they mean yet, but be sure that the 2 secret keys are not shared. OAuth is a real pain. These 4 keys won’t give you access. They’ll let you get 3 more one use keys which you can then use to access the API.
Fortunately for you as a Ruby user, there are two libraries that will do all the menial work for you. Twitter is a conveniently named library to access the standard Twitter API (it is not developed by Twitter Inc) while the other, TweetStream is designed to use Twitter’s streaming API (kind of like email pushing on your phone). It’s unlikely that you’ll need to use the streaming API for this assignment so I won’t be showing you TweetStream.
Twitter Gem
Install the twitter gem with gem install twitter
and make the following config file, replacing the upper case strings with the relevant keys.
1 2 3 4 5 6 |
|
There are some usage examples here, but there’s plenty more functionality so do refer to the documentation.
1 2 |
|
Lets find the last person to have proposed to Justin Bieber
1 2 3 4 5 6 7 |
|
Just to give another example, I’m going to get the last tweet from each of the users I’m stalking.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
Because we don’t care about the return value, let’s not do this in irb
1 2 3 4 5 6 7 8 |
|
But there’s still a problem, I’m following more users than this.
This is because Twitter paginates the results to 20 by default. So if there is more than 20 records, you’ll have to iterate through each page to get all the results.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Just to a more relevant example, this is to get the last 200 tweets with #ausvotes excluding retweets. Search results pagination work slightly different to friends – refer to documentation!!
Note that the count parameter refers to the number you want per page, although the maximum is 100.
1 2 3 4 5 6 7 8 9 10 11 12 |
|