Slack : What comes to your mind when you hear word Slack ? It is probably one of best collaboration tool available in the market. Now a days Slack is also widely used across multiple organization of all level. [Big, mid or small]
Now since everyone is active on Slack , it is of extreme importance to send messages to slack channels. This is when the need arise to send automated notifications. Slack provides a lot of rest api's to accomplish this task.
In this post, We will cover how to send attachments in Slack channels using Slack endpoint with Java.
Prerequisite:
- You should have slack authentication token generated.
- Name of the slack channel where the message will be delivered.
package com.dht.test;
import java.io.File;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
public class SlackChannelAttachmentUtil{
public static void main(String[] args) {
try {
String url = "https://slack.com/api/files.upload";
HttpClient httpclient = HttpClientBuilder.create().disableContentCompression().build();
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.addBinaryBody("file", new File("C:\\dht.properties"));
reqEntity.addTextBody("channels", "attachment-testing");
reqEntity.addTextBody("token","xoxp-4735837518-xxxxxx");
reqEntity.addTextBody("media", "file");
reqEntity.addTextBody("initial_comment", "Hello This is from code");
httppost.setEntity(reqEntity.build());
HttpResponse execute = httpclient.execute(httppost);
System.out.println(execute.getStatusLine().getReasonPhrase());
System.out.println(execute.getStatusLine().getStatusCode());
} catch (Exception e) {
System.out.println(e);
}
}
}
The above code will send dht.properties file to attachment-testing slack channel. You will also see Message "Hello This is from code" along with attachment.
No comments:
Post a Comment