Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Perl2SMS (for Vodafone Australia)

by hagus (Monk)
on May 25, 2002 at 12:21 UTC ( #169265=sourcecode: print w/ replies, xml ) Need Help??

Category: cgi programming
Author/Contact Info hagus
Description: This is some code I whipped up to automate the tedious process of using Vodafone.com.au's web2sms facility. Given an account on this site, you can use my script to send SMSs from the command line.

It might also serve as quick template code for anyone contemplating similar types of things. It fetches several URLs, stores cookies, handles redirects on POSTs, etc.

Required modules: LWP::UserAgent and friends, plus Crypt::SSLeay

Updated: Incensed by graff's critique, I raged through the house smashing crockery and garden gnomes. When the plaster dust had settled, I refactored the code into a nightmarish perl structure state machine. Muahahaha. (as opposed to the nightmarish if/then/else it was before).

Updated again: An exercise for the reader would be to introduce hooks that parse the HTML. At the moment if you don't successfully login, it silently fails. Hint: subclass HTML::Parse.

#!/usr/bin/perl

use warnings;
use strict;

package MyAgent;

use base 'LWP::UserAgent';

sub redirect_ok
{
    my ($self, $request) = @_;
    return 1;
}

package URLStateMachine;

use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
use HTTP::Cookies;

sub new
{
    my $class = shift;
    my $args = shift;

    my $self = { states => $args };

    $self->{ua} = new MyAgent;
    $self->{cookieJar} = new HTTP::Cookies;
    $self->{ua}->cookie_jar($self->{cookieJar});

    return bless($self, $class);
}

sub run
{
    my $self = shift;

    my @stateList = @{$self->{states}};

    foreach my $state (@stateList)
    {
        my $res;
        $self->logmsg($state->{info});
        if ($state->{method} eq 'GET')
        {
            $res = $self->{ua}->request(new HTTP::Request(GET => $stat
+e->{url}));
            $res->is_success or $self->logerr($res->status_line);
        }
        elsif ($state->{method} eq 'POST')
        {
            $res = $self->{ua}->request(POST $state->{url},
                                           $state->{args});
            $res->is_success or $self->logerr($res->status_line);
        }
    }
}

sub logerr
{
    my $self = shift;
    my $msg = shift;
    print scalar localtime(time) . " ERROR: $msg\n";
}

sub logmsg
{
    my $self = shift;
    my $msg = shift;
    print scalar localtime(time) . " INFO: $msg\n";
}

package main;

my $config = {
    username => 'blah',
    password => 'foo',
    };

unless (@ARGV == 2)
{
    print "Arguments: [phone numbers] [message]\n";
    exit 1;
}

my @stateConfig
    = (
       { name   => 'get_homepage',
         method => 'GET',
         url     => "https://www1.myvodafone.com.au",
         info   => "Getting homepage ...", },

       { name   => 'login',
         method => 'POST',
         url     => "https://www1.myvodafone.com.au/userpages",
         info   => "Logging in ...",
         args   => [ login       => $config->{username},
                     password => $config->{password},
                     TYPE       => 'login' ] },
       
       { name   => 'get_form',
         method => 'GET',
         info   => "Getting SMS page ...",
         url     => "https://www1.myvodafone.com.au/userpages/web2txt.
+fcgi"
         },
       
       { name   => 'submit_form',
         method => 'POST',
         url     => "https://www1.myvodafone.com.au/userpages/web2txt.
+fcgi",
         info   => "Submitting form ...",
         args   => [ sendmsg => 1,
                     message => $ARGV[1],
                     min      => $ARGV[0] ]
                     },
       );

my $machine = new URLStateMachine(\@stateConfig);
$machine->run;

Comment on Perl2SMS (for Vodafone Australia)
Download Code
Re: Perl2SMS (for Vodafone Australia)
by graff (Chancellor) on May 26, 2002 at 04:26 UTC
    Update: The code is very different now compared to when I first wrote this reply, so I'll just keep the parts that I think might still be relevant (and ++ the current version!)</update>

    I agree that this provides a nice case study for simplifying streamlining web interaction, but every time I see more than two levels of indentation for nested "if (okay) ... else ..." blocks, I wince a little. I think it would be more readable (as Perl code, at least) if you did it this way:

    ... my $baseURL = "http://www1.myvodafone.com.au"; my $res; logmsg("Requesting homepage ..."); $res = $ua->request(new HTTP::Request(GET=>$baseURL)); $res->is_success or giveUp($res->status_line); logmsg("Logging in..."); $res = $ua->request(POST "$baseURL/userpages", ... ); $res->is_success or giveUp($res->status_line); logmsg("Requesting SMS form..."); $res = $ua->request(new HTTP::Request(GET=>"$baseURL/userpages/web2txt +.fcgi")); $res->is_success or giveUp($res->status_line); logmsg("Submitting SMS form..."); $res = $ua->request(POST "$baseURL/userpages/web2txt.fcgi"),...); $res->is_success or giveUp($res->status_line); logmsg("Completed submission."); sub giveUp { my $msg = shift; print scalar localtime(time) . "Error: $msg\n"; exit(1); } ...

    but your newer version has nice features that many folks may appreciate more than this simple-minded approach

    There may be better idioms than what I have suggested (which was equivalent to your original version), and your revised code seems to be one such idiom.

    For example, you could now look at generalizing the process by reading the stateConfig data from a file -- it'll be fun figuring out how to get that to work with other args from the command line to fill in slots within the stateConfig data... Thanks for a very instructive update!

      ++, many thanks for the feedback!

      I think, personally, when you look at the core data of the new one (the statConfig array), it's simpler than my first effort. Everything you need to know is in that array, and it just boils down to a few lines ... when you move the package into a separate file, the main routine is just the data structure, newing up the class, and calling a single method!

      The complexity of introducing a data structure and whatnot is I guess offset by the benefits of generacity (is that a word?). And separation of functional code from data. And all that good stuff.

      Moving forward, I think I might tack a Tk interface on the front, and perhaps add HTML::Parse in there to take care of errors. Keeping it generic, of course :)

      Re: reading the data in from a file - if it got really complex I would make it XML. Since it's only a handful of GETs and POSTs, the effort of a nice config file is hard to justify.

      Also: it's using https rather than http for everything. Wouldn't want people sniffing those SMS!

      --
      Ash OS durbatulk, ash OS gimbatul,
      Ash OS thrakatulk, agh burzum-ishi krimpatul!
      Uzg-Microsoft-ishi amal fauthut burguuli.

Re: Perl2SMS (for Vodafone Australia)
by tomhukins (Curate) on Jun 05, 2002 at 15:20 UTC
    You don't mention whether you're aware of the Net::SMS::Web or WWW::SMS frameworks. Either of these frameworks might make it easier to write Perl code that uses Web-based SMS gateways.
Re: Perl2SMS (for Vodafone Australia)
by andymc (Initiate) on May 01, 2007 at 06:13 UTC
    Currently this code seems to be broken.

    I have had a go at fixing it. I can login but cannot work out how to handle the pop-up window for the actual send SMS javascript.

    Does anyone have any ideas? Hagus, you out there????

    Andy.

Back to Code Catacombs

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: sourcecode [id://169265]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (10)
As of 2014-12-19 13:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (83 votes), past polls