Twilio Functions - post data from multiple sms messages? - node.js

I have a function that posts the content from an incoming sms message to a third party api. So, a customer sends us a message and Twilio posts the message to the api. But, I want to add an extra step. So, when a user sends us a message, I want Twilio to reply asking for an email then post the message along with the email from the second message to the api. Unless we get that second message, nothing should be posted to the api. Any ideas on how to do something like that?
I was looking through the docs and saw something about the Message instance resource but I'm not sure if that will do it.
const https = require('https');
exports.handler = function(context, event, callback) {
let twiml = new Twilio.twiml.MessagingResponse();
twiml.message("Your message has been recieved.");
let postData = JSON.stringify({
....
});
let postOptions = {
...
};
let req = https.request(postOptions, function(res) {
res.setEncoding('utf8');
res.on('data', function(chunk) {
console.log(chunk);
callback(null, twiml);
});
});
req.write(postData);
req.end();
};

Twilio developer evangelist here.
In order to take two steps like that, you'd need to save the message from the first message somewhere while you wait for the second message. Since the second message will come in via a new HTTP request, you can't save this within a function anywhere, you'd want to use some sort of third party store. Then you'd write your function to check for the existence of the first message in that store, if it exists, then send both messages to the API, if it doesn't then store the first message and respond to the user with your second question.
Alternatively, you could use the Twilio API to look up all the previous messages that the user has sent to you. If there are no previous messages, then this is definitely the first message they have sent. If there is a previous message then you need to determine whether it was an initiating message for this conversation, possibly by how long ago it was or a heuristic on the content, and then decide whether to send both the messages on to your API or ask for the next response.
Let me know if that helps at all.

Related

how to send sms from within Twilio programmable voice function

I have a Twilio function which executes whenever someone calls a certain number. I'm trying to have the function send an sms. It's not working, but I'm not getting any error. Any help debugging would be great.
exports.handler = function(context, event, callback) {
let response = new Twilio.twiml.MessagingResponse();
response.message({
to: '+11234567890',
}, 'new sms from testing');
};
Additionally, If you could let me know how to access the incoming phone number within this function, I would greatly appreciate it. Thanks in advance for any suggestions or insights.
You will not be able to send a messaging response to a voice event, you'll need to create a messaging client and send separately. See docs here: https://www.twilio.com/docs/sms/tutorials/how-to-send-sms-messages-node-js .
For incoming phone numbers, that is included in the event object. It should be event.From, but you can log the event object to get all the parameters. They should follow the Call object schema: https://www.twilio.com/docs/voice/api/call

How to use Twilio to send SMS, and wait for response from phone to finish request in NodeJS

I know how to send an SMS via Twilio to a phone number specified in the request body, however I need a way for this route to wait for the user to respond with a text message. I need to capture that messages body and send it as a response.
router.post('/', function(req, res){
var customerNumber = req.body.mobileNumber;
var twilioNumber = process.env.TWILIO_NUMBER;
client.messages
.create({
to: '+1' + customerNumber,
from: twilioNumber,
body: 'message to user',
provideFeedback: 'true',
}, function(err, message){
if(err) res.send('message err: ' + err);
else{
// wait 10-20 seconds for user to respond
res.send("A response from the user");
}
})
});
I also know how to listen to responses with Twilio, but this doesn't work because I need the above route to respond with the message I get from the user in the route below.
router.post('/sms-response', function(req, res){
var twilio = require('twilio');
var twiml = new twilio.twiml.MessagingResponse();
twiml.message('thanks for your feedback');
res.writeHead(200, {'Content-Type':'text/xml'});
res.end(twiml.toString());
});
I've been looking for a way to do this all day with no success at all. I appreciate your help!
I dont know if that is possible yet, I went through their documentation and didnt see that feature yet. I would suggest using a web socket like socket.io. When message comes in you can just pass the response in through the socket to the user.
Twilio developer evangelist here.
While this could technically be possible I strongly recommend against it. You mention that you might be waiting for 10-20 seconds, but users are much more fickle than that, as are mobile networks. So getting a response may take much longer that that or even never happen. Then you'd be left with a long running connection to your server waiting for a response that might never come.
As Hammer suggested, it would be better to return a response to the user straight away, saying something like "We're waiting for your response", then connecting that user's browser to your server via a websocket or server sent event stream. When you receive the incoming message on your webhook endpoint, you can then send the information down the websocket or event source and react to that in the front end.
Let me know if that helps at all.

How to catch twilio events in nodejs?

I'm new in twilio and trying to understand how can i catch twilio's events in my backend (nodejs). For exemple each time i send a message, i want the console logs "Message sent" just for testing.
I read the twilio webhook documentation , however i can't really understand how to apply it in a nodejs environment.
Thanks for helping.
Twilio developer evangelist here. I think you will find this Twilio tutorial great, as it will walk you through exactly what you're trying to do, and will show you how to add events to the console.
But the gist of what you want to do it is the following:
// Create a new REST API client to make authenticated requests against the
// twilio back end
var client = new twilio.RestClient('TWILIO_ACCOUNT_SID', 'TWILIO_AUTH_TOKEN');
// Pass in parameters to the REST API using an object literal notation. The
// REST client will handle authentication and response serialzation for you.
client.sms.messages.create({
to:'YOUR_NUMBER',
from:'YOUR_TWILIO_NUMBER',
body:'Twilio message from Node.js'
}, function(error, message) {
// The HTTP request to Twilio will run asynchronously. This callback
// function will be called when a response is received from Twilio
// The "error" variable will contain error information, if any.
// If the request was successful, this value will be false
if (!error) {
// The second argument to the callback will contain the information
// sent back by Twilio for the request. In this case, it is the
// information about the text messsage you just sent:
console.log('Success! The SID for this SMS message is:');
console.log(message.sid);
console.log('Message sent on:');
console.log(message.dateCreated);
} else {
console.log('Oops! There was an error.');
}
});
Full documentation for the Node library can be found here.
Hope this helps you out.

how to connect two anonymous callers together using twilio

I am currently doing using node js twilio module for a functionality in a project that i am working on for a client. Basically the server is going to initiate a call using twilio api to call a certain person A the connect him to another person B. I am new to twilio so i am still a noob, but this is the code i have written so far. Please i need u guys input on how to achieve this. cheers
var client = require('twilio')(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);
exports.makeCall = function(callDetails, cb) {
client.makeCall({
to:'+16515556677', // Any number Twilio can call
from: TWILIO_CALLER_ID,
url: 'https://demo.twilio.com/welcome/voice' // A URL that produces an XML document (TwiML) which contains instructions for the call
}, function(err, responseData) {
//executed when the call has been initiated.
console.log(responseData.from); // outputs "+14506667788"
var resp = new client.TwimlResponse();
resp.say('Welcome to Acme Customer Service!')
.gather({
action:'http://www.example.com/callFinished.php',
finishOnKey:'*'
}, function() {
this.say('Press 1 for customer service')
.say('Press 2 for British customer service', { language:'en-gb' });
});
});
};
Twilio developer evangelist here.
You're part way there with this, but you don't want to be creating a TwiML response in the callback to your call to client.makeCall. The responseData there is a representation of the call in Twilio's system.
What you need to do is provide a URL to the makeCall function that hosts some TwiML that connects the call to another phone number. Currently you have the demo URL in place, so you'll need to point that to a URL that you own.
There's a very good in depth tutorial on how to accomplish all of this on the Twilio site which you might find helps out. You can find the tutorial here, give it a go and let me know if that helps.

ss.api.publish.user('someUser Id', content) is not working in socket stream

I'm using socket stream to send the data to the logged in user by using the following code
var ss = require('socketstream');
....
....
ss.api.publish.user('userId', content);
but the ss.api.publish is undefined is what the error i'm receiving.
Where am i going wrong.
Please advice.
The API for a publish to a user is:
Sending to Users
Once a user has been authenticated (which basically means their session now includes a value for req.session.userId), you can message the user directly by passing the userId (or an array of IDs) to the first argument of ss.publish.user as so:
// in a /server/rpc file
ss.publish.user('fred', 'specialOffer', 'Here is a special offer just for you!');
Important: When a user signs out of your app, you should call req.session.setUserId(null, cb) to prevent the browser from receiving future events addressed to that userId. Note: This command only affects the current session. If the user is logged in via other devices/sessions these will be unaffected.
The above is taken from the original document describing the socketstream pub/sub api.
as you can see, you need to supply one more argument than you thought. That is, becasue on the client side you need to subscribe to a message channel in order to get the message. In the above example, you need to do this in your client side code:
ss.event.on('specialOffer', function(message){
alert(message);
});

Resources