marcz2007
marcz2007

Reputation: 167

How do I use the Spotify api endpoint (the URL of the API is included below) to play a specific song from my index.js file?

I am making a Google assistant app which (1). takes the emotion of the user, (2). retrieves a song from a pre analysed database of the same emotion and (3). plays that song via Spotify.

I have finished with parts 1 and 2 but am struggling with the 3rd part. I have found on here ( https://developer.spotify.com/console/put-play ) the API for sending a POST request to Spotify which plays a certain song or album. How do I convert this information into a POST request from my index.js file?

For example, if I wanted to POST the Spotify code for Red Hot Chili Peppers' "Suck My Kiss", what would the code look like for sending the spotify track id?

3
    artist: 
      "Red Hot Chili Peppers"
    id: 
      "4"
    maxEmotion: 
      "anger"
    score: 
      "0.578864"
    song: 
      "Suck My Kiss"
    spotifyCode: 
      "spotify:track:0psB5QzGb4653K0uaPgEyh"

I have tried using the Webhook format but am not sure if I understand the right way to use this and also it would mean that my entire index.js file is useless (since you can only have one or the other on the Google Assistant). So I am interested to see how to do this in the index.js file if possible? I have included the most important code below:

'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);
});

Upvotes: 0

Views: 541

Answers (1)

marcz2007
marcz2007

Reputation: 167

SOLVED: Here is the code below (using the Google assistant agent to say 'Enjoy' before it plays):

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);
    });
}

Upvotes: 1

Related Questions