I am trying to initial a call with a custom variable.
As twilio states, the call is initiated by making a post request to the url provided
var client = require('twilio')(accountSid, authToken);
client.calls.create({
url: "http://demo.twilio.com/docs/voice.xml",
to: "+14155551212",
from: "+1544444444"
}, function(err, call) {
process.stdout.write(call.sid);
});
if the file voice.xml has a variable {{firstName}}
how do I post body.firstName? and whats the appropriate way to format that on the xml side? thank you
Twilio developer evangelist here.
If you need to pass information via that URL, you can do so as URL parameters. For example:
var client = require('twilio')(accountSid, authToken);
client.calls.create({
url: "http://example.com/voice.xml&firstName=Phil",
to: "+14155551212",
from: "+1544444444"
}, function(err, call) {
process.stdout.write(call.sid);
});
Then, when you handle that incoming POST request from Twilio, you can retrieve the URL parameter yourself. If you were using Express as a server, it would look a bit like this:
var express = require('express');
var twilio = require('twilio');
var app = new express();
app.post('/voice.xml', function(request, response) {
var firstName = request.query.firstName;
var twiml = new twilio.TwimlResponse();
twiml.say('Hello ' + firstName + '! How are you today?';
response.set('Content-Type', 'text/xml');
response.send(twiml.toString());
});
Let me know if that helps at all.
Related
I am currently working with the Express platform, the Twilio Node.js SMS API and obviously javascript to send text messages to my users. Problem is, I don't know what I should do in order to send data through my GET variables on the front-end and capture those values with node.js on the back-end.
For testing purposes, I created a simple button that sends a text message to a fixed number when clicked.
Here is the javascript side:
function sms() {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:5001", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText);
}
}
xmlhttp.send();
}
Here is the node.js side:
var accountSid = 'ACCOUNT_SID';
var authToken = 'ACCOUNT_TOKEN';
//require the Twilio module and create a REST client
var client = require('twilio')(accountSid, authToken);
var express = require("express");
var app = express();
app.get('/',function(request,response){
var to = "TO";
var from = "FROM";
client.messages.create({
to: to,
from: from,
body: 'Another message from Twilio!',
}, function (err, message) {
console.log("message sent");
});
});
app.listen(5001);
I have came across two ways to send a responseText from Node.js, but can't manage to make them work
first one using response.send("Hello World"); or the second one response.write("Hello again"); response.end();
So just to sum it up, I want to send variables (to, from, message, etc.) through my http request, capture them in node.js and send a responseText! As a heads up, I'm very comfortable with AJAX requests between JS and PHP, but Node.js is new to me.
Thanks in advance
I think the new Guides will help you out here with How to receive and reply to SMS in Node.js:
https://www.twilio.com/docs/guides/sms/how-to-receive-and-reply-in-node-js
The CodeRail along the right hand side will walk you through it step-by-step but you should pay attention particularly to the section titled "Generate a dynamic TwiML Message".
var http = require('http'),
express = require('express'),
twilio = require('twilio'),
bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', function(req, res) {
var twilio = require('twilio');
var twiml = new twilio.TwimlResponse();
if (req.body.Body == 'hello') {
twiml.message('Hi!');
} else if(req.body.Body == 'bye') {
twiml.message('Goodbye');
} else {
twiml.message('No Body param match, Twilio sends this in the request to your server.');
}
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
http.createServer(app).listen(1337, function () {
console.log("Express server listening on port 1337");
});
So I'm building a connector using the Domo developer tool (they like to call it an IDE) and I just can't seem to get the authentication piece working with their libraries.
Domo uses httprequest library for basic and oauth types of authentication.
I'm having trouble getting token back through Domo, but I can easily do it through a curl or by using the Postman api tool.
Here's the code below:
var client_id = '4969e1ea-71b9-3267-ae7d-4ce0ac6bfa28';
var client_secret = '*****************************';
var user = '*********';
var pass = '*********';
var postData =
{
data: {
'grant_type': 'password',
'username': user,
'password': pass,
'client_id': client_id,
'client_secret': client_secret,
'scope': 'internal'
}
};
var res = httprequest.post('https://rest.synthesio.com/security/v1/oauth/token', postData);
DOMO.log('res: ' + res);
Pleae let me know if you have a different way of approaching this. I've tried to add the header within the postData object itself as well as removing the data variable, leaving the attributes as is, too.
When you past the postData as an object like that, DOMO will run it through JSON.stringify and send the result in the request body.
You can either encode the request body manually or use their httprequest.addParameter function to add them. Try something like this:
var client_id = '4969e1ea-71b9-3267-ae7d-4ce0ac6bfa28';
var client_secret = '*****************************';
var user = '*********';
var pass = '*********';
httprequest.addParameter('grant_type', 'password');
httprequest.addParameter('username', user);
httprequest.addParameter('password', pass);
httprequest.addParameter('client_id', client_id);
httprequest.addParameter('client_secret', client_secret);
httprequest.addParameter('scope', 'internal');
var res = httprequest.post('https://rest.synthesio.com/security/v1/oauth/token');
DOMO.log('res: ' + res);
var http = require('http');
var twilio = require('twilio')(ACCOUNT_SID, AUTH_TOKEN);
var qs = require('querystring');
http.createServer(function (req, res) {
var body = '';
req.setEncoding('utf8');
req.on('data', function(data) {
body += data;
});
req.on('end', function() {
var data = qs.parse(body);
var jsonString = JSON.stringify(data);
var jsonDataObject = JSON.parse(jsonString);
// log the received message
console.log(jsonDataObject.Body);
twilio.messages.create({
to:'MY_PHONE_NUMBER',
from:'TWILIO_NUMBER',
body:'Hello World'
}, function(error, message) {
if (error) {
console.log('There was an error.')
console.log(error.message);
}
});
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end();
});
}).listen(1337, '127.0.0.1');
console.log('TwiML servin\' server running at http://127.0.0.1:1337/');
I'm trying to use the Twilio node module to receive a text message and in turn respond to that text message once received. There seems to be no problem receiving the message as I'm able to log the body. But, I get a 401 Authenticate error when I try and respond to that message. I'm using ngrok to expose my localhost so I can hook it into Twilio's API. Please see below:
Where am I going wrong here?
Twilio developer evangelist here.
You actually don't need to use the REST API in order to reply to an incoming message to a Twilio number. You can, in fact, respond to the incoming HTTP request with TwiML that describes the message in response.
To do this, you need to use the <Message> verb. In your application, this would look like:
First, just require the twilio module without the account credentials:
var twilio = require("twilio");
Then, respond to the incoming request with TwiML, like so:
req.on('end', function() {
var data = qs.parse(body);
var jsonString = JSON.stringify(data);
var jsonDataObject = JSON.parse(jsonString);
// log the received message
console.log(jsonDataObject.Body);
var twiml = new twilio.TwimlResponse();
twiml.message("Hello world");
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
Let me know if this helps at all.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const MessagingResponse = require('twilio').twiml.MessagingResponse;
var server = app.listen(80, function () {
var host = server.address().address
var port = server.address().port
console.log(" web app listening at http://%s:%s", host, port)
})
app.post('/txt', urlencodedParser,(req, res) => {
const twiml = new MessagingResponse();
twiml.message('Finally Twilio works!');
res.status(200);
res.send(twiml.toString());
});
Under your phone number in the console.
You can click webhooks and change it to the http://"putyourserverhere"/txt
This will automatically text back the inbound user.
Enjoy. Make sure you have the newest version of twilio installed.
For my front-end (angular) app, I need to connect to an external API, which does not support CORS.
So my way around this is to have a simple proxy in Node.JS / Express.JS to pass the requests. The additional benefit is that I can set my api-credentials at proxy level, and don't have to pass them to the front-end where the user might steal/abuse them.
This is all working perfectly.
Here's the code, for the record:
var request = require('request');
var config = require('./config');
var url = config.api.endpoint;
var uname = config.api.uname;
var pword = config.api.pword;
var headers = {
"Authorization" : 'Basic ' + new Buffer(uname + ':' + pword).toString('base64'),
"Accept" : "application/json"
};
exports.get = function(req, res) {
var api_url = url+req.url;
var r = request({url: api_url, headers: headers});
req.pipe(r).pipe(res);
};
The API-endpoint I have to use has XML as only output format. So I use xml2js on the front-end to convert the XML reponse to JSON.
This is also working great, but I would like to lighten the load for the client, and do the XML -> JSON parsing step on the server.
I assume I will have to create something like:
req.pipe(r).pipe(<convert_xml_to_json>).pipe(res);
But I don't have any idea how do create something like that.
So basically I'm looking to create an XML to JSON proxy as a layer on top of an already existing API.
There are a lot of questions on SO regarding "how do I make a proxy" and "how do I convert XML to JSON" but I couldn't find any that combine the two.
you need to use transform stream and for xml to json conversion you need some library i use this xml2json
..then u use it like this (simplified but it should work with request too)
var http = require('http');
var fs = require('fs');
var parser = require('xml2json');
var Transform = require('stream').Transform;
function xmlParser () {
var transform = new Transform();
transform._transform = function(chunk, encoding, done) {
chunk = parser.toJson(chunk.toString())
console.log(chunk);
this.push(chunk);
done();
};
transform.on('error', function (err) {
console.log(err);
});
return transform;
}
var server = http.createServer(function (req, res) {
var stream = fs.createReadStream(__dirname + '/data.xml');
stream.pipe(xmlParser()).pipe(res);
});
server.listen(8000);
Please can anybody help me to find out how to get the server socket context in node.js, so that i will come to know request came on which port number on my server.
I can read the server port if i request using http headers but I want it through network and something like socket context which tells request came on which port number.
Here is the sample code:
var http=require('http');
var url = require('url');
var ports = [7006, 7007, 7008, 7009];
var servers = [];
var s;
function reqHandler(req, res) {
var serPort=req.headers.host.split(":");
console.log("PORT:"+serPort[1]);//here i get it using http header.
}
ports.forEach(function(port) {
s = http.createServer(reqHandler);
s.listen(port);
servers.push(s);
});
The req object has a reference to the underlying node socket. You can easily get this information as documented at: http://nodejs.org/api/http.html#http_message_socket and http://nodejs.org/api/net.html#net_socket_remoteaddress
Here is your sample code modified to show the local and remote socket address information.
var http=require('http');
var ports = [7006, 7007, 7008, 7009];
var servers = [];
var s;
function reqHandler(req, res) {
console.log({
remoteAddress: req.socket.remoteAddress,
remotePort: req.socket.remotePort,
localAddress: req.socket.localAddress,
localPort: req.socket.localPort,
});
}
ports.forEach(function(port) {
s = http.createServer(reqHandler);
s.listen(port);
servers.push(s);
});