Slack API Operators

Introduction

Slack API operators can post text messages or send files to specified Slack channel(s).

SlackAPIPostOperator

Use the SlackAPIPostOperator to post messages to a Slack channel.

Using the Operator

You could send simple text message

tests/system/providers/slack/example_slack.py[source]

slack_operator_post_text = SlackAPIPostOperator(
    task_id="slack_post_text",
    channel=SLACK_CHANNEL,
    text=(
        "Apache Airflow™ is an open-source platform for developing, "
        "scheduling, and monitoring batch-oriented workflows."
    ),
)

Or you could use Block Kit for create app layouts

tests/system/providers/slack/example_slack.py[source]

slack_operator_post_blocks = SlackAPIPostOperator(
    task_id="slack_post_blocks",
    channel=SLACK_CHANNEL,
    blocks=[
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": (
                    "*<https://github.com/apache/airflow|Apache Airflow™>* "
                    "is an open-source platform for developing, scheduling, "
                    "and monitoring batch-oriented workflows."
                ),
            },
            "accessory": {"type": "image", "image_url": IMAGE_URL, "alt_text": "Pinwheel"},
        }
    ],
    text="Fallback message",
)

SlackAPIFileOperator

Use the SlackAPIFileOperator to send files to a Slack channel(s).

Using the Operator

Note

Operator supports two methods for upload files, which controlled by method_version, by default it use Slack SDK method upload_files however this might impact a performance and cause random API errors. It is recommended to switch to Slack SDK method upload_files_v2 by set v2 to method_version, however this action required to add additional scope to your application:

  • files:write - for write files.

  • files:read - for read files (not required if you use Slack SDK >= 3.23.0).

  • channels:read - get list of public channels, for convert Channel Name to Channel ID.

  • groups:read - get list of private channels, for convert Channel Name to Channel ID

  • mpim:read - additional permission for API method conversations.list

  • im:read - additional permission for API method conversations.list

You could send file attachment by specifying file path

tests/system/providers/slack/example_slack.py[source]

    slack_operator_file = SlackAPIFileOperator(
        task_id="slack_file_upload_1",
        channels=SLACK_CHANNEL,
        filename="/files/dags/test.txt",
        filetype="txt",
    )

Or by directly providing file contents

tests/system/providers/slack/example_slack.py[source]

    slack_operator_file_content = SlackAPIFileOperator(
        task_id="slack_file_upload_2",
        channels=SLACK_CHANNEL,
        content="file content in txt",
        method_version="v2",
    )

Was this entry helpful?