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.
Related
I'm trying this:
agent.add(Simple message);
It works normally with Google Actions
But when the answer must return to Twilio, the error occurs:
Error: No responses defined for platform: twilio at WebhookClient.send
What kind of response should I send to Twilio?
I'm trying to get an Azure Web Function to receive a Twilio SMS message - and failing!
I've created a Web Function to successfully send SMS messages - now I want to listen and react to responses.
I've set up a web function as per the below. Its pretty simple at the moment, and is supposed to parrot back the original message:
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
var data = await req.Content.ReadAsStringAsync();
var formValues = data.Split('&')
.Select(value => value.Split('='))
.ToDictionary(pair => Uri.UnescapeDataString(pair[0]).Replace("+", " "),
pair => Uri.UnescapeDataString(pair[1]).Replace("+", " "));
// Perform calculations, API lookups, etc. here
var response = new MessagingResponse()
.Message($"You said: {formValues["Body"]}");
var twiml = response.ToString();
twiml = twiml.Replace("utf-16", "utf-8");
return new HttpResponseMessage
{
Content = new StringContent(twiml, Encoding.UTF8, "application/xml")
};
}
In Twilio, I've configured the phone to use web hooks:
I've deployed the Web Function, however when I try testing by sending a message, I get the following error in the Twilio logs:
11200 There was a failure attempting to retrieve the contents of this URL
Msg Unsupported Media Type
Message: The WebHook request must contain an entity body formatted as JSON.
Does anyone have any experience in how to fix this error?
I just got this working with Twilio's SMS services. In the Azure Portal, if you go to the function, then go to Integrate, change the mode to Standard. This forces the Azure function to return a normal HTTP response and you can control the content type. If you use application/xml it will work fine.
Okay, the current solution to this is .... it can't be done in Azure Web Functions. An Azure Web Function expects a JSON payload. Twilio Webhooks are an XML value/pair. So, the web function will reject the webhook call.
The best/easiest approach is to use a WebAPI or MVC Controller as per the Twilio example. I tried a sample version and had my Twilio Webhooks working to reply to an SMS in about 15 minutes from start to finish.
To debug, I'd use a tool such as Postman or Fiddler to manually replay (or create from scratch) an identical request to what you're expecting from Twilio. You can then see what kind of response you get and not have to solely rely on Twilio's error message.
From the error code, I'd imagine that the problem is either:
Your URL set up in the Twilio number configuration isn't actually reaching your function.
Your function is taking too long to respond. Twilio will throw 11200 if it doesn't get a response in a certain time.
Your response is formatted incorrectly. This is where the aforementioned strategy can help you diagnose the issue.
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.
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.
When a user texts my number, I would like to respond with a message using TwiML. I'd also like to know whether my response message sends or fails. I'm creating my TwiML response using the Twilio library for Node.js.
Here is my code:
const response = new twilio.TwimlResponse();
response.message(Response, {
statusCallback: '/sms/status/'
});
Here is the code for the route. Please note that the router is mounted upon the "/sms/" router:
router.post('/status/', acceptRequestsOnlyFromTwilio, (req, res) => {
const Event = require('./../models/schemas/event');
const event = new Event({
description:
`MessageSid = ${req.body.MessageSid}
MessageStatus = ${req.body.MessageStatus}`
});
event.save();
console.log(
`MessageSid = ${req.body.MessageSid}
MessageStatus = ${req.body.MessageStatus}`
);
res.sendStatus(200);
});
When I check my logs using the Heroku CLI, I don't log nor do I see a record when I check MongoDB.
Anyone have any ideas or tips on how I can go about debugging this or if I'm implementing this incorrectly?
Thanks for you time!
Twilio developer evangelist here.
Firstly, have you set your Messaging request URL for the Twilio phone number you are using? Is it pointing at the correct route for your Message TwiML response?
Also, your first code block should also be within a router.post endpoint for your server. Do you correctly return the TwiML response as the server response?
As a tip, it might be better to develop this application locally and test your webhook endpoints using a tool like ngrok. I love using ngrok to test webhooks.