DEV Community

Cover image for SMS Notifications with Perl and Twilio
Mitch Jackson
Mitch Jackson Subscriber

Posted on

SMS Notifications with Perl and Twilio

Twilio is beyond useful, and easy to integrate. It's one of those tools that, once you get started, you just can't stop using it. You can add SMS Notifications and password resets to your existing application in an afternoon.

I see several examples of Twilio usage on dev.to. But of course, none for Perl, until now.

First, the entire simple program:

#!/usr/bin/env perl
use v5.10;
use strict;
use warnings;
use LWP::UserAgent;

my %text_message = (
    From => '12513001300', # Me
    To   => '16198675309', # Jenny
    Body => 'Thank you for being a friend! Travel down the road and back again!'
);

my %credentials = (
    account_id => '____YOUR_ACCOUNT_SID_GOES_HERE____',
    auth_token => '____YOUR_AUTH_TOKEN_GOES_HERE____',
);

my %twilio = (
    # HTTP Authentication
    api_domain => 'api.twilio.com:443',
    api_realm  => 'Twilio API',

    # Keep your line length within 80 characters please!
    api_url    => 'https://api.twilio.com/2010-04-01/Accounts/'
                  . $credentials{account_id}
                  . '/Messages'
);

my $ua = LWP::UserAgent->new;
$ua->credentials(
    $twilio{api_domain},
    $twilio{api_realm},
    $credentials{account_id},
    $credentials{auth_token}
);

my $response = $ua->post( $twilio{api_url}, \%text_message );

say $response->is_success
    ? "Message delivered"
    : "Error: ".$response->decoded_content;

Enter fullscreen mode Exit fullscreen mode

As this is a #beginner post, let's break this down statement by statement.

#!/usr/bin/env perl
use v5.10;
use strict;
use warnings;
Enter fullscreen mode Exit fullscreen mode

Begin with a Shebang Line. If you execute this program from a shell, this is how the shell knows which interpreter to use for the program. #!/usr/bin/env perl has replaced the long in the tooth standard #!/usr/bin/perl with good reason.

Invoking use v5.10; here allows us to use the say function.

use strict and use warnings asks Perl to warn you if you're doing something stupid. Like misspelling a variable name, or blogging at 2am.

use LWP::UserAgent;
Enter fullscreen mode Exit fullscreen mode

LWP::UserAgent can perform most actions your web browser does. You can use it to browse pages, click links, and POST forms. It can keep persistent cookies. If you wanted to, say, write a robot to cheat an online poll, look no further.

my %text_message = (
    From => '12513001300', # Me
    To   => '16198675309', # Jenny
    Body => 'Thank you for being a friend! Travel down the road and back again!'
);
Enter fullscreen mode Exit fullscreen mode

Store information about your text message into a hash. You'll want to replace the example data with your own. Jenny's had enough phone harassment.

my %credentials = (
    account_id => '____YOUR_ACCOUNT_SID_GOES_HERE____',
    auth_token => '____YOUR_AUTH_TOKEN_GOES_HERE____',
);
Enter fullscreen mode Exit fullscreen mode

You can find your Twilio account credentials in the Dashboard under Settings/General. Twilio offers test API access. You can use the test API to text yourself.

my %twilio = (
    # HTTP Authentication
    api_domain => 'api.twilio.com:443',
    api_realm  => 'Twilio API',

    # Keep your line length within 80 characters please!
    api_url    => 'https://api.twilio.com/2010-04-01/Accounts/'
                  . $credentials{account_id}
                  . '/Messages'
);
Enter fullscreen mode Exit fullscreen mode

Information you need to send a request to the Twilio API. Twilio uses Basic HTTP Authentication. Here is the DOMAIN and REALM for this authentication scheme. The Twilio API URL contains your account SID, so the full API URL is concatenated here.

my $ua = LWP::UserAgent->new;
$ua->credentials(
    $twilio{api_domain},
    $twilio{api_realm},
    $credentials{account_id},
    $credentials{auth_token}
);
Enter fullscreen mode Exit fullscreen mode

Instantiate a new instance of the LWP::UserAgent object, and set the credentials it will use for the HTTP Request to the Twilio API.

my $response = $ua->post( $twilio{api_url}, \%text_message );
Enter fullscreen mode Exit fullscreen mode

$ua makes a HTTP POST request to $twilio{api_url}. The data from %text_message are sent as form values. This operation returns a HTTP::Response Object.

say $response->is_success
    ? "Message delivered"
    : "Error: ".$response->decoded_content;

Enter fullscreen mode Exit fullscreen mode

This statement includes the ternary operator, a short-hand for an if-else block. (Side note: If you didn't know what a ternary operator was, or what it was called, and you saw this statement block in some code, how would you phrase your internet search to learn what this statement was doing? Let me know in the comments...)

$response->is_success returns true or false based on the HTTP Status Code returned by the web server.

If Twilio reports the request was successful, you see Message Delivered displayed in your terminal. If Twilio reports a problem, you will see the full response from the Twilio API displayed in your terminal.

See how easy Twilio is? Go build something...

Frankly, Twilio has made themselves so easy to use that most languages can break their use down to one-liners. You can easily deliver an SMS via the shell using curl.

If you ever meet a Twilio engineer, be sure to buy them a beer.

Are you still reading? Go build something!

Top comments (6)

Collapse
 
mrdvt92 profile image
Michael R. Davis

I wrote a Perl library on CPAN to do the HTTP/JSON stuff in the SMS::Send way.

metacpan.org/pod/SMS::Send::NANP::...

Configure /etc/SMS-Send.ini

[NANP::Twilio]
username=accountSid
password=authToken
MessagingServiceSid=String

use SMS::Send::NANP::Twilio;
my $sms = SMS::Send::NANP::Twilio->new;
my $success = $sms->send_sms(text=> 'Hello World!', to =>'+17035551212');

I use an RPM to provide /etc/SMS-Send.ini with all of our accounts so, I can change to the cheapest SMS provider in a manner of minutes.

mrdvt92

Collapse
 
philnash profile image
Phil Nash

I've been working at Twilio for almost 4 years now and I think this is the first time I've seen an example in Perl. Thanks for sharing and for explaining it so clearly!

Collapse
 
mjac profile image
Mitch Jackson

You guys are a perfect example of an API done right. Thanks for the awesome products!

Collapse
 
eqmapbox profile image
Erin Quinn

Great how-to post, love Twilio services!

Collapse
 
pbouillon profile image
Pierre Bouillon

Awesome, very clear, thank you !

Collapse
 
michaelbluejoy profile image
Michael Bluejay

Thank you for the article. I'm afraid the code in the article doesn't seem to work any more now that Twilio discontinued their old API.