404 truncated server response on Apps Script Bot
Asked Answered
H

1

-1

I'm trying to work on a chat bot for Hangouts that runs a function every day and sends a message. I started with the template on the Google Developers site, but I'm getting an 404 Truncated server response error while fetching the URL.

Error:

Truncated server response: <h1>Not Found</h1> <h2>Error 404</h2>

Here is the code:

function onTrigger() {
  var spaceIds = PropertiesService.getScriptProperties()
      .getKeys();
  var message = { 'text': 'Hi! It\'s now ' + (new Date()) };
  for (var i = 0; i < spaceIds.length; ++i) {
    postMessage(spaceIds[i], message);
  }
}

var SCOPE = 'https://www.googleapis.com/auth/chat.bot';
// The values below are copied from the JSON file downloaded upon
// service account creation.
var SERVICE_ACCOUNT_PRIVATE_KEY = "-----BEGIN PRIVATE KEY---- bla bla bla---END PRIVATE KEY-----\n";
var SERVICE_ACCOUNT_EMAIL = "blablabla";

//key and email deleted here for safety reasons.

// Posts a message into the given space ID via the API, using
// service account authentication.
function postMessage(spaceId, message) {

  var service = OAuth2.createService('chat')
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')
      .setPrivateKey(SERVICE_ACCOUNT_PRIVATE_KEY)
      .setClientId(SERVICE_ACCOUNT_EMAIL)
      .setPropertyStore(PropertiesService.getUserProperties())
      .setScope(SCOPE);
  if (!service.hasAccess()) {
    Logger.log('Authentication error: %s', service.getLastError());
    return;
  }
  var url = 'https://chat.googleapis.com/v1/' + spaceId + '/messages';
  UrlFetchApp.fetch(url, {
    method: 'post',
    headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
    contentType: 'application/json',
    payload: JSON.stringify(message),
  });event.type == "ADDED_TO_SPACE"
}

Any help will be appreciated.

Thanks in advance. Marcos

Howdy answered 18/1, 2020 at 7:45 Comment(0)
U
1

Answer:

The URL for creating a message in a space needs to be supplied in the form spaces/* where * is the space ID.

Fix:

You need to change your URL as per the documentation:

var url = 'https://chat.googleapis.com/v1/space/' + spaceId + '/messages';

References:

Ultimatum answered 20/1, 2020 at 11:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.