Navigation
  • Tutorials >
  • Slack Service Tutorial: Using Slack in a Stitch Web App

Slack Service Tutorial: Using Slack in a Stitch Web App

Overview

This tutorial provides step-by-step instructions for creating a simple MongoDB Stitch app that allows you to send a message to a Slack channel using a web form.

Slack is a communications platform you can use to send messages and files to other members of your team. To complete this tutorial, you’ll need:

  • a Slack account and Team ID
  • a MongoDB Stitch app with the Slack service enabled

An app which receives data from Slack will also need a Stitch Incoming Webhook. The app in this tutorial only sends data to Slack, so a Stitch Incoming Webhook isn’t required.

Slack Setup

Estimated Time to Complete: ~3 minutes

Use the following procedure to get started with Slack:

  1. Visit Slack and either create a new account or log in with your existing credentials.

  2. Open the navigation dropdown in the top left corner of the Slack app and open Apps & Integrations

  3. Find Incoming WebHooks by searching the App Directory.

  4. Click the Add Configuration button.

    Note

    If you are using a Slack account of which you are not the owner, you’ll need to request permission from the account owner to add an incoming webhook.

  5. Choose a Slack channel for your app to send messages to, or create a new channel.

  6. Click the Add Incoming WebHooks integration button.

  7. Copy the Webhook URL for use with a Slack Service in your Stitch app.

Stitch App Setup

Estimated Time to Complete: ~5 minutes

  1. If you haven’t yet created a MongoDB Stitch app, see Stitch app setup.

  2. Click Authentication in the left-side nav and enable anonymous authentication.

  3. Click Add Service in the navigation pane.

  4. Select Slack.

  5. Enter a name for the service in the Service Name box.

  6. Click Add service.

  7. Use your Webhook URL to provide the Slack Config information:

    • Team ID. Your team ID can be found in your Webhook URL, which is in the format https://hooks.slack.com/services/<TEAM ID>/...
    • Incoming Webhook URL. Enter your URL just as you copied it from the Slack configuration page.
  8. Click the Rules tab.

  9. Click ADD RULE.

  10. Click post in the ACTIONS column.

  11. Fill in the document in the WHEN box with any restrictions you would like to place on your Slack service. For example, to ensure that only the username george can post messages to Slack, enter the following document:

    {
      "username": "george"
    }
    
  12. Click the SAVE button in the lower right corner.

Create an HTML Form

Estimated Time to Complete: ~3 minutes

In this app, messages are sent to Slack by entering them into a web form. The form needs fields for channel, username, and message. When the form is submitted, app.js will pass the inputs to a Stitch pipeline.

Create a file called index.html and add the following code:

index.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!doctype html>
<html>
    <head>
        <title>Slack Post via Stitch</title>
        <meta charset="utf-8">
        <script src="https://s3.amazonaws.com/stitch-sdks/js/library/master/stitch.min.js">
        </script>
        <script defer type="text/javascript" src="app.js"></script>
        <style>
            body {
                font-family: "Helvetica";
                margin-top: 50px;
                margin-left: 50px;
            }
        </style>
    </head>
    <body>
        <h2>Slack Post via Stitch</h2>
        <table>
          <tr>
            <td>Channel:</td>
            <td><input id="channel" type="text" size="30" maxlength="40"> </input></td>
          </tr>
          <tr>
            <td>Username:</td>
            <td><input id="username" type="text" size="30" maxlength="50"> </input></td>
          </tr>
          <tr>
            <td>Message:</td>
            <td><textarea id="message" rows="4" cols="40" maxlength="50"> </textarea></td>
          </tr>
          <tr>
            <td></td>
            <td><button id="sendButton">Send Message</button></td>
          </tr>
        </table>
        <div>
            <p id="jsonResponse"></p>
        </div>
    </body>
</html>

Create a JavaScript File

Estimated Time to Complete: ~3 minutes

After the form is submitted, the inputs need to be passed to your Stitch app using the Stitch JavaScript API.

The code creates a StitchClient object and anonymously authenticates to Stitch. Once authenticated, the StitchClient executes a pipeline containing a Slack Service stage. The stage invokes the post action and takes the values entered in the web form as arguments. If the arguments satisfy the service rules specified during the Stitch App Setup step, the message is posted to the specified channel under the given username.

Note

This app uses anonymous authentication for simplicity’s sake, but any real-world app which involves Slack message posting should use MongoDB Stitch‘s security features. Learn more about authentication.

To connect the web form to Stitch, do the following:

  1. Create a file called app.js in the same location as index.html. Copy and paste the code below into app.js.
  2. Visit the Clients section of the Stitch Admin Console to locate your app’s Application ID. Replace STITCH-APP-ID with your Application ID in app.js.
  3. If you named your Slack service something other than slk1, replace slk1 with your service’s name in app.js.
  4. Test the app by opening index.html in a web browser and filling out the form. When you press Send Message the app should post to the specified Slack channel.
app.js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
document.addEventListener('DOMContentLoaded', () => {

    'use strict'

    // Replace STITCH-APP-ID with your Application ID
    const stitchClient = new stitch.StitchClient("STITCH-APP-ID");
    const sendButton = document.getElementById('sendButton');

    // allow anonymous user access for this app
    function doAnonymousAuth() {
      stitchClient.login()
        .then( result => {
          console.log("authenticated");
        }).catch( err => {
          console.error("Error performing auth", err)
        });
    }

    // execute pipeline when Send button is clicked
    sendButton.onclick = () => {

      const channel = document.getElementById("channel").value;
      const username = document.getElementById("username").value;
      const message = document.getElementById("message").value;

      // check to make sure our fields are populated
      if (channel != "" && username != "" && message != "") {

        stitchClient.executePipeline([
          {
            // Replace "slk1" with the name of your Slack service
            service: "slk1",
            action: "post",
            args: {
              "channel": channel,
              "username": username,
              "text": message
            }
          }
        ]).then (function (result) {
          if (result) {
            // show a message for successful execution
            let response = document.getElementById('jsonResponse')
            response.innerText = "Message successfully sent to channel " + channel;
          }
        }).catch( err => {
          /* possible errors:
             invalid Slack service configuration,
             username not approved in the service rules */
          let response = document.getElementById('jsonResponse')
          response.innerText = "Message could not be sent. " + err;
        });

      } else {
        // A field is missing, show an error
        let response = document.getElementById('jsonResponse')
        response.innerText = "Please fill in all the fields.";
      }
    }

    doAnonymousAuth()

});