Creating a YouTube Thumbnail Sensor in Home Assistant

Hello everyone.

When connected via AirPlay, the Apple TV integration in Home Assistant cannot retrieve the thumbnail of a YouTube video playing on the Apple TV's YouTube app

I was searching for a solution to this issue when I came across matt8707's project. youtube-watching

However, it did not work well in my environment, so I integrated it into AppDaemon.

It can be installed via HACS, and the MQTT integration is required. It's easy to use.

Exactly what I was looking for. I’ve followed all the steps, but I can’t get the sensors to show up, they don’t exist. What do I need to do?

Show me what appears in the AppDaemon logs.

Hey, I’ve been playing with this again. Here’s what I’ve come up with so far

apperently yt_dlp is available in home assistant so just

import yt_dlp
import json

URL = "https://www.youtube.com/feed/history"

ydl_opts = {
    "cookiefile": "/config/python/.cookies.txt",
    "skip_download": True,
    "playlist_items": "1",
    "quiet": True,
    "no_warnings": True,
}

with yt_dlp.YoutubeDL(ydl_opts) as ydl:
    info = ydl.extract_info(URL, download=False)
    data = ydl.sanitize_info(info)
    entry = data.get("entries", [data])[0]
    print(
        json.dumps(
            {
                "channel": entry.get("channel"),
                "title": entry.get("fulltitle"),
                "video_id": entry.get("id"),
                "thumbnail": entry.get("thumbnail"),
                "original_url": entry.get("original_url"),
            },
            indent=2,
        )
    )

and to “force” set entity_picture on the media player

import argparse
import requests
from secrets import get_secret

HOST = get_secret("ha_host")
TOKEN = get_secret("ha_token")


def update_entity_picture(entity_id, entity_picture):
    url = f"{HOST}/api/states/{entity_id}"
    headers = {"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"}
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        data = response.json()
        data["attributes"]["entity_picture"] = entity_picture
        response = requests.post(url, headers=headers, json=data)
        if response.status_code == 200:
            print("ok")
        else:
            print("Error posting update: ", response.text)
    else:
        print("Error retrieving state: ", response.text)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="update entity_picture")
    parser.add_argument("--entity_id", required=True, help="entity_id")
    parser.add_argument("--entity_picture", required=True, help="entity_picture")
    args = parser.parse_args()
    update_entity_picture(args.entity_id, args.entity_picture)

alias: Set youtube entity_picture
triggers:
  - trigger: state
    entity_id:
      - media_player.sovrum
      - media_player.vardagsrum
    to:
      - playing
      - paused
conditions:
  - condition: template
    value_template: >
      {% set entity_id = trigger.entity_id %}
      {% set youtube = 'sensor.youtube_thumbnail' %}

      {{ is_state_attr(entity_id, 'app_id', 'com.google.ios.youtube')
      and (state_attr(entity_id, 'media_artist') != state_attr(youtube, 'channel')) 
      and (state_attr(entity_id, 'media_title') != state_attr(youtube, 'title')) }}
actions:
  - action: homeassistant.update_entity
    data:
      entity_id:
        - sensor.youtube_thumbnail
  - action: shell_command.set_entity_picture
    data:
      entity_id: >
        {{ trigger.entity_id }}
      entity_picture: >
        {{ states('sensor.youtube_thumbnail') }}
mode: single

still some quirks, like pausing the media player will remove entity_picture, and because it’s not a session every yt fetch takes like 3 seconds. I’ve tried a container with GitHub - LuanRT/YouTube.js: A JavaScript client for YouTube's private API, known as InnerTube. and that is much faster

Nevermind, my AppDeamon was causing trouble. Got it working, trying to figure out how to get this code show up in my media conditional, still using Mattias old dashboard…

That’s great.

- type: conditional
  conditions:
    - entity: select.conditional_media
      state: 4k
  card:
    type: custom:button-card
    entity: media_player.4k
    name: Apple tv
    triggers_update: sensor.youtube_watching
    template:
      - conditional_media

You should write it inside the dashboard’s media conditional. Of course, select.conditional_media must include the Apple TV entity. (Mine is media_player.4k)


I’m a huge fan of yours. I’ll try to understand the code you provided a bit more and leave my additional comments. EDIT The command_line isn’t working very well, though.

I have no idea how to execute this code,
```
import yt_dlp
import json

URL = “https://www.youtube.com/feed/history”

ydl_opts = {
“cookiefile”: “/config/python/.cookies.txt”,
“skip_download”: True,
“playlist_items”: “1”,
“quiet”: True,
“no_warnings”: True,
}

with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(URL, download=False)
data = ydl.sanitize_info(info)
entry = data.get(“entries”, [data])[0]
print(
json.dumps(
{
“channel”: entry.get(“channel”),
“title”: entry.get(“fulltitle”),
“video_id”: entry.get(“id”),
“thumbnail”: entry.get(“thumbnail”),
“original_url”: entry.get(“original_url”),
},
indent=2,
)
)
```

Fewww… I finally solved it. I was still using core 3.4, and the default installed version of yt-dlp was 2025.02.19. After updating yt-dlp to version 2025.3.31 in the console, it works correctly. In core 4.1, it’s version 2025.03.26.


But I still haven’t solved the import requests issue…
EDIT2

Alright. I’ve finally solved everything. Thank you so much

                  - type: conditional
                    conditions:
                      - entity: select.conditional_media
                        state: Vardagsrum
                    card:
                      type: custom:button-card
                      entity: media_player.vardagsrum_2
                      triggers_update: sensor.youtube_watching
                      template:
                        - conditional_media
                        - icon_apple_tv
                        - progress_bar

Not showing youtube thumbnail in conditional media grid place, but both mqtt sensors are working and giving correct data.

If so, you should take a look at the conditional_media template.
In fact, rather than focusing on conditional_media, you should take a closer look at the other included templates: base_media and media.

base_media

The is_youtube and entity_picture variables must be defined among the variables of the base_media template.

variables:
  media_on: >
    [[[ return !entity || ['playing', 'paused'].indexOf(entity.state) !== -1; ]]]
  media_off: >
    [[[ return !entity || ['off', 'idle', 'standby', 'unknown', 'unavailable'].indexOf(entity.state) !== -1; ]]]
  # entity_picture: >
  #   [[[ return !entity || entity.attributes.entity_picture; ]]]
  entity_picture: >
    [[[ 
      if (!entity || entity.attributes.entity_picture === undefined) {
        return entity.attributes.title_image;
      }
      return entity.attributes.entity_picture;
    ]]]

  is_youtube: >
    [[[
      let is_youtube = entity?.attributes?.app_id === 'com.google.ios.youtube',
          sensor = this?._config?.triggers_update,
          media_title = entity?.attributes?.media_title,
          watching_title = states[sensor]?.attributes?.title;
      if (is_youtube && media_title === watching_title) {
          return true;
      }
    ]]]

media

media:
  template:
    - base
    - base_media
styles:
    custom_fields:
      icon:
        - width: 70%
        - margin-left: 2%
        - fill: '#9da0a2'
        - display: >
            [[[
            if (variables.is_youtube) {
                return `none`;
            }
            else {
                return variables.media_off || variables.entity_picture === undefined
                    ? 'initial'
                    : 'none';
            }
            ]]]
    card:
      - background-color: none
      - background-size: cover
      - background-position: center
      - background-image: >
          [[[
            if (variables.is_youtube) {
                return `linear-gradient(0deg, rgba(0,0,0,.8) 0%, rgba(0,0,0,0) 100%), url(${states[this._config?.triggers_update].state})`;
            } else {
                return variables.media_on && variables.entity_picture === undefined
                    ? 'linear-gradient(0deg, rgba(255, 255, 255, 0.8) 0%, rgba(255, 255, 255, 0.8) 100%)'
                    : variables.media_off
                        ? 'linear-gradient(0deg, rgba(115, 115, 115, 0.2) 0%, rgba(115, 115, 115, 0.2) 100%)'
                        : `linear-gradient(0deg, rgba(0,0,0,.8) 0%, rgba(0,0,0,0) 100%), url(${variables.entity_picture})`;
            }
          ]]]

conditional_media

conditional_media:
  aspect_ratio: 1000/996
  template:
    - base
    - base_media
    - icon_play_pause
  variables:
    i: >
      [[[
        if (entity) {
            let data = entity.attributes.data;
            return data === undefined || Math.floor(Math.random() * (data.length - 1)) + 1;
        }
      ]]]
  styles:
    card:
      - background: rgba(115, 115, 115, 0.2) center center/cover no-repeat
      # - background-image: &media_background_image >
      - background-image: >
          [[[
            if (entity) {
              if (variables.is_youtube) {
                  return `url(${states[this._config?.triggers_update].state})`;
              } else {
                let data = entity.attributes.data;
                return data && (data[variables.i].fanart || data[variables.i].poster)
                    ? `url("${data[variables.i].fanart}"), url("${data[variables.i].poster}")`
                    : `url("${variables.entity_picture}")`;
              }
            }

Since I made a number of modifications from the original, there may be some differences.

how did you solve secret problem? i got this error?

ImportError: cannot import name ‘get_secret’ from ‘secrets’
(/usr/local/lib/python3.13/secrets.py)

Look at item number 6. The file /config/secret.yaml must contain the ha_token and ha_host entries.

import yaml

with open('/config/secrets.yaml') as f:
    secrets = yaml.safe_load(f)

HOST = get_secret("ha_host")
TOKEN = get_secret("ha_token")

that solves it. But when i use it i get following response.

However, last week when i tried first, youtube watching (getting image) sensor was working. now it doesnt anymore. I get following error in the log.

Command failed (with return code 1): python3 << EOF import yt_dlp import json URL = "https://www.youtube.com/feed/history" ydl_opts = { "cookiefile": "/config/youtube_cookies.txt", "skip_download": True, "playlist_items": "1", "quiet": True, "no_warnings": True, } with yt_dlp.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(URL, download=False) data = ydl.sanitize_info(info) entry = data.get("entries", [data])[0] print( json.dumps( { "channel": entry.get("channel"), "title": entry.get("fulltitle"), "video_id": entry.get("id"), "thumbnail": entry.get("thumbnail"), "original_url": entry.get("original_url"), }, indent=2, ) ) EOF

I used the python code in my laptop, it works. that means cookies file is valid still. but within HA it isnt working.

Hi, kind regards.
I know this is probably a lot to ask, but I’m still new to Home Assistant. I’d love to see the yt thumbnails on my dashboard—would you mind making a clear guide, easy to follow, on how to set it up? I can kofee you to thank you for your time.

Thanks, have a nice day.

Hello. I’m sorry for such a late reply.

The easiest way is to get sensor.youtube_watching through AppDaemon, and then use it as the background for a custom card.

I was wondering if you managed to get sensor.youtube_watching working using GitHub - kkqq9320/Youtube-Thumbnail: Make a thumbnail of a recently watched youtube video on apple tv as a homeassistant sensor · GitHub?

Hello! Sorry for the very late reply.

There have been a few changes in the meantime, so I’m not entirely sure if it will work correctly using shell_command. I recently updated the AppDaemon code because there were some changes related to YouTube.

First off, the issue you showed me looks like a problem with the shell_command.

shell_command:
  set_entity_picture: "python3 /config/python/set_entity_picture.py --entity_id '{{ entity_id }}' --entity_picture '{{ entity_picture }}'"`

Is this how you wrote it?

I haven’t been able to update the guide for this part yet (I’m personally using AppDaemon right now), but the error code seems to be caused by it failing to receive the entity_id and entity_picture values.

I’ve left a guide in my GitHub repository on how to make it work using shell_command. Checking it out should be helpful.

instead of shell_command i wanted to try appdaemon way first, since it seems easy. But its also not working. Here are the steps that i did:

Install appdaemon add on
Installed Youtube-Thumbnail from HACS

# addon_configs/a0d7b954_appdaemon/appdaemon.yaml
---
appdaemon:
  latitude: 52.379189
  longitude: 4.899431
  elevation: 2
  time_zone: Europe/Amsterdam
  plugins:
    HASS:
      type: hass
      token: !env_var SUPERVISOR_TOKEN
http:
  url: http://0.0.0.0:5050
admin:
api:
hadashboard:
app_dir: /homeassistant/appdaemon/apps
# addon_configs/a0d7b954_appdaemon/apps/app.yaml
---
hello_world:
  module: hello
  class: HelloWorld
## apps.yaml
youtube_thumbnail:
  module: youtube_thumbnail
  class: YouTubeThumbnail
  apple_tv_entity_id: media_player.office_display
  cookies_url: /homeassistant/.youtube_cookies.txt

The log of the addon

2026-04-29 17:37:36.851349 INFO hello_world: You are now ready to run Apps!
2026-04-29 17:37:36.852944 INFO AppDaemon: App initialization complete
2026-04-29 17:38:09.101523 INFO AppDaemon: New app config: youtube_thumbnail
2026-04-29 17:38:09.110994 ERROR Error: =====  Error importing 'youtube_thumbnail'  ===============================
2026-04-29 17:38:09.115216 ERROR Error: FailedImport: Failed to import 'youtube_thumbnail'
2026-04-29 17:38:09.116128 ERROR Error:   Import paths:
2026-04-29 17:38:09.117036 ERROR Error:     /config/apps
2026-04-29 17:38:09.119621 ERROR Error:   ModuleNotFoundError: No module named 'youtube_thumbnail'
2026-04-29 17:38:09.122933 ERROR Error: ===========================================================================

location of youtube_thumbnail.py is
config\appdaemon\apps\Youtube-Thumbnail\youtube_thumbnail.py

Create a new apps.yaml file in the folder where your .py file is located
In your case, Youtube-Thumbnail.

## config\appdaemon\apps\Youtube-Thumbnail\apps.yaml
youtube_thumbnail:
  module: youtube_thumbnail
  class: YouTubeThumbnail
  apple_tv_entity_id: media_player.office_display
  cookies_url: /homeassistant/.youtube_cookies.txt

or move the .py file to the apps folder. DOCS!

To explain this a bit more simply, having

in your

configuration literally means that you are setting your apps directory to the /homeassistant/appdaemon/apps path.

However, since the current location of apps.yaml is

this is why you are getting the following error:

A new integration is now available: youtube-now-playing-on-apple-tv.

It does not depend on AppDaemon and can be easily installed and configured via HACS.

Please consider using it instead.