### Complete example with Slack instance and token loading in Java Source: https://docs.slack.dev/tools/java-slack-sdk/guides/web-api-basics A self-contained example demonstrating how to initialize the Slack instance, load the token from an environment variable, and send a message using the concise functional approach. ```java import com.slack.api.Slack;import com.slack.api.methods.response.chat.ChatPostMessageResponse; Slack slack = Slack.getInstance(); String token = System.getenv("SLACK_TOKEN"); ChatPostMessageResponse response = slack.methods(token).chatPostMessage(req -> req .channel("#random") .text(":wave: Hi from a bot written in Java!")); ``` -------------------------------- ### Quarkus Development Mode Startup Output Source: https://docs.slack.dev/tools/java-slack-sdk/guides/supported-web-frameworks Example output when a Quarkus application starts in development mode, showing listening port and activated features. ```log [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/classesListening 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:3000INFO [io.quarkus] (main) Profile dev activated. Live Coding activated.INFO [io.quarkus] (main) Installed features: [cdi, servlet] ``` -------------------------------- ### Generate Helidon SE Quickstart Project Source: https://docs.slack.dev/tools/java-slack-sdk/guides/supported-web-frameworks Maven command to generate a new Helidon SE quickstart project with specified group ID, artifact ID, and package. ```bash mvn archetype:generate \ -DinteractiveMode=false \ -DarchetypeGroupId=io.helidon.archetypes \ -DarchetypeArtifactId=helidon-quickstart-se \ -DarchetypeVersion=2.5.0 \ -DgroupId=com.exmple \ -DartifactId=helidon-se-bolt-app \ -Dpackage=hello ``` -------------------------------- ### Gradle Command to Run Example Source: https://docs.slack.dev/tools/java-slack-sdk/guides/web-api-client-setup Execute this command in your terminal to run the Example.java file using Gradle. ```bash gradle run ``` -------------------------------- ### Logback configuration example Source: https://docs.slack.dev/tools/java-slack-sdk/guides/bolt-basics This is an example of a logback.xml configuration file, which can be used to configure logging settings for applications using the logback-classic library. ```xml %date %level [%thread] %logger{64} %msg%n ``` -------------------------------- ### Application Startup Output Source: https://docs.slack.dev/tools/java-slack-sdk/guides/supported-web-frameworks Expected console output when the application starts successfully. ```text [main] io.helidon.webserver.NettyWebServer Version: 2.5.0[nioEventLoopGroup-2-1] io.helidon.webserver.NettyWebServer Channel '@default' started: [id: 0x9fcf416d, L:/0:0:0:0:0:0:0:0:3000][nioEventLoopGroup-2-1] com.slack.api.bolt.helidon.SlackAppServer ⚡️ Bolt app is running! ``` -------------------------------- ### Build SDK from Source Source: https://docs.slack.dev/tools/java-slack-sdk/guides/web-api-client-setup Commands to clone the repository and install the SDK modules to the local Maven repository. ```bash git clone git@github.com:slackapi/java-slack-sdk.gitcd java-slack-sdkmvn install -Dmaven.test.skip=true ``` -------------------------------- ### Maven Command to Compile and Run Example Source: https://docs.slack.dev/tools/java-slack-sdk/guides/web-api-client-setup Execute this command in your terminal to compile and run the Example.java file using Maven. ```bash mvn compile exec:java \ -Dexec.cleanupDaemonThreads=false \ -Dexec.mainClass="Example" ``` -------------------------------- ### Assistant Simple App Java Example Source: https://docs.slack.dev/tools/java-slack-sdk/guides/ai-apps This is a complete Java example for a Slack Assistant app using Bolt. It demonstrates how to initialize the app, configure the Assistant middleware, and handle different user message events. Ensure you have SLACK_BOT_TOKEN and SLACK_APP_TOKEN environment variables set. ```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.Arrays; 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 && ctx.getThreadContext().getChannelId() != null) { String contextChannel = ctx.getThreadContext().getChannelId(); ctx.say("I am aware 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 downloading the files..."); Thread.sleep(500L); ctx.setStatus("is analyzing the files...", Arrays.asList("Reading bytes...", "Confirming hashes...")); 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("I can help you at our 1:1 DM!"); return ctx.ack(); }); new SocketModeApp(appToken, app).start(); } } ``` -------------------------------- ### Implement Custom Installation and OAuth State Services Source: https://docs.slack.dev/tools/java-slack-sdk/guides/app-distribution Demonstrates how to register custom S3-based installation and state services as Spring beans within the Slack App configuration. ```java 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; }} ``` -------------------------------- ### Implement Slack API Test in Kotlin Source: https://docs.slack.dev/tools/java-slack-sdk/guides/web-api-client-setup A basic example demonstrating how to initialize the Slack client and perform an API test. ```kotlin import com.slack.api.Slackfun main() { val slack = Slack.getInstance() val response = slack.methods().apiTest { it.foo("bar") } println(response)} ``` -------------------------------- ### Java Example for Slack API Client Verification Source: https://docs.slack.dev/tools/java-slack-sdk/guides/web-api-client-setup A simple Java class with a main method to test the Slack API client setup. Ensure you have OpenJDK 8+ and Maven installed. ```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); } } ``` -------------------------------- ### Configure Logback Logging Source: https://docs.slack.dev/tools/java-slack-sdk/guides/supported-web-frameworks Example logback.xml configuration for SLF4J logging implementation. ```xml %date %level [%thread] %logger{64} %msg%n ``` -------------------------------- ### Run the Helidon Application Source: https://docs.slack.dev/tools/java-slack-sdk/guides/supported-web-frameworks Commands to start the application using Helidon CLI or Maven. ```bash helidon dev ``` ```bash mvn exec:java -Dexec.mainClass="hello.Main" # or mvn package && java -jar target/helidon-se-bolt-app.jar ``` -------------------------------- ### Starting a Kotlin Bolt App Source: https://docs.slack.dev/tools/java-slack-sdk/guides/getting-started-with-bolt Minimum source code to start a Bolt application in Kotlin. ```kotlin import com.slack.api.bolt.Appimport com.slack.api.bolt.socket_mode.SocketModeAppfun main() { val app = App() // Write some code here SocketModeApp(app).start()} ``` ```kotlin import com.slack.api.bolt.Appimport com.slack.api.bolt.jetty.SlackAppServerfun main() { val app = App() // Write some code here val server = SlackAppServer(app) server.start() // http://localhost:3000/slack/events} ``` -------------------------------- ### Configure Redis Metrics Datastore Source: https://docs.slack.dev/tools/java-slack-sdk/guides/web-api-basics Set up a RedisMetricsDatastore for collecting metrics. Ensure Redis is installed and running. ```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(); // 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); ``` -------------------------------- ### Boot Spring Boot application Source: https://docs.slack.dev/tools/java-slack-sdk/guides/supported-web-frameworks Command to start the Spring Boot application using Gradle. ```bash $ gradle bootRun> Task :bootRun . ____ _ __ _ _ /\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v3.0.0)[main] hello.Application : Starting Application on MACHNE_NAME with PID 7815 (/path-to-project/build/classes/java/main started by seratch in /path-to-project)[main] hello.Application : No active profile set, falling back to default profiles: default[main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 3000 (http)[main] o.apache.catalina.core.StandardService : Starting service [Tomcat][main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.29][main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext[main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 478 ms[main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'[main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 3000 (http) with context path ''[main] hello.Application : Started Application in 1.079 seconds (JVM running for 1.301)<=========----> 75% EXECUTING [17s]> :bootRun ``` -------------------------------- ### Metrics Datastore backed by Redis Source: https://docs.slack.dev/tools/java-slack-sdk/guides/web-api-basics Example of configuring a Redis-backed datastore for collecting metrics across nodes. ```APIDOC ## Metrics Datastore backed by Redis ### Description This section demonstrates how to configure a Redis cluster to act as a unified datastore for collecting metrics across different nodes in your application. ### Method Configuration ### Endpoint N/A (Client-side configuration) ### Request Body N/A ### Request Example ```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(); // Ensure Redis is running: 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); ``` ### Response N/A (Client-side configuration) ``` -------------------------------- ### Initialize Slack Bolt with Helidon Source: https://docs.slack.dev/tools/java-slack-sdk/guides/supported-web-frameworks Defines the main entry point to initialize the Slack App and start the Helidon HTTP server. ```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; }} ``` -------------------------------- ### Instantiate SocketModeApp with Java-WebSocket Backend Source: https://docs.slack.dev/tools/java-slack-sdk/guides/socket-mode This example shows how to instantiate `SocketModeApp` and explicitly set the `JavaWebSocket` backend. Ensure the `org.java-websocket:Java-WebSocket` library is added to your project dependencies. ```java String appToken = "xapp-"; App app = new App(); SocketModeApp socketModeApp = new SocketModeApp( appToken, SocketModeClient.Backend.JavaWebSocket, app); socketModeApp.start(); ``` -------------------------------- ### Customize Slack API Clients Source: https://docs.slack.dev/tools/java-slack-sdk/guides/web-api-basics Guide to customizing Slack API clients using `com.slack.api.SlackConfig` with various available options. ```APIDOC ## Customize your Slack API clients ### Description This section details how to customize Slack API clients using the `com.slack.api.SlackConfig` class. You can configure various aspects of the client, such as proxy settings, response logging, and endpoint URLs, by creating a custom `SlackConfig` instance. ### Method Configuration ### Endpoint N/A (Client-side configuration) ### Parameters #### Customizable Options in `SlackConfig` - **`proxyUrl`** (String) - If you enable a proxy server for all outgoing requests to Slack, you can set a single string value representing an absolute URL such as `http://localhost:8888`. (default: null) - **`prettyResponseLoggingEnabled`** (boolean) - If this flag is set as true, the logger prints the whole response JSON data from Slack APIs in a prettified format. (default: `false`) - **`failOnUnknownProperties`** (boolean) - If this flag is set as true, the JSON parser throws an exception when detecting an unknown property in a Slack API response. (default: `false`) - **`tokenExistenceVerificationEnabled`** (boolean) - If this flag is set as true, `MethodsClient` throws exceptions when detecting missing token for API calls. (default: `false`) - **`httpClientResponseHandlers`** (List) - `HttpResponseListener` is a `Consumer` function that works as a post-processing hook for Web API calls. To learn how to implement it, check the code snippet below. (default: mutable empty list) - **`auditEndpointUrlPrefix`** (String) - If you need to set a different URL prefix for Audit Logs API calls, you can set the one. (default: `"https://api.slack.com/audit/v1/"`) - **`methodsEndpointUrlPrefix`** (String) - If you need to set a different URL prefix for API methods calls, you can set the one. (default: `"https://slack.com/api/"`) - **`scimEndpointUrlPrefix`** (String) - If you need to set a different URL prefix for SCIM API calls, you can set the one. (default: `"https://api.slack.com/scim/v1/"`) - **`statusEndpointUrlPrefix`** (String) - If you need to set a different URL prefix for Status API calls, you can set the one. (default: `"https://status.slack.com/api/v2.0.0/"`) - **`legacyStatusEndpointUrlPrefix`** (String) - If you need to set a different URL prefix for Legacy Status API calls, you can set the one. (default: `"https://status.slack.com/api/v1.0.0/"`) ### Request Example ```java import com.slack.api.*; SlackConfig config = new SlackConfig(); config.setPrettyResponseLoggingEnabled(true); Slack slack = Slack.getInstance(config); ``` ### Response N/A (Client-side configuration) ``` -------------------------------- ### Initialize Slack App and Assistant Source: https://docs.slack.dev/tools/java-slack-sdk/ja-jp/guides/assistants Initializes the Slack application with bot token and configures an assistant. The assistant is set up to handle thread started events by sending an initial message with interactive buttons. ```java App app = new App(AppConfig.builder() .singleTeamBotToken(System.getenv("SLACK_BOT_TOKEN")) .ignoringSelfAssistantMessageEventsEnabled(false) .build());Assistant assistant = new Assistant(app.executorService());assistant.threadStarted((req, ctx) -> { try { ctx.say(r -> r .text("Hi, how can I help you today?") .blocks(Arrays.asList( section(s -> s.text(plainText("Hi, how I can I help you today?"))), actions(a -> a.elements(Collections.singletonList( button(b -> b.actionId("assistant-generate-numbers").text(plainText("Generate numbers"))) ))) )) ); } catch (Exception e) { ctx.logger.error("Failed to handle assistant thread started event: {e}", e); }});app.blockAction("assistant-generate-numbers", (req, ctx) -> { app.executorService().submit(() -> { Map eventPayload = new HashMap<>(); eventPayload.put("num", 20); try { ctx.client().chatPostMessage(r -> r .channel(req.getPayload().getChannel().getId()) .threadTs(req.getPayload().getMessage().getThreadTs()) .text("OK, I will generate numbers for you!") .metadata(new Message.Metadata("assistant-generate-numbers", eventPayload)) ); } catch (Exception e) { ctx.logger.error("Failed to post a bot message: {e}", e); } }); return ctx.ack();});assistant.botMessage((req, ctx) -> { if (req.getEvent().getMetadata() != null && req.getEvent().getMetadata().getEventType().equals("assistant-generate-numbers")) { try { ctx.setStatus("is typing..."); Double num = (Double) req.getEvent().getMetadata().getEventPayload().get("num"); Set numbers = new HashSet<>(); SecureRandom random = new SecureRandom(); while (numbers.size() < num) { numbers.add(String.valueOf(random.nextInt(100))); } Thread.sleep(1000L); ctx.say(r -> r.text("Her you are: " + String.join(", ", numbers))); } catch (Exception e) { ctx.logger.error("Failed to handle assistant bot message event: {e}", e); } }});assistant.userMessage((req, ctx) -> { try { ctx.setStatus("is typing..."); ctx.say(r -> r.text("Sorry, I couldn't understand your comment.")); } catch (Exception e) { ctx.logger.error("Failed to handle assistant user message event: {e}", e); try { ctx.say(r -> r.text(":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.assistant(assistant); ``` -------------------------------- ### Handle Select Menu Selections in Kotlin Source: https://docs.slack.dev/tools/java-slack-sdk/guides/interactive-components Kotlin example for handling selections from an external select menu using `app.blockAction`. Acknowledges the interaction. ```kotlin // when a user chooses an item from the "Topics" app.blockAction("topics-action") { req, ctx -> ctx.ack() } ``` -------------------------------- ### Post a Message using chat.postMessage in Kotlin Source: https://docs.slack.dev/tools/java-slack-sdk/guides/web-api-basics A concise Kotlin example for sending a message to a Slack channel, leveraging the SDK's Kotlin DSL. ```kotlin import com.slack.api.Slack val slack = Slack.getInstance() val token = System.getenv("SLACK_TOKEN") val response = slack.methods(token).chatPostMessage { it.channel("#random") it.text(":wave: Hi from a bot written in Kotlin!") } ``` -------------------------------- ### Configure Bolt App for OAuth and API Requests Source: https://docs.slack.dev/tools/java-slack-sdk/guides/app-distribution This example shows how to set up two Bolt App instances: one for handling standard Slack API requests (e.g., commands) and another specifically for managing the OAuth flow. The OAuth app needs to be explicitly enabled using `asOAuthApp(true)`. Ensure all necessary environment variables are configured for each app. ```java import com.slack.api.bolt.App; import com.slack.api.bolt.jetty.SlackAppServer; import java.util.HashMap; import java.util.Map; import static java.util.Map.entry; // API Request Handler App // expected env variables: // SLACK_SIGNING_SECRET App apiApp = new App(); apiApp.command("/hi", (req, ctx) -> { return ctx.ack("Hi there!"); }); // OAuth Flow Handler App // expected env variables: // SLACK_CLIENT_ID, SLACK_CLIENT_SECRET, SLACK_REDIRECT_URI, SLACK_SCOPES, // SLACK_INSTALL_PATH, SLACK_REDIRECT_URI_PATH // SLACK_OAUTH_COMPLETION_URL, SLACK_OAUTH_CANCELLATION_URL App oauthApp = new App().asOAuthApp(true); // 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 ``` -------------------------------- ### Send Message via Incoming Webhook (cURL) Source: https://docs.slack.dev/tools/java-slack-sdk/guides/incoming-webhooks Example of sending a simple 'Hello, World!' message to Slack using cURL and an incoming webhook URL. ```bash curl -X POST \ -H 'Content-type: application/json' \ -d '{"text":"Hello, World!"}' \ https://hooks.slack.com/services/T1234567/AAAAAAAA/ZZZZZZ ``` -------------------------------- ### Kotlin Slack App Servlet for Quarkus Source: https://docs.slack.dev/tools/java-slack-sdk/guides/supported-web-frameworks Example of a Kotlin Slack application using Bolt integrated with Quarkus Servlet. This sets up a command handler for '/ping'. ```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 } } } ``` -------------------------------- ### Handle Select Menu Suggestions in Kotlin Source: https://docs.slack.dev/tools/java-slack-sdk/guides/interactive-components Kotlin example for handling suggestions in external select menus using `app.blockSuggestion`. It filters options based on the input keyword. ```kotlin import com.slack.api.app_backend.interactive_components.response.Option import com.slack.api.model.block.composition.BlockCompositions.plainText // static import import com.slack.api.model.block.composition.PlainTextObject val allOptions = listOf( Option(plainText("Schedule", true), "schedule"), Option(plainText("Budget", true), "budget"), Option(plainText("Assignment", true), "assignment")) // when a user enters some word in "Topics" app.blockSuggestion("topics-action") { req, ctx -> val keyword = req.payload.value val options = allOptions.filter { (it.text as PlainTextObject).text.contains(keyword) } ctx.ack { it.options(if (options.isEmpty()) allOptions else options) } } ``` -------------------------------- ### Initialize Distributed Socket Mode App with OAuth Source: https://docs.slack.dev/tools/java-slack-sdk/guides/socket-mode Initialize a distributed Socket Mode app and start an embedded Jetty Web server for the OAuth flow. Uses startAsync() for Socket Mode to avoid blocking the main thread. ```java import com.slack.api.bolt.App; import com.slack.api.bolt.AppConfig; import com.slack.api.model.event.AppMentionEvent; // As this is a distributed Socket Mode app, // you do not need a token for a specific workspace and the signing secret here. AppConfig appConfig = AppConfig.builder() .clientId("111.222") .clientSecret("xxx") .scope("app_mentions:read,chat:write,commands") .oauthInstallPath("install") .oauthRedirectUriPath("oauth_redirect") .build(); // Initialize the App and register listeners App app = new App(appConfig); app.event(AppMentionEvent.class, (req, ctx) -> { ctx.say("Hi there!"); return ctx.ack(); }); // ------------------------------ // Start a new thread that runs the Socket Mode app in this process 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; String appToken = "xapp-1-A111-111-xxx"; SocketModeApp socketModeApp = new SocketModeApp(appToken, app); // This does not block the current thread socketModeApp.startAsync(); // ------------------------------ // Start an embedded Jetty Web server in this process import com.slack.api.bolt.jetty.SlackAppServer; import java.util.HashMap; import java.util.Map; Map apps = new HashMap<>(); apps.put("/slack/", new App(appConfig).asOAuthApp(true)); SlackAppServer oauthSever = new SlackAppServer(apps); // Block the current thread oauthSever.start(); // Access the OAuth URL - https://{your public domain}/slack/install ``` -------------------------------- ### Java Slack App Servlet with Dependency Injection for Quarkus Source: https://docs.slack.dev/tools/java-slack-sdk/guides/supported-web-frameworks Example of a Java Slack application using Bolt with Quarkus, demonstrating Dependency Injection for the App instance. It configures a '/ping' command. ```java 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 } } ``` -------------------------------- ### Initialize Socket Mode App Source: https://docs.slack.dev/tools/java-slack-sdk/guides/socket-mode Initialize the SocketModeApp adapter for Socket Mode communications using an app-level token and a Bolt app. The start() method blocks the current thread. ```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(); ``` -------------------------------- ### App Class Initialization and Command Handling Source: https://docs.slack.dev/tools/java-slack-sdk/guides/bolt-basics Demonstrates how to initialize the App class and set up a basic command handler for a slash command. ```APIDOC ## POST /command ### Description Handles incoming slash command invocations. ### Method POST ### Endpoint /command ### Parameters #### Query Parameters - **command name** (String | Pattern) - Required - The name of the slash command to handle. ### Request Body (Not explicitly defined, but implied to contain command details) ### Request Example ```java import com.slack.api.bolt.App; App app = new App(); app.command("/echo", (req, ctx) -> { return ctx.ack(req.getText()); }); ``` ### Response #### Success Response (200) - **response** (String) - Acknowledgment response, often containing the echoed text. #### Response Example ``` "You said: [command text]" ``` ``` -------------------------------- ### Slack API Error Response Example Source: https://docs.slack.dev/tools/java-slack-sdk/guides/web-api-basics An example of an unsuccessful response from the Slack Web API, where 'ok' is false and an 'error' property is present. ```json { "ok": false, "error": "something_bad" } ``` -------------------------------- ### Initialize Slack Client with Default Config Source: https://docs.slack.dev/tools/java-slack-sdk/guides/web-api-basics Create a Slack instance using the default configuration, which includes in-memory metrics tracking. ```java import com.slack.api.Slack;import com.slack.api.SlackConfig;SlackConfig config = new SlackConfig();Slack slack = Slack.getInstance(config); ``` -------------------------------- ### Configure Environment Variables and Run Application Source: https://docs.slack.dev/tools/java-slack-sdk/guides/getting-started-with-bolt Set the required Slack credentials as environment variables and execute the application using Gradle or Maven. ```bash # 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 users should run: gradle run # maven users should run: mvn compile exec:java -Dexec.mainClass="hello.MyApp" ``` -------------------------------- ### Initialize SCIM Client in Java Source: https://docs.slack.dev/tools/java-slack-sdk/guides/scim-api Create an instance of the SCIM client using an admin access 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 requiredSCIMClient scim = slack.scim(token); ``` -------------------------------- ### Set Up and Run Kotlin Bolt App Source: https://docs.slack.dev/tools/java-slack-sdk/guides/getting-started-with-bolt Before running, ensure you have obtained your Slack Bot Token and Signing Secret from api.slack.com/apps. Then, set these as environment variables before executing the Gradle run command. ```bash # 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 ``` -------------------------------- ### Micronaut startup log Source: https://docs.slack.dev/tools/java-slack-sdk/guides/supported-web-frameworks Console output confirming the Micronaut server is running. ```text [main] INFO io.micronaut.runtime.Micronaut - Startup completed in 1321ms. Server Running: http://localhost:3000 ``` -------------------------------- ### Example MethodsStats JSON Structure Source: https://docs.slack.dev/tools/java-slack-sdk/guides/web-api-basics A representation of the metrics data structure recorded by the SDK for monitoring API usage. ```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 } } }} ``` -------------------------------- ### Initialize Bolt App and Handle Command Source: https://docs.slack.dev/tools/java-slack-sdk/guides/bolt-basics This snippet shows how to initialize the `App` class and configure a basic command handler for a slash command. It acknowledges the command with the text provided by the user. ```java import com.slack.api.bolt.App; App app = new App(); app.command("/echo", (req, ctx) -> { return ctx.ack(req.getText()); }); ``` -------------------------------- ### Acknowledge Command Request Source: https://docs.slack.dev/tools/java-slack-sdk/guides/bolt-basics Always acknowledge incoming requests using `ctx.ack()`. This example shows a basic acknowledgement for a command. ```java app.command("/hello", (req, ctx) -> { // ctx: Context return ctx.ack(); // empty body, that means your bot won't post a reply this time }); ``` -------------------------------- ### Initialize Audit Client in Java Source: https://docs.slack.dev/tools/java-slack-sdk/guides/audit-logs-api Instantiate the Slack client and obtain an AuditClient. Ensure the SLACK_ADMIN_ACCESS_TOKN environment variable is set with the 'auditlogs:read' scope. ```java import com.slack.api.Slack; import com.slack.api.audit.*; Slack slack = Slack.getInstance(); String token = System.getenv("SLACK_ADMIN_ACCESS_TOKN"); // `auditlogs:read` scope required AuditClient audit = slack.audit(token); ``` -------------------------------- ### Example Actions Block Payload Source: https://docs.slack.dev/tools/java-slack-sdk/guides/interactive-components This JSON represents the payload received when a user interacts with an 'actions' block, such as clicking a button. ```json { "type": "actions", "elements": [{ "type": "button", "action_id": "button-action", "text": { "type": "plain_text", "text": "Button", "emoji": true }, "value": "button's value" }] } ``` -------------------------------- ### Initialize the Slack object Source: https://docs.slack.dev/tools/java-slack-sdk/guides/web-api-basics The entry point for accessing all Slack API clients in the SDK. ```java import com.slack.api.Slack;Slack slack = Slack.getInstance(); ``` -------------------------------- ### Handle Slash Commands in Java Source: https://docs.slack.dev/tools/java-slack-sdk/guides/slash-commands Demonstrates how to register a command handler and return a response using ack(). ```java app.command("/echo", (req, ctx) -> { String commandArgText = req.getPayload().getText(); String channelId = req.getPayload().getChannelId(); String channelName = req.getPayload().getChannelName(); String text = "You said " + commandArgText + " at <#" + channelId + "|" + channelName + ">"; return ctx.ack(text); // respond with 200 OK}); ``` ```java app.command("/echo", (req, ctx) -> { String text = buildMessage(req); ctx.respond(text); // perform an HTTP request return ctx.ack(); // respond with 200 OK}); ``` -------------------------------- ### Slack API Success Response Example Source: https://docs.slack.dev/tools/java-slack-sdk/guides/web-api-basics A typical successful response from the Slack Web API, indicated by the 'ok' property being true. ```json { "ok": true, "stuff": "This is good" } ``` -------------------------------- ### Audit Logs API - Get Actions Source: https://docs.slack.dev/tools/java-slack-sdk/guides/audit-logs-api Retrieves information about the types of actions that the Audit Logs API returns. Authentication is not required. ```APIDOC ## GET /actions ### Description This endpoint returns information about the kind of actions that the Audit Logs API returns as a list of all actions and a short description of each. Authentication is not required. ### Method GET ### Endpoint /actions ### Request Example ```java import com.slack.api.audit.response.ActionsResponse; ActionsResponse response = audit.getActions(); ``` ### Response #### Success Response (200) - **actions** (array) - A list of action objects, each with a `name` and `description`. #### Response Example ```json { "actions": [ { "name": "user_login", "description": "A team member logged in." }, { "name": "channel_created", "description": "A new channel was created." } ] } ``` ``` -------------------------------- ### Publish App Home Tab in Java Source: https://docs.slack.dev/tools/java-slack-sdk/guides/app-home Handles the app_home_opened event to build and publish a view to the user's Home tab, including logic to handle race conditions via view hashes. ```java import com.slack.api.methods.response.views.ViewsPublishResponse;import com.slack.api.model.event.AppHomeOpenedEvent;import com.slack.api.model.view.View;import java.time.ZonedDateTime;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.*;// /reference/events/app_home_openedapp.event(AppHomeOpenedEvent.class, (payload, ctx) -> { // Build a Home tab view ZonedDateTime now = ZonedDateTime.now(); View appHomeView = view(view -> view .type("home") .blocks(asBlocks( section(section -> section.text(markdownText(mt -> mt.text(":wave: Hello, App Home! (Last updated: " + now + ")")))), image(img -> img.imageUrl("https://www.example.com/foo.png").altText("alt text for image")) )) ); // Update the App Home for the given user if (payload.getEvent().getView() == null) { ViewsPublishResponse res = ctx.client().viewsPublish(r -> r .userId(payload.getEvent().getUser()) .view(appHomeView) ); } else { ViewsPublishResponse res = ctx.client().viewsPublish(r -> r .userId(payload.getEvent().getUser()) .hash(payload.getEvent().getView().getHash()) // To safeguard against potential race conditions .view(appHomeView) ); } return ctx.ack();}); ``` -------------------------------- ### Audit Logs API - Get Schemas Source: https://docs.slack.dev/tools/java-slack-sdk/guides/audit-logs-api Retrieves information about the types of objects that the Audit Logs API returns. Authentication is not required. ```APIDOC ## GET /schemas ### Description This endpoint returns information about the kind of objects, which the Audit Logs API returns as a list of all objects and a short description. Authentication is not required. ### Method GET ### Endpoint /schemas ### Request Example ```java import com.slack.api.audit.response.SchemasResponse; SchemasResponse response = audit.getSchemas(); ``` ### Response #### Success Response (200) - **schemas** (array) - A list of schema objects, each with a `name` and `description`. #### Response Example ```json { "schemas": [ { "name": "user", "description": "Represents a user in the organization." }, { "name": "channel", "description": "Represents a channel in the organization." } ] } ``` ``` -------------------------------- ### Audit Logs API - Get Logs Source: https://docs.slack.dev/tools/java-slack-sdk/guides/audit-logs-api Retrieves actual audit events from your organization. Requires authentication and the `auditlogs:read` scope. ```APIDOC ## GET /logs ### Description This is the primary endpoint for retrieving actual audit events from your organization. It will return a list of actions that have occurred on the installed workspace or grid organization. ### Method GET ### Endpoint /logs ### Parameters #### Query Parameters - **oldest** (Unix timestamp) - Optional - Unix timestamp of the least recent audit event to include (inclusive) - **action** (string) - Optional - Filters events by a specific action (e.g., `Actions.User.user_login`) - **limit** (integer) - Optional - Number of results to return ### Request Example ```java import com.slack.api.audit.response.LogsResponse; import com.slack.api.audit.Actions; LogsResponse response = audit.getLogs(req -> req .oldest(1521214343) .action(Actions.User.user_login) .limit(10) ); ``` ### Response #### Success Response (200) - **logs** (array) - A list of audit log entries. - **response_metadata** (object) - Metadata about the response, including pagination information. #### Response Example ```json { "logs": [ { "id": "a1b2c3d4e5f6", "date": 1678886400, "actor": { "type": "user", "id": "U12345678", "name": "testuser" }, "event": "user_login", "entity": { "type": "user", "id": "U12345678", "name": "testuser" }, "context": { "ip_address": "192.168.1.1", "user_agent": "Mozilla/5.0" } } ], "response_metadata": { "next_cursor": "dXNlcmlkOjE1MTE2NjQyNDk=" } } ``` ``` -------------------------------- ### Initialize Slack App for HTTP Mode Source: https://docs.slack.dev/tools/java-slack-sdk/guides/socket-mode Initialize an App instance and register listeners. Requires SLACK_BOT_TOKEN environment variable. ```java import com.slack.api.bolt.App; import com.slack.api.bolt.AppConfig; import com.slack.api.model.event.AppMentionEvent; // The bot token that starts with xoxb- is NOT the app-level token. // The token here is the one you got by installing the app into a workspace String botToken = System.getenv("SLACK_BOT_TOKEN"); AppConfig appConfig = AppConfig.builder().singleTeamBotToken(botToken).build(); // If you go with the default constructor, the App initialization requires an env variable named SLACK_BOT_TOKEN. App app = new App(appConfig); app.event(AppMentionEvent.class, (req, ctx) -> { ctx.say("Hi there!"); return ctx.ack(); }); ``` -------------------------------- ### Quarkus Hot Reload Output Source: https://docs.slack.dev/tools/java-slack-sdk/guides/supported-web-frameworks Example output during a hot reload in Quarkus development mode, indicating source file changes and recompilation. ```log 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:3000INFO [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 ```