Developer Guides

Building a News Chat bot with CivicFeed

Introduction

In this developer guide, we’re going to show you how to build a chat bot that responds with recent news articles about a specific topic you ask it. 

We’ll use Dialogflow, a framework for creating bots to take care of the language processing and deploying it out to popular messenger services and CivicFeed’s News API to power the news feed.

Prerequisites

To follow this tutorial, we’ll assume you’re developing in a Mac environment and have some familiarity with developing basic software.

Step 1 – Setting up your CivicFeed Developer Account

In this step, we’ll create your CivicFeed Developer account and get an API key.

First, go to https://developers.civicfeed.com/

Then, click “Get Started”

Fill out your username, password, email and phone number then confirm your account.  

After logging in, go to your Dashboard, located in the top right:

Take note of your API key and save it for later.

Step 2 – Setting up your Dialogflow account

Go to Dialogflow.com and click “Sign-up for Free”

Sign-in with your Google account.  If you don’t have one, you’ll need to create one first.

Step 3 – Create a new agent

Pick a name for your agent – such as “CivicFeed-News” and select the correct timezone.

Step 4 – “Hello World”

Let’s start by making sure our bot knows how to say “Hello”.  Click on “Default Welcome Intent”

If you scroll down, you’ll also see some default responses that your bot will use.

Let’s test it out by typing “Hello” on the sidebar.  

Be sure to enable Billing within the Google Cloud console at console.cloud.google.com

Step 5 – “Tell me the news” intent

Let’s go back to the “Intents” section and add our own for telling the user the news.

Start by clicking “Create Intent”

Then, setup your “Training phrases” and “Action and Parameters” as follows:

In addition, let’s define a Prompt by clicking “Define Prompt” and setting it up as follows:

For now, we’ll set up a temporary Response to make sure that our Intent is triggering correctly.  

Let’s “Save” it and test it by typing “Tell me news about Trump” on the right hand side.

Step 6 – Wiring up the News

Let’s enable a web hook call for this intent by clicking “Fulfillment” and turning the switch on.

While we’re here, let’s also name our intent something more friendly, like “News”.  Then hit Save.

On the left, click “Fulfillment”.  We’re going to leverage Google’s built-in Cloud Functions to connect our bot to the CivicFeed News API.

Drop this code into the Inline Editor.  

// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';
 
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
 
const axios = require('axios');

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
 
var CVFNews = axios.create({
    method: 'get',
    baseURL: 'https://api-beta.civicfeed.com',
    headers: {'x-api-key': 'ENTER OUR API KEY HERE'}
    });
 
 
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
 
  function welcome(agent) {
    agent.add(`Welcome to my agent!`);
  }
 
  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
}

  function news(agent) {
    console.log('news function', JSON.stringify(request.body.queryResult.parameters))
    const word = request.body.queryResult.parameters.search;
    return CVFNews.get('/news/search?q='+encodeURIComponent(word)+'&limit=1&tags=news')
        .then(function(response){
            const {title, source} = response.data.articles[0];
            console.log('response', response.data.articles[0])
            return agent.add('The last article about ' + word + ' was: ' + title + ' and was published by ' + source.name);
        })
        .catch(function(error){
            console.log(error);
        });
  }

  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('News', news);
  // intentMap.set('your intent name here', googleAssistantHandler);
  agent.handleRequest(intentMap);
});

You’ve created code that leverages the “axios” package to call the CivicFeed API.  Be sure to update your API key here!

Then, you’ve added a new function to the intentMaps to handle the “News” intent. 

CivicFeed’s API is called with the action parameter defined above and is set to return a single article from its news archive.  By default, it will return the most recent article in CivicFeed’s database.

Lastly, click on “package.json” and be sure to add “axios” as a dependency.

Go ahead and hit “Deploy” and test the code on the right.

If all goes well, you’ve just created your first bot! 

Next, play around with Integrations and try integrating your bot into apps like Facebook Messenger.

Leave a Reply