Get a list of active playing media players or grouped media players

Hi everyone,

I have a automation such that on my apple watch when it runs it asks me which Sonos speaker I want to start playing music on and it then selects a random station from a list to start playing. I want to add that if something in my network is already playing it asks me if I want to the Selected Sonos speaker to the group or play something new.

I’m trying to use Template to get the list of currently playing sonos media players or group of media players. Based on a fixed group of Sonos media player entities I can get a list of active players. Next I’m trying to figure out what are the active groups because if 2 players are playing in a group and 1 is play alone, I should have 2 active, not 3.

This is the none working code. Any suggestions?

{% set media_players = [
              states.media_player.living_room,
              states.media_player.move,
              states.media_player.bedroom,
              ] %}
{% set active_player =  media_players | selectattr('state','eq','playing') | map(attribute='entity_id') | list   %}

{{ active_player == [] }}
{{ active_player }}

{% set ns = namespace(player_groups = []) %}

{% for player in active_player %}
  {% set grp = state_attr( player, 'group_members') %}
  grp {{ grp }}, playergroups: {{ ns.player_groups }}
  {% set ns.player_groups = [ns.player_groups, grp] if grp not in ns.player_groups %}
{% endfor %}
player_group: {{ ns.player_groups }}

Any suggestions appreciated! I’m really struggling with Template