Start tracking your progress
Trailhead Home
Trailhead Home

Integrate with Your Database

Mock the Database

Start by creating your mock database.

  1. In your text editor, create a New File.
  2. Enter {} in the first line.
  3. Click File in the menu, then Save As, and save this as database.json.

Boom! You’ve just created a database. Let’s use it.

Use the Database

  1. Back in index.js, go to the line // Initialize http near the top of your code (line 2). Press enter to create a new line after it.
  2. In the new line, enter const fs = require('fs'). This line enables your bot to read from and write to your database file.
  3. Now you’re going to rewrite the code that listens for when a user joins one more time (the code under the comment // Attach listeners to events by Slack Event “type”). Let's give it even more power! Replace the block (46-54) with the following.
slackEvents.on('team_join', (event) => {
  // post message
  console.log(`Received a team_join event: user ${event.user.name} has joined.`);
  slackWeb.chat.postMessage({
    channel: event.user.id,
    text: message.text,
    attachments: message.attachments
  }).then((res) => {
    console.log(`Message sent: ${res.ts}`);
    // store the user's data
    fs.readFile('database.json', (err, data) => {
      if (err) throw err;
      // read the data into your program to be read
      let usersSent = JSON.parse(data);
      // build the object for a specific user to save
      usersSent[event.user.id] = {
          'time_sent': res.message.ts,
          'accepted': false,
          'time_accepted': ''
        };
        // And finally, string up the data, write it back to file!
        let stringifiedUsersSent = JSON.stringify(usersSent);
        fs.writeFile('database.json', stringifiedUsersSent, () => {
          if (err) throw err;
        console.log(`data saved for user ${event.user.id}`);
      });
    });
  }).catch(console.error);
});
  1. Save your code.

You’ve now given the app the ability to store the data about when the message is first sent to a user. This tags each user with both the time they received the message and if they’ve accepted the code of conduct. The additional field, time_accepted, does exactly what it sounds like—it tracks when a user accepts the code of conduct.

Note

Note

For reference, here’s the structure of the database you just set up:

user ID:

time sent,

accepted,

time accepted

Almost There

Guess what, you’re almost done!

So far, you’ve built a Slack App that listens for when new users join, then sends them a message and tracks when they’ve received those messages! 

As of right now, though, the button in your message doesn’t do anything. In the final step, you give this button life by allowing it to update your database. You also give the message the ability to update the user with a confirmation once users click it.

We won't check any of your setup. Click Verify Step to go to the next step in the project.

retargeting