Prefect Slack Integration

0.3.1 · active · verified Thu Apr 16

The `prefect-slack` library provides official integrations for connecting Prefect 2.x workflows with Slack. It enables sending notifications and messages to Slack channels using webhooks or bot tokens, typically via Prefect Blocks. The current stable version is `0.3.1`, and it's part of the PrefectHQ monorepo, with releases often following the Prefect core library's major versions, though `prefect-slack` `0.3.1` is specifically for Prefect `2.x`.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to send a simple Slack notification from a Prefect flow using the `SlackWebhook` block. It requires a Slack incoming webhook URL, which should be set as an environment variable (`SLACK_WEBHOOK_URL`) for secure handling of credentials. In a production environment, it's recommended to create and save `SlackWebhook` blocks via the Prefect UI or API to reuse them across multiple flows and deployments.

import os
from prefect import flow
from prefect_slack.webhooks import SlackWebhook

@flow(log_prints=True)
def send_slack_notification_flow(message: str = "Hello from Prefect!"):
    """Sends a custom message to Slack via a configured webhook."""
    # Retrieve Slack Webhook URL from environment variables or Prefect secrets
    slack_webhook_url = os.environ.get("SLACK_WEBHOOK_URL", "")
    if not slack_webhook_url:
        print("Warning: SLACK_WEBHOOK_URL environment variable is not set. Skipping Slack notification.")
        return

    # Initialize the SlackWebhook block with the URL
    # For production, consider creating and storing this block in the Prefect UI/API
    # and loading it via await SlackWebhook.load("my-slack-webhook-block")
    webhook_block = SlackWebhook(url=slack_webhook_url)
    
    # Send the notification
    webhook_block.notify(body=message)
    print(f"Successfully sent Slack notification: {message}")

if __name__ == "__main__":
    # To run this example, set the SLACK_WEBHOOK_URL environment variable:
    # export SLACK_WEBHOOK_URL="https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX"
    send_slack_notification_flow(message="This is a test notification from my Prefect flow!")

view raw JSON →