GithubHelp home page GithubHelp logo

twilio / twilio-node Goto Github PK

View Code? Open in Web Editor NEW
1.4K 90.0 494.0 42.48 MB

Node.js helper library

License: MIT License

Makefile 0.01% JavaScript 1.18% Dockerfile 0.01% TypeScript 98.80%
twilio twiml twilio-api

twilio-node's Introduction

twilio-node

Documentation

The documentation for the Twilio API can be found here.

The Node library documentation can be found here.

Versions

twilio-node uses a modified version of Semantic Versioning for all changes. See this document for details.

Supported Node.js Versions

This library supports the following Node.js implementations:

  • Node.js 14
  • Node.js 16
  • Node.js 18
  • Node.js LTS (20)

TypeScript is supported for TypeScript version 2.9 and above.

Warning Do not use this Node.js library in a front-end application. Doing so can expose your Twilio credentials to end-users as part of the bundled HTML/JavaScript sent to their browser.

Installation

npm install twilio or yarn add twilio

Test your installation

To make sure the installation was successful, try sending yourself an SMS message, like this:

// Your AccountSID and Auth Token from console.twilio.com
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';

const client = require('twilio')(accountSid, authToken);

client.messages
  .create({
    body: 'Hello from twilio-node',
    to: '+12345678901', // Text your number
    from: '+12345678901', // From a valid Twilio number
  })
  .then((message) => console.log(message.sid));

After a brief delay, you will receive the text message on your phone.

Warning It's okay to hardcode your credentials when testing locally, but you should use environment variables to keep them secret before committing any code or deploying to production. Check out How to Set Environment Variables for more information.

Usage

Check out these code examples in JavaScript and TypeScript to get up and running quickly.

Environment Variables

twilio-node supports credential storage in environment variables. If no credentials are provided when instantiating the Twilio client (e.g., const client = require('twilio')();), the values in following env vars will be used: TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN.

If your environment requires SSL decryption, you can set the path to CA bundle in the env var TWILIO_CA_BUNDLE.

Client Initialization

If you invoke any V2010 operations without specifying an account SID, twilio-node will automatically use the TWILIO_ACCOUNT_SID value that the client was initialized with. This is useful for when you'd like to, for example, fetch resources for your main account but also your subaccount. See below:

// Your Account SID, Subaccount SID Auth Token from console.twilio.com
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const subaccountSid = process.env.TWILIO_ACCOUNT_SUBACCOUNT_SID;

const client = require('twilio')(accountSid, authToken);
const mainAccountCalls = client.api.v2010.account.calls.list; // SID not specified, so defaults to accountSid
const subaccountCalls = client.api.v2010.account(subaccountSid).calls.list; // SID specified as subaccountSid

Lazy Loading

twilio-node supports lazy loading required modules for faster loading time. Lazy loading is enabled by default. To disable lazy loading, simply instantiate the Twilio client with the lazyLoading flag set to false:

// Your Account SID and Auth Token from console.twilio.com
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;

const client = require('twilio')(accountSid, authToken, {
  lazyLoading: false,
});

Enable Auto-Retry with Exponential Backoff

twilio-node supports automatic retry with exponential backoff when API requests receive an Error 429 response. This retry with exponential backoff feature is disabled by default. To enable this feature, instantiate the Twilio client with the autoRetry flag set to true.

Optionally, the maximum number of retries performed by this feature can be set with the maxRetries flag. The default maximum number of retries is 3.

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;

const client = require('twilio')(accountSid, authToken, {
  autoRetry: true,
  maxRetries: 3,
});

Specify Region and/or Edge

To take advantage of Twilio's Global Infrastructure, specify the target Region and/or Edge for the client:

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;

const client = require('twilio')(accountSid, authToken, {
  region: 'au1',
  edge: 'sydney',
});

Alternatively, specify the edge and/or region after constructing the Twilio client:

const client = require('twilio')(accountSid, authToken);
client.region = 'au1';
client.edge = 'sydney';

This will result in the hostname transforming from api.twilio.com to api.sydney.au1.twilio.com.

Iterate through records

The library automatically handles paging for you. Collections, such as calls and messages, have list and each methods that page under the hood. With both list and each, you can specify the number of records you want to receive (limit) and the maximum size you want each page fetch to be (pageSize). The library will then handle the task for you.

list eagerly fetches all records and returns them as a list, whereas each streams records and lazily retrieves pages of records as you iterate over the collection. You can also page manually using the page method.

For more information about these methods, view the auto-generated library docs.

// Your Account SID and Auth Token from console.twilio.com
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);

client.calls.each((call) => console.log(call.direction));

Enable Debug Logging

There are two ways to enable debug logging in the default HTTP client. You can create an environment variable called TWILIO_LOG_LEVEL and set it to debug or you can set the logLevel variable on the client as debug:

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;

const client = require('twilio')(accountSid, authToken, {
  logLevel: 'debug',
});

You can also set the logLevel variable on the client after constructing the Twilio client:

const client = require('twilio')(accountSid, authToken);
client.logLevel = 'debug';

Debug API requests

To assist with debugging, the library allows you to access the underlying request and response objects. This capability is built into the default HTTP client that ships with the library.

For example, you can retrieve the status code of the last response like so:

const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';

const client = require('twilio')(accountSid, authToken);

client.messages
  .create({
    to: '+14158675309',
    from: '+14258675310',
    body: 'Ahoy!',
  })
  .then(() => {
    // Access details about the last request
    console.log(client.lastRequest.method);
    console.log(client.lastRequest.url);
    console.log(client.lastRequest.auth);
    console.log(client.lastRequest.params);
    console.log(client.lastRequest.headers);
    console.log(client.lastRequest.data);

    // Access details about the last response
    console.log(client.httpClient.lastResponse.statusCode);
    console.log(client.httpClient.lastResponse.body);
  });

Handle exceptions

If the Twilio API returns a 400 or a 500 level HTTP response, twilio-node will throw an error including relevant information, which you can then catch:

client.messages
  .create({
    body: 'Hello from Node',
    to: '+12345678901',
    from: '+12345678901',
  })
  .then((message) => console.log(message))
  .catch((error) => {
    // You can implement your fallback code here
    console.log(error);
  });

or with async/await:

try {
  const message = await client.messages.create({
    body: 'Hello from Node',
    to: '+12345678901',
    from: '+12345678901',
  });
  console.log(message);
} catch (error) {
  // You can implement your fallback code here
  console.error(error);
}

If you are using callbacks, error information will be included in the error parameter of the callback.

400-level errors are normal during API operation ("Invalid number", "Cannot deliver SMS to that number", for example) and should be handled appropriately.

Use a custom HTTP Client

To use a custom HTTP client with this helper library, please see the advanced example of how to do so.

Use webhook validation

See example for a code sample for incoming Twilio request validation.

Docker image

The Dockerfile present in this repository and its respective twilio/twilio-node Docker image are currently used by Twilio for testing purposes only.

Getting help

If you need help installing or using the library, please check the Twilio Support Help Center first, and file a support ticket if you don't find an answer to your question.

If you've instead found a bug in the library or would like new features added, go ahead and open issues or pull requests against this repo!

Contributing

Bug fixes, docs, and library improvements are always welcome. Please refer to our Contributing Guide for detailed information on how you can contribute.

⚠️ Please be aware that a large share of the files are auto-generated by our backend tool. You are welcome to suggest changes and submit PRs illustrating the changes. However, we'll have to make the changes in the underlying tool. You can find more info about this in the Contributing Guide.

If you're not familiar with the GitHub pull request/contribution process, this is a nice tutorial.

Get started

If you want to familiarize yourself with the project, you can start by forking the repository and cloning it in your local development environment. The project requires Node.js to be installed on your machine.

After cloning the repository, install the dependencies by running the following command in the directory of your cloned repository:

npm install

You can run the existing tests to see if everything is okay by executing:

npm test

To run just one specific test file instead of the whole suite, provide a JavaScript regular expression that will match your spec file's name, like:

npm run test:javascript -- -m .\*client.\*

twilio-node's People

Contributors

alexpayment avatar asabuhere avatar carlosdp avatar childish-sambino avatar cjcodes avatar codejudas avatar dkundel avatar dougblack avatar ekarson avatar eshanholtz avatar ilanbiala avatar jennifermah avatar jingming avatar jmctwilio avatar jwitz10 avatar kwhinnery avatar philnash avatar porsager avatar ragil avatar sbansla avatar shwetha-manvinkurke avatar sjwalter avatar skimbrel avatar stern-shawn avatar thinkingserious avatar tiwarishubham635 avatar tmconnors avatar twilio-ci avatar twilio-dx avatar wanjunsli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

twilio-node's Issues

XML entities not escaped in TwiML response

Symbols like ampersand aren't escaped in the XML response.

For example:

var resp = new Twilio.TwimlResponse();
resp.sms("one, two, & three");
resp.toString(); // doesn't escape the & and creates invalid markup

The competing "twilio-js" package fixed this in their project by doing this: stevegraham/twilio-js@4dce3ee

v1.10.0 not reading environment variables correctly

Hi, it appears that something in the 1.10.0 release broke part of the twilio initialization process. In v1.9.0, I could call the following:
var twilio = require('twilio');
If I had the appropriately-named environment variables (TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN), they would get picked up just fine and I could go straight to sending messages (ex. twilio.messages.create(...)).

However, in v1.10.0, running the same code results in a Exception while invoking method '/notifications/insert' TypeError: Cannot call method 'create' of undefined error. Specifically, it looks like calling var twilio = require('twilio') does not actually run the initializer. If I call console.log(twilio), I get:

{ [Function: initializer]
RestClient: [Function: RestClient],
Capability: [Function: Capability],
TwimlResponse: [Function],
validateRequest: [Function],
validateExpressRequest: [Function],
webhook: [Function] }

If I explicitly call var twilio = require('twilio')($accountSid, $authToken), it works just fine in v1.10.0. Ultimately, I don't think is a huge issue, but per the discussion I had with the support team via email, the behavior that v1.9.0 exhibited (reading in environment variables) has been in place since February. That implies something else broke this, so curious to see if anyone else has noticed similar issues.

media.delete() on a media instance returns 404

When I create and send an MMS, I call a function in a separate fallback application using the statusCallback property. I'm trying to use that function to check for smsStatus of 'sent' and then delete any media instances that were created for a message from Twilio's servers.

I can get as far as actually listing the media instances, but attempting to delete them is a problem. I actually get a media list with media instances in the array, and the console.log statement in the if(err) block shows a value for mediaElement.sid, but the second console.log statement there shows err.status of 404.

if (req.body.SmsStatus === 'sent') {
        twilio_client.messages(req.body.MessageSid).media.list(function(err, data) {
            if (data.media_list.length > 0) {
                data.media_list.forEach(function(mediaElement) {
                twilio_client.messages(req.body.MessageSid).media(mediaElement.sid).delete(function(err, data) {
                    if (err) {
                      console.log('Unable to delete Twilio media instance: ' + mediaElement.sid);
                      console.log('Error status: ' + err.status);
                    } else {
                      console.log('Twilio media instance ' + mediaElement.sid + ' deleted successfully.');
                    }
                });
            });
            }
        });
    }

Events for Calls

The unofficial node-twilio-api has a nice feature where its call object emits an event when the status of the call changes. For example:

app.makeCall("+12225551234", "+13335551234", function(err, call) {
  if(err) throw err;

  call.on('connected', function(status) {
    //Called when the caller picks up
    call.say("This is a test. Goodbye!");
  });
  call.on('ended', function(status, duration) {
      //Called when the call ends
  });
});

This makes things a heck of a lot easier when dealing with user data stored in sessions, request/response objects (especially POST data), etc.

Imagine if on('ended') you could then do res.send(...) within the same route. Would this be possible to implement here?

TwiML Node Example

Is there an example of capturing dial-pad response during a call w/ TwiML through this node module?

Getting error on line 89 of generate.js

When running global.smsTransporter = require('twilio')(accountSid, authToken); With both arguments as strings, I get the following error:

object[key] = object[method[key].toLowerCase()];
TypeError: Object function (cb) {
    for (var k in this) {
        if(this.hasOwnProperty(k)) {
            cb(k);
        }
    }
} has no method 'toLowerCase'

I made this modification to line 89 and it fixed it:

object[key] = object[(method[key]+"").toLowerCase()];

(forcing it to be a string).

Am I doing something wrong?

Escaping & to & when creating gather URL

Hi, am trying to create the following request:

/executeQuestion/d63cdc0b-40b1-433b-b205-788af18b92b2?surveyId=2c4b8d56-2817-42da-98f3-8a868c2a3aaa&stepId=2

but when i do a resp.toString() it parses the URI in XML, its escaping the ampersand, so i get:

/executeQuestion/d63cdc0b-40b1-433b-b205-788af18b92b2?surveyId=2c4b8d56-2817-42da-98f3-8a868c2a3aaa&stepId=2

client.messages(sid).media.list() returns no media

I'm having some difficulty getting media for a message. I sent an image from my phone to the number and I can see that mediaNum is 1. However, the mediaList returned is an empty array.

import twilio from 'twilio';

var SID = '...';
var AUTH_TOKEN = '...';
var client = twilio(SID, AUTH_TOKEN);

client.messages.list(function (err, data) {
  if (err) throw err;

  let {messages} = data;

  messages.forEach(function(message) {
    let {sid} = message;

    if (message.numMedia > 0) {
      client.messages(sid).media.list(function (err, data) {
        if (err) throw err;
        console.log(JSON.stringify(data, null, 2));
      });
    }
  });
});

What I get in return is this

{
  "first_page_uri": "/2010-04-01/Accounts/.../Messages/.../Media.json?PageSize=50&Page=0",
  "end": 0,
  "media_list": [],
  "previous_page_uri": null,
  "uri": "/2010-04-01/Accounts/.../Messages/.../Media.json?PageSize=50&Page=0",
  "page_size": 50,
  "start": 0,
  "next_page_uri": null,
  "num_pages": 0,
  "total": 0,
  "last_page_uri": "/2010-04-01/Accounts/.../Messages/.../Media.json?PageSize=50&Page=0",
  "page": 0,
  "firstPageUri": "/2010-04-01/Accounts/.../Messages/.../Media.json?PageSize=50&Page=0",
  "mediaList": [],
  "previousPageUri": null,
  "pageSize": 50,
  "nextPageUri": null,
  "numPages": 0,
  "lastPageUri": "/2010-04-01/Accounts/.../Messages/.../Media.json?PageSize=50&Page=0"
}

Am I doing it wrong?

recordings.delete broken in 1.11.0

While using version 1.10.0 of twilio-node, I used a command like this to delete a recording:

client.recordings(sid).delete(func callback(err){})

This works fine in 1.10.0. In 1.11.0, the recording is deleted off of the Twilio server, but the delete() call dies on line 147 of Client.js because the variable "data" is null. "data" is set to null on line 122 of Client.js because the variable "body" is empty.

I haven't dug further than this. Any thoughts?

MMS not going through?

I'm running the below and "yay" with messageData JSON is being logged into console, but I don't seem to receive any texts. I've tried this w/ multiple carriers and phones. What's the next step for debugging?

client.sendMessage({
    to: 'omitted',
    body: 'test',
    mediaUrl: 'http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg',
    from: 'omitted'
  }, function(err, messageData) {
      if (err) {
        console.error(err);
      } else {
        console.log(messageData)
        console.log('yay')
      }
  });

documentation has no mention of how to send a dial response

I'm trying to create a server that forwards the call with the twilio number in the callerId so that the person receiving the call knows it's a business call (and to answer appropriately).

The documentation makes no mention of TwimlResponse in relation to Dial, Number, callerId, record, etc... and just looking over the code it's unclear to me.

(The raw xml I tried responds with an application error, so I figured trying the node api response object would be a good idea)

Add 'Accept-Charset: utf-8' header

To specify we want utf-8 data back from Twilio, clients must to pass an Accept-Charset: utf-8 header to the API.

In general a Unicode audit would be good - test that unicode characters generate the correct percent-encoded request URL's.

Document error handling

How do you get the error message? Is the Twilio error code or the HTTP status code attached to the error?

version 1.4.0 sendMessage using wrong URL?

when following this document:
https://www.twilio.com/docs/api/rest/test-credentials#test-sms-messages
the curl command url ends in "[SID]/SMS/Messages"

when using this library (twilio-node) to call sendMessage and logging out the url of the post (around line 33 of lib/resources/Messages.js)
console.log(baseResourceUrl)
Messages.post = generate(client, 'POST', baseResourceUrl);

it shows that the url ends in "[SID]/Messages" and it fails with an 21606 error even when using the 5005550006 phone number for testing.

Am I using this wrong or is the URL from line 8 of Messages.js wrong?
var baseResourceUrl = '/Accounts/' + accountSid + '/Messages';

SendMessage for international numbers issue

I've been investigating a bug on our phone verification service that has me a bit lost. I've managed to find out that the issue begins to happen on any version after 1.1. US phone numbers are the only numbers that continue to work fine on v1.10, while many of our international users have had issues receiving texts.

Below is the request/responses from using 1.1.4 vs 1.10.0. I went ahead and purchased a twilio Belgium number to test this out and can confirm that the Belgium number is error-ing out in 1.10.0 while the US phone continues to work. Any idea?

Version 1.1.4:

Request opts

method: 'POST',
form:
{ To: '+32460200231',
From: '+18622147444',
Body: 'Hi @y, your verification code is 6531' },
headers:
{ Accept: 'application/json',
'User-Agent': 'twilio-node/1.1.4' } }

Error Response

null

Version 1.10.0

Request opts - Belgium phone number

method: 'POST',
form: null,
headers:
{ Accept: 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'twilio-node/1.10.0',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
timeout: 31000,
body: 'To=+32460200231&From=+18622147444&Body=Hi @y, your verification code is 2250' }

Error Response:

{ status: 400,
message: 'The 'To' number 32460200231 is not a valid phone number.',
code: 21211,
moreInfo: 'https://www.twilio.com/docs/errors/21211' }

Request opts - US phone number

method: 'POST',
form: null,
headers:
{ Accept: 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'twilio-node/1.10.0',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
timeout: 31000,
body: 'To=+1908XXXXXXX&From=+18622147444&Body=Hi @y, your verification code is 7511' }

Error Response:

null

media twiml verb

You should be able to

var resp = new twilio.TwimlResponse();
resp.media("...");

but, there is no media method.

LookupsClient in docs but not in module.

I cannot seem to find the LookupsClient, but I see it in the docs:
https://www.twilio.com/docs/api/rest/lookups

// Download the Node helper library from twilio.com/docs/node/install
// These vars are your accountSid and authToken from twilio.com/user/account
var accountSid = 'AC7425ab30a8809d5b4f714da8b3740860';
var authToken = "{{ auth_token }}";
var client = require('twilio').LookupsClient(accountSid, authToken);

client.phoneNumbers.get("+15108675309", function(error, number) {
    process.stdout.write(number.phoneNumber);
});

Sails.js

Hello,

i am using sails.js and i am not able to trace my code in controller like print array ....

eventhough it is not displaying in console.log..

pl.help me

TwiMLresponse missing

My apologies if I'm asking a basic question but the twil.say always fails,
The calls comes throuh but the say says, "an application error occurred".

Would you guide me as how I should properly do the following please.
Thanks alot.
Cheers,

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var twilio = require('twilio');
var client = twilio('AC02981xxxxxxxxxxxxxxxxxxxx', 'e5e7c54cb5xxxxxxxxxxxxxxxxxxxx');


var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);



app.post('/voiceapi', function(req, res){
        var twiml = new twilio.TwimlResponse();
        twiml.say('Thanks for your call');
        res.type('text/xml');
        res.send(twiml.toString());
});



http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));

        console.log("twilio obj is");
        console.log(twilio);
});

//Place a phone call, and respond with TwiML instructions from the given URL
client.makeCall({

    to:'+1604xxxxxx', // Any number Twilio can call
    from: '+1604xxxxxx', // A number you bought from Twilio and can use for outbound communication
    url: 'http://thawing-anchorage-2174.herokuapp.com/voiceapi' // 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("The call has been initiated.");
    console.log(responseData.from); // outputs "+14506667788"

});

why not lodash?

In general it seems that underscore is being replaced by lodash. Is there any particular reason this project is using the original underscore instead?

Send message Example incorrect

examples/example.js currently has the following for its send MMS example:

client.messages.post({
    to: '+16515556677', // Any number Twilio can deliver to
    from: '+14506667788', // A number you bought from Twilio and can use for outbound communication
    body: 'Kind sir, won\'t you instruct me how to douglas?',
    contentUrls: 'http://cdn.memegenerator.co/images/200x/42.jpg'
}, function (err, responseData) {
    console.log(responseData);
});

but contentUrls doesn't exist and should be mediaUrl

Twillio client pegging CPU at 100% with node 0.10.24

I had to disable Twillio because it was crashing my node server. I was sending a couple of SMS , no more that 10.

I observed two things. I was getting the following message:
"connections property is deprecated. Use getConnections() method". I googled and this message is thrown because it's deprecated in 0.10.

Also run node-tick to get a profile of what was consuming the CPU and found that it mostly stuck in the getSafe function, that's how I figure out it was Twillio. I commented out the code that sends the message and the problem went away. I like twillio but this makes me wonder its reliability....

split long messages into more

Hi Kevin,

unfortunately this is not valid for UK:
https://www.twilio.com/help/faq/sms/how-much-does-it-cost-to-send-a-message-with-more-than-160-characters

as this Twilio support communication state:

[...]
 I know that getting concatenated SMS for the UK is a priority for our product team, but it's hard to say exactly when it will be rolled out
[...]

So I was wondering if there is something this library can do about it, or do you have any suggestion on how to write a little function that splits texts in multiple parts taking into consideration multibyte characters as well.

Explosive memory consumption under node 0.10.2x

TL;DR; it appears that there is a significant memory leak in this library -- I'm trying to track it down, this is a preliminary report to provide context.

Full version:

I've created a small web app that accepts messages with attachments, stores the attachments securely, and sends a password via twilio to the recipient. The mailer daemon is a single long-running node process that follows a CouchDB _changes feed, looking for new messages.

When I use twilio-node to send the text message, the SMS successfully arrives, BUT the node process' memory consumption balloons to ~700mb resident, ~2Gb all told.

While not certain, I believe the bug is about 50% replicable. I know for sure it can be reliably reproduced after sending three or four messages. We closed the bug by removing/replacing this library.

Therefore it's off the critical path insofar as my work is concerned. While I can't share the (proprietary) code that's demonstrating the issue, I will attempt to debug twilio-node in my spare time, and will keep you posted. I also have a core file (decanted from the still-running node process via gcore) but again it's got proprietary information in it; I'd need to share it via formal channels with Twilio Inc. (We're a medical services firm, and have to worry about HIPAA privacy legislation in the U.S. and PIPEDA in Canada, and thus have to take security about five times more seriously than I would like -- at least, while I'm debugging ;D)

OS: cloud-provisioned CentOS 6.x, x86_64, 1gb RAM; bug reproducible, even with SELinux disabled.

Reproduced in: nvm-installed 0.10.21, 0.10.22, 0.10.23, and 0.11.x

twilio-node version: 1.4.0

errors should inherit from the Error object

currently twilio errors are represented as a dictionary:

            error = {};
            // response is null if server is unreachable
            if (response) {
                error.status = response.statusCode;
                error.message = data ? data.message : 'Unable to complete HTTP request';
                error.code = data && data.code;
                error.moreInfo = data && data.more_info;
            } else {
                error.status = err.code;
                error.message = 'Unable to reach host: "'+client.host+'"';
            }

it would be better if errors inherited from the Error js object. there are a few reasons for this:

  • Error objects have stack traces, which help you nail down where they originate
  • makes it possible for someone to throw a Twilio error (currently a dictionary). the JS behavior for throwing/catching non-Error objects is wonky at best and handling varies by library
  • mocha, raven-node behave oddly when you're using them without an Error object.

It would be pretty straight forward to add considering there is already a message property on the object.

Multiple media URLs for MMS

It's not entirely clear how you would pass multiple media URLs for MMS with the node module. In keeping with the actual REST API, there is only one parameter name, called mediaUrl or MediaUrl (names are automatically capitalized if need be by the helper).

To pass multiple media URLs, you need to assign an array of String URLs to this property rather than just a single string. We have not documented this anywhere.

Further, it may be confusing to have a parameter called mediaUrl when the parameter being passed is an array. Maybe there needs to be a magic parameter mediaUrls which knows how to handle the array of URLs as well.

empty response blows the server away

TypeError: Cannot read property 'statusCode' of undefined 
   Request._callback() ./node_modules/twilio/lib/RestClient.js:116:43
   self.callback() ./node_modules/request/request.js:129:22
   Request.EventEmitter.emit() events.js:95:17
   ClientRequest.self.clientErrorHandler() ./node_modules/request/request.js:239:10
   ClientRequest.EventEmitter.emit() events.js:95:17
   CleartextStream.socketErrorListener() http.js:1547:9
   CleartextStream.EventEmitter.emit() events.js:95:17
   SecurePair.<anonymous>() tls.js:1386:15
   SecurePair.EventEmitter.emit() events.js:95:17
   SecurePair.error() tls.js:1006:27
   EncryptedStream.CryptoStream._done() tls.js:695:22
   CleartextStream.read() [as _read] tls.js:496:24
   CleartextStream.Readable.read() _stream_readable.js:320:10
   EncryptedStream.onCryptoStreamFinish() tls.js:301:47
   EncryptedStream.g() events.js:175:14
   EncryptedStream.EventEmitter.emit() events.js:117:20
   finishMaybe() _stream_writable.js:354:12
   endWritable() _stream_writable.js:361:3
   EncryptedStream.Writable.end() _stream_writable.js:339:5
   EncryptedStream.CryptoStream.end() tls.js:633:31
   Socket.onend() _stream_readable.js:483:10
   Socket.g() events.js:175:14
   Socket.EventEmitter.emit() events.js:117:20
   _stream_readable.js:920:16()
   process._tickCallback() node.js:415:13


 Thrown: ./node_modules/twilio/lib/RestClient.js:116
   114:             var error = null;
   115:             if (err || (response.statusCode < 200 || response.statusCode > 206))
 ✘ 116:                 error = { status: response.statusCode };
   117:                 error.message = data ? data.message : 'HTTP request error, check
   118:                 error.code = data && data.code;

Got this error on production from last night.
As the stack says we have a case when response from module request is undefined. I will try to send a pull request. Most probably it would be better to hard code the minor version in the package.json to avoid surprises, 2.27.x.

Media "delete" returns no error, but data has ``status: 500``.

I'm running this:

var twilioClient = require("twilio")(<AccountSID>, <AuthToken>);
twilioClient.messages(<MessageID>).media(<MediaID>).delete(function(err, data) {
      console.log(err, data); // Logs "null, {status: 500, message: 'Empty body'}"
});

Within the callback, err is null, but data is {status: 500, message: "Empty body"}. The media file is successfully deleted. It's confusing to get a reported 500 status when the command succeeds and no err is given.

Queue and Member information not being returned

I am getting an error when attempting to access members of a queue.

I have tried both methods below for adding members to the queue in case I was mistaken about how the system worked. (I started using the Enqueue method)

support and support Both of these seem to work in adding the call to the queue and playing the hold music

I have also checked to make sure I have the correct SID for the queue

Running the code

client.queues.list(function(err, data) {
data.queues.forEach(function(queue) {
console.log(queue.friendlyName + ": " + queue.sid);
});
});
give me the result

support: QUxxxxxxxxxxxxxxxx6

Yet when I have calls in the queue holding and try to extract data using an example right from the twilio API page at https://www.twilio.com/docs/api/rest/member

client.queues('QUxxxxxxxxxxxxxxxx6').members.list(function(err, data) {
data.members.forEach(function(member) {
console.log(member.Position);
});
});
I get the following error

GET /inbound/call/agent 200 39.997 ms - 73

/var/www/tcc/node_modules/twilio/node_modules/q/q.js:126
throw e;
^
TypeError: Cannot call method 'forEach' of undefined
at /var/www/tcc/routes/index.js:348:20
at /var/www/tcc/node_modules/twilio/node_modules/q/q.js:1920:17
at flush (/var/www/tcc/node_modules/twilio/node_modules/q/q.js:108:17)
at process._tickCallback (node.js:415:13)
17 Feb 14:02:42 - [nodemon] app crashed - waiting for file changes before starting...

After doing additional testing I can manually queue the resource page like you would using cURL and the data is displayed correctly there.

This error exists for queueing any information for a Queue except for its Sid

the Sid displays fine

StatusCallback not working

Hi guys,

I developed a function to make call using Rest API as below:
client.calls.create({
url: url_to_twiml,
to: tonumber,
from: fromnumber,
timeout: 60,
method : 'GET',
statuscallback : "https://****/api/call-status",
statuscallbackmethod : 'GET'
}, function(err, call) {
});

When I ran that function, a call was made but I didn't get any callback to statuscallback url which configed above.

Has anyone faced this problem yet?

Please help me to fix this.

Thank you.

Twilio.sendMessage, price in response data is null

I used Twilio.sendMessage to send SMS:

Twilio.sendMessage({to: to, from: from, body: message   }, function(err, responseData) {
   console.log(responseData);
};

Here is the sample of the responseData: (some fields are masked)

{ sid: 'xxx',
  date_created: 'Tue, 20 May 2014 04:34:22 +0000',
  date_updated: 'Tue, 20 May 2014 04:34:22 +0000',
  date_sent: null,
  account_sid: 'xxx',
  to: 'xxx',
  from: 'xxx',
  body: 'xxx',
  status: 'queued',
  num_segments: '1',
  num_media: '0',
  direction: 'outbound-api',
  api_version: '2010-04-01',
  price: null,
  price_unit: 'USD',
  uri: '/2010-04-01/Accounts/xxx/Messages/xxx.json',
  subresource_uris: { media: '/2010-04-01/Accounts/xxx/Messages/xxx/Media.json' },
  dateCreated: Tue May 20 2014 12:34:22 GMT+0800 (HKT),
  dateUpdated: Tue May 20 2014 12:34:22 GMT+0800 (HKT),
  dateSent: null,
  accountSid: 'xxx',
  numSegments: '1',
  numMedia: '0',
  apiVersion: '2010-04-01',
  priceUnit: 'USD',
  subresourceUris: { media: '/2010-04-01/Accounts/xxx/Messages/xxx/Media.json' } }

and the field price become null

Twilio & Stackmob

I'm trying to use Stackmob as my database backend for client's data including their phone numbers and then use Twilio to call/sms them. I'm new to Javascript and learning quickly and have been using Backbone with Stackmob to query my schema .Collections object
Generally is it feasible to assume that an incoming voice call that triggers the Twilio Voice url ../example.js could have both the TwimlResponse object and also have a Stackmob.model object which could be queried to provide the JS variable "to" for the dial verb to forward the incoming call to "to" ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.