# Final code

## Explanation

Dummy responses are great but we want to fetch our data from a database since we can't add everyone at the entity values.&#x20;

For each of the 'get\_location', 'get\_name' and 'get\_skill' intents enable the fulfilment.

![Enable fulfillment for each intent](/files/-LGrH5brdSv_kY97j0k4)

\
Then we need to add the intent names at the intent map in our inline editor:

1. Go back to[ ](https://console.dialogflow.com/)[https://console.dialogflow.com/](https://console.dialogflow.com/a)
2. Click Fulfilment&#x20;
3. In your Inline Editor(Powered by Cloud Functions for Firebase) make sure you have the code below:

```
...
intentMap.set("Default Welcome Intent - search - get_name", searchName);
intentMap.set("Default Welcome Intent - search - get_location",searchLocation);
intentMap.set("Default Welcome Intent - search - get_skill", searchSkill);
```

then we need to initialize our database:

```
var admin = require("firebase-admin");
admin.initializeApp({
  databaseURL: "<<<COPY_THIS_FROM_FIREBASE_DATABASE>>>"
});

var db = admin.database();
```

Finally, we need to create our 3 methods:

```
function searchName(agent) {
      var results = db.ref("myDatabase");
      results
        .orderByChild("Name")
        .startAt(agent.parameters.person_name)
        .endAt(`${agent.parameters.person_name}~`)
        .on("value", function(snapshot) {
          snapshot.forEach(function(data) {
            agent.add("The WTM lead is " + data.val().Email);
          });
        });
    }
```

```
function searchLocation(agent) {
      var ref = db.ref("myDatabase");
      ref
        .orderByChild("Location")
        .equalTo(agent.parameters.person_location)
        .on("value", function(snapshot) {
          snapshot.forEach(function(data) {
            console.log(
              "The WTM lead" + data.val().Name + " - " + data.val().Location
            );
            agent.add(
              "The WTM lead" +
                data.val().Name +
                " is based in " +
                data.val().Location
            );
          });
        });
    }
```

```
function searchSkill(agent) {
      var scoresRef = db.ref("myDatabase");
      scoresRef
        .orderByChild("Skill")
        .equalTo(agent.parameters.person_skill)
        .on("value", function(snapshot) {
          snapshot.forEach(function(data) {
            agent.add(
              "The WTM lead expert at " +
                data.val().Skill +
                " is " +
                data.val().Name
            );
          });
        });
    }
```

## Final Code

This is how the **final code** can look like.

**IMPORTANT**: **make sure you have your own Database URL, instead of**: `https://wtm-summit-f6708.firebaseio.com`&#x20;

{% code title="index.js" %}

```javascript
const functions = require(firebase-functions); 
const { WebhookClient } = require(dialogflow-fulfillment); 
const { Card, Suggestion } = require(dialogflow-fulfillment);
process.env.DEBUG = 'dialogflow:debug'; 
// enables lib debugging statements
var admin = require(firebase-admin); 
admin.initializeApp({ databaseURL: https://wtm-summit-f6708.firebaseio.com/ });
var db = admin.database();
process.env.DEBUG = "dialogflow:debug"; // enables lib debugging statements
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(`Hello! Welcome to the WTM leads directory conversational app. Would you like to find a lead by 1. Name,  2. Location or 3. Skill`);
}

function fallback(agent) {
  agent.add(`Dear WTM Lead, sorry but could you say that one more time?`);
  agent.add(`hey WTM Lead, I missed what you said. Say it again?`);
}

function getSearchTerm(agent) {
  if (agent.parameters.search_terms == 1) {
    agent.add(`What's the WTM lead's name?`);
  } else if (agent.parameters.search_terms == 2) {
    agent.add(`For which location are you interested?`);
  } else {
    agent.add(`Which skill are you looking for?`);
  }
}

function searchName(agent) {
  var results = db.ref("databaseAmandaEliza");
  results
    .orderByChild("Name")
    .startAt(agent.parameters.person_name)
    .endAt(`${agent.parameters.person_name}~`)
    .on("value", function(snapshot) {
      snapshot.forEach(function(data) {
          console.log(`The WTM lead's email is ${data.val().Email}`);
        agent.add(`The WTM lead's email is ${data.val().Email}`);
      });
    });
}

function searchLocation(agent) {
  var ref = db.ref("databaseAmandaEliza");
  ref
    .orderByChild("Location")
    .equalTo(agent.parameters.person_location)
    .on("value", function(snapshot) {
      snapshot.forEach(function(data) {
        console.log(
          "The WTM lead" + data.val().Name + " - " + data.val().Location
        );
        agent.add(
          "The WTM lead " +
            data.val().Name +
            " is based in " +
            data.val().Location
        );
      });
    });
}

function searchSkill(agent) {
  var scoresRef = db.ref("databaseAmandaEliza");
  scoresRef
    .orderByChild("Skill")
    .equalTo(agent.parameters.person_skill)
    .on("value", function(snapshot) {
      snapshot.forEach(function(data) {
        agent.add(
          "The WTM lead expert at " +
            data.val().Skill +
            " is " +
            data.val().Name
        );
      });
    });
}

let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set("Default Welcome Intent - search", getSearchTerm);
intentMap.set("Default Welcome Intent - search - get_name", searchName);
intentMap.set("Default Welcome Intent - search - get_location",searchLocation);
intentMap.set("Default Welcome Intent - search - get_skill", searchSkill);
agent.handleRequest(intentMap);
} );
```

{% endcode %}

And the `package.json` tab:

`{ "name": "dialogflowFirebaseFulfillment", "description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase", "version": "0.0.1", "private": true, "license": "Apache Version 2.0", "author": "Google Inc.", "engines": { "node": "~6.0" }, "scripts": { "start": "firebase serve --only functions:dialogflowFirebaseFulfillment", "deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment" }, "dependencies": { "actions-on-google": "2.0.0-alpha.4", "firebase-admin": "^5.4.2", "firebase-functions": "^0.5.7", "dialogflow": "^0.1.0", "dialogflow-fulfillment": "0.3.0-beta.3" }}`


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wtm-assistant.gitbook.io/project/webhook.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
