Search code examples
google-apps-scripttwitter

Twitter API for Non-public/organic/promoted metrics in Google Script


I'm trying to use the Twitter API in Google Script to get the non-public metrics of my posts. I believe have done all of the authentication properly since I am able to get the information when using Postman. I have generate a consumer_key, a consumer_secret, an access_token, and a token_secret. According to the twitter documentation , I MUST use Oauth1.0 (https://developer.twitter.com/en/docs/twitter-api/metrics).

In order use the Oauth1, I used Google's own script for Twitter Oauth1 (https://developers.google.com/google-ads/scripts/docs/examples/twitter-oauth10).

I was able to take that code (along with the library it required) and successfully retrieve the tweets for my username.

My attempt to get the non_public metric was replacing the "https://api.twitter.com/1.1/statuses/user_timeline.json" with the GET request I had from POSTMAN but it returned a "401 error".

I have a hunch that I can't just replace that url with my own but I am unsure how to approach it.

In summary:

  1. Tokens/Twitter Authorization/GET request are written properly since they work in Postman
  2. Google Script is writing properly since the default URL works
  3. Unsure how to replace the default url to accomplish different tasks

Solution

  • Ended up figuring it it out!

    I was not supposed to pass the entire url as a replacement for "https://api.twitter.com/1.1/statuses/user_timeline.json". It is supposed to be replaced by the "base" url. In my case this was "https://api.twitter.com/2/tweets". I then had to change the variable "params" that feed into it. note that the params is from the code provided by Google in my original post

    They have to be in the following format (https://developer.twitter.com/en/docs/tutorials/twitter-api-google-sheets): params = { "tweet.fields": "author_id,created_at,lang", "ids": "21,1293593516040269825,1334542969530183683", }

    I was able to add my own fields such as "non_public_metrics,organic_metrics" to get:

    params = { "tweet.fields": "author_id,created_at,lang,non_public_metrics,organic_metrics", "ids": "21,1293593516040269825,1334542969530183683", }

    I hope this helps someone someday :)