GitHub

Slack

Run a pyfect.chat bot on Slack: the adapter, the signed Events API and Interactivity routes, and the options that decide who a post notifies.

pyfect.chat.slack is Effect's @effect/chat-slack, the Slack adapter for Chat. slack_chat.layer(bot_token=..., team_id=...) registers it for one workspace and needs only an HttpClient. It calls Slack's Web API over HTTP, with no Slack SDK. A thread is slack_chat.thread(team=..., channel=..., thread_ts=...), and everything Chat does (posts, edits, reactions, files, history, native streaming) works on it.

Web API calls go to https://slack.com/api unless you pass base_url. For GovSlack, pass base_url="https://slack-gov.com/api" to slack_chat.layer, or to slack_web_api.layer when you use the client on its own.

Events and interactions

slack_chat.layer_webhook(path=..., signing_secret=..., app_id=...) adds the Events API route to an HttpRouter. Every request is untrusted until it passes Slack's v0 signature check: an HMAC-SHA256 of the timestamp and body with your signing secret, compared in constant time through Mac (pyfect.crypto.native.layer_mac), with a timestamp at most five minutes from now. A request that fails it is answered 401 before its body is parsed, and one over max_body_bytes (1 MiB) is answered 413 before that. The body is parsed into typed events at the route, and the ChatHandler gets them one at a time. When the handler fails NotAccepted, or the request runs past deadline, the route answers 503 so that Slack retries. chat_event.dedupe_key gives a redelivery the same key.

slack_chat.layer_interactivity(...) is the route for buttons, selects, modals and slash commands, with the same checks. It hands each payload to the chat_interaction.Handler within Slack's three seconds. With Socket Mode instead of a public URL, pass each envelope to slack_chat.normalize and each interaction to SlackChatService.interaction yourself.

Slow slash commands

A slash-command handler that is still running at Slack's deadline is interrupted, the route answers 503, and Slack shows the user an error. When the work may take longer, race it against a budget below the deadline. If the work wins, answer with chat_interaction.respond. If the budget runs out first, return chat_interaction.defer(command), which acknowledges the command at once, and send the answer later with Chat.follow_up, which posts to the command's response_url for up to 30 minutes. The work and the follow-up run on fibers forked into the interactions layer's scope, so they outlive the handler and stop when the app shuts down.

slack_defer.py
import pyfect as fx
from pyfect import layer, testing
from pyfect.chat import chat_interaction as ci
from pyfect.chat import chat_test
from pyfect.chat.chat import Chat
from pyfect.chat.chat_test import ChatTest

report = ci.command("report", description="Builds the weekly report")


# Stands in for slow work: a summary is quick, the full report takes 5 seconds.
def build_report(text: str) -> fx.Effect[str]:
    took = "5 seconds" if text == "full" else "100 millis"
    return fx.sleep(took).as_(f"Weekly report ({text}): 42 deploys, 0 rollbacks")


@fx.gen
def handlers():
    # The layer's scope. Work forked into it outlives the handler, which is
    # interrupted at Slack's deadline, and stops when the app shuts down.
    scope = yield from fx.Scope()
    chat = yield from Chat()

    def on_report(command: ci.CommandInvoked) -> fx.Effect[ci.Respond | ci.Defer]:
        @fx.gen
        def answer():
            # start_immediately runs the work up to its first wait before going on.
            work = yield from build_report(command.text).fork_in(scope, start_immediately=True)
            # Two of Slack's three seconds go to the work; the rest is the reply's.
            done = yield from work.join().timeout_option("2 seconds")
            if isinstance(done, fx.Some):
                return ci.respond(markdown=done.value)
            # Too slow: answer now, and send the report through the command's
            # response_url once the work is done.
            deferred = ci.defer(command)
            yield from (
                work.join()
                .flat_map(lambda text: chat.follow_up(deferred, markdown=text))
                .ignore(log=True, message="the report's follow-up failed")
                .fork_in(scope)
            )
            return deferred

        return answer

    return [report.handler(on_report)]


interactions = ci.group(report).to_layer(handlers)


# The test platform answers commands as Slack would, with a 3 second deadline
# on the test clock, so the 5 second report takes no real time.
@fx.gen
def program():
    test = yield from ChatTest()
    thread = yield from test.make_thread()
    for text, wait in [("summary", "100 millis"), ("full", "2 seconds")]:
        command = yield from test.command(thread, "report", text=text)
        asked = yield from test.interact(command).fork()
        yield from testing.adjust(wait)
        print(f"/report {text}:", type((yield from asked.join())).__name__)
    yield from testing.adjust("3 seconds")
    for call in (yield from test.calls):
        print(call.op, call.outcome, repr(call.markdown))


layers = interactions.pipe(layer.provide_merge(ci.layer())).pipe(
    layer.provide_merge(chat_test.layer())
)
testing.run_test(program.pipe(fx.provide(layers)).or_die())

Who a post notifies

Slack decides who a message notifies from its text field, so the adapter sends every <@user>, <!here> or group token as plain text unless the post allows it. slack_chat.with_post_options(SlackPostOptions(...)) sets the options for every write inside an effect: notify_users, notify_groups and notify_broadcast let those tokens through, and unfurl, native_stream and session_status_at_end turn link previews, Slack's native streaming and the agent session status on or off. Nested options merge, and the inner option wins.

Text a user wrote still forms syntax inside your Markdown: a display name of <!channel> notifies the channel when the options allow broadcasts, and [x](https://evil.example) is a live link. Put such text through slack_chat.escape_markdown first, within a line, as in f"Approved by {slack_chat.escape_markdown(name)}". It writes &, < and > as entities, as Slack's formatting rules ask, and backslash-escapes Markdown syntax, so the text shows as typed and no token in it notifies, whatever the options allow.

A call Slack answers 429 is retried after its Retry-After, however long Slack asks for. Pass max_retry_after to slack_chat.layer, such as "1 minute", and a longer wait fails the op at once with RateLimited, its retry_after the wait Slack asked for.

slack_bot.py
import hashlib
import hmac
import json
import time
from typing import Never
from urllib.parse import parse_qsl

import pyfect as fx
from pyfect import layer
from pyfect.chat import chat, chat_handler, chat_markdown
from pyfect.chat.chat import Chat
from pyfect.chat.chat_event import ChatEvent, MessageCreated
from pyfect.chat.slack import slack_chat
from pyfect.chat.slack.slack_chat import SlackPostOptions
from pyfect.crypto.native import layer_mac
from pyfect.http import body as http_body
from pyfect.http import client, router
from pyfect.http import request as http_request
from pyfect.http import response as http_response
from pyfect.http.request import HttpClientRequest
from pyfect.redacted import make as redacted

SIGNING_SECRET = "8f742231b10e8888abcd99yyyzzz85a5"


# Answers a message that mentions the bot. A mention in a post notifies no one
# unless the post's options allow it; this one allows the person who asked.
def on_event(event: ChatEvent) -> fx.Effect[None, Never, Chat]:
    if not isinstance(event, MessageCreated):
        return fx.void
    message = event.message
    if not any(mention.is_self for mention in message.mentions):
        return fx.void
    reply = chat_markdown.post(event.thread, f"On it, <@{message.author.id}>. Ping <@U0OTHER>?")
    allowed = SlackPostOptions(notify_users=(message.author.id,))
    return reply.pipe(slack_chat.with_post_options(allowed)).as_void().or_die()


# The Slack app: the Events API route, the adapter and the handler.
app = (
    slack_chat.layer_webhook(
        path="/slack/events", signing_secret=redacted(SIGNING_SECRET), app_id="A0APP"
    )
    .pipe(layer.provide(layer.merge(chat_handler.layer(on_event), layer_mac)))
    .pipe(layer.provide_merge(slack_chat.layer(bot_token=redacted("xoxb-1"), team_id="T0TEAM")))
    .pipe(layer.provide_merge(chat.layer))
)


# Stands in for Slack's Web API here, printing what the bot posts.
def slack(request: HttpClientRequest) -> fx.Effect[http_response.HttpClientResponse]:
    assert isinstance(request.body, http_body.Bytes)
    fields = dict(parse_qsl(request.body.body.decode()))
    if request.url.endswith("/chat.postMessage"):
        print("chat.postMessage", repr(fields["text"]))
    answer = {"ok": True, "user_id": "U0BOT", "channel": "C0GENERAL", "ts": "1794600000.000100"}
    return fx.succeed(http_response.make(request, json.dumps(answer)))


# What Slack would send when someone mentions the bot, signed with the app's secret.
def delivery() -> tuple[bytes, dict[str, str]]:
    event = {
        "type": "message",
        "channel": "C0GENERAL",
        "channel_type": "channel",
        "user": "U0ASKER",
        "text": "<@U0BOT> deploy the docs",
        "ts": "1794509003.000001",
    }
    body = json.dumps(
        {"type": "event_callback", "team_id": "T0TEAM", "api_app_id": "A0APP", "event": event}
    ).encode()
    timestamp = str(int(time.time()))
    signed = f"v0:{timestamp}:".encode() + body
    signature = hmac.new(SIGNING_SECRET.encode(), signed, hashlib.sha256).hexdigest()
    headers = {"x-slack-request-timestamp": timestamp, "x-slack-signature": "v0=" + signature}
    return body, headers


@fx.gen
def program():
    http = yield from router.in_memory_client(app)
    body, headers = delivery()
    sent = http_request.post("http://localhost").body_bytes(body, "application/json").body
    response = yield from http.post("http://localhost/slack/events", body=sent, headers=headers)
    print("answered", response.status)
    unsigned = yield from http.post("http://localhost/slack/events", body=sent)
    print("unsigned", unsigned.status)


fx.run_blocking(fx.scoped(program).pipe(fx.provide(client.layer_test(slack))).or_die())

The app needs these bot token scopes: chat:write, channels:history, groups:history, im:history, mpim:history, channels:read, groups:read, im:read, mpim:read, users:read, reactions:read, files:read and files:write, plus commands for slash commands. Subscribe it to message.channels, message.groups, message.im, message.mpim, app_mention, reaction_added, reaction_removed and agent_session_stopped. Slack's stop button for a streaming reply needs the app declared as an agent; without that, the adapter stops setting the session status after Slack's first not_authorized.

Testing

slack_chat.normalize and slack_chat.normalize_interaction are pure functions from Slack's JSON to events, so captured payloads test them directly. For the adapter's writes, provide an HttpClient from pyfect.http.client.layer_test that answers like Slack, as the example above does. Effect's conformance suite runs against the adapter this way in pyfect's own tests (chat_test.conformance).

Reference: slack_chat, slack_web_api.