Thursday, October 30, 2014

Autoposting to twitter account using WWW::Mechanize module (No More Functional Just An Example For Working With WWW::Mechanize Module)

WWW::Mechanize module is used for automatic interaction with websites, this method is also termed as web scrapping, it helps a Perl program to interpret as an individual website visitor and perform many actions automatically on behalf of the individual user. 
In the following example we have used this module for automatic posting of twit/ message into a twitter account, scrapping twitter mobile website.

#!/usr/bin/perl

use WWW::Mechanize; # required module for webpage scrapping

my $twitter_username = 'provide here twitter account username'; # twitter account username
my $twitter_password = 'provide here twitter account password'; # twitter account password

my $message = 'Hello Folks!!!'; # twit to be posted in the twitter account

my $uaa = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 ( .NET CLR 3.5.30729; .NET4.0C)"; # specifying the browser agent

my $mech = WWW::Mechanize->new( agent => $uaa ); # creating an object of mechanize module 

$mech->get('https://mobile.twitter.com/session/new'); # calling the required url and fetching the webpage

$authenticihty_token = $mech->field('authenticity_token'); # fetching the authenticity token value from a hidden field named 'authenticity_token' in the fetched webpage, which is required for logging into this website

$mech->post( 'https://mobile.twitter.com/session', { authenticity_token => $authenticihty_token, username => $twitter_username, password => $twitter_password } ); # posting the required values to another url for further processing ( here it is logging into the mobile twitter website )

$mech->post( 'https://mobile.twitter.com/', { authenticity_token => $authenticihty_token, commit => 'Tweet', 'tweet[text]' => "$message" } ); # posting the twit/ message in the twitter account 

if ( $mech->success() ) # returns true if earlier mechanize posting was successful
{
 print qq{Twitter posting successful\n};
}
else
{
 print qq{Twitter posting unsuccessful\n};
}


Output:
-------
On running the Perl script from command line, it will post the specified message into the twitter account mentioned in the script.