Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

Scriptrunner script works in console but not in a listener

Kevin Bouman
Contributor
May 24, 2023

I am trying to create a Slack channel when a version is created. I created a script that that can create a slack channel from Jira. It works when executing it in the script console but not when I put it into a listener. The frustrating thing is that I am getting a 200 response in the listener logs. Nothing is changed between the console and listener scripts. The Slack bot is also that same. I am on Jira Datacenter.

What am I missing?

Script

import groovyx.net.http.ContentType

import groovyx.net.http.RESTClient

import groovyx.net.http.HttpResponseDecorator

import groovyx.net.http.RESTClient

final String URL = "https://slack.com/api/"

def channelName = "pretend-channel-4"

def channelPrivacy = "false" //true = private / false = public

def data = [:]

 

data.put("name", channelName)

data.put("is_private", channelPrivacy)

data.put("prety", "1")

def postResponse = post(URL, "conversations.create?", data)

def post(def hostUrl, def endpointAndQuery, def bodyJson) {

    //TOKEN FOR SLACK APP

    def SLACK_API_TOKEN = "<SLACK TOKEN>"

    def client = new RESTClient(hostUrl)

    client.setHeaders([

        'Authorization': "Bearer $SLACK_API_TOKEN"

    ])

    client.handler.success = { HttpResponseDecorator response ->

        log.debug("POST Success: $response.")

    }

    client.handler.failure= { HttpResponseDecorator response ->

        log.error "POST Error: $response.status"

    }

    client.post(

            path: endpointAndQuery,

            contentType: ContentType.JSON,

            body: bodyJson

    )  

}

 

Log screenshot

script logs.PNG

2 answers

1 accepted

Suggest an answer

Log in or Sign up to answer
0 votes
Answer accepted
Kevin Bouman
Contributor
June 9, 2023

Thanks @PD Sheehan for your support.

Turns out that my script was correct. The problem was the channel name I was using. Slack has specific requirements for naming a channel. I was creating my name based off the version description. Because of this, I have to parse out all special characters, spaces and capitals. I also had to limit the string length to 80 characters.

Here is my updated code

import org.apache.log4j.Level
//For Slack POST
import groovyx.net.http.ContentType
import groovyx.net.http.RESTClient
import groovyx.net.http.HttpResponseDecorator
import java.util.*
import java.io.*

/////////////// GET EVENT DETAILS /////////////////
def fieldMap = [:]
fieldMap["versionName"] = event.getVersion().getName()
fieldMap["versionReleaseDate"] = event.getVersion().getReleaseDate()
fieldMap["parsedReleaseDate"] = event.getVersion().getReleaseDate().toString().substring(0,10)
fieldMap["versionStartDate"] = event.getVersion().getStartDate()
fieldMap["versionDescription"] = event.getVersion().getDescription()

/////////////// CREATE SLACK CHANNEL /////////////////
def slackchannelName = fieldMap.versionDescription.toString()
def slackchannelPrivacy = "false" //true = private / false = public
def slackchannelNameModified = slackchannelName.toLowerCase().replaceAll("[^a-zA-Z0-9]","-")
def slackchannelNameModified2 = slackchannelNameModified.replaceAll("\\s+","-")

log.debug("slackchannelNameModified: " + slackchannelNameModified.length() + " = $slackchannelNameModified")

Vector<Character> v = new Vector<>();

for (int i = 0; i < slackchannelNameModified.length(); ++i){
    def myChar = slackchannelNameModified.charAt(i)
    v.add(myChar);
    if (v.size() > 1 && myChar == "-"){
        int sz = v.size();
        // removing two consecutive duplicates
        if (v.get(sz - 1) == v.get(sz - 2)){
            v.setSize(sz - 2); // Removing two characters from the string
        }
    }
}

//Puting the string back together
def endChannelName = ""

for(n in v){
    endChannelName = endChannelName + n
}

//endChannelName.take(80)
log.debug("endChannelName: " + endChannelName.length() + " = $endChannelName")

final String URL = "https://slack.com/api/"
def data = [:]
    data.put("name", endChannelName)
    data.put("is_private", "false") //slackchannelPrivacy)
    data.put("prety", "1")
def postResponse = post(URL, "conversations.create?", data)

def post(def hostUrl, def endpointAndQuery, def bodyJson) {

    //TOKEN FOR SLACK APP
    def SLACK_API_TOKEN = ""
    def client = new RESTClient(hostUrl)
    client.encoder.charset = 'utf-8'
    client.setHeaders([
            'Authorization': "Bearer $SLACK_API_TOKEN"
    ])

    client.handler.success = { HttpResponseDecorator response ->
        log.debug("POST Status: $response.")
        log.debug("POST Response: $response.entity.content.text")
    }

    client.handler.failure = { HttpResponseDecorator response ->
        log.error "POST Error: $response."
    }

    client.post(
            path: endpointAndQuery,
            contentType: ContentType.JSON,
            body: bodyJson
    )
}
0 votes
PD Sheehan
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
May 24, 2023

So, when executing in the listener, you get a log entry that shows the post request was successful but the corresponding slack channel isn't created?

It's possible for an API to respond with a success status code, but report a failure as part of the message.

Maybe you need to extract a bit more out of that response to get some clues. 

import groovyx.net.http.ContentType
import groovyx.net.http.HttpResponseDecorator
import groovyx.net.http.RESTClient

final String URL = "https://slack.com/api/"
def channelName = "pretend-channel-4"
def channelPrivacy = "false" //true = private / false = public

def data = [:]
data.put("name", channelName)
data.put("is_private", channelPrivacy)
data.put("prety", "1")

def postResponse = post(URL, "conversations.create?", data)

def post(def hostUrl, def endpointAndQuery, def bodyJson) {
//TOKEN FOR SLACK APP
def SLACK_API_TOKEN = "<SLACK TOKEN>"

def client = new RESTClient(hostUrl)
client.setHeaders([
'Authorization': "Bearer $SLACK_API_TOKEN"
])

client.handler.success = { HttpResponseDecorator response ->
log.debug("POST Status: $response.")
log.debug("POST Response: $response.entity.content.text")
}

client.handler.failure = { HttpResponseDecorator response ->
log.error "POST Error: $response."
}

client.post(
path: endpointAndQuery,
contentType: ContentType.JSON,
body: bodyJson
)

}
Kevin Bouman
Contributor
May 25, 2023

@PD Sheehan Thanks for the direction. It looks like it is doing exactly what you say. The request is successful but I am getting 

POST Response: {"ok":false,"error":"invalid_name_specials","warning":"missing_charset","response_metadata":{"warnings":["missing_charset"]}}

do you know how to fix this? I have never had to define the ContentType other then what is currently in the script. From what I can tell it needs the Charset defined. 

PD Sheehan
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
May 25, 2023

I don't think it'a content type error.

I haven't worked with Slack API before, but a quick google search revealed this:

https://api.slack.com/methods/conversations.create#errors

See the "invalid_name_specials" error.
That means your channel name "pretend-channel-4" is apparently invalid.

PD Sheehan
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
May 25, 2023

And if you want to take care of the warning too... you can try adding something like this:

client.encoder.charset = 'utf-8'

But I'm not sure. I've never tried that. I just found it from the javadocs.

TAGS
AUG Leaders

Atlassian Community Events