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
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
)
}
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
)
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
@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.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Online forums and learning are now in one easy-to-use experience.
By continuing, you accept the updated Community Terms of Use and acknowledge the Privacy Policy. Your public name, photo, and achievements may be publicly visible and available in search engines.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.