0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【GAS】Slackにダイレクトメッセージを送る

Last updated at Posted at 2023-04-16

slackのユーザーのchannelIDは下記の手順で一括取得
https://qiita.com/80syokumotsu/items/46205cd71da5cd2d6ce1

tokenは下記の手順で登録
https://qiita.com/80syokumotsu/items/bf1043606289a28f1d02

const slack_app_token5 = PropertiesService.getScriptProperties().getProperty("slack_token");
//botからDMを送る
//function postDM() {
function postDM2(id,text) {

  //【処理1】DMを開き、チャンネルIDを取得する
  var channel_id = id
  const message = text;
  //var channnel=id

  //var getchannelid=getChannelID_(id)
  //Logger.log(getchannelid)
 // channel_id=	getchannelid
  
  Logger.log(channel_id)
  //【処理2】指定の[チャンネルID]にDMを送信する
  const message_options = {
    "method" : "post",
    "contentType": "application/x-www-form-urlencoded",
    "payload" : {
      "token": slack_app_token5,
      "channel": channel_id,
      "text": message
    }
  }
  //必要scope = chat:write

  const message_url = 'https://slack.com/api/chat.postMessage';
  UrlFetchApp.fetch(message_url, message_options);
}
/**
* メンバーIDを受け取りチャンネルIDを返す
*
* @param {string} メンバーID
* @return {string} チャンネルID
*/
function getChannelID_(id) {
  const options = {
    "method" : "post",
    "contentType": "application/x-www-form-urlencoded",
    "payload" : {
      "token": slack_app_token5,
      "users": id
    }
  }
  //必要scope = im:write
  const url = 'https://slack.com/api/conversations.open';
  const response = UrlFetchApp.fetch(url, options);
  const obj = JSON.parse(response);
  console.log(obj);
  return obj.channel.id;
}

function getMassage(){
 //var sheets = SpreadsheetApp.openById('スプレッドシートのID');
  var sheets = SpreadsheetApp.getActiveSpreadsheet();
  //「"フォームの回答 1"」のシート情報を取得し「fmSheet」に代入
  var fmSheet =sheets.getSheetByName("フォームの回答 1");
  //シート「フォームの回答 1」のC列の最終行取得
  var fmSheetlastRowC = fmSheet.getRange(1, 3).getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow();
  //シート「フォームの回答 1」の最終行のM(13列目)列の値がchannelIDなのでidに入れる
  var id= fmSheet.getRange(fmSheetlastRowC,13,1,1).getValue();
  //シート「フォームの回答 1」の最終行のG(7列)列の値が送信したいメッセージ内容なので取得してtextに入れる
  var text = fmSheet.getRange(fmSheetlastRowC,7,1,1).getValue();
  Logger.log(id);

  Logger.log(text);
  postDM2(id,text)

}

参考にしたサイト:https://moripro.net/gas-slackapi-bot-send-dm:

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?