Send custom notification to Slack

Add custom slack notifications on a workflow post function, or as a custom listener after an issue event. Configure the message content and direct the message to a room or specific user. A slack incoming webhook is required to use this code. Visit the following link for information on adding and modifying formatting: https://api.slack.com/incoming-webhooks#advanced_message_formatting

Requirements

Jira Jira (7.3 - 7.13)

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.config.properties.APKeys
import groovyx.net.http.ContentType
import groovyx.net.http.RESTClient
import groovyx.net.http.HttpResponseDecorator
import groovyx.net.http.URIBuilder

// Once you have your webhook, Note the whole url for it in the variable below
final String webhookURL = "https://hooks.slack.com/services/XYZ/XYZ/XYZ"

// Enter a channel name like #channel or a SlackUserId like @UH3DJXYZ7
final String channelOrUserId = "#jira"

def baseUrl = ComponentAccessor.applicationProperties.getString(APKeys.JIRA_BASEURL)
def message = "New issue created in project ${issue.projectObject.name} : "
def client = new RESTClient("https://hooks.slack.com")
def data = [:]

data.put("channel", channelOrUserId)
data.put("text", message)
data.put("iron_emoji", ":ghost:")
data.put("attachments",
    [
        [
            "fallback": "Summary: ${issue.summary}, Reporter: ${issue.reporter}",
            "color"   : "warning",
            "fields"  : [
                [
                    "title": "Summary",
                    "value": issue.summary,
                    "short": true
                ],
                [
                    "title": "Reporter",
                    "value": issue.reporter.displayName,
                    "short": true
                ],
                [
                    "title": "Description",
                    "value": issue.description,
                    "short": false
                ]
            ]
        ]
    ])

def response = client.post(
    path: new URIBuilder(webhookURL).path,
    contentType: ContentType.HTML,
    body: data,
    requestContentType: ContentType.JSON) as HttpResponseDecorator

assert response.status == 200 : "Request failed with status $response.status. $response.entity.content.text"
Discovered an issue? Report it here

Suggested for you