Output multiple responses from a single Intent - javascript

I have an Alexa Skill which I want to have an initial response to an intent, then after a delay, states another response.
I've attempted using multiple response.tell(...) call with a setTimeout() between them, but this only responds with the first .tell() and ends. (.tell() is set to end the session, but even if I set this to false, my code still never reaches the setTimeout() )
I have included some psuedo-code about what I would like to do:
intentHandlers.DynamicDurationIntent = function(intent, session, response) {
var calculatedDuration = doCalculation();
var speechDuration = convertToSpeech(calculatedDuration);
var speechOutput = "Your duration will last <say-as interpret-as="time">' +
speechDuration +
'</say-as>";
response.tell(speechOutput); //I get this far
setTimeout(function () {
var speechOutputEnd = "Great job! You're done.";
response.tell(speechOutputEnd);
}, calculatedDuration);
}
An example of this model is used in the 7 Minute Workout Alexa Skill.
Is this feasible using AWS Lambda?
Thanks!

This is not an AWS Lambda related issue, this is an Alexa related issue.
Part of the confusion seems to be the asynchronous nature of node.js making it appear that you could send multiple responses to Alexa, you can't. The way to think about Alexa is in the same request/response type nature that a normal API call would be. Your second response.tell has nowhere to send its data because the original request has long since concluded.
The way to think about it is Alexa is holding a conversation with the user and doesn't provide you a way to interrupt the user without them first interacting. Your first response.tell puts the conversation back in the users hands and you can't say anything until they talk to you again.
All that said, there is a straightforward solution that will probably work for you available in the Alexa platform today.
You can provide a single response with SSML and put breaks in the speech output. The documentation for an SSML break shows that you would look like <break time="420s"/> and you are already using SSML in your response.
However, for usability I would not recommend putting in a 7 minute pause. You have alternatives such as putting in minute pauses and having encouraging speech between each minute (actually you'd want to pause for 50 something seconds probably). Another alternative would be for you to play some time of music or workout related sound for the 7 minutes using the audio SSML tag.

Related

Handle Multiple Concurent Requests for Express Sever on Same Endpoint API

this question might be duplicated but I am still not getting the answer. I am fairly new to node.js so I might need some help. Many have said that node.js is perfectly free to run incoming requests asynchronously, but the code below shows that if multiple requests hit the same endpoint, say /test3, the callback function will:
Print "test3"
Call setTimeout() to prevent blocking of event loop
Wait for 5 seconds and send a response of "test3" to the client
My question here is if client 1 and client 2 call /test3 endpoint at the same time, and the assumption here is that client 1 hits the endpoint first, client 2 has to wait for client 1 to finish first before entering the event loop.
Can anybody here tells me if it is possible for multiple clients to call a single endpoint and run concurrently, not sequentially, but something like 1 thread per connection kind of analogy.
Of course, if I were to call other endpoint /test1 or /test2 while the code is still executing on /test3, I would still get a response straight from /test2, which is "test2" immediately.
app.get("/test1", (req, res) => {
console.log("test1");
setTimeout(() => res.send("test1"), 5000);
});
app.get("/test2", async (req, res, next) => {
console.log("test2");
res.send("test2");
});
app.get("/test3", (req, res) => {
console.log("test3");
setTimeout(() => res.send("test3"), 5000);
});
For those who have visited, it has got nothing to do with blocking of event loop.
I have found something interesting. The answer to the question can be found here.
When I was using chrome, the requests keep getting blocked after the first request. However, with safari, I was able to hit the endpoint concurrently. For more details look at the following link below.
GET requests from Chrome browser are blocking the API to receive further requests in NODEJS
Run your application in cluster. Lookup Pm2
This question needs more details to be answer and is clearly an opinion-based question. just because it is an strawman argument I will answer it.
first of all we need to define run concurrently, it is ambiguous if we assume the literal meaning in stric theory nothing RUNS CONCURRENTLY
CPUs can only carry out one instruction at a time.
The speed at which the CPU can carry out instructions is called the clock speed. This is controlled by a clock. With every tick of the clock, the CPU fetches and executes one instruction. The clock speed is measured in cycles per second, and 1c/s is known as 1 hertz. This means that a CPU with a clock speed of 2 gigahertz (GHz) can carry out two thousand million (or two billion for those in the US) for the rest of us/world 2000 million cycles per second.
cpu running multiple task "concurrently"
yes you're right now-days computers even cell phones comes with multi core which means the number of tasks running at the same time will depend upon the number of cores, but If you ask any expert such as this Associate Staff Engineer AKA me will tell you that is very very rarely you'll find a server with more than one core. why would you spend 500 USD for a multi core server if you can spawn a hold bunch of ...nano or whatever option available in the free trial... with kubernetes.
Another thing. why would you handle/configurate node to be incharge of the routing let apache and/or nginx to worry about that.
as you mentioned there is one thing call event loop which is a fancy way of naming a Queue Data Structure FIFO
so in other words. no, NO nodejs as well as any other programming language out there will run
but definitly it depends on your infrastructure.

Discord bot editing messages too slow

I want my discordbot to send send a message with an attached file in it and a text. Then the bot has to edit this text a couple of times but the problem is that when bot eddits message 5 times then it waits some time and then edits again 5 times etc etc. How can i make it edit messages without stopping?
if(msg.content.includes("letter")){
msg.channel.send("alphabet", { files: ["/Users/48602/Videos/discordbot/aaa.png"]})}
if(msg.content === 'alphabet'){
msg.edit("**a**")
msg.edit("**b**")
msg.edit("**c**")
msg.edit("**d**") // Here bot stop for a 2 seconds and i dont know why
msg.edit("**e**")
msg.edit("**f**")
msg.edit("**g**")
msg.edit("**h**")
msg.edit("**i**")
msg.edit("**j**")// Here bot stop for a 2 seconds and i dont know why
msg.edit("**k**")
msg.edit("**l**")
msg.edit("**m**")
msg.edit("**n**")
msg.edit("**o**") // Here bot stop for a 2 seconds and i dont know why
msg.delete()
}
Discord has a rate limit of 5 in each request. Trying to bypass this would be considered API abuse (the solutions later is not API abuse).
Exceeding this limit will pause other requests until a certain number of seconds has passed. Along with my research, I came across this simple explanation:
5 anything per 5 seconds per server (if you did not understand what I said above).
On Discord's Developer guide on rate limits, it tells you this:
There is currently a single exception to the above rule [rate limits] regarding different HTTP methods sharing the same rate limit, and that is for the deletion of messages. Deleting messages falls under a separate, higher rate limit so that bots are able to more quickly delete content from channels (which is useful for moderation bots).
One workaround, without API abusing, would be to send messages, and delete the previous messages since there is a higher limit for deleting messages.
Another workaround would be to add intermediate timeouts to your animation.
A simple method such as:
function async wait = { require("util").promisify(setTimeout); };
//syntax: await wait(1000); to "pause" for 1 second
You will need to play around with the timings so it fits your intended animation speed, and without pausing due to the rate limit.

How to run asynchronous tasks for multiple users

So I've this project for school who is about "triggers" for social networks.
Let me explain:
- A user can register for our application and login
- He can sign in for multiple services like Facebook, Twitter etc.
- Then their is what we call triggers, once he signed in on our application and registered his services, everytime he will post something on twitter for example my server will see it and post it on Facebook aswell.
I knew nothing about node.js a month ago so I'm kinda new to all this async stuff but I took some course to help myself. So far so good I can now manage users etc, (I've again some research to do with oauth).
My biggest problem is this "real-time" update on our server.
I mean I searched on the internet and saw this what we call polling (?), the idea to make request frequently to a server every X seconds.
So with a bit a sudo code this what I tought it would look like:
For each User
asynchronously watch for every update on Facebook and Twitter for
this User
So I did some research about performing request every each second and found about setInterval and setTimeout
const watchSocialMedia = setInterval(function(){
Users.forEach(user => {
User.watchAndPostAnyNewPost() //
}
}, 60000);
So I put some dummy data to illustrate.
Problem is I don't think It'll be done asynchronously ?
I mean the ideal is if I could put one time for each user a 'watcher' like saying
For each User
User.watchAndPostAnyNewPost()
where watchAndPostAnyNewPost() look like this
class User () {
...
const watchAndPostAnyNewPost = setInterval(function(){
fetchFacebook();
fetchTwitter();
}, 60000);
}
So each user have his own setInterval function running on him to check if he posted anything
Anyone can tell me if it's even possible ? :-)
Thanks a lot for reading me !!!

Python - Bots, Asyncio, Javascript, and Loops

Hello Everyone and thank you for your time. In the previous couple of days I have been undergoing a little project of mine to create a online chatbot for LINE. I understand the API but ran into a problem. I am trying to get my chabot to use online responses to user text. To accomplish this I am trying to use a websocket between python and JavaScript. The API I am using is in python hence the websocket must also be written in Python. I picked asyncio websockets. In short, I am trying to fetch a response from a user input on Line --> Send that response over a websocket to my javascript in a browser console --> The javascript will proceed with it's logic and send the response back to the server --> the Program will proceed with it's execution. My problem is that both the Websocket programming as well as my Line programming use a loop. The Line Code can be seen at
https://github.com/fadhiilrachman/line-py/blob/master/examples/groupbot.py
As you can see at the end of the code there is a while statement which traces the READ_MESSAGE Function over and over again for each message. You can ignore the NOTIFIED_LEAVE one. So basically my code while proceed with it's own logic and then do something like:
else:
#ExternalBot code
ExtText = text[6:]
I now wish to send this ExtText over my websocket to my javascript which will fetch a response from the browser and send it back. The javascript will do something like this:
exampleSocket = new WebSocket("ws://192.168.1.9:8765/")
exampleSocket.onmessage = function(e){
var server_message = e.data;
console.log(server_message);
(logic)
exampleSocket.send(response);
Now this is where the problem begins as I simply do not know how to proceed. The python asyncio Websockets requires a loop to run as seen below:
async def Send(websocket, path):
await websocket.send(ExtText)
await Receive(websocket, path)
async def Receive(websocket, path):
resposne = await websocket.recv()
if response is None:
await Recieve(websocket, path)
else:
print (Response)
start_server = websockets.serve(Send,'192.168.1.9','8765')
loop = asyncio.get_event_loop()
loop.run_untill_complete(start_server)
loop.run_forever()
(continue to do a line.send() the response back to the client on Line.)
This is the code that I currently have. Now the problem is, If I never close the loop the loop with something like loop.call_soon_threadsafe(loop.stop) it will keep running and in turn the message will never get sent back to the client(the program will not proceed with it's LINE logic). if I DO close the loop the server is "shutdown" in effect. If the server is shutdown and reopened for each message I have to send over the websocket, I now face the problem of getting my JavaScript to continually try to reconnect to the server every single message. I have tried this and have never succeeded in getting the Javascript to keep trying to establish a connection. I have tried to use Javascript websocket readyState attribute but that hasn't worked either. I am coming here simply because I Have no idea on how to proceed and what to do further. How do you people suggest I proceed, closing the loop or somehow leaving it open but continuing with my program's logic. If so how would you go about implementing it into my already looping code( the LINE while true statement)? I really do apologize for such a long question but I am completely stuck. Thank you for your time people who decide to read and help me, I really appreciate it.
After days of research I have solved the issue by separating the loops into two python scripts and communicating between them. If anyone here has a similar issue and wishes a more in depth explanation, feel free to ask me.

display number of message dynamically using javascript or asp.net

I will do my best to explain my problem to avoid people pointing me into different directions.
I got an assignment from business people. I don't know the terminology. It is very similar to email notification, message notification on facebook, notification on social media games.
For example, people are sending 20 email messages 5 minutes ago. the screen will display 20 (see attachment). Now, 3 more messages have arrived, the web page should update the number to 23.
Facebook has similar concepts when our friends like/comment message. The notification changes. Same thing is true on social media game. Any status changes on our game, it will reflect it.
I kind of have idea on how to do it cosmetically (on CSS). How to do it using javascript/asp.net. Do I need to postback in order to refresh the message. I never pay attention to that on facebook/yahoo email/social media games. All I know is something is happening, the webpage is updating the status.
Sorry the question is too broad. If someone can help me to point to the right direction, I appreciate any help
HTML5 introduced a very interesting concept call Server-Sent Events in which server can dynamically connect to the client and send data.
Eg:
var source = new EventSource("demo_sse.asp");
source.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data + "<br>";
};
And on server side you can write,
<%
Response.ContentType = "text/event-stream"
Response.Expires = -1
<!--Writing "data:" is important-->
Response.Write("data: The server time is: " & now())
Response.Flush()
%>
However, some old browsers may not support this.
One other way to accomplish this task is to use Ajax call as,
function checkNewMessages(totalMessages){
return $.ajax({
url: 'demo.asp',
type: 'GET',
cache: false,
data: {
totalMessages: totalMessage;
}
});
}
checkNewMessages(totalMessages).success(function (data) {
// display the data wherever you want
});
//Checking for new messages every 5 seconds
setInterval(checkNewMessages(totalMessages,5000));
Whatever you write within your Write() in server side will be displayed here. Now to constantly check for the new messages you can call the above ajax function with the help of setInterval()
There are many ways to do this, depending on how real time you need it to be.
The most common way is to use JavaScript with an XmlHttpRequest to call an ASP.NET page which returns the number of messages, I recommend you use a JSON object for this. The benefit of this approach allows you to request data from the server without the user experiencing a full page refresh. You can use JavaScript to set it to call every x seconds depending on your requirements.
Collectively that is known as AJAX, using a JavaScript library such as JQuery can make this much easier.

Categories

Resources