Use Block Kit when integrating Amazon Lex bots with Slack

If youre incorporating your Amazon Lex chatbots with Slack, possibilities are youll encounter Block Kit. Block Kit is a UI framework for Slack apps. Like reaction cards, Block Kit can assist simplify interactions with your users. It offers flexibility to format your bot messages with blocks, buttons, check boxes, date pickers, time pickers, select menus, and more.
For instructions on integrating with Slack, see Integrating an Amazon Lex Bot with Slack. If you desire to utilize Block Kit and other Slack native parts, you require a custom endpoint for the demand URL.
This post explains an option architecture with a custom-made endpoint and demonstrates how to utilize Block Kit with your Amazon Lex bot. It also supplies an AWS Serverless Application Model (AWS SAM) template carrying out the architecture.
Solution overview
We also present an Amazon Simple Queue Service (Amazon SQS) line to invoke the Lambda function asynchronously. The rest of the architecture includes an Amazon Lex bot and another Lambda function used for recognition, initialization, and fulfillment.
The following diagram shows the service architecture.
Usage Slack Block Kit with an Amazon Lex bot to publish messages
You can utilize Block Kit to format messages you configured at develop time within the Lambda function connected with an intent. The following example utilizes blocks to display available flowers to users.
Each time you want to display a message with blocks, the following actions are required:

Construct the block. Block Kit Builder helps you visually format your messages.
Check whether the demand stemmed from Slack before you post the block. This enables you to deploy your bots on numerous platforms without major modifications.
Use the chat_postMessage operation from the Slack WebClient to post them in Slack. You can utilize the following operation to publish both text and obstructs to Slack:

Gather info for Secrets Manager.
To collect details for Secrets Manager, complete the following steps:.

helper.postInSlack (channel_id, blocks, blocks).

BOT_ALIAS– Your Amazon Lex bots alias name.

These steps deploy an AWS CloudFormation stack that introduces the following resources:.

On the Secrets Manager console, from the list of secrets, pick SLACK_LEX_BLOCK_KIT.

Go back to the Slack group where you installed your application.
In the navigation pane, in the Direct Messages section, pick your bot.

Your bot now prompts you with the blocks you set up, as displayed in the following example discussion.
Tidy up.
To prevent incurring future charges, erase the CloudFormation stack by means of the AWS CloudFormation console or the AWS Command Line Interface (AWS CLI):.

cd amazon-lex-slack-block-kit.
sam build.
sam deploy– directed.

SLACK_SIGNING_SECRET– The finalizing trick from Slack.

Validate that the gotten request is from Slack.
Forward the text worth associated to the occasion to Amazon Lex.
Post the Amazon Lex response to Slack.

You likewise require to erase the Amazon Lex bot resources that you created, the Amazon CloudWatch logs, and the Lambda layer that was developed by the stack.
In this post, we revealed how to use Block Kit to format Amazon Lex messages within Slack. We provided code examples to post blocks to Slack, listen to events from users interactions with the blocks aspects, and process those events.

Choose Save.

Post the Amazon Lex response to Slack.
Lastly, we publish the message from Amazon Lex to Slack:.

To illustrate those steps with the OrderFlowers bot, we reveal you how to use a date picker from Block Kit to re-prompt users for the pick-up date.

Update the Slack demand URL.
To upgrade the Slack request URL, finish the following actions:.

aws cloudformation delete-stack– stack-name amazon-lex-slack-block-kit.

On the Slack API console, under Settings, pick Basic Information.
Note down the worth for Signing Secret.
Under Features, choose OAuth & & Permissions.
Take down the value for Bot User OAuth Token.
On the Amazon Lex console, note the following:.

except SlackApiError as e:.
logger.error( f” Error publishing message: e “).

If the breached slot is PickupDate, you post the block you defined earlier to Slack. Then, you ask Amazon Lex to elicit the slot with the returned recognition message:.

def postInSlack( user_id, message, messageType= Plaintext, bot_token= slacksecret [ SLACK_BOT_TOKEN]:
# Call the chat.postMessage method using the WebClient
if (messageType == blocks):.
outcome = _ postMessage(.
channel= user_id, token= bot_token, obstructs= message.

postInSlack( user_id, action [ message].

Then, you customize the validation code hook as follows. This checks if the request stemmed from Slack utilizing the channel-type request characteristic.

Select Retrieve secret worth.

AWS Identity and Access Management (IAM) roles associated to the API and the Lambda functions.
A Lambda layer with slack_sdk, urllib3, and common operations utilized by the two Lambda functions.
A trick in Secrets Manager with the secret keys our code utilizes.

Release the required resources.
Update the Slack demand URL with the released API Gateway endpoint.
Gather info for Secrets Manager.
Occupy the secret worth.
Update the Lambda function for Amazon Lex satisfaction initialization and recognition.
Update the listener Lambda function.
Check the combination.

Participate in a conversation with your Slack application.

Beyond Slack, the user only receives the validation result message.
In Slack, the user gets both the pick-up date block and the recognition result message.
You can utilize this approach to enhance messages that you had set up at build time with Block Kit.
User interactions.
Now that you understand how to use blocks to post your bot messages, lets discuss how you handle users interactions with the blocks.
When a user communicates with an action block element, the following actions occur:.

Choose the plus icon (+) next to Direct Messages to search for it if you do not see your bot.

if validation_result [ violatedslot] == PickupDate:.
blocks = get_pickup_date_block().

If youre integrating your Amazon Lex chatbots with Slack, chances are youll come across Block Kit. For directions on integrating with Slack, see Integrating an Amazon Lex Bot with Slack. For Slacks suggestion on demand verification, see Verifying demands from Slack.
In this post, we showed how to utilize Block Kit to format Amazon Lex messages within Slack. We offered code examples to post blocks to Slack, listen to occasions from users interactions with the blocks elements, and procedure those events.

LEX_SLACK_CHANNEL_ID– The worth you tape-recorded from the callback URLs.

Your bots name.
Your bots alias.
The last part of the 2 callback URLs that Amazon Lex generated when you created your Slack channel (for example,

The following screenshot shows the action on Slack.
From the users perspectives, the experience is the following:.

Slack sends out an HTTP demand to API Gateway.
API Gateway forwards the request to Amazon SQS.
Amazon SQS gets the changed demand as a message, and conjures up the Lambda function that processes the request.

Integrate Amazon Lex and Slack with a custom-made request URL.
To develop the resources, complete the following actions:.

SLACK_BOT_TOKEN– The bot user OAuth token from Slack.

if intent_request [ requestAttributes] and x-amz-lex: channel-type in intent_request [ requestAttributes] and intent_request [ requestAttributes] [ x-amz-lex: channel-type] == Slack:.
blocks = [] userId] 2]

The bot re-prompts the user for the pick-up date with a date picker.
The user chooses a date.
The bot prompts the user for the pick-up time.

BOT_NAME– Your Amazon Lex bots name.

An API Gateway endpoint integrated with an SQS queue.
A Lambda function to listen to demands from Slack.
A Lambda function for Amazon Lex recognition, satisfaction, and initialization hooks.


Initially, you construct the block in the format Slack anticipates:.

About the Author.
Anne Martine Augustin is an Application Consultant for AWS Professional Services based in Houston, TX. She is passionate about assisting consumers designer and develop contemporary applications that accelerate their service results. In her spare time, Martine takes pleasure in costs time with loved ones, listening to audio books, and attempting brand-new foods.

In this section, we discuss each action in more detail.
Validate that the received demand is from Slack.
Use the signature module from slack_sdk to validate the requests. You can conserve and recover your signing secret from AWS Secrets Manager. For Slacks suggestion on demand verification, see Verifying requests from Slack.
Forward the text worth associated to the occasion to Amazon Lex.
If the request is from Slack, the Lambda function draws out the text worth associated with the action type. It forwards the user input to Amazon Lex. See the following code:.

For this walkthrough, you need the following:.

We use the Amazon Lex client post_text operation to forward the text to Amazon Lex. You can also recover the bot and keeps name, bots alias, and the channel ID from Secrets Manager. See the following code:.

actions = payload [” actions”] “id”]
action_type = actions [0] [” type”]
if action_type == “button”:.
forwardToLex = actions [0] [” value”]
elif action_type == datepicker:.
forward_to_Lex( team_id, user_id, forwardToLex).

Occupy the secret value.
To populate the secret value, complete the following actions:.

Update the Lambda satisfaction function and Lambda initialization and recognition for your Amazon Lex bot.
If youre utilizing the OrderFlowers bot, follow the instructions in Step 4: Add the Lambda Function as Code Hook (Console) to add the Lambda function amazon-lex-slack-block-kit-OrderFlowerFunction as code hooks for initialization, fulfillment, and validation.
Utilize the Lambda layer slack-lex-block that the stack produced if your runtime is Python version 3.6 and later on if youre not utilizing the OrderFlowers bot. The layer consists of an operation postInSlack to publish your blocks:.

The messages that use Block Kit are flawlessly integrated to the initial discussion circulation with the Amazon Lex bot.
In this part of the post, we stroll through the implementation and setup of the parts you require to utilize Block Kit. We discuss the following steps:.

The following diagram illustrates the interaction flow.
Lets take a better take a look at what happens at each action.
Slack sends an HTTP request to API Gateway.
When a user picks an action block component, Slack sends out an HTTP post with the event information to the endpoint set up as demand URL. The endpoint must respond to Slack with an HTTP 2xx response within 3 seconds. If not, Slack resends the exact same event. We decouple the intake and processing of occasions by utilizing an Amazon SQS line between API Gateway and the processing Lambda function. The line allows you to respond to occasions with HTTP 200, queue them, and asynchronously process them. This prevents unneeded retry occasions from flooding the custom endpoint.
API Gateway forwards the request to Amazon SQS.
When API Gateway gets an event from Slack, it uses a combination request-mapping design template to transform the demand to the format Amazon SQS is expecting. It forwards the request to Amazon SQS.
Amazon SQS gets and processes the changed request.
When Amazon SQS receives the message, it initiates the process Lambda function and returns the 200 HTTP action to API Gateway that, in turn, returns the HTTP action to Slack.
Process demands.
The Lambda function finishes the following steps:.

You can utilize Slack Block Kit Builder to build your blocks.
Update the listener Lambda function.
Relocation to the next step to check the integration if youre using the OrderFlowers bot.
If youre not using the OrderFlowers bot, update the Lambda function starting with amazon-lex-slack-block-kit-ListenFunction to process the actions your blocks utilized.
Evaluate the integration.
To check the combination, complete the following actions:.

result = _ postMessage(.
channel= user_id, token= bot_token, text= message.

helper.postInSlack (channel_id, blocks, blocks).

#Post event gotten from Slack to Lex and post Lex reply to #Slack.
def forward_to_Lex( team_id, user_id, forwardToLex):.
response = _ text(.
botName= slacksecret [ BOT_NAME],.
botAlias= slacksecret [ BOT_ALIAS],.
userId= slacksecret [ LEX_SLACK_CHANNEL_ID] +”:”+ team_id+ “:” + user_id,.
inputText= forwardToLex.

if source == DialogCodeHook:.
slots = helper.get _ slots( intent_request).
validation_result = validate_order_flowers( flower_type, date, pickup_time).
if not validation_result [ isValid]:.
= None.

Clone the repository

Choose Edit.
Change the secret worths as follows:.

Sign in to the Slack API console.
Pick the app you incorporated with Amazon Lex.
Update the Interactivity & & Shortcuts feature by changing the value for Request URL with the ListenSlackApi endpoint URL.
Choose Save Changes.

Build the application and run the assisted deploy command:.

If request from slack, #check.

git clone

def get_pickup_date_block():.
responseBlock = [

On the AWS CloudFormation console, navigate to the stack Outputs tab and copy the ListenSlackApi endpoint URL.

Leave a Reply

Your email address will not be published.