Start tracking your progress
Trailhead Home
Trailhead Home

Add Interactivity

Right now, you have a functioning bot that sends a new user a message with a button to accept a code of conduct. That button does not do anything. Let’s change that.

Use the Interactive Message Framework on api.slack.com

Time to go on your API page and enable it to work with an interactive component.

  1. Go back to your Slack App’s page at  https://api.slack.com/apps.
  2. Click Interactive Components on the left navigation menu.
  3. Click the switch to set it to on. A box should appear that accepts a URL.
  4. Enter your ngrok URL. If you need to retrieve it again, follow these steps:
    • In your terminal, open a new tab and start ngrok on your port by entering ./ngrok http 3000
    • What should pop up in this tab, among other session information, is a Secure Forwarding URL that looks something like https://0000aaaa.ngrok.io
    • Copy your Forwarding URL
  5. Add /slack/button to the end of the URL.
  6. Finally, click the Save Changes button at the bottom of the screen.
Note

Note

Let’s say you stepped away from this project and have to restart your terminal and ngrok in particular. That’s okay! Just know whenever a new ngrok http 3000 command is entered in Terminal or Command Line, you get a new Forwarding URL. Make sure to use that new URL to update both the Events Subscription Request URL and the Interactive Components Request URL in api.slack.com so that everything matches.

And that’s it! It’s simple to enable interactivity on a Slack App.

Now let’s get to actually building the code for it!

Meaningful Feedback

Let’s go back to index.js in your text editor. It’s time to write the code so the bot responds when a user clicks a button. The bot will update the message in Slack and commit data to your database.

  1. In index.js, find your JSON message (the block of code that starts with const message = {) and create a new line after it. It should be around line 30 after the };.
  2. Copy and paste in the following code.
const updatedCodeOfConduct = {
  "title": "Code of Conduct",
  "text": " Here at this company, we treat each other with respect and empathy.\n :white_check_mark: Thank you for accepting!",
  "callback_id": "accept_terms",
  "color": "#3f1daf"
};

This block of code represents the feedback that shows after the user clicks the accept terms button. We’re going to use the Slack Web API’s chat.update method to ensure the best user experience by enabling the bot to give immediate feedback.

In order to do this, we update the attachment originally containing a button with an attachment that contains a white check mark emoji. And this is the code for that attachment.

The Welcome Trailhead bot in action posting the welcome message along with the new white check mark emoji.

Talk to the Server

Let’s update the code again.

  1. Below the listener block that starts with the comment // Attach listeners to events by Slack Event “type” , add a new line (should be after the }); on line 80).
  2. Then copy and paste the following in that new line.
app.post('/slack/button', bodyParser.urlencoded({ extended: true }), (req, res) => {
  const sendData = JSON.parse(req.body.payload);
  const user = sendData.user.id;
  const timeAccepted = sendData.action_ts;
});

This code tells Slack to send your server data on the user and the timestamp of when they accept the code by clicking the button. 

Write to the Database

  1. Add one more line after const timeAccepted = sendData.action_ts; (line 84)
  2. Copy and paste the following code in the new space you’ve created.
fs.readFile('database.json', (err, data) => {
  if (err) throw err;
  let acceptDatabase = JSON.parse(data);
  acceptDatabase[user].accepted = true;
  acceptDatabase[user].time_accepted = timeAccepted;
  let stringifiedAcceptDatabase = JSON.stringify(acceptDatabase);
  fs.writeFile('database.json', stringifiedAcceptDatabase, (err) => {
    if (err) throw err;
    res.sendStatus(200);
    console.log(`${user} has accepted the code of conduct.`);
  });
});
  1. Save your code.

This last bit of code enables the database to store the information. 

Update the Message

The very last thing to do after we’ve stored user data is to offer a confirmation message.

In this case, we use Slack’s Web API to update the message.

Note

Note

When formatting messages, it is important to be as clear as possible, and this is doubly important when it comes to interactivity—give users visual confirmation when they’ve done something important so they know they’ve completed their task.

Let’s make the code complete:

  1. Create a new line after console.log(`${user} has accepted the code of conduct`); (line 94)
  2. Copy and paste the following block of code.
// update
slackWeb.chat.update({
  channel: sendData.channel.id,
  ts: sendData.message_ts,
  attachments: [sendData.original_message.attachments[0], updatedCodeOfConduct]
}).then(() => {
  console.log(`Message updated! ${timeAccepted}`);
}).catch(console.error);
  1. Save your code.

Here, you’re using the Web API’s chat.update method, which is for updating a message. It requires three parameters.

  • channel: the channel the message is in.
  • ts: the time stamp of the message you’re trying to update.
  • attachments: new attachments you want to affix to your message, in place of the old ones.

Test Your Bot

Try out your code!

  1. Go back to your terminal, and type node index.js
  2. Then, go to your Slack workspace.
  3. Invite yourself with a different email or someone else.
  4. Once the new user signs in, they’ll see that your bot messaged the code of conduct in a new direct message.
  5. Hit the accept button and watch it update!

That’s It!

You’ve finished creating your very first Slack App! You learned how to apply both the Slack Web and the Events APIs, and you worked a lot with the Slack API website to make your bot work.

Now, go forth, and create more Slack Apps to help you on your adventure for more productive, collaborative work!

We won't check any of your setup. Click Verify Step to earn your badge.

retargeting