Wednesday, October 29, 2008

Using Perl Against Facebook - Part II: Status Updates

This post continues from Part I - Login to Facebook

By now, we are able to login to our Facebook account, so it is time to do more things with it. Facebook lets you publish your status, a short text descsribing what you are doing any time. It has a 160-char limit, just like the Twitter thing.

To get or set the status, we only need the homepage html page. To retrieve our status we just match it against a pattern and to set the status we send a POST request with the appropriate arguments. Here is the code:

#go to the homepage
$response = $browser->get('http://www.facebook.com/home.php',@header);

#Let's now post a new status
my $newStatus = "Testing DOL Code..";
$response->content =~ /id="post_form_id" name="post_form_id" value="(.+?)"/;

my $postformid = $1;
my %post_data = ("status"=>$newStatus,"post_form_id"=>$postformid);

$response = $browser->post('http://www.facebook.com/updatestatus.php',\%post_data,@header);

##Ok! The status was posted...
##Let's now see what we have done...


$response = $browser->get('http://www.facebook.com/home.php',@header);
if($response->content =~ /<span id="chat_su_text">(.+?)<\/span>/)
{
#Here is the new status
print "My status: ",$1;
}
else
{
print "Could retrieve status...";
}


This piece of code should be used in conjuction with the previous post. It assumes we have already setup the brower and the response object and that we have already logged in to Facebook. The code first posts a new status ('Testing DOL code...') and then tests if everything was setup ok.