This guide will teach you how to automatically post a message into a slack channel of your choice with details of a new signup to your dapp.

Prerequisites

Post a message to Slack

As long as you have completed the serverless webhook guide, you’ll know how to access the email of a user within your serverless function. Now we have the email, we can post a message to Slack. To do this we’ll need to create a Slack app and set it up to post messages using incoming webhooks.

This guide will get you set up, and once you’ve completed it you will end up with a webhook URL, that’s all you need.

It’s time to write the code to send our Slack message. We can do this with anything like Axios or Request, but here we will use the Slack/webhook library to make things even easier.

// Slack.js

const { IncomingWebhook } = require("@slack/webhook");

// Read a url from the environment variables
const url = YOUR_SLACK_WEBHOOK_URL;

// Initialize
const webhook = new IncomingWebhook(url);

const sendMessage = async (message) => {
  try {
    return await webhook.send({
      text: message,
    });
  } catch (error) {
    console.error(error);
  }
};

module.exports = sendMessage;
// index.js

const webhook = require("./slack");

module.exports.handler = async (event) => {
  const email = event.data.email;

  const message = `New signup: ${email}`;

  await webhook(message);

  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: "Go Serverless v3.0! Your function executed successfully!",
        input: event,
      },
      null,
      2
    ),
  };
};

Test it out

As per the serverless webhook guide, we can test this out using:

serverless invoke local --function FUNCTION_NAME_HERE --data '{data: {"email":"[email protected]"}}'

We can then deploy using serverless deploy, and you’re good to go!