The agent.add() function is malfunctioning, while console.log() is functioning properly

I'm currently working on integrating a bot using Telegram, Dialogflow, and Firebase. One particular function that I'm struggling with is as follows:

function findDoc(agent){
    const userId = request.body.originalDetectIntentRequest.payload.data.from.id.toString();
    const first_name = request.body.originalDetectIntentRequest.payload.data.from.first_name;
    console.log(`Telegram user ID: ${userId}, first_name: ${first_name}`);//THIS SHOWS
    agent.add(`voy a ver si existe el documento`);//THIS SHOWS
    agent.setContext({name: "firstTimer", lifespan:10});
    return db.collection('users').doc(''+userId).get()
      .then((doc) => {
        if (!doc.exists) {
          console.log(`New user created in database `);//THIS SHOWS
          agent.add(`New user created in the database`);//THIS DOESN'T SHOW
          var data={
            'id':userId, 
            'name':first_name, 
            'contadorP': 0,
            'doneQuestions': [],
          };
          return db.runTransaction((dataDB)=>{
            dataDB.set(db.collection('users').doc(''+userId), data,{merge:true});
            return Promise.resolve();
          }).catch((err) => {
                console.error(`Error creating file: `+err);
            });
        } else {
          console.log('Found Telegram profile: ', JSON.stringify(doc.data()));//THIS SHOWS
          const data = doc.data();
          agent.add(`User ${data.id} has the name of ${data.nombre}`);//THIS DOESN'T SHOW
        }
      })
      .catch((err) => {
        console.error(err);
      });
  }

Despite all indications pointing to this function working correctly (confirmed by the respective console.log() outputs), I am not encountering any errors.

Below are the dependencies listed in my package.json:

"dependencies": {
    "actions-on-google": "^2.5.0",
    "firebase-admin": "^8.2.0",
    "firebase-functions": "^2.0.2",
    "dialogflow": "^0.6.0",
    "dialogflow-fulfillment": "^0.6.1"
  }

This is how I'm handling intents:

  intentMap.set('Default Welcome Intent', welcome);

Additionally, here is the function that invokes the findDoc() function:

function welcome(agent){
    console.log(`Estoy en la funcion de welcome`);
    agent.add(`Welcome`);
    findDoc(agent);
  }

Both the console.log() and agent.add() within the welcome function are successfully displaying output. Despite affirmations from online resources regarding proper dependency management, I remain puzzled about why things aren't functioning as expected. I've exhaustively followed suggestions found online but have yet to resolve the issue at hand. Any assistance would be greatly appreciated...

Answer №1

The main issue here lies in the fact that while findDoc(agent) is designed to handle tasks asynchronously and return a Promise, you have not integrated this promise properly into your welcome() handler function. The dialogflow-fulfillment library mandates that you must return a Promise from your handler if any asynchronous operations are being performed.

Although it might seem like everything is working fine because the Promise does eventually complete, the absence of returning this Promise to the dispatcher results in only partial data being sent back – specifically up to the point where the async operations begin.

To resolve this problem, a straightforward solution can be implemented. Given that findDoc() already returns a Promise, all that is required is for welcome() to also return this specific promise. An adjusted code snippet such as the following should suffice:

function welcome(agent){
  console.log(`I am inside the welcome function`);
  agent.add(`Welcome`);
  return findDoc(agent);
}

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

When hovering over a select option, a description and clickable link will be displayed

I need to display a description with a clickable link when hovering over any option in the select tag. <div class="col-lg-4"> <div class="form-group"> <label class="form-label">Goal</label> <select name="semiTaskType ...

The magic of $.ajax lies in its ability to load an unexpected URL, diverging from my original

Every time I send a request using an absolute URL, Ajax is posting the wrong URL. For instance, when I request "http://localhost/app/home/session", it mistakenly calls "http://localhost/app/home/home/session" var baseURL = function(link) { var url = & ...

Utilizing long polling technique with jQuery/AJAX on the server end

Currently, I am facing an issue with long polling on a single page that contains multiple pages. The problem arises when a new request is made while a previous request is still processing. Even though I attempt to abort the previous request, it completes b ...

Is there a way for me to extract and showcase the initial 10 items bearing a particular class name from a different html document on my homepage?

I am looking to extract a list of movies from an HTML file titled "movies.html". The structure of the file is as follows: <div class="movie">Content 1</div> <div class="movie">Content 2</div> <div class=" ...

"Enhancing User Interaction with jQuery Hover State Dropdown Menus

Here's my issue: I've created a drop-down menu and I want the text color to change when hovering over the menu. Additionally, I'd like the hover state to remain active when hovering over the submenu. Currently, I'm using this code: $( ...

When setting up Vue.js for unit testing, the default installation may show a message stating that

Recently set up a fresh Vue project on Windows 7 using the VueJS UI utility. Unit testing with Jest enabled and added babel to the mix. However, when running "npm test" in the command line, an error is returned stating 'Error: no test specified' ...

npm package.json scripts not executing

Whenever I try to run npm start or npm run customScriptCommand, npm seems to not be executing anything on my project and just quickly returns a new line in the terminal. I attempted to solve this issue by uninstalling node and npm from my machine, then in ...

Electron: Interactive menu customization

Is there a way in Electron to dynamically enable/disable specific MenuItem in the context menu based on the element that the user right-clicks on? Additionally, I am looking for a method to identify the exact element clicked and pass that information to th ...

What is the best way to capture a screenshot of a website using its URL?

I've been curious about the possibility of capturing a screenshot of a remote website using only a URL and some JavaScript code. This functionality is often seen on bookmarking sites. I can't help but wonder if this is achieved through a virtual ...

Is it possible to manipulate an Angular #variableName in order to retrieve an ElementRef for an HTML element?

Suppose I have a scenario where I create a button like this: <button #myButton>My Button</button> ...and then use ViewChild in the following way: @ViewChild('myButton', { static: true }) createButton: ElementRef; In this case, creat ...

The issue with IE-9 is that it is mistakenly picking up the placeholder value as

My HTML code looks like this: <input id="SLOCriteriaOtherText" name="SLOCriteriaOtherText" style="width: 100%;" type="text" data-role="autocomplete" placeholder="Enter name for 'other' metric..." class="k-input" autocomplete="off" role="textb ...

Creating a delay in a test to ensure a 5-second wait before validating the appearance of an element using React testing library

I am currently facing an issue in my React component where an element is supposed to appear after a delay of 5 seconds. I have been trying to write a test using 'jest fake timers' to check if the element appears after the specified time, but hav ...

What is the procedure for selecting an element based on its child containing specifically filtered text?

Imagine a webpage with the following elements: <div data-search="type1"> any HTML <!-- .click is a child of any level --> <span class="click" data-source="page1.html">blue</span> <!-- let's call it "click1 ...

Create a variable and set it equal to the value of a form

I'm having trouble setting a value to a hidden form field that needs to come from a query string parameter. The function that extracts the query string parameter is working properly, but the function that assigns this variable to the hidden form field ...

Utilizing Promises with Multiple .then() in JavaScript

I'm currently in the process of creating an array structure. In this structure, we have different parts and each part contains articles. What I've done is create a promise to gather all the parts using .then(), then I need to iterate through eac ...

Can I deactivate JavaScript on my website directly from my server settings?

I'm currently attempting to link my Android application to a PHP script hosted on a free server. However, when my app tries to access the page, I receive an HTML message stating that JavaScript is disabled and needs to be enabled in order to view the ...

Improving the efficiency of JSON data retrieval in JavaScript

I possess a hefty 10MB JSON file with a structured layout comprising 10k entries: { entry_1: { description: "...", offset: "...", value: "...", fields: { field_1: { offset: "...", description: "...", ...

What is the process for triggering property decorators during runtime?

Wondering about dynamically invoking a property decorator at runtime. If we take a look at the code snippet below: function PropertyDecorator( target: Object, // The prototype of the class propertyKey: string | symbol // The name of th ...

Creating an import map using jspm2 can be done by following these steps

Currently, my goal is to utilize JSPM module loader to import javascript packages from npm instead of CDN and employ an offline package loader. Now, the next step involves incorporating an importmap script in order to successfully import modules like rea ...

How can we verify that the client has successfully completed the file download process?

I am currently working with a single large file. My goal is to accomplish the following tasks: 1) Upload the file to the server 2) Automatically delete the file from the server once it has been successfully downloaded by the user. Is there a method to ...