How to Send Slack Messages with Google Apps Script (GAS)

Tadashi Shigeoka ·  Sat, February 1, 2020

I’ll introduce sample code for sending Slack messages with Google Apps Script.

slack

Creating a Slack App

First, create a Slack App by referencing the following article:

? Slack API 推奨Tokenについて - Qiita

Sending Slack Messages with GAS + Slack API

Execute Slack API with curl

After creating the Slack app, use the curl script available from the admin screen to confirm that the Slack API can execute properly.

curl -X POST \\
-H 'Content-type: application/json' \\
--data '{"text":"Hello, World!"}' \\
https://hooks.slack.com/services/XXX/YYY/ZZZ

(Sample Code) Sending Slack Messages with GAS

Here’s sample code for sending Slack messages using the Slack API with Google Apps Script:

function postSlackMessage(text) {
  var data = {
    text: text
  };
  var options = {
    'method' : 'post',
    'contentType': 'application/json',
    'payload' : JSON.stringify(data) // Convert the JavaScript object to a JSON string.
  };
  
  UrlFetchApp.fetch(
    PropertiesService.getScriptProperties().getProperties().SLACK_URL,
    options
  );
}

For how to configure and use PropertiesService.getScriptProperties().getProperties().SLACK_URL, please refer to the following article:

? GoogleAppsScript スクリプトのプロパティの超簡単な使い方 - Qiita

Request to https://hooks.slack.com failed (Error: 400)

If you get an error message like the one below when executing Google Apps Script, the above postSlackMessage method should work fine, so try copying and implementing it entirely.

Message Details

Request to https://hooks.slack.com failed (Error: 400). Server response excerpt: invalid_payload (use muteHttpExceptions option to see full response) (line 43, file “Code”)

That’s all about wanting to send messages to Slack with Google Apps Script from the Gemba.

Reference Information