Search code examples
google-apps-scriptgoogle-chat

Unsolicited response from Google Chat API


I did so according to the instructions given here But the result is not desirable

function myFunction() {

  var url = 'https://chat.googleapis.com/v1/spaces/AAAA*******'
  var options = {
    method: 'GET',
    headers: {"Authorization": 'Bearer ' + ScriptApp.getOAuthToken()},
    muteHttpExceptions: true,
  };
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response)
}

And this is how the permissions look in the manifest

"oauthScopes": [
  "https://www.googleapis.com/auth/script.external_request",
  "https://www.googleapis.com/auth/chat.spaces"
]

But the result I got is an unwanted result

{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.ErrorInfo",
        "reason": "CREDENTIALS_MISSING",
        "domain": "googleapis.com",
        "metadata": {
          "method": "google.chat.v1.ChatService.GetSpace",
          "service": "chat.googleapis.com"
        }
      }
    ]
  }
}

What can cause a 401 error

editing

I wrote the permissions incorrectly the first time but that is not the cause of the problem because even if I write correctly the problem exists I corrected above to the new code


Solution

  • The headers need to be specified correctly:

    function myFunction() {
    
      var url = 'https://chat.googleapis.com/v1/spaces/AAAA*******'
      var options = {
        method: 'GET',
     
        // THIS
        headers: { 
          "Authorization": 'Bearer ' + ScriptApp.getOAuthToken(),
        },
    
        // NOT THIS
        // Authorization: 'Bearer ' + ScriptApp.getOAuthToken(),
    
        muteHttpExceptions: true,
      };
    
      var response = UrlFetchApp.fetch(url, options);
      Logger.log(response)
    }