I would like to ask you how could I set to zero or null a lifespan of a context.
Example that I’ve tried:
const { WebhookClient } = require('dialogflow-fulfillment'); //"dialogflow-fulfillment": "^0.5.0"
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
agent.context.set({
'name': 'context_name',
'lifespan': 0
});
Or
agent.context.set({
'name': 'context_name',
'lifespan': null
});
Or
agent.setContext({ name: 'context_name', lifespan: 0 });
Or
agent.setContext({ name: 'context_name', lifespan: null });
or
agent.context.delete('context_name');
However, it always sets itself up to the value of 5 again.
Is there a way to delete or set it to zero?
you need to clear the context inside your intent handler. contexts are updated every time an intent is invoked. the preferred way to clear the context is
agent.context.delete('context_name');
You need to use clearContext():
const { WebhookClient } = require('dialogflow-fulfillment'); //"dialogflow-fulfillment": "^0.5.0"
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
agent.clearContext('context_name');
Hope it helps.
Try to set the lifespan to "-1" by doing the following:
agent.setContext({ name: 'context_name', lifespan: -1 });
Related
I tried doing this and adapting it from discordjs.guide, but I've either adapted something wrongly or it isn't working in my context. I tried this:
botMessage.react('❌');
const filter = (reaction, user) => {
return ['❌'].includes(reaction.emoji.name);
};
botMessage.awaitReactions({ filter, max: 1, time: 60000, errors: ['time'] }).then(collected => {
const reaction = collected.first();
console.log('a')
if(reaction.emoji.name === '❌'){
console.log('x')
botMessage.delete(1);
}
}).catch(collected => {});
botMessage is the response from the bot, since I am using a message command.
neither of the console.log() output anything.
any help is grateful and thank you
All you have to do is add the GUILD_MESSAGE_REACTIONS intent:
const client = new Client({ intents: [Intents.FLAGS.GUILD_MESSAGE_REACTIONS /* other intents */] });
I'm trying to create a simple AI chatbot command for my discord bot and it's working out, however, my Dialogflow doesn't seem to utilize any changes that I made like new intents or different responses. it always just returns the text from before the changes or just doesn't return anything at all.
I might be really stupid.
This is my code:
const Discord = require("discord.js")
const axios = require('axios');
const uuid = require('uuid');
const dialogflow = require('#google-cloud/dialogflow');
require("dotenv").config();
const projectId = "mydialogprojectid";
console.log(process.env.GOOGLE_APPLICATION_CREDENTIALS)
const config = require(`../config.json`)
exports.run = async(client, message, args) => {
message.channel.startTyping();
// A unique identifier for the given session
const sessionId = uuid.v4();
console.log(sessionId)
// 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: args.join(' '),
// The language used by the client (en-US)
languageCode: 'en-US',
},
},
};
// Send request and log result
const responses = await sessionClient.detectIntent(request);
const result = responses[0].queryResult;
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
console.log(result)
message.channel.stopTyping();
return message.channel.send(result.fulfillmentText ? result.fulfillmentText : "Something went wrong, forgive me please! I'm still in beta.")
}
I have the same issue it works on the Dialogflow console etc but when using it in discord it wouldnt find the intent etc like you described.
At first i thought this was just some cache issue. I will update this if i find a solution.
I have a default fallback intent that has a followup fallback intent that is attached to it (its a followup and also linked via output and input contexts). When I use the Dialogflow console to test it this feature it works well. However, when I go through my API I don't get the same effect. Can someone tell me where I am going wrong in my code?
"use strict";
const express = require("express");
const bodyParser = require("body-parser");
const app = express().use(bodyParser.json()); // creates http server
const { JWT } = require("google-auth-library");
const dialogflow = require("dialogflow");
const uuid = require("uuid");
const token = "token"; // type here your verification token
const result = "";
app.get("/", (req, res) => {
// check if verification token is correct
if (req.query.token !== token) {
return res.sendStatus(401);
}
// return challenge
return res.end(req.query.challenge);
});
app.post("/", (req, res) => {
// check if verification token is correct
if (req.query.token !== token) {
return res.sendStatus(401);
}
// print request body
console.log(req.body);
//var request = req;
//console.log(req.body.result.parameters.testing);
console.log(req.body.result.resolvedQuery);
runSample();
/**
* Send a query to the dialogflow agent, and return the query result.
* #param {string} projectId The project to be used
*/
async function runSample(projectId = "projectid") {
// A unique identifier for the given session
const sessionId = uuid.v4();
// Create a new session
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: req.body.result.resolvedQuery,
// 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}`);
//first not matched user query
if (result.intent.displayName === 'Default Fallback Intent')
{
result.fulfillmentText = 'Sorry, can you rephase your question?';
//result.fulfillmentText = 'Sorry, I am unable to answer your question';
}
if (result.intent.displayName === 'Default Fallback Intent - fallback')
{
//result.fulfillmentText = 'Sorry, can you rephase your question?';
result.fulfillmentText = 'Sorry, I am unable to answer your question';
}
// return a text response
const data = {
responses: [
{
type: "text",
elements: [result.fulfillmentText]
}
]
};
// return a text response
res.json(data);
} else {
console.log(` No intent matched.`);
}
}
});
// listen for requests :)
const listener = app.listen(3000, function() {
console.log("Your app is listening on port " + listener.address().port);
});
It does not look like you are either looking at the Context that is sent back as part of result, nor sending any Context in your call to sessionClient.detectIntent(request);. Dialogflow only maintains state in Contexts, in the same way a web server might maintain state through Cookies, so it does not know that an Output Context was set unless you send it as an Input Context the next round.
Because of this, every Fallback ends up being treated as the "Default Fallback Intent".
I have written webhook functions in the inline editor.
I get the deadline exceeded error intermittently.
All webhooks which failed with deadline exceeded error has webhook_latency_ms : 4992ms
In Dialogflow documentation (https://cloud.google.com/dialogflow/docs/fulfillment-how) it's mentioned that default timeout is 5sec, as per this my webhook should not throw this error because it's within 5sec.
The webhook has a very simple code that will take no more than 20-30ms.
Most of the time, the same function has webhook_latency_ms: less than 50ms.
What are the factors that could contribute to increased latency?
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
function testHandler(agent) {
let pendingHabits = agent.getContext('pendinghabits').parameters.habits;
let message = "Ok, let me know when you complete these habits:";
for (let i = 0; i < pendingHabits.length; i++) {
message = message + "\n" + pendingHabits[i];
}
let payload = {
type: 'message',
isPositive: false,
messages: [{ type: 0, text: message }]
};
agent.add(new Payload(agent.UNSPECIFIED, payload));
}})
You are missing your handler call, as i can see the code you have provided,
const functions = require('firebase-functions');
const {WebhookClient, Card, Suggestion} = require('dialogflow-fulfillment');
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((req, res) => {
const agent = new WebhookClient({ req, res });
function intentHandler(agent) {
agent.add('This message is from Dialogflow\'s Cloud Functions for Firebase editor!');
agent.add(new Card({
title: 'Title: this is a card title',
imageUrl: 'https://developers.google.com/actions/assistant.png',
text: 'This is the body text of a card. You can even use line\n breaks and emoji! 💁',
buttonText: 'This is a button',
buttonUrl: 'https://assistant.google.com/'
})
);
agent.add(new Suggestion('Quick Reply'));
agent.add(new Suggestion('Suggestion'));
}
agent.handleRequest(intentHandler);
});
Im wondering if there is a way to keep track of contexts of the intents as they follow. I know that you can use the output context of the previous intent as the input context of the followup intent. but this means i have to keep track of the lifespan as well. Is there another way???
var context = [];
async function TextRecognition(queryText) {
const sessionId = uuid.v4();
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: queryText,
// The language used by the client (en-US)
languageCode: 'en-US',
},
},
};
if (contextList !== null && contextList.length !== 0) {
console.log(contextList);
request.queryParams = {
contexts: context,
};
}
const responses = await sessionClient.detectIntent(request);
const result = responses[0].queryResult;
if (result.intent) {
if (typeof result.outputContexts[0] !== 'undefined') {
result.outputContexts.forEach(context => {
context.push(context);
});
}
return result.fulfillmentText;
} else {
console.log(`No intent matched.`);
}
}
found the answer :) there wasnt a problem in the first place just make sure to create sessionid for each client you dont need to keep track of anythiing dialogflow does it for you :p