Skip to content

Blocks

Blocks are a series of container components that can be combined to create rich and interactive messages.

See: https://api.slack.com/reference/block-kit/blocks.

ActionsBlock

A Block that is used to hold interactive elements (normally for users to interface with).

Parameters:

Name Type Description Default
elements Optional[List[Element]]

a list of Elements (up to a maximum of 25).

None
block_id Optional[str]

you can use this field to provide a deterministic identifier for the block.

None
Throws

InvalidUsageError: if any of the items in elements are invalid.

Source code in slackblocks/blocks.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
class ActionsBlock(Block):
    """
    A `Block` that is used to hold interactive elements (normally for users to interface with).

    Args:
        elements: a list of [Elements](/reference/elements) (up to a maximum of 25).
        block_id: you can use this field to provide a deterministic identifier for the block.

    Throws:
        InvalidUsageError: if any of the items in `elements` are invalid.
    """

    def __init__(
        self,
        elements: Optional[List[Element]] = None,
        block_id: Optional[str] = None,
    ) -> "ActionsBlock":
        super().__init__(type_=BlockType.ACTIONS, block_id=block_id)
        self.elements = coerce_to_list(
            elements, (Element), allow_none=True, max_size=25
        )

    def _resolve(self):
        actions = self._attributes()
        actions["elements"] = [element._resolve() for element in self.elements]
        return actions

ContextBlock

A ContextBlock displays contextul message info, including both images and text.

Parameters:

Name Type Description Default
elements Optional[List[Union[Element, CompositionObject]]]

a list of Text objects and Image elements.

None
block_id Optional[str]

you can use this field to provide a deterministic identifier for the block.

None
Throws

InvalidUsageError: when items in elements are not Text or Image or exceed 10 items.

Source code in slackblocks/blocks.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
class ContextBlock(Block):
    """
    A `ContextBlock` displays contextul message info, including both images and text.

    Args:
        elements: a list of `Text` objects and `Image` elements.
        block_id: you can use this field to provide a deterministic identifier for the block.

    Throws:
        InvalidUsageError: when items in `elements` are not `Text` or `Image` or exceed 10 items.
    """

    def __init__(
        self,
        elements: Optional[List[Union[Element, CompositionObject]]] = None,
        block_id: Optional[str] = None,
    ) -> "ContextBlock":
        super().__init__(type_=BlockType.CONTEXT, block_id=block_id)
        self.elements = []
        for element in elements:
            if (
                element.type == CompositionObjectType.TEXT
                or element.type == ElementType.IMAGE
            ):
                self.elements.append(element)
            else:
                raise InvalidUsageError(
                    f"Context blocks can only hold image and text elements, not {element.type}"
                )
        if len(self.elements) > 10:
            raise InvalidUsageError("Context blocks can hold a maximum of ten elements")

    def _resolve(self) -> Dict[str, any]:
        context = self._attributes()
        context["elements"] = [element._resolve() for element in self.elements]
        return context

DividerBlock

A content divider, like an <hr> in HTML, to split up different blocks inside of a message.

Parameters:

Name Type Description Default
block_id Optional[str]

you can use this field to provide a deterministic identifier for the block.

None
Source code in slackblocks/blocks.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
class DividerBlock(Block):
    """
    A content divider, like an `<hr>` in HTML, to split up different blocks inside of
    a message.

    Args:
        block_id: you can use this field to provide a deterministic identifier for the block.
    """

    def __init__(self, block_id: Optional[str] = None) -> "DividerBlock":
        super().__init__(type_=BlockType.DIVIDER, block_id=block_id)

    def _resolve(self):
        return self._attributes()

FileBlock

Displays a remote file (e.g. a PDF).

For details on how remote files are exposed to Slack, see https://api.slack.com/messaging/files#adding.

Parameters:

Name Type Description Default
external_id str

the ID assigned to the remote file when it was added to Slack.

required
block_id Optional[str]

you can use this field to provide a deterministic identifier for the block.

required
source str

always "remote" as per the Slack API (may change in the future).

'remote'
Source code in slackblocks/blocks.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
class FileBlock(Block):
    """
    Displays a remote file (e.g. a PDF).

    For details on how remote files are exposed to Slack, see
    <https://api.slack.com/messaging/files#adding>.

    Args:
        external_id: the ID assigned to the remote file when it was added to Slack.
        block_id: you can use this field to provide a deterministic identifier for the block.
        source: always "remote" as per the Slack API (may change in the future).
    """

    def __init__(
        self, external_id: str, block_id: Optional[str], source: str = "remote"
    ) -> "FileBlock":
        super().__init__(type_=BlockType.FILE, block_id=block_id)
        self.external_id = external_id
        self.source = source

    def _resolve(self) -> Dict[str, any]:
        file = self._attributes()
        file["external_id"] = self.external_id
        file["source"] = self.source
        return file

HeaderBlock

A Header Block is a plain-text block that displays in a larger, bold font.

Parameters:

Name Type Description Default
text Union[str, Text]

the text that will be rendered as a heading.

required
block_id Optional[str]

you can use this field to provide a deterministic identifier for the block.

None
Source code in slackblocks/blocks.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
class HeaderBlock(Block):
    """
    A Header Block is a plain-text block that displays in a larger, bold font.

    Args:
        text: the text that will be rendered as a heading.
        block_id: you can use this field to provide a deterministic identifier for the block.
    """

    def __init__(
        self, text: Union[str, Text], block_id: Optional[str] = None
    ) -> "HeaderBlock":
        super().__init__(type_=BlockType.HEADER, block_id=block_id)
        if type(text) is Text:
            self.text = text
        else:
            self.text = Text(text, type_=TextType.PLAINTEXT, verbatim=False)

    def _resolve(self) -> Dict[str, any]:
        header = self._attributes()
        header["text"] = self.text._resolve()
        return header

ImageBlock

An Image Block contains a single graphic, accessed by URL.

Parameters:

Name Type Description Default
image_url str

the URL pointing to the image file you want to display.

required
alt_text Optional[str]

alternative text for accessibility purposes and when the image fails to load.

' '
title Optional[Union[Text, str]]

an optional text title to be presented with the image.

None
block_id Optional[str]

you can use this field to provide a deterministic identifier for the block.

None
Throws

InvalidUsageError: when one or more of the provided args fails validation.

Source code in slackblocks/blocks.py
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
class ImageBlock(Block):
    """
    An Image Block contains a single graphic, accessed by URL.

    Args:
        image_url: the URL pointing to the image file you want to display.
        alt_text: alternative text for accessibility purposes and when the image fails to load.
        title: an optional text title to be presented with the image.
        block_id: you can use this field to provide a deterministic identifier for the block.

    Throws:
        InvalidUsageError: when one or more of the provided args fails validation.
    """

    def __init__(
        self,
        image_url: str,
        alt_text: Optional[str] = " ",
        title: Optional[Union[Text, str]] = None,
        block_id: Optional[str] = None,
    ) -> "ImageBlock":
        super().__init__(type_=BlockType.IMAGE, block_id=block_id)
        self.image_url = validate_string(
            string=image_url,
            field_name="title",
            max_length=3000,
        )
        self.alt_text = validate_string(
            alt_text, field_name="alt_text", max_length=2000
        )
        if title and isinstance(title, Text):
            if title.text_type == TextType.MARKDOWN:
                # Coerce title into plaintext
                self.title = Text(
                    text=title.text,
                    type_=TextType.PLAINTEXT,
                    emoji=title.emoji,
                    verbatim=title.verbatim,
                )
            else:
                self.title = title
        elif isinstance(title, str):
            self.title = Text(text=title, type_=TextType.PLAINTEXT)

    def _resolve(self) -> Dict[str, Any]:
        image = self._attributes()
        image["image_url"] = self.image_url
        if self.alt_text:
            image["alt_text"] = self.alt_text
        if self.title:
            image["title"] = self.title._resolve()
        return image

InputBlock

A block that collects information from users - it can hold a plain-text input element, a checkbox element, a radio button element, a select menu element, a multi-select menu element, or a datepicker.

Parameters:

Name Type Description Default
label TextLike

the name which identifies the input field.

required
element Element

an interactive Element (e.g. a text field).

required
dispatch_action bool

whether the Element should trigger the sending of a block_actions payload.

False
block_id Optional[str]

you can use this field to provide a deterministic identifier for the block.

None
hint Optional[TextLike]

an optional additional guide on what input the user should prodive.

None
optional bool

whether this input field may be empty when the user submits e.g. the modal.

False
Throws

InvalidUsageError: when any of the provided arguments fail validation.

Source code in slackblocks/blocks.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
class InputBlock(Block):
    """
    A block that collects information from users - it can hold a plain-text
    input element, a checkbox element, a radio button element, a select
    menu element, a multi-select menu element, or a datepicker.

    Args:
        label: the name which identifies the input field.
        element: an interactive [Element](/reference/elements) (e.g. a text field).
        dispatch_action: whether the [Element](/reference/elements) should trigger the
            sending of a `block_actions` payload.
        block_id: you can use this field to provide a deterministic identifier for the block.
        hint: an optional additional guide on what input the user should prodive.
        optional: whether this input field may be empty when the user submits e.g. the modal.

    Throws:
        InvalidUsageError: when any of the provided arguments fail validation.
    """

    def __init__(
        self,
        label: TextLike,
        element: Element,
        dispatch_action: bool = False,
        block_id: Optional[str] = None,
        hint: Optional[TextLike] = None,
        optional: bool = False,
    ) -> "InputBlock":
        super().__init__(type_=BlockType.INPUT, block_id=block_id)
        self.label = Text.to_text(
            label, force_plaintext=True, max_length=2000, allow_none=False
        )
        if not isinstance(element, ALLOWED_INPUT_ELEMENTS):
            raise InvalidUsageError("")
        self.element = element
        self.dispatch_action = dispatch_action
        self.hint = Text.to_text(
            hint, force_plaintext=True, max_length=2000, allow_none=True
        )
        self.optional = optional

    def _resolve(self) -> Dict[str, Any]:
        input_block = self._attributes()
        input_block["label"] = self.label._resolve()
        input_block["element"] = self.element._resolve()
        if self.hint:
            input_block["hint"] = self.hint._resolve()
        if self.dispatch_action:
            input_block["dispatch_action"] = self.dispatch_action
        if self.optional:
            input_block["optional"] = self.optional
        return input_block

RichTextBlock

A RichTextBlock is used to provide easier rich text formatting than standard markdown text (e.g. in a SectionBlock) and access to text formatting features not available in traditional markdown (e.g. strikethrough). See the various rich text elements you can include here.

Parameters:

Name Type Description Default
elements Union[RichTextObject, List[RichTextObject]]

a single rich text element or a list of those elements.

required
block_id Optional[str]

you can use this field to provide a deterministic identifier for the block.

None
Throws

InvalidUsageError: if the elements in elements are not valid rich text elements.

Source code in slackblocks/blocks.py
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
class RichTextBlock(Block):
    """
    A RichTextBlock is used to provide easier rich text formatting
        than standard markdown text (e.g. in a
        [`SectionBlock`](/reference/blocks/#blocks.SectionBlock))
        and access to text formatting features not available in traditional
        markdown (e.g. strikethrough). See the various rich text elements
        you can include [here](/reference/rich_text).

    Args:
        elements: a single [rich text element](../../reference/rich_text)
            or a list of those elements.
        block_id: you can use this field to provide a deterministic identifier
            for the block.

    Throws:
        InvalidUsageError: if the elements in `elements` are not valid rich
            text elements.
    """

    def __init__(
        self,
        elements: Union[RichTextObject, List[RichTextObject]],
        block_id: Optional[str] = None,
    ) -> "RichTextBlock":
        super().__init__(type_=BlockType.RICH_TEXT, block_id=block_id)
        self.elements = coerce_to_list(
            elements,
            (
                RichTextList,
                RichTextCodeBlock,
                RichTextQuote,
                RichTextSection,
            ),
            min_size=1,
        )

    def _resolve(self) -> Dict[str, Any]:
        rich_text_block = self._attributes()
        rich_text_block["elements"] = [element._resolve() for element in self.elements]
        return rich_text_block

SectionBlock

A section is one of the most flexible blocks available - it can be used as a simple text block, or with any of the available block elements.

Section blocks can also optionally be given an "accessory," which is typically one of the interactive Elements.

Parameters:

Name Type Description Default
text Optional[TextLike]

text to include in the block. Can be a string or Text object (of either mrkdwn or plaintext variety). Defaults to markdown if unspecified. One of either text or fields must be provided.

None
block_id Optional[str]

you can use this field to provide a deterministic identifier for the block.

None
fields Optional[Union[TextLike, List[TextLike]]]

a list of text objects. One of either text or fields must be provided.

None
accessory Optional[Element]

an optional Element object that will take a secondary place in the block (after or to the side of text or fields).

None
Throws

InvalidUsageError: if any of the provided arguments fail validation checks.

Source code in slackblocks/blocks.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
class SectionBlock(Block):
    """
    A section is one of the most flexible blocks available -
    it can be used as a simple text block, or with any of the
    available block elements.

    Section blocks can also optionally be given an "accessory,"
    which is typically one of the interactive [Elements](/reference/elements).

    Args:
        text: text to include in the block. Can be a string or `Text` object (of either
            `mrkdwn` or `plaintext` variety). Defaults to markdown if unspecified. One of either
            `text` or `fields` must be provided.
        block_id: you can use this field to provide a deterministic identifier for the block.
        fields: a list of text objects. One of either `text` or `fields` must be provided.
        accessory: an optional [Element](/reference/elements) object that will take a
            secondary place in the block (after or to the side of  `text` or `fields`).

    Throws:
        InvalidUsageError: if any of the provided arguments fail validation checks.
    """

    def __init__(
        self,
        text: Optional[TextLike] = None,
        block_id: Optional[str] = None,
        fields: Optional[Union[TextLike, List[TextLike]]] = None,
        accessory: Optional[Element] = None,
    ) -> "SectionBlock":
        super().__init__(type_=BlockType.SECTION, block_id=block_id)
        if not text and not fields:
            raise InvalidUsageError(
                "Must supply either `text` or `fields` or `both` to SectionBlock."
            )
        self.text = Text.to_text(text, max_length=3000, allow_none=True)
        self.fields = coerce_to_list(
            (
                [
                    Text.to_text(field, max_length=2000, allow_none=False)
                    for field in coerce_to_list(
                        fields, class_=(str, Text), allow_none=True
                    )
                ]
                if fields
                else None
            ),
            class_=Text,
            allow_none=True,
            max_size=10,
        )

        self.accessory = accessory

    def _resolve(self) -> Dict[str, Any]:
        section = self._attributes()
        if self.text:
            section["text"] = self.text._resolve()
        if self.fields:
            section["fields"] = [field._resolve() for field in self.fields]
        if self.accessory:
            section["accessory"] = self.accessory._resolve()
        return section