我正在尝试使用 Telegram、Dialogflow 和 Firebase 实现一个机器人。 我在使用此功能时遇到问题:
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);
});
}
我确信该功能可以正常工作,因为 firebase 控制台中的 console.log() 可以正常工作,因为它们显示了应有的内容;而且我也没有收到任何错误...
这是我的 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"
}
这就是我处理意图的方式:
intentMap.set('Default Welcome Intent', welcome);
这是调用 findDoc() 函数的函数:
function welcome(agent){
console.log(`Estoy en la funcion de welcome`);
agent.add(`Welcome`);
findDoc(agent);
}
欢迎函数的console.log()和agent.add()都显示了。 从我在网上读到的内容来看,依赖关系很好并且应该可以工作。所以我不知道还能尝试什么,因为我(我认为)已经正确地完成了找到的每一个建议。请帮助...
最佳答案
问题是,尽管 findDoc(agent)
异步处理事务并返回 Promise,但您并未将此 Promise 用作 welcome()
处理程序的一部分。如果您正在进行任何异步操作,dialogflow-fulfillment 库要求您从处理程序返回 Promise。
它似乎可以工作,因为 Promise 正在完成,因此对 console.log()
的调用可以按预期工作。但由于您没有将此 Promise 返回给调度程序,因此它只会发回从 agent.add()
到异步操作点的所有内容。
对于您的情况,解决方案很简单。由于 findDoc()
返回一个 Promise,因此您所需要做的就是让 welcome()
返回此 Promise。像这样的东西应该有效:
function welcome(agent){
console.log(`Estoy en la funcion de welcome`);
agent.add(`Welcome`);
return findDoc(agent);
}
关于javascript - agent.add() 不起作用,尽管 console.log() 起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61262516/