Rule for searching youtube (KODI)

Wonder if it’s possible with HA to set up a rule which will launch the youtube plugin in kodi and search up for a predefined string - let’s say "cartoon pony (believe fathers will understand :slight_smile: )

2 Likes

You actually want the search list to appear so you have to select the video you want or just want to play the first video that comes up when you search the string?( i think the second option will be easy to achieve with a slight modification of the project below.

This below is not exactly what you want but maybe it helps you. It starts the latest video from a specific youtube channel of choice.
https://community.home-assistant.io/t/get-latest-video-id-from-youtube-channel-and-play-youtube-video-on-kodi/

still looking for a solution. especilly considering that now ha has an input text component. maybe somebody has an appdaemon or other script up their sleeve which provides this functionality?

Well slowly moving forward (hopefully some python guru will se this topic and give a helping hand)

Adopted a google api script to run under Python3. Currently it works from command line like

python3 youtubev3.py --q="kodi" --max-results=10 > youtuber1.txt

And returns values like (format could be changed)

cat youtuber1.txt
buXCt9zGqSs (Rowdy Hero 2 (Kodi) Full Hindi Dubbed Movie | Dhanush, Trisha Krishnan)
zSg6KXsjCVM (Dhanush New Movie in Hindi Dubbed 2016 | Kodi Hindi Dubbed Movies 2016 Full Movie)
...

And so on. So wondering now which way to go. Would be great to dynamically populate some input_select with the results.
Would be great to have a search string taken from the input_text field in home assistant.
So taking the above together - the only option would be to use an appdaemon?
Is there any example simple code how to populate input_select results from a text file (as i don’t think i will be able to merge the code below into appdaemon directly.

DEVELOPER_KEY = "APIKEYWASHERE"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

def youtube_search(options):
  youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    developerKey=DEVELOPER_KEY)

  # Call the search.list method to retrieve results matching the specified
  # query term.
  search_response = youtube.search().list(
    q=options.q,
    part="id,snippet",
    maxResults=options.max_results,
    type="video",
    order="viewCount",
    videoDefinition="high",
 ).execute()

  videos = []
  channels = []
  playlists = []

  # Add each result to the appropriate list, and then display the lists of
  # matching videos, channels, and playlists.
  for search_result in search_response.get("items", []):
    if search_result["id"]["kind"] == "youtube#video":
      videos.append("%s (%s)" % (search_result["id"]["videoId"],
                             search_result["snippet"]["title"]))

  print ("\n".join(videos))


if __name__ == "__main__":
  argparser.add_argument("--q", help="Search term", default="Rome")
  argparser.add_argument("--max-results", help="Max results", default=2)
  args = argparser.parse_args()

  try:
    youtube_search(args)
  except HttpError as e:
    print ("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))

Hi @moskovskiy82,

There is my implementation, with an Appdaemon app, to search youtube videos with an input_text, dynamically populate an input_select with the results, and play the selected videos in Kodi, using the Youtube video plugin:


(it requires a Youtube API key to make the search)

Screenshots:

4 Likes

Works as advertised!
This is one of the coolest time savers now. Thank you for your time!

Just in case someone doesn’t know where to get an api key - here are the detailed official instructions

https://developers.google.com/youtube/v3/getting-started

2 Likes

Do You have any tutorial? I’m using hassio with google assistant. Want to play yt videos using search functionality. I tried to use your sollution with Appdaemon but with no luck. I found that in web browser you can use link with search querry to play videos (it gives a playlist in result):

https://www.youtube.com/embed?listType=search&list=[whattosearch] eg:
https://www.youtube.com/embed?listType=search&list=nothingelsematters

Tried to use it with Kodi YouTube plugin but with no luck:
plugin://plugin.video.youtube/play/?listType=search&list=nothingelsematters&order=shuffle&play=1&repeat=all"
and many other variations.

It will be cool if I would say “OK Google YouTube Unforgiven” and then kodi plays Metallica’s Unforgiven from YT ;-). All I’m missing is searching mechanism.

Well check out youtube api. Instead of returning several values you can rewrite to return just one which i believe you will be able to use

I will up it up in search for help… Trying to rewrite the script so it will call the most viewed video directly to use together with the api.ai so it will be exactly like say “OK Google YouTube Unforgiven”

For this i have change the max_results=1 throught the script. Also changed the sorting to viewCount
But as i lack any python skill i’m stuck with the calling out playing video without input_select.

Here is the code for the update of input_select

    # Update input_select values:
    self._ids_options.update({name: v_id for v_id, name in found})
    labels = [f[1] for f in found]
    self.log('NEW OPTIONS:\n{}'.format(labels))
    self.call_service('input_select/set_options',
                      entity_id=self._input_select,
                      options=[DEFAULT_ACTION] + labels)

And here is the code for calling out kodi play

def video_selectionbest(self, entity, attribute, old, new, kwargs):
    """Play the selected video from a previous query."""
    self.log('SELECTED OPTION: {} (from {})'.format(new, old))
    try:
        selected = self._ids_options[new]
    except KeyError:
        self.error('Selection "{}" not in memory (doing nothing)'
                   .format(new), 'WARNING')
        return

    if selected:
        self.log('PLAY MEDIA: {} [id={}]'.format(new, selected))
        self.call_service(
            'media_player/play_media', entity_id=self._media_player,
            media_content_type="video",
            media_content_id=KODI_YOUTUBE_PLUGIN_MASK.format(selected))

So how to throw away input_select and pass the results directly to kodi?

To whomever finds this thread and wants to use the app. It’s great.
I’ve fixed it to work using current hass, kodi and appdaemon.
Submitted a pull request to @azogue.

You can get it from here:

2 Likes