Return Youtube 视频 URL 来自 Javascript 关键字搜索

Return Youtube video URL from keyword search with Javascript

好的,所以我正在为我的服务器在 Discord 中制作一个机器人,我想实现的是一个 youtube 命令。
我一直在搜索并查看 Youtube API,我所能找到的只是他们搜索看起来像浏览器的东西

我正在使用 nodejs 运行 它脱离我的笔记本电脑,我的机器人 运行 脱离 discord.js
我有一个类似的命令MAL 和 Urban Dictionary 搜索,但我什么也没找到,也不知道如何在 youtube 上做同样的事情

我曾经有一个 python 机器人的命令能够做到这一点,而且我看到其他 Discord 机器人也能够做到这一点,所以我知道这显然是可能的

基本上我要说的是我需要能够从一串搜索字词中搜索并 return 一个 youtube 视频 URL(第一个搜索结果),这样使用看起来像

>>youtube Tunak Tunak Tun

会return https://www.youtube.com/watch?v=vTIIMJ9tUc8 ,这是该关键字的第一个搜索结果

编辑:
我找到了可以执行此操作的 python 命令,但几乎没有技能也没有信心尝试将其转换为 JavaScript

elif prefix and cmd=="youtube" and len(args) > 0:
        try:
            yword=args.replace(" ","_")
            ydata= urlreq.urlopen("http://gdata.youtube.com/feeds/api/videos?vq="+yword+"&racy=include&orderby=relevance&max-results=1")
            yread= str(ydata.read())
            if "<openSearch:totalResults>0</openSearch:totalResults>" in yread:
                room.message("I got nothin' for ya by the name of "+args)
            else:
                trash , yclean=yread.split("<media:player url='http://www.youtube.com/watch?v=",1)
                yclean , trash=yclean.split("&amp;",1)
                room.message("http://http://www.youtube.com/watch?v="+yclean,True)
        except:
            room.message("Somethin ain't right")

EDIT2(对长度表示歉意):好的!我发现了一些让我离自己更近的东西! https://www.npmjs.com/package/youtube-search
现在我的机器人中有一个命令是这样的:

if (commandIs("yt" , message)){
  search(args.join(' ').substring(4), opts, function(err, results) {
    if(err) return console.log(err);
  message.channel.sendMessage(results);
  console.log(results);
  });
}

所以现在当我输入 >>yt Tunak Tunak Tun 我得到

[ { id: 'vTIIMJ9tUc8',
link: 'https://www.youtube.com/watch?v=vTIIMJ9tUc8',
kind: 'youtube#video',
publishedAt: '2014-03-21T07:00:01.000Z',
channelId: 'UC3MLnJtqc_phABBriLRhtgQ',
channelTitle: 'SonyMusicIndiaVEVO',
title: 'Daler Mehndi - Tunak Tunak Tun Video',
description: 'Presenting \'Tunak Tunak Tun\' music video sung by the talented Daler Mehndi Song Name - Tunak Tunak Tun Album - Tunak Tunak Tun Singer - Daler Mehndi ...',
thumbnails: { default: [Object], medium: [Object], high: [Object] } } ]

在控制台中,[object Object] 在不和谐频道中。 http://i.imgur.com/Vorpn0f.png

所以现在的问题是 link 触手可及,但我无法将其发送到 return JUST link, 我不知道如何把它从那个烂摊子里拉出来。

好的,这是另一种对我有用的方法,使用 google javascript API。再一次,SO 片段没有 运行 它,所以 I'll link you to the fiddle.

此方法需要您setup a google API key, then enable youtube API access.

我已经从 fiddle 中删除了我的 google API 密钥,因此您需要对其进行设置。如果你想先测试,我可以私信你。

var apiKey = null //put your API key here

function search() {
 var searchTerm = $('#txtSearch').val()
 
  gapi.client.init({
    'apiKey': apiKey, 
    'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest']
  }).then(function() {
    return gapi.client.youtube.search.list({
      q: searchTerm,
      part: 'snippet'
    });
  }).then(function(response) {
   var searchResult = response.result;
    $('#search-results').append(JSON.stringify(searchResult, null, 4))
   console.log(searchResult.items[0])
    var firstVideo = searchResult.items[0]
    firstVideo.url = `https://youtube.com/watch?v=${firstVideo.id.videoId}`
    $('#first-video').text(firstVideo.url).attr('href', firstVideo.url)
    $('#first-video-title').text(firstVideo.snippet.title)
    $('#first-video-description').text(firstVideo.snippet.description)
  });

}


$('#btnSearch').on('click', function() {
   $('#first-video-title').text("")
    if (!apiKey) {
      $('#first-video-title').text("You need to set an apiKey!")
      return;
    }
   gapi.load('client', search)
  });
#search-results { white-space: pre; font-family: monospace; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src='https://apis.google.com/js/api.js'></script>

<div id="container">
  <input id="txtSearch" type="text" />
  <button id="btnSearch">
    Search!
  </button>
  <br />
  <p id='first-video-title'> </p>
  <p id='first-video-description'></p>
  <a target="_blank" id="first-video"></a>
  <div id='search-results'>
  
  </div>
</div>

听起来您的结果对象是一个 JSON 字符串。这实质上意味着它是 javascript 对象的字符串表示形式。您可以使用 JSON.parse().

将其解析为一个对象
var objResults = JSON.parse(results);
console.log(objResults);
console.log(objResults.link);

编辑

未能注意到您的结果实际上是一个数组。您只需要像这样访问它:console.log(results[0].link)。不需要 JSON.parse()