Slack/bolt api

Slack/bolt api DEFAULT

Getting Started with Bolt

Bolt for Java is a framework on the JVM that offers an abstraction layer to build Slack apps quickly using modern platform features.

This guide explains how to start your first-ever Bolt app.

  • Project Setup
  • Run Your Bolt App in 3 Minutes
    • Use bolt-jetty
    • Start the App with Two Env Variables
    • Enable Command
    • OK, What about Spring Boot?
  • Getting Started in Kotlin
  • Next Steps

If you’re not yet familiar with Slack app development in general, we recommend reading An introduction to Slack apps.


Project Setup

Let’s start building a Slack app using Bolt! This guide includes instructions on how to set up a Bolt project with Maven and Gradle, so use whichever section you’d like.

Maven

After you create your Maven project, you need to add the bolt dependency to your file. The bolt dependency is a framework-agnostic module. If you use Bolt along with Spring Boot, Quarkus (Undertow), and any others on top of Servlet environment, the bolt-servlet library is required for your app. Adding only bolt-servlet also works for you.

If you run the Bolt app on the Jetty HTTP server without any frameworks, you can simply go with bolt-jetty module.

Gradle

After you create your Gradle project, add the bolt dependencies to .


Run Your Bolt App in 3 Minutes

Use bolt-jetty

bolt-jetty is a handy way to start your Slack app server. It allows developers to build a Slack app backend service by writing only a main method initializes App and starts an HTTP server.

build.gradle

The following build settings should be working as-is. Put it in the root directory of your project.

src/main/java/hello/MyApp.java

Coding with this framework is much simpler than you think.

Only single source code is required to run your first-ever Bolt app. All you need to do is define the main method that starts SlackAppServer. Your server with the default configuration will listen to the 3000 port but it’s configurable. Check other constructors of the class to customize the behavior.

If you go with JDK 10+, thanks to Local Variable Type Inference, your code could be much more concise. To take advantage of it, install OpenJDK 11 and set the compatible Java versions in as below. Also, configure the same on your IDE.

Now, you don’t need to repeat the same type in a single line.

Start the App with Two Env Variables

The default constructor expects the following two env variables exist when starting the app.

Env VariableDescription
SLACK_BOT_TOKENThe valid bot token value starting with in your development workspace. To issue a bot token, you need to install your Slack App that has a bot user to your development workspace. Visit the Slack App configuration page, choose the app you’re working on, and go to Settings > Install App on the left pane (Add bot scope if you see the message saying “Please add at least one feature or permission scope to install your app.”).

If you run an app that is installable for multiple workspaces, no need to specify this. Consult App Distribution (OAuth) for further information instead.
SLACK_SIGNING_SECRETThe secret value shared only with the Slack Platform. It is used for verifying incoming requests from Slack. Request verification is crucial for security as Slack apps have internet-facing endpoints. To know the value, visit the Slack App configuration page, choose the app you’re working on, go to Settings > Basic Information on the left pane, and find App Credentials > Signing Secret on the page. Refer to the document for further information.

If you prefer configuring an App in a different way, write some code to initialize AppConfig on your own.

Anyway, set the two env variables and hit on your terminal. The command runs your main method. For more detailed logging, is also available.

You will see the message saying “⚡️ Bolt app is running!” in stdout.

If you get stuck this setup, go through the following checklist:

Enable Command

Your app is up now! However, the slash command in the code is still unavailable. To enable it, follow the steps below:

  • Set up some way to allow Slack API server to access your Bolt app
    • A well-known way is to use ngrok - install it and run on another terminal
  • Configure & Reinstall the Slack App
    • Visit Slack App configuration pages
    • Choose your app, go to Features > Slash Commands on the left pane
    • Click Create New Command button
    • Input the command information on the dialog:
      • Command:
      • Request URL: - if you use ngrok for development, the URL would be
      • Short Description: whatever you like
    • Click Save Button
    • Go to Settings > Install App and click Reinstall App button

Now you can hit the command in your development workspace. If your app is successfully running, the app should respond to the command by replying .

OK, What about Spring Boot?

As Spring Boot is one of the most popular web frameworks in the Java world, you may be curious about the possibility to let this Bolt live together with it.

Rest assured about it! It’s quick and easy to inject Bolt into Spring Boot apps.

All you need to do is add to in and write a few lines of code.

Check the detailed guide here for further information.


Getting Started in Kotlin

For code simplicity, Kotlin language would be a great option for writing Bolt apps. In this section, you’ll learn how to set up a Kotlin project for Bolt apps.

build.gradle

Most of the build settings are necessary for enabling Kotlin language. Adding bolt-jetty dependency is the only one that is specific to Bolt.

If you’re already familiar with Kotlin and prefer the Gradle Kotlin DSL, of course, there is nothing stopping you.

src/main/kotlin/MyApp.kt

Here is a minimum source file that just starts a Bolt app on your local machine.

Make Sure If It Works

OK, you should be done. Just in case, here is the checklist:

If all are ✅, bootstrapping your first-ever Kotlin-flavored Bolt app will succeed.

… Did you see the message saying “⚡️ Bolt app is running!” in stdout?

If yes, that’s all settled! 🎉

From here, all you need to do is write code and restart the app. Enjoy Bolt app development in Kotlin! 👋

Pro tip: We strongly recommend using IntelliJ IDEA here even if you don’t prefer using IDEs. The IDE is the smoothest way to try Kotlin application development.


Next Steps

Read the Bolt Basics for further information.

If you want to know ways to run Bolt app with Spring Boot, Micronaut, Quarkus, or Helidon SE, refer to Supported Web Frameworks.

Also, many examples are available in the GitHub repository.

Sours: https://slack.dev/java-slack-sdk/guides/getting-started-with-bolt

To make your Slack app ready for distribution, you will need to implement OAuth and store installation information (i.e. access tokens) securely. Bolt supports OAuth and will handle most of the work for you by setting up OAuth routes and verifying state.

You will need to provide your:

  • , , and
  • An option with and handlers defined for storing installation data to a database (recommended for production)

Installing your App

Bolt for JavaScript provides an Install Path out-of-the-box. This returns a simple button where users can initiate direct installs of your app.

If you need additional authorizations (user tokens) from users inside a team when your app is already installed, or have a reason to dynamically generate an install URL, manually instantiate an , assign the instance to a variable named , and then call . Read more about in the OAuth docs.

💡 Bolt for JavaScript does not support OAuth for custom receivers. If you’re implementing a custom receiver, you can use our Slack OAuth library, which is what Bolt for JavaScript uses under the hood.


Redirect URI

Bolt for JavaScript provides a Redirect URI Path out-of-the-box. Slack uses this to redirect users after they complete your app’s installation flow.

💡 You will need to add the full Redirect URI including your app domain in your app configuration settings under OAuth and Permissions, e.g. .

If you’d like to supply your own custom Redirect URI, you can do this by setting in the App options and . You must supply both, and the path must be consistent with the full URI.

Org-wide installation

To add support for org-wide installations, you will need Bolt for JavaScript version or newer. Make sure you have enabled org-wide installations in your app configuration settings under Org Level Apps.

Installing an org-wide app from admin pages requires additional configuration to work with Bolt. In that scenario, the recommended parameter is not supplied. Bolt will try to verify and stop the installation from progressing.

You may disable state verification in Bolt by setting the option to false. See the example setup below:

To learn more about the OAuth installation flow with Slack, read the API documentation.


Sours: https://slack.dev/bolt-js/concepts
  1. Daedalus wallet
  2. 5e wizard spells
  3. Red barrel studio
  4. My business bing
  5. Target rolling storage bins

Bolt Bolt logo for JavaScript

codecovNode.js CI

A JavaScript framework to build Slack apps in a flash with the latest platform features. Read the getting started guide to set-up and run your first Bolt app.

Read the documentation to explore the basic and advanced concepts of Bolt for JavaScript.

Setup

Initialization

Create an app by calling the constructor, which is a top-level export.

const{ App }=require('@slack/bolt');constapp=newApp({signingSecret: process.env.SLACK_SIGNING_SECRET,token: process.env.SLACK_BOT_TOKEN,});/* Add functionality here */(async()=>{// Start the appawaitapp.start(process.env.PORT||3000);console.log('⚡️ Bolt app is running!');})();

Listening for events

The Slack Request URL for a Bolt app must have the path set to .
For example: .
Otherwise, all incoming requests from Slack won't be handled.

Apps typically react to a collection of incoming events, which can correspond Events API events, actions, shortcuts, slash commands or options requests. For each type of request, there's a method to build a listener function.

// Listen for an event from the Events APIapp.event(eventType,fn);// Convenience method to listen to only `message` events using a string or RegExpapp.message([pattern,]fn);// Listen for an action from a Block Kit element (buttons, select menus, date pickers, etc)app.action(actionId,fn);// Listen for dialog submissionsapp.action({callback_id: callbackId},fn);// Listen for a global or message shortcutsapp.shortcut(callbackId,fn);// Listen for slash commandsapp.command(commandName,fn);// Listen for view_submission modal eventsapp.view(callbackId,fn);// Listen for options requests (from select menus with an external data source)app.options(actionId,fn);

Making things happen

Most of the app's functionality will be inside listener functions (the parameters above). These functions are called with a set of arguments.

ArgumentDescription
Contents of the incoming event. The payload structure depends on the listener. For example, for an Events API event, will be the event type structure. For a block action, it will be the action from within the array. The object is also accessible via the alias corresponding to the listener (, , , , , , or ). For example, if you were building a listener, you could use the and arguments interchangably. An easy way to understand what's in a payload is to log it, or use TypeScript.
Function to send a message to the channel associated with the incoming event. This argument is only available when the listener is triggered for events that contain a (the most common being events). accepts simple strings (for plain-text messages) and objects (for messages containing blocks). returns a promise that will resolve with a response.
Function that must be called to acknowledge that an incoming event was received by your app. exists for all actions, shortcuts, view, slash command and options requests. returns a promise that resolves when complete. Read more in Acknowledging events
Web API client that uses the token associated with that event. For single-workspace installations, the token is provided to the constructor. For multi-workspace installations, the token is returned by the function.
Function that responds to an incoming event if it contains a (shortcuts, actions, and slash commands). returns a promise that resolves with the results of responding using the .
Event context. This object contains data about the event and the app, such as the . Middleware can add additional context before the event is passed to listeners.
Object that contains the entire body of the request (superset of ). Some accessory data is only available outside of the payload (such as and ).

The arguments are grouped into properties of one object, so that it's easier to pick just the ones your listener needs (using object destructuring). Here is an example where the app sends a simple response, so there's no need for most of these arguments:

// Reverse all messages the app can hearapp.message(async({ message, say })=>{constreversedText=[...message.text].reverse().join("");awaitsay(reversedText);});

Calling the Web API

In addition to the property passed to listeners, each app has a top-level that can be used to call methods. Unlike the passed to listeners, the top-level client must be passed a . Read the documentation for more details.

Acknowledging events

Some types of events need to be acknowledged in order to ensure a consistent user experience inside the Slack client (web, mobile, and desktop apps). This includes all action, shortcut, view, command, and options requests. Listeners for these events need to call the function, which is passed in as an argument.

In general, the Slack platform expects an acknowledgement within 3 seconds, so listeners should call this function as soon as possible.

Depending on the type of incoming event a listener is meant for, should be called with a parameter:

  • Block actions, global shortcuts, and message shortcuts: Call with no parameters.

  • View submissions: Call with no parameters or with a response action.

  • Options requests: Call with an object containing the options for the user to see.

  • Legacy message button clicks, menu selections, and slash commands: Either call with no parameters, a to to update the message with a simple message, or an to replace it with a complex message. Replacing the message to remove the interactive elements is a best practice for any action that should only be performed once.

  • Events API events do not need an function since they are automatically acknowledged by your app.

Getting Help

The documentation has more information on basic and advanced concepts for Bolt for JavaScript.

If you otherwise get stuck, we're here to help. The following are the best ways to get assistance working through your issue:

  • Issue Tracker for questions, bug reports, feature requests, and general discussion related to Bolt for JavaScript. Try searching for an existing issue before creating a new one.
  • Email our developer support team:

Contributing

We welcome contributions from everyone! Please check out our Contributor's Guide for how to contribute in a helpful and collaborative way.

Sours: https://github.com/slackapi/bolt-js

Events API

The Events API is a streamlined, easy way to build apps and bots that respond to activities in Slack. All you need is a Slack app and a secure place for us to send your events.

Slack App Configuration

To enable Events API, visit the Slack App configuration page, choose the app you’re working on, and go to Features > Event Subscriptions on the left pane. There are a few things to do on the page.

  • Turn on Enable Events
  • Set the Request URL to (this step is not required for Socket Mode apps)
  • Add subscriptions to bot events
    • Click Subscribe to bot events
    • Click Add Bot User Event button
    • Choose events to subscribe
  • Click the Save Changes button at the bottom for sure

What Your Bolt App Does

All you need to do to handle Events API requests are:

  1. Verify requests from Slack
  2. Parse the request body and check if the in is the one you’d like to handle
  3. Whatever you want to do with the event data
  4. Respond to the Slack API server with 200 OK as an acknowledgment

Your app has to respond to the request within 3 seconds by method. Otherwise, the Slack Platform may retry after a while.


Examples

NOTE: If you’re a beginner to using Bolt for Slack App development, consult Getting Started with Bolt, first.

Bolt does many of the commonly required tasks for you. The steps you need to handle would be:

  • Specify the Java class corresponding to (and also when necessary) to handle
  • Whatever you want to do with the event data
  • Call as an acknowledgment

In event payloads, is not included as it’s not a payload coming from direct user interactions. Also, it’s not possible to post a message using for the same reason. If an event you receive is a user interaction and you’d like to post a reply to the user at the conversation the event happened, call chat.postMessage method or other similar ones with in the event payload.

The same code in Kotlin looks as below. (New to Kotlin? Getting Started in Kotlin may be helpful)

Here is another example. With an listener, you can receive only the events that contains given keyword or regular expressions, and do something with those event data in a fewer lines of code.

If matching an exact word in a text message works for you, the code looks much simpler as below.

Under the Hood

If you hope to understand what is actually happening with the above code, reading the following (a bit pseudo) code may be helpful.

Sours: https://slack.dev/java-slack-sdk/guides/events-api

Api slack/bolt

Bolt Basics

Bolt for Java is a framework on the JVM that offers an abstraction layer to build Slack apps quickly using modern platform features.

This guide covers all the basics of Bolt app development. If you’re not yet familiar with Slack app development in general, we recommend reading An introduction to Slack apps.


Start with the App class

The App class is a place to write only essential parts of your Slack app without being bothered by trifles.

The code configuring an App instance mainly consists of the ways to respond to incoming events from Slack such as user actions, command invocations, requests to load options in select menus, and any events you subscribe to in the Events API.


Dispatching Events

Here is the list of the available methods to dispatch events.

MethodConstraints (value: type)Description
app.eventevent type: Class<Event>Events API: Responds to any kinds of bot/user events you subscribe.
app.messagekeyword: String | PatternEvents API: Responds to messages posted by a user only when the text in messages matches the given keyword or regular expressions.
app.commandcommand name: String | PatternSlash Commands: Responds to slash command invocations in the workspace.
app.blockActionaction_id: String | PatternInteractive Components: Responds to user actions (e.g., click a button, choose an item from select menus, radio buttons, etc.) in blocks. These events can be triggered in all the surfaces (messages, modals, and Home tabs).
app.blockSuggestionaction_id: String | PatternInteractive Components: Responds to user actions to input a keyword (the length needs to be the or longer) in select menus (external data source).
app.viewSubmissioncallback_id: String | PatternModals: Responds to data submissions in modals.
app.viewClosedcallback_id: String | PatternModals: Responds to the events where users close modals by clicking Cancel buttons. The has to be when opening/pushing the modal.
app.globalShortcutcallback_id: String | PatternShortcuts: Responds to global shortcut invocations.
app.messageShortcutcallback_id: String | PatternShortcuts: Responds to shortcut invocations in message menus.
app.dialogSubmissioncallback_id: String | PatternDialogs: Responds to data submissions in dialogs.
app.dialogSuggestioncallback_id: String | PatternDialogs: Responds to requests to load options for typed select menus in dialogs.
app.dialogCancellationcallback_id String | PatternDialogs: Responds to the events where users close dialogs by clicking Cancel buttons.
app.attachmentActioncallback_id: String | PatternLegacy Messaging: Responds to user actions in attachments. These events can be triggered in only messages.

Development Guides by Feature

On these guide pages, you’ll find a more concrete example code for each.


Acknowledge Incoming Requests

Actions, commands, and options events must always be acknowledged using the method. All such utility methods are available as the instance methods of a Context object.

If your app replies to a user action, you can pass a message text to the method.

It’s also possible to use Block Kit to make messages more interactive.

By default, the reply will be sent as an ephemeral message. To send a message visible to everyone, use type.


Respond to User Actions

Are you already familiar with ? If not, we recommend reading this guide first.

As the guide says, some of the user interaction payloads may contain a . This is unique to each payload, and can be used to publish messages back to the place where the interaction happened.

Similarly to above, the Context object offers method for easily taking advantage of .


Use Web APIs / Reply using say utility

When you need to call some Slack Web APIs in Bolt apps, use for it. The MethodsClient created by the method already holds a valid bot token. So, you don’t need to give a token to it. Just calling a method with parameters as below works for you.

For chat.postMessage API calls with the given channel ID, using utility is much simpler. If your slash command needs to be available anywhere, using would be more robust as method does not work for the conversations where the app’s bot user is not a member of (e.g., a person’s own DM).

In the case to use a user token over a bot token, overwriting the token by giving a user token as an argument works.


Use Logger

You can access SLF4J logger in Context objects.

If you use the ch.qos.logback:logback-classic library as the implementation of the APIs, you can configure the settings by logback.xml etc.


Middleware

Bolt offers chaining middleware supports. You can customize App behavior by weaving a kind of filter to all events.

Here is an example demonstrating how it works. The middleware changes your app’s behavior in error patterns only when env variable exists.

The middleware transforms an unsuccessful response such as 404 Not Found to a 200 OK response with an ephemeral message that tells useful information for debugging.

Order of Execution in Middleware List

A set of the built-in middleware precedes your custom middleware. So, if the app detects something in built-in ones and stops calling , succeeding ones won’t be executed.

The most common would be the case where a request has been denied by RequestVerification middleware. After the denial, any middleware won’t be executed, so that the above middleware also doesn’t work for the case.

Customize the Built-in Middleware List

Bolt turns the following middleware on by default:

Although we generally do not recommend disabling these middleware as they are commonly necessary, you can disable them using the flags like in objects.

Make sure if it’s safe enough when you turn a built-in middleware off. We strongly recommend using for better security. If you have a proxy that verifies request signature in front of the Bolt app, it’s totally fine to disable to avoid duplication of work. Don’t turn it off just for easiness of development.


Supported Web Frameworks

Refer to this page for more details.


Deployments

We’re planning to have some guide documents for deployments.

Sours: https://slack.dev/java-slack-sdk/guides/bolt-basics
Python Slack Bot Tutorial #2 - Handling Events (Events API)

Getting started with Bolt for JavaScript

This guide is meant to walk you through getting up and running with a Slack app using Bolt for JavaScript. Along the way, we’ll create a new Slack app, set up your local environment, and develop an app that listens and responds to messages from a Slack workspace.

When you’re finished, you’ll have this ⚡️Getting Started app to run, modify, and make your own.


Create an app

First thing’s first: before you start developing with Bolt, you’ll want to create a Slack app.

💡 We recommend using a workspace where you won’t disrupt real work getting done — you can create a new one for free.

After you fill out an app name (you can change it later) and pick a workspace to install it to, hit the button and you’ll land on your app’s Basic Information page.

This page contains an overview of your app in addition to important credentials you’ll need later, like the under the App Credentials header.

Basic Information page

Look around, add an app icon and description, and then let’s start configuring your app. 🔩


Tokens and installing apps

Slack apps use OAuth to manage access to Slack’s APIs. When an app is installed, you’ll receive a token that the app can use to call API methods.

There are three main token types available to a Slack app: user (), bot (), and app () tokens.

  • User tokens allow you to call API methods on behalf of users after they install or authenticate the app. There may be several user tokens for a single workspace.
  • Bot tokens are associated with bot users, and are only granted once in a workspace where someone installs the app. The bot token your app uses will be the same no matter which user performed the installation. Bot tokens are the token type that most apps use.
  • App-level tokens represent your app across organizations, including installations by all individual users on all workspaces in a given organization and are commonly used for creating websocket connections to your app.

We’re going to use bot and app tokens for this guide.

  1. Navigate to the OAuth & Permissions on the left sidebar and scroll down to the Bot Token Scopes section. Click Add an OAuth Scope.

  2. For now, we’ll just add one scope: . This grants your app the permission to post messages in channels it’s a member of.

  3. Scroll up to the top of the OAuth & Permissions page and click Install App to Workspace. You’ll be led through Slack’s OAuth UI, where you should allow your app to be installed to your development workspace.

  4. Once you authorize the installation, you’ll land on the OAuth & Permissions page and see a Bot User OAuth Access Token.

OAuth Tokens

💡 Treat your token like a password and keep it safe. Your app uses it to post and retrieve information from Slack workspaces.


Setting up your project

With the initial configuration handled, it’s time to set up a new Bolt project. This is where you’ll write the code that handles the logic for your app.

If you don’t already have a project, let’s create a new one. Create an empty directory and initialize a new project:

You’ll be prompted with a series of questions to describe your new project (you can accept the defaults by hitting on each prompt if you aren’t picky). After you’re done, you’ll have a new file in your directory.

Before we install the Bolt for JavaScript package to your new project, let’s save the bot token and Signing Secret that were generated when you configured your app.

  1. Copy your Signing Secret from the Basic Information page and then store it in a new environment variable. The following example works on Linux and macOS; but similar commands are available on Windows.
  2. Copy your bot (xoxb) token from the OAuth & Permissions page and store it in another environment variable.

🔒 Remember to keep your tokens and signing secret secure. At a minimum, you should avoid checking them into public version control, and access them via environment variables as we’ve done above. Checkout the API documentation for more on best practices for app security.

Now, let’s create your app. Install the package and save it to your dependencies using the following command:

Create a new entrypoint file called in this directory and add the following code:

Save your file, then on the command line run the following:

Your app should let you know that it’s up and running. 🎉


Setting up events

Your app behaves similarly to people on your team — it can post messages, add emoji reactions, and listen and respond to events.

To listen for events happening in a Slack workspace (like when a message is posted or when a reaction is posted to a message) you’ll use the Events API to subscribe to event types. For this guide, we are going to be using Socket Mode, our recommended option for those just getting started and building something for their team.

💡 Socket Mode lets apps use the Events API and interactive components without exposing a public HTTP endpoint. This can be helpful during development, or if you’re receiving requests from behind a firewall. HTTP is more useful for apps being deployed to hosting environments (like AWS or Heroku), or apps intended for distribution via the Slack App Directory. To continue this setting up guide with HTTP, head over here.

Okay, let’s enable Socket Mode:

  1. Head to your app’s configuration page (click on the app from your app management page). Navigate to Socket Mode on the left side menu and toggle to enable.

  2. Go to Basic Information and scroll down under the App Token section and click Generate Token and Scopes to generate an app token. Add the scope to this token and save the generated token, we’ll use that in just a moment.

Finally, it’s time to tell Slack what events we’d like to listen for. Under Event Subscriptions, toggle the switch labeled Enable Events.

When an event occurs, Slack will send your app information about the event, like the user that triggered it and the channel it occurred in. Your app will process the details and can respond accordingly.

Scroll down to Subscribe to Bot Events. There are four events related to messages:

  • listens for messages in public channels that your app is added to
  • listens for messages in 🔒 private channels that your app is added to
  • listens for messages in your app’s DMs with users
  • listens for messages in multi-person DMs that your app is added to

If you want your bot to listen to messages from everywhere it is added to, choose all four message events. After you’ve selected the events you want your bot to listen to, click the green Save Changes button.

Back in your project, make sure to store the token you saved earlier in your environment.

Make a simple change to your Bolt initialization code and restart the app.


Listening and responding to a message

Your app is now ready for some logic. Let’s start by using the method to attach a listener for messages.

The following example listens and responds to all messages in channels/DMs where your app has been added that contain the word “hello”:

If you restart your app, so long as your bot user has been added to the channel/DM, when you send any message that contains “hello”, it will respond.

This is a basic example, but it gives you a place to start customizing your app based on your own goals. Let’s try something a little more interactive by sending a button rather than plain text.


Sending and responding to actions

To use features like buttons, select menus, datepickers, modals, and shortcuts, you’ll need to enable interactivity. Head over to Interactivity & Shortcuts in your app configuration.

💡 You’ll notice that with Socket Mode on, basic interactivity is enabled for us by default, so no further action here is needed. If you’re using HTTP, you’ll need to supply a Request URL for Slack to send events to.

When interactivity is enabled, interactions with shortcuts, modals, or interactive components (such as buttons, select menus, and datepickers) will be sent to your app as events.

Now, let’s go back to your app’s code and add logic to handle those events:

  • First, we’ll send a message that contains an interactive component (in this case a button).
  • Next, we’ll listen for the action of a user clicking the button before responding

Below, the code from the last section is modified to send a message containing a button rather than just a string:

The value inside of is now an object that contains an array of . Blocks are the building components of a Slack message and can range from text to images to datepickers. In this case, your app will respond with a section block that includes a button as an accessory. Since we’re using , the is a fallback for notifications and accessibility.

You’ll notice in the button object, there is an . This will act as a unique identifier for the button so your app can specify what action it wants to respond to.

💡 The Block Kit Builder is a simple way to prototype your interactive messages. The builder lets you (or anyone on your team) mockup messages and generates the corresponding JSON that you can paste directly in your app.

Now, if you restart your app and say “hello” in a channel your app is in, you’ll see a message with a button. But if you click the button, nothing happens (yet!).

Let’s add a handler to send a followup message when someone clicks the button:

You can see that we used to listen for the that we named . If you restart your app and click the button, you’ll see a new message from your app that says you clicked the button.


Next steps

You just built your first Bolt for JavaScript app with Socket Mode! 🎉

Now that you have a basic app up and running, you can start exploring how to make your Bolt app stand out. Here are some ideas about what to explore next:

  • Read through the Basic concepts to learn about the different methods and features your Bolt app has access to.

  • Explore the different events your bot can listen to with the method. All of the events are listed on the API site.

  • Bolt allows you to call Web API methods with the client attached to your app. There are over 220 methods on our API site.

  • Learn more about the different token types on our API site. Your app may need different tokens depending on the actions you want it to perform. For apps that do not use Socket Mode, typically only a bot () token is required. For example of this, see Getting Started with HTTP.

Sours: https://slack.dev/bolt-js/tutorial/getting-started

You will also like:

Getting Started with Bolt (Socket Mode)

Bolt for Java is a framework on the JVM that offers an abstraction layer to build Slack apps quickly using modern platform features.

This guide explains how to start your first-ever Bolt app.

  • Project Setup
  • Run Your Bolt App in 3 Minutes
    • Use bolt-socket-mode
    • Start the App with Two Env Variables
    • Enable Command
  • Getting Started in Kotlin
  • Next Steps

If you’re not yet familiar with Slack app development in general, we recommend reading An introduction to Slack apps.


Project Setup

Let’s start building a Slack app using Bolt! This guide includes instructions on how to set up a Bolt project with Maven and Gradle, so use whichever section you’d like.

Maven

After you create your Maven project, you need to add the bolt dependency to your file. The bolt dependency is a framework-agnostic module. To enable Socket Mode, the bolt-socket-mode library and its provided-scope dependencies are also required for your app.

If you use Java-WebSocket library, add the artifact instead of tyrus-standalone-client.

Gradle

After you create your Gradle project, add the bolt dependencies to .


Run Your Bolt App in 3 Minutes

Use bolt-socket-mode

bolt-socket-mode is a handy way to start your Socket Mode app. It allows developers to build a Slack app backend service by writing only a main method initializes App and establishes a WebSocket connection to the Socket Mode servers.

build.gradle

The following build settings should be working as-is. Put it in the root directory of your project.

src/main/java/hello/MyApp.java

Coding with this framework is much simpler than you think.

Only single source code is required to run your first-ever Bolt app. All you need to do is define the main method that starts SocketModeApp.

If you go with JDK 10+, thanks to Local Variable Type Inference, your code could be much more concise. To take advantage of it, install OpenJDK 11 and set the compatible Java versions in as below. Also, configure the same on your IDE.

Now, you don’t need to repeat the same type in a single line.

Start the App with Two Env Variables

The default constructor expects the following two env variables exist when starting the app.

Env VariableDescription
SLACK_BOT_TOKENThe valid bot token value starting with in your development workspace. To issue a bot token, you need to install your Slack App that has a bot user to your development workspace. Visit the Slack App configuration page, choose the app you’re working on, and go to Settings > Install App on the left pane (Add bot scope if you see the message saying “Please add at least one feature or permission scope to install your app.”).

If you run an app that is installable for multiple workspaces, no need to specify this. Consult App Distribution (OAuth) for further information instead.
SLACK_APP_TOKENThe valid app-level token value starting with for your Slack app. To issue an app-level token, Visit the Slack App configuration page, choose the app you’re working on, and go to Settings > Basic Information > App-Level Tokens, and then create a new one with scope.

If you prefer configuring an App in a different way, write some code to initialize AppConfig on your own.

Anyway, set the two env variables and hit on your terminal. The command runs your main method. For more detailed logging, is also available.

You will see the message saying “⚡️ Bolt app is running!” in stdout.

If you get stuck this setup, go through the following checklist:

  • ✅ JDK 8 or higher installed (if not, run for macOS / visit OpenJDK website for others)
  • ✅ Gradle installed (if not, run for macOS / visit their website for others)
  • ✅ has bolt-socket-mode and tyrus-standalone-client in the dependencies and valid application plugin settings
  • ✅ with a class having its main method
  • ✅ Create a Slack App, add bot scope, add an app-level token with scope, and install the app to your development workspace
  • ✅ Copy Bot User OAuth Access Token and App-Level Token from your Slack App admin pages and set them to env variables

Enable Command

Your app is up now! However, the slash command in the code is still unavailable. To enable it, follow the steps below:

  • Visit Slack App configuration pages
  • Choose your app
  • Go to Settings > Socket Mode on the left pane
    • Turn on Enable Socket Mode
  • Go to Features > Slash Commands on the left pane
    • Click Create New Command button
    • Input the command information on the dialog:
      • Command:
      • Short Description: whatever you like
    • Click Save Button

Now you can hit the command in your development workspace. If your app is successfully running, the app should respond to the command by replying .


Getting Started in Kotlin

For code simplicity, Kotlin language would be a great option for writing Bolt apps. In this section, you’ll learn how to set up a Kotlin project for Bolt apps.

build.gradle

Most of the build settings are necessary for enabling Kotlin language. Adding bolt-socket-mode && tyrus-standalone-client to the dependencies is the only one that is specific to Bolt.

If you’re already familiar with Kotlin and prefer the Gradle Kotlin DSL, of course, there is nothing stopping you.

src/main/kotlin/MyApp.kt

Here is a minimum source file that just starts a Bolt app on your local machine.

Make Sure If It Works

OK, you should be done. Just in case, here is the checklist:

  • ✅ JDK 8 or higher installed (if not, run for macOS / visit OpenJDK website for others)
  • ✅ Gradle installed (if not, run for macOS / visit their website for others)
  • ✅ with valid Kotlin language settings and bolt-socket-mode and tyrus-standalone-client in the dependencies
  • ✅ with a main method
  • ✅ Create a Slack App, add bot scope, add an app-level token with scope, and install the app to your development workspace
  • ✅ Copy Bot User OAuth Access Token and App-Level Token from your Slack App admin pages and set them to env variables

If all are ✅, bootstrapping your first-ever Kotlin-flavored Bolt app will succeed.

… Did you see the message saying “⚡️ Bolt app is running!” in stdout?

If yes, that’s all settled! 🎉

From here, all you need to do is write code and restart the app. Enjoy Bolt app development in Kotlin! 👋

Pro tip: We strongly recommend using IntelliJ IDEA here even if you don’t prefer using IDEs. The IDE is the smoothest way to try Kotlin application development.


Next Steps

Read the Bolt Basics for further information.

Sours: https://slack.dev/java-slack-sdk/guides/getting-started-with-bolt-socket-mode


43504 43505 43506 43507 43508