1

I created a google script linked to a spreadsheet that is designed to send a message to a slack channel thread when a cell is updated. The messages are posting fine to the channel, but I can't get the 'thread_ts' attribute to post the message as a reply to the specific thread as indicated by the timestamp for the parent message. I've read through the documentation several times. What I am doing wrong?

function myonEdit(e) {

    var sheet = SpreadsheetApp.getActiveSheet()  
    var range = e.range;
    var columnOfCellEdited = range.getColumn();

    if (columnOfCellEdited == 7) {
        var url = "https://hooks.slack.com/services/xxxx/xxxx/xxxx" ;
        var currentRow = sheet.getActiveCell().getRow()
        var name = sheet.getSheetValues(currentRow, 1, 1, 1);

        var payload = {
            "username" : "robot", 
            "text" : name,
            "icon_emoji": ":robot_face:",
            "icon_url" : "http://image",
            "thread_ts": "1511829070.000023"
       }

    sendToSlack_(url,payload) 
  }
}

   function sendToSlack_(url,payload) {
   var options =  {
       "method" : "post",
       "contentType" : "application/json",
       "payload" : JSON.stringify(payload),
  };
  return  UrlFetchApp.fetch(url, options)
  }
Ian Percy
  • 65
  • 4

1 Answers1

1

How about the following modifications?

Modification points :

  • It cannot reply to the thread using Incoming WebHooks. I'm sorry. I couldn't find the document about this. I knew this from my experiences. In order to reply to thread, an access token is required to do it. You can get the access token from https://api.slack.com/custom-integrations/legacy-tokens or get using OAuth2 process.
  • In order to reply thread_ts, please add channel name or channel ID to the payload.

Modified script :

This modified script sends a message to a thread using access token.

function myonEdit(e) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = e.range;
  var columnOfCellEdited = range.getColumn();
  if (columnOfCellEdited == 7) {
    var url = "https://slack.com/api/chat.postMessage"; // Modified
    var currentRow = sheet.getActiveCell().getRow();
    var name = sheet.getSheetValues(currentRow, 1, 1, 1);
    var payload = {
      token: "### your access token ###", // Added
      channel: "#####", // Please input channel name or ID which includes thread_ts. // Added
      username : "robot", 
      text : name, // name[0][0] or JSON.stringify(name) may be suitable for this line.
      icon_emoji: ":robot_face:",
      icon_url : "http://image",
      thread_ts: "1511829070.000023",
    }
    sendToSlack_(url, payload);
  }
}

function sendToSlack_(url,payload) {
  var options =  {
    "method" : "post",
    // "contentType" : "application/json", // Removed
    "payload" : payload // Modified
  };
  return  UrlFetchApp.fetch(url, options)
}

If I misunderstand your question, I'm sorry.

Tanaike
  • 181,128
  • 11
  • 97
  • 165