Sonos master template sensor

I would like to have a template sensor that displays the master sonos speaker. I have 2 zones with speakers for my livingroom and kitchen. Sometimes these get controlled from HA and sometimes from the sonos app. Within HA had an automation that would respont to the event that creates the group. but whenever you join them trough the Sonos app that event doesn’t show.
Yet the mini mediaplayer card does detect what device is master, also when it’s done from the Sonos app.

I asked ChatGPT to create a template sensor but the answer I got doesn’t work. The attibute it uses is not on any of my devices.

- platform: template
  sensors:
    sonos_master:
      friendly_name: "Sonos Master Speaker"
      value_template: >
        {% set master = state_attr('media_player.kitchen', 'current_master') %}
        {% if master %}
          {{ master.split('.')[1] }}
        {% else %}
          None
        {% endif %}

Got it working for what I need. Maybe this will ever be usefull for someone. When not grouped the speaker will be it’s own master.

  - platform: template
    sensors:
      sonos_master:
        friendly_name: "Sonos Master"
        value_template: >
          {% if states.media_player.kitchen.attributes.group_members[0]==states.media_player.symfonisk_bookshelf.attributes.group_members[0] %}
            {{ states.media_player.kitchen.attributes.group_members[0].split('.')[1] }}
          {% else %}
            'None'
          {% endif %}

For my needs it was important to know when the speaker is not the master so I can hide it fromthe GUI and only display the master speaker. I use this conditional card configuration:

type: conditional
conditions:
  - entity: media_player.symfonisk_bookshelf
    state: playing
  - entity: sensor.sonos_master
    state_not: kitchen
card:
  type: custom:mini-media-player
  hide:
    power: true
    icon: false
    source: true
    name: false
  speaker_group:
    platform: sonos
    show_group_count: true
    entities:
      - entity_id: media_player.symfonisk_bookshelf
        name: Sonos Woonkamer
      - entity_id: media_player.kitchen
        name: Sonos Keuken
  entity: media_player.symfonisk_bookshelf
  artwork: material