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.
Related
I am beginner in dialogflow and trying to create intent and context through code, but i am unable to achieve it.This is the code i am using,
i referred the below link also but no help,
https://cloud.google.com/dialogflow/es/docs/how/manage-intents#create_intent
but getting below error:
function main(
projectId = 'trainer-gulw',
displayName = 'intent_001',
trainingPhrasesParts = [
'Hello, What is weather today?',
'How is the weather today?',
],
messageTexts = ['Rainy', 'Sunny']
) {
const dialogflow = require('#google-cloud/dialogflow');
// Instantiates the Intent Client
const intentsClient = new dialogflow.IntentsClient();
async function createIntent() {
// Construct request
// The path to identify the agent that owns the created intent.
const agentPath = intentsClient.projectAgentPath(projectId);
const trainingPhrases = [];
trainingPhrasesParts.forEach(trainingPhrasesPart => {
const part = {
text: trainingPhrasesPart,
};
// Here we create a new training phrase for each provided part.
const trainingPhrase = {
type: 'EXAMPLE',
parts: [part],
};
trainingPhrases.push(trainingPhrase);
});
const messageText = {
text: messageTexts,
};
const message = {
text: messageText,
};
const intent = {
displayName: displayName,
trainingPhrases: trainingPhrases,
messages: [message],
};
const createIntentRequest = {
parent: agentPath,
intent: intent,
};
// Create the intent
const [response] = await intentsClient.createIntent(createIntentRequest);
console.log(`Intent ${response.name} created`);
}
createIntent();
// [END dialogflow_create_intent]
}
TIA
From the screen shot, it looks like you're running this on your local machine. The error message suggests that the environment variables that point to your credentials isn't setup.
See the Before you Begin section of the library documentation for how to setup that environment. One of the steps includes setting up authentication by downloading credentials and setting an environment variable to point to them. This will also set the project ID you're working with.
I'm having a problem trying to get my discord bot to play songs.
It is able to enter the voice channel and search for the song, but when it enters it does not play anything, I look at the status of the player and it comes out 'buffering'.
const { joinVoiceChannel, createAudioPlayer, createAudioResource, StreamType, AudioPlayerStatus, NoSubscriberBehavior } = require('#discordjs/voice');
const { Client, Intents, Interaction } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const ytdl = require('ytdl-core');
const yrS = require('yt-search');
async function vdSearch(cancion){
const vdE = await yrS(cancion);
return vdE.videos.length > 0 ? vdE.videos[0] : null;
}
client.on('messageCreate', async(message) =>{
switch(args[0]){
case 'play':
const vdRepro = await vdSearch(args[1]);
if(!vdRepro){
message.channel.send("No se ha encontrado esa cancion");
}else{
message.channel.send("Reproduciendo: "+ vdRepro.title);
}
//CONEXION
const stream = ytdl(vdRepro.url, { filter:'audioonly' });
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
})
var resource = createAudioResource(stream, {inputType:StreamType.Arbitrary,});
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
player.play(resource);
connection.subscribe(player);
console.log(player.state);
break;
}
})
Does anyone know how I could solve it?
Thanks for taking the time to read
I would recommend that you use "Distube". Its really easy to use and great for Musik Bots.
https://distube.js.org/#/docs/JS-DisTube/v2/class/DisTube
For example the play() command in Distube is distube.play(message, "searchQuery")
I need help with Displaying the response I get from my API to Dialogflow UI. Here is my code. I am currently using WebHook to connect Dialogflow to backend in Heroku.
My code
const functions = require('firebase-functions');
var admin = require("firebase-admin");
var serviceAccount = require("../../reactpageagent-dxug-firebase-adminsdk-26f6q-e1563ff30f.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://reactpageagent-dxug.firebaseio.com"
});
const { WebhookClient } = require('dialogflow-fulfillment');
const { Card, Suggestion } = require('dialogflow-fulfillment');
const axios = require('axios');
module.exports = (request, response) => {
const agent = new WebhookClient({ request, response });
function welcome(agent) {
agent.add('Welcome to my agent');
}
function rhymingWordHandler(agent) {
const word = agent.parameters.word;
agent.add(`Here are the rhyming words for ${word}`)
axios.get(`https://api.datamuse.com/words?rel_rhy=${word}`)
.then((result) => {
console.log(result.data);
result.data.map(wordObj => {
console.log(wordObj.word);
agent.add(JSON.stringify(wordObj.word));
return;
// agent.end(`${wordObj.word}`);
});
});
};
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('rhymingWord', rhymingWordHandler);
agent.handleRequest(intentMap);
}
When I console.log my the result. I get the data from the API in my console.log output, but the Data is not displayed in Dialogflow UI I also do not get any error.
Heroku log
I had real trouble with the result.data.map line of code.
In the end, I avoided it and instead processed result.data after the .then((result) => { line by checking the array length that my API returned, and if it was > 0, loop through it to output each line individually, using agent.add. If the array length was 0, I used agent.add to display a message saying 'No records found'. I used a catch to log any errors (again, using agent.add to send an error message to the user).
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".
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