Go to Slack

Handling events from the Events API using AWS Lambda

By John Agan

Introduction

This is a demonstration of Slack's Event API using AWS Lambda to receive events and respond to specific messages. This demo looks for the words aws and lambda in a message. If found, it will respond by mentioning the sender and giving Lambda praises.

Prerequisites

Demonstration

How it works

Lambda Function

const https = require('https'),
      qs = require('querystring'),
      VERIFICATION_TOKEN = "[APP VERIFICATION TOKEN]",
      ACCESS_TOKEN = "[SLACK ACCESS TOKEN]";

// Verify Url - https://api.slack.com/events/url_verification
function verify(data, callback) {
    if (data.token === VERIFICATION_TOKEN) callback(null, data.challenge);
    else callback("verification failed");   
}

// Post message to Slack - https://api.slack.com/methods/chat.postMessage
function process(event, callback) {
    // test the message for a match and not a bot
    if (!event.bot_id && /(aws|lambda)/ig.test(event.text)) {
        var text = `<@${event.user}> isn't AWS Lambda awesome?`;
        var message = { 
            token: ACCESS_TOKEN,
            channel: event.channel,
            text: text
        };

        var query = qs.stringify(message); // prepare the querystring
        https.get(`https://slack.com/api/chat.postMessage?${query}`);
    }

    callback(null);
}

// Lambda handler
exports.handler = (data, context, callback) => {
    switch (data.type) {
        case "url_verification": verify(data, callback); break;
        case "event_callback": process(data.event, callback); break;
        default: callback(null);
    }
};

Readying your app for the Events API

Navigate to your Slack Apps and select the App you would like to use for subscriptions. If you don't have an App already, you can follow this guide to set one up.

1. Enable Events

Events setup

2. Add Your AWS Lambda URL

This is the URL that will trigger the Lambda event. If you haven't set this up yet, follow the AWS Lambda guide first.

Lambda URL

3. Select The Events

For this tutorial, we're only listening for the message.channels event.

Selecting events

4. All Systems Go!

If everything goes well, we're done on the Slack side. Now we need to setup Lambda to handle these events.

Make it go

Configuring your Lambda Function

Copy/paste the Lambda Function (provided above) into the Lambda function you created. Replace the following variables in the code with real data:

  • [APP VERIFICATION TOKEN] - Replace with the Verification Token found at the bottom of your Slack App's OAuth & Permission Page https://api.slack.com/apps/A####XXXX/oauth

  • [SLACK ACCESS TOKEN] - The Slack access token used to post messages to Slack. This should have been collecting after installing the App to a team. [LINK TO TUTORIAL]

Pasting it all in

Related documentation