Spotify Playlist Player

I am trying to start spotify in an automation but I get this error O_o
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://api.spotify.com/v1/me/player/play

this is my automation.

  • service: media_player.select_source
    data_template:
    entity_id: media_player.spotify
    source: >
    google_home_mini
    - service: media_player.play_media
    data_template:
    entity_id: media_player.spotify
    media_content_type: playlist
    media_content_id: >
    spotify:user:spotify:playlist:37i9dQZEfdddffdfdfS

I noticed that the firs error is:
media id must be spotify uri

but I the uri is correct

using spotify connect I succeded in playing Spotify playlist without external devices acting like sources, Hass.io became the source for spotify.
this is good.

action:
  - data:
      payload: '{"state": "ON", "brightness": 0, "color": {"r": 0, "g": 0, "b": 255},
        "effect": "solid"}'
      topic: lights/pcambiligh/set
    service: mqtt.publish
  - data:
      brightness: 255
      transition: 600
    service: light.turn_on
  - delay: 10
  - data:
      language: it
      message: Buongiorno Davide, ti auguro una buona giornata.
    service: tts.google_say
  - service: media_player.volume_set
    data_template:
      entity_id: media_player.spotify
      volume_level: 0.3
  - delay: 2
  - service: media_player.turn_on
    entity_id: media_player.spotify
  - delay: 2
  - data:
      entity_id: media_player.spotify
      source: Hass.io
    service: media_player.select_source
  - data:
      entity_id: media_player.spotify
      media_content_id: spotify:user:spotify:playlist:yourplaylist
      media_content_type: playlist
    service: media_player.play_media

this achieve what I am saying but it only output audio from the raspberry audio jack.
is it possible to output the audio via bluetooth speaker or google home using Hass.io as source that is never “expiring”?

In this way if I connect a jack to the raspberry all my Spotify automations works correctly. The problem is that I need to output the sound to a Bluetooth speaker and not with an audio jack connected to the raspberry.

I’m using HA version 0.89.0.dev0, implemented the Spotify like Wheezy shoved with packages.

  1. I can get some parts to work; but the source do not play in my Sonos speakers !
  2. And the automation part do not work at all !! (disabled this part of the script to debug the system)

Mon Feb 25 2019 21:39:13 GMT+0100 (Centraleuropæisk normaltid)
Error doing job: Task exception was never retrieved
Traceback (most recent call last):
File “/usr/lib/python3.5/asyncio/tasks.py”, line 241, in _step
result = coro.throw(exc)
File “/srv/homeassistant/lib/python3.5/site-packages/homeassistant/helpers/service.py”, line 289, in _handle_service_platform_call
await getattr(entity, func)(**data)
File “/usr/lib/python3.5/asyncio/futures.py”, line 380, in iter
yield self # This tells Task to wait for completion.
File “/usr/lib/python3.5/asyncio/tasks.py”, line 304, in _wakeup
future.result()
File “/usr/lib/python3.5/asyncio/futures.py”, line 293, in result
raise self._exception
File “/usr/lib/python3.5/concurrent/futures/thread.py”, line 55, in run
result = self.fn(*self.args, **self.kwargs)
File “/srv/homeassistant/lib/python3.5/site-packages/homeassistant/components/media_player/spotify.py”, line 246, in select_source
self._player.transfer_playback(self._devices[source],
KeyError: ‘STUE’

If I add the section with automation , then nothing works; get this script error:

Invalid config for [automation]: required key not provided @ data[‘action’]. Got None
required key not provided @ data[‘trigger’]. Got None. (See ?, line ?). Please check the docs at Automation - Home Assistant

My file:

homeassistant:


packages:
pack_1: !include packages/spotify_playlist_player.yaml

packages/spotify_playlist_player.yaml

media_player:
  - platform: spotify
    client_id: xxxxxxxxxx
    client_secret: xxxxxxxxx
    aliases:
        RINCON_xxxxx: 'STUE'
        RINCON_xxxxx: 'KÆLDER'
group:
  home_spotify_player:
    name: Spotify Player
    entities:
      - media_player.spotify
  
  home_spotify_controls:
    name: Spotify Controls
    control: hidden
    entities:
      - input_select.spotify_playlist
      - input_select.spotify_source
      - script.spotify_music
      - input_number.spotify_volume
      - input_boolean.spotify_shuffle

homeassistant:
  customize:
    script.spotify_music:
      friendly_name: 'Play'
      icon: mdi:play

sensor:
  - platform: template
    sensors:
      spotify_volume:
        friendly_name: "Spotify Volume"
        value_template: "{{ states.media_player.spotify.attributes.volume_level }}"
  - platform: template
    sensors:
      spotify_shuffle:
        friendly_name: "Spotify Shuffle"
        value_template: "{{ states.media_player.spotify.attributes.shuffle }}"
  - platform: template
    sensors:
      spotify_source:
        friendly_name: "Spotify Source"
        value_template: "{{ states.media_player.spotify.attributes.source }}"

input_number:
  spotify_volume:
    name: Volume
    icon: mdi:volume-high
    initial: 50
    min: 0
    max: 100
    step: 1

input_select:
  spotify_playlist:
    name: 'Playlist:'
    options:
      - Made In Germany
      - Murmel
    icon: mdi:spotify
  spotify_source:
    name: 'Source:'
    options:
      - STUE
      - KÆLDER
    initial: STUE
    icon: mdi:speaker-wireless

input_boolean:
  spotify_shuffle:
    name: Shuffle
    icon: mdi:shuffle-variant

script:
  spotify_music:
    alias: "Play selected spotify playlist"
    sequence:
      - service: media_player.select_source
        data_template: 
          entity_id: media_player.spotify
          source: >
            {% if is_state("input_select.spotify_source", "STUE") %} STUE
            {% elif is_state("input_select.spotify_source", "KÆLDER") %} KÆLDER
            {% endif %}
      - service: media_player.play_media
        data_template:
          entity_id: media_player.spotify
          media_content_type: playlist
          media_content_id: >
            {% if is_state("input_select.spotify_playlist", "Made In Germany") %} spotify:user:playlists.germany:playlist:5M7jfvXr6fiQ21U8jfe9aE
            {% elif is_state("input_select.spotify_playlist", "Murmel") %} spotify:user:1143893613:playlist:5dfbLgeesT8gixq1GTWBoU
            {% elif is_state("input_select.spotify_playlist", "Chillige Bässe") %} spotify:user:spotify:playlist:37i9dQZF1DX37cXruBmbRS
            {% elif is_state("input_select.spotify_playlist", "Chillstep") %} spotify:user:kent1337:playlist:6IjDl5eRczFdgZkKYXhuHZ
            {% elif is_state("input_select.spotify_playlist", "Mixed Hip Hop") %} spotify:user:1143893613:playlist:4yuXhTpPFSTnRSYmAN8mse
            {% elif is_state("input_select.spotify_playlist", "Mixed Electro") %} spotify:user:1143893613:playlist:1grR3x1MSPlyfS6VsaSzPn
            {% elif is_state("input_select.spotify_playlist", "Mixed Rock") %} spotify:user:1143893613:playlist:2ECMyR5ovezJBGQDnL3w23
            {% elif is_state("input_select.spotify_playlist", "Mixed Dub") %} spotify:user:1143893613:playlist:093q3iMD3lAA4h5oatDJPh
            {% elif is_state("input_select.spotify_playlist", "Good Feeling") %} spotify:user:1143893613:playlist:0rHdZMqeSR4XVvPf6QmFM4
            {% elif is_state("input_select.spotify_playlist", "Nightair") %} spotify:user:1143893613:playlist:2C4xXSYKJp0CYwIyWhODpD
            {% elif is_state("input_select.spotify_playlist", "Streetbangers") %} spotify:user:1143893613:playlist:1JzR2qe9P3EOjgSyVNJ80R
            {% endif %}
automation:
  - alias: 'Spotify Volume (Set)'
    trigger:
      platform: state
      entity_id: input_number.spotify_volume
    action:
      service: media_player.volume_set
      data_template:
        entity_id: media_player.spotify
        volume_level: '{{  states.input_number.spotify_volume.state | int / 100  }}'
  
  - alias: 'Spotify Volume (Sync)'
    trigger:
      - platform: homeassistant
        event: start
      - platform: state
        entity_id: sensor.spotify_volume
    action:
      - delay:
          seconds: 5
      - service: input_number.set_value
        data_template:
          entity_id: input_number.spotify_volume
          value: '{{  states.sensor.spotify_volume.state | float | round(2) * 100  }}'
  
  - alias: 'Spotify Shuffle (Set)'
    trigger:
      platform: state
      entity_id: input_boolean.spotify_shuffle
    action:
      service: media_player.shuffle_set
      data_template:
        entity_id: media_player.spotify
        shuffle: >
          {% if is_state('input_boolean.spotify_shuffle', 'off') %} 
          false
          {% elif is_state('input_boolean.spotify_shuffle', 'on') %}
          true
          {% endif %}
  
  - alias: 'Spotify Shuffle (Sync)'
    trigger:
      - platform: homeassistant
        event: start
      - platform: state
        entity_id: sensor.spotify_shuffle
    action:
      - delay:
          seconds: 5
      - service_template: >
          {% if states.sensor.spotify_shuffle.state == 'False' %}
            input_boolean.turn_off
          {% else %}
            input_boolean.turn_on
          {% endif %}
        data:
          entity_id: input_boolean.spotify_shuffle

  - alias: 'Spotify Source (Sync)'
    trigger:
      - platform: homeassistant
        event: start
      - platform: state
        entity_id: sensor.spotify_source
    action:
      service: input_select.select_option
      entity_id: input_select.spotify_source
      data_template:
        option: '{{  states.sensor.spotify_source.state  }}'

Does anyone have a system running Spotify & Sonos ? please share code.

Does anyone have a system running Spotify & Sonos ? please share code.

Hey friends! I just wanted to share a card I’ve done called Spotify Card which can be found here: https://github.com/fondberg/spotify-card and it is similar to this project but uses the Spotify Web API.

4 Likes

That looks rather nifty, I’ll have to try that out.

Sonos is not supported. Read the bottom of this page.

Here is the code
https://pastebin.com/rCX5MfWh
Ill get this error when ill checks ths config.
Package spotify setup failed. Component script has duplicate key ‘alias’

Anyone that might be able to help me what to look for?!

Hello, I’m the author of spotcast which is a service to initiate Spotify playback on an idle chromecast device. I’m looking to get in contact with someone who has intimate knowledge about the media_player.py standard component to discuss possible merge between the components.

1 Like

Hi everyone, does anyone know if this can work as part of a trigger e.g. if my door sensor triggers it can play a specific spotify playlist on my bose speaker??

I dont see why not
trigger the playlist as a script

spotify_door_sensor:
  alias: Spotify Door Sensor
  sequence:
  - service: media_player.play_media
    data_template:
      entity_id: media_player.favourite_speaker
      media_content_id: 'spotify:user:spotify:playlist:0ztMQWTqq8pM1ej5sf4lMn'
      media_content_type: 'playlist'

Then use the script in an automation

- id: 'door_sensor'
  alias: "Door Sensor start Playlist"
  trigger:
    platform: state
    entity_id: sensor.door
    from: 'off'
    to: 'on'
  action:
  - service: script.turn_on
    data:
      entity_id: script.spotify_door_sensor

Thanks a lot for this! It’s exactly what i’m looking for i think.

Will give it ago tonight and see what happens, thanks!

1 Like

Hey,

Sorry to be a pain but how do you go about getting the long spotify media_content_ID?

Is there something i need to do to do this?

I find the easiest way is to open the playlist on the web player on a PC. In the address bar will be the string you need.

I set up Spotify. I created albums in Spotify, then I created scripts for playback. Scripts work as long as Spotify runs on your PC or phone. If Spotify does not work on your PC or phone, then scripts will not work.

Here are the settings:

in media_player.yaml

- platform: spotify
  client_id: 0997a528e9e34c06846c91b955912345
  client_secret: 10596adc7c184bdd958f775e07954321

in scripts.yaml

spotify:
  alias: 'Spotify'
  sequence:
    - service: media_player.play_media
      data_template:
        entity_id: media_player.spotify
        media_content_id: 'spotify:user:spotify:playlist:xxxxxxxxxxxxxxxxxxxx'
        media_content_type: 'playlist'

I would like the scripts to work permanently for use in automation.
What else do I have to do?
THX

I added all these codes to the right files (i also created customizes.yaml).
How do i add into lovelace card?

Hi @Nicras, can you provide any help for how you added this as a card on lovelace?

Hello! Please help me out here.

The config is valid, everything looks good. When I try to start a playlist, I get an error in the log with this exception:

spotipy.client.SpotifyException: http status: 404, code:-1 - https://api.spotify.com/v1/me/player/volume?volume_percent=40:
Player command failed: No active device found

What am I doing wrong?

just reboot yuor raspberry, this plugin is a crap

Hi guys,

I am a bit lost, I tried a lot to setup spotify to run via a script and play a playlist on my google home mini.
Unfortunately it does not work.
I have the following script:

spotify_test_playback:
  alias: Spotify playback
  sequence:
  - service: media_player.media_play
    data_template:
      entity_id: media_player.office_speaker
      media_content_id: 'spotify:user:vladchiriloiu:spotify:playlist:3rzgkeEOq570xyFZlsv9mV'
      media_content_type: 'playlist'

But whenever I execute the script, it does not work and throws this error:

Logger: homeassistant.components.websocket_api.http.connection.140102125000016
Source: core.py:1212
Integration: websocket_api (documentation, issues)
First occurred: 10:44:02 AM (1 occurrences)
Last logged: 10:44:02 AM

extra keys not allowed @ data['media_content_id']
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 134, in handle_call_service
    connection.context(msg),
  File "/usr/src/homeassistant/homeassistant/core.py", line 1234, in async_call
    await asyncio.shield(self._execute_service(handler, service_call))
  File "/usr/src/homeassistant/homeassistant/core.py", line 1257, in _execute_service
    await handler.func(service_call)
  File "/usr/src/homeassistant/homeassistant/components/script/__init__.py", line 207, in service_handler
    await script.async_turn_on(variables=service.data, context=service.context)
  File "/usr/src/homeassistant/homeassistant/components/script/__init__.py", line 284, in async_turn_on
    await self.script.async_run(kwargs.get(ATTR_VARIABLES), context)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 693, in async_run
    await run.async_run()
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 444, in async_run
    await self._async_run()
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 460, in _async_run
    await self._async_step(not propagate_exceptions)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 138, in _async_step
    self, f"_async_{cv.determine_script_action(self._action)}_step"
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 233, in _async_call_service_step
    context=self._context,
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 101, in async_call_from_config
    domain, service_name, service_data, blocking=blocking, context=context
  File "/usr/src/homeassistant/homeassistant/core.py", line 1212, in async_call
    processed_data = handler.schema(service_data)
  File "/usr/local/lib/python3.7/site-packages/voluptuous/validators.py", line 208, in __call__
    return self._exec((Schema(val) for val in self.validators), v)
  File "/usr/local/lib/python3.7/site-packages/voluptuous/validators.py", line 287, in _exec
    raise e if self.msg is None else AllInvalid(self.msg, path=path)
  File "/usr/local/lib/python3.7/site-packages/voluptuous/validators.py", line 283, in _exec
    v = func(v)
  File "/usr/local/lib/python3.7/site-packages/voluptuous/schema_builder.py", line 272, in __call__
    return self._compiled([], data)
  File "/usr/local/lib/python3.7/site-packages/voluptuous/schema_builder.py", line 817, in validate_callable
    return schema(data)
  File "/usr/local/lib/python3.7/site-packages/voluptuous/schema_builder.py", line 272, in __call__
    return self._compiled([], data)
  File "/usr/local/lib/python3.7/site-packages/voluptuous/schema_builder.py", line 594, in validate_dict
    return base_validate(path, iteritems(data), out)
  File "/usr/local/lib/python3.7/site-packages/voluptuous/schema_builder.py", line 432, in validate_mapping
    raise er.MultipleInvalid(errors)
voluptuous.error.MultipleInvalid: extra keys not allowed @ data['media_content_id']

Can you please give me an idea on what I need to do to make it work?