Access sender phone number twilio Node.js webhook - node.js

To respond if a user replies to a Twilio message, Twilio makes a post request to a server you can specify. How exactly can I access the sender phone number from the post request params? I want to be able to send them a Twilio message at a later date.
Example Code
const http = require('http');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const app = express();
app.post('/sms', (req, res) => {
const twiml = new MessagingResponse();
twiml.message('The Robots are coming! Head for the hills!');
// is it
// req.params.From
// ?
// that's giving me undefined
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
http.createServer(app).listen(8080, () => {
console.log('Express server listening on port 8080');
});
The docs say this information is given in the "post request params" but like I indicated in the example code, req.params.From is returning undefined for me.

Twilio developer evangelist here.
The from phone number, and other parameters, are sent as form encoded parameters (application/x-www-form-urlencoded) in the body of the post request. All the request parameters are listed in the documentation.
To read them, you will need to parse the body of the request using Express's urlencoded middleware (you can set this up for your application by calling app.use(express.urlencoded());) and you will then be able to read the parameters from req.body.From.
const http = require('http');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const app = express();
app.use(express.urlencoded());
app.post('/sms', (req, res) => {
const twiml = new MessagingResponse();
twiml.message('The Robots are coming! Head for the hills!');
console.log(req.body.From);
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
http.createServer(app).listen(8080, () => {
console.log('Express server listening on port 8080');
});

Related

How do I parse the SMS sender's from number and body of what s/he texted to Twilio number via a webhook and node.js?

Hello StackOverflow Friends:
The following code works fine, I've tested with nGrok running locally.
Two of the requirements I have left and can't figure out are:
Capture the phone number of the sender (put in variable)
Capture the body of the text the sender sent (put in variable)
Many thanks in advance!
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const app = express();
});
app.post('/sms', (req, res) => {
// Start our TwiML response.
const twiml = new MessagingResponse();
// Add a text message.
const msg = twiml.message('some canned response');
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
app.listen(3000, () => {
console.log('Example app listening on port 3000!');
});
Twilio developer evangelist here.
You can get the inbound message from an incoming SMS webhook request with req.body.Body and the inbound phone number with req.body.From.
To save into a variable, maybe something like const inbMsg = req.body.Body and const inbPhoneNum = req.body.From.
For more information on parsing an incoming Twilio SMS Webhook with Node.js, I'd recommend this blog post by my teammate Sam Agnew.
Let me know if this helps at all!

How to recieve a file using request.get()?

I am writing a server that is meant to serve and receive files. It is written in node.js, using express.js. I also have a client, also written in node, which is meant to send a request to the server and receive the files on the server.
Server-side
const express = require("express");
const app = express();
const file = "./samplefiles/Helloworld.txt";
app.get("/", (res)=>{
res.download(file);
});
module.exports = app; //this exports to server.js
const http = require("http");
const app = require("./app.js);
const port = 8080;
const server = http.createServer(app);
server.listen(port, () => {
console.clear();
console.log("server running");
})
Client-side
const request = require("request");
request.get("http://localhost:8080/", (req, body) => {
console.log(body);
console.log(res);
});
If I try to access it by my browser I am asked what I want to do with the file, it works. However, Is I run my client-side code it prints the body and the res(being null). I expected the file name and it's content to be in the body but only the content of the file was in the body.
I want to receive the whole file, is possible, or at least get the name of it so that I can "make" a copy of it on the client-side.
Change code your server side to:
const port = 8080;
const express = require("express");
const app = express();
const path = require('path');
app.get("/", function(req, res){
res.sendFile(path.join(__dirname, 'app.js'));
});
app.listen(port, () => {
console.clear();
console.log("server running");
});
Change code your client-side to:
var request = require('request');
request('http://localhost:8080/', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print data of your file
});
You need to install request npm i request for client side
You can serve up any files you want with express static method:
app.use(express.static('public'))
in this case just put all the files you want to serve in folder called public and then you can access it by localhost:8080/Helloworld.txt.
I ended up working around it.
I sent the file name as a header and was thus able to create a replica of the file I wanted to download using the body info and the filenameheader.

Using Twilio in Node.js,

I am trying to make an automated SMS text app using Twilio and I am having a hard time connecting it to my localhost. I keep receiving a "cannot /get" error. Basically, I am trying to send and receive messages using a webhook. Can someone take a look and see what's going on? This code was given to me by Twilio:
const http = require('http');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const app = express();
app.post('/sms', (req, res) => {
const twiml = new MessagingResponse();
twiml.message('The Robots are coming! Head for the hills!');
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
http.createServer(app).listen(2001, () => {
console.log('Express server listening on port 2001');
});
Looks like you've misplaced post but wanted get (since you're trying to access the route via a get request)
change
app.post('/sms' ...
to
app.get('/sms' ...

How do I get the recording ID from a Twilio recorded call?

My twilio code is:
const express = require('express');
const VoiceResponse = require('twilio').twiml.VoiceResponse;
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/health', (req, res) => {
res.send('ok')
})
// Returns TwiML which prompts the caller to record a message
app.post('/record', (request, response) => {
// Use the Twilio Node.js SDK to build an XML response
const twiml = new VoiceResponse();
twiml.say("Hi!");
// Use <Record> to record the caller's message
twiml.record();
console.log(twiml.toString())
response.send(twiml.toString());
});
// Create an HTTP server and listen for requests on port 3000
app.listen(PORT);
But I want to know the recording ID so I can access the raw file programatically. How would I do that?
To get the recording ID, (RecordingSid), you need to tell Twilio an action URL, with something like this:
twiml.record({
action: '/finished'
});
You can read more here: (https://www.twilio.com/docs/voice/twiml/record#attributes). Also, read about the recordingStatusCallback URL attribute, maybe that's something you need too.
Then, you need to parse the body of this second request Twilio will make to your app.
You can read more about this here: (https://www.twilio.com/blog/2016/07/how-to-receive-a-post-request-in-node-js.html).
For this you can use body-parser, which you can get with npm install body-parser.
The recording ID will be part of the parameters under body.RecordingSid.
Anyway, here is a rough modification of your code, to get started:
// npm install express body-parser
const express = require('express');
const bodyParser = require('body-parser');
const VoiceResponse = require('twilio').twiml.VoiceResponse;
const app = express();
// Tell express to use the body-parser middleware and to not parse extended bodies
app.use(bodyParser.urlencoded({
extended: false
}))
const PORT = process.env.PORT || 3000;
app.get('/health', (req, res) => {
res.send('ok')
})
// Returns TwiML which prompts the caller to record a message
app.post('/record', (request, response) => {
// Use the Twilio Node.js SDK to build an XML response
const twiml = new VoiceResponse();
twiml.say("Hi!");
// Use <Record> to record the caller's message
twiml.record({
action: '/finished'
});
console.log(twiml.toString())
response.send(twiml.toString());
});
app.post('/finished', function (req, res) {
const body = req.body;
res.set('Content-Type', 'text/plain');
res.send(``);
console.log(body);
console.log(body.RecordingSid);
});
// Create an HTTP server and listen for requests on port 3000
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
I hope this helps.

Twilio 11200 HTTP retrieval failure with Node app on Heroku

My Node.js app is set to respond to a text message received at a paid Twilio number. I tested it using ngrok and everything worked fine. Once I deployed the app to Heroku, however, I started seeing an 11200 HTTP retrieval failure error in the Twilio console.
Are there configuration settings in Heroku that I need to set up?
// Twilio Credentials
const accountSid = 'xxx';
const authToken = 'xxx';
const client = require('twilio')(accountSid, authToken);
const MessagingResponse = require('twilio').twiml.MessagingResponse;
var express = require('express');
var app = express();
var bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({extended: true}));
app.set('port', (process.env.PORT || 3000));
app.use('/', function(request, response){
response.send();
});
app.post('/sms', function(req, res) {
const twiml = new MessagingResponse();
twiml.message('Hi, this is Culpability. Your incident has been logged. Your
unique id # XXXX');
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
app.listen(app.get('port'), function() {
// console.log('Node app is running on port', app.get('port'));
});
Twilio developer evangelist here.
I think the problem is mostly in the method you are using to send the response. Currently your final line of the /sms route is res.end(twiml.toString()); however Response#end is used "to quickly end the response without any data."
I think your use of res.writeHead() might be outdated now too.
I would change your /sms route to something like this:
app.post('/sms', function(req, res) {
const twiml = new MessagingResponse();
twiml.message('Hi, this is Culpability. Your incident has been logged. Your unique id # XXXX');
res.set('Content-Type', 'text/xml');
res.status(200).send(twiml.toString());
});
Then try redeploying to Heroku and see what happens.

Resources