Post a message to Slack from Jira Cloud

Overview

This script allows you to post a message to Slack in the format specified, along with issue details.

Example

As a project manager, I want a message be posted on Slack when an issue has been done. So everyone is informed when an issue has been finished.

Good to Know

// Specify the issue key.
def issueKey = '<IssueKeyHere>'

//Get the issue
def issueResp = get("/rest/api/2/issue/${issueKey}")
        .header("Content-Type", "application/json")
        .asObject(Map)

assert issueResp.status == 200

def issue = issueResp.body

// Get the issue summary.
def summary = issue.fields.summary

// Get the issue description.
def description = issue.fields.description

// Specify the name of the Slack room you want to post to.
def channelName = '<ChannelName>'

// Specify the name of the user who will make the post.
def username = '<SlackUsername>'

// Specify the message metadata.
Map msg_meta = [ channel: channelName, username: username ,icon_emoji: ':rocket:']

// Specify the message body which is a simple string.
Map msg_dets = [text: "A new issue was created with the details below: \n Issue key = ${issueKey} \n Issue Sumamry = ${summary} \n Issue Description = ${description}"]

// Post the constructed message to Slack.
def postToSlack = post('https://slack.com/api/chat.postMessage')
        .header('Content-Type', 'application/json')
        .header('Authorization', "Bearer ${SLACK_API_TOKEN}") // Store the API token as a script variable named SLACK_API_TOKEN.
        .body(msg_meta + msg_dets)
        .asObject(Map)
        .body

assert postToSlack : "Failed to create Slack message check the logs tab for more details"

return "Slack message created successfully"