Thursday, April 1, 2010

Change the desktop background using Perl script - GNOME (Fedora and Ubuntu)

Hi Guys,

These days people are opting Linux distributions like Fedora, Ubuntu, etc., for their PC's mainly to avoid malware and virus attacks. Bundling them with all kind of multimedia and entertainment tools make them more interesting and the fact that they are free make them further irresistible.

Many of the home users find them wanting. But there are small things that you would find irritating, say, something as simple as changing the desktop background. To make your life simple, here I have made a simple, sample perl script to change the desktop image. It will download pictures from National Geographic website and set it as your wallpaper. This is just a sample script, if you have the time please try it out with different website/urls. I am sure, you might as well start learning perl like I did... :-)

Note : If you want to run this script daily, just add an entry in the crontab. Crontab entry must be Xserver login user and not other users.

Here the script:-
-----------------

#!/usr/bin/perl

use WWW::Mechanize;

my $url  = "http://photography.nationalgeographic.com/photography/photo-of-the-day/";

my $mech  = WWW::Mechanize->new();
$mech->get( $url );
my @links = $mech->links();
my $download_link;

foreach my $link (@links)
{
   if  ($link->text() eq "Download Wallpaper (1600 x 1200 pixels)")
      {
       $download_link = $link->url();
       last;
      }
}

$uri = $download_link;
$date_time = localtime(time);
my @file_name = split(' ',$date_time);

#Picture will be stored in "/home/vivek/Pictures/" folder and file will be like this "Apr-1-2010.jpg"
#Change the path/folder...
 
$tempfile = "/home/vivek/Pictures/$file_name[1]-$file_name[2]-$file_name[4].jpg";

$mech->get( $uri, ':content_file' => $tempfile );


if ( -e $tempfile )
{
system("gconftool-2 --type string --set /desktop/gnome/background/picture_filename $tempfile");
}

-------------------

Important links:-

http://photography.nationalgeographic.com/photography/photo-of-the-day/
http://search.cpan.org/~petdance/WWW-Mechanize-1.60/lib/WWW/Mechanize.pm