Get alerted when someone subscribes to your Youtube channel or likes a video

Last question I promise. I added the sensor to my configuration.yaml file and I can add the sensor as an entity in Lovelace. It obviously only shows the fake value “1”. How would I display the attributes in the entity card? I am guessing this is some more yaml config right?

Yes isn’t there always a need for more yaml and configuration? :wink:

  - platform: template
    sensors:
      youtube_subscriber_count:
        friendly_name: "Subscriber count"
        value_template: >-
                        {% if state_attr('sensor.youtube_api', 'items') != None %}
                        {{ state_attr('sensor.youtube_api', 'items').statistics.subscriberCount }}
                        {%- endif %}

  - platform: template
    sensors:
      youtube_view_count:
        friendly_name: "View count"
        value_template: >-
                        {% if state_attr('sensor.youtube_api', 'items') != None %}
                        {{ state_attr('sensor.youtube_api', 'items').statistics.viewCount }}
                        {%- endif %}

Should give you two sensors with the views and subscribers.

You can try the template in developer tools first to make sure they work as expected.

Thanks again for the help. I am obviously doing something wrong but I took your first template and pasted into the developer template window and it just outputs the code not the result. I checked that the sensor.youtube_api is available under the states section but it only shows friendly_name as an attribute. see screenshots below:

This seems to show the sensor.youtube_api as empty.

hmm…
I just tried the json in the template tool

The thing is that the sensor should get the “items”.
But apparently it doesn’t. I’m lost now.

But your count and view sensor needs the [0] also as you can see above. But that won’t solve the issue since sensor.youtube_api is empty

Just a wild guess here to see if anything at all works.
Replace the fake value with "{{ value_json.["items"][0].statistics.subscriberCount }}" and restart.

It does not like the format with the quotes. I tried single quotes but that also gave an error.

Sorry…
"{{ value_json.['items'][0].statistics.subscriberCount }}"

Jeeze I feel like I am so waisting your time now but that too gave an error.

Found the issue. There was an extra ’ at the and of my key before the " and once I removed that it now shows the attributes. Let me try the template now. I will report back.

1 Like

Ok so I got the youtube api sensor working but if I test the subscriber count and view count template you sent me in developer template it give the below error.

You don’t need all the text there only the stuff in between { } that will also make it easier to see what you have there.

Did you remember to add the [0] as I said here:

meaning:

- platform: template
    sensors:
      youtube_subscriber_count:
        friendly_name: "Subscriber count"
        value_template: >-
                        {% if state_attr('sensor.youtube_api', 'items') != None %}
                        {{ state_attr('sensor.youtube_api', 'items').[0].statistics.subscriberCount }}
                        {%- endif %}

  - platform: template
    sensors:
      youtube_view_count:
        friendly_name: "View count"
        value_template: >-
                        {% if state_attr('sensor.youtube_api', 'items') != None %}
                        {{ state_attr('sensor.youtube_api', 'items').[0].statistics.viewCount }}
                        {%- endif %}

Oh I see, Ok cool let me change the [0] and then test it out again.

Thank you so much for your help.

Did it work?

Sorry I had to step out. I will check it now and let you know.

So I have the following in my configuration.yaml and changed the fake value to 0 as you mentioned. (I only put a 0 there instead of the 1 as when I put the code there that you posted and I check my configuration before restart it gives me the error )

#####Youtube Statistics Sensor#######        
  - platform: rest
    name: youtube_api
    resource_template: "https://youtube.googleapis.com/youtube/v3/channels?part=statistics&id=UCOSx30ko605VZI4f0mdMlYw&key=$mykey"
    method: GET
    headers:
      content-type: 'application/json'
    value_template: "0"
    json_attributes:
      - "items"
    scan_interval: 300 # 5 Minutes
  - platform: template
    sensors:
      youtube_subscriber_count:
        friendly_name: "Subscriber count"
        value_template: >-
                        {% if state_attr('sensor.youtube_api', 'items') != None %}
                        {{ state_attr('sensor.youtube_api', 'items').statistics.subscriberCount }}
                        {%- endif %}

And then I pasted only the stuff between the {{ }} into the developer template and the below is what I am getting:

I may be pointing out the obvious but in case there are those who haven’t read the subscriberCount notes it may save some anguish.

The API does not return a true subscriber count. It returns a rounded count with the rounded numbers (they round down always) a significant part of the count. For example, if you have 12,345 subscribers it will show 12,300. If you have 1,234,567 subs you will get 1230000.

In a developer email I received in 2019, YouTube stated that this was done for “mental health reasons” and “anxiety” (I wish I kept the email!) of their publishers who watch subscriber counts like a hawk, causing stress. You know what didn’t work well for my mental health, YouTube? Breaking all the of the automations I had around my YouTube subscriber count, my live counters, and fudging your data to treat me like a child.

Anyway, point is that this rounding significantly reduces the usefulness, at least in my experience, of subscriberCount as a data source for automations.

So I played with the code you sent me with the [0] in it and it turns out that I needed to remove the < . > in front of the [0]
Original code:

{{ state_attr('sensor.youtube_api', 'items').[0].statistics.subscriberCount }}

After I changed it:

{{ state_attr('sensor.youtube_api', 'items')[0].statistics.subscriberCount }}

And that seems to have fixed the issue.

Thank you so much for your assistance, much appreciated.

Hi guys just an update on what I have done with my Youtube integration in Lovelace

The Only thing I would still like to incorporate is the “Watch Time - Hours” but I have not managed to find a way to get that info using the DataAPIV3 yet. If anyone knows please do share.

Thanks

Similar to this, I created a rest sensor and template to fetch a YouTube video url when an artist and song name input is provided. When the input_text var is changed, it will trigger an automation that will trigger a refresh of the REST sensor. Which will capture the first result matching the artist name and song provided. It will fetch the youtube title, videoId and thumbnail url. With this a direct youtube url can be build which can then be used to stream/cast.

  1. Create YouTube API key
  2. Store API credentials in secret.yaml:
youtube_api_key: XXXXXXXXXXXXXXXXXXXXXXXXXXX
  1. Link hidden password input_text to secret in configuration.yaml:
input_text:
    youtube_api_key:
      initial: !secret youtube_api_key
      mode: password
homeassistant:
  ...
  customize:
    input_text.youtube_api_key:
      hidden: true
  1. Enable YouTube API v3
  2. Restrict API key to only query YouTube API
  3. Add REST sensor to query YouTube API, set high scan interval so REST call will only be executed when a refresh would be triggered. configuration.yaml (or can be split into sensor.yaml):
sensor:
  - platform: rest
    name: Get YouTube first search result
    scan_interval: 99999999
    resource_template: "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&type=video&&format=json&q={{states('input_text.search_mp3_youtube')}}&key={{states('input_text.youtube_api_key')}}"
    value_template: "{{value[:250]}}"
    json_attributes:
      - items
  - platform: template
    sensors:
      youtube_search_song_video_url:
        value_template: "https://www.youtube.com/watch?v={{state_attr('sensor.get_youtube_first_search_result','items')[0].id.videoId }}"
  - platform: template
    sensors:
      youtube_search_song_video_title:
        value_template: "{{state_attr('sensor.get_youtube_first_search_result','items')[0].snippet.title }}"
  - platform: template
    sensors:
      youtube_search_song_video_thumbnail:
        value_template: "{{state_attr('sensor.get_youtube_first_search_result','items')[0].snippet.thumbnails.high.url }}"
  1. Create automation to trigger REST sensor refresh when input_text to search is changed
- id: 'XXXXXXX'
  alias: Search YouTube URL
  description: ''
  trigger:
  - platform: state
    entity_id: input_text.search_mp3_youtube
    to:
  condition: []
  action:
    - service: homeassistant.update_entity
      target:
         entity_id: sensor.get_youtube_first_search_result
  mode: single
  1. Create script to cast first found YouTube result based on search input text. With a short delay to make sure the rest sensor is updated after input has changed. In scripts.yaml:
play_youtube_search_selection:
  alias: Play YouTube search
  sequence:
    - delay:
        hours: 0
        minutes: 0
        seconds: 3
        milliseconds: 0
    - service: media_extractor.play_media
      data_template:
        entity_id: media_player.chromecast
        media_content_id: '{{ states(''sensor.youtube_search_song_video_url'') }}'
        media_content_type: video/youtube
  mode: single
  icon: mdi:youtube
  1. Add input text and button to trigger script into lovelace. Thumbnail and title could also be added based on sensors above:
 - entity: input_text.search_mp3_youtube
    type: custom:text-input-row
 - type: button
    tap_action:
        action: toggle
    entity: script.play_youtube_search_selection

Hi @uncapped_shady

Can you please share the final config here?

Im trying to solve it, but no luck

I don’t have this code.
Talk to OP instead

1 Like