Search code examples
javascriptjsonwebhookshangouts-api

Post to Google Hangouts with Webhook and GScript


Right now we use a Slack webhook to send important data from an email account into our Slack channel. Management wants us to switch to Hangouts and retain similar functionality with automated alerts. I tried adapting my slack gscript with no success. I even tried dumbing down the script as much as possible to eliminate potential errors. I want to use a webhook and not an API because it should be easier. I only need async messaging without the bot replying back.

I have used their python quickstart (which works well!), but my script is getting content from an email and then sending it to the webhook. GScript makes this easy (at least it was easy with Slack).

No matter what I try (I even copied Wesley's example exactly with no success)

Maybe I am doing something wrong, but at this point I can't figure out what. Any help would be much appreciated!

Omitting all the extra stuff about getting details from an email thread, as I can't even get the GScript to post a "Hello World" (only python)

var data = {
  text: "hello"
};

var payload = JSON.stringify(data);

var options = {
  method: "POST",
  ContentType: "application/json; charset=UTF-8",
  payload: payload,
  muteHttpExceptions: true
};

var webhook = 'https://chat.googleapis.com/v1/spaces/{space}/messages?key={key}&token={token}';
var response = UrlFetchApp.fetch(webhook, options);
Logger.log(response.getContentText());
[20-02-14 12:15:10:615 CST] {
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"{\"text\":\"hello\"}\": Cannot bind query parameter. Field '{\"text\":\"hello\"}' could not be found in request message.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "description": "Invalid JSON payload received. Unknown name \"{\"text\":\"hello\"}\": Cannot bind query parameter. Field '{\"text\":\"hello\"}' could not be found in request message."
          }
        ]
      }
    ]
  }
}

Solution

  • In order to be able to have the options sent properly, you should be using contentType instead of ContentType.

    After changing the parameter you can see that the message is sent accordingly.

    hello bot after changing the parameter

    You can also check this example for seeing the exact names for the parameters for the options you send the for the request.

    UrlFetchApp.fetch(url, {
        method: 'post',
        headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
        contentType: 'application/json',
        payload: JSON.stringify(message),
      });
    

    Reference