<@ULVA73B9P> How can I enable slack notifications ...
# ask-marvin
d
@Marvin How can I enable slack notifications to notify me if a flow run fails or enters completed state
m
To enable Slack notifications in Prefect for flow run state changes, follow these steps: 1. Configure Notifications in Prefect Cloud: - Go to the Notifications page and select "Create Notification". - Choose the run states that should trigger a notification (e.g., "failed" or "completed"). - Specify the tags to filter which flow runs are covered by the notification. - For Slack notifications, you need Slack webhook credentials and the channel to which the message is sent. - For example, to get a Slack message if a flow with a
daily-etl
tag fails:
Copy code
If a run of any flow with daily-etl tag enters a failed state, send a notification to my-slack-webhook
More details can be found in the Prefect documentation. 2. Using State Change Hooks: - State change hooks allow you to execute code in response to changes in flow or task run states. - You can define custom actions for specific states, such as sending a Slack notification when a flow run fails or completes. Here is a simple example of setting up a state change hook to send a Slack notification using Python:
Copy code
python
from prefect import flow, task
from prefect.engine.state import Failed, Completed
import requests

# Define your Slack webhook URL and channel
SLACK_WEBHOOK_URL = "<https://hooks.slack.com/services/your/webhook/url>"
CHANNEL = "#your-channel"

def send_slack_message(message: str):
    payload = {
        "channel": CHANNEL,
        "text": message
    }
    <http://requests.post|requests.post>(SLACK_WEBHOOK_URL, json=payload)

@task
def process_data():
    # Your task logic
    pass

@flow
def my_flow():
    process_data()

# Define your state change hooks
def notify_on_failure(state):
    if isinstance(state, Failed):
        send_slack_message("Flow run failed!")

def notify_on_completion(state):
    if isinstance(state, Completed):
        send_slack_message("Flow run completed!")

# Attach hooks to your flow
my_flow.set_state_change_hooks([notify_on_failure, notify_on_completion])

if __name__ == "__main__":
    my_flow()
For more details, check out the Prefect documentation on state change hooks. If you have any further questions or encounter issues, refer to the Prefect support page, or feel free to ask. Oh, the joy of being helpful. One more task awaits me, I'm sure.