Building an app with Bolt for Java

Bolt for Java

Bolt is a foundational framework that makes it easier to build Slack apps with the platform's latest features. This guide walks you through building your first app with Bolt for Java.

If you prefer developing in another language, read our Bolt overview.

Along the way, you'll create a Slack app, set up a development environment, and build an app that listens and responds to events from your Slack workspace.


Getting started

The first section of this guide covers creating a basic Slack app tailored to work with Bolt. While we glance over some configuration here, our more general app setup guide goes into greater detail.

Creating a Slack app

To get started, you'll need to create a Slack app:

Create a Slack app

Click From scratch, enter your App Name, and select the workspace where you'll play around and build your app. Don't fuss too much over either field—no matter what workspace you select, you'll still be able to distribute your app to other workspaces if you choose. Click Create app.

Requesting scopes

Scopes give your app permission to perform actions, such as posting messages in your workspace. You can select the scopes to add to your app by navigating to the OAuth & Permissions sidebar or selecting your app below:

Try it out by creating an app
View configuration

Scroll down to the Bot Token Scopes section and click Add an OAuth Scope.

For now, we'll only use one scope. Add the chat:write scope to grant your app the permission to post messages in channels it's a member of.

Installing your app

Install your own app by selecting Install to Workspace at the top of the OAuth & Permissions page, or from the sidebar. Click Allow.

OAuth UI in app installation process

After installation, you'll land back in the OAuth & Permissions page and find a Bot User OAuth Token.

Access tokens represent the permissions delegated to your app by the installing user. Keep it secret. Keep it safe. At a minimum, avoid checking them into public version control. Instead, access them via an environment variable.

Enabling your app's Home tab

This guide uses Home tabs, a feature which offers a persistent space for your app to display dynamic interfaces for users.

To enable your app's Home tab, click the App Home sidebar on the App Management page, or select your app from the dropdown below:

Try it out by creating an app
View configuration

Toggle Home Tab to ON.

Configuring your local environment

With the app configured and installed, it’s time to set up a new Bolt for Java project with your app's credentials.

If you don’t have JDK 8 or higher installed, now is the time to do it. If you’re using macOS, you can install Java using brew install openjdk@11. If you’re using another OS, read the OpenJDK website for instructions.

Adding your app credentials

Before creating and starting the app, you'll need to copy over the credentials for your app. Copy the Bot User OAuth Token under the OAuth & Permissions sidebar.

You'll just be using a local project in this guide, so you'll save your bot token as an environment variable. In the command line, you'll export your token as SLACK_BOT_TOKEN:

export SLACK_BOT_TOKEN=xoxb-your-token

In addition to the access token, you'll need a signing secret. Your app's signing secret verifies that incoming requests are coming from Slack. Navigate to the Basic Information page from your app management page. Under App Credentials, copy the value for Signing Secret.

Like before, export your signing secret. This time as SLACK_SIGNING_SECRET:

export SLACK_SIGNING_SECRET=your-signing-secret

Using ngrok as a local proxy

To develop locally we'll be using ngrok, which allows you to expose a public endpoint that Slack can use to send your app events. If you haven't already, install ngrok from their website .

If you haven't used ngrok before, read our full tutorial for a more in-depth walkthrough on using ngrok to develop locally.

After you've installed ngrok, go ahead and tell ngrok to use port 3000 (which Bolt for Java uses by default):

ngrok http 3000

The next parts of this guide explore different approaches to building Bolt for Java apps, depending on the build tool that you prefer. The first part uses Gradle, so if you prefer Maven, you can skip to that section.

Developing your app

With your local environment configured, let's begin coding the app.

If you aren't using local variable type inference, go here for more instructions and sample code.

Using Gradle as your build tool

If you haven't already installed Gradle, follow the installation guide . Then initialize a Gradle project and paste the following into the dependencies block of your build.gradle file:

dependencies {
  implementation("com.slack.api:bolt:1.1.+")
  implementation("com.slack.api:bolt-servlet:1.1.+")
  implementation("com.slack.api:bolt-jetty:1.1.+")
}

And if you haven't already, paste the following in your repositories block:

repositories {
  mavenCentral()
}

Using Maven as your build tool

If you haven't already installed Maven, follow the installation guide . Then create a Maven project and paste the following into the dependencies of your pom.xml file:

<dependency>
  <groupId>com.slack.api</groupId>
  <artifactId>bolt-jetty</artifactId>
  <version>[1,)</version>
</dependency>

Initializing your app

After you've included the necessary dependencies, paste the following in your project (.java) file:

import com.slack.api.bolt.App;
import com.slack.api.bolt.jetty.SlackAppServer;

public class MyApp {
  public static void main(String[] args) throws Exception {
    var app = new App();

     // All the room in the world for your code

    var server = new SlackAppServer(app);
    server.start();
  }
}

The above code initializes the app using the App constructor, then creates and starts a jetty server. You can run your app now, but it won't do much.

If you'd prefer to write your code in Kotlin, use the Kotlin example code.

Optional: If you want to test that your app is correctly configured, go ahead and start your app. "⚡️ Bolt app is running!" should appear, indicating that your app is successfully running.

Subscribing to events

Your app can listen to all sorts of events happening around your workspace — messages being posted, reactjis being emoted, users joining the team, and more. To listen for events, your app uses the Events API.

Let's subscribe to the app_home_opened event. On your app configuration page, select the Event Subscriptions sidebar. You'll be presented with an input box to enter a Request URL, which is where Slack sends the events your app is subscribed to. For local development, we'll use your ngrok URL from above.

For example: https://1234abcde.ngrok.io

By default Bolt for Java listens for all incoming requests at the /slack/events route, so for the Request URL you can enter your ngrok URL appended with /slack/events.

For example: https://1234abcde.ngrok.io/slack/events

After you've saved your Request URL, click on Subscribe to bot events, then Add Bot User Event and search for app_home_opened. Then Save Changes using the the green button on the bottom right, and your app will start receiving app_home_opened events as users navigate to your app from the Slack sidebar or search bar.

Responding to events

To respond to events with Bolt for Java, you can write a listener. Listeners have access to the event body, the entire request payload, and an additional context object that holds helpful information like the bot token you used to instantiate your app.

Let's set up a basic listener using the app_home_opened event that publishes a view to your Home tab, which is a persistent space where your app can display a dynamic interface for users.

First, paste the following at the top of your Bolt app's file to important necessary classes:

import static com.slack.api.model.block.Blocks.*;
import static com.slack.api.model.block.composition.BlockCompositions.*;
import static com.slack.api.model.view.Views.*;
import com.slack.api.model.event.AppHomeOpenedEvent;
import static com.slack.api.model.block.element.BlockElements.*;

Then, paste this listener code into your main class:

app.event(AppHomeOpenedEvent.class, (payload, ctx) -> {
  var appHomeView = view(view -> view
    .type("home")
    .blocks(asBlocks(
      section(section -> section.text(markdownText(mt -> mt.text("*Welcome to your _App's Home tab_* :tada:")))),
      divider(),
      section(section -> section.text(markdownText(mt -> mt.text("This button won't do much for now but you can set up a listener for it using the `actions()` method and passing its unique `action_id`. See an example on <https://slack.dev/java-slack-sdk/guides/interactive-components|slack.dev/java-slack-sdk>.")))),
      actions(actions -> actions
        .elements(asElements(
          button(b -> b.text(plainText(pt -> pt.text("Click me!"))).value("button1").actionId("button_1"))
        ))
      )
    ))
  );

  var res = ctx.client().viewsPublish(r -> r
    .userId(payload.getEvent().getUser())
    .view(appHomeView)
  );

  return ctx.ack();
});

View this example

Try it out! Navigate to your app's Home tab by clicking your app from the sidebar in your workspace. When you open the Home tab, you should see your view appear. Congrats on building your first Bolt for Java app! 🙌

Next steps

With the basics under your belt, you can start exploring the rest of Bolt and the entire Slack platform. Here's a few paths you may consider wandering down:

  • Read the Bolt for Java documentation to learn about advanced functionality and to find example code snippets that show you what else is possible.
  • Improve your app's design with Block Kit Builder. This is a prototyping tool that allows you to design Slack apps quickly, then paste the code into your Bolt app (we also have public Figma files if you'd rather use them to design your app).
  • Explore other surfaces where your app can exist, such as messages and pop-up modals.
  • When you're ready to take your app from development to deployed, you'll want to host it on the platform of your choice.

Need help or have questions?

Email our developer support team