Handling Line Breaks in Home Assistant’s YAML to Send LineMessenger Push Messages (Restful Request)

In this blog post, I won't guide you step-by-step on how to configure Home Assistant to send Gmail notifications to LINE, but focusing on how to correctly handle line breaks (\n). This seemingly simple requirement can become quite challenging due to the complexities between YAML, JSON, and various APIs.

This post will focus on ensuring that line breaks are correctly displayed in LINE messages.


1. Problem Description: Handling Line Breaks in LINE API (\n)

Initially, I tried to configure Home Assistant to send Gmail content to LINE. The idea was simple: trigger an automation in Home Assistant whenever a new email arrives, and use the LINE Messaging API to send the content to LINE.

However, I kept getting the error 400 Bad Request. This error was caused by improper handling of line breaks in the message content, which made the LINE API unable to parse the JSON payload correctly.


2. Trial and Error

At first, I tried simply including \n in the message, as suggested in most documentation. However, when Home Assistant's YAML and templates processed these characters, they often over-escaped them or treated them as literal strings, resulting in incorrect JSON being sent to LINE.

I tried several approaches that were either ineffective or unsatisfactory:

  • Removing all line breaks (resulting in a single line that was difficult to read).
  • Experimenting with different YAML configurations (|, > markers) to handle multi-line strings.
  • Replacing \n with Unicode or other characters.

3. Final Solution

The solution focused on carefully using YAML markers (>), properly escaping characters, and ensuring the correct transition from templates to JSON.

Correct Configuration

automations.yaml:

We used the > marker to indicate a folded block, allowing multi-line content to be collapsed into a single line while retaining line breaks as \n in JSON.

- alias: "IMAP - Send Email Content to Line"
  description: "Trigger when an email with subject '#www-message' is received and send content to LINE Messenger"
  trigger:
    - platform: event
      event_type: imap_content
  condition:
    - condition: template
      value_template: "{{ trigger.event.data['subject'] == '#www-message' and trigger.event.data['initial'] == true }}"
  action:
    - service: rest_command.send_line_message
      data:
        message: >
          {{ trigger.event.data['text'] | replace('\r\n', '\n') | replace('\r', '\n') | replace('\n', '\n') }}
  • >: This marker folds multi-line content while ensuring line breaks are correctly passed to JSON.
  • replace('\r\n', '\n'): This ensures that any Windows-style line endings (\r\n) are converted to a single \n.

rest_commands.yaml:

We kept this part unchanged, but ensured that the text received from the automation step was correctly formatted:

rest_command:
  send_line_message:
    url: https://api.line.me/v2/bot/message/push
    method: POST
    headers:
      Authorization: !secret line_channel_access_token
      Content-Type: "application/json"
    payload: >
      {
        "to": "{{ states('input_text.line_group_id') }}",
        "messages": [
          {
            "type": "text",
            "text": "{{ message }}"
          }
        ]
      }

4. Summary

After multiple attempts, we finally found a way to correctly handle line breaks so that they can be accepted and displayed properly by the LINE API.

  • Use the YAML > marker to handle multi-line strings and ensure that line breaks remain consistent during the conversion process.
  • Use template filters to convert all line breaks to \n to ensure the final JSON format is correct.

I hope this guide helps those with similar needs to successfully configure Home Assistant and integrate it with the LINE API. If you have more questions or need additional help, feel free to leave a comment!

Facebook 留言

Posted in R&D.

Leave a Reply

Your email address will not be published. Required fields are marked *