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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
class ActionsBlock(Block):
    """
    A `Block` that is used to hold interactive elements (normally for users to interface with).

    Args:
        elements: a list of [Elements](/slackblocks/latest/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,
    ) -> None:
        super().__init__(type_=BlockType.ACTIONS, block_id=block_id)
        self.elements: Optional[List[Element]] = 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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
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,
    ) -> None:
        super().__init__(type_=BlockType.CONTEXT, block_id=block_id)
        self.elements = []
        if elements is not None:
            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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
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) -> None:
        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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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"
    ) -> None:
        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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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) -> None:
        super().__init__(type_=BlockType.HEADER, block_id=block_id)
        if type(text) is Text:
            self.text = text
        else:
            self.text = Text.to_text_nonnull(text=text, force_plaintext=True)

    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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
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,
    ) -> None:
        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
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
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](/slackblocks/latest/reference/elements)
            (e.g. a text field).
        dispatch_action: whether the [Element](/slackblocks/latest/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,
    ) -> None:
        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(
                f"InputBlocks can only hold elements of type: {ALLOWED_INPUT_ELEMENTS}"
            )
        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()
        if self.label is not None:
            input_block["label"] = self.label._resolve()
        if self.element is not None:
            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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
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
class RichTextBlock(Block):
    """
    A RichTextBlock is used to provide easier rich text formatting
        than standard markdown text (e.g. in a
        [`SectionBlock`](/slackblocks/latest/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](/slackblocks/latest/reference/rich_text).

    Args:
        elements: a single [rich text element](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,
    ) -> None:
        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: Dict[str, Any] = self._attributes()
        if self.elements is not None:
            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
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
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](/slackblocks/latest/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](/slackblocks/latest/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,
    ) -> None:
        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: Optional[List[Text]]
        if fields is not None:
            field_list: List[Union[str, Text]] = coerce_to_list_nonnull(
                fields, class_=(str, Text)
            )
            self.fields = [
                Text.to_text_nonnull(field, max_length=2000)
                for field in field_list
                if field is not None
            ]
            if len(self.fields) > 10:
                raise InvalidUsageError(
                    "Section blocks can hold a maximum of ten fields"
                )
        else:
            self.fields = None

        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 isinstance(field, Text)
            ]
        if self.accessory:
            section["accessory"] = self.accessory._resolve()
        return section

TableBlock

A TableBlock displays data in a table format.

Parameters:

Name Type Description Default
rows List[List[Union[RawText, RichTextObject]]]

a list of lists of RawText or RichTextObject objects.

required
column_settings Optional[List[ColumnSettings]]

a list of ColumnSettings objects.

None
block_id Optional[str]

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

None
Throws

InvalidUsageError: when items in rows are not RawText or RichTextObject objects. InvalidUsageError: when the number of column_settings does not match the number of columns in each row. InvalidUsageError: when the number of rows is greater than 100. InvalidUsageError: when the number of columns in a row is greater than 20. InvalidUsageError: when the number of column_settings is greater than 20.

Source code in slackblocks/blocks.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
class TableBlock(Block):
    """
    A `TableBlock` displays data in a table format.

    Args:
        rows: a list of lists of `RawText` or `RichTextObject` objects.
        column_settings: a list of `ColumnSettings` objects.
        block_id: you can use this field to provide a deterministic identifier for the block.

    Throws:
        InvalidUsageError: when items in `rows` are not `RawText` or `RichTextObject` objects.
        InvalidUsageError: when the number of column_settings does not match the number of 
            columns in each row.
        InvalidUsageError: when the number of rows is greater than 100.
        InvalidUsageError: when the number of columns in a row is greater than 20.
        InvalidUsageError: when the number of column_settings is greater than 20.
    """

    def __init__(
        self,
        rows: List[List[Union[RawText, RichTextObject]]],
        column_settings: Optional[List[ColumnSettings]] = None,
        block_id: Optional[str] = None,
    ) -> None:
        super().__init__(type_=BlockType.TABLE, block_id=block_id)
        # Validate that there is at least one row
        if len(rows) < 1:
            raise InvalidUsageError("`rows` must have at least one row.")
        # If column_settings are provided, make sure each row has the same number of elements
        num_columns = len(rows[0])
        for row in rows:
            if len(row) != num_columns:
                raise InvalidUsageError(
                    "All rows must have the same number of columns."
                )
        if column_settings is not None:
            if num_columns != len(column_settings):
                raise InvalidUsageError(
                    f"Number of column_settings ({len(column_settings)}) must"
                    f"match number of columns in each row ({num_columns})."
                )
        if len(rows) > 100:
            raise InvalidUsageError("`rows` can have a maximum of 100 items.")
        for row in rows:
            if len(row) > 20:
                raise InvalidUsageError("Each row can have a maximum of 20 cells.")
        # Validate each cell is an allowed type
        self.rows = []
        for row in rows:
            validated_row = []
            for cell in row:
                # Validate cell type
                if not isinstance(cell, ALLOWED_TABLE_CELL_ELEMENTS):
                    raise InvalidUsageError(
                        f"Table cells must be one of {ALLOWED_TABLE_CELL_ELEMENTS}"
                    )
                validated_row.append(cell)
            self.rows.append(validated_row)
        if column_settings and len(column_settings) > 20:
            raise InvalidUsageError("`column_settings` can have a maximum of 20 items.")
        self.column_settings = column_settings

    def _resolve(self) -> Dict[str, Any]:
        table = self._attributes()
        table["rows"] = [
            [self._resolve_cell(cell) for cell in row] for row in self.rows
        ]
        if self.column_settings:
            table["column_settings"] = [
                setting._resolve() for setting in self.column_settings
            ]
        return table

    def _resolve_cell(self, cell: Union[RawText, RichTextObject]) -> Dict[str, Any]:
        """
        Resolve a table cell to its JSON representation.

        RawText cells are resolved directly.
        RichTextObject cells are wrapped in a rich_text structure.
        """
        if isinstance(cell, RawText):
            return cell._resolve()
        else:
            # Wrap RichTextObject in rich_text structure
            return {"type": "rich_text", "elements": [cell._resolve()]}

_resolve_cell

_resolve_cell(cell)

Resolve a table cell to its JSON representation.

RawText cells are resolved directly. RichTextObject cells are wrapped in a rich_text structure.

Source code in slackblocks/blocks.py
564
565
566
567
568
569
570
571
572
573
574
575
def _resolve_cell(self, cell: Union[RawText, RichTextObject]) -> Dict[str, Any]:
    """
    Resolve a table cell to its JSON representation.

    RawText cells are resolved directly.
    RichTextObject cells are wrapped in a rich_text structure.
    """
    if isinstance(cell, RawText):
        return cell._resolve()
    else:
        # Wrap RichTextObject in rich_text structure
        return {"type": "rich_text", "elements": [cell._resolve()]}