Integrate Slack and WhatsApp with Low-Code (Part 1)
Published on July 4, 2024

Startups and small businesses often lack resources for full-fledged (and expensive) customer support solutions. However, with Vonage's AI Studio low-code platform, you can build a custom, cost-effective customer experience solution tailored to your needs. One option is to build a WhatsApp integration with Slack.

This two part tutorial will show you how to integrate WhatsApp and Slack to create a powerful customer support system. In this first article, you’ll get the project setup and make your first connection to send WhatsApp messages to Slack. In part two, you will handle the more advanced logic so that your team can respond to customer inquiries directly from Slack.

TL;DR: Find the refactored server code on Github to follow along with the AI Studio and Slack setup without worrying about JavaScript programming.

Preview of Slack-WhatsApp IntegrationPreview of Slack-WhatsApp Integration

Integrating WhatsApp with Slack for Customer Support Overview

Initially, I aimed for a flow similar to the famous Giphy slash command. However, custom slash commands are not allowed in threads by Slack (Giphy is a special case). Using a slash command in a regular channel response doesn't associate the response with a specific conversation. With simultaneous conversations, this approach would create a mess! To keep conversations threaded, we implemented the following workaround:

  1. A new message appears in the customer support channel with the conversation_id from a new WhatsApp conversation.

  2. A team member clicks a Slack Shortcut on the message, which tells our application to link that conversation to the current Slack thread.

  3. The team member uses the /reply slash command followed by the session_id and their response.

  4. Our application handles the reply, sends it to AI Studio, and adds it as a response in the thread.

  5. Our application also handles customer responses and adds them to the correct thread.

  6. The conversation continues until the agent uses the /close_ticket slash command, terminating the session in AI Studio and adding a "conversation resolved" response in the Slack thread.

Following this approach, you can seamlessly integrate WhatsApp and Slack for customer support, allowing your team to manage conversations directly from Slack while maintaining proper threading and context.

Prerequisites

  • Vonage Virtual Number

  • Slack Account and permission to install apps in your workspace

  • Node

    

    DT API Account

    To complete this tutorial, you will need a DT API account. If you don’t have one already, you can sign up today and start building with free credit. Once you have an account, you can find your API Key and API Secret at the top of the DT API Dashboard.

Setup

How to Setup a Node Application with Express

  1. Create a new directory for your project and navigate into it using your terminal.

    • mkdir whatsapp-to-slack

    • cd whatsapp-to-slack

  2. Initialize a new Node.js project:

    • npm init -y

  3. Install Dependencies

    • npm install express axios body-parser dotenv

  4. Create Your Project Files

    • touch server.js .env .gitignore 

    • code .

In the .gitignore, we’ll need to add a single line so git doesn’t accidentally share our .env credentials: 

.env

In our .env file we’ll need to add our secure values from both Slack and AI Studio. We’ll fill those out in the next steps. For now add:

// Inside our ENV file 
SLACK_WEBHOOK_URL=""
AI_STUDIO_KEY=""

In the server.js add the following boilerplate:

// Import required modules
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');

// Create an Express application
const app = express();
const PORT = process.env.PORT || 3000;

// Import our secure ENV variables
const SLACK_WEBHOOK_URL = process.env.SLACK_WEBHOOK_URL;
const AI_STUDIO_KEY = process.env.AI_STUDIO_KEY;

// Middleware to parse JSON requests
app.use(express.json());

// Middleware to parse requests from Slack
const urlencodedParser = bodyParser.urlencoded({ extended: false })

// Global Variables

// Define the /start endpoint
app.post('/start', (req, res) => {
    // Handle POST request to /start
    res.send('Start endpoint reached');
});

// Define the /inbound endpoint
app.post('/inbound', (req, res) => {
    // Handle POST request to /inbound
    res.send('Inbound endpoint reached');
});

// Define the /slack/start endpoint 
app.post('/slack/start', urlencodedParser, function (req, res){
res.send("Begin initiated");
});

// Define the /slack/message endpoint
app.post('/slack/message', urlencodedParser, function (req, res) {
  res.send("Response sent to user")
});

app.post('/slack/end', urlencodedParser, function (req, res) {
res.send("Conversation ended")
});

// Start the server
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

// We'll add our function declarations below here 

In our boilerplate, we do 4 main things:

  1. Import our dependencies.

    • Express runs our server.

    • Axios allows us to make HTTP requests. HTTP requests are what allow us to send and receive information from Slack & AI Studio.

    • bodyParser helps us parse or clean up the data we get back from Slack. 

  2. Configure our app’s server, middleware, and env variables

  3. Create endpoints for each of our application's functionalities

  4. Start our server

How to Expose Our Application Through localtunnel

Our application requires passing data several times between AI Studio and Slack. We’ll use localtunnel to expose our localhost and create publicly accessible tunnels. In your terminal run the following command: npx localtunnel --port 3000 This will create a tunnel url that should look something like this:

➜  whatsapp-to-slack npx localtunnel --port 3000
your url is: https://some-parks-beg.loca.lt

The url that starts with https and ends in loca.lt is your tunnel url. In the remainder of the article anytime that TUNNEL_URL is mentioned, this value should be used.

Open a second tab in your terminal for later. 

How to Setup a Slack App

  1. Log in to your Slack Workspace and open your applications

  2. Click on “Create a New App”. Select the “From Scratch” option.

  3. Give your app a name and select the Workspace where you want to use it.

  4. Click “Create App”

Ta-da! You now have your first Slack App! There’s one last thing you’ll need to do. You’ll need to enable Incoming Webhooks. Once you’ve toggled incoming webhooks on, scroll to the bottom of the page and click “Add New Webhook to Workspace”. You’ll be asked to select the desired channel and then click “allow”. This will redirect you to the Incoming Webhooks page of your app, except now if you scroll to the bottom you will see a Webhook URL for your desired channel. Copy the URL and now add it as the value for your SLACK_WEBHOOK_URL in your .env file. It should look something like this:

SLACK_WEBHOOK_URL="https://hooks.slack.com/services/..."

How to Create an Inbound WhatsApp Chatbot

To create your agent, follow the instructions found in the AI Studio documentation here. There are three important options for our agent, select:

  • Type: WhatsApp

  • Template: Start From Scratch

  • Event: Inbound

The flow of our agent will be relatively simple. Upon the user messaging the agent, we’ll use a Collect Input node to ask what they need help with. The answer will be stored in a parameter called inquiry. Then we’ll use a conditional to check if inquiry is equal to “escalate”. If it is, we’ll then send the user a message saying “Please hold while we connect you to a live agent”.

If the inquiry is something else, we’ll mimic all other possible flows by simply sending a message “Thanks for using our service!” (Send Thank You node). The Please Hold node will connect to a Live Agent Routing Node. Finally, both the Live Agent Routing Node and Send Thank You Node will connect to an End Conversation node.

AI Studio Flow OverviewAI Studio Flow Overview

How to Setup a Live Agent Routing Node

The Live Agent Routing Node is how AI Studio creates your Whatsapp to Slack integration. In the Live Agent Routing Node we need to do 3 things:

  1. Add your ‘TUNNEL_URL/start’ in the Start Connection EP field

  2. Add your ‘TUNNEL_URL/inbound’  in the Inbound Transfer EP field

  3. Select inquiry in the Transfer Parameters 

And hit “Save and Exit”.

Live Agent Routing NodeLive Agent Routing Node

Next, we’ll need to add your AI Studio API Key to your .env file. You can find the X-Vgai-Key on the top right of your AI Studio canvas. Click on the "user" icon, and then "Generate API Key". 

Copy the X-Vgai-Key and now add it as the value for your AI_STUDIO_KEY in your .env file. It should look something like this:

SLACK_WEBHOOK_URL="https://hooks.slack.com/services/..."
AI_STUDIO_KEY="YOUR_KEY_VALUE"

Lastly, you’ll need to assign your Vonage Number to the agent. Follow the publishing instructions from the documentation.  

How to Initiate a Slack Conversation Using Incoming Webhooks

The first action we need to take is connecting AI Studio to Slack. We will use the Live Agent’s Start Connection Endpoint and Slack’s Incoming Webhooks. We’ve already configured these in the setup but now we need to add the logic to actually connect them. Our agent’s Start Connection Endpoint is configured to send a request to our /start endpoint. There we will send 2 pieces of information to Slack: the sessionId and the transcription of our conversation thus far. We’ll package this up in the data object according to what Slack is expecting with a little formatting. We’ll use the axios library to send all our POST requests. This is how our /start endpoint now looks:

app.post('/start', (req, res) => {
  const sessionId = req.body.sessionId;
  const transcription =  handleTranscription(req.body.history.transcription);
  const data = { text: `Session: \`${sessionId}\`\nTranscription:${transcription}`, }
  axios.post(SLACK_WEBHOOK_URL, data)
  res.send('Start endpoint reached');
});

You’ll notice that we call the function handleTranscription. This function formats our raw transcription into something nice for Slack. You can add this at the bottom of our file.

const handleTranscription = (transcription = []) => {
  if (!transcription.length) return null;

  let strTrans = '```';

  for (const message of transcription) {
    for (const key in message) {
      strTrans += `\n${key}: ${message[key]}`;
    }
  }

  strTrans += '```';
  return strTrans;
};

How to Test Your WhatsApp to Slack Connection

You can now test that your agent is connected to your Slack channel! In your second terminal tab, run your application:

node server.js

Did your transcription appear in Slack? How cool! Because we haven’t implemented a way to end conversations in AI Studio yet, each time you test you’ll need to manually end the conversation. You can do so by sending a POST request to the Stop Connection EP with a tool like Postman. You can find your active sessions under the Reports tab.

End Conversation with PostmanEnd Conversation with Postman

Additionally, each time you want to test a new change in your node application you’ll need to restart the server.

Conclusion

That’s it for part one! In Integrate Slack and WhatsApp with Low-Code (Part 2), you’ll complete the functionality of our customer support flow. You’ll learn how to create Slack Messages Shortcuts, how to create Slack Slash Commands, and how to a full back-and-forth conversation between WhatsApp and Slack.

If you have issues with this tutorial or have questions, be sure to join the Vonage Developer Community Slack. You can also follow us on  X, formerly known as Twitter to stay in the loop on the latest Vonage developer news!

Additional Resources

Benjamin AronovDeveloper Advocate

Benjamin Aronov is a developer advocate at Vonage. He is a proven community builder with a background in Ruby on Rails. Benjamin enjoys the beaches of Tel Aviv which he calls home. His Tel Aviv base allows him to meet and learn from some of the world's best startup founders. Outside of tech, Benjamin loves traveling the world in search of the perfect pain au chocolat.

Ready to start building?

Experience seamless connectivity, real-time messaging, and crystal-clear voice and video calls-all at your fingertips.