> For the complete documentation index, see [llms.txt](https://amandacavallaro.gitbook.io/conversacomigo/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://amandacavallaro.gitbook.io/conversacomigo/codigo-final.md).

# Código final

1.Clique em `fulfilment` no menu esquerdo

2.No `Inline Editor(Powered by Cloud Functions for Firebase)` você pode adicionar o código abaixo.

3\. Clique no botão azul `deploy` abaixo de todo o código.

{% hint style="info" %}
**IMPORTANTE**: certifique-se que você possui o seu proório URL do banco de dados ao invés de: [`https://gdg-cloud-fc257.firebaseio.com/`](https://gdg-cloud-fc257.firebaseio.com/)&#x20;
{% endhint %}

{% tabs %}
{% tab 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://gdg-cloud-fc257.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(
        `Olá, bem vindo ao app de conversação GDG Cloud. Você gostaria de procurar um organizador por 1.Name ou 2.Skill?`
      );
  }
​
  function fallback(agent) {
    agent.add(`Eu não entendi`);
    agent.add(`Desculpe, poderia falar novamente?`);
  }
    
  function getSearchTerm(agent) {
    if (agent.parameters.search_terms == 1) {
      agent.add(`Qual o nome do organizador do GDG Cloud?`);
    } else {
      agent.add(`Qual skill você está procurando?`);
    }
  }

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) {
          console.log(`The GDG Cloud lead's email is ${data.val().Email}`);
        agent.add(`The GDG Cloud lead's email is ${data.val().Email}`);
      });
    });
}
​
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 GDG Cloud 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_skill", searchSkill);
agent.handleRequest(intentMap);
} );
```

{% endtab %}

{% tab title="package.json" %}

```javascript
{ "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" }}
```

{% endtab %}
{% endtabs %}

E na aba `package.json` adicione o seguinte:

{% code title="package.json" %}

```javascript
{ "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" }}
```

{% endcode %}

## Explicação

Que maravilha, ao seguir estes passos você utilizou o `Firebase Real time Database`  assim como o `firebase inline editor` para fazer com que o seus intents comuniquem com o banco de dados e dêem as respostas corretas aos usuários conversando com a sua action!


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://amandacavallaro.gitbook.io/conversacomigo/codigo-final.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.
