Sagi Kedmi

Sagi Kedmi

Jul 30, 22

DRAFT

Owning Yourself

TL;DR

I’m happy to open source a battle-tested library for using Slack’s API through Cloudflare Workers:

sagi/workers-slack

We built it out of necessity - we needed to speed up the response times of our app and still use a serverless architecture.

Read on to learn more.

Background

One of the core features of OpenSay (a tool for responsible anonymity in organizations) is the ability to do real-time AI classification of content and dynamically render the results as an image.

It looks like this:

OpenSay Slack Preview Message

It is a serial process - the AI classification must come before the image rendering.

It is also a time intensive process - usually less than 2 seconds, which is forever in terms of user experience.

We needed a way to shave some time off.

How Slack Bots Work?

When a Slack user, within a Slack workspace, interacts with a bot (e.g. with a slash command) an event is sent to Slack’s regional servers which then relays the event to the bot’s backend server.

💡 Aha, if we can bring our backend closer to Slack’s regional servers we can definitely shave some time off!

Enter Cloudflare Workers

Cloudflare Workers is a highly performant serverless runtime with an almost infinite scale and ~0ms cold starts which runs at network’s edge with over 250 locations.

Cloudflare uses anycast routing to make sure that when an origin sends a request it triggers the closest (in terms of network speed or region) worker.

Fits like a glove to what we are trying to achieve.

How It Works?

Code speaks louder than words.

sagi/workers-slack

$ npm install @sagi.io/workers-slack

Example code:

const SlackREST = require('@sagi.io/workers-slack')

const botAccessToken = process.env.SLACK_BOT_ACCESS_TOKEN;
const SlackAPI = new SlackREST({ botAccessToken })
const formData = {
  token: botAcccessToken,
  channel: 'general',
  text: 'hello world'
}
const result = await SlackREST.chat.postMessage(formData)

It mimicks Slack’s Web API. For example, under SlackREST you have the chat.postMessage method.

If you need methods that weren’t implemented, just change the METHODS object here and open a pull request.

I hope the above made sense and that it helps you build faster Slack apps.

Comments and thoughts are welcome on this tweet:


© 2024 Sagi Kedmi