DEV Community

Cover image for Google action fetching data from an RSS feed
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Google action fetching data from an RSS feed

In the previous article, we looked at fetching data from an API for our Google action.

However, in my case, I don't have an API at my disposal. I have an RSS feed, so let's see how we can use that to fetch the latest article, which we can return.

If you'd like to follow along, you can use this article as your starting point.

Fetching RSS data and prompt in Google action

Since our action is based on a cloud function, we can add some dynamic data fetching.

Open up your webhook package.json, and let's first add the package we need to parse XML.

{
  "dependencies": {
      // The other deps
    "xml-js": "^1.6.11"
  }
}
Enter fullscreen mode Exit fullscreen mode

Now you can head over to the index.js file and start importing the packages we need.
This includes the node-fetch API.

const fetch = require('node-fetch');
const convert = require('xml-js');
Enter fullscreen mode Exit fullscreen mode

Then we'll need to convert our handle function to an async function.

// Previous
app.handle('greeting', (conv) => {});

// New
app.handle('greeting', async (conv) => {});
Enter fullscreen mode Exit fullscreen mode

And then, we can start by fetching our RSS feed. This can be parsed as plain text.

const response = await fetch('https://daily-dev-tips.com/sitemap.xml');
const text = await response.text();
Enter fullscreen mode Exit fullscreen mode

From here, we can use the xml-js package to convert it into a readable stream of JSON.

const jsonData = JSON.parse(convert.xml2json(text, { compact: true }));
Enter fullscreen mode Exit fullscreen mode

Note: I'm using compact mode, which removes a lot of unneeded lines

Then we can add a new card with the first item's data.

conv.add(
  new Card({
    title: jsonData.feed.entry[0].title._cdata,
    text: jsonData.feed.entry[0].content._cdata,
    image: new Image({
      url: 'https://daily-dev-tips.com/images/logo.png',
      alt: 'Daily Dev Tips logo',
    }),
  })
);
Enter fullscreen mode Exit fullscreen mode

Save and deploy your function; wait for the deployment to finish and test it out.

Google actions get data from RSS

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (0)