Input_text / Alexa Intent => youtube search => media_player

Thank you so much. I will try now.

Is this another automation needed? or only on your first post? also regarding the input_text.youtube

I have to create one inside right?

I created two automation but I think you could use one. The first one checks input_text.youtube which has the url and plays the url. The second one checks input_text.youtubesearch for new search terms and runs the script to create the url.

This is all in one automation. (I had two because its on two different HA’s for me) It might need a delay / wait so it gets a new url before playing.

automation musicsearch:
  alias: music
  trigger:
    platform: state
    entity_id: input_text.youtubesearch
  action:
    - service: shell_command.youtube
#might need a delay here so it gets a new url
    - service:  media_player.volume_set
      data:
        entity_id: media_player.speaker
        volume_level: 1
    - service: media_extractor.play_media
      data_template:
        entity_id: media_player.speaker
        media_content_id: "{{  states.input_text.youtube.state }}"
        media_content_type: 'music'

So I need to create 2 input_text, one is input_text.youtube and second is input_text.youtubesearch ?

Yes, sorry for not mentioning that.

  1. I have relocated the youtube.py to where I kept it and change the shell_command to the file directory but nothing happen.

    shell_command:
    youtube: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 /home/homeassistant/.homeassistant/youtube.py --q="{{ states.input_text.youtubesearch.state }}"

  2. I have create 2 input_text and put in a group to display on front end.

input_text:
  youtube:
    name: Youtube
    initial: Youtube
  youtubesearch:
    name: Youtube Search
    initial: Youtube Search

group:
  youtube:
  name: Youtube
  entities:
   - input_text.youtube
   - input_text.youtubesearch

automation:
  alias: music
  trigger:
  platform: state
  entity_id: input_text.youtubesearch
    action:
      - service: shell_command.youtube
      - service:  media_player.volume_set
        data:
          entity_id: media_player.ha_speaker
          volume_level: 1
      - service: media_extractor.play_media
        data_template:
          entity_id: media_player.ha_speaker
          media_content_id: "{{  states.input_text.youtube.state }}"
          media_content_type: 'music'

In youtube.py
I have change and put my api key,my ha local ip address

On frontend it loads normally the group I created. Once I put the text example ‘song name’ in the input_text.youtube (the service call) but nothing happened. Is there anything I have to change?

You should try to test youtube.py at command prompt The shell command I had has the location of python3 which is specific to my mac computer.

on your command prompt / terminal / ssh try

python3 /home/homeassistant/.homeassistant/youtube.py --q=“rolling stones”

if this changes the state of input_text.youtube in HA then this should probably work

shell_command:
youtube: python3 /home/homeassistant/.homeassistant/youtube.py --q="{{ states.input_text.youtubesearch.state }}"

you can also try pasting a youtube url into input_text.youtube to check if your media player will play it automatically.

No error. But I can’t get it to work. Maybe I don’t understand clearly,

input_text.youtube == is the result display example http://youtube… ?
input_text.youtubesearch == is where I put the search keyword or song name for youtube.py to generate the http link?
automation, I have only one HA to use so I use your below automation?

Yes, that is how it works. If you are sure youtube.py works (doesn’t give errors when run), then you can go to your browser and put the url you used in the python script.

I use this url . (your might be http://localhost:8123/api/states/input_text.youtube)

http://192.168.2.181:8123/api/states/input_text.youtube

from here in the python script above
url = "http://192.168.2.181:8123/api/states/input_text.youtube"

and put into a browser and what do you get? I get this

{"attributes": {}, "entity_id": "input_text.youtube", "last_changed": "2018-05-05T15:55:01.206930+00:00", "last_updated": "2018-05-05T15:55:01.206930+00:00", "state": "https://www.youtube.com/watch?v=RqcjBLMaWCg"}

This tell me that youtube.py worked and put the found youtube url into input_text.youtube. You can also tell by just putting input_text.youtube on your front end or looking on the state page.

If this is not there, we will need to determine why youtube.py isn’t working.

I ran the above script in a fresh pi and had to install some programs with these commands

to create the script

sudo nano youtube.py

to install dependancies

sudo pip3 install google-api-python-client
sudo pip3 install  simplejson

then i could run this

python3 youtube.py --q=“rolling stones”

and the state of input_text.youtube changed

I rewrote the youtube.py to give better search results and not rely on google api.

youtube.py

import time
import requests
import simplejson as json
import urllib.request
import urllib.parse
import re
from sys import argv

# get the youtube search results

search = argv[1].replace(" ", "+")
query_string = search
html_content = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + query_string)
search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode())
print("http://www.youtube.com/watch?v=" + search_results[0])

# put info into HA
  
url = "http://192.168.2.181:8125/api/states/input_text.youtube"
data = {"state": "http://www.youtube.com/watch?v=" + search_results[0]} 
headers = {'Content-type': 'application/json'}
r = requests.post(url, data=json.dumps(data), headers=headers)

I got error when run youtube.py from both files. whether with or without google api

Traceback (most recent call last):
File “youtube.py”, line 7, in
import requests <==
ModuleNotFoundError: No module named ‘requests’

try

sudo pip3 install requests

I have some error, i am vietnam
pi@hassbian:~ $ python3 /home/homeassistant/.homeassistant/youtube.py --q=“rollins”
Traceback (most recent call last):
File “/home/homeassistant/.homeassistant/youtube.py”, line 13, in
html_content = urllib.request.urlopen(“https://www.youtube.com/results?search_query=” + query_string)
File “/usr/lib/python3.5/urllib/request.py”, line 163, in urlopen
return opener.open(url, data, timeout)
File “/usr/lib/python3.5/urllib/request.py”, line 466, in open
response = self._open(req, data)
File “/usr/lib/python3.5/urllib/request.py”, line 484, in _open
‘_open’, req)
File “/usr/lib/python3.5/urllib/request.py”, line 444, in _call_chain
result = func(*args)
File “/usr/lib/python3.5/urllib/request.py”, line 1297, in https_open
context=self._context, check_hostname=self._check_hostname)
File “/usr/lib/python3.5/urllib/request.py”, line 1254, in do_open
h.request(req.get_method(), req.selector, req.data, headers)
File “/usr/lib/python3.5/http/client.py”, line 1107, in request
self._send_request(method, url, body, headers)
File “/usr/lib/python3.5/http/client.py”, line 1142, in _send_request
self.putrequest(method, url, **skips)
File “/usr/lib/python3.5/http/client.py”, line 984, in putrequest
self._output(request.encode(‘ascii’))
UnicodeEncodeError: ‘ascii’ codec can’t encode character ‘\u201c’ in position 30: ordinal not in range(128)

Sorry, I can’t help with that error. I would make sure you can reach youtube in a browser in Vietnam.

You can try other peoples apps.

thanks, i has write new code, it worked thanks for repllyed

Hi,
Wonderful script, sadly stuck with hass login failed errors. Anyone can help out to complete youtube.py with hass token, not able to get it working with authorization bearer token.

I tried below but didn’t work out:

token = ‘MYTOKEN’

headers = {‘Content-type’: ‘application/json’, ‘Authorization’: 'Bearer ’ + token}

thanks

1 Like

@RobDYI
Short note to thank you for this script; works great. Tested with chromecast and performs well.
Unfortunately it doesn’t with Bose-Soundtouch and that’s just another flaw of these speakers. They’re “smart” integration is rubbish to be polite.

This might help. If it doesn’t you can publish the url on a mqtt topic and get HA to automate playing that url by watching the mqtt topic.

Example: Python

import requests

url = "https://your.awesome.home/api/error/all"
headers = {
    'Authorization': "Bearer ABCDEFGH",
}
response = requests.request('GET', url, headers=headers)

print(response.text)
1 Like

Much cleaner youtube.py which does not require any additional pip installs.
Usage: youtube.py 'search term’

import requests
import json
import sys

key = 'YOUR KEY'
address = 'https://home.assistant:8123/'
auth = 'bearer token for webrequest authentication'

requests.post(address + "api/states/input_text.youtube", data=json.dumps({"state": "https://www.youtube.com/watch?v="+requests.get('https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&q=' +  sys.argv[1] + '&type=video&key=' + key).json()["items"][0]["id"]["videoId"]}), headers={'Content-type': 'application/json', 'Authorization': 'Bearer ' + auth},verify=False)
3 Likes

Hello,
I want to play from youtube the first result of a spoken searched phrase.
I’m confused from all the posts, can someone please explain me step by step how to do this?
I’m on HASS.IO