Tips for creating an Alexa skill that can vocalize JSON information using node.js

Currently, I am working on a project to develop an Alexa skill that can read out the headlines from the Google News API. I have obtained a JSON URL and now I am trying to create a function that can extract and read the titles using the Alexa device. Here is what I have coded so far: (I still need to add the main function with JSON parsing)

/**
 * Skill's App ID
 */
var APP_ID = undefined;
/**
 * The AlexaSkill prototype and helper functions
 */
var AlexaSkill = require('./AlexaSkill');

var News = function () {
    AlexaSkill.call(this, APP_ID);
};

// Extend AlexaSkill
News.prototype = Object.create(AlexaSkill.prototype);
News.prototype.constructor = News;

News.prototype.eventHandlers.onSessionStarted = function (sessionStartedRequest, session) {

};

News.prototype.eventHandlers.onLaunch = function (launchRequest, session, response) {
    handleNewsRequest(response);
};


News.prototype.eventHandlers.onSessionEnded = function (sessionEndedRequest, session) {

};

News.prototype.intentHandlers = {
    "NewsIntent": function (intent, session, response) {
        handleNewsRequest(response);
    },

    "AMAZON.HelpIntent": function (intent, session, response) {
        response.ask("You can ask me for the latest news headlines in the world right now. Simply ask Top News for the latest news.");
    },

    "AMAZON.StopIntent": function (intent, session, response) {
        var speechOutput = "Goodbye";
        response.tell(speechOutput);
    },

    "AMAZON.CancelIntent": function (intent, session, response) {
        var speechOutput = "Goodbye";
        response.tell(speechOutput);
    }
};

/**
 * News API
 */
function handleNewsRequest(response) {
  /**
   * This is where I need help!!!!!!!!
   */







    // Create speech output
    var speechOutput =     ;
    var cardTitle = "Top News";
    response.tellWithCard(speechOutput, cardTitle, speechOutput);
}

// Create the handler that responds to the Alexa Request.
exports.handler = function (event, context) {
    // Create an instance of the Top News skill.
    var news = new News();
    news.execute(event, context);
};

Answer №1

Retrieve data from an API by making a request and utilize the result in Alexa's tell function.

Consider utilizing the Request module to fetch data from the API. Refer to the first example on the npm website for guidance.

request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Display the HTML for the Google homepage. 
  }
});

As you await the response, it is recommended to incorporate Bluebird's Promisfication into the function. This ensures that you can wait for the response before passing it to the tell function due to potential delays in receiving data from the API.

var Promise = require("bluebird");
var Request = require("request");
Promise.promisifyAll(Request);

Request.getAsync(url)
.then(function(error, response, body){
    console.log(body);
});

Additionally, make use of JSON.parse to extract the necessary value from the body and incorporate it in the tell function.

var obj = JSON.parse(body);
response.tell(obj);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is AngularJS Experiencing Bugs with the Webcam getUserMedia API?

I recently created a webcam directive in AngularJS that utilizes a service. For reference, I followed this example: Surprisingly, the example works perfectly on my tablet, but when I integrate the code into my tablet's Google Chrome browser, it encou ...

Different text in AMP

Is there a way to make a line of text quickly fade in, stay visible for 5 seconds, fade out quickly, then have a different line of text quickly fade in, stay for about 5 seconds, fade out quickly, and repeat this process infinitely in AMP? I tried using ...

Implement a personalized click function for the delete icon in the mini cart

Is there a way to customize the click event for the remove button in the mini cart? function ajax_call(){ $.ajax({ url: ajax_url, type: 'post', data: {action : 'remove_from_cart','cart_item_key' : 10}, ...

Guide on fetching data from a different php file using jQuery's .load() method?

I am trying to use a basic .load() function from jQuery to load a div element with an id from another file in the same directory when changing the selected option in a selector. However, I am having trouble getting it to work. Nothing happens when I change ...

What is the best way to sort inertia data on the client-side?

Looking for a solution with my component that receives data, I have the following setup in my controller: route::get('/', function() { return inertia('foo', ['data' => Model::all()]) }); Within my Vue component: <templa ...

stopping action when hovering

Looking for some assistance with my javascript function that scrolls through an array of images on a set interval. I want to enhance it by pausing the rotation when hovering over any of the images. Javascript (function() { var rotator = document.getE ...

Difficulty Converting Android String into JSON Array

I am trying to parse a JSON string from a URL. TextView tv3 = (TextView) findViewById(R.id.tv3); TextView tv2 = (TextView) findViewById(R.id.tv2); TextView tv1 = (TextView) findViewById(R.id.tv1); String str = "[{\"ID\":\"1\",\"l ...

Code functioning correctly in Chrome but encountering issues in Firefox

I've come across an issue with my HTML and JavaScript code for a select drop-down box. My goal is to have the background color of the selected option update to match the color selected by the user. Currently, when using Firefox, the hover color chang ...

Make sure to execute the fire directive only when ng-repeat has completed

Currently, I am utilizing owl carousel with data being fetched through an Ajax call. Once the data populates the HTML content using ng-repeat, I need to trigger the directive that initializes the owl carousel. How can I achieve this? One approach I consid ...

When using multiple select tags with *ngFor in Angular, modifying the value of the first select tag will have an

<table id="DataTable" border="1" ALIGN="center"> <tr ALIGN="center"> <th>name</th> <th>address</th> <th>number</th> <th>type</th> </tr> <tr class="tcat" *ngFor ...

eval concealing program in JGraph compared to obfuscation and packing

Many times when the topic of eval is brought up, the response is always the same - avoid using eval. However, I believe there is a valid reason for eval to exist. Nevertheless, there are numerous pitfalls to consider. Regarding jgraph - why do they incorp ...

The Art of Determining the Text's Baseline

My goal is to create a test that determines whether the text rendered inside an <input> has the same baseline as a label: To achieve this, I want to calculate the baseline of the rendered text in each element and compare their values. Is it possible ...

Guide for integrating the shadcn/ui Range Date Picker within a Form

Encountering an issue with using The Range Date Picker within the Form component. Specifically, I am looking to store {from, to} values of the range in an object, however, utilizing an object as a Form field value results in error messages not functioning ...

Tips for updating the display by fetching data from a database through a websocket

I am looking for a solution to update a specific part of my webpage without having to refresh the entire content. On my index.html page, I have three panels displaying various ticket statuses. I want to automatically update the number of resolved tickets s ...

Vuetify's data table now displays the previous and next page buttons on the left side if the items-per-page option is hidden

I need help hiding the items-per-page choices in a table without affecting the next/previous functionality. To achieve this, I've set the following props: :footer-props="{ 'items-per-page-options':[10], &apo ...

When it comes to using jQuery, I find that it only functions properly when I manually input the code into the Google Chrome console. Otherwise

Below is the HTML snippet: <textarea cols="5" disabled id="textareRSAKeypair"> @Model["keypair"] </textarea> <a href="#" class="btn btn-primary" id="downloadKeypair">Download Key</a> Here is the jQuery code: <script src="ht ...

Dealing with problems related to types in React and TypeScript createContext

Struggling to pass the todos (initial state) and addNewTodo (methods) using React Context hook and typescript. Despite trying multiple solutions, errors persist. Partial generics do not cause issues in the context component, but I encounter the error Cann ...

Adjust the vertical size and smoothly lower a text input field

When a user clicks on a textarea, I want it to smoothly change height to 60px and slide down in one fluid animation. Check out the JSFiddle example here: http://jsfiddle.net/MgcDU/6399/ HTML: <div class="container"> <div class="well"> ...

Implementing a JSON array to object conversion in an Express REST API

After conducting a test on a REST API using Postman, the outcome was as follows: { "success": true, "message": "success", "data": [ { "id_buku": 9, "judul_bu ...

Encountering an error: "Unhandled promise rejection SyntaxError: Unexpected character in JSON data at line 1 column 1."

When the submit button is clicked, my registration form data is sent using an event function called postData() in React. The user data is sent at the register route, and I have mentioned line numbers in the comments: const postData = async(event) =>{ ...