Latest Version: 2.0.0
The Twilio library wraps Twilio’s API for sending and receiving SMS messages. To get started with this library, you will need a Twilio developer account. Once you’ve created your account, make a note of your Twilio Phone Number, Account SID and Auth Token as these are required to instantiate Twilio objects.
You can view the library’s source code on GitHub.
To include this library in your project, add
#require "Twilio.agent.lib.nut:2.0.0"
at the top of your agent code
To create a new Twilio object, pass your Account SID, Auth token and Twilio Phone Number to the constructor:
#require "Twilio.agent.lib.nut:2.0.0"
twilio <- Twilio("YOUR_ACCOUNT_SID", "YOUR_AUTH_TOKEN", "YOUR_TWILIO_NUMBER");
The send() method is used to send an SMS message. An optional callback can be passed to the function — if a callback is supplied, the message will be sent asynchronously, and your callback will fire when the HTTP request completes. The callback function must include a single parameter into which will be passed a table containing three fields: statuscode, headers and body. If you don’t pass a callback, it will execute the request synchronously and return the table outlined above.
recipientsNumber <- "15555555555";
textMessage <- "Hello World!";
// Send the message synchronously
local response = twilio.send(recipientsNumber, textMessage);
server.log(response.statuscode + ": " + response.body);
// Send it again, this time asynchronously
twilio.send(recipientsNumber, textMessage, function(response) {
server.log(response.statuscode + " - " + response.body);
});
You can respond to text messages by using the respond() method, which will generate the necessary headers and XML for Twilio to understand your response. You must pass on an impOS™ HTTPResponse object, which will be used by the library to respond to Twilio. In the following examples, we’re sending back the message we received, placed in single quote marks and preface with “You just said”. The code uses the HTTPResponse object automatically generated by impOS on receiving an HTTP request. If you don’t pass a message, Twilio will send nothing back to the original sender.
http.onrequest (function(request, response) {
local path = request.path.tolower();
if (path == "/twilio" || path == "/twilio/") {
// Twilio request handler
try {
local data = http.urldecode(request.body);
twilio.respond(response, "You just said '" + data.body + "'");
} catch(ex) {
local message = "Uh oh, something went horribly wrong: " + ex;
twilio.respond(response, message);
}
}
// Default response: all OK
response.send(200, "OK");
});
Note Before the above example will work, you need to configure your Twilio Phone Number:
/twilio
to the end of the path so we know when the message is coming from Twilio:https://agent.electricimp.com/{agentID}/twilio
The Twilio library is licensed under the MIT License.