### Verify Slack API Client Installation with Java Example Source: https://tools.slack.dev/java-slack-sdk/guides/web-api-client-setup This Java code demonstrates how to initialize the Slack client and make a basic API test call. It requires the `slack-api-client` dependency and uses the `Slack.getInstance().methods().apiTest()` method. The output shows the success of the API call. ```java import com.slack.api.Slack; import com.slack.api.methods.response.api.ApiTestResponse; public class Example { public static void main(String[] args) throws Exception { Slack slack = Slack.getInstance(); ApiTestResponse response = slack.methods().apiTest(r -> r.foo("bar")); System.out.println(response); } } ``` -------------------------------- ### Run Slack API Client Example using Maven Source: https://tools.slack.dev/java-slack-sdk/guides/web-api-client-setup This command executes the Java example code using Maven's `exec:java` plugin. It specifies the main class to run and ensures proper daemon thread handling. The output confirms the successful installation and execution of the Slack API client. ```bash mvn compile exec:java \ -Dexec.cleanupDaemonThreads=false \ -Dexec.mainClass="Example" ``` -------------------------------- ### Kotlin Example Usage Source: https://tools.slack.dev/java-slack-sdk/guides/web-api-client-setup A simple Kotlin program demonstrating how to initialize the Slack API client and make a basic API call. This code snippet is intended to be run after setting up the project with the Gradle configuration provided. ```kotlin import com.slack.api.Slack fun main() { val slack = Slack.getInstance() val response = slack.methods().apiTest { it.foo("bar") } println(response) } ``` -------------------------------- ### Build Slack SDK from Source Source: https://tools.slack.dev/java-slack-sdk/guides/web-api-client-setup Commands to clone the Slack Java SDK repository from GitHub and build it using Maven. This process installs all SDK modules into the local Maven repository. ```bash git clone git@github.com:slackapi/java-slack-sdk.git cd java-slack-sdk mvn install -Dmaven.test.skip=true ``` -------------------------------- ### Quarkus Development Mode Commands Source: https://tools.slack.dev/java-slack-sdk/ja-jp/guides/supported-web-frameworks Commands to start a Quarkus application in development mode. These commands compile and run the application, enabling features like live coding and hot-reloading. Includes Maven and Gradle examples. ```shell ./mvnw quarkus:dev ./mvnw clean quarkus:dev # 変更が反映されないときは clean を試してみてください ``` ```shell ./gradlew quarkusDev ``` -------------------------------- ### Initialize Slack Client with Default Config Source: https://tools.slack.dev/java-slack-sdk/ja-jp/guides/web-api-basics Demonstrates the basic setup of the Slack Java SDK client using default configuration. This is the initial step for interacting with Slack APIs. ```java import com.slack.api.Slack; import com.slack.api.SlackConfig; SlackConfig config = new SlackConfig(); Slack slack = Slack.getInstance(config); ``` -------------------------------- ### Build Slack SDK from Source with Maven Source: https://tools.slack.dev/java-slack-sdk/ja-jp/guides/web-api-client-setup Commands to clone the Slack SDK repository and build it locally using Maven. This installs all modules into the local Maven repository. ```bash git clone git@github.com:slackapi/java-slack-sdk.git cd java-slack-sdk mvn install -Dmaven.test.skip=true ``` -------------------------------- ### Kotlin Slack API Client Example Source: https://tools.slack.dev/java-slack-sdk/ja-jp/guides/web-api-client-setup A simple Kotlin program demonstrating how to initialize the Slack client and make an API test call. It uses the Slack API client library and prints the response. ```kotlin import com.slack.api.Slack fun main() { val slack = Slack.getInstance() val response = slack.methods().apiTest { it.foo("bar") } println(response) } ``` -------------------------------- ### Initialize and Start Slack Bolt Helidon Server Source: https://tools.slack.dev/java-slack-sdk/guides/supported-web-frameworks Demonstrates how to initialize a Slack `App` and start a `SlackAppServer` using Helidon. It includes registering metrics and health checks, and defines an event handler for `AppMentionEvent`. ```java package hello; import com.slack.api.bolt.App; import com.slack.api.bolt.helidon.SlackAppServer; import com.slack.api.model.event.AppMentionEvent; import io.helidon.health.HealthSupport; import io.helidon.health.checks.HealthChecks; import io.helidon.metrics.MetricsSupport; public final class Main { public static void main(final String[] args) { startServer(); } public static SlackAppServer startServer() { SlackAppServer server = new SlackAppServer(apiApp(), oauthApp()); // If you add more settings to Routing, overwrite this configurator server.setAdditionalRoutingConfigurator(builder -> builder .register(MetricsSupport.create()) .register(HealthSupport.builder().addLiveness(HealthChecks.healthChecks()).build())); server.start(); return server; } // POST /slack/events - this path is configurable with bolt.apiPath in application.yaml public static App apiApp() { App app = new App(); app.event(AppMentionEvent.class, (event, ctx) -> { ctx.say("May I help you?"); return ctx.ack(); }); return app; } } ``` -------------------------------- ### Run Slack Bolt App with HTTP Mode (Standard Java) Source: https://tools.slack.dev/java-slack-sdk/guides/getting-started-with-bolt Demonstrates the main method to initialize a Slack Bolt `App` and start it using `SlackAppServer`. This requires `SLACK_BOT_TOKEN` and `SLACK_SIGNING_SECRET` environment variables. ```java package hello; import com.slack.api.bolt.App; // If you use bolt-jakarta-jetty, you can import `com.slack.api.bolt.jakarta_jetty.SlackAppServer` instead import com.slack.api.bolt.jetty.SlackAppServer; public class MyApp { public static void main(String[] args) throws Exception { // App expects env variables (SLACK_BOT_TOKEN, SLACK_SIGNING_SECRET) App app = new App(); app.command("/hello", (req, ctx) -> { return ctx.ack(":wave: Hello!"); }); SlackAppServer server = new SlackAppServer(app); server.start(); // http://localhost:3000/slack/events } } ``` -------------------------------- ### Spring Boot Slack App Setup Source: https://tools.slack.dev/java-slack-sdk/guides/app-distribution Demonstrates setting up a Slack Bolt `App` within a Spring Boot application. It includes initializing the `App` as an OAuth app and defining Spring `@WebServlet` components to handle Slack events, installation requests, and OAuth redirect callbacks. ```Java package hello; // export SLACK_SIGNING_SECRET=xxx // export SLACK_CLIENT_ID=111.222 // export SLACK_CLIENT_SECRET=xxx // export SLACK_SCOPES=commands,chat:write.public,chat:write // export SLACK_USER_SCOPES= // export SLACK_INSTALL_PATH=/slack/install // export SLACK_REDIRECT_URI_PATH=/slack/oauth_redirect // export SLACK_OAUTH_COMPLETION_URL=https://www.example.com/completion // export SLACK_OAUTH_CANCELLATION_URL=https://www.example.com/cancellation import com.slack.api.bolt.App; import javax.servlet.annotation.WebServlet; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class SlackApp { @Bean public App initSlackApp() { App app = new App().asOAuthApp(true); // Do not forget calling `asOAuthApp(true)` here app.command("/hello-oauth-app", (req, ctx) -> { return ctx.ack("What's up?"); }); return app; } } import com.slack.api.bolt.servlet.SlackAppServlet; import com.slack.api.bolt.servlet.SlackOAuthAppServlet; @WebServlet("/slack/events") public class SlackEventsController extends SlackAppServlet { public SlackEventsController(App app) { super(app); } } @WebServlet("/slack/install") public class SlackOAuthInstallController extends SlackOAuthAppServlet { public SlackOAuthInstallController(App app) { super(app); } } @WebServlet("/slack/oauth_redirect") public class SlackOAuthRedirectController extends SlackOAuthAppServlet { public SlackOAuthRedirectController(App app) { super(app); } } ``` -------------------------------- ### Run Slack Bolt App with Socket Mode (Standard Java) Source: https://tools.slack.dev/java-slack-sdk/guides/getting-started-with-bolt Demonstrates the main method to initialize a Slack Bolt `App` and start it using `SocketModeApp`. This requires `SLACK_BOT_TOKEN` and `SLACK_APP_TOKEN` environment variables. ```java package hello; import com.slack.api.bolt.App; import com.slack.api.bolt.socket_mode.SocketModeApp; public class MyApp { public static void main(String[] args) throws Exception { // App expects an env variable: SLACK_BOT_TOKEN App app = new App(); app.command("/hello", (req, ctx) -> { return ctx.ack(":wave: Hello!"); }); // SocketModeApp expects an env variable: SLACK_APP_TOKEN new SocketModeApp(app).start(); } } ``` -------------------------------- ### Gradle Maven Local Repository Configuration Source: https://tools.slack.dev/java-slack-sdk/guides/web-api-client-setup A Gradle repository configuration snippet that enables the use of the local Maven repository. This is necessary if you have built the Slack SDK from source and want to use the locally installed artifacts. ```gradle repositories { mavenLocal() } ``` -------------------------------- ### Initialize Slack Client with Default Configuration Source: https://tools.slack.dev/java-slack-sdk/guides/web-api-basics Demonstrates the basic setup for using the Slack Java SDK by creating a default SlackConfig and initializing the Slack client instance. ```java import com.slack.api.Slack; import com.slack.api.SlackConfig; SlackConfig config = new SlackConfig(); Slack slack = Slack.getInstance(config); ``` -------------------------------- ### Kotlin HTTP Server App Initialization Source: https://tools.slack.dev/java-slack-sdk/guides/getting-started-with-bolt A minimal Kotlin code snippet to initialize and start a Slack Bolt application using an embedded HTTP server (Jetty). It configures the Bolt App and starts the SlackAppServer on localhost. ```kotlin import com.slack.api.bolt.App import com.slack.api.bolt.jetty.SlackAppServer fun main() { val app = App() // Write some code here val server = SlackAppServer(app) server.start() // http://localhost:3000/slack/events } ``` -------------------------------- ### Maven Run Command with Debug Logging Source: https://tools.slack.dev/java-slack-sdk/guides/getting-started-with-bolt Example of running a Maven application with SLF4J debug logging enabled for detailed output. ```Shell mvn compile exec:java -Dexec.mainClass="hello.MyApp" -Dorg.slf4j.simpleLogger.defaultLogLevel=debug ``` -------------------------------- ### Gradle Run Command with Debug Logging Source: https://tools.slack.dev/java-slack-sdk/guides/getting-started-with-bolt Example of running a Gradle application with enhanced logging enabled for detailed output. ```Shell gradle run -DslackLogLevel=debug ``` -------------------------------- ### Start Slack Socket Mode App (Java) Source: https://tools.slack.dev/java-slack-sdk/guides/socket-mode Shows how to initialize and start a `SocketModeApp` to enable real-time communication with Slack via WebSockets. This requires an app-level token and a pre-configured Bolt `App` instance. ```Java import com.slack.api.bolt.socket_mode.SocketModeApp; // Note: If you use bolt-jakarta-socket-mode instead, the import would be: // import com.slack.api.bolt.jakarta_socket_mode.SocketModeApp; // the app-level token with `connections:write` scope String appToken = System.getenv("SLACK_APP_TOKEN"); // Initialize the adapter for Socket Mode // with an app-level token and your Bolt app with listeners. SocketModeApp socketModeApp = new SocketModeApp(appToken, app); // #start() method establishes a new WebSocket connection and then blocks the current thread. // If you do not want to block this thread, use #startAsync() instead. socketModeApp.start(); ``` -------------------------------- ### Initialize and Start Socket Mode App with Java-WebSocket Source: https://tools.slack.dev/java-slack-sdk/guides/socket-mode Demonstrates how to initialize and start a Slack Socket Mode application using the `bolt-socket-mode` library. It specifies the `JavaWebSocket` backend and requires the `org.java-websocket:Java-WebSocket` Maven dependency. The app token is used to establish the connection. ```java String appToken = "xapp-"; App app = new App(); SocketModeApp socketModeApp = new SocketModeApp( appToken, SocketModeClient.Backend.JavaWebSocket, app ); socketModeApp.start(); ``` -------------------------------- ### Assistant Simple App Java Example Source: https://tools.slack.dev/java-slack-sdk/ja-jp/guides/ai-apps This Java code demonstrates a Slack Assistant application. It uses Bolt and Socket Mode to handle assistant-specific events like thread starts and user messages, including file uploads. The example shows how to set suggested prompts and manage status updates. ```java package samples; import com.slack.api.bolt.App; import com.slack.api.bolt.AppConfig; import com.slack.api.bolt.middleware.builtin.Assistant; import com.slack.api.bolt.socket_mode.SocketModeApp; import com.slack.api.model.assistant.SuggestedPrompt; import com.slack.api.model.event.AppMentionEvent; import com.slack.api.model.event.MessageEvent; import java.util.Collections; public class AssistantSimpleApp { public static void main(String[] args) throws Exception { String botToken = System.getenv("SLACK_BOT_TOKEN"); String appToken = System.getenv("SLACK_APP_TOKEN"); App app = new App(AppConfig.builder().singleTeamBotToken(botToken).build()); Assistant assistant = new Assistant(app.executorService()); assistant.threadStarted((req, ctx) -> { try { ctx.say("Hi, how can I help you today?"); ctx.setSuggestedPrompts(r -> r .title("Select one of the following:") // optional .prompts(Collections.singletonList(SuggestedPrompt.create("What does SLACK stand for?"))) ); } catch (Exception e) { ctx.logger.error("Failed to handle assistant thread started event: {e}", e); } }); assistant.userMessage((req, ctx) -> { try { // ctx.setStatus(r -> r.status("is typing...")); works too ctx.setStatus("is typing..."); Thread.sleep(500L); if (ctx.getThreadContext() != null) { String contextChannel = ctx.getThreadContext().getChannelId(); ctx.say("I am ware of the channel context: <#" + contextChannel + ">"); } else { ctx.say("Here you are!"); } } catch (Exception e) { ctx.logger.error("Failed to handle assistant user message event: {e}", e); try { ctx.say(":warning: Sorry, something went wrong during processing your request!"); } catch (Exception ee) { ctx.logger.error("Failed to inform the error to the end-user: {ee}", ee); } } }); assistant.userMessageWithFiles((req, ctx) -> { try { ctx.setStatus("is analyzing the files..."); Thread.sleep(500L); ctx.setStatus("is still checking the files..."); Thread.sleep(500L); ctx.say("Your files do not have any issues!"); } catch (Exception e) { ctx.logger.error("Failed to handle assistant user message event: {e}", e); try { ctx.say(":warning: Sorry, something went wrong during processing your request!"); } catch (Exception ee) { ctx.logger.error("Failed to inform the error to the end-user: {ee}", ee); } } }); app.use(assistant); app.event(MessageEvent.class, (req, ctx) -> { return ctx.ack(); }); app.event(AppMentionEvent.class, (req, ctx) -> { ctx.say("You can help you at our 1:1 DM!"); return ctx.ack(); }); new SocketModeApp(appToken, app).start(); } } ``` -------------------------------- ### Setup Slack Env and Run Kotlin App with Gradle Source: https://tools.slack.dev/java-slack-sdk/guides/getting-started-with-bolt Configures Slack API credentials via environment variables and initiates the application build and execution using the Gradle build tool. This process is essential for launching your Kotlin-based Bolt application. ```Shell # Visit https://api.slack.com/apps to know these export SLACK_BOT_TOKEN=xoxb-...your-own-valid-one export SLACK_SIGNING_SECRET=123abc...your-own-valid-one # run the main function gradle run ``` -------------------------------- ### Basic Slack Bolt App with Jetty Source: https://tools.slack.dev/java-slack-sdk/ja-jp/guides/getting-started-with-bolt A minimal Java application using Slack Bolt and Jetty to start a server. It defines a handler for the '/hello' command and listens for Slack events on the default port (3000). ```java package hello; import com.slack.api.bolt.App; // bolt-jakarta-jetty を使う場合は `com.slack.api.bolt.jakarta_jetty.SlackAppServer` を import してください import com.slack.api.bolt.jetty.SlackAppServer; public class MyApp { public static void main(String[] args) throws Exception { // SLACK_BOT_TOKEN, SLACK_SIGNING_SECRET という環境変数が設定されている前提 App app = new App(); app.command("/hello", (req, ctx) -> { return ctx.ack(":candy: はい、アメちゃん!"); }); SlackAppServer server = new SlackAppServer(app); server.start(); // http://localhost:3000/slack/events } } ``` -------------------------------- ### Running the Slack Bolt App Source: https://tools.slack.dev/java-slack-sdk/ja-jp/guides/getting-started-with-bolt Commands to run the application using Gradle or Maven after setting up the required environment variables. This starts the Jetty server and makes the Slack app accessible. ```shell # main メソッドを実行して、サーバープロセスを起動 # Gradle の場合 gradle run # Maven の場合 mvn compile exec:java -Dexec.mainClass="hello.MyApp" ``` -------------------------------- ### Running Quarkus Application in Development Mode Source: https://tools.slack.dev/java-slack-sdk/guides/supported-web-frameworks Provides commands to run a Quarkus application in development mode using Maven or Gradle. It also shows example output logs indicating the application has started and is listening for events, including hot reload status. ```shell ./mvnw quarkus:dev ./mvnw clean quarkus:dev # try clean when you don't see some updates ``` ```shell ./gradlew quarkusDev ``` ```shell [INFO] --- quarkus-maven-plugin:2.12.0.Final:dev (default-cli) @ code-with-quarkus --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 1 source file to /path-to-projet/target/classes Listening for transport dt_socket at address: 5005 __ ____ __ _____ ___ __ ____ ______ --/ __ \/ / / / _ | / _ \/ //_/ / / / __/ -/ /_/ / /_/ / __ |/ , _/ ,< / /_/ /\ \ --\___\_\____/_/ |_/_/|_/_/|_|\____/___/ INFO [io.quarkus] (main) code-with-quarkus 1.0.0-SNAPSHOT (powered by Quarkus 2.12.0.Final)) started in 0.846s. Listening on: http://0.0.0.0:3000 INFO [io.quarkus] (main) Profile dev activated. Live Coding activated. INFO [io.quarkus] (main) Installed features: [cdi, servlet] INFO [io.qua.dev] (vert.x-worker-thread-0) Changed source files detected, recompiling [/path-to-project/src/main/java/hello/SlackApp.java] INFO [io.quarkus] (vert.x-worker-thread-0) Quarkus stopped in 0.001s __ ____ __ _____ ___ __ ____ ______ --/ __ \/ / / / _ | / _ \/ //_/ / / / __/ -/ /_/ / /_/ / __ |/ , _/ ,< / /_/ /\ \ --\___\_\____/_/ |_/_/|_/_/|_|\____/___/ INFO [io.quarkus] (vert.x-worker-thread-0) code-with-quarkus 1.0.0-SNAPSHOT (powered by Quarkus 2.12.0.Final) started in 0.021s. Listening on: http://0.0.0.0:3000 INFO [io.quarkus] (vert.x-worker-thread-0) Profile dev activated. Live Coding activated. INFO [io.quarkus] (vert.x-worker-thread-0) Installed features: [cdi, servlet] INFO [io.qua.dev] (vert.x-worker-thread-0) Hot replace total time: 0.232s ``` -------------------------------- ### Configure Amazon S3 Storage for Slack Bolt Java SDK Source: https://tools.slack.dev/java-slack-sdk/guides/app-distribution Example demonstrating how to use Amazon S3 for storing installation data and OAuth state parameters in a Slack Bolt Java application. It shows the setup of `InstallationService` and `OAuthStateService` using AWS environment variables and a specified S3 bucket name, then integrates them with `App` instances and `SlackAppServer`. ```Java import com.slack.api.bolt.App; import com.slack.api.bolt.jetty.SlackAppServer; import com.slack.api.bolt.service.InstallationService; import com.slack.api.bolt.service.OAuthStateService; import com.slack.api.bolt.service.builtin.AmazonS3InstallationService; import com.slack.api.bolt.service.builtin.AmazonS3OAuthStateService; import java.util.HashMap; import java.util.Map; import static java.util.Map.entry; // The standard AWS env variables are expected // export AWS_REGION=us-east-1 // export AWS_ACCESS_KEY_ID=AAAA************* // export AWS_SECRET_ACCESS_KEY=4o7*********************** // Please be careful about the security policies on this bucket. String awsS3BucketName = "YOUR_OWN_BUCKET_NAME_HERE"; InstallationService installationService = new AmazonS3InstallationService(awsS3BucketName); // Set true if you'd like to store every single installation as a different record installationService.setHistoricalDataEnabled(true); // apiApp uses only InstallationService to access stored tokens App apiApp = new App(); apiApp.command("/hi", (req, ctx) -> { return ctx.ack("Hi there!"); }); apiApp.service(installationService); // Needless to say, oauthApp uses InstallationService // In addition, it uses OAuthStateService to create/read/delete state parameters App oauthApp = new App().asOAuthApp(true); oauthApp.service(installationService); // Store valid state parameter values in Amazon S3 storage OAuthStateService stateService = new AmazonS3OAuthStateService(awsS3BucketName); // This service is necessary only for OAuth flow apps oauthApp.service(stateService); // Mount the two apps with their root path SlackAppServer server = new SlackAppServer(new HashMap<>(Map.ofEntries( entry("/slack/events", apiApp), // POST /slack/events (incoming API requests from the Slack Platform) entry("/slack/oauth", oauthApp) // GET /slack/oauth/start, /slack/oauth/callback (user access) ))); server.start(); // http://localhost:3000 ``` -------------------------------- ### Gradle Build Configuration for Kotlin Source: https://tools.slack.dev/java-slack-sdk/guides/web-api-client-setup Sets up a Kotlin project with Gradle, including the Kotlin JVM plugin, Maven Central repository, and dependencies for the Slack API client and Kotlin extensions. It also specifies the main class name for Kotlin applications. ```gradle plugins { id("org.jetbrains.kotlin.jvm") version "1.7.21" // use the latest Kotlin version id("application") } repositories { mavenCentral() } dependencies { implementation(platform("org.jetbrains.kotlin:kotlin-bom")) implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") implementation("com.slack.api:slack-api-client:1.45.3") // Add these dependencies if you want to use the Kotlin DSL for building rich messages implementation("com.slack.api:slack-api-model-kotlin-extension:1.45.3") implementation("com.slack.api:slack-api-client-kotlin-extension:1.45.3") } application { mainClassName = "ExampleKt" // add "Kt" suffix for main function source file } ``` -------------------------------- ### Spring Boot Application Entry Point Source: https://tools.slack.dev/java-slack-sdk/guides/supported-web-frameworks The main class for bootstrapping the Spring Boot application. It enables component scanning and starts the embedded web server, providing the foundation for the Slack Bolt application to run. ```java package hello; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication @ServletComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` -------------------------------- ### Gradle Build Configuration for Java Source: https://tools.slack.dev/java-slack-sdk/guides/web-api-client-setup Configures a Java project to use the Slack API client via Gradle. This `build.gradle` file specifies the application plugin, Maven Central repository, and the Slack API client dependency. ```gradle plugins { id("application") } repositories { mavenCentral() } dependencies { implementation("com.slack.api:slack-api-client:1.45.3") } application { mainClassName = "Example" } ``` -------------------------------- ### InstallationService Interface Methods Source: https://tools.slack.dev/java-slack-sdk/guides/app-distribution This API documentation outlines the essential methods required for a custom `InstallationService` implementation in Bolt for Java. These methods are crucial for securely managing bot and user installation data, especially when handling token revocation or app uninstallation events. ```APIDOC InstallationService Interface: Methods required for custom implementations: - void deleteBot(Bot bot) Description: Deletes the installation data associated with a specific bot. Parameters: - bot: The Bot object containing installation details. - void deleteInstaller(Installer installer) Description: Deletes the installation data associated with a specific installer (user). Parameters: - installer: The Installer object containing installation details. - void deleteAll(String enterpriseId, String teamId) Description: Deletes all installation data for a given enterprise and team. Parameters: - enterpriseId: The ID of the Slack enterprise. - teamId: The ID of the Slack team. ``` -------------------------------- ### Java Quarkus Slack App Servlet Source: https://tools.slack.dev/java-slack-sdk/ja-jp/guides/supported-web-frameworks Example of a Java Slack application using the Slack Bolt SDK with Quarkus. It extends `SlackAppServlet` and registers a `/hello` command handler. Requires `com.slack.api.bolt` and `javax.servlet.annotation.WebServlet`. ```java package hello; import com.slack.api.bolt.App; import com.slack.api.bolt.servlet.SlackAppServlet; import javax.servlet.annotation.WebServlet; @WebServlet("/slack/events") public class SlackApp extends SlackAppServlet { private static final long serialVersionUID = 1L; public SlackApp() { super(initSlackApp()); } public SlackApp(App app) { super(app); } private static App initSlackApp() { App app = new App(); app.command("/hello", (req, ctx) -> { return ctx.ack("What's up?"); }); return app; } } ``` -------------------------------- ### Socket Mode Considerations Source: https://tools.slack.dev/java-slack-sdk/ja-jp/guides/events-api Notes on how Socket Mode affects the Event API setup process, specifically regarding the Request URL configuration. ```APIDOC Socket Mode Note: When using Socket Mode, the step of setting a `Request URL` in the Slack app's Event Subscriptions configuration is not necessary. Slack communicates directly with your application via the WebSocket connection established through Socket Mode. ``` -------------------------------- ### Custom Slack Installation and State Services with Spring Source: https://tools.slack.dev/java-slack-sdk/guides/app-distribution Shows how to configure custom implementations for `InstallationService` and `OAuthStateService` as Spring beans. This allows for custom storage solutions, such as Amazon S3, for managing installation data and OAuth state, enhancing flexibility and persistence. ```Java import com.slack.api.bolt.service.InstallationService; import com.slack.api.bolt.service.OAuthStateService; import com.slack.api.bolt.service.impl.AmazonS3InstallationService; import com.slack.api.bolt.service.impl.AmazonS3OAuthStateService; // ... other imports public class SlackApp { // Please be careful about the security policies on this bucket. private static final String S3_BUCKET_NAME = "your-s3-bucket-name"; @Bean public InstallationService initInstallationService() { InstallationService installationService = new AmazonS3InstallationService(S3_BUCKET_NAME); installationService.setHistoricalDataEnabled(true); return installationService; } @Bean public OAuthStateService initStateService() { return new AmazonS3OAuthStateService(S3_BUCKET_NAME); } @Bean public App initSlackApp(InstallationService installationService, OAuthStateService stateService) { App app = new App().asOAuthApp(true); app.service(installationService); app.service(stateService); return app; } } ``` -------------------------------- ### SCIM API Client Setup (Java) Source: https://tools.slack.dev/java-slack-sdk/ja-jp/guides/scim-api Initializes the SCIM API client using the Slack instance and an administrator access token. Requires the 'admin' scope for the token. ```java import com.slack.api.Slack; import com.slack.api.scim.*; Slack slack = Slack.getInstance(); String token = System.getenv("SLACK_ADMIN_ACCESS_TOKN"); // `admin` scope が必要 SCIMClient scim = slack.scim(token); ``` -------------------------------- ### Bolt for Java OAuth Flow Handling Source: https://tools.slack.dev/java-slack-sdk/guides/app-distribution Details the steps required for a Bolt for Java application to handle the OAuth flow for app installation and distribution. This includes initiating the authorization process, managing callbacks, and completing the installation. ```APIDOC Bolt for Java OAuth Flow: This section outlines the essential steps for implementing OAuth in your Bolt for Java application to allow users to install your app in their Slack workspaces. 1. **Initiate OAuth Flow**: * Provide an endpoint that redirects installers to Slack's `authorize` endpoint. * Generate a unique `state` parameter to verify the request later. * Append necessary parameters to the authorization URL: `client_id`, `scope`, `user_scope` (for v2), and the generated `state`. * Example URL structure: `https://slack.com/oauth/v2/authorize?client_id={client_id}&scope={scope}&user_scope={user_scope}&state={state}` 2. **Handle Redirect from Slack**: * Create an endpoint to receive the callback from Slack after the user authorizes the app. * Verify the received `state` parameter against the one generated in step 1 to ensure security. * Complete the installation by calling the Slack API method `oauth.v2.access` (for OAuth v2) or `oauth.access` (for legacy OAuth apps). * Store the acquired access tokens securely for future API calls. * API Method: `oauth.v2.access` * Description: Exchanges an authorization code for an access token. * Parameters: * `code`: The authorization code received from Slack. * `client_id`: Your app's client ID. * `client_secret`: Your app's client secret. * `redirect_uri`: The redirect URL used in the authorization request. * Returns: An object containing `access_token`, `scope`, `user` (if `user_scope` was requested), `team`, etc. * API Method: `oauth.access` (Legacy) * Description: Exchanges an authorization code for an access token (for older apps). * Parameters: * `code`: The authorization code. * `client_id`: Your app's client ID. * `client_secret`: Your app's client secret. * `redirect_uri`: The redirect URL. * Returns: Similar to `oauth.v2.access` but may differ in structure and available fields. 3. **Provide Completion/Cancellation Endpoints**: * Offer endpoints that guide users through the final stages of installation or allow them to cancel the process. * Bolt for Java provides built-in functionality to serve these endpoints. **Configuration Notes**: * **Redirect URL**: For Bolt apps, the recommended redirect URL is `https://{your app's public URL domain}/slack/oauth/callback`. * **Org-Wide Installations**: Supported since Bolt for Java version `1.4.0`. Enable this in your app settings under **Org Level Apps**. ``` -------------------------------- ### MethodsStats JSON Structure Example Source: https://tools.slack.dev/java-slack-sdk/ja-jp/guides/web-api-basics An example JSON representation of the `MethodsStats` object, illustrating the metrics collected for API calls. This includes counts for completed, successful, unsuccessful, and failed calls, as well as queue size and rate-limited methods. ```json { "DEFAULT_SINGLETON_EXECUTOR": { "T1234567": { "all_completed_calls": { "chat.postMessage": 120, "users.info": 2, "conversations.members": 2 }, "successful_calls": { "chat.postMessage": 110, "users.info": 2, "conversations.members": 2 }, "unsuccessful_calls": { "chat.postMessage": 7 }, "failed_calls": { "chat.postMessage": 3 }, "current_queue_size": { "chat.postMessage_C01ABC123": 5, "users.info": 0 }, "last_minute_requests": { "chat.postMessage_C01ABC123": 100, "chat.postMessage_C03XYZ555": 3, "users.info": 2, "conversations.members": 2 }, "rateLimitedMethods": { "chat.postMessage_C01ABC123": 1582183395064 } } } } ``` -------------------------------- ### Kotlin Socket Mode App Initialization Source: https://tools.slack.dev/java-slack-sdk/guides/getting-started-with-bolt A minimal Kotlin code snippet to initialize and start a Slack Bolt application using Socket Mode. It sets up the Bolt App and then wraps it in a SocketModeApp to listen for events. ```kotlin import com.slack.api.bolt.App import com.slack.api.bolt.socket_mode.SocketModeApp fun main() { val app = App() // Write some code here SocketModeApp(app).start() } ``` -------------------------------- ### Kotlin Quarkus Slack App Servlet Source: https://tools.slack.dev/java-slack-sdk/ja-jp/guides/supported-web-frameworks Example of a Kotlin Slack application using the Slack Bolt SDK with Quarkus. It extends `SlackAppServlet` and registers a `/ping` command handler. Requires `com.slack.api.bolt` and `javax.servlet.annotation.WebServlet`. ```kotlin package hello import com.slack.api.bolt.App import com.slack.api.bolt.servlet.SlackAppServlet import javax.servlet.annotation.WebServlet @WebServlet("/slack/events") class SlackApp : SlackAppServlet(initSlackApp()) { companion object { fun initSlackApp(): App { val app = App() app.command("/ping") { req, ctx -> ctx.ack("<@${req.payload.userId}> pong!") } return app } } } ``` -------------------------------- ### Configure RedisMetricsDatastore Source: https://tools.slack.dev/java-slack-sdk/ja-jp/guides/web-api-basics Sets up the `RedisMetricsDatastore` to aggregate metrics from all nodes into a Redis cluster. This example shows configuration using a local JedisPool instance. ```java import com.slack.api.Slack; import com.slack.api.SlackConfig; import com.slack.api.methods.metrics.RedisMetricsDatastore; import redis.clients.jedis.JedisPool; SlackConfig config = new SlackConfig(); // macOS では、以下の手順で起動させることができます // brew install redis // redis-server /usr/local/etc/redis.conf --loglevel verbose JedisPool jedis = new JedisPool("localhost"); config.getMethodsConfig().setMetricsDatastore(new RedisMetricsDatastore("test", jedis)); Slack slack = Slack.getInstance(config); ``` -------------------------------- ### Equivalent cURL Command for Post Message Source: https://tools.slack.dev/java-slack-sdk/guides/web-api-basics Illustrates the cURL command that performs the same action as the Java code examples: posting a message to a Slack channel. It shows the necessary headers and data payload. ```curl curl -XPOST https://slack.com/api/chat.postMessage \ -H 'Content-Type: application/x-www-form-urlencoded' \ -H 'Authorization: Bearer xoxb-123-123-abcabcabc' \ -d 'channel=%23random&text=%3Awave%3A%20Hi%20from%20a%20bot%20written%20in%20Java%21' ``` -------------------------------- ### Slack App Home Configuration and Interaction Source: https://tools.slack.dev/java-slack-sdk/guides/app-home Guides users through configuring App Home settings within the Slack app dashboard and outlines the core API interactions for managing App Home content. This includes enabling the Home tab, setting up event subscriptions, publishing view updates, and handling user interactions within the App Home. ```APIDOC Slack App Configuration: 1. Enable Home Tabs: - Navigate to Slack app settings page (api.slack.com/apps). - Select your app. - Go to **Features** > **App Home**. - Turn on **Home Tab**. 2. Enable Events API: - Go to **Features** > **Event Subscriptions**. - Turn on **Enable Events**. - Set **Request URL** to `https://{your app's public URL domain}/slack/events` (not required for Socket Mode apps). - Subscribe to bot events: - Click **Subscribe to bot events**. - Click **Add Bot User Event**. - Choose the **app_home_opened** event. - Click **Save Changes**. App Home Interaction with Bolt for Java: 1. Publish Views: - Use the `views.publish` method to update the Home tab for a specific user. - This method requires a `token` (user or bot token), `user_id`, and a `view` payload (JSON object defining the UI). - Example usage pattern: `slack.methods("views.publish").call(ViewsPublishRequest.builder().userId(userId).view(view).build());` 2. Handle Events: - Handle user interactions within the Home tab by subscribing to events like `block_actions` and `block_suggestion`. - The `app_home_opened` event is commonly used as a trigger to initially publish the Home tab view. - Example event handler signature: `app.event(AppHomeOpened.class, (payload, ctx) -> { ... });` `app.blockAction("your_block_id", (payload, ctx) -> { ... });` Related Methods/Events: - `views.publish`: API method to update a user's Home tab. - `app_home_opened`: Event triggered when a user opens the app's Home tab. - `block_actions`: Event triggered by user interaction with blocks (e.g., buttons). - `block_suggestion`: Event triggered when a user interacts with input elements that require suggestions (e.g., select menus). ``` -------------------------------- ### Slack API Success Response Example Source: https://tools.slack.dev/java-slack-sdk/guides/web-api-basics Illustrates a typical successful response from the Slack Web API, containing an 'ok' boolean set to true and additional data. ```json { "ok": true, "stuff": "This is good" } ``` -------------------------------- ### Run App with Helidon CLI Dev Mode Source: https://tools.slack.dev/java-slack-sdk/guides/supported-web-frameworks Starts the application in development mode using the Helidon CLI, which typically provides features like hot-reloading. ```shell helidon dev ``` -------------------------------- ### Slack Bolt App with Kotlin Command Handler Source: https://tools.slack.dev/java-slack-sdk/guides/supported-web-frameworks Demonstrates setting up a Slack Bolt application using Kotlin. It registers a `/ping` command that acknowledges the user with a "pong!" message. This example uses the `SlackAppServlet` for integration with servlet containers. ```kotlin package hello import com.slack.api.bolt.App import com.slack.api.bolt.servlet.SlackAppServlet import javax.servlet.annotation.WebServlet @WebServlet("/slack/events") class SlackApp : SlackAppServlet(initSlackApp()) { companion object { fun initSlackApp(): App { val app = App() app.command("/ping") { req, ctx -> ctx.ack("<@${req.payload.userId}> pong!") } return app } } } ``` -------------------------------- ### Kotlin Quarkus Slack App with CDI Producers Source: https://tools.slack.dev/java-slack-sdk/ja-jp/guides/supported-web-frameworks Example of a Kotlin Slack application using Slack Bolt with Quarkus, leveraging CDI for dependency injection. It defines a producer for the `App` instance and registers a `/ping` command. ```kotlin package hello import com.slack.api.bolt.App import com.slack.api.bolt.servlet.SlackAppServlet import javax.enterprise.inject.Produces import javax.inject.Inject import javax.servlet.annotation.WebServlet @WebServlet("/slack/events") class SlackApp(app: App?) : @Inject SlackAppServlet(app) class Components { @Produces fun initApp(): App { val app = App() app.command("/ping") { req, ctx -> ctx.ack("<@${req.payload.userId}> pong!") } return app } } ``` -------------------------------- ### Redis Metrics Datastore Setup Source: https://tools.slack.dev/java-slack-sdk/guides/web-api-basics Configures the Slack Java SDK to use a Redis instance as a datastore for collecting application metrics. This requires a running Redis server and the Jedis client library. ```java import com.slack.api.Slack; import com.slack.api.SlackConfig; import com.slack.api.methods.metrics.RedisMetricsDatastore; import redis.clients.jedis.JedisPool; // Ensure Redis is installed and running (e.g., via brew install redis && redis-server /usr/local/etc/redis.conf --loglevel verbose) JedisPool jedis = new JedisPool("localhost"); SlackConfig config = new SlackConfig(); config.getMethodsConfig().setMetricsDatastore(new RedisMetricsDatastore("test", jedis)); Slack slack = Slack.getInstance(config); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.