I want to implement Slack notifications on flow st...
# ask-community
a
I want to implement Slack notifications on flow state change that can notify/@-mention a specific Slack user, which can be different between flow runs. I see documentation for using the
slack_notifier
(https://docs.prefect.io/core/advanced_tutorials/slack-notifications.html#slack-notifications) or creating your own state handler to attach to a flow (https://docs.prefect.io/core/concepts/notifications.html#state-handlers) but don't see a straightforward way to change the Slack message based on some runtime value other than
old_state
and
new_state
. Is there any recommended way to do this? I think if there's some way for a state handler to read a Parameter value that would work for me, but not sure if that's possible.
k
Hey @Aric Huang, I don’t think you can do it with that notifier. Instead, use the SlackTask to customize the message. I suggest putting it in your state handler and then using
SlackTask(message).run()
and this will be the easiest way to fire out a message
a
@Kevin Kho OK, would that state handler look something like this:
Copy code
def post_to_slack(task, old_state, new_state):
    msg = "Task {0} is now in state {1}".format(task, new_state)
    SlackTask(msg).run()
    return new_state
And then this state handler would be attached to a flow or task?
k
Yes exactly
a
What I'm not seeing is how I could vary the message at runtime. For example if I want the person running the flow to specify who to notify when running it
For example i'd like to do something like this:
Copy code
def post_to_slack(task, old_state, new_state):
    username = <some Parameter value>
    msg = "@{username}: Task {0} finished in state {1}".format(username, task, new_state)
    SlackTask(msg).run()
    return new_state
k
You can use the Parameters in the state handler through the Prefect context. Try logging
prefect.context.get("parameters")
. I think it’s a dictionary of all the values.
a
Ahh gotcha. that sounds like it will work, will give it a try
Thank you!
👍 1