Slack Blocks API Python Wrapper
raw JSON → 1.2.3 verified Mon Apr 27 auth: no python
Python wrapper for the Slack Blocks API, providing a fluent interface for constructing Block Kit messages. Current version 1.2.3 works with Python >= 3.8.1, released occasionally with minor updates. It aims to simplify building complex Slack message layouts.
pip install slackblocks Common errors
error TypeError: Object of type SectionBlock is not JSON serializable ↓
cause Trying to serialize the Message object directly without calling its `build()` or using `**message`
fix
Use
**message when passing to slack_sdk: client.chat_postMessage(**message). Or call message.build() to get a dict. error ModuleNotFoundError: No module named 'slackblocks' ↓
cause slackblocks is not installed or installed in a different environment.
fix
Run
pip install slackblocks in your active environment. error KeyError: 'blocks' ↓
cause The Slack API requires a 'blocks' field in the payload, but Message without blocks may omit it.
fix
Always provide a
blocks parameter when constructing Message, even if empty list: blocks=[]. Warnings
gotcha `Message` does not directly send requests; it only builds the payload. You must use an HTTP client (e.g., slack_sdk) to send. ↓
fix Use `client.chat_postMessage(**message)` where `message` is a SlackBlocks Message object.
gotcha Blocks must be passed as a list to `Message`; passing a single block without list wrapping will break. ↓
fix Always wrap blocks: `blocks=[SectionBlock(...)]` even if one block.
deprecated The `channel` parameter in `Message` may be deprecated in future versions; prefer passing channel when sending via the client. ↓
fix Omit channel from Message constructor and set it in the HTTP call: `client.chat_postMessage(channel="#general", **message)`.
gotcha Text in SectionBlock must be a string, not a dict; using Block Kit object syntax incorrectly may cause errors. ↓
fix Use plain strings: `SectionBlock(text="Hello")`. For rich text, use `mrkdwn=True` or similar parameters.
Imports
- Message
from slackblocks import Message - SectionBlock
from slackblocks import SectionBlock - ImageBlock
from slackblocks import ImageBlock - DividerBlock
from slackblocks import DividerBlock - ContextBlock
from slackblocks import ContextBlock
Quickstart
import os
from slackblocks import Message, SectionBlock, ImageBlock
message = Message(
channel="#general",
text="Hello, world!",
blocks=[
SectionBlock(text="This is a section block"),
ImageBlock(image_url="https://example.com/image.png", alt_text="Example Image")
]
)
# Send via slack_sdk or similar
from slack_sdk import WebClient
client = WebClient(token=os.environ.get("SLACK_TOKEN", ""))
response = client.chat_postMessage(**message)
print(response)