LoginSignup
5
2

More than 5 years have passed since last update.

GoogleAppsScriptからSlackに通知を送るスクリプト

Last updated at Posted at 2016-12-29

コピペで使える簡単スクリプト

1.Slackメッセージ送信用クラスを作る

Slack.gsファイルを新規作成する

#Slack.gs
(function(global){
  var Slack = (function() {

    function Slack(options){
      var options = options || {};
      this.url = options.url || "https://slack.com/api/chat.postMessage";
      this.token = options.token || "Slack API Token";  // APIトークン (デフォルト値を設定)
      this.channel = options.channel || "#channel_name";  // 通知するチャンネル (デフォルト値を設定)
      this.username = options.username || "username";  // ボットの名前 (デフォルト値を設定)
      this.icon_emoji = options.icon_emoji || ":icon:";  // ボットのアイコン画像を指定 (デフォルト値を設定)
    }

    Slack.prototype.send =  function(text) {
      var self = this;
      UrlFetchApp.fetch(self.url, {
        "method" : "POST",
        "payload" : {
          token: self.token,
          channel: self.channel,
          username: self.username,
          icon_emoji: self.icon_emoji,
          text: text
        }
      });
    };

    return Slack;
  })();

  global.Slack = Slack;
})(this);

2.メッセージ送るメインスクリプトを作成

#main.gs
function myFunction() {
  // デフォルト値を設定していればこれだけでOK
  var slack = new Slack();
  var msg = "Slackに通知したい";
  slack.send(msg);

  // optionsに引数を渡せば通知先などを変更できる
  var anotherSlack = new Slack({
    channel: "#another_channel",
    username: "another_username",
    icon_emoji: ":another_icon:"
  });
  var msg = "別のチャネルに通知したい";
  anotherSlack.send(msg);
}

以上!

トリガーを設定すれば簡単に定時つぶやきボットが作れますね。
Googleスプレッドシートのセルからメッセージを取得するようにすれば、簡単にメッセージ編集ができるようになります。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2