-
-
Save Gugic/cfc008599fa9a82eeba4127648009132 to your computer and use it in GitHub Desktop.
<html> | |
<head> | |
<title>API Example</title> | |
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> | |
<script type="text/javascript"> | |
var accessToken = "<your agent's client access token>"; | |
var baseUrl = "https://api.api.ai/v1/"; | |
$(document).ready(function() { | |
$("#input").keypress(function(event) { | |
if (event.which == 13) { | |
event.preventDefault(); | |
send(); | |
} | |
}); | |
$("#rec").click(function(event) { | |
switchRecognition(); | |
}); | |
}); | |
var recognition; | |
function startRecognition() { | |
recognition = new webkitSpeechRecognition(); | |
recognition.onstart = function(event) { | |
updateRec(); | |
}; | |
recognition.onresult = function(event) { | |
var text = ""; | |
for (var i = event.resultIndex; i < event.results.length; ++i) { | |
text += event.results[i][0].transcript; | |
} | |
setInput(text); | |
stopRecognition(); | |
}; | |
recognition.onend = function() { | |
stopRecognition(); | |
}; | |
recognition.lang = "en-US"; | |
recognition.start(); | |
} | |
function stopRecognition() { | |
if (recognition) { | |
recognition.stop(); | |
recognition = null; | |
} | |
updateRec(); | |
} | |
function switchRecognition() { | |
if (recognition) { | |
stopRecognition(); | |
} else { | |
startRecognition(); | |
} | |
} | |
function setInput(text) { | |
$("#input").val(text); | |
send(); | |
} | |
function updateRec() { | |
$("#rec").text(recognition ? "Stop" : "Speak"); | |
} | |
function send() { | |
var text = $("#input").val(); | |
$.ajax({ | |
type: "POST", | |
url: baseUrl + "query?v=20150910", | |
contentType: "application/json; charset=utf-8", | |
dataType: "json", | |
headers: { | |
"Authorization": "Bearer " + accessToken | |
}, | |
data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }), | |
success: function(data) { | |
setResponse(JSON.stringify(data, undefined, 2)); | |
}, | |
error: function() { | |
setResponse("Internal Server Error"); | |
} | |
}); | |
setResponse("Loading..."); | |
} | |
function setResponse(val) { | |
$("#response").text(val); | |
} | |
</script> | |
<style type="text/css"> | |
body { width: 500px; margin: 0 auto; text-align: center; margin-top: 20px; } | |
div { position: absolute; } | |
input { width: 400px; } | |
button { width: 50px; } | |
textarea { width: 100%; } | |
</style> | |
</head> | |
<body> | |
<div> | |
<input id="input" type="text"> <button id="rec">Speak</button> | |
<br>Response<br> <textarea id="response" cols="40" rows="20"></textarea> | |
</div> | |
</body> | |
</html> |
i was able to run it using python simple httpserver
REVISED HTML5 CODE
<html>
<head>
<title>API Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var accessToken ="youraccesstokenhere";
var baseUrl = "https://api.dialogflow.com/v1/";
$(document).ready(function() {
$("#input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
send();
this.value = '';
}
});
$("#rec").click(function(event) {
switchRecognition();
});
});
var recognition;
function startRecognition() {
recognition = new webkitSpeechRecognition();
recognition.onstart = function(event) {
updateRec();
};
recognition.onresult = function(event) {
var text = "";
for (var i = event.resultIndex; i < event.results.length; ++i) {
text += event.results[i][0].transcript;
}
setInput(text);
stopRecognition();
};
recognition.onend = function() {
stopRecognition();
};
recognition.lang = "en-US";
recognition.start();
}
function stopRecognition() {
if (recognition) {
recognition.stop();
recognition = null;
}
updateRec();
}
function switchRecognition() {
if (recognition) {
stopRecognition();
} else {
startRecognition();
}
}
function setInput(text) {
$("#input").val(text);
send();
}
function updateRec() {
$("#rec").text(recognition ? "Stop" : "Speak");
}
function send() {
var text = $("#input").val();
conversation.push("Me: " + text + '\r\n');
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }),
success: function(data) {
var respText = data.result.fulfillment.speech;
console.log("Respuesta: " + respText);
setResponse(respText);
$("#response").scrollTop($("#response").height());
},
error: function() {
setResponse("Internal Server Error");
}
});
}
function setResponse(val) {
//Edit "AI: " to change name
conversation.push("AI: " + val + '\r\n');
$("#response").text(conversation.join(""));
}
var conversation = [];
</script>
<style type="text/css">
bot.body { width: 500px; margin: 0 auto; margin-top: 20px; }
bot.div { position: absolute; }
bot.input { width: 400px; }
bot.button { width: 50px; }
bot.textarea { width: 100%; }
</style>
</head>
<body>
<div class="bot">
<textarea readOnly = true; id="response" cols="40" rows="20" style="resize: none;"></textarea>
<br />
<input id="input" type="text" placeholder="Type here..." autocomplete="off" /><button id="rec">Speak</button>
</div>
</body>
</html>
Added: Text response only, auto-clear input box, "conversation" view, auto-scroll (not entirely working, after a little bit stops working)
(That extra code was me, I think it made it look better, plus the classes keep it from styling other parts of your page)
-Thanks to @Towerss @PatricioJulian and @Adetee for some of the additional code
I made a fiddle with a demo bot so you can see how it works: https://jsfiddle.net/TristianK3604/9kz7sx7h/
@thealexin05 I think it's because he said "Add conversation.push("Me: " + text + '\r\n');
just before var text = $("#input").val();
to store your query." Really, you're supposed to put conversation.push("Me: " + text + '\r\n');
after var text = $("#input").val();
. Hope that helps!
Hey guys,
Does someone know about some css or jquery ui to use to integrate this in a nice way as a chat window in an existing web page?
Thanks!
@ignaciostellino You could just implement this in it's own stand-alone web page and use some other code to have it pop-up as a new window, and also adjust the height and width settings.
Is there any way I can integrate images to my response?
if (event.which == 13) {
event.preventDefault();
send();
this.value = ''; //add this line to auto clear your text field so that you won't have to press backspace to clear the text field
}
Hi, thanks @TristianK3604 etc for your great work. Does anyone have any code that we could add in order to automatically send the voice messages? (ie speech to text). Currently the speech is converted into text and user has to automatically press enter to send this text.
Cheers!
Hi @TristianK3604,
Do you know why we are using "query?v=20150910" if I am not wrong the "v" represents the version realeased by dialogflow and I think there are more recent ones. Is that right?
Here's the stuff mentioned above. Just put in your access token and it should all work.
`
<title>API Example</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript"> var accessToken ="INSERT YOUR ACCESS TOKEN"; var baseUrl = "https://api.dialogflow.com/v1/"; $(document).ready(function() { $("#input").keypress(function(event) { if (event.which == 13) { event.preventDefault(); send(); this.value = ''; } }); $("#rec").click(function(event) { switchRecognition(); }); }); var recognition; function startRecognition() { recognition = new webkitSpeechRecognition(); recognition.onstart = function(event) { updateRec(); }; recognition.onresult = function(event) { var text = ""; for (var i = event.resultIndex; i < event.results.length; ++i) { text += event.results[i][0].transcript; } setInput(text); stopRecognition(); }; recognition.onend = function() { stopRecognition(); }; recognition.lang = "en-US"; recognition.start(); } function stopRecognition() { if (recognition) { recognition.stop(); recognition = null; } updateRec(); } function switchRecognition() { if (recognition) { stopRecognition(); } else { startRecognition(); } } function setInput(text) { $("#input").val(text); send(); } function updateRec() { $("#rec").text(recognition ? "Stop" : "Speak"); } function send() { var text = $("#input").val(); conversation.push("Me: " + text + '\r\n'); $.ajax({ type: "POST", url: baseUrl + "query?v=20150910", contentType: "application/json; charset=utf-8", dataType: "json", headers: { "Authorization": "Bearer " + accessToken }, data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }), success: function(data) { var respText = data.result.fulfillment.speech; console.log("Respuesta: " + respText); setResponse(respText); }, error: function() { setResponse("Internal Server Error"); } }); } function setResponse(val) { //Edit "AI: " to change name conversation.push("AI: " + val + '\r\n'); $("#response").text(conversation.join("")); } var conversation = []; </script> <style type="text/css"> body { background-color: #333333; width: 500px; margin: 0 auto; text-align: center; margin-top: 20px; } div { position: absolute; } input { color: #000000; background-color: #00BFFF; width: 500px; } button { color: #FFD700; background-color: #228B22; width: 100px; } textarea { background-color: #FFD700; width: 100%; } </style>Response
<textarea id="response" cols="40" rows="20"></textarea>@ignaciostellino No idea. Sorry.
@smartin681 No problem, and I haven't been able to figure that out myself. Sorry, but I will add it into my comment above once I figure it out and let you know!
Buenas, ya probe el ejemplo, y funciona, SOOOLO que el micro no funciona y en chorme me bloquea en migro y lo acepto y nada. Ayuda por favor.
tengo el codigo asi.
function stopRecognition() {
if (recognition) {
recognition.stop();
recognition = null;
}
updateRec();
}
function switchRecognition() {
if (recognition) {
stopRecognition();
} else {
startRecognition();
}
}
function setInput(text) {
$("#input").val(text);
send();
}
function updateRec() {
$("#rec").text(recognition ? "Stop" : "Speak");
}
function send() {
var text = $("#input").val();
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }),
success: function(data) {
setResponse(data);
setResponse(JSON.stringify(data, undefined, 2));
},
error: function() {
setResponse("Internal Server Error");
}
});
setResponse("Loading...");
}
function setResponse(val) {
$("#response").text(val);
if (val.result) {
var say="";
say = val.result.fulfillment.speech;
synth = window.speechSynthesis;
var utterThis = new SpeechSynthesisUtterance(say);
//utterThis.lang = "en-US";
synth.speak(utterThis);
}
}
</script>
<style type="text/css">
body { width: 500px; margin: 0 auto; text-align: center; margin-top: 20px; }
div { position: absolute; }
input { width: 400px; }
button { width: 50px; }
textarea { width: 100%; }
</style>
Response
<textarea id="response" cols="40" rows="20"></textarea>
I can get a response, but I do not see the rich content data in the JSON. Testing my app in Google Actions console and I get a beautiful image. But using this code I only get the text.
"fulfillment": { "speech": "We found the perfect product for you. Always Maxi Size 4 Overnight Pads with Wings, Unscented, 33 Count. View now at: https://walmart.com/ip/33469691", "messages": [ { "type": 0, "speech": "We found the perfect product for you. Always Maxi Size 4 Overnight Pads with Wings, Unscented, 33 Count. View now at: https://walmart.com/ip/33469691" } ], "data": { "google": { "expect_user_response": false, "no_input_prompts": [], "is_ssml": false } } }, "score": 1 }, "status": { "code": 200, "errorType": "success", "webhookTimedOut": false }, "sessionId": "somerandomthing"
How do I actually get the rich content back?
@TristianK3604 Man you are amazing :) thanks a lot for putting the whole filtered code
i am getting this error can anyone help please urgent!!!
mato.html:1 Failed to load https://api.dialogflow.com/v1/query?v=20150910: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'null' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access.
getting same error @ruchit2277
did u find any solution?
please help!
Getting the same error of @ruchit2277 and @sai2018
Failed to load https://api.dialogflow.com/v1/query?v=20150910: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'null' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access.
@cassanellicarlo
just upload the file to web server and open it in localhost.for ex: localhost:8080/filename.html.
I have used wamp server ,but any server can be used .
Thanks, it works!
(I was trying without a web server with Microsoft Edge and it worked)
How do i add microphone glyphicon in the place of chat button ?
Is it possible get a response without clicking stop button i.e just by recording and sending after few seconds??
internal server error is displaying. i tried a lot please.. anyone give solution to it
Dude I was trying to get this working for a hot minute. Thanks a lot!
Hey Guys,
Dose anyone have HTML + JS sdk for V2 version. ?
Thanks.
@Samarth26 - Expanding on @TristianK3604 comment on Oct 23, 2017 I have used a div to display the user and bot output rather than a textarea. This way any html in the output (links,images,etc) will display. I have also added some additional styling allowing you to easily hide the user/bot name, highlight the current response, general prettyness and added a container to hide the response scroll bar if needed:
https://github.com/latestscoop/DialogFlow-HTML5/blob/edfae95c8283fb58c54339b99253a5470539debd/Simple-DialogFlow-HTML5.html#L1-L121
@latestscoop Thanks alot i was looking for a code like this thanks again
How do you add voice recognition to this example? I don't want to be typing to answer.
Someone knows how to differentiate a message with accents from one without accents?
The json does not recognize him
I have also getting JSON Respond. How I can use only reply from that format
{
"id": "0ed65683-64b3-41eb-990b-4d1f2b6606e7",
"timestamp": "2017-03-11T20:24:21.693Z",
"result": {
"source": "domains",
"resolvedQuery": "Hi",
"action": "smalltalk.greetings",
"parameters": {
"simplified": "hello"
},
"metadata": {},
"fulfillment": {
"speech": "Howdy."
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success"
},
"sessionId": "somerandomthing"
}
Store it to a variable like this
var resp = <the response data from the api>;
and to specifically use response in the app:
var speech = resp.speech;
This will return 'Howdy' as per your response...
Does anyone have an example with API V2?
Hi guys, If I want a picture after a specific response? How do I get it do that? I have tried using custom payload but I can't get it to work!