Created
November 21, 2017 02:10
-
-
Save armaandhir/d55162b6926c1539f6fcf1397eed417f to your computer and use it in GitHub Desktop.
Send a slack message to a channel. This provides a demo code to use the slack api and use json to design slack message.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.armaandhir.slack_integration.util; | |
import com.mashape.unirest.http.HttpResponse; | |
import com.mashape.unirest.http.Unirest; | |
import com.mashape.unirest.http.exceptions.UnirestException; | |
import org.json.JSONArray; | |
import org.json.JSONObject; | |
/** | |
* Send slack messages using java. | |
* | |
* It can be used like: | |
* url = "https://slack.com/api"; | |
* slackToken = "xxop-somethinglikethis-verylong"; | |
* SlackIntegration slackIntegration = new SlackIntegration(url, slackToken); | |
* slackIntegration.sendSlackNotification("YourChannelName", text.trim()); | |
*/ | |
public class SlackIntegration | |
{ | |
private final String slackApiUrl; | |
private final String token; | |
private final String postMessageUrl; | |
public SlackIntegration(String slackApiUrl, String token) | |
{ | |
this.slackApiUrl = slackApiUrl; | |
this.token = token; | |
postMessageUrl = "/chat.postMessage"; | |
} | |
/** | |
* Method to send Slack Notifications regrading unlinked line items. | |
* @param channel name of the channel | |
* @param message | |
*/ | |
public void sendSlackNotification(String channel, String message) throws UnirestException | |
{ | |
log.info("Sending slack notification to {}: {}", channel, message); | |
JSONArray json = new JSONArray(); | |
JSONObject lineOne = new JSONObject(); | |
lineOne.put("color", "warning"); | |
lineOne.put("title", "Warning! Warning Items heading"); | |
lineOne.put("text", "<!here> The following items are causing problems."); | |
JSONObject lineTwo = new JSONObject(); | |
lineTwo.put("text", message.trim()); | |
JSONArray markdownArray = new JSONArray(); | |
markdownArray.put("text"); | |
lineTwo.put("mrkdwn_in", markdownArray); | |
json.put(lineOne); | |
json.put(lineTwo); | |
HttpResponse<String> httpResponse = Unirest.post(slackApiUrl + postMessageUrl) | |
.header("Content-Type", "application/x-www-form-urlencoded") | |
.queryString("token", token) | |
.queryString("channel", channel) | |
//.queryString("text", message) | |
.queryString("as_user", "false") | |
.queryString("username", "Test User") | |
.queryString("attachments", json.toString()) | |
.asString(); | |
// find a better way to print toString the json response | |
log.info("Slack notification sent"); | |
log.info("Response: {}", httpResponse.getBody().trim()); | |
} | |
} // end of class |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment