Skip to main content

Python wrapper for the Slack Blocks API

Project description

slackblocks

Licence: MIT Licence: BSD-3-Clause Python Versions PyPI Downloads Build Status Docs

Build Slack messages in Python — without writing JSON by hand.

slackblocks is a typed, validating Python wrapper around the Slack Block Kit API. It exists because Block Kit JSON is verbose, easy to get subtly wrong, and unpleasant to maintain in source control.

Why slackblocks?

  • ConciseSectionBlock("Hello, *world*!") instead of a 10-line JSON object.
  • Validated — character limits, required fields, mutually-exclusive options, and element-type restrictions are enforced at construction time, so you find out before hitting Slack's API.
  • Drop-in compatible with both the official slack-sdk and the legacy slackclient — unpack a Message directly into client.chat_postMessage(**message).
  • Typed — full type hints; ships py.typed.
  • Zero runtime dependencies.

Installation

pip install slackblocks

slackblocks 2.x requires Python 3.10 or newer. Users on Python 3.8 / 3.9 should pin to the 1.x line — see the Compatibility page.

Quickstart

from slackblocks import (
    ActionsBlock,
    Button,
    DividerBlock,
    HeaderBlock,
    Message,
    SectionBlock,
)

message = Message(
    channel="#general",
    text="Build #482 passed",  # plain-text fallback for notifications
    blocks=[
        HeaderBlock("Build #482 passed :white_check_mark:"),
        SectionBlock(
            fields=[
                "*Branch*\n`main`",
                "*Author*\n@nick",
                "*Duration*\n3m 12s",
                "*Tests*\n1,247 passed",
            ],
        ),
        DividerBlock(),
        ActionsBlock(
            elements=[
                Button(text="View build", action_id="view", url="https://ci.example.com/482"),
                Button(text="Re-run", action_id="rerun", value="482", style="primary"),
            ],
        ),
    ],
)

message can be sent in one line with the official Slack SDK:

import os
from slack_sdk import WebClient

client = WebClient(token=os.environ["SLACK_API_TOKEN"])
client.chat_postMessage(**message)

The ** operator unpacks slackblocks Message objects directly into the SDK call — no to_dict() boilerplate required.

A simple Slack message rendered in Slack

What's supported

Surface Status
Blocks ✅ All current block types (Section, Header, Divider, Image, Context, Actions, Input, RichText, File, Table, Markdown, Video)
Elements ✅ Buttons, all select menus, date/time pickers, checkboxes, radio groups, all input types, overflow menus, workflow buttons
Composition Objects ✅ Text (+ PlainText / Markdown aliases), Option, Confirm, Conversation/Dispatch filters, Workflow, Trigger
Rich Text ✅ Sections, lists, quotes, code blocks, inline links/users/channels/emoji
Modals & Home Tabs ✅ Full views API
Messages chat.postMessage, webhook messages, slash-command/interaction responses, threaded replies, ephemeral messages
Attachments ⚠️ Supported but deprecated by Slack
Round-tripping Block.from_dict(data) and per-class from_dict for parsing incoming Slack JSON back into objects

What's new in 2.0

slackblocks 2.x is the first major release in the modernised line. Highlights:

  • Two new block types: MarkdownBlock (GitHub-flavored Markdown) and VideoBlock.
  • PlainText and Markdown thin aliases for Text(type_=...).
  • block_kit_builder_url(payload) — turn any block, message, or view into a Block Kit Builder URL for browser preview.
  • Workflow.from_url(url, **params) — one-line workflow construction.
  • Block.from_dict(data) + per-class from_dict parsers — round-trip incoming Slack JSON back into slackblocks objects.
  • Typed exception subclasses of InvalidUsageError (LengthError, RangeError, TypeMismatchError, MutualExclusivityError, MissingRequiredError) — existing except InvalidUsageError blocks continue to work.
  • Tighter type signatures: Literal narrowing on Button.style, ColumnSettings.align, ConversationFilter.include; @overload on Text.to_text so the return type narrows on allow_none.
  • Modern annotation syntax (list[X], X | Y) throughout.

Existing 1.x code continues to work unchanged; see the Migration Guide for the full diff.

Documentation

Comparison with slack-sdk block classes

The official slack-sdk ships its own block classes. slackblocks predates them and offers a more concise API, stricter up-front validation, and independent versioning. They produce equivalent JSON; pick whichever you find more ergonomic.

# slackblocks
SectionBlock("Hello, *world*!")

# slack-sdk equivalent
from slack_sdk.models.blocks import SectionBlock as SDKSectionBlock
from slack_sdk.models.blocks.basic_components import MarkdownTextObject
SDKSectionBlock(text=MarkdownTextObject(text="Hello, *world*!"))

Licensing

slackblocks is dual-licensed under MIT and BSD-3-Clause. Use whichever fits your project — this makes it safe to vendor into projects under either license.

Contributing

Contributions are welcome. Quick start (the project uses uv for dependency management):

git clone https://github.com/nicklambourne/slackblocks.git
cd slackblocks
uv sync --all-groups

uv run pytest test/unit
uv run ruff format --check .
uv run ruff check .
uv run mypy slackblocks

Preview the documentation locally with uv run mkdocs serve.

For the full development guide — testing conventions, validation patterns, docstring style, release process, and a PR checklist — see the Contributing page.

Bug reports and feature requests: https://github.com/nicklambourne/slackblocks/issues.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

slackblocks-2.0.0.tar.gz (1.7 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

slackblocks-2.0.0-py3-none-any.whl (50.0 kB view details)

Uploaded Python 3

File details

Details for the file slackblocks-2.0.0.tar.gz.

File metadata

  • Download URL: slackblocks-2.0.0.tar.gz
  • Upload date:
  • Size: 1.7 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.14 {"installer":{"name":"uv","version":"0.11.14","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for slackblocks-2.0.0.tar.gz
Algorithm Hash digest
SHA256 0583ac89b25d81b42f6cde54357b4fa0d8290d4604980b05a3c346b42dd3efe7
MD5 737b901c3a781923afbcef9340049612
BLAKE2b-256 0c4ab64bcb453cb62ab47f8ae35568051489f0ebc5732dc8b25dd9716de7b850

See more details on using hashes here.

File details

Details for the file slackblocks-2.0.0-py3-none-any.whl.

File metadata

  • Download URL: slackblocks-2.0.0-py3-none-any.whl
  • Upload date:
  • Size: 50.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.14 {"installer":{"name":"uv","version":"0.11.14","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for slackblocks-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 bd684822f2c8001111b00503ac7277becc6a4fc9e265370d74fabd305a9399c9
MD5 65af285ba149d02a85205eba8cd86d8b
BLAKE2b-256 206dd6f8d596290d2e1c8506dc52a5f6bedb761fd69b83f53a892b7cc723fded

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page