Step 7: Responding to Slash Commands

Step 7: Responding to Slash Commands

Next we’ll set up our server to respond to the Slash command, here’s how Slack describes the process in their documentation:

When a slash command is invoked, Slack sends an HTTP POST to the Request URL you specified above. This request contains a data payload describing the source command and who invoked it, like a really detailed knock at the door.

We are going to have our server send back an immediate response the process is detailed here

1. Update index.js

Add the following code to the bottom of index.js

app.post('/test', async (req, res) => {
  try {
    console.log(req)
    const data = {
      'response_type': 'in_channel',
      'text': 'Testing testing 123!'
    }

    res.json(data)
  } catch (e) {
    console.log(e)
  }
})
  • Here’s a summary of the newly added code

    • We are using the API of Express to create a route with the path /test, this is the same route that matches url we entered during the creation of the Slash command on Step 5

    • We are also leveraging a feature of Express that allows us to use the async/await syntax (and the try..catch syntax for error handling) to handle asynchronous calls

    • When we create a route in Express, we get access to a callback that provides us with two parameters (request and response)

      • The request object will contain information about the request that was sent to our server

      • The response object allows us to send back a response to the sender

    • We are constructing a json object (according to Slack’s API documentation) that will allow send a response back with data to Slack

    • We are using the .json() method available on the response object to send back a json response to Slack

2. Restart your Express server

  • Any time we make changes to our server code, we will need to restart the server before those new changes can be applied

  • Navigate to the tab in your command line application that houses the running node server

  • On your keyboard press Ctrl-C to shut down the server

  • Then press the up arrow to access your previous command (which should be node index.js) and press enter to restart the server