I'm using the Botfront/rasa-webchat component on a webpage. I want to send the message returned by the bot to a bot libre avatar. TBH I'm not a javascript programmer, most of my work is in python, but I cannot figure out how I can get the result returned by rasa so I can pass it to the avatar SDK. I believe the onSocketEvent may hold the key, but I haven't been able to make that work. Please help. Here's my current (dysfunctional) code.
<html>
<body>
<p>welcome to the class chatbot</p>
<script type='text/javascript' src="https://www.botlibre.com/scripts/sdk.js"></script>
<script type='text/javascript'>
!(function () {
let e = document.createElement("script"),
t = document.head || document.getElementsByTagName("head")[0];
(e.src =
"https://cdn.jsdelivr.net/npm/rasa-webchat/lib/index.js"),
(e.async = !0),
(e.onload = () => {
window.WebChat.default(
{
customData: { language: "en" },
socketUrl: "http://localhost:5005",
onSocketEvent: onSocketEvent,
// add other props here
},
null
);
}),
t.insertBefore(e, t.firstChild);
})();
SDK.applicationId = "1591399486198011154";
var sdk = new SDKConnection();
var web = new WebAvatar();
web.version = 8.5;
web.connection = sdk;
web.avatar = "37788053";
web.voice = "cmu-slt";
web.voiceMod = "default";
web.width = "300";
web.height = "300";
web.createBox();
web.addMessage("Hello, I am Tuesday. The class chatbot", "", "", "");
web.processMessages();
onSocketEvent={
'bot_uttered': function(e) {console.log(e.bot_uttered)
},
'connect': () => console.log('connection established'),
'disconnect': () => doSomeCleanup(),
};
</script>
</body>
</html>
Just replace e.bot_uttered with e.text. The event object already contains the text key with value as the recently uttered message. Also, directly assign the onSocketEvent like this:
onSocketEvent:{
'bot_uttered': function(e) {console.log(e.text)},
'connect': function() {console.log('connection established')},
'disconnect': function() {doSomeCleanup()},
};
Helo!
To "capture" bot messages and all events you will need to enable generation of events in the rasa (called event-brokers). One of the events that are generated are the responses from the bot.
In this scenario you have some alternatives such as:
send events to rabbitMQ (pika events)
send events to kafka broker
send events directly in SQL
This way you can consume this information and send it wherever you want.
Documentation on event-brokers:
https://rasa.com/docs/rasa/event-brokers
Documentation about the events that will be generated:
https://rasa.com/docs/action-server/events/
I hope I've helped.
Related
As title, I manage to retrieve all-suggestion-accepted content on Google Docs through API. I have referred to its guideline and a couple of posts on this platform but in vain. Below is the snippet I currently have. Please Advise.
function myFunction()
{
var documentId ="My file ID";
var doc = Docs.Documents.get(documentId);
var SUGGEST_MODE= "PREVIEW_SUGGESTIONS_ACCEPTED";
var doc1 = Docs.Documents.get(documentId).setSuggestionsViewMode(SUGGEST_MODE);
console.log(doc1.body.content)
}
Upon seeing the documentation, you should use it like this
Script:
function myFunction() {
doc_id = '1s26M6g8PtSR65vRcsA90Vnn_gy1y3wj7glj8GxcNy_E';
SUGGEST_MODE = 'PREVIEW_SUGGESTIONS_ACCEPTED'
suggestions = Docs.Documents.get(doc_id, {
'suggestionsViewMode': SUGGEST_MODE
});
new_content = '';
suggestions.body.content.forEach(obj => {
if(obj.paragraph)
obj.paragraph.elements.forEach(element => {
new_content += element.textRun.content;
});
});
console.log(new_content);
}
Sample suggestions (with added paragraph):
Output:
EDIT:
Added an additional paragraph, and instead of just logging them, I have stored them in a single variable and printed at the end.
Reference:
documents.get
I am trying to create an IE11 compatible webpage which will sit on a few users desktops, which will grab some data from a JSON API and display it.
The user will type in their individual API key before pressing a button, revealing the API data.
Could you please help where my code has gone wrong? The error message I get from the console is: "Unable to get property 'addEventListener' of undefined or null reference. " So it looks like it is not even making the call to the API.
<script>
var btn = document.getElementById("btn");
var apikey = document.getElementById("apikey").value
btn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://example.example?&apikey=' + document.getElementById("apikey").value);
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var ourData = JSON.parse(ourRequest.responseText);
document.getElementById("title").textContent = ourData.data[0]["name"];
}}}
);
</script>
.
<body>
Enter API key: <input type="text" id="apikey">
<button id="btn">Click me</button>
<p id="title"></p>
</body>
The API data which I am trying to just extract the name from, looks something like this:
{"data":[{"name":"This is the first name"},{"name":"This is the second name"}]}
It's likely that you're including the Javascript in the page before the HTML. As Javascript is executed as soon as the browser reaches it, it will be looking for the #btn element which will not have been rendered yet. There are two ways to fix this:
Move the Javascript to the bottom of the <body> tag, making it run after the HTML has been output to the page.
Wrap the Javascript in a DOMContentLoaded event, which will defer the script until the page has finished loading. An example is as follows:
window.addEventListener('DOMContentLoaded', function() {
var btn = document.getElementById('btn');
var apikey = document.getElementById("apikey").value;
[...]
});
I'm trying to make use of the New Google Sites for a web page that I've developed, however, I'm having trouble storing local data. Local files work fine in windows and apple safari/chrome. Try it from Google Sites, and no joy! Additionally, in safari, an error is thrown, "IDBFactory.open() called in an invalid security context".
I really would like to host my site via google sites without linking to another server. I specifically need locally persistent data for just a few small items. I can't seem to make cookies work either.
Any suggestions?
I have tried this on a Windows 10 Surface Pro 2017, Apple iPad running 12.2 of Safari, Apple Mac Mini running macOs Mojave 10.14. I use SimpleHTTPServer from Windows 10 command line to share the files as a web server. I also email the files and open directly on the specified systems. Finally, I have created a New Google Sites website at https://sites.google.com/view/gerrymap It's very simple, just an Embed HTML element with the below text copied into the source code edit box. All are welcome to hit that page if they desire. Otherwise, use the short posted file below.
Instructions are in the HTML page itself.
All code works fine from a local instance of the html file. Can enter new values for the lat, long, rad, and key, save them, and read them. I can also refresh the page, then read them without storing first, and there is no problem. This proves that the values aren't just session persistent.
From Google Sites is a different matter. I set up a site that uses the html file in this question. When I enter new values and press the save button, IndexedDB fails, but localStorage succeeds in returning the values saved. If I press the refresh button, however, and then read the values without attempting to store first, IndexedDB again fails, but localStorage also fails in that it doesn't retrieve any values.
I believe I've correctly implemented the code (although some out there may take exception, I'm sure. No pride here, critics are welcome).
I've done a bunch of google searches, particularly about google sites and indexeddb/localstorage, and also posted on the google community help forum. Still no success.
Currently, I have no fallback methods, but need something relatively simple. Can anyone throw a little joy my way? Thanks in advance!
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Test Local Storage</title>
<style>
</style>
</head>
<body onload="initializeValues()">
Instructions: <br />
1. Save this sample code in an html file locally and open in a browser.<br />
2. Enter different values into the lat, long, rad, and key edit boxes.<br />
3. Press TrySave to store the values in indexedDB and localStorage.<br />
4. Refresh the webpage from the browser address line<br />
5. Press the individual Try IndexedDB and Try LocalStorage buttons to attempt<br />
6. Try inserting this code into a New Google Site, or access https://sites.google.com/view/gerrymap/home <br />
<br>
<input id="latitude" /> Latitude<br><br>
<input id="longitude" /> Longitude<br><br>
<input id="radius" /> Radius<br><br>
<input id="key" /> Key<br><br>
<button onclick="TryIndexedDB()" title="This tries to load via IndexedDB">Try IndexedDB</button><br><br>
<button onclick="TryLocalStorage()" title="This tries to load via localStorage">Try localStorage</button><br><br>
<button onclick="trySave()" title="This tries to save the data in both methods (IndexedDB, localStorage)">Try Save</button><br><br>
<button onclick="clearAll()" title="Clear the log space at the bottom of this example page">Clear Log</button><br><br>
<div id="hello">
</div>
<script>
"use strict";
function clearAll() {
document.getElementById("hello").innerHTML = "";
}
// tagBeginDefaultsReplace
var navLatitude = 39;
var navLongitude = -76.7;
var navMaxDist = 200;
var navKey = "PleaseAddYourKey";
function initializeValues() {
document.getElementById("latitude").value = navLatitude;
document.getElementById("longitude").value = navLongitude;
document.getElementById("radius").value = navMaxDist;
document.getElementById("key").value = navKey;
}
function trySave() {
navLatitude = document.getElementById("latitude").value;
navLongitude = document.getElementById("longitude").value;
navMaxDist = document.getElementById("radius").value;
navKey = document.getElementById("key").value;
// Save using indexeddb
getLocationDB(true, FinishIndexedDB);
// Save using localStorage
localStorage.setItem('latitude', navLatitude.toString());
localStorage.setItem('longitude', navLongitude.toString());
localStorage.setItem('radius', navMaxDist.toString());
localStorage.setItem('key', navKey.toString());
mylog("Done saving localStorage");
}
function getLocationDB(bSave, callbackf) {
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
var openDB;
try {
var myitem;
openDB = indexedDB.open("SampleDatabase", 1);
openDB.onupgradeneeded = function () {
var db = openDB.result;
var store = db.createObjectStore("SampleStore", { keyPath: "id" });
var index = store.createIndex("PosIndex", ["pos.latitude", "pos.longitude", "pos.radius", "pos.navkey"]);
};
openDB.onsuccess = function () {
// Start a new transaction var db = openDB.result;
callbackf("Successfully opened openDB");
var db = openDB.result;
var tx = db.transaction("SampleStore", "readwrite");
var store = tx.objectStore("SampleStore");
if (bSave) {
if (navLatitude != undefined && navLongitude != undefined && navMaxDist != undefined)
store.put({ id: 0, pos: { latitude: navLatitude, longitude: navLongitude, radius: navMaxDist, navkey: navKey } });
else
store.put({ id: 0, pos: { latitude: "38", longitude: "-75.7", radius: "100", navkey: "Please Enter Mapbox Key" } });
callbackf("Save indexeddb finished");
}
else {
var getNavLoc = store.get(0);
getNavLoc.onsuccess = function () {
if (getNavLoc != undefined
&& getNavLoc.result != undefined) {
callbackf("Succeeded reading from store. Result=" + JSON.stringify(getNavLoc.result));
navLatitude = parseFloat(getNavLoc.result.pos.latitude);
navLongitude = parseFloat(getNavLoc.result.pos.longitude);
navMaxDist = parseFloat(getNavLoc.result.pos.radius);
navKey = getNavLoc.result.pos.navkey;
}
else {
callbackf("Succeeded reading from store. Result=undefined");
navLatitude = navLongitude = navMaxDist = navKey = "undef";
}
initializeValues();
}
getNavLoc.onerror = function () {
callbackf("An error occurred getting indexeddb");
}
}
}
openDB.onerror = function () {
callbackf("An error occurred opening openDB");
}
}
catch (e) {
callbackf("Caught error in try block of indexeddb: " + e.Message);
}
}
function TryIndexedDB() {
getLocationDB(false, FinishIndexedDB);
}
function TryLocalStorage() {
mylog("localStorage read");
navLatitude = localStorage.getItem('latitude');
mylog("latitude=" + navLatitude);
navLongitude = localStorage.getItem('longitude');
mylog("longitude=" + navLongitude);
navMaxDist = localStorage.getItem('radius');
mylog("radius=" + navMaxDist);
navKey = localStorage.getItem('key');
mylog("key=" + navKey);
if (navLatitude == undefined)
navLatitude = "undef";
if (navLongitude == undefined)
navLongitude = "undef";
if (navMaxDist == undefined)
navMaxDist = "undef";
if (navKey == undefined)
navKey = "undef";
initializeValues();
}
function FinishIndexedDB(nSucceeded) {
mylog(nSucceeded);
}
function mylog(logstr) {
document.getElementById("hello").innerHTML += "<br>" + logstr.toString();
}
</script>
</body>
</html >
The problem is the way Google Sites is serving the iframe content. I'm not sure of the exact details behind the scenes, but it seems to have a randomly generated domain every time the page loads. Since localStorage and IndexedDB are associated with a specific domain, this causes the saved data to be "lost" when the page reloads.
As an example, here is the iframe's data from when I first loaded the page:
And here is the iframe's data after refreshing the page:
As you can see, the domain is completely different after refreshing, which means it has a brand new empty database.
First of all, I would like to apologize for the horribly worded title; I have been trying to think of one for the past 20 minutes but I do not know a succinct way to describe the problem I am having. If anyone has a better suggestion, please let me know or edit the title if you are able to.
Background: In order to learn NodeJS, I am creating a chat server. When the user clicks the createRoomBtn, an event is created containing the name of the room the user just created, and sent to the socket.js module in app.js, app.js then appends the room to the array of rooms (these rooms are displayed as a list in the browser), and creates a broadcast event to all users including the active user.
Problem: Let's say there is an empty list, and user adds a new room, titled "NodeJS", this will display the room on the screen, and everything is fine and dandy. Now, if I was to add another room, Socket.io, for example, the browser renders the following result: Socket.io, NodeJS, NodeJS. If I was to add "Javascript", the result would be Javascript, Socket.io, NodeJS, Socket.io, Node.JS. Basically, the browser renders the list over and over again, and each time the list shrinks by one. I do not have the slightest idea of why this is happening. The weird thing is that if I press refresh, the browser renders the list correctly Javascript, Socket.io, NodeJS. What is going on?
socket.js:
module.exports = function(io, rooms) {
var chatrooms = io.of('/roomlist').on('connection', function(socket) { //io.of creates a namespace
console.log('Connection established on the server');
socket.emit('roomupdate', JSON.stringify(rooms));
socket.on('newroom', function(data) {
console.log(data);
rooms.push(data);
socket.broadcast.emit('roomupdate', JSON.stringify(rooms));
socket.emit('roomupdate', JSON.stringify(rooms));
})
})
var messages = io.of('/messages').on('connection', function(socket) {
console.log('Connected to the chatroom!');
socket.on('joinroom', function(data) {
socket.username = data.user;
socket.userpic = data.userPic;
socket.join(data.room);
})
socket.on('newMessage', function(data) {
socket.broadcast.to(data.room_number).emit('messagefeed', JSON.stringify(data));
})
})
}
chatrooms.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{title}}</title>
<link rel="stylesheet" href="../css/chatrooms.css">
<script src="//code.jquery.com/jquery-1.11.0.min.js"> </script>
<script src="/socket.io/socket.io.js"> </script>
<script>
$(function() {
var host = '{{config.host}}';
var socket = io.connect(host + '/roomlist');
socket.on('connect', function() {
console.log('connection established');
})
socket.on('roomupdate', function(data) {
$('.roomlist').html('');
var procData = JSON.parse(data);
for (var i = 0; i < procData.length; i++) {
var str = '<a href="room/' + procData[i].room_number + '"><li>'
+ procData[i].room_name + '<li></a>';
$('.roomlist').prepend(str);
console.log(str);
}
})
$(document).on('click', '#createRoomBtn', function() {
var room_name = $('#newRoomText').val();
console.log(room_name);
if (room_name != '') {
var room_number = parseInt(Math.random() * 10000);
socket.emit('newroom', {room_name: room_name, room_number: room_number});
$('#newRoomText').val('');
}
})
})
</script>
</head>
<body>
<div class="cr-userbox">
<img src="{{user.profilePic}}" class="userPic">
<h3 class="username">{{user.fullName}}| Logout</h3>
</div>
<div class="cr-container">
<h1> ChatRooms</h1>
<div class="cr-newroom">
<input type="text" id="newRoomText" autocomplete="off">
<input type="submit" id="createRoomBtn" value=" Create Room">
</div>
<div class="cr-roomlist">
<ul class="roomlist">
</ul>
</div>
</div>
</body>
</html>
Please let me know if more information/modules are required, and I will be happy to provide them.
Update1: As correctly suggested by alex-rokabilis, I have changed $('.roomlist').html() = '' to $('.roomlist').html(''), however, the problem continues to persist.
I'm not sure if this is the cause of your problem or not but you're getting nested list eliments because you have two opening <li> tags in your socket.on ('roomupdate') function
I believe the problem is how you render your rooms in the html part, not how socket.io sends the data.
You use $('.roomlist').html=''; but this is not doing anything! .html is a function in jquery so the right thing to do is $('.roomlist').html('');.
So basically you didn't erase the previous rooms but instead you only add more duplicates. Also something i noticed that is not part of your question, in your nodejs code you use: socket.broadcast.emit('roomupdate', JSON.stringify(rooms));
socket.emit('roomupdate', JSON.stringify(rooms));
if you want to broadcast something to all connected clients there is a function for it and also there is no need to stringify your data, socketio do this internally for you! So you could use something like this:
io.emit('roomupdate',rooms);
I am using tokbox trial for video chatting on my website. But the problem i am facing is that ::: User 1 can see and hear User 2 clearly. User 2 can see User 1 clearly, but user 2 couldnt here user 1. And code i am using
<html>
<head>
<title>Monkvyasa | Test</title>
<script src='http://static.opentok.com/webrtc/v2.2/js/opentok.min.js'></script>
<script type="text/javascript">
// Initialize API key, session, and token...
// Think of a session as a room, and a token as the key to get in to the room
// Sessions and tokens are generated on your server and passed down to the client
var apiKey = "xxxxxxx";
var API_KEY=apiKey;
var sessionId = "2_MX40NTAyMDgxMn5-xxxxxxxxxxxxxxxxxxxxHBXZEZoWHN-fg";
var token = "T1==cGFydG5lcl9pZD00NTAyMDgxMiZzaWc9ZDNiYjYyZGE2NTBkYmUzMTUyNGNjNDZjYzAzY2NjZWRhZGY3NTEyZjpyb2xlPW1vZGVyYXRvciZzZXNzaW9uX2lkPTJfTVg0xxxxxxxxxxxxxxxxxxxxxxxxBNM1JsYlRCUFdXWkhSSEJYWkVab1dITi1mZyZjcmVhdGVfdGltZT0xNDEzMjAwMjIxJm5vbmNlPTAuMTk1MzEwNTU0MzY1MjEwNSZleHBpcmVfdGltZT0xNDEzMjg0MzY5";
// Initialize session, set up event listeners, and connect
var session;
var connectionCount = 0;
function connect() {
session = TB.initSession(sessionId);
session.addEventListener("sessionConnected", sessionConnectHandler);
session.addEventListener('streamCreated', function(event){
e=event;
console.log(e);
for (var i = 0; i < event.streams.length; i++) {
streams = event.streams;
// Make sure we don't subscribe to ourself
alert("new user connected :)");
if (streams[i].connection.connectionId == session.connection.connectionId) {
return;
}
// Create the div to put the subscriber element in to
var div = document.createElement('div');
div.setAttribute('id', 'stream' + streams[i].streamId);
document.body.appendChild(div);
session.subscribe(streams[i], div.id);
}
});
session.connect(API_KEY, token);
}
function sessionConnectHandler(event) {
var div = document.createElement('div');
div.setAttribute('id', 'publisher');
var publisherContainer = document.getElementById('publisherContainer');
// This example assumes that a publisherContainer div exists
publisherContainer.appendChild(div);
var publisherProperties = {width: 500, height:450};
publisher = TB.initPublisher(API_KEY, 'publisher', publisherProperties);
session.publish(publisher);
}
function disconnect() {
session.disconnect();
}
connect();
</script>
</head>
<body>
<h1>Monkvysa videofeed test!</h1>
<input style="display:block" type="button" id="disconnectBtn" value="Disconnect" onClick="disconnect()">
<table>
<tr>
<td> <div id="publisherContainer"></div></td> <td><div id="myPublisherDiv"></div></td>
</tr>
</table>
</body>
</html>
Thanks in advance
The code looks mostly correct, except you're using an older form of the 'streamCreated' event handler. In the latest version of the API, you no longer need to iterate through the event.streams array, you actually get one invocation of the event handler per stream.
In order to further dig into the problem, would you be able to add a link to a gist containing all the console logs? To make sure the logs are being outputted, you can call OT.setLogLevel(OT.DEBUG); at the beginning of the script.
Lastly, the newer API is greatly simplified and you could save yourself the effort of DOM element creation and iteration. What you have implemented is basically identical to our Hello World sample applications, which you can find in any of our server SDKs, for example here: https://github.com/opentok/opentok-node/blob/61fb4db35334cd30248362e9b10c0bbf5476c802/sample/HelloWorld/public/js/helloworld.js