Hugo Sainte-Marie
Hugo Sainte-Marie

Reputation: 312

Connect to Twitter API with Google Script — oAuth error

I'm having lots of trouble finding out how to connect to my Twitter with a Google Script via oAuth authentication. I'm kind of a newbie and I'm really unsure about the many things that could be wrong in my code.

function getTwitterService() {
return OAuth1.createService('twitter')
    .setAccessTokenUrl('https://api.twitter.com/oauth/access_token')
    .setRequestTokenUrl('https://api.twitter.com/oauth/request_token')
    .setAuthorizationUrl('https://api.twitter.com/oauth/authorize')

    .setConsumerKey('xxxxxxxxxxxxxxxxxxxxxxxxx')
    .setConsumerSecret('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')

    .setCallbackFunction('authCallback')

    .setPropertyStore(PropertiesService.getUserProperties());
}

function tweet() {
  var options =
   {
     "oAuthServiceName" : "twitter",
     "oAuthUseToken" : "always",
     "method" : "post"
   };

   UrlFetchApp.fetch("https://api.twitter.com/1.1/statuses/update.json?status=Hi", options);
}

I'm pretty sure my Twitter Application is authorized, since it appears as a read-write application in my https://twitter.com/settings/applications, and also i fired this function ...

function logAuthorizationUrl() {
  var twitterService = getTwitterService();
  if (!twitterService.hasAccess()) {
    var authorizationUrl = twitterService.authorize();
    Logger.log(authorizationUrl);
  } else {
    Logger.log('We already have access don\'t we?');
  }
}

... and it does log that custom message.

Still I'm getting an error (sorry french copy/paste).

Échec de la requête pour https://api.twitter.com/1.1/statuses/update.json?status=Hi. Code renvoyé : 400. Réponse tronquée du serveur : {"errors":[{"code":215,"message":"Bad Authentication data."}]} (Utilisez l'option muteHttpExceptions pour examiner la réponse entière.) (ligne 51, fichier "")

So as you guessed, my main problem here is {"errors":[{"code":215,"message":"Bad Authentication data."}]}

Any idea what I'm missing ?

Upvotes: 0

Views: 439

Answers (1)

Jens Astrup
Jens Astrup

Reputation: 2454

It looks like the problem is that you're using POST, but not indicating the payload - see the Google Documentation for UrlFetchApp, specifically the payload parts (they actually use twitter as the example there).

Usually, I test out my answer before posting, but there are a few more hoops involved for this question. Going off the twitter API documentation though I'm confident that should at least help. Also, I'm sure you've already gone here, but just in case - the response from twitter will be in JSON, which this documentation can help you parse.

Upvotes: 1

Related Questions