Solution Recipe: How to Use Slack Webhooks to Capture a Channel Message as a Custom Klaviyo Event via Napkin

Mokhsira
8 min read
For developers
July 10, 2023

By Mokhsira Kurbonova

Solution Recipes are tutorials to achieve specific objectives in Klaviyo. They can also help you master Klaviyo, learn new third-party technologies, and come up with creative ideas. They are written mainly for developers & technically-advanced users.

This is a guest post written by Mokhsira Kurbonova, who recently built this as part of Klaviyo’s internal Solution Architect mentorship program.

What you’ll learn

How to send a Slack channel message, starting with a trigger word, to Klaviyo as a custom event using Napkin.io. This process involves utilizing the Slack outgoing Webhook integration, creating a function in Napkin, and as an added bonus, configuring your flow in Klaviyo.

Why it matters


According to Axioshq, our weekly internal communication typically consumes around 3–10 hours on average. In addition to regular communication, there are critical pieces of information that require dissemination, such as major sales or new VIP clients. To address this, many organizations rely on Slack as their primary internal communication platform. However, important updates often necessitate follow-up emails.
Imagine a scenario where you could simply send a message in a Slack channel and automatically trigger an email through Klaviyo. This streamlined approach to internal communication would significantly enhance workflow efficiency and eliminate unnecessary steps.

Level of sophistication

Moderate



Introduction

Klaviyo offers immense customization potential. Through its robust API offering, it’s possible to create custom events for any occasion or use case. These events can serve as triggers for automated flows and facilitate email, SMS, and notification automation. In essence, Klaviyo provides limitless possibilities for automating various communication channels.

Challenge

As Slack serves as the primary communication channel for many organizations, important messages often get buried among less relevant ones. It’s important to simplify the process of disseminating information. In this Solution Recipe, we will outline the process of triggering an email to a Klaviyo List when a pre-configured keyword is sent in a Slack channel.

Ingredients

Instructions

Step 1:

Napkin.io offers developers a streamlined and secure platform for writing and deploying code, accessible directly from a web browser. Given this functionality, it proves to be highly advantageous for our specific needs:

  • Visit Napkin.io, signup and choose from the range of sign-up options provided:
  • In this example, the solution was written in Python. Navigate to the left-hand side and choose the Python option, as illustrated below:
  • After the dashboard has finished loading, copy the public URL displayed at the top of the screen. This URL will be required for the upcoming steps:

Step 2:

Integrate Slack’s Outgoing Webhook: 

*If you have Slack admin rights, please follow the instructions provided below. For non-admin users, please share this step with your Workspace admin.

  • You can directly access the Slack integration by following this link. If you have admin rights, you can add Outgoing Webhooks to your Slack Workspace. For non-admin users, you can request configuration assistance using the same link:
  • Once you have successfully added the Webhook, you will be prompted to configure the trigger word, select the desired channel, and paste the Napkin URL from Step 1 as a “URL(s)” (or share the details of configuration with your workspace admin):

Step 3:

Good news! We’ve reached the halfway point! All the essential settings for Slack have been successfully configured. Now, let’s shift our attention to Napkin, where we will work on writing the function that will process incoming payload from Slack, subsequently transmitting this data to Klaviyo.

  • Return to your function in Napkin, and before we proceed, let’s begin by importing the necessary libraries for our code:
import requests
import urllib.parse
import json
from datetime import datetime
from napkin import request, response
  • As a signed-in user on Napkin, you have the capability to add environment variables to your user functions. This feature will enable us to securely store the Klaviyo private key for future use. Go to Other tab > Environment Variables, add key and value:
  • We will now be able to implement this in our code, where “klaviyopk” is my Environment Variable: 
import os
klkey=os.environ.get('klaviyopk')
  • Slack will send the message details to the Napkin public URL. In order to process this data, we will need to parse it. Napkin io documentation provides the detailed instructions on how to achieve this. However, for your convenience, you can also refer to the code snippet below as an example: 
# Parse inbound payload
text= request.form.get('text')
channel_name= request.form.get('channel_name')
time=datetime.now()

Note: You might have noticed that the timestamp is also included here. This is done to ensure that our Klaviyo event carries the precise timestamp in its payload.

Step 4:

To create a Klaviyo custom event, we require both a profile for whom the event will be registered and the event data itself. A profile represents any individual within your organization who should receive the Slack message as an email. Consequently, you will need to create a new email list in Klaviyo that encompasses the email addresses of your colleagues. This list should have all intended recipients of the email notifications. 

Once the list is ready, we can move forward and pull the list members via Klaviyo API:

# Get Klaviyo list members
url = "https://a.klaviyo.com/api/lists/TRuQqu/profiles/?fields[profile]=email"

headers = {
    "accept": "application/json",
    "revision": "2023-02-22",
    "Authorization": f"Klaviyo-API-Key {klkey}"
}
r = requests.get(url, headers=headers)

* “TRuQqu” in request represents my list ID, learn how to locate your list ID here. In this example, we are retrieving only the “email” field from the profiles. However, if you intend to send SMS notifications instead of emails, please make sure to adjust the “fields” accordingly. While this step is not mandatory, it can certainly decrease processing time.

Step 5:

At this stage, we need to iterate through all the profiles we have retrieved from the Klaviyo list. Within this loop, we will send a custom event for each profile using events Klaviyo endpoint:

# Loop through each list member and send a custom event with Slack message content as an event property
list_members=r.json()['data']
for i in list_members:
    email=i['attributes']['email']
    message=text
    channel=channel_name
    timestamp=time.strftime("%Y-%m-%dT%H:%M:%S")
    url = "https://a.klaviyo.com/api/events/"
    payload = {"data": {
          "type": "event",
          "attributes": {
            "profile": {"email": email},
            "metric": {"name": "Alert"},
            "properties": {"text": message,
            "Slack_channel": channel},
            "time": timestamp
          }
        }}
    headers = {
         "accept": "application/json",
         "revision": "2023-02-22",
         "content-type": "application/json",
         "Authorization": f"Klaviyo-API-Key {klkey}"
         }
    r = requests.post(url, json=payload, headers=headers)
    print(r.text)

Solution can be cloned into your Napkin via this link. Please make sure to add your private key, configure the Slack Integration, and change the list ID. 

Bonus

Let’s take a look at what the end result should appear as:
From Slack: 

To Klaviyo Automated Flow:

Information from Slack message can be pulled into the email via event variables:

Additional Notes about the Code and Its Configuration:

To effectively parse through the incoming payload, refer to the documentation provided by Napkin.io. Furthermore, when working with Klaviyo API endpoints, it is crucial to utilize a private Klaviyo API key, which should be stored as an environment variable within Napkin.

The Klaviyo endpoints used in this solution are as follows:

  1. Get list profiles
  2. Create event

By leveraging these endpoints, you can retrieve the necessary profile information and create custom events within Klaviyo to facilitate seamless communication and automation.

Impact

This Solutions Recipe provides a comprehensive guide on leveraging Klaviyo APIs to create custom events and automate flows. The example demonstrates a versatile function that can be adapted to extract data from any application and send it to Klaviyo as an event. This enables seamless automation of email, SMS, and notification workflows based on the received data. The versatility of this solution extends far beyond the described use-case. Consider its potential for VIP client notifications, out-of-office status updates, meeting details, SMS notifications for on-call employees and much more. The possibilities are virtually limitless, allowing you to streamline various communication processes and enhance efficiency across a wide range of scenarios.

Mokhsira
Mokhsira Kurbonova

Related content

For developers
Dec 22, 2023
Account Subscription History Solution Recipe

This Solution Recipe goes over how to extract historical data regarding a profile’s subscription timeline.

For developers
Dec 4, 2023
Solution Recipe: Using AI and APIs to create and upload images to your Klaviyo account

Solution Recipes are tutorials to achieve specific objectives in Klaviyo. They can also help you master Klaviyo, learn new third-party technologies, and come up with creative ideas. They are written mainly for developers and technically-advanced users. Note: We do our best to make sure any code and API references are accurate and current when this […]

For developers
Oct 24, 2023
Solution Recipe: Append, unappend, and unset custom properties programmatically with Klaviyo

Solution Recipes are tutorials to achieve specific objectives in Klaviyo. They can also help you master Klaviyo, learn new third-party technologies, and come up with creative ideas. They are written mainly for developers and technically-advanced users. Note: We do our best to make sure any code and API references are accurate and current when this […]