Dialogflow fulfillment not responding to keywords - javascript

I am trying to make sense of how the fulfillment works, and I cannot get the responses from the if statements to work. Whenever I write the keyword, the default response I get is Not available.
The webhook for the intent is enabled, the entity is 'hooked' in the intent as well.
What am I missing here?
const functions = require('firebase-functions');
const { dialogflow } = require('actions-on-google');
const app = dialogflow();
const WELCOME_INTENT = 'Default Welcome Intent';
const USER_MESSAGE_ENTITY = 'UserMessage';
app.intent(WELCOME_INTENT, (conv) => {
const userMessage = conv.parameters(USER_MESSAGE_ENTITY).toLowerCase();
if (userMessage == 'hey') {
conv.ask('Hey there');
} else if (userMessage == 'greetings') {
conv.ask('Greetings, how are you');
} else if (userMessage == 'evening') {
conv.ask('Good evening');
}
});
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);
{
"responseId": "8499a8f2-b570-4fb2-9f3c-262bd03db01e-c4f60134",
"queryResult": {
"queryText": "hey",
"action": "input.welcome",
"parameters": {
"UserMessage": "hey"
},
"allRequiredParamsPresent": true,
"intent": {
"name": "projects/wandlee-zad-rekrutacyjne--euol/agent/intents/d76ffc6c-c724-4fa4-8c9b-7178a2d7f9b7",
"displayName": "Default Welcome Intent"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"webhook_latency_ms": 76
},
"languageCode": "pl",
"sentimentAnalysisResult": {
"queryTextSentiment": {
"score": 0.2,
"magnitude": 0.2
}
}
},
"webhookStatus": {
"code": 14,
"message": "Webhook call failed. Error: UNAVAILABLE."
}
}

I don't know where you got conv.parameters(USER_MESSAGE_ENTITY).
The parameters of the intent are accessible as a second function argument. It is going to be a map:
app.intent(WELCOME_INTENT, (conv, params) => {
const userMessage = params[USER_MESSAGE_ENTITY].toLowerCase();
// ...
})
``

Related

How do I setup OneDrive Filepicker v8 for Business/Sharepoint with Javascript? (Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException)

I already have put some hours into the setup of the OneDrive FilePicker v8 for Javascript for personal users to access their personal OneDrive files. Now I want to do the same for users with business/school accounts. I manage to get to the My Files part, but I cannot access any Sharepoint folder/site. I am not sure whether my lies with
The app configuration (AAD)
The javascript implementation
The configuration/permissions of the individual Sharepoint
The error I receive is Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException, and I struggle to find any meaningful documentation for it.
This is the AAD configuration:
{
"id": "***",
"acceptMappedClaims": null,
"accessTokenAcceptedVersion": null,
"addIns": [],
"allowPublicClient": null,
"appId": "***",
"appRoles": [],
"oauth2AllowUrlPathMatching": false,
"createdDateTime": "2023-01-17T13:20:32Z",
"description": null,
"certification": null,
"disabledByMicrosoftStatus": null,
"groupMembershipClaims": null,
"identifierUris": [],
"informationalUrls": {
"termsOfService": "https://***.com/app/tos",
"support": null,
"privacy": "https://***.com/app/privacy",
"marketing": null
},
"keyCredentials": [],
"knownClientApplications": [],
"logoUrl": "https://aadcdn.msftauthimages.net/c1c6b6c8-v-6zmda-jxeuzcj5pwn1sghjyu3gaqcdbwxfx543nak/appbranding/caofuabptruma-iurozspazfz7p4ilc95fi3qyhjlu0/1033/bannerlogo?ts=638095585782399340",
"logoutUrl": null,
"name": "File Picker (SharePoint)",
"notes": null,
"oauth2AllowIdTokenImplicitFlow": false,
"oauth2AllowImplicitFlow": false,
"oauth2Permissions": [],
"oauth2RequirePostResponse": false,
"optionalClaims": null,
"orgRestrictions": [],
"parentalControlSettings": {
"countriesBlockedForMinors": [],
"legalAgeGroupRule": "Allow"
},
"passwordCredentials": [],
"preAuthorizedApplications": [],
"publisherDomain": "***.com",
"replyUrlsWithType": [
{
"url": "https://localhost",
"type": "Spa"
},
{
"url": "http://localhost",
"type": "Spa"
},
{
"url": "https://***.com/onedrive/search",
"type": "Spa"
}
],
"requiredResourceAccess": [<see next image>],
"samlMetadataUrl": null,
"signInUrl": "https://***.com",
"signInAudience": "AzureADMultipleOrgs",
"tags": [],
"tokenEncryptionKeyId": null
}
With following scopes (requiredResourceAccess):
And the browser implementation (reduced to the minimum to reproduce the error):
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/public/css/style.css">
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
<title>File Picker</title>
</head>
<body>
<div class="container-lg pt-3">
<h3 class="d-flex align-items-center"><span>OneDrive File Picker</span></h3>
<div><button class="btn btn-primary" id="launchPicker">Pick from OneDrive</button></div>
<iframe class="w-100 mt-3" id="iframe" frameborder="0" style="min-height:600px;resize:vertical;"></iframe>
</div>
<script type="text/javascript" src="https://alcdn.msauth.net/browser/2.19.0/js/msal-browser.min.js"
nonce="392b4bdf6481a24edf09d81187872ce7"></script>
<script type="text/javascript" nonce="392b4bdf6481a24edf09d81187872ce7">
const SUB = "***"; // Test user
const REDIRECT_URI = `https://***.com/onedrive/search` // Test redirect url
const BASE_URL = `https://***-my.sharepoint.com/` // Test url
const msalParams =
{
auth:
{
authority: "https://login.microsoftonline.com/organizations", // Full directory URL, in the form of https://login.microsoftonline.com/<tenant>
clientId: "***", // 'Application (client) ID' of app registration in Azure portal - this value is a GUID
redirectUri: REDIRECT_URI
},
}
const app = new msal.PublicClientApplication(msalParams);
const redirectResponse = app.handleRedirectPromise();
async function getToken() {
let accessToken = "";
const account = await app.getAccountByLocalId(SUB);
if (await redirectResponse !== null) {
// Acquire token silent success
accessToken = redirectResponse.accessToken;
}
else {
authParams =
{
scopes: [`${BASE_URL}.default`],
account: account
};
try {
// see if we have already the idtoken saved
const resp = await app.acquireTokenSilent(authParams);
accessToken = resp.accessToken;
}
catch (e) {
// per examples we fall back to popup
return app.acquireTokenRedirect(authParams);
}
}
return accessToken;
}
// the options we pass to the picker page through the querystring
const params =
{
sdk: "8.0",
entry:
{
oneDrive:
{
files: {},
}
},
authentication: {},
messaging:
{
origin: window.location.href,
channelId: "27"
},
typesAndSources:
{
mode: "files",
pivots:
{
oneDrive: true,
recent: true,
sharedLibraries: true,
},
//- filters: ".csv,.xlsx"
},
selection:
{
mode: "pick"
},
commands:
{
pick:
{
label: "Import"
},
close:
{
label: "Close"
}
}
};
async function launchPicker(e) {
e.preventDefault();
//- win = window.open("", "Picker", "width=800,height=600")
const frame = document.getElementById("iframe");
const win = frame.contentWindow;
const authToken = await getToken();
const queryString = new URLSearchParams(
{
filePicker: JSON.stringify(params),
});
const url = `${BASE_URL}_layouts/15/FilePicker.aspx?${queryString}`;
const form = win.document.createElement("form");
form.setAttribute("action", url);
form.setAttribute("method", "POST");
win.document.body.append(form);
const input = win.document.createElement("input");
input.setAttribute("type", "hidden")
input.setAttribute("name", "access_token");
input.setAttribute("value", authToken);
form.appendChild(input);
form.submit();
window.addEventListener("message", (event) => {
if (event.source && event.source === win) {
const message = event.data;
if (message.type === "initialize" && message.channelId === params.messaging.channelId) {
port = event.ports[0];
port.addEventListener("message", messageListener);
port.start();
port.postMessage(
{
type: "activate",
});
}
}
});
}
async function messageListener(message) {
switch (message.data.type) {
case "notification":
console.log(`notification: ${message.data}`);
break;
case "command":
port.postMessage(
{
type: "acknowledge",
id: message.data.id,
});
const command = message.data.data;
switch (command.command) {
case "authenticate":
// getToken is from scripts/auth.js
const token = await getToken();
if (typeof token !== "undefined" && token !== null) {
port.postMessage(
{
type: "result",
id: message.data.id,
data:
{
result: "token",
token,
}
});
}
else {
console.error(`Could not get auth token for command: ${JSON.stringify(command)}`);
}
break;
case "close":
history.back();
break;
case "pick":
console.log(`Picked: ${JSON.stringify(command)}`);
port.postMessage(
{
type: "result",
id: message.data.id,
data: {
result: "success",
},
});
console.info(command)
break;
default:
console.warn(`Unsupported command: ${JSON.stringify(command)}`, 2);
port.postMessage(
{
result: "error",
error:
{
code: "unsupportedCommand",
message: command.command
},
isExpected: true,
});
break;
}
break;
}
}
document.getElementById("launchPicker").onclick = launchPicker;
// Check the token directly and reload when no access token acquirable
getToken().then((accessToken) => {
if (!accessToken) {
console.info("Something went wrong acquiring a token, reloading the page and try again!")
window.location.reload();
}
})</script>
<footer></footer>
</body>
</html>

Set value of a js file properties from outside of it

I`m new to JS and apologize for asking a primary question!
We have this first.js file as a js class example with:
const {MakeRequest} = require("./Request");
let api;
let token;
let unique_token;
function chat(data, unique_token = null) {
try {
if (api != null && token != null) {
return MakeRequest(token, api, data, unique_token)
} else {
return {
"provider": {
"website": "https://example.com",
"source": "Example"
},
"status": true,
"response": [],
"options": {},
"error": {
"code": 207,
"message": "Token or Api token did not valueted!"
}
}
}
} catch (e) {
return {
"provider": {
"website": "https://example.com",
"source": "Example"
},
"status": true,
"response": [],
"options": {},
"error": {
"code": e.code,
"message": e.message
}
}
}
}
module.exports = {
token,api,unique_token,chat
}
also, I have this second.js file as a executable js file:
const object = require("./first.js")
object.token ="123456"
object.api ="123456"
object.token ="123456"
console.log(object.chat("hello"))
If I run the second.js file, the api variable is undefined and didn`t get the value from second.js, how can I resolve this problem without change the second.js codes!
You can't edit a variable from a scope outside where it was declared.
Consider passing the values as arguments to chat function when you call it.

Transfer function for "eosio.token" smart contract is not working

const network = {
blockchain:'eos',
protocol:'https',
host:'jungle2.cryptolions.io',
port:443,
chainId: 'e70aaab8997e1dfce58fbfac80cbbb8fecec7b99cf982a9444273cbc64c41473',
sign: true,
broadcast: true,
debug: true,
verbose: false,
}
try {
const scatterInfo = await ScatterJS.scatter.connect('eosbetdice');
console.log({scatterInfo})
if ( scatterInfo ) {
const scatter = ScatterJS.scatter;
const requiredFields = { accounts:[network] };
const scatterVal = await scatter.getIdentity(requiredFields);
console.log({scatter,scatterVal})
if ( scatterVal ) {
const account = scatter.identity.accounts.find(x => x.blockchain === 'eos');
console.log("account",account)
const result = await api.transact({
actions: [{
account: 'eosio.token',
name: 'transfer',
authorization: [{
actor: account.name,
permission:'active',
signatures:[signature],
available_keys:[account.publicKey]
}],
data: {
from: 'abceristest2',
to: account.name,
quantity: betAsset,
memo: memo
},
}]
}, {
blocksBehind: 3,
expireSeconds: 30,
});
console.log({result})
return result;
}
} return false;
} catch ( exception ) {
console.log( exception )
}
I expect the transfer function will be work fine but It give me 401 unauthorized error. This transfer function hit the api of jungle testnet , "http://jungle.eosgen.io/v1/chain/get_required_keys"
How I can authenticate this function?
Error which I got, when this transfer function run
I don't check your codes in detail, but I think it is needed to set the data of "abceristest2" to authorization parameter.

Rocket Chat Realtime API in browser

I want to create a Rocket Chat client to subscribe to a channel through browser using Realtime API. Documentation here does not provide step by step procedure. Please let me know how to achieve it.
Links to any documentation would be very helpful.
I had less idea about websockets when I asked this question. For the benefit of all, mentioning the steps I followed.
Open websocket
var rocketChatSocket = new WebSocket("ws://locahost:3000/websocket");
Connect
var connectRequest = {
"msg": "connect",
"version": "1",
"support": ["1", "pre2", "pre1"]
}
rocketChatSocket.send(JSON.stringify(connectRequest));
After connecting, keep responding with {"msg":"pong"} for {"msg":"ping"} from server.
Login with authToken received by calling this API
var loginRequest = {
"msg": "method",
"method": "login",
"id": "42",
"params": [
{ "resume": "authToken" }
]
}
rocketChatSocket.send(JSON.stringify(loginRequest));
Subscribe to room
var subscribeRequest = {
"msg": "sub",
"id": "unique-id",
"name": "stream-notify-room",
"params":[
"room-id/event",
false
]
}
rocketChatSocket.send(JSON.stringify(subscribeRequest));
Send message
var request={
"msg": "method",
"method": "sendMessage",
"id": "42",
"params":
[
{
"_id": "message-id",
"rid": "room-id",
"msg": "Hello World!"
}
]
}
rocketChatSocket.send(JSON.stringify(request));
Thank you Mr Nandan,we were able to use your answer to build fully custom client to talk with the rocket chat real time api
here's the link for future people who will want the same thing
https://github.com/lalosh/rocketchat.realTimeAPI.customClient/blob/master/main.js
and here's the code in case you want to check immediately
/*
Rocket Chat Real Time API Custom Client
even though this code works great I don't know what exactly each event we listen for is doing
you can go back to rocket chat real time api for further declarations
we were able to write this code after we test real normal use case of livechat in a web page
and we listen for WebSocket connection inside the browser Network tab(by filtering ws(WebSocket) connections)
*/
let socket = new WebSocket('ws://[rocketChatIP]:[rocketChatPort]/websocket');
//note messageCount is incremented with every message
//but it can works even if you didn't change it
let messagesCount = 1;
// the variables chatToken and chatRoomId are very important
// and they are the identifier to the room(the whole chat) you are using
// if you want to get access to the chat again you need these two variables tokens
let chatToken = generateHash(17);
let chatRoomId = generateHash(17);
let subId = generateHash(17);
let roomSubId = generateHash(17);
let streamLivechatchatRoomId = generateHash(17);
let steamNotifyRoomSubId = generateHash(17);
let name = 'user28';
let email = 'user28#gmail.com';
let guestName = 'guest';
// listen to messages passed to this socket
socket.onmessage = function(e) {
let response = JSON.parse(e.data);
console.log('response', response);
// you have to pong back if you need to keep the connection alive
// each ping from server need a 'pong' back
if (response.msg == 'ping') {
console.log('pong!');
socket.send(JSON.stringify({
msg: 'pong'
}));
return;
}
// here you receive messages from server //notive the event name is: 'stream-room-messages'
if (response.msg === 'changed' && response.collection === 'stream-room-messages') {
console.log('msg received ', response.fields.args[0].msg, 'timestamp ', response.fields.args[0].ts.$date, 'from ' + response.fields.args[0].u.name);
return;
}
// receive all messages which will only succeed if you already have messages
// in the room (or in case you send the first message immediately you can listen for history correctly)
if (response.msg === 'result' && response.result) {
if (response.result.messages) {
let allMsgs = response.result.messages;
console.log('-----previous msgs---------------');
allMsgs.map(x => console.log(x))
console.log('---------------------------------')
}
}
}
//////////////////////////////////////////////
// steps to achieve the connection to the rocket chat real time api through WebSocket
//1 connect
let connectObject = {
msg: 'connect',
version: '1',
support: ['1', 'pre2', 'pre1']
}
setTimeout(() => {
socket.send(JSON.stringify(connectObject));
}, 1000)
//////////////////////////////////////////////
//2 getInitialData
let getInitialDataObject = {
msg: 'method',
method: 'livechat:getInitialData',
params: [String(chatToken), null],
id: String(messagesCount++),
}
setTimeout(() => {
socket.send(JSON.stringify(getInitialDataObject));
}, 2000)
//////////////////////////////////////////////
//3 loginByToken
let loginByToken = {
msg: 'method',
method: 'livechat:loginByToken',
params: [String(chatToken)],
id: String(messagesCount++),
}
setTimeout(() => {
socket.send(JSON.stringify(loginByToken));
}, 3000)
//////////////////////////////////////////////
//4 subscribtion
let subObj = {
msg: 'sub',
id: subId,
name: 'meteor.loginServiceConfiguration',
params: []
}
setTimeout(() => {
socket.send(JSON.stringify(subObj));
}, 4000)
//////////////////////////////////////////////
//5 register // you may skip this if you alredy registered
// or you can re use it even though you are registered.. no problems
// the crucial part is the `chatToken` and later on the `chatRoomId`
let registerObj = {
msg: 'method',
method: 'livechat:registerGuest',
params: [{
token: chatToken,
name: name,
email: email,
'department': null
}],
id: String(messagesCount++),
};
setTimeout(() => {
socket.send(JSON.stringify(registerObj));
}, 5000)
//////////////////////////////////////////////////
//6 stream-notify-room
let streamNotifyObj = {
msg: 'method',
method: 'stream-notify-room',
params: [
'null/typing',
guestName, true, {
token: String(chatToken)
}
],
id: String(messagesCount++)
};
setTimeout(() => {
socket.send(JSON.stringify(streamNotifyObj));
}, 6000)
//////////////////////////////////////////////////
//7 send a msg //use the same method to send your own messages again when you are all connected
let myMsg = {
msg: 'method',
method: 'sendMessageLivechat',
params: [{
_id: String(generateHash(17)),
rid: chatRoomId,
msg: 'first message',
token: String(chatToken),
}, null],
id: String(messagesCount++),
}
setTimeout(() => {
socket.send(JSON.stringify(myMsg));
}, 7000)
//////////////////////////////////////////////////
//8 send userPresence
let UserPresence = {
msg: 'method',
method: 'UserPresence:connect',
params: [
String(chatToken),
{
visitor: String(chatToken)
}
],
id: String(messagesCount++)
}
setTimeout(() => {
socket.send(JSON.stringify(UserPresence));
}, 8000)
/////////////////////////////////////////////////
//9 loadHistory of old messages
let loadHistory = {
msg: 'method',
method: 'livechat:loadHistory',
params: [{
token: String(chatToken),
rid: String(chatRoomId),
ts: {
$date: new Date().getTime()
}, //current point of time
limit: 50
}],
id: String(messagesCount++)
};
setTimeout(() => {
socket.send(JSON.stringify(loadHistory));
}, 9000)
/////////////////////////////////////////////////
// 10 stream-room-messages
// listen to all received messages
let roomMessagesSub = {
msg: 'sub',
id: String(roomSubId),
name: 'stream-room-messages',
params: [
String(chatRoomId),
{
useCollection: false,
args: [{
visitorToken: String(chatToken)
}]
}
]
};
setTimeout(() => {
socket.send(JSON.stringify(roomMessagesSub));
}, 10000)
/////////////////////////////////////////////////
// 11 getAgentData
let getAgentData = {
msg: 'method',
method: 'livechat:getAgentData',
params: [{
roomId: String(chatRoomId),
token: String(chatToken),
}],
id: String(messagesCount++)
}
setTimeout(() => {
socket.send(JSON.stringify(getAgentData));
}, 11000)
/////////////////////////////////////////////////
//12 stream-livechat-room
let streamLivechatRoom = {
msg: 'sub',
id: String(streamLivechatchatRoomId),
name: 'stream-livechat-room',
params: [
String(chatRoomId),
{
useCollection: false,
args: [{
'visitorToken': String(chatToken)
}]
}
]
}
setTimeout(() => {
socket.send(JSON.stringify(streamLivechatRoom));
}, 12000)
//////////////////////////////////////////
//13 stream-notify-room
let steamNotifyRoomSub = {
msg: 'sub',
id: String(steamNotifyRoomSubId),
name: 'stream-notify-room',
params: [
`${String(chatRoomId)}/typing`,
{
useCollection: false,
args: [{
token: String(chatToken)
}]
}
]
}
setTimeout(() => {
socket.send(JSON.stringify(steamNotifyRoomSub));
}, 13000)
//////////////////////////////////////
//14 userpresence 2
let UserPresence2 = {
msg: 'method',
method: 'UserPresence:online',
params: [String(chatToken)],
id: String(messagesCount++),
}
setTimeout(() => {
socket.send(JSON.stringify(UserPresence2));
}, 14000)
//////////////////////////////////////
//use it to send new messages
function sendNewMsg(msg, messagesCount) {
let myMsg = {
msg: 'method',
method: 'sendMessageLivechat',
params: [{
_id: String(generateHash(17)),
rid: chatRoomId,
msg: String(msg),
token: String(chatToken),
}, null],
id: String(messagesCount++),
}
setTimeout(() => {
socket.send(JSON.stringify(myMsg));
}, 500);
}
function generateHash(targetLength) {
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < targetLength; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
If you like to use an open source library for this purpose, here is one https://github.com/inf3cti0n95/Rocket.Chat.RealTime.API.RxJS
Here is the sample code:
import { RealTimeAPI } from "rocket.chat.realtime.api.rxjs";
const realTimeAPI = new RealTimeAPI("wss://demo.rocket.chat/websocket");
realTimeAPI.keepAlive();
const auth = realTimeApi.login(USERNAME, PASSWORD);
//Subscribe to messages and errors
auth.subscribe(
(data) => console.log(data),
(err) => console.log(err),
() => console.log('completed'));
//Subscribe to a specific channel, identified by roomId
realtimeAPI.sendMessage({
msg: 'sub',
id: '<a unique Id for subscription>',
name: 'stream-room-messages',
params: [roomId, false],
});

Javascript associate dynamic array

I have a JSON response as below;
"finalData" :
[
{
"message":"Display success msg",
"status":["SUCCESS"]
},
{
"message":"Display fail msg",
"status":["FAIL"]
}
]
Now this is dynamic. Meaning, I can either get just "SUCCESS" or just "FAILURE" or both
So finalData can be an array of 0 or 1 or 2 objects
My question is what is the best way to access the "message" property of the array dynamically. i.e. I want to know if finalData.message belongs to
"status":["SUCCESS"] or "status":["FAILURE"]
So kind of associate the array
var d = { "finalData": [{ "message": "Display success msg", "status": ["SUCCESS"] }, { "message": "Display fail msg", "status": ["FAIL"] }] }
var status = 'SUCCESS';
var message = d.finalData.filter(e => e.status == status).map(e => e.message)[0];
document.write(message);
ES5 code:
var d = { "finalData": [{ "message": "Display success msg", "status": ["SUCCESS"] }, { "message": "Display fail msg", "status": ["FAIL"] }] }
var status = 'SUCCESS';
var message = d.finalData.filter(function(e) {
return e.status == status;
}).map(function(e) {
return e.message;
})[0];
document.write(message);
Check whether each code is there, then just use an if statement to continue conditionally, depending on the status.
var status = finalData[0].status;
var succeeded = status.indexOf('SUCCESS') >= 0;
var failed = status.indexOf('FAIL') >= 0;
if(succeeded && failed) {
// code when both are true
}
else if(succeeded) {
// code for only success
}
else if(failed) {
// code for only failure
}
else {
// code if neither are present
}

Categories