【问题标题】:Return Youtube video URL from keyword search with Javascript使用 Javascript 从关键字搜索返回 Youtube 视频 URL
【发布时间】:2017-07-04 09:37:48
【问题描述】:

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

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

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

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

>>youtube Tunak Tunak Tun

会回来 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);
  });
}

所以现在当我输入&gt;&gt;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] 在 discord 频道中。 http://i.imgur.com/Vorpn0f.png

所以现在的问题是我有链接,但我无法让它返回 JUST 链接,而且我不知道如何将它从混乱中拉出来。

【问题讨论】:

  • 试试 console.log(results.link)
  • @jonofan 未定义

标签: javascript node.js parsing youtube discord


【解决方案1】:

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

这个方法需要你setup a google API key,然后enable youtube API access.

我已从小提琴中删除了我的 google API 密钥,因此您需要进行设置。如果你想先测试,我可以 PM 你我的。

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>

【讨论】:

  • 对于遇到此问题并需要在浏览器中使用某些内容的任何人来说,这实际上效果很好。
【解决方案2】:

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

var objResults = JSON.parse(results);
console.log(objResults);
console.log(objResults.link);

编辑

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

【讨论】:

  • 结果我得到了pastebin.com/yUr2Jy3。我什至不知道它现在在咬什么。这就是我输入您的 sn-p pastebin.com/qBiRhWXj 的方式和位置
  • @Paraxo 第一个 pastebin 链接坏了,所以看不到你的错误,只有你的代码。
  • @Paraxo 已更新此答案,您实际上不需要解析它。像数组一样访问它。
  • 这行得通,但你知道错误是什么试图解析它SyntaxError: Unexpected token o in JSON at position 1
  • @Paraxo 您只能解析 JSON 字符串,不能解析对象。您遇到错误的事实促使我去重新检查您的原始控制台输出。 :)
猜你喜欢
  • 1970-01-01
  • 2013-03-02
  • 2016-07-13
  • 1970-01-01
  • 2012-09-28
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
  • 2015-01-14
相关资源
最近更新 更多