以 Marco 的出色回答为基础——这里有一个更简单的版本:
package.json
{
"name": "credtest",
"version": "1.0.0",
"dependencies": {
"dialogflow": "^1.2.0",
"pb-util": "^0.1.3"
}
}
index.js
const {ContextsClient} = require('dialogflow')
const { struct } = require('pb-util');
// REPLACE THESE:
/*
1. Service Account Credential file (KEEP SAFE)
// where/how to get this key: https://cloud.google.com/iam/docs/creating-managing-service-account-keys
// For different auth options, see Marco Casagrande's explainer: https://stackoverflow.com/questions/50545943/dialogflow-easy-way-for-authorization/50546430#50546430)
// Note: JSON hard-coded below for copy/paste, just import/require in when using for real
*/
const credential = {
"type": "__REPLACE__ME___",
"project_id": "__REPLACE__ME___",
"private_key_id": "__REPLACE__ME___",
"private_key": "__REPLACE__ME___",
"client_email": "__REPLACE__ME___",
"client_id": "__REPLACE__ME___",
"auth_uri": "__REPLACE__ME___",
"token_uri": "__REPLACE__ME___",
"auth_provider_x509_cert_url": "__REPLACE__ME___",
"client_x509_cert_url": "__REPLACE__ME___"
}
/*
2. Project ID, Google cloud project id
Tip: notice the service-account naturally already has your product id
*/
const project_id = '__REPLACE__ME___' // This is your google cloud project
const client = new ContextsClient({
credentials: credential
});
createContext('123456789', {name: 'bongo_context', lifespanCount: 3, parameters: {a:1, b:2, c:3 }} )
function createContext(sessionID, {name, lifespanCount, parameters = {} } = {} ) {
const formattedParent = client.sessionPath(project_id, sessionID);
const formattedContextName = `projects/${project_id}/agent/sessions/${sessionID}/contexts/${name}`
const context = {
"name": formattedContextName,
"lifespanCount": 2,
"parameters": struct.encode(parameters)
}
const request = {
parent: formattedParent,
context: context,
}
client.createContext(request)
.then(responses => {
const response = responses[0];
console.log('context now active:', response)
})
.catch(err => {
console.error(err);
});
}