Search code examples
twittergoogle-apps-scriptgoogle-sheetstwitter-oauth

accessing Twitter API from Google Apps Script


I'm trying to read in a Google sheet my Twitter timeline. I've copied the following code reported in the GAS documentation about twitter authentication (omitting step 2 since I'm not using the code inside a UI):

function getTwitterService() {
  // Create a new service with the given name. The name will be used when
  // persisting the authorized token, so ensure it is unique within the
  // scope of the property store.
  return OAuth1.createService('twitter')
      // Set the endpoint URLs.
      .setAccessTokenUrl('https://api.twitter.com/oauth/access_token')
      .setRequestTokenUrl('https://api.twitter.com/oauth/request_token')
      .setAuthorizationUrl('https://api.twitter.com/oauth/authorize')

      // Set the consumer key and secret.
      .setConsumerKey('mykey')
      .setConsumerSecret('mysecret')

      // Set the name of the callback function in the script referenced
      // above that should be invoked to complete the OAuth flow.
      .setCallbackFunction('authCallback')

      // Set the property store where authorized tokens should be persisted.
      .setPropertyStore(PropertiesService.getUserProperties());
}

function authCallback(request) {
  var twitterService = getTwitterService();
  var isAuthorized = twitterService.handleCallback(request);
  if (isAuthorized) {
    return Logger.log('Success! You can close this tab.');
  } else {
    return Logger.log('Denied. You can close this tab');
  }
}

function makeRequest() {
  var twitterService = getTwitterService();
  var response = twitterService.fetch('https://api.twitter.com/1.1/statuses/user_timeline.json');
  Logger.log(response);
}

but I obtain the message error: Service not authorized. (row 292, file "Service", project "OAuth1").

What's wrong?


Solution

  • I needed to add the following line the first time I execute makeRequest:

    var authorizationUrl = twitterService.authorize();
    Logger.log(authorizationUrl);
    

    Then, open the url read from the log and authorize the app.

    After that, all works fine.