
前提・実現したいこと
GASで指定列に指定文字列が入力(手動入力ではない)されたら、Slack通知を飛ばすGASを作成したい。
発生している問題・エラーメッセージ
下記に貼り付けたコードを作成しましたが、Slack通知が飛びません。
調べてみると、スクリプト等で自動で入力される場合は、トリガーの「編集時」には当てはまらないということがわかりました。
ただ調べてみても、その問題の解決方法がよくわからず質問させていただきました。
該当のソースコード
GAS
1//送付エラーのタイムスタンプ/件名/本文/メールIDをスプレッドシートに吐き出す 2 3function getGmailToSS() { 4const ss = SpreadsheetApp.getActiveSpreadsheet(); 5const sheet = ss.getSheetByName('errordata_gmail'); 6 7const searchlabel = '"送付エラー"'; 8 9const threads = GmailApp.search('label:(' + searchlabel + ') -label:処理済み'); 10 11const msgIdArray = sheet.getRange("D:D").getValues().filter(String).flat(); 12let lastRow = msgIdArray.length + 1; 13 14for(const n in threads){ 15 const thread = threads[n]; 16 const msgs = thread.getMessages(); 17 msgs 18 19for(m in msgs){ 20 const msg = msgs[m]; 21 const id = msg.getId(); 22 23 if(msgIdArray.includes(id)) continue; //IDがD列に既に存在する場合はスルー 24 25 26 const msgData = [[msg.getDate(),msg.getSubject(),msg.getPlainBody(),id]]; 27 sheet.getRange(lastRow,1,1,4).setValues(msgData); //まとめて書き込み 28 29 lastRow++ 30 } 31 32 33const label = GmailApp.getUserLabelByName('処理済み'); 34 thread.addLabel(label); 35 } 36 37 38 // スプレッドシートから必要なデータを読み取り、スラックに投稿する。 39 const staffErrorEmail = sh.getRange(writeRow, 5).getValue(); //5=E列(送付エラーアドレス) 40 const staffName = sh.getRange(writeRow, 6).getValue(); //6=F列(スタッフ名) 41 const temphireId = sh.getRange(writeRow, 7).getValue(); //7=G列(ID) 42 const slackId = sh.getRange(writeRow, 9).getValue(); //9=I列(SlackID) 43 44 const message = slackId + '\n' + staffName + '\n' + staffErrorEmail + temphireId; 45 postToSlack(message); 46 47} 48 49 50function postToSlack(message){ 51 const postToMDS = "通知先のWebhooksURL"; // 52 53 const jsonData = 54 { 55 "text" : message, 56 }; 57 58 const payload = JSON.stringify(jsonData); 59 60 const options = 61 { 62 "method" : "post", 63 "contentType" : "application/json", 64 "payload" : payload, 65 }; 66 67 // リクエスト 68 UrlFetchApp.fetch(postToMDS, options); 69} 70
補足情報
トリガー設定
関数:getActiveCell
デプロイ時に実行:Head
イベントソース:スプレッドシートから
イベント種類:編集時
GASのif文で条件にしているスプレッドシートのJ列には下記関数を入れております。
=ARRAYFORMULA(IF(I3:I="","","SlackID生成済み"))
スプレッドシートのI列には<@SlackID>
が表示されるようにしています。
Slack通知させるプログラムをつくるのも初めての経験で、
自分が把握していないミスもあるかもしれませんが、何卒よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー