Skip to content

Instantly share code, notes, and snippets.

@ilKhr
Last active September 20, 2020 08:28
Show Gist options
  • Save ilKhr/8c7a676f9dc964d5d274ad8ad9b65ee4 to your computer and use it in GitHub Desktop.
Save ilKhr/8c7a676f9dc964d5d274ad8ad9b65ee4 to your computer and use it in GitHub Desktop.
File for save contexts DialogFlow when use Default Intent
export type DfRequest = {
headers: object;
body: {
session: string;
responseId: string;
queryResult: IQueryResult;
originalDetectIntentRequest: IOriginalDetectIntentRequest;
};
};
export type IQueryParameters = {
age?: number;
};
export type IQueryResult = {
queryText: string;
parameters: IQueryParameters;
allRequiredParamsPresent: boolean;
fulfillmentText: object;
fulfillmentMessages: [
{
text: {
text: Array<string>;
};
}
];
outputContexts: OutputContexts;
intent: {
name: string;
displayName: string;
};
intentDetectionConfidence: 1;
diagnosticInfo: {};
languageCode: string;
};
export interface IOriginalDetectIntentRequest {
payload: {
data: {
date: number;
message_id: number;
text: string;
from: {
id: number;
language_code: string;
first_name: string;
username: string;
};
chat: { id: string; type: string };
};
};
}
export type OutputContexts = Array<ItemContext>;
export type ItemContext = {
name: string;
parameters: ITargetContextParams;
};
export interface ITargetContextParams {
//here you write your params field
}
import { WebhookClient } from "dialogflow-fulfillment";
import { IQueryResult, ITargetContextParams } from "dfQuery";
type IReqContext = {
name: string;
parameters: object;
lifespan: number;
};
export async function saveDefaultContexts(
agent: WebhookClient,
queryResult: IQueryResult
) {
console.log(
"<--------------------------saveDefaultContexts running-------------------------->"
);
try {
const targetContext = agent.context.get("YOUR-MAIN-CONTEXT-WITH-ALL-PARAMS");
const targetContextParams: ITargetContextParams = targetContext
? JSON.parse(JSON.stringify(targetContext.parameters))
: {};
const contexts = queryResult.outputContexts.map((item) => {
const tmp = item.name.split("/").slice();
return tmp[tmp.length - 1];
});
contexts.forEach((context) => {
const reqContext: IReqContext =
context === "YOUR-MAIN-CONTEXT-WITH-ALL-PARAMS"
? {
name: context,
parameters: targetContextParams,
lifespan: 1,
}
: {
name: context,
parameters: {},
lifespan: 1,
};
try {
agent.context.set(reqContext);
} catch (e) {
console.log("ERROR: ", e);
}
});
agent.end("");
} catch (e) {
console.log(e);
throw new Error("Error in `saveDefaultContext`");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment