好吧,所以我在Discord中为我的服务器制作机器人,我想要实现的是一个youtube命令 .
我一直在搜索并查看Youtube API,我只能找到他们搜索的浏览器
我正在使用nodejs从我的笔记本电脑上运行它,而我的机器人运行了discord.js
我有一个类似的命令,做一个MAL和一个城市词典搜索,但我什么也没发现,也不知道如何用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("&",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] } } ]
在控制台中和不和谐 Channels 中的 [object Object]
. http://i.imgur.com/Vorpn0f.png
所以现在的问题是我的链接在我的范围内,但我无法让它返回 JUST 链接,我不知道如何把它从那个混乱中拉出来 .
2 回答
听起来你的结果对象是
JSON
字符串 . 这实质上意味着它是javascript对象的字符串表示 . 您可以使用JSON.parse()将其解析为对象 .EDIT
无法注意到您的结果实际上是一个数组 . 您只需要像这样访问它:
console.log(results[0].link)
. 不应该JSON.parse()
好的,这里's another approach that is working for me, using the google javascript API. Once again, the SO snippet doesn' t运行它,所以I'll link you to the fiddle.
此方法需要您setup a google API key,然后enable youtube API access.
我已经从小提琴中删除了我的谷歌API密钥,所以你需要设置它 . 如果你想先测试,我可以PM你 .