Code Monkey home page Code Monkey logo

node-twilio's Introduction

This is many years out of date now - please use the official library instead: https://github.com/twilio/twilio-node

node-twilio

A Node.js Twilio helper library.

Installation

Parts of node-twilio depend on express.

To install via npm:

npm install twilio

To install by hand, download the module and create a symlink in ~/.node_libraries

$ ln -s /path/to/node-twilio ~/.node-libraries/twilio

Note: Previously, the npm package named twilio referred to Aaron Blohowiak's Twilio helper library. Due to Aaron's time constraints, he has let this package use the twilio name while he is unable to work on that implementation.

Usage

To start, you'll need to obtain a Twilio account. (http://twilio.com). This will give you a Twilio Account Sid and a Twilio Auth Key. Using these, you may start using node for complex, awesome telephony applications.

To really get down to business, check out the documentation.

API

Low-Level REST Api Client

node-twilio provides a low-level interface for making requests of Twilio. This functionality is contained in lib/rest-client.js, and maps pretty much one-to-one with the Twilio REST API documentation.

Each method accepts a callback function that returns the HTTP response object resulting from the API request, as well as options specific to that call.

The low-level REST Api, whil helpful, is little more than a simple wrapper around the node HTTP library. It takes care of the HTTP Basic auth, ensuring all your parameters are serialized properly, unmarshalling the responses (which we use purely the JSON representation from Twilio), and letting you, the developer, use the responses. This is pretty boring. (Note: My saying 'this is pretty boring' is just a way for me to excuse myself from writing the documentation for the low-level client right now. I'll do it soon. The source is fairly well documented, and while I recognize documentation for everything is important, I just wanna skip over this part right now.)

High-Level Rest Api Client

node-twilio provides a high-level interface for dealing with Twilio requests and responses, and encapsulates all the functionality within EventEmitters. This means you can develop Twilio applications in node without worrying about or provisioning URIs for every request and response your application will make; It may be non-obvious from the description, but that is awesome.

In order to explain how great this is, I will use an example:

If you were to build a Twilio application in any language using any helper library other than this one, you'd wind up doing something like:

Twilio.makeOutgoingCall(toNumber, fromNumber, UriForCallback);

Then, you'd have to go out and ensure than UriForCallback is a real, provisioned URI, and you'd put either a script or a static Twiml file there, and Twilio would go and fetch it.

node-twilio, however, takes care of all of that provisioning for you, and represents all Twilio interacts as EventEmitters. Again, this is awesome. Here's an example:

First, we want to instantiate a new Twilo client object. The constructor takes three parameters: the account SID and auth token, as well as the hostname of the application server. (This is used to construct URIs to give Twilio.)

var sys = require('sys'),
    TwilioClient = require('twilio').Client,
    client = new TwilioClient(ACCOUNT_SID, AUTH_TOKEN, MY_HOSTNAME);

Now that we have our client, let's get a PhoneNumber object using one of the phone numbers that we've provisioned through some other channel. (Note: You can provision phone numbers very simply via the Low-Level REST API) The phone number used here can be any sort of Twilio number. If it's an outgoing caller ID, the object will only be able to make outgoing phone calls/SMS. If it's a regular incoming number, it will be able to make/receive phone calls and SMS.

var phone = client.getPhoneNumber('+16269239971');

We'll now setup our phone number. This goes out and requests the phone number instance resource and fills in a data structure with this phone number's details.

phone.setup(function() {
    
    // Alright, our phone number is set up. Let's, say, make a call:
    phone.makeCall('+18674451795', null, function(call) {
        
        // 'call' is an OutgoingCall object. This object is an event emitter.
        // It emits two events: 'answered' and 'ended'
        call.on('answered', function(reqParams, res) {
            
            // reqParams is the body of the request Twilio makes on call pickup.
            // For instance, reqParams.CallSid, reqParams.CallStatus.
            // See: http://www.twilio.com/docs/api/2010-04-01/twiml/twilio_request
            // res is a Twiml.Response object. This object handles generating
            // a compliant Twiml response.
            
            console.log('Call answered');

            // We'll append a single Say object to the response:
            res.append(new Twiml.Say('Hello, there!'));

            // And now we'll send it.
            res.send();
        });
        
        call.on('ended', function(reqParams) {
            console.log('Call ended');
        });
    });

    // But wait! What if our number receives an incoming SMS?
    phone.on('incomingSms', function(reqParams, res) {
        
        // As above, reqParams contains the Twilio request parameters.
        // Res is a Twiml.Response object.
        
        console.log('Received incoming SMS with text: ' + reqParams.Body);
        console.log('From: ' + reqParams.From);
    });

    // Oh, and what if we get an incoming call?
    phone.on('incomingCall', function(reqParams, res) {
        
        res.append(new Twiml.Say('Thanks for calling! I think you are beautiful!'));
        res.send();
    });
});

To get going beyond the basics, check out the documentation.

Notes

More documentation is forthcoming.

License (MIT License)

Copyright (c) 2010 Stephen J. Walters [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

node-twilio's People

Contributors

aslafy-z avatar chadsmith avatar jamessun avatar mattaylor avatar muneebs avatar sjwalter avatar ukd1 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

node-twilio's Issues

Timeouts on heroku

Hey,

I was able to launch my app but I notice its reallly slow right now. Looking at the logs I see:

2012-01-20T02:10:47+00:00 heroku[router]: Error H12 (Request timeout) -> POST morning-dawn-8986.herokuapp.com/autoprovision/58 dyno=web.1 queue= wait= service=30000ms status=503 bytes=0
2012-01-20T02:10:47+00:00 heroku[router]: Error H12 (Request timeout) -> POST morning-dawn-8986.herokuapp.com/autoprovision/57 dyno=web.1 queue= wait= service=30000ms status=503 bytes=0
2012-01-20T02:10:48+00:00 heroku[router]: Error H12 (Request timeout) -> POST morning-dawn-8986.herokuapp.com/autoprovision/59 dyno=web.1 queue= wait= service=30000ms status=503 bytes=0

What are these requests ment to be doing, and should they be timing out (and slowing things down) like this?

Library incompatible with Heroku, etc

This library is incompatible with hosting platforms like Heroku and Joyent, which provide you with a specific port in which to listen. The AutoUri lib makes it necessary to have an additional port open for Twilio requests. Apps therefore crash on startup.

Can the library accept an existing express instance, and add endpoints to it?

Example SMS Send Erroring - Could Not Get Number

In playing around with this library I am starting by trying to send SMS. Following the SMS example I am getting an error thrown at

var phone = client.getPhoneNumber('+XXXXXXXXXX');

The number is a full "upgraded" Twilio number and testing the REST API with CURL indicates it works fine. Starting to dig into the library some now to see if I can find where the issue lies. Any help or suggestions would be appreciated.

Full Error:

/home/chad/twilio2factor/node_modules/twilio/lib/twilio.js:141

                throw new Error('Could not get number ' + 

 ^

Error: Could not get number +4154187543
at /home/chad/twilio2factor/node_modules/twilio/lib/twilio.js:141:27
at IncomingMessage. (/home/chad/twilio2factor/node_modules/twilio/lib/rest-client.js:87:40)
at IncomingMessage.emit (events.js:81:20)
at HTTPParser.onMessageComplete (http.js:133:23)
at CleartextStream.ondata (http.js:1228:22)
at CleartextStream._push (tls.js:303:27)
at SecurePair.cycle (tls.js:577:20)
at EncryptedStream.write (tls.js:96:13)
at Socket.ondata (stream.js:36:26)
at Socket.emit (events.js:64:17)

Is this package still supported?

No updates in a year, pull requests and issues piling up. Just curious. I have an eval account for Twilio and I'm not sure I want to go premium if the node client isn't actively supported.

Modules object is deprecated

Hello,

I've just attempted to install the package with npm and I got the warning about 'modules' being deprecated. I think there's a new way of doing this in the later versions of node, and so the code has to be refactored slightly.

The version of node I'm running is the latest: 'v0.7.0-pre'

npm install twilio
npm http GET https://registry.npmjs.org/twilio
npm http 200 https://registry.npmjs.org/twilio
npm http GET https://registry.npmjs.org/twilio/-/twilio-0.4.0.tgz
npm http 200 https://registry.npmjs.org/twilio/-/twilio-0.4.0.tgz
npm WARN [email protected] package.json: 'modules' object is deprecated
[email protected] ./node_modules/twilio

I'm looking forward to giving this module a try!

undefined request params

I there I have this code

phone.on('incomingSms', function(smsParams, response) {
    console.log("REQUEST:");
    console.log(smsParams);
    var from = smsParams.From;
    ...
});

And when I get a response I see this in my logs

012-01-20T00:00:41+00:00 app[web.1]: REQUEST:
2012-01-20T00:00:41+00:00 app[web.1]: undefined
2012-01-20T00:00:41+00:00 app[web.1]: TypeError: Cannot read property 'From' of undefined

Am I doing something wrong? This seems like the exact way the docs do it.

Thank you!

Demo Account and OutgoingCallerID support

Demo accounts (free credit on twilio.com) are not allocated OutgoingNumbers, so client.getPhoneNumber() fails even though there are numbers registered which work for outgoing calls with the REST api, this also means that the registration of incoming events not associated with outgoing calls is automatic which may not be desired.

Proposed fix: add a getOutgoingNumber() call to match getPhoneNumber() which does not register the incoming number callbacks, other wise the API would be unchanged. This may require an additional parameter to the PhoneNumber constructor which is an internal object and not exported.

Dial Syntax?

I'm trying to get it to just forward the call -- not sure what I'm doing wrong here:

phone.setup(function() {
  phone.on('incomingCall', function(reqParams, res) {
    console.log("New Call:");

    var dial = new Twiml.Dial({Number: new Twiml.Num("+15555555"), callerId: "+15555555"});

    res.append(dial);
    res.send();
  });
});

Twilio is saying app error but I'm not seeing anything in my logs -- perhaps a timeout. Do I need to listen for the answered event or am I just getting the Twiml API wrong?

Thanks!

Changing "hostname" to "base_url"

I was needing more flexibility for specifying the protocol (http/https) and port (80/443) for the callback URI, so I simplified the whole process by just passing an entire URL string into lib/auto-uri.js

I updated the rest of the project accordingly. See this commit in my fork:

robertjd@ce0a9f2

I wanted to solicit opinions on this before I make a pull request.

Thanks everyone!

Use on dev machines.

Hey, this is my first twillio app ever and I am a newcomer to node as well so please forgive my ignorance. I'm trying to use the dial-list example you provided to create the application.

I keep on getting the following error:

 Error: Could not get number +NNNNNNNNNN

I just tried to do the demo app after verifying my personal number on the twillio website. I used that number for the outgoing number in the config file. I'm confused about what I should put for the hostname. I tried to use my IP address but that didn't work. I would like to try things from my dev machine, rather than push to heroku or ec2 to see if things are working. Any advice?

Facilitate Paging?

I don't see any way to get the next set of data with the twilioClient object. I'm calling getIncomingNumbers and have quite a few to pull down. I suppose I could just say:

client.getIncomingNumbers({ 'PageSize': 150 }, function(data) { .. });

But that doesn't really seem future proof.

Error 'Could not get number '

With the following code:

var phone_number = "12345";
var phone = client.getPhoneNumber(phone_number);
phone.setup(function() { })

If phone_number does not exist in your account, the following is thrown:


                    throw new Error('Could not get number ' + 

^

Error: Could not get number 1234
    at /Users/robert/colingo/Express/node_modules/twilio/lib/twilio.js:142:27
    at IncomingMessage.<anonymous> (/Users/robert/colingo/Express/node_modules/twilio/lib/rest-client.js:86:41)
    at IncomingMessage.emit (events.js:81:20)
    at HTTPParser.onMessageComplete (http.js:133:23)
    at CleartextStream.ondata (http.js:1231:22)
    at CleartextStream._push (tls.js:303:27)
    at SecurePair.cycle (tls.js:577:20)
    at EncryptedStream.write (tls.js:96:13)
    at Socket.ondata (stream.js:36:26)
    at Socket.emit (events.js:64:17)

I have found that putting try/catch around the call to phone.setup() does not actually catch the error.

Two questions:

1.) Why does my try/catch not work?

2.) Is there a better way to check that a number exists in an account?

Is there mandatory events with incomingCall?

After every "incomingCall" event the twilio debugger gets populated with the following error:

ERROR HTTP connection failure

An attempt to retrieve TwiML from
http://4iif.localtunnel.com/autoprovision/3
failed; the connection timed out. Please check the URL and your network settings and try again.

And according to Request it looks like a call status data
I'm wondering which event I should listen to to omit this error?

e.g. for outgoing call I must be listening to "ended" even to omit another similar issue, but it didn't help with incomingCall event...

Thanks.

express dependency missing from package.json

You have no express dep in your package.json file.

You also don't specify which version of express you require. I tried to install the latest express and run your demos, but all I get is:

node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Object # has no method 'bodyDecoder'
at new AutoUri (/Users/maraksquires/dev/hook.io-twilio/node_modules/twilio/lib/auto-uri.js:32:17)
at new Client (/Users/maraksquires/dev/hook.io-twilio/node_modules/twilio/lib/twilio.js:18:15)
at Object. (/Users/maraksquires/dev/hook.io-twilio/test.js:3:15)
at Module._compile (module.js:404:26)
at Object..js (module.js:410:10)
at Module.load (module.js:336:31)
at Function._load (module.js:297:12)
at Array. (module.js:423:10)
at EventEmitter._tickCallback (node.js:126:26)

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.