Rasa to dialogflow connection in javascript - javascript

I need a solution for the Rasa nlu to dialogflow connection. I tried different ways in the code from adding the yml file, tar.gz file and Rasa provided webhooks and API. None of these methods are working and it is not responsing the answers from the domain.yml file but getting the response "Sorry. Something went wrong. Can you say that again?" in the dialogflow and getting different errors in the vs code terminal when I try to enter the inputs from the nlu.yml file for Rasa nlu in the dialogflow.
async function defaultFallback(agent) {
const yaml = require('js-yaml');
const fs = require('fs');
const defaultFallback = yaml.load(fs.readFileSync('nlu.yml'));
const dialog = [
`The following is a conversation with an AI assistant that can have meaningful conversations with users. The assistant is helpful, empathic, and friendly. Its objective is to make the user feel better by feeling heard. With each response, the AI assisstant prompts the user to continue the conversation in a natural way.
AI: Hello, my name is Debra. I am your personal AI assistant from Orient Telecoms. How are you doing today?`,
];
let query = agent.query;
console.log('querytext ', query)
dialog.push(`User: ${query}`);
dialog.push('AI:');
try{
var targz = require('targz');
var tar = require('tar-stream');
var extract = tar.extract();
// targz.decompress({src: '20221206-172837-simple-assistant.tar.gz',
// dest: '\dialogflow'})
// const response = yaml.load(fs.readFileSync('domain.yml'));
// const response = await fetch (extract.on('20221206-172837-simple-assistant.tar.gz'));
const response = await fetch ('http://0.0.0.0:5005',
{
method: "POST",
body: JSON.stringify(query),
});
const botResponse = await response.json();
console.log('botResponse: ', botResponse)
agent.add(botResponse[0].generated_text.substring(botResponse[0].generated_text.indexOf('?') + 1).trim());
}catch(err){
console.log('This is error:', err);
agent.add('Sorry. Something went wrong. Can you say that again?');
}
}
I was able to run with rasa shell, node and ngrok command together but there is no response from the yml file when I'm working on the dialogflow. Is there a solution for these problems?

Related

How to do 'signTransaction' after authenticated by 'signPersonalMessage' by WalletConnect of '#walletconnect/react-native-dapp'?

I am developing a react native mobile app where user can connect their existing wallet(rainbow, metamask and many more) to app.
I have already done the authentication part, like user can successfully connect their app wallet to app by this code.
import { useWalletConnect } from '#walletconnect/react-native-dapp';
const connector = useWalletConnect();
await connector.connect();
const message = `App name is XYZ - ${new Date().toUTCString()}`;
const hexMsg = convertUtf8ToHex(message);
const address = connector.accounts[0];
await setItemToStorage('address', address);
const msgParams = [hexMsg, address];
connector.signPersonalMessage(msgParams).then(async result => {
let data = {
message,
signature: result,
};
Now every thing is working as expected.
And then I have to transfer my wallet amount to other address, and to achieve this I know I have to get permission from wallet app,
To achieve this I am trying to do like
let txObj = {
gas: Web3js.utils.toHex(100000),
to: receiver_address!,
data: data,
from: userWallet,
};
console.log('Start transaction...');
const singTrasaction = await connector.signTransaction(txObj);
The connector.signTransaction(txObj) open the wallet app but not prompted me to confirm.
I am just confused and nothing get help me.
Please help me anyone I am getting stuck on this since a week.

How to use quick.db variable in client.users.fetch discordjs

I am trying to use a value (Discord User ID stored as a string) stored via quick.db in my code, but it returns me the error user_id: Value "[object Promise]" is not snowflake. I've spent hours trying to figure it out but it just doesn't work. If I store the ID directly in the code it works just fine and I can fetch the user.
This is my "ready.js" file. The cron package lets me define at what time of the day that part of code is being executed. I don't think it's a part of the problem.
const Discord = require("discord.js")
const cron = require('cron');
const path = require('path');
const { QuickDB } = require("quick.db");
const db = new QuickDB()
module.exports = client => {
console.log(`${client.user.username} ist online`)
client.user.setActivity('Online!', { type: 'PLAYING' });
let userid1 = db.get("id1.string");
let scheduledMessage = new cron.CronJob('00 00 08 * * *', () => {
client.users.fetch(userid1).then(user => {
user.send('Test').catch(err => {
let channel = client.channels.cache.get('998568073034465341')
channel.send(`${user} blocked the bot`)
})
})
})
scheduledMessage.start()
}
This is where I want to utilize a User ID stored via quick.db in "id1.string"
client.users.fetch(userid1).then(user => {
-> This doesn't work
client.users.fetch(400120540989227010).then(user => {
-> This is working fine
I've already tried using
`${userid1}`
but this also doesn't work
I'd be so happy if someone could help me with that.
db.get("id1.string") is an async function, meaning unless you put await behind it, it will returns a Promise who isn't finished yet. It's like wanting to send a discord message. You can't just get the message immediatly since because of your connection and the api's connection. It takes time. So to bypass this you have to use the await keyword before the .get method (and async the main function here) so that it won't execute the rest of the code until you get what you want from the database.
let userid1 = db.get("id1.string"); // What you have now
let userid1 = await db.get("id1.string"); // What you should do instead
module.exports = client => { // What you have now
module.exports = async client => { // What you should do instead

The npm puppeter package is returning an error regarding node_package space

Here is the error that it is returning
Here is a picture of the error i'm getting when I run npm install puppeter
I found some stuff online with permissions, but this is about node_package space. It is not disk space as I've looked over my disk storage availability and there's plenty. Working on an Apify SDK, and I'm following the documentation, but the console is returning a whole bunch of error messages.
Can someone please help?
const Apify = require('apify')
Apify.main(async () => {
const requestQueue = await Apify.openRequestQueue();
await requestQueue.addRequest({ url: 'https://www.iana.org/' });
const crawler = new Apify.PuppeteerCrawler({
requestQueue,
handlePageFunction: async ({ request, page }) => {
const title = await page.title();
console.log(`Title of ${request.url}: ${title}`);
await Apify.utils.enqueueLinks({
requestQueue,
page,
pseudoUrls: ['https://www.iana.org/[.*]'],
});
},
});
await crawler.run();
});

Google cloud dialogflow intent detection nodejs example not working

I am trying to implement a very simple dialogflow agent integration with nodejs.
Here is what I did so far
I followed the code from Intent detection
I added the service account private key file .json to my server.
I added the environment variable GOOGLE_APPLICATION_CREDENTIALS with the path to my .json private key file.
Here is the code I am trying to run right now:
require('dotenv').config()
const projectId = 'gg-chatbot-216808';
const sessionId = 'quickstart-session-id';
const query = 'hello';
const languageCode = 'en-US';
// Instantiate a DialogFlow client.
const dialogflow = require('dialogflow');
const sessionClient = new dialogflow.SessionsClient();
// Define session path
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
text: query,
languageCode: languageCode,
},
},
};
// This prints the private key path correctly.
console.log(process.env.GOOGLE_APPLICATION_CREDENTIALS);
// Send request and log result
sessionClient
.detectIntent(request)
.then(responses => {
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.`);
}
})
.catch(err => {
console.error('ERROR:', err);
});
Then I get this error in the console when I run this file
Auth error:Error: invalid_user: Robot is disabled.
ERROR: { Error: 14 UNAVAILABLE: Getting metadata from plugin failed with error: invalid_user: Robot is disabled.
at Object.exports.createStatusError (/var/www/html/google_auth/node_modules/grpc/src/common.js:87:15)
at Object.onReceiveStatus (/var/www/html/google_auth/node_modules/grpc/src/client_interceptors.js:1188:28)
at InterceptingListener._callNext (/var/www/html/google_auth/node_modules/grpc/src/client_interceptors.js:564:42)
at InterceptingListener.onReceiveStatus (/var/www/html/google_auth/node_modules/grpc/src/client_interceptors.js:614:8)
at callback (/var/www/html/google_auth/node_modules/grpc/src/client_interceptors.js:841:24)
code: 14,
metadata: Metadata { _internal_repr: {} },
details: 'Getting metadata from plugin failed with error: invalid_user: Robot is disabled.' }
i also faced a similar issue for my angular bot.
What i did was, instead of using using the google_credentials from the json file, i created an object with private_key,client_email {these values can be taken from the service account private key file .json}, and passed the object while setting up the session client.
var config = {
credentials: {
private_key: "YOUR_PRIVATE_KEY",
client_email: "YOUR_CLIENT_EMAIL"
}
}
const sessionClient = new dialogflow.SessionsClient(config);
note: do copy the full private_key string from .json. It will start as "-----BEGIN PRIVATE KEY-----\n......" .
Also, in GCP go to the project->IAM then try setting role for the service as DIALOGLOW API ADMIN. Check if this works.
If this has not been resolved yet , the solution is to provide "fileKey" inside sessionClient.
const sessionClient = new dialogflow.SessionsClient({
fileKey:" path of your credentials.json file"
});
or
let filePath = process.env.GOOGLE_APPLICATION_CREDENTIALS ="Location of credentials file".
const sessionClient = new dialogflow.SessionsClient({
fileKey:filePath
});
this will even work if there is no system env variable is set as GOOGLE_APPLICATION_CREDENTIALS.
Hope this is helpful.

window.WebSocket - window is not defined

I am a bit out of my comfort zone here, so looking for a bit of guidance. I am trying to access an api to display live metrics, using phonic-elixir (https://www.npmjs.com/package/phoenix-elixir) - am just sort of trying to get it running first, so have loaded up their example code and connecting to an api (forgive me if the terminology is all wrong, I am new at this!)
This is my code:
import {Socket} from 'phoenix-elixir';
let socket = new Socket('ws://API_URL_HERE', {params: {'auth-token': 'AUTH_TOKEN'}})
socket.connect()
let channel = socket.channel('updates:new', {})
channel.join()
.receive('ok', resp => { console.log('Joined successfully', resp) })
.receive('error', resp => { console.log('Unable to join', resp) })
channel.on('update', payload => {
console.log('Received: ' + payload);
console.log(payload);
})
export default socket
When I run babel index.js | node I am getting the error: this.transport = opts.transport || window.WebSocket || LongPoll; and ReferenceError: window is not defined
Just some advice to point me in the right direction would be fantastic. Is window not defined because it needs a dom? Do I need a server to run this in?
Thank you :)
I just ported the client to be compatible with node.JS.
Here is the link https://github.com/mcampa/phoenix-channels
The difference with the original client is that this does not use long-polling and you need to pass the absolute url instead of the relative url.
To install it run:
npm install --save phoenix-channels
Same API as the original:
const { Socket } = require('phoenix-channels')
let socket = new Socket("ws://example.com/socket")
socket.connect()
// Now that you are connected, you can join channels with a topic:
let channel = socket.channel("room:lobby", {})
channel.join()
.receive("ok", resp => { console.log("Joined successfully", resp) })
.receive("error", resp => { console.log("Unable to join", resp) })
phoenix-elixir is client-side library that is supposed to be used in browsers not in node environment. You should create html page with your code and open it in browser to test it out.

Categories

Resources