Skip to main content

Automating Slack Notifications with State2Slack

·5 mins

Introduction #

State2Slack automates the posting of Slack messages based on the state of a Home Assistant entity.

It retrieves an entity’s state and maps it to a configurable Slack webhook URL, message, and optional target ID. These values are then used to send the message to Slack via a webhook request. If configured, a summary of the execution results is sent to a designated Slack webhook.

Log files track execution history and, if maintained, prevent re-execution within the same day.

Scheduled to run on weekdays, State2Slack posts a curated working location to a designated Slack channel based on my physical location.

Configuration #

Configuration is provided through a YAML file. Unless specified via command-line options, State2Slack defaults to using config.yaml.

Home Assistant #

For State2Slack to retrieve an entity’s state from Home Assistant, the following configuration must be defined.

home_assistant:
  url:              # the URL of Home Assistant
  access_token:     # the long-lived access token for authentication
  entity_id:        # the entity ID to trigger based on state
  insecure:         # (optional) true to ignore verifying the SSL certificate

Long-lived Access Tokens #

Important

The generated access token is only accessible during the creation process. Be sure to copy it correctly when presented to avoid any issues.

Go to User Profile > Security, scroll down to Long-lived access tokens, and click CREATE TOKEN. Enter a descriptive name for the token, then click OK. Finally, copy the generated access token into the designated access_token configuration field.

Home Assistant: Long-lived access tokens

Entity ID #

Tip

This demonstration uses a Person entity, as its state represents their location. The Zone integration allows you to define specific regions on a map, enabling zone-based presence detection and additional state values.

Go to Developer Tools > STATES, then use the filter to locate the desired entity ID.

Home Assistant: Entity states

Slack #

Messages are sent to Slack via webhook requests. The following sections explain how to create a webhook and explore the available configuration options.

Webhook #

To set up a new webhook-triggered workflow, navigate to More > Automations > Workflows, then click New Workflow.

Slack: New workflow

In the workflow editor, click Choose an event and select From a webhook.

To configure the webhook, click Set Up Variables and create a variable with the Key message and Data type set to Text. If the webhook will be used for multiple channels or users, add another variable with the Key target_id and the appropriate Data type. Once configured, click Continue.

Slack: From a webhook

Note

As shown in the image above, the webhook URL will be generated once you save this information. To retrieve the URL, you must edit the webhook after its creation.

Return to the workflow editor, click Add steps, and choose either Send a message to a channel or Send a message to a person.

To configure the message, choose a value for Select a channel or Select a member. If applicable, use target_id in this field. Then, add the message variable to the Add a message input and click Save.

Slack: From a webhook

Return to the workflow editor, click Finish Up, then enter a Name, Description, and set Permissions for the workflow. Finally, click Publish.

Slack: Finish Up

States #

The following configuration maps entity states to Slack message settings. The default state entry serves as the fallback when no matching entity state is found. All entity states must be defined in lowercase.

slack_states:
  ENTITY_STATE:     # the entity state value represented in lowercase
    webhook_url:    # the webhook URL for sending state messages
    message:        # the message content
    target_id:      # (optional) the target ID of the message recipient

Refer to Sample for an example configuration file supporting multiple scenarios.

Summary #

This configuration is optional, but if defined, a Slack message will be sent summarizing the automation outcomes. It is particularly useful when state-based webhooks span multiple channels or users, or those targets experience high volumes of messages.

slack_summary:
  webhook_url:    # the webhook URL for sending summary messages
  target_id:      # (optional) the target ID of the message recipient

Sample #

Below is an example configuration file using sample values.

---

home_assistant:
  url: http://homeassistant.local:8123
  access_token: RNH8w8gEFHG6PbpfM8Vcm44Jdjr72HXxaTRxZivm
  entity_id: person.demo
  insecure: true

slack_states:
  # send 'Unavailable' when no other states match
  default:
    webhook_url: https://hooks.slack.com/triggers/...
    message: Unavailable
  # send 'Working from home' when 'person.demo' is at 'home'
  home:
    webhook_url: https://hooks.slack.com/triggers/...
    message: Working from home
  # send 'In the office' to channel 'C123456789' when 'person.demo' is at 'work'
  work:
    webhook_url: https://hooks.slack.com/triggers/...
    message: In the office
    target_id: C123456789
  # skip sending a message when 'person.demo' is at 'coffee'
  coffee:

slack_summary:
  webhook_url: https://hooks.slack.com/triggers/...
  target_id: U123456789

Usage #

State2Slack is a Python project with a few dependencies listed here. Once all dependencies are installed, the automation can be executed using

python3 state2slack.py

Various command-line options are available for customizing the automation which can be viewed using

python3 state2slack.py --help

Container #

There are many advantages to running an application in a container-based environment, and State2Slack is no exception. Using Docker Compose simplifies this process. To build the container image

docker compose build

After building the container image, it can be run using

docker compose run --rm state2slack

or with command-line options

docker compose run --rm state2slack python3 state2slack.py --state work

Troubleshooting #

Enable Debugging #

To enable verbose logging, use the --verbose command-line option.

Slack Permissions #

When using a workflow to send a message to a variable Slack channel via target_id, a permissions error may occur (see image below). This happens only if the workflow has not previously posted in the channel associated with the target_id value.

To resolve this issue, temporarily modify the workflow to send a message directly to the intended channel, execute the workflow to post the message, and then revert it back to target_id. This process may need to be repeated for each channel referenced by target_id.

Slack: Channel Permissions