Send telegrams with important hassio 'persistent notifications'

Posting here in case somebody needs something similar:

Having this in hassio…

How to get informed on your phone?:

First I created a log file that saves every persistent notification that creates home assistatn to a log file. This is taken from VDRainer from here:

That is not needed. I did that to have a record with all notification events, which is always nice to have.

I use splitted configuration files to keep codes organized so, adapt for your case:

###/notify/notify_files.yaml
- name: persistent_notification_to_log
  platform: file
  filename: persistent_notify.log

…and for the automation that saves the file:

###/automations/automations_global.yaml
### PERSISTENT NOTIFICATION TO FILE:
- id: 'save_my_persistent_notifications_to_file_0937700372861'
  alias: Save my persistent notification to file
  trigger:
    - platform: event
      event_type: call_service
      event_data:
        domain: persistent_notification
        service: create
  action:
    - service: notify.persistent_notification_to_log
      data_template:
        message: >
          {{ now().strftime('%Y-%m-%d %H:%M:%S') }}
          {{ trigger.event.data.service_data.title }} /
          {{ trigger.event.data.service_data.message }}

I added an automated process that trims the log file daily to a maximun of 200 lines of text:

###shell_commands/shell_commands_global.yaml
trim_to_200_lines_the_persistent_notifications_log: ssh [email protected] -p 22 -o StrictHostKeyChecking=no -i /my_keyfile 'MYTMP=$(tail -n 5 /usr/share/hassio/homeassistant/persistent_notify.log 2>/dev/null) && echo "${MYTMP}" > /usr/share/hassio/homeassistant/persistent_notify.log'

(note: for my shell commands from hassio, I use to do an ssh out to self linux to take adventages of my already configured paths, commands, etc that’s because I always have had many problems when using the hassio internal shell directly. Not sure if it is a good way of executing commands, but that’s what works for me. Of course you have to check that you can ssh from hassio terminal to your native shell to execute the command (accept keys, etc, of first login).

…now the automation to trim the log daily a t 13:39:43 :crazy_face:

###/automations/automations_global.yaml
- id: 'trim_to_200_lines_daily_the_persistent_notifications_log_2336478374673'
  alias: Trim to 200 lines daily the persistent notifications log
  trigger:
    platform: time
    at: '13:39:43'
  action:
    service: shell_command.trim_to_200_lines_the_persistent_notifications_log

(You can start here for only the telegram part)…now the automation that sends a telegram when a persistent notification, containing a matching string, is received:

###/automations/automations_assistants.yaml
- id: 'send_telegram_when_alexa_authorization_is_needed_3562223673560'
  alias: Send telegram when Alexa authorization is needed
  trigger:
    - platform: event
      event_type: call_service
      event_data:
        domain: persistent_notification
        service: create
  condition:
    ### CHECKS IF THE NOTIFICATION IS FOR AUTHORIZING AN ALEXA DEVICE:
    condition: template
    value_template: >
      {{ 'Reauthenticate' in trigger.event.data.service_data.message }}
  action:
    - service: notify.telegrams_to_myself
      data:
        message: "Alert!. Notification at hassio to re-authorize Alexa, today at {{ now().strftime('%H:%M') }}"

Important thing to have in mind is that the text to be triggered from the persistent notification (‘Reauthenticate’ text in my case for alexa notification) MUST be part of the body of the notification (the small characters), not the bigger font of the title. That’s important because if you search for a string in the title, it will never trigger the alert. It doesn’t have to be just one word… it could be more like ‘Reauthenticate on the Integrations page’.

…of course, you need the notify service for telegram already configured, something like:

###/configuration.yaml
telegram_bot:
  - platform: polling
    parse_mode: html
    api_key: 9876543210987654321abcdefghijklmnopqrstuvw
    allowed_chat_ids:
      - 123456789

and the notify entry:

###/notify/notify_telegram.yaml
- name: telegrams_to_myself
  platform: telegram
  chat_id: 123456789

Configuration → server_controls → Check_configuration button and → if green ok, then → restart_server.

You don’t have to wait for an Alexa authorize message to see if your automation triggers the text string you configured… you could just test with:

Developer Tools → Services → Service: persistent_notification.create → and paste this code to simulate an alexa authorization notification request:

###paste it in the service data field:
{
  "title": "Sample notification",
  "message": "test... Reauthenticate on the Integrations"
}

…and press CALL SERVICE button.

If everything went well, you will see that you phone receives a telegram notification of the alexa addon event.
Hope it helps somebody.

1 Like

This is really great. I moving from Homey to HA and what I am really missing is a notification timeline with only items that you find important to notify. Is there also may be a nice Lovelace card to present this?

Hi, i know this is an old post, but can you please help me make this work?

I have never - as in ever - done coding in raw yaml directly in home assistant, so i’m quite confused.
I directly copied your code into my automation.yaml file in the config folder and it throws a lot of errors that im not sure what to do with.

Is it not possible for me to directly copy what you posted?

Hi, i know this is an old post, but can you please help me make this work?

I have never - as in ever - done coding in raw yaml directly in home assistant, so i’m quite confused.
I directly copied your code into my automation.yaml file in the config folder and it throws a lot of errors that im not sure what to do with.

Is it not possible for me to directly copy what you posted?

Sure. Wow!, I have been re-reading my old post, and noticed many things has changed in HA from the day I write down that procedure. ‘Notify’, completely… and ‘file’ platform has changed and now can not be setup from the yaml files, only from ‘devices & services’ GUI… so, forget about almost everything in my open post.

Ok, let’s keep it as simple as we can.

I have check with this new automation, and is working. I have created this simple automation to check if things work:

### FORWARD WITH A TELEGRAM IN CASE THERE IS A FAILED LOGIN ATTEMPT IN HA:
- id: 'send_telegram_when_login_attempt_failed_3562223673560'
  alias: send telegram when login attempt failed
  trigger:
    - platform: persistent_notification
      update_type: added
  condition:
    - condition: template
      value_template: "{{ 'invalid authentication' in trigger.notification.message }}"
  action:
    - service: telegram_bot.send_message
      data:
        target: '123456789'
        message: "Alert!. Somebody tried to log in your homeassistant"

Of course… are you using telegram to send messages?. Do you have a valid configuration of telegram in your home assistant?, …with a valid chat_id (which is the nine digits number in target field, etc).

If not. You need first to setup telegram. Or if you are using a different notification service, we could try to create the action with that service.

To check if this automation works, you need to logout of your home assistant instance:

…and then, try to login with a wrong password. That will generate a persistent notification:

2024-10-26_163343

…as you have seen, I set in my automation a condition that when in a persistent notification appears the words ‘invalid authentication’ (as you can see in the previous screen capture), it triggers and run the action (send telegram).

If the automation is working, you should receive a telegram message alerting of that, each time you try to login with a wrong password.

Let me know if that works…

Thanks for the write up!

Is it possible to get a notification for every persistent notification?
I don’t use Telegram, but i use Discord, can that be used? Else i think i can do a notification directly from HA to my iphone.

Yes. The whole point of HA is that all the parts are independant. You can swap out anything.

Swap the telegram_bot. service call with the relevant one for your Discord notify. service.

Yes, remove the condition from example above.

Yes. Just remove the condition part, and HA will send the alert with every persistent notification.

Yes. Both.

I also use the notifications send to my HA companion app. I even send voice notifications so I don’t even need to turn on the phone to know whats going on.

The automation to send alerts to the phone via HA app will be something like:

### FORWARD EVERY PERSISTENT NOTIFICATION TO PHONE:
- id: 'forward_all_persistent_notifications_to_mobile_5778233477123'
  alias: Forward all persistent notifications to mobile
  trigger:
    - platform: persistent_notification
      update_type: added
  action:
    - service: notify.mobile_app_matiasphone
      data:
        title: New persistent notification
        message: "{{ trigger.notification.title }} {{ now().strftime('%d %b %Y') }} at {{ now().strftime('%H:%M') }}"

Of course, you have to change the ‘matiasphone’ string with your iPhone name. It’s the name of your iPhone in settings → General → about.

Check first paragraph here:
Introduction | Home Assistant Companion Docs

To test it… just logout your home assistant instance on your computer and try to login with a wrong password. That creates a persistent notification immediately, so you should receive a message on your phone if it works.

You can also include the complete persistent notification body text with ‘trigger.notification.message’, instead of only _title as in my example.

As a bonus, here I paste you (just for reference) some action I have configured to HEAR a voice message on my android phone with certain notifications thanks to the companion app. Not sure if it is the same syntax for iPhones:

[...]
    - service: notify.mobile_app_galaxy_a22
      data:
        message: "TTS"
        data:
          ttl: 0
          priority: high
          media_stream: "notify_stream"
          tts_text: "Treadmill has been switched off"

I even stop music on the phone before text-to-speech is told, and let it continue when the voice notificacion ends, but I have remove those steps to keep the example simple.

You said you also use Discord… I don’t…, but I’m reading it has been integrated too:
Check this page for configuration and examples. Just swap the lines with your Discord config on my example if you prefer Discord againts the companion app:
Discord - Home Assistant

Hope it helps!.

1 Like

First: Thank you once again for a very descriptive answer!

I haven’t tried any kind of voice notification or TTS, because i’m a bit sensitive to sounds, so i’d rather do text.

It seems like it’s working! I was also looking at logging the notifications, so i’ll have a history of them - that was the only reason for integrating it with Discord, which i didn’t have success with. Anyway, i’d much rather have a textfile with all notifications saved. Can you help me with something like that?

Thanks for the TTS example! :slight_smile:

https://www.home-assistant.io/integrations/file#notifications

You need to add ‘File’ integration at system → Devices & Services → ADD INTEGRATION → search ‘file’. Add it.

Previous to anything, you need to have a directory inside ‘www’ directory of Home Assistant (it’s a generic easily reachable folder)… for this example, called ‘my_logs’, like:
/homeassistant/www/my_logs/
or
/config/www/my_logs/

Add a new entry at File integration to save notifications, like:
Device & services → File → ADD ENTRY → Setup a notification service →

File path: /config/www/my_logs/my_persistent_notifications.txt
Time stamp: disable
SUBMIT → Success

The name of the service is set by default to ‘file’ which will make that in the next automation we will have to call a service called ‘notify.file’. I DON’T LIKE THAT!. It is not descriptive, and will be a mess if we add multiple entries in the future in the File integration. So, at the Device&Services → click on ‘3 ENTITIES’ label, under ‘File’ integration


→ Select our notify.file line → cogwheel icon → Change the text from ‘notify.file’ to ‘notify.save_persistent_to_txt’ (for example) → UPDATE button:

02_rename

Now we will create an automation that will save every new persistent notification entry to that text file:

### PERSISTENT NOTIFICATION TO FILE:
- id: 'record_every_persistent_to_txt_3884999234432'
  alias: Record every persistent to txt
  trigger:
    - platform: persistent_notification
      update_type: added
  action:
    - service: notify.send_message
      data:
        entity_id: notify.save_persistent_to_txt
      data_template:
        message: >
          {{ now().strftime('%Y-%m-%d %H:%M:%S') }}
          {{ trigger.notification.title }} /
          {{ trigger.notification.message }}

…with that two things done, you will have a text file in this location, and every new persistent will be added, there: /homeassistant/www/my_logs/my_persistent_notifications.txt. And it’s contents will be:

Home Assistant notifications (Log started: 2024-11-01T18:50:29.251944+00:00)
--------------------------------------------------------------------------------
2024-11-01 19:50:29 Login attempt failed / Login attempt or request with invalid authentication from nox (192.168.25.46). See the log for details.
2024-11-01 19:50:34 Login attempt failed / Login attempt or request with invalid authentication from nox (192.168.25.46). See the log for details.
2024-11-02 00:27:03 Login attempt failed / Login attempt or request with invalid authentication from nox (192.168.25.46). See the log for details.

I also have an automation that trims the text file to 200 lines once a day, if it grows over that size to avoid collapsing the sd card in case of years of loggings, but don’t want to complicate the post so much.

Greetings from Spain!

Thanks! When i try to add it in a new automation, it says:
“Message malformed: extra keys not allowed @ data[‘0’]”
Why is that?
i tried searching for it and it seems something might be wrong with the formatting, but i’m not sure.
billede

I think we need somebody will have to help us here (because I never entered an automation from the HA gui).

I think the problem could be that you are trying o enter the automation through the HA web… and I have never did that. What I do (since I start doing things with HA) is to split the configuration in text files. Because if not, and you keep adding things and automations to different things, it will become a mess.

I probably gives an error because I gave you the content of my automation in my automations_global.yaml text file… and it is not working for you because you don’t have it splitted.

You could search google with: ‘home assistat split configuration’, and you will see how the automations or other files could go in separate file to order things a lot.

To give you a clue, I can paste my configuration, and how this same automation I send you, pass the check configuration button without problems:

03_automations_global

…you could see there are some things in spanish… but that’s because in my previous automation post I change to english for a better understanding and in those is how I really have it.

Probably somebody could help us translate my automation, and how you should syntax it to fit the home assistant gui, or on the other hand, you could split the configuration in separated text files as I do, to make it work as you could see in my captures.

I’m with a recently updated version of HA, so that shouldn’t be the ‘malformed’ error.

Having said all that… and after checking how should be the syntax if the automation would go directly in your configuration.yaml file… I think, it should be something like this:

### PERSISTENT NOTIFICATION TO FILE:
automation my_persistent_to_file:
  - alias: "Record every persistent to txt"
    trigger:
      - platform: persistent_notification
        update_type: added
    action:
      - service: notify.send_message
        data:
          entity_id: notify.save_persistent_to_txt
        data_template:
          message: >
            {{ now().strftime('%Y-%m-%d %H:%M:%S') }}
            {{ trigger.notification.title }} /
            {{ trigger.notification.message }}

Try to enter that automation (maintain the spacing in columns) where you were trying to enter in your previous capture, or you could add it inside your configuration.yaml file. And we will see what happens…

(in any case, I advise you to split your configuration, or as soon as you create some automations, your configuration.yaml file will become really messy).

Once again thank you for all your extensive help!

i’ve been looking into split configuration and i think it’s a good idea to do so, but it looks a bit overwhelming with all your folders and files. Additionally, i read the docs for it and for the different commands, but i’m not sure i fully understand yet. Nonetheless, i’ll try, thanks!

You are welcome!.

Well… efectivelly is notepad++, but it is not a plugin. The captures you see in the explorer images is WINSCP. It supports several protocols to connect and browse remote computers. To login in my HA instance, I use sftp protocol.

The remote folder where HA is, depends on your installation. I have 3 HA at different locations and some are using HA operating system… where you can find the main folder of HA in /homeassistant directly… and I also have a raspberry with raspbian with HA on it… and in that case, I find my HA folder here: /usr/share/hassio/homeassistant/

As said up there, I use winscp. Really easy to navigate to where the .yaml files are and edit directly, and when saved, you don’t need to upload anywhere or anything. Just save and with winscp and notepad++, file will be updated in your server.

The only thing I think I have to configure is… inside winscp, tell it to open .yaml file with notepad++. That’s why you see icons of notepad++ in yaml file in my winscp explorer captures.

Sure. I guess you are a bit confused with the ‘!include_dir_merge_list’… things. Don’t worry. Is better to not try to understand it.

My advise. Forget about all my files and folders. And without changing anything of your current configuration (which I suppose is entering every automation directly in configuration.yaml file, or do it in the webgui)… just add the automation of the persistent notifications with the split configuration.

If you already has some automation or input_booleans, or whatever, it wll not interfere. Just that particular automation will be loaded from your first ‘splitted’ configuration file.

I think, you only need to…
-Create this folder:

/homeassistant/programming/automations/

(I gave this ‘programming’ name, but could be anything, always that you update your configuration.yaml line)

Enter this line in the configuration.yaml file:

automation: !include_dir_merge_list programming/automations/

Create a txt file inside that folder, for example called:
automations_persistent.yaml
(or any name you want to gave it. All files yaml inside programming/automations will be checked looking for automations thanks to our previous configuration.yaml line. As you saw I separate all my automations for all of my cameras, other file for the pool automations, washing machine, etc…), and name the files:

automations_cameras.yaml
automations_pool.yaml
automations_washingmachine.yaml
etc...

In the automations_persistent.yaml just enter the text of the post for my configuration with the files splitted, which was this one:

### PERSISTENT NOTIFICATION TO FILE:
- id: 'record_every_persistent_to_txt_3884999234432'
  alias: Record every persistent to txt
  trigger:
    - platform: persistent_notification
      update_type: added
  action:
    - service: notify.send_message
      data:
        entity_id: notify.save_persistent_to_txt
      data_template:
        message: >
          {{ now().strftime('%Y-%m-%d %H:%M:%S') }}
          {{ trigger.notification.title }} /
          {{ trigger.notification.message }}

With those things: creating the folder, creating the file with this automation, and adding the line to configuration.yaml… you can go to your HA → Dev tools → Check configuration… and see if it gives you this green message: Configuration will not prevent Home Assistant from starting!

If it’s green, you can restart or faster… reload automations (down below) and check if the my_persistent_notifications.txt file is updated. Of course you need to have done the things explained at Send telegrams with important hassio 'persistent notifications' - #10 by user512

(Or add one simpler automation you already have working on, in the new automations folder and file, to check if it keep working good)