Search code examples
google-sheetsslackslack-api

Google Sheets: Send Slack message grabbing the text in a cell


I found a code that I linked to a button so that, when clicking it, a message is sent in Slack. So far I was only able to have that message within the code itself, as in here:

function sendNotification() {
  const url = "https://hooks.slack.com/services/"
  const params = {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify({
      "text":"Hello, World!"
    })
  }

  const sendMsg = UrlFetchApp.fetch(url, params)
  var respCode = sendMsg.getResponseCode()
  Logger.log(sendMsg)
  Logger.log(respCode)
}

However, what I would want it to do is to grab the text from a cell, and send that as the message. Also, I don´t know if this would change anything, but the message in the cell comes up as the result of a formula un that cell, so it is the text that needs to go through, but not the formula.

If someone could help with this that would be awesome! TIA!


Solution

  • To retrieve the text from a specific cell, you can use getRange() and getValue().

    You can use the following example, just make sure to change the name of the sheet and the cell in the script:

    function sendNotification() {
      let ss = SpreadsheetApp.getActive();
      let sheet = ss.getSheetByName("Sheet1");//Change the name of the sheet where you have the message
      let message = sheet.getRange("C1").getValue();//Change the cell where you have the message
    
      const url = "https://hooks.slack.com/services/"
      const params = {
        method: "post",
        contentType: "application/json",
        payload: JSON.stringify({
          "text":message
        })
      }
    
      const sendMsg = UrlFetchApp.fetch(url, params)
      var respCode = sendMsg.getResponseCode()
      Logger.log(sendMsg)
      Logger.log(respCode)
    }