How do I refer to any media player currently playing something?

Problem: The Plex integration, when played from an Alexa device, will show up as many different media players over time, such as media_player.plex_plex_for_alexa_alexa_4, media_player.plex_plex_for_alexa_alexa_5, etc. Only one of these is ever playing at once, and I would like to refer to this media player device in a script.

plex_write_track:
  sequence:
    - service: notify.plex_log
      data:
        message: '{{"------------------------\n"}}Title: {{((state_attr("media_player.plex_plex_for_alexa_alexa", "media_title")))}}
        {{"\n"}}Artist: {{((state_attr("media_player.plex_plex_for_alexa_alexa", "media_artist")))}}'

But obviously this approach only refers to one specific device. Is there a way to refer to the currently playing media player with “plex_plex_for_alexa_alexa” in its name?

Try this:

plex_write_track:
  sequence:
    - service: notify.plex_log
      data:
        message: >
         {% set mp = states.media_player
           | selectattr('state', 'eq', 'playing')
           | selectattr('object_id', 'match', 'plex_plex_for_alexa_alexa')
           | map(attribute='entity_id') | first %}
         {{'------------------------\n'}}
         Title: {{ state_attr(mp, 'media_title') }}
         {{'\n'}}Artist: {{ state_attr(mp, 'media_artist') }}

EDIT

Correction. As pointed out by Software2 below, original example contained a typo; it should be attribute not attributes.

1 Like

Thank you! There’s a slight error in your script (should be attribute not attributes), but that’s exactly what I needed.

The message is all on one line because multiline annoyingly inserts a space before “Title”. For anyone else that would find this useful, the working script is below.

plex_write_track:
  sequence:
    - service: notify.plex_log
      data:
        message: >
          {% set mp = states.media_player
            | selectattr('state', 'eq', 'playing')
            | selectattr('object_id', 'match', 'plex_plex_for_alexa_alexa')
            | map(attribute='entity_id') | first %}
          {{'------------------------\n'}}Title: {{ state_attr(mp, 'media_title') }}{{'\n'}}Artist: {{ state_attr(mp, 'media_artist') }}
1 Like