javascript - 生成令牌以调用 Dialogflow V2
问题描述
我需要调用 Dialogflow V2 API,但为此我需要生成一个令牌。我发现了很多关于如何做到这一点的代码,但对我不起作用。
我正在做一个 API 来生成令牌,然后将令牌传递给另一个 API 以调用 DialogFlow API。
谁能帮助我如何生成一个令牌来调用 Dialogflow V2 API?
我的 API 生成令牌代码如下:
const express = require('express');
const router = express.Router();
const googleAuth = require('google-oauth-jwt');
function generateAccessToken() {
return new Promise((resolve) => {
googleAuth.authenticate(
{
email: "<myemail>",
key: "<myprivatekey>",
scopes: "https://www.googleapis.com/auth2/v4/token",
},
(err, token) => {
resolve(token);
},
);
});
}
router.get('/token', async(req, res) => {
try {
let tok = await generateAccessToken();
return res.status(200).send({ Token: tok});
} catch(err) {
return res.status(500).send({ error: 'Erro ao gerar token'});
}
});
module.exports = app => app.use('/', router);
解决方案
Dialogflow V2 不再使用开发人员/客户端访问令牌。您需要使用您的服务帐户密钥文件来访问 API。您可以按照本文设置您的服务帐户。设置服务帐户后,您可以使用 nodejs检查对话流的示例实现。
安装客户端库:
npm install @google-cloud/dialogflow
来自github 链接的代码片段:
const dialogflow = require('@google-cloud/dialogflow');
const uuid = require('uuid');
/**
* Send a query to the dialogflow agent, and return the query result.
* @param {string} projectId The project to be used
*/
async function runSample(projectId = 'your-project-id') {
// A unique identifier for the given session
const sessionId = uuid.v4();
// Create a new session
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.projectAgentSessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: 'hello',
// The language used by the client (en-US)
languageCode: 'en-US',
},
},
};
// Send request and log result
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
}
推荐阅读
- javascript - 2 篇具有相同“数据类型”的文章
- angularjs - AngularJs http请求优先级和http拦截器
- python - 如何打印 x 行的循环标签?
- java - 如何为 graphql-java-servlet 和 Micronaut 控制器配置 GraphQL servlet 端点?
- javascript - 如何在表单提交时选择打开新窗口或保持不变?
- java - Eclipse 2019-03 中 Java v3.141.59 中的类路径不起作用
- symfony - 如何将客户端连接到 Symfony API 以进行 OAuth2 身份验证
- c# - C# 类引用类型
- python - 使用 pyinstaller 运行具有 xgboost 包的 exe 文件时出错
- google-cloud-platform - 以特定间隔创建动态 Cron 作业