How to Send Messages to Slack with Spring Boot Easily and Without Dependencies

Daniel Angel
10 min readSep 16, 2024

--

Photo by Scott Webb on Unsplash
  1. What is Slack and How Does the Slack API Work?

Slack is a messaging platform focused on teamwork. It allows companies to create communication channels for different projects and work teams and offers a wide range of integrations with other tools and services.

The Slack API is a set of endpoints that allow other applications to send and receive messages through Slack. To use the Slack API, you must first create an application on the Slack platform and obtain an access token. Then, you can use any of the API endpoints to send and receive messages through Slack.

Can you access the content of the link without membership from the first comment

This is a revised and improved copy of my previously published story in Spanish.

2. Creating a Slack Application and Obtaining the Access Token for the API

To start integrating Slack with your Spring Boot application, you first need to create a Slack application. Follow these steps:

  1. Sign up or log in to Slack: If you don’t already have a Slack account, create one at Slack.com. Once logged in, create or select a workspace where you want the application to be used.
  2. Create a new application: Go to the Slack API page and click “Create New App”. You will be prompted to name your app and choose the workspace where it will be installed.
  3. Obtain the access token: After setting up your app, navigate to the “OAuth & Permissions” section. Here, you’ll find the “OAuth Tokens for Your Workspace”. Click “Install App to Workspace” to generate an access token. This token is crucial, as it will allow your Spring Boot application to authenticate and interact with the Slack API.
  4. Add permissions: Make sure your app has the necessary scopes (permissions) to send messages. In the same “OAuth & Permissions” section, under “Scopes”, add the chat:write permission to allow your app to post messages on behalf of users or in specific channels.

Once these steps are completed, you will have everything you need: your Slack app is configured, and you have the access token ready to integrate with your Spring Boot application.

Next, search for the “Incoming Webhooks” app.

Once your Slack application is set up, you need to enable the Incoming Webhooks feature, which allows external applications (like your Spring Boot app) to send messages to Slack channels through simple HTTP requests. Here’s how to do it:

  1. Enable Incoming Webhooks: In the settings for your Slack app, go to the “Incoming Webhooks” section, and toggle the switch to activate it.
  2. Create a Webhook URL: Once Incoming Webhooks are enabled, click the “Add New Webhook to Workspace” button. You’ll be asked to select the channel where the messages will be sent. After selecting a channel, Slack will generate a unique Webhook URL for that channel.
  3. Save the Webhook URL: This URL is what you’ll use in your Spring Boot application to send messages to the selected Slack channel. Keep it safe as you’ll need it later to make HTTP requests directly from your application.

Click on the card and add it to a Slack workspace.

Once you’ve found the Incoming Webhooks app, click on its card to open the details. From here, you’ll need to add the app to a specific Slack workspace where you want the messages to be sent.

  1. Select the workspace: After clicking on the Incoming Webhooks card, you’ll be prompted to choose the workspace where the app will be installed. Make sure to select the correct workspace, especially if you manage multiple Slack environments.
  2. Authorize the app: You’ll be asked to authorize the app’s access to your selected workspace. Click “Allow” to grant the necessary permissions. This step ensures that your Slack app can send messages to the channels in that workspace.

Select the channel where you want to publish your messages.

After authorizing the Incoming Webhooks app, the next step is to choose the Slack channel where you want your messages to be posted. When creating a new Webhook URL, Slack will prompt you to select a specific channel from your workspace.

  1. Channel selection: In the popup window, choose the desired channel from the list. This could be a public channel where your team communicates, or a private channel if the messages should be limited to certain users.
  2. Custom Webhook URL: Once the channel is selected, Slack will generate a unique Webhook URL for that specific channel. This URL is what your Spring Boot application will use to send messages to the selected channel via HTTP request

Copy the API link; this will be the one we use to connect our REST API in Spring Boot to send messages.

Once you have generated the Webhook URL for the selected Slack channel, copy the URL. This Webhook URL will serve as the endpoint for your Spring Boot application to send messages to Slack.

  1. Copy the Webhook URL: After selecting the channel, Slack will generate a unique Webhook URL. This URL is a key part of the integration as it allows your Spring Boot application to send messages by making simple HTTP POST requests.

3. Installing the Slack Dependency in Your Spring Boot Project

For integrating Slack into your Spring Boot application, you only need the basic dependencies provided by Spring Boot itself. You don’t need to add any third-party dependencies for this integration. Here’s what you need to do:

  1. Add Spring Web Dependency: In your pom.xml file (for Maven) or build.gradle file (for Gradle), ensure you have the spring-boot-starter-web dependency. This starter includes everything needed to create RESTful web services, which is essential for sending HTTP requests to Slack.

For Maven, add the following dependency:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

For Gradle, add this line to your build.gradle file:

implementation 'org.springframework.boot:spring-boot-starter-web'

2. Include DevTools (optional): You can also include Spring Boot DevTools for development convenience, but it’s not required for the Slack integration itself. DevTools provides additional features like automatic restarts and live reloads.

For maven:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>

For gradle:

developmentOnly 'org.springframework.boot:spring-boot-devtools'

Next, we need to add the Webhook URL to our application.properties.

To properly configure your Spring Boot application to send messages to Slack, you should store the Webhook URL in your application.properties file. This practice helps manage configurations more effectively and keeps sensitive information secure.

  1. Open application.properties: Locate the application.properties file in the src/main/resources directory of your Spring Boot project.
  2. Add the Webhook URL: Add a new property for the Slack Webhook URL. For example:

Create a DTO with the following properties.

Here’s how to create a Data Transfer Object (DTO) for sending messages to Slack using Spring Boot. This DTO will help encapsulate the properties required to send a message through the Slack API.

import java.io.Serializable;

public class SlackMessage implements Serializable {

private static final long serialVersionUID = 1L;

private String username; // Direct user to whom the message will be sent
private String text; // The message content
private String icon_emoji; // Customizable Slack bot icon
private String channel; // Channel to send the message

// Default constructor
public SlackMessage() {}

// Parameterized constructor
public SlackMessage(String username, String text, String icon_emoji, String channel) {
this.username = username;
this.text = text;
this.icon_emoji = icon_emoji;
this.channel = channel;
}

// Getters and setters
public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getText() {
return text;
}

public void setText(String text) {
this.text = text;
}

public String getIcon_emoji() {
return icon_emoji;
}

public void setIcon_emoji(String icon_emoji) {
this.icon_emoji = icon_emoji;
}

public String getChannel() {
return channel;
}

public void setChannel(String channel) {
this.channel = channel;
}
}

4. Creating a Spring Component to Send Messages to Slack

In this step, we’ll create a Spring component in a service package that will use RestTemplate to handle the HTTP request for sending messages to Slack.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class SlackComponent {

@Value("${slack.webhook.url}")
private String slackWebhookUrl;

public Object sendMessageNative(SlackMessage message) {
// Create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();

// Set the headers for the request
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

// Create the request entity with the SlackMessage payload and headers
HttpEntity<SlackMessage> request = new HttpEntity<>(message, headers);

// Send the POST request to the Slack webhook URL
return restTemplate.postForObject(slackWebhookUrl, request, String.class);
}
}

Explication:

  1. @Component: We define SlackComponent as a Spring-managed bean using the @Component annotation.
  2. Webhook URL injection: We use the @Value annotation to inject the Slack webhook URL, which is stored in the application.properties.
  3. RestTemplate: This is used to send the HTTP POST request to Slack.
  4. Headers and payload: We set the content type to application/json and use SlackMessage as the request body.

This simple component allows you to easily send messages from your Spring Boot application to a Slack channel using the Webhook URL and RestTemplate.

Keep in mind that slackWebhookUrl uses the value defined earlier in the application.properties file of our application.

With this setup, we should be able to perform a unit test to verify that our component works correctly. Let’s define a simple unit test for the SlackComponent.

Unit Test for SlackComponent

To test the SlackComponent, we’ll use Spring Boot’s testing support along with mocking to simulate the interaction with Slack. Here’s an example of how you can write a unit test using JUnit and Mockito:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.assertEquals;

@SpringBootTest
class SlackMessagingSpringbootApplicationTests {

@Autowired
private SlackComponent slackComponent;

@Test
void testSendMessage() {
// Given
String message = "Hola mundo desde junit :heart: :smile:";
SlackMessage slackMessage = new SlackMessage();
slackMessage.setText(message);
slackMessage.setChannel("varios");
// slackMessage.setIcon_emoji(":smiley:"); // Uncomment if needed

// When
var response = slackComponent.sendMessageNative(slackMessage);

// Then
assertEquals("ok", response); // Adjust the expected response as per Slack's actual response
}
}

When running our test, you would receive the message in the “varios” channel.

5. Injecting the Slack Component Where Messages Need to Be Sent

To complete our API, we will create a controller that injects the SlackComponent and exposes a method to send messages through it. This allows you to use this method from anywhere else in the application.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
public class SlackController {

@Autowired
private SlackComponent slackComponent;

@PostMapping("/send")
public ResponseEntity<?> sendMessage(@RequestBody SlackMessage slackRequest) {
// Use SlackComponent to send the message
Object response = slackComponent.sendMessageNative(slackRequest);
return ResponseEntity.ok(response); // Return the response from SlackComponent
}
}

As the final step, test it using Postman.

And this would be the result.

6. Sending Messages with Emojis and Attachments to Slack

To include emojis and images in a Slack message from your API, you need to use Slack’s message formatting.

Emojis in Slack Messages

To include emojis in the text of a message, you should use Slack’s emoji formatting. Here’s how to include emojis in your Slack message:

  1. Slack Emoji Syntax:
  • Basic Emoji: Use :emoji_name: where emoji_name is the name of the emoji. For example, :smile: will display a smiley face.
  • Custom Emoji: If your workspace has custom emojis, you can use them with the format :custom_emoji_name:.

Sample:

Result:

You can also add an emoji_message field to our DTO and then concatenate it to the message to provide a better segmentation experience, though it's not necessary for this example.

Yes, it’s possible to include images directly in the text of a message using Slack’s formatting, which allows for adding links and formatting text in various ways.

Including Images Directly in the Message Text

To include an image directly within the text of a Slack message, you can use Markdown-style formatting. Here’s how to format your message to include an image:

Image Format:

  • Use the following format to include an image in the text of the message:
![alt_text](image_url)
  • alt_text: This is the alternative text for the image, which describes the content for users who might not be able to view it.
  • image_url: This is the URL of the image you want to include.

Example:

Result:

With this, we conclude our tutorial on how to integrate the Slack API easily into a Spring Boot application. It is also possible to perform this integration using OpenFeign or WebClient. If you have any questions, feel free to contact me or let me know if you would like a tutorial on using these libraries.

GitHub Repository: https://github.com/danielangel22/slack-messaging-springboot

Thanks for reading!!

--

--

Daniel Angel
Daniel Angel

Written by Daniel Angel

Backend developer | Java, Spring boot, Cloud| Laravel, Php

Responses (1)