SgtBatten / HA_blueprints

Somewhere to store automation blueprints
178 stars 67 forks source link

[Feature Request]: Use Telegram as the notification platform instead of app notifications #31

Open Ranger2959 opened 1 year ago

Ranger2959 commented 1 year ago

Describe what you are trying to accomplish and why in non technical terms I want to be able to use telegram to publish notifications instead of only app notifications.

Describe the solution you'd like Use notify.telegram to publish notifications

Additional context I set the notification_group to "notify.telegram" (that I set up) but I only receive a message saying "Motion was detected on the porch camera."

SgtBatten commented 1 year ago

Can you please provide a sample of the required format to send all the things we already send. Links to documentation etc

Ranger2959 commented 1 year ago

@SgtBatten

Here is the docs for text: https://www.home-assistant.io/integrations/telegram/#text-message Photo: https://www.home-assistant.io/integrations/telegram/#photo-support Video: https://www.home-assistant.io/integrations/telegram/#video-support

SgtBatten commented 1 year ago

Please test the version at that link

pedromrg commented 1 year ago

Please test the version at that link

getting: Invalid blueprint: Missing input definition for telegram_group

SgtBatten commented 1 year ago

@pedromrg just made some changes. Note you'll need to set the group again as the input key has changed to notify_telegram_group

pedromrg commented 1 year ago

some changes. Note you'll need to set the group again as the input key has changed to notify_telegram_group

Same error: Invalid blueprint: Missing input definition for notify_telegram_group


Another thing I forgot to mention:

selector: entity: integration: frigate domain: camera device_class: camera - ERROR here :

Value is not accepted. Valid values: "apparent_power", "aqi", "atmospheric_pressure", "awning", "battery", "battery_charging", "blind", "carbon_dioxide", "carbon_monoxide", "cold", "connectivity", "current", "curtain", "damper", "data_rate", "data_size", "date", "distance", "door", "duration", "energy", "energy_storage", "enum", "frequency", "garage", "garage_door", "gas", "gate", "heat", "humidity", "illuminance", "irradiance", "light", "lock", "moisture", "monetary", "motion", "moving", "nitrogen_dioxide", "nitrogen_monoxide", "nitrous_oxide", "occupancy", "opening", "outlet", "ozone", "plug", "pm1", "pm10", "pm25", "power", "power_factor", "precipitation", "precipitation_intensity", "presence", "pressure", "problem", "reactive_power", "receiver", "running", "safety", "shade", "shutter", "signal_strength", "smoke", "sound", "sound_pressure", "speaker", "sulphur_dioxide", "switch", "tamper", "temperature", "timestamp", "tv", "update", "vibration", "volatile_organic_compounds", "voltage", "volume", "volume_storage", "water", "weight", "wind_speed", "window".yaml-schema: http://schemas.home-assistant.io/blueprint-automation(1) No quick fixes available

SgtBatten commented 1 year ago

@pedromrg hey mate, sorry about that. I was doing it from my phone and missed an e. I think it's good now.

The second error will always be there. Frigate gives the actual camera entities the device class of camera and it's the only way i can distinguish between things like camera.front and camera.front_person for the camera select input. Home assistant does not consider camera a valid device class, but it still works for the purpose of eliminating all but the real frigate cams from that drop down. I did a pull request a long time ago to add camera as a valid device class and it was rejected. It's only an error in the schema validation. works fine.

pedromrg commented 1 year ago

@pedromrg hey mate, sorry about that. I was doing it from my phone and missed an e. I think it's good now.

The second error will always be there. Frigate gives the actual camera entities the device class of camera and it's the only way i can distinguish between things like camera.front and camera.front_person for the camera select input. Home assistant does not consider camera a valid device class, but it still works for the purpose of eliminating all but the real frigate cams from that drop down. I did a pull request a long time ago to add camera as a valid device class and it was rejected. It's only an error in the schema validation. works fine.

Thanks for the explanation!

Tested, so I have added the name of the group set on my notify.

Name set on the blueprint test_group

Getting this error when automation is executed:

Stopped because an error was encountered at 27 May 2023 at 00:46:49 (runtime: 0.05 seconds)

Template rendered invalid service: notify.

SgtBatten commented 1 year ago

What is the name of the telegram service you are using? From Dev tools, services.

pedromrg commented 1 year ago

What is the name of the telegram service you are using? From Dev tools, services.

notify.test_group

Tested and working on dev tools

SgtBatten commented 1 year ago

Can you send me a screenshot of the trace for one of these errored ones. Like of the picture/image version of the trace on the left.

pedromrg commented 1 year ago

Sure,

image
SgtBatten commented 1 year ago

Okay it's trying to do the normal group notify instead of the telegram one. I'll have to fix something.

SgtBatten commented 1 year ago

Just made a change to the condition test. Appreciate you trying it out. I don't have telegram setup

pedromrg commented 1 year ago

No worries, mate, I can test it out. Thanks a lot for the good job.

This is now hitting the correct condition, but it's fetching base_url with https://xxxx.xxx.xx// where does this gets the base URL? If I set it manually in the blueprint, it's working (photo)

Video not working:

service: notify.{{ telegram_target }} data: title: '{{title}}' message: '{{message}}' data: message_tag: '{{ id }}' photo:

SgtBatten commented 1 year ago

Okay two questions before I change something.

The IP address when you don't have a baseurl set... Is it you home assistant IP?

For video, do you have the video input set to clip in the automation config?

pedromrg commented 1 year ago

My config:

image

is this what you mean?

When nothing is set, it brings my external URL ending in //

Confirm. clip is selected in the blueprint.

pedromrg commented 1 year ago

Just FYI something aI just spotted in HA logs:

Logger: homeassistant.helpers.template Source: helpers/template.py:237 First occurred: 20:53:56 (2 occurrences) Last logged: 20:54:54

Template variable warning: 'video' is undefined when rendering '{{video}}'

pedromrg commented 1 year ago

Changes that you made are now outputting the correct value for video URL.

image

Video is not coming to Telegram.

I think that to send video we need to use:

service: telegram_bot.send_video data: authentication: digest target: -54645643 file: /config/test.mp4

ridizy commented 1 year ago

I'm looking forward to seeing this blueprint working with Telegram.

Just sharing here that I've been using the following to send video to Telegram:

- service: notify.telegram_home
  data_template:
    message: (required, but not used)
    data:
      id: "{{ id }}"
      timeout: 100
      video:
      - url: 'https://my.hass.public.host.name/api/frigate/notifications/{{ id }}/clip.mp4'
        caption: "my caption"

And here is my notify.telegram_home confirguraton:

- name: Telegram_home
  platform: telegram
  chat_id: !secret telegram_home_group

Thank you for working on this

SgtBatten commented 1 year ago

Yeah I think one issue with my current version is you can't do pictures and videos at the same time.

I reversed the order yesterday to see if that might help but haven't tested yet.

pedromrg commented 1 year ago

Just did a quick test, same behaviour.

My toughts, maybe this is sending the video but the video is not ready yet so there no file to be sent.... hence nothing arrives.

maybe we need a delay ?!

another theory.

Tested using dev tools, if I send just video it works fine.

If I send photo + video it just sends the photo indepent from the order.

laban85 commented 1 year ago

Thanks for putting this together! Telegram notification works for me with thumbnail.

SgtBatten commented 1 year ago

If I send photo + video it just sends the photo indepent from the order.

Thanks, it must just be how telegram does it's thing. might have to make it a choice by the user, e/g if video is not set to none , no photo is sent.

ridizy commented 1 year ago

In my automation, I'm using a sequence to send the photo first using my notify.telegram_home service . Then a repeat sequence that has the condition below to wait for the event to end before sending the video. I should note that this has broken for me recently and I haven't had time to dig into why

- condition: template
  value_template: "{{ wait.trigger.payload_json['type'] == 'end' }}"

It's basically taken from here: https://github.com/blakeblackshear/frigate/discussions/2898

joopdo commented 1 year ago

Wonderful, thank you! I was going to make a ticket for feature request to add Signal (https://www.home-assistant.io/integrations/signal_messenger/) support, but with the above, I got it to work in no time! (just put a signal notify entity in 'Telegram Group (Optional)'. Thanks!

                        sequence:
                          - service: "notify.{{ telegram_target }}"
                            data:
                              message: "{{message}}"
                              data:
                                verify_ssl: false
                                urls:
                                  - "{{base_url}}/api/frigate{{client_id}}/notifications/{{id}}/{{attachment}}.jpg"
SgtBatten commented 1 year ago

@joopdo

I got it to work in no time!

Are you saying signal worked with the blueprint or you had to make changes?

SgtBatten commented 1 year ago

@Ranger2959 can yuu try the latest version in the telegram branch please

xekil commented 1 year ago

@Ranger2959 can yuu try the latest version in the telegram branch please

Good morning,

I tested this beta version and it does not work, I do not receive any notification from telegram. My notification service is: notify.telegram, I fill in telegram

Frigate Notifications (0.12.0.1h) Telegram Beta

The origional version of the blueprint works with home assistant app notifications but I am using telegram.

Thanks in advance


id: '169131705810'
alias: Frigate - Notifications Telegram - Présence Parents
description: >-
  https://github.com/SgtBatten/HA_blueprints/blob/telegram/Frigate%20Camera%20Notifications/Beta
use_blueprint:
  path: SgtBatten/Beta.yaml
  input:
    notify_telegram_group: telegram
    color: '#f44336'
    icon: mdi:cctv
    labels:
      - person
    button_1: Voir Vidéo
    button_2: Voir Image
    url_3: >-
      {{base_url}}/api/camera_proxy_stream/camera.{{trigger.payload_json['after']['camera']
      | lower | replace('-','_')}}?token={{state_attr( 'camera.' ~ camera,
      'access_token')}}
    button_3: Voir en Direct
    camera: camera.parents
    attachment: /api/frigate{{client_id}}/notifications/{{id}}/snapshot.jpg
    message: 'Person'
    title: Person
    state_filter: true
    state_entity: input_boolean.notification_frigate_parents
    state_filter_states:
      - 'on'
    critical: 'false'
    subtitle: Test
    tap_action: '{{base_url}}/api/frigate{{client_id}}/notifications/{{id}}/snapshot.jpg'
    client_id: frigate
    video: /api/frigate{{client_id}}/notifications/{{id}}/{{camera}}/clip.mp4
    base_url: https://secreturlaccesmyinstance/
Logger: homeassistant.components.telegram_bot
Source: components/telegram_bot/__init__.py:855
Integration: Telegram bot ([documentation](https://www.home-assistant.io/integrations/telegram_bot), [issues](https://github.com/home-assistant/core/issues?q=is%3Aissue+is%3Aopen+label%3A%22integration%3A+telegram_bot%22))
First occurred: 13:28:07 (1 occurrences)
Last logged: 13:28:07

Can't send file with kwargs: {'title': 'Person', 'message': 'Person, 'message_tag': '1991551296.711749-qzi972', 'url': '/api/frigate/frigate/notifications//snapshot.jpg', 'caption': 'Person'}
Logger: homeassistant.helpers.template
Source: helpers/template.py:240
First occurred: 13:28:07 (1 occurrences)
Last logged: 13:28:07

Template variable warning: 'id' is undefined when rendering '/api/frigate{{client_id}}/notifications/{{id}}/snapshot.jpg'
Logger: homeassistant.components.telegram_bot
Source: components/telegram_bot/__init__.py:761
Integration: Telegram bot ([documentation](https://www.home-assistant.io/integrations/telegram_bot), [issues](https://github.com/home-assistant/core/issues?q=is%3Aissue+is%3Aopen+label%3A%22integration%3A+telegram_bot%22))
First occurred: 13:28:07 (1 occurrences)
Last logged: 13:28:07

Can't load data into ByteIO: Invalid URL '/api/frigate/frigate/notifications//snapshot.jpg': No scheme supplied. Perhaps you meant https:///api/frigate/frigate/notifications//snapshot.jpg?
SgtBatten commented 1 year ago

The first error might be something but the last two look like you tried to run it manually?

xekil commented 1 year ago

I did not perform any manual execution. I have these three errors at each trigger following the detection of a presence

SgtBatten commented 1 year ago

Gotta get some sleep but i've added a baseurl back in (untested). hopefully resolves most of it.

xekil commented 1 year ago

Thank you and good night, rest well.

xekil commented 1 year ago

There are changes in the logs but still errors:

For information, I use the Addon Frigate Proxy and the Bleuprint Telegram does not seem to take it into account unlike the original Blueprint because I receive images and videos with the Bleuprint Original. A lead can be...

Logger: homeassistant.components.telegram_bot
Source: components/telegram_bot/__init__.py:855
Integration: Telegram bot (documentation, issues)
First occurred: 14:53:13 (1 occurrences)
Last logged: 14:53:13

Can't send file with kwargs: {'title': 'Person', 'message': 'Person', 'message_tag': '16451336592.654785-imghpm', 'url': 'https://secreturlaccesmyinstanceha.com/api/frigate/frigate/notifications//snapshot.jpg', 'caption': 'Person'}
Logger: homeassistant.components.telegram_bot
Source: components/telegram_bot/__init__.py:761
Integration: Telegram bot (documentation, issues)
First occurred: 14:53:13 (6 occurrences)
Last logged: 14:53:13

Status code 404 (retry #2) loading https://secreturlaccesmyinstanceha.com/api/frigate/frigate/notifications//snapshot.jpg
Status code 404 (retry #3) loading https://secreturlaccesmyinstanceha.com/api/frigate/frigate/notifications//snapshot.jpg
Status code 404 (retry #4) loading https://secreturlaccesmyinstanceha.com/api/frigate/frigate/notifications//snapshot.jpg
Status code 404 (retry #5) loading https://secreturlaccesmyinstanceha.com/api/frigate/frigate/notifications//snapshot.jpg
Can't load data in https://secreturlaccesmyinstanceha.com/api/frigate/frigate/notifications//snapshot.jpg after 5 retries
Logger: homeassistant.helpers.template
Source: helpers/template.py:240
First occurred: 14:53:13 (1 occurrences)
Last logged: 14:53:13

Template variable warning: 'id' is undefined when rendering '/api/frigate{{client_id}}/notifications/{{id}}/snapshot.jpg'

PS:

I just tried the Stable version "Branch Telegram" and I only receive the text as the author of this topic. With the beta version and despite your modifications I receive nothing at all.

THANKS

SgtBatten commented 1 year ago

It's not processing the event ID which is really odd.

See the double slash before snapshot.jpg.

xekil commented 1 year ago

Yeah that's what I noticed too, strange...

SgtBatten commented 1 year ago

Can you turn on debug and post the outputs from that. I apologise for not testing myself right now. Very little time.

There are instructions here https://github.com/SgtBatten/HA_blueprints/blob/main/Frigate%20Camera%20Notifications/Guide%3A%20Debug%20Option.md

xekil commented 1 year ago

No need to apologize, it's already very nice to do what you do :) Here is the debug output with the beta version Telegram, I created a new simple automation for clarity. I don't get anything, not even the text

Thanks in advance.

Trace

Executed: 7 août 2023 à 18:36:54
Result:
params:
  domain: logbook
  service: log
  service_data:
    name: Frigate Notification
    message: |-
      DEBUG: 
        Info:
          fps: 5, 
          frigate event id: 1691426213.497053-l9r3ru, 
          object (formatted): person (Person),
        Config: 
          camera(formatted): suite_parentale(Suite Parentale), 
          Base URL: https://mysecreturlaccesha.com, 
          critical: False, 
          alert once: False, 
          Update Thumbnails: False, 
          attachment: /api/frigate/notifications//snapshot.jpg
          Video: , 
          Target: Telegram: telegram
          cooldown: 30s, 
          loiter timer: 0s, 
          initial delay: 0s, 
          color: #f44336, 
          sound: default, 
          Channel: , 
          Sticky: False, 
          Title: Motion Détected, 
          Message: A Person was detected on the Bedroom,
          Subtitle: , 
          tap_action: https://mysecreturlaccessha.com/api/frigate/notifications/1691426213.497053-l9r3ru/suite_parentale/clip.mp4, 
          button 1 Text/URL/Icon: View Clip (https://mysecreturlaccessha.com/api/frigate/notifications/1691426213.497053-l9r3ru/suite_parentale/clip.mp4) , 
          button 2 Text/URL/Icon: View Snapshot (https://mysecreturlaccessha.com/api/frigate/notifications/1691426213.497053-l9r3ru/snapshot.jpg) , 
          button 3 Text/URL/Icon: Silence New Notifications (silence-suite_parentale) , 
          icon: mdi:cctv
          tv: False, 
          tv_position: center, 
          tv_size: large, 
          tv_duration: 10, 
          tv_transparency: 0%, 
          tv_interrupt: False, 
          Max updates: 1000
        Filters: 
          Zones: 
            zone filter toggle on: False, 
            Multi Zone toggle on: False, 
            Required zones: [], 
            Entered Zones: [], 
            Zone Filter TEST: PASS, 
          Required objects TEST: 
            Input: ['person'], 
            TEST: PASS
          presence entity (not home):
            Entity: 
            TEST:  PASS, 
          disabled times: [], 
          State Filter: 
            state filter toggle on: False, 
            state filter entity: , 
            required states: [], 
            State Filter TEST: PASS,
  target: {}
running_script: false
Executed: 7 août 2023 à 18:36:54
Result:
params:
  domain: notify
  service: telegram
  service_data:
    title: Motion Détected
    message: A Person was detected on the Bedroom
    data:
      message_tag: 1691426213.497053-l9r3ru
      video:
        - url: ''
          caption: A Person was detected on the Bedroom
      photo:
        - url: https://mysecreturlaccessha.com/api/frigate/notifications//snapshot.jpg
          caption: A Person was detected on the Bedroom
  target: {}
running_script: false
Executed: 7 août 2023 à 18:37:01
Result:
params:
  domain: logbook
  service: log
  service_data:
    name: Frigate Notification
    message: |-
      DEBUG (in loop): 
        Info: 
          Last Zones: [], 
          Current zones: [], 
          sublabel: None, 
          IOS sound: False, 
          Android Sound: enabled, 
          image: "/api/frigate/notifications//snapshot.jpg"
          video: ""
          critical: False, 
        Triggers: 
          New Snapshot: False, 
          Presence Changed: False, 
          stationary moved: False, 
          entered zones changed: False, 
          sublabel changed: False, 
        Conditions: 
          Loitering: 0
            or 
          Presence Entity not home: OFF - PASS, 
          zone filter TEST: OFF - PASS, 
          multi-zone filter: OFF - PASS, 
          state filter TEST: OFF - PASS
  target: {}
running_script: false
SgtBatten commented 1 year ago

Okay thank you. I see the issue with the ID.

xekil commented 1 year ago

I just tested the current corrected version [223acd6], there is something new. I now receive a message and the image, however I no longer receive anything if I choose "clip" or "video for telegram". And in any case, I don't have the buttons either.

SgtBatten commented 1 year ago

Great thank you.

So we are back to where we were earlier as we don't seems to be able to send a picture and a video only one.

xekil commented 1 year ago

I forgot to specify, I do not receive the title of the notification

xekil commented 1 year ago

Good morning,

I found a BluePrint that works with the Telegram videos, I receive a photo and 2 minutes later I receive a video (there is a delay in the BluePrint)

Can you adapt it to your blueprint because it cannot be personalized and if you were able to add buttons this would be even better.

Bleuprint : https://pastecode.io/s/7diyrizc It is in this video that he shares this BluePrint https://www.youtube.com/watch?v=vZdVYfTzBrw

THANKS

SgtBatten commented 1 year ago

Can you adapt it to your blueprint

I've tried to adapt it. But flying blind. It will probably error, but if you could give me the errors that would be good.

xekil commented 1 year ago

thank you, Impossible to load the BluePrint


Sgtbatten/beta_2.yaml could not be loaded

Failed to load blueprint: while parsing a block mapping in 
"/config/blueprints/automation/SgtBatten/Beta_2.yaml", line 989, column 25 
expected <block end>, but found '-' in 
"/config/blueprints/automation/SgtBatten/Beta_2.yaml", line 990, column 25

I tried to change the indentation but it doesn't seem to be that

xekil commented 1 year ago

I just tested with the fix cc416ee , the blueprint can load but I don't receive any notification and I have these errors

Frigate Notifications (0.12.0.1h) beta 2: Choose at step 1: Frigate Event: Debug: write to Log: choice 1: Error executing script. Error for call_service at pos 1: Error rendering data template: TypeError: can only concatenate str (not "int") to str
Frigate Notifications (0.12.0.1h) beta 2: Choose at step 1: Frigate Event: Error executing script. Error for choose at pos 2: Error rendering data template: TypeError: can only concatenate str (not "int") to str
Frigate Notifications (0.12.0.1h) beta 2: Error executing script. Error for choose at pos 1: Error rendering data template: TypeError: can only concatenate str (not "int") to str

Error while executing automation automation.frigate_notifications_0_12_0_1h_beta_2: Error rendering data template: TypeError: can only concatenate str (not "int") to str```
SgtBatten commented 1 year ago

I have these errors

I think this was the debug code so I've changed that.

Please let me know.

Are you now using a telegram chat ID?

xekil commented 1 year ago

I tested https://github.com/SgtBatten/HA_blueprints/commit/b1e9d174f51bafe12775540abbe463d4ea6afdf4, I receive the photo but not the video, I use a Telegram ID -1006XXXXXXXXX

the beta logs are empty