Slack: Post Chat (Bots)
Send a message to Slack with Bots.
Configs
  • C1: Slack Bot Token *
  • C2: Slack Channel Name *
  • C3: Sending Text#{EL}
  • C4: Attachment Summary (In notifications when no sending text)#{EL}
  • C5: Attachment Color
  • C6: Attachment Title#{EL}
  • C7: Attachment Title Link#{EL}
  • C8: Attachment Text#{EL}
Script (click to open)

main();
function main() {
  const token = configs.get("Token");
  let text = "";
  if (configs.get("Text") !== "" && configs.get("Text") !== null){
    text = configs.get("Text");
  }
  const channel = configs.get("ChannelName");
  
  let attachment = {};

  attachAdd(attachment, "Fallback", "fallback");
  attachAdd(attachment, "Color", "color");
  attachAdd(attachment, "Title", "title");
    if (attachment["title"] !== undefined){
    attachAdd(attachment, "TitleLink", "title_link");
  }
  attachAdd(attachment, "AttachText", "text");

 if (attachment["title"] === undefined && attachment["text"] === undefined && text === ""){
    throw "Message to send isn't set.";
  }

  sendMessage(token, channel, text, attachment);
}

/**
  * Send Message with Bots  チャット投稿
  * @param {String} token 
  * @param {String} channel
  * @param {String} text 
  * @param {String} attachment
  */  
function sendMessage(token, channel, text, attachment) {  
  let jsonReq = {};
  jsonReq["text"] = text;
  jsonReq["channel"] = channel;
  jsonReq["as_user"] = "true";

  let attachArray = [];
  if (Object.keys(attachment).length !== 0) {
    attachArray.push(attachment);
  }

  jsonReq["attachments"] = attachArray;
  let response = httpClient.begin()
    .bearer(token)
    .body(JSON.stringify(jsonReq), "application/json; charset=UTF-8")
    .post("https://slack.com/api/chat.postMessage");

  const status = response.getStatusCode();
  const responseTxt = response.getResponseAsString();
  const responseJson = JSON.parse(responseTxt);
  if (responseJson.ok == false ) {
    const error = `Failed to send`;
    engine.log(responseTxt);
    throw error;
  }
}

function attachAdd(attachment, config, attachName){
  const value = configs.get(config);
  if (value !== "" && value !== null){
    attachment[attachName] = value;
  }
}

Download

2021-02-16 (C) Questetra, Inc. (MIT License)
https://support.questetra.com/addons/slack-chat-post-bots/
The Addon-import feature is available with Professional or Enterprise edition.

Capture

See also

%d bloggers like this: