我正在制作一个谷歌助理应用程序,它(1)。 获取用户的情感,(2)。 从预先分析的相同情感数据库中检索歌曲,以及 (3)。 通过Spotify播放这首歌。
我已经完成了第 1 部分和第 2 部分,但正在为第 3 部分苦苦挣扎。我在这里(https://developer.spotify.com/console/put-play)找到了用于向Spotify发送POST请求的API,该请求播放某首歌曲或专辑。如何将此信息转换为我的索引.js文件中的 POST 请求?
例如,如果我想发布Red Hot Chili Peppers的"吮吸我的吻"的Spotify代码,发送spotify曲目ID的代码会是什么样子?
3
artist:
"Red Hot Chili Peppers"
id:
"4"
maxEmotion:
"anger"
score:
"0.578864"
song:
"Suck My Kiss"
spotifyCode:
"spotify:track:0psB5QzGb4653K0uaPgEyh"
我尝试过使用 Webhook 格式,但不确定我是否理解使用它的正确方法,这也意味着我的整个索引.js文件毫无用处(因为您只能在 Google Assistant 上拥有一个或另一个)。所以我有兴趣看看如果可能的话如何在索引.js文件中执行此操作?我在下面包含了最重要的代码:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {WebhookClient} = require('dialogflow-fulfillment');
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: 'ws://mood-magic-four-ptwvjb.firebaseio.com/'
});
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
//4
function playAngrySong (agent) {
// Get the database collection 'dialogflow' and document 'agent'
return admin.database().ref((`3`) ).once('value').then((snapshot) => {
const song = snapshot.child('song').val();
const artist = snapshot.child('artist').val();
agent.add(`I will play ${song} by ${artist}`);
// THIS IS WHERE I NEED THE POST TO THE SPOTIFY API
});
}
// Map from Dialogflow intent names to functions to be run when the intent is matched
let intentMap = new Map();
intentMap.set('-Angry - yes', playAngrySong);
agent.handleRequest(intentMap);
});
已解决: 以下是以下代码(使用 Google 助理代理在播放前说"享受"):
function playMusic(agent){
agent.add('Enjoy!');
var request = require("request");
var options = { method: 'PUT',
url: 'https://api.spotify.com/v1/me/player/play',
headers:
{ 'cache-control': 'no-cache,no-cache',
'Content-Type': 'application/json',
Authorization: `Bearer ${Access.accessToken}`,
Accept: 'application/json' },
body: { uris: [ `${SongInfo.Spotify_uri}` ] },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log('This is the body of the play music request ' + body);
});
}