2

I am trying to implement a bot using Telegram, Dialogflow and Firebase. I am having trouble with this function:

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 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);
      });
  }

I am sure that the function works fine becasue the console.log() in the firebase console work fine as they show what they are supposed to; and I am getting no errors back either...

Here are my dependencies from 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 am handling the intents:

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

and this is the function that calls 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() of the welcome function are showing. From what I have read online, the dependencies are fine and should work.So I don't know what else to try, since I have (I think) done correctly every suggestion found.Please help...

  • 1
    Your example shows you explicitly calling `return findDoc(agent)`. Can you update the question to show the function that is making this call? It would also help if you update the code to show how you're registering the Intent Handler for the Intent that is being called. – Prisoner Apr 17 '20 at 01:51
  • 1
    Hi, I updated the code to the latest version...still having the same issue. Sorry for taking so long to answer.. – Eugenia Castilla Apr 25 '20 at 18:49

1 Answers1

2

The issue is that, although findDoc(agent) handles things asynchronously and returns a Promise, you aren't using this promise as part of your welcome() handler. The dialogflow-fulfillment library requires you to return a Promise from your handler if you are doing any asynchronous operation.

It appears to work since the Promise is completing, so the calls to console.log() do work as expected. But since you aren't returning this Promise to the dispatcher, it only sends back everything from agent.add() up to the point of the async operations.

In your case, the solution is simple. Since findDoc() is returning a Promise, all you need to do is have welcome() return this promise as well. Something like this should work:

function welcome(agent){
  console.log(`Estoy en la funcion de welcome`);
  agent.add(`Welcome`);
  return findDoc(agent);
}
Prisoner
  • 49,922
  • 7
  • 53
  • 105
  • Thank you so much!!! I can't believe I haven't figured that one out earlier....you saved my final degree project; let's hope I don't need more help. Thank you!!!! – Eugenia Castilla Apr 25 '20 at 21:51
  • 1
    It's easy to trip up with Promises sometimes, which is why I asked for details about how you were calling it. Glad it helped - and if you do need further help, just remember to create a new question with as many details as you can. – Prisoner Apr 25 '20 at 21:58
  • I have the same situation as Eugenia, but still having trouble after your solution @Prisoner https://stackoverflow.com/questions/63653304/why-am-i-getting-undefined-on-this-function – vpego Aug 30 '20 at 12:37