Search code examples
perltwilio

Using Perl to send sms via Twilio


I have an extensive app in Perl that sends an occasional txt msg to me, and me only. Definitely not a spammer. I've had this app running for years on Plivo, but recently they have cut me off via 10DLC campaigns. I have not been able to convince them that this is extremely low volume and does not go to a wide-spread audience - it's actually sending notices from a weather station of particular events, like temp going below freezing, high wind, etc.

So I'm trying to change over to Twilio to see if that works out better for me.

I have tried using their sample windows command-line CURL example, and this does work, I am able to successfully send a msg.

As my program is in Perl, there's no pre-built API, so I'm having to manually craft the request packet myself. My old Plivo code forms a tidy json packet, albeit with different names.

I've changed it to the Twilio appropriate "To", "From", and "Body" parts. I get back a "400 Bad Request", "code 21604 A 'To' phone number is required".

I am providing a "To", so clearly it's just not understanding my json packet. Can anyone fill me in on exactly what Twilio request packet should look like?


Solution

  • A 30 second search on https://metacpan.org gives me this useful result:

    Install proper modules:

    cpan SMS::Send SMS::Send::Twilio
    

    Then:

    use SMS::Send;
    # Create an object. There are three required values:
    my $sender = SMS::Send->new('Twilio',
      _accountsid => 'ACb657bdcb16f06893fd127e099c070eca',
      _authtoken  => 'b857f7afe254fa86c689648447e04cff',
      _from       => '+15005550006',
    );
     
    # Send a message to me
    my $sent = $sender->send_sms(
      text => 'Messages can be up to 1600 characters',
      to   => '+31645742418',
    );
     
    # Did it send?
    if ( $sent ) {
      print "Sent test message\n";
    } else {
      print "Test message failed\n";
    }
    

    If you want to craft this request without a module, you can use HTTP::Proxy to intercept the request maybe. Should also be feasible with a POST with WWW::Mechanize or LWP.

    With shell cURL:

    curl \
        -d "Body=test" \
        -d "From=+1123456789" \
        -d "To=+1123456788" \
        -u "$twilio_account_sid:$twilio_auth_token" \
        "https://api.twilio.com/2010-04-01/Accounts/$twilio_account_sid/Messages"