ratnakar vanapalli
ratnakar vanapalli

Reputation: 31

how to get twitter analytics using twitter gem rails?

I want to get twitter analytics for tweets I posted using twitter gem in my ruby on rails application. Is there any possibility to achieve this ? I want to show tweet impression on my application,please let me know if there is any possible way .

Upvotes: 1

Views: 646

Answers (1)

Daniel Bonnell
Daniel Bonnell

Reputation: 4997

You can pull engagement data for your account as a whole. On a per-tweet basis you can pull in a favorites count as well as a retweet count. Here is an example the latter:

First define your client like so:

client = Twitter::REST::Client.new do |config|
    config.consumer_key        = Devise.omniauth_configs[:twitter].strategy.consumer_key
    config.consumer_secret     = Devise.omniauth_configs[:twitter].strategy.consumer_secret
    config.access_token        = self.identities.find_by(provider: :twitter).token
    config.access_token_secret = self.identities.find_by(provider: :twitter).token_secret
end

Now define the API endpoint you want to pull data from along with an array of tweet ids you want to get data on:

path = "1.1/statuses/lookup.json"
ids = ['1234567890','56324931407']

Now call the API and do something with the response:

response = Twitter::REST::Request.new(client, 'get', path, {id: ids, map: true}).perform

The result you get back will be a JSON hash where the keys are the post ids. Calling map: true in the options hash tells the API to include missing post keys with a null value, rather than excluding them from the response. You can read more in the docs on the Twitter::REST::Request class.

Note that with the Twitter::REST::Request class you can specify any path and/or method from the API.

If you want to calculate engagement data for your account, you will have to pull in a large batch of tweets (say 100) and then parse the response and calculate the rate yourself, as Twitter doesn't offer that data through the API in a prepackaged way. This Quora post goes into more detail on how you can calculate the engagement rate yourself.

As for pulling impression data, that is not currently possible through the public API. See this discussion for more details.

Upvotes: 1

Related Questions