NAME

WWW::Myspace - Access MySpace.com profile information from Perl

VERSION

Version 0.53

SYNOPSIS

WWW::Myspace.pm provides methods to access your myspace.com account and functions automatically. It provides a simple interface for scripts to log in, access lists of friends, scan user's profiles, retreive profile data, send messages, and post comments.

use WWW::Myspace;
my $myspace = WWW::Myspace->new ($account, $password);
    OR
my $myspace = new WWW::Myspace; # Prompts for email and password
unless ( $myspace->logged_in ) { die "Login failed: " . $myspace->error }

my ( @friends ) = $myspace->get_friends();

This module is designed to help you automate and centralize redundant tasks so that you can better handle keeping in personal touch with numerous friends or fans, or coordinate fan communications among multiple band members. This module operates well within MySpace's security measures. If you're looking for a spambot, this ain't it.

WWW::Myspace works by interacting with the site through a UserAgent object, using HTTP::Request::Form to process forms. Since by nature web sites are dynamic, if you find that some interaction with the site breaks, check for a new version of this module (or if you go source diving, submit a patch). You can run "cpan -i WWW::Myspace" as a cron job or before running your scripts, if appropriate, to make sure you have the latest version.

SET OPTIONS / LOG IN

The new method takes the following options, all of which are optional. See the accessor methods below for defaults. Any option can be passed in a hash or hashref to the "new" method, and retreived or set using the appropriate accessor method below.

account_name => 'myaccount',
password => 'mypass',
cache_dir => '/path/to/dir',
cache_file => 'filename', # $cache_dir/$cache_file
auto_login => 1  # 1 or 0, default is 1.
human => 1  # Go slow.  Saves bandwidth.

OPTION ACCESSORS

These methods can be used to set/retreive the respective option's value. They're also up top here to document the option, which can be passed directly to the "new" method.

account_name

Sets or returns the account name (email address) under which you're logged in. Note that the account name is retreived from the user or from your program depending on how you called the "new" method. You'll probably only use this accessor method to get account_name.

EXAMPLE

The following would prompt the user for their login information, then print out the account name:

use WWW::Myspace;
my $myspace = new WWW::Myspace;

print $myspace->account_name;

$myspace->account_name( 'other_account@myspace.com' );
$myspace->password( 'other_accounts_password' );
$myspace->site_login;

WARNING: If you do change account_name, make sure you change password and call site_login. Changing account_name doesn't (currently) log you out, nor does it clear "password". If you change this and don't log in under the new account, it'll just have the wrong value, which will probably be ignored, but who knows.

password

Sets or returns the password you used, or will use, to log in. See the warning under "account_name" above - same applies here.

cache_dir

WWW::Myspace stores the last account/password used in a cache file for convenience if the user's entering it. Other modules store other cache data as well.

cache_dir sets or returns the directory in which we should store cache data. Defaults to $ENV{'HOME'}/.www-myspace.

If using this from a CGI script, you will need to provide the account and password in the "new" method call, or call "new" with "auto_login => 0" so cache_dir will not be used.

cache_file

Sets or returns the name of the file into which the login cache data is stored. Defaults to login_cache.

If using this from a CGI script, you will need to provide the account and password in the "new" method call, so cache_file will not be used.

auto_login

Really only useful as an option passed to the "new" method when creating a new WWW::Myspace object.

# Don't log in, just create a new object
my $myspace = new WWW::Myspace( auto_login => 0 );

Defaults to 1 for backwards compatibility.

human

When set to a true value (which is the default), adds delays to make the module act more like a human. This is both to offset "faux security" measures, and to conserve bandwidth. If you're dumb enough to try to use multiple accounts to spam users who don't want to hear what you have to say, you should turn this off because it'll make your spamming go faster.

new( $account, $password )

new( )

If called without the optional account and password, the new method looks in a user-specific preferences file in the user's home directory for the last-used account and password. It prompts for the username and password with which to log in, providing the last-used data (from the preferences file) as defaults.

Once the account and password have been retreived, the new method automatically invokes the "site_login" method and returns a new WWW::Myspace object reference. The new object already contains the content of the user's "home" page, the user's friend ID, and a UserAgent object used internally as the "browser" that is used by all methods in the WWW::Myspace class.

Myspace.pm is now a subclass of WWW::Myspace::MyBase (I couldn't resist, sorry), which basically just means you can call new in many ways:

EXAMPLES
    use WWW::Myspace;
    
    # Prompt for username and password
    my $myspace = new WWW::Myspace;
    
    # Pass just username and password
    my $myspace = new WWW::Myspace( 'my@email.com', 'mypass' );
    
    # Pass options as a hashref
    my $myspace = new WWW::Myspace( {
        username => 'my@email.com',
        password => 'mypass',
        cache_file => 'passcache',
    } );
    
    # Hash
    my $myspace = new WWW::Myspace(
        username => 'my@email.com',
        password => 'mypass',
        cache_file => 'passcache',
        auto_login => 0,
    );

    # Print my friend ID
    print $myspace->my_friend_id;
    
    # Print the contents of the home page
    print $myspace->current_page->content;
    
    # Print all my friends with a link to their profile.
    @friend_ids = $myspace->get_friends;
    foreach $id ( @friend_ids ) {
        print 'http://profile.myspace.com/index.cfm?'.
            'fuseaction=user.viewprofile&friendID='.
            ${id}."\n";
    }

    # How many friends do we have? (Note: we don't include Tom
    # because he's everybody's friend and we don't want to be
    # bugging him with comments and such).
    print @friend_ids . " friends (not incl Tom)\n";

site_login

Logs into the myspace account identified by the "account_name" and "password" options. You don't need to call this right now, because "new" does it for you. BUT I PLAN TO CHANGE THAT. You don't need to be logged in to access certain functions, so it's semi-silly to make you log in the second you call "new". Plus, it's not good practice to have "new" require stuff. Bad me.

If you call the new method with "auto_login => 0", you'll need to call this method if you want to log in.

It's also called automatically if the _check_login method finds that you've been mysteriously logged out, for example if Myspace.com were written in Cold Fusion running on Windows.

If the login gets a "you must be logged-in" page when you first try to log in, $myspace->error will be set to an error message that says to check the username and password.

Once login is successful for a given username/password combination, the object "remembers" that the username/password is valid, and if it encounters a "you must be logged-in" page, it will try up to 20 times to re-login. Clever, huh?

logout

Clears the current web browsing object and resets any login-specific internal values. Currently this drops and creates a new WWW::Mechanize object. This may change in the future to actually clicking "logout" or something.

CHECK STATUS

logged_in

Returns true if login was successful. When you call the new method of WWW::Myspace, the class logs in using the username and password you provided (or that it prompted for). It then retreives your "home" page (the one you see when you click the "Home" button on myspace.com, and checks it against an RE. If the page matches the RE, logged_in is set to a true value. Otherwise it's set to a false value.

Notes:
- This method is only set on login. If you're logged out somehow,
  this method won't tell you that (yet - I may add that later).
- The internal login method calls this method to set the value.
  You can (currently) call logged_in with a value, and it'll set
  it, but that would be stupid, and it might not work later
  anyway, so don't.

Examples:

my $myspace = new WWW::Myspace;
unless ( $myspace->logged_in ) {
   die "Login failed\n";
}

# This will try forever to log in
my $myspace;

do {
   $myspace = new WWW::Myspace( $username, $password );
} until ( $myspace->logged_in );

error

This value is set by some methods to return an error message. If there's no error, it returns a false value, so you can do this:

$myspace->get_profile( 12345 );
if ( $myspace->error ) {
    warn $myspace->error . "\n";
} else {
    # Do stuff
}

current_page

Returns a reference to an HTTP::Response object that contains the last page retreived by the WWW::Myspace object. All methods (i.e. get_page, post_comment, get_profile, etc) set this value.

EXAMPLE

The following will print the content of the user's profile page:

use WWW::Myspace;
my $myspace = new WWW::Myspace;

print $myspace->current_page->content;

mech

The internal WWW::Mechanize object. Use at your own risk: I don't promose this method will stay here or work the same in the future. The internal methods used to access Myspace are subject to change at any time, including using something different than WWW::Mechanize.

GET INFO

my_friend_id

Returns the friendID of the user you're logged in as. Croaks if you're not logged in.

EXAMPLE

print $myspace->my_friend_id;

is_band( [friend_id] )

Returns true if friend_id is a band profile. If friend_id isn't passed, returns true if the account you're logged in under is a band account. If it can't get the profile page it returns -1 and you can check $myspace->error for the reason (returns a printable message). This is used by send_friend_request to not send friend requests to people who don't accept them from bands, as myspace passively accepts the friend request without displaying an error, but doesn't add the friend request.

EXAMPLE

$myspace->is_band( $friend_id );

if ( $myspace->error ) {
    die $myspace->error . "\n";
} else {
    print "They're a band, go listen to them!\n";
}

IMPORTANT: You can NOT assume that a profile is a personal profile if is_band is false. It could be a film profile or some future type of profile. There is currently no test for a personal or film profile.

user_name

Returns the profile name of the logged in account. This is the name that shows up at the top of your profile page above your picture. This is NOT the account name.

Normally you'll only retreive the value with this method. When logging in, the internal login method calls this routine with the contents of the profile page and this method extracts the user_name from the page code. You can, if you really need to, call user_name with the contents of a page to have it extract the user_name from it. This may not be supported in the future, so it's not recommended.

friend_user_name( [friend_id] )

Returns the profile name of the friend specified by friend_id. This is the name that shows up at the top of their profile page above their picture.

If no friend_id is specified, this method scans the current page so you can do:

$myspace->get_profile( $friend_id );
print $myspace->friend_user_name;

(Note, DON'T go using this to sign comments because most users use funky names and it'll just look cheesy. If you really want to personalize things, write a table mapping friend IDs to first names - you'll have to enter them yourself).

friend_url( [friend_id] )

Returns the custom URL of friend_id's profile page. If they haven't specified one, it returns an empty string.

Example:

foreach my $friend_id ( $myspace->get_friends ) {
    my $url = $myspace->friend_url( $friend_id );
    if ( $url ) {
        print 'Friend's custom URL: http://www.myspace.com/' .
        $myspace->friend_url( $friend_id );
    } else {
        print 'Friend doesn't have a custom URL. Use: '.
        'http://www.myspace.com/' . $friend_id;
    }
}

If no friend_id is specified, this method scans the current page so you can do:

$myspace->get_profile( $friend_id );
print $myspace->friend_url;

friend_id ( friend_url )

Returns the friend_id corresponding to a given custom URL. (This is basically the reverse of friend_url).

# Print the friendID of Amber G: myspace.com/iamamberg
print $myspace->friend_id("iamamberg");

> 37033247

If no friend_url is specified, this method scans the current page so you can do:

$myspace->get_profile( $friend_id );
print $myspace->friend_url;

friend_count

Returns the logged in user's friend count as displayed on the profile page ("You have NN friends").

Note that due to one of WWW::Myspace's many bugs, this count may not be equal to the count of friends returned by get_friends.

Like the user_name method, friend_count is called by the internal login method with the contents of the user's profile page, from which it extracts the friend count using a regexp on the "You have NN friends" string. If you need to, you can do so also, but again this might not be supported in the future so do so at your own risk.

last_login( [friend_id] )

Returns the last login date from the specified profile in Perl "time" format.

If no friend_id is specified, this method scans the current page so you can do:

$myspace->get_profile( $friend_id );
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
   localtime( $myspace->last_login );

# or

if ( $myspace->last_login( $friend_id ) < today - 3600 * 60 ) {
   print "They haven't logged in in 60 days!"
}

get_profile( $friend_id )

Gets the profile identified by $friend_id.

Returns a reference to a HTTP::Response object that contains the profile page for $friend_id.

The following displays the HTML source code of the friend's
profile identified by "$friend_id":

my $res = $myspace->get_profile( $friend_id );

print $res->content;

get_comments( $friend_id )

Returns a list of hashrefs, like "inbox", of all comments left for the profile indicated by $friend_id.

Each list element contains:
{ 
  sender => $friend_id, # friendID of the person who sent the comment
  date => $date_time,   # As formatted on MySpace
  comment => $string    # HTML of the comment.
}

Comments are returned in the order in which they appear on myspace (currently most recent first).

Dies if called when not logged in.

FIND PEOPLE

cool_new_people( $country_code )

This method provides you with a list of "cool new people". Currently Myspace saves the "cool new people" data to a JavaScript file which is named something like this:

http://viewmorepics.myspace.com/js/coolNewPeople_us.js

Since these files are named using country codes, you'll need to provide the ISO 3166-1 two letter code country code for the list you'd like to get. For example,

$myspace->cool_new_people( 'US' )

When called in a list context, this function returns the friend ids of the cool folks:

my @friend_ids = $myspace->cool_new_people( 'US' );

If you treat the return value as a hash reference, you'll get a hash keyed on friend ids. The values consist of hash references containing the urls of the friend thumbnails (thumb_url) as well as their display names (friend_user_name). There will probably be about 200 keys returned in the hash.

my $cool = $myspace->cool_new_people('US');
my %cool_new_people = %{$cool};

%cool_new_people = {

...

    'friend_id' => {
        'thumb_url'         => 'url_to_jpg_here',
        'friend_user_name'  => 'friend display name here'
    },

...

}

So far, we know of 4 country-specific cool new people lists: AU, CA, UK/GB and US Submitting any of these values to the function should return valid friend ids. If you want to check for other countries for which cool people lists may exist, you can do something like this:

use Locale::SubCountry;

my $world         = new Locale::SubCountry::World;
my %countries     = $world->code_full_name_hash();  
my @country_codes = sort keys %countries;

foreach my $country_code ( @country_codes ) {
    my %cool_people = $myspace->cool_new_people($country_code);
    if (%cool_people) {
        print "$country_code $countries{$country_code} has cool folks\n";
    }
    else {
       print "****** $country_code\n";
    }
}
                       

get_friends( %options )

Returns, as a list of friendIDs, all of your friends. It does not include Tom, because he's everybody's friend and when you're debugging your band central CGI page it's probably best to limit your mistakes to actual friends.

# Simplest form - gets your friends.
@friends = $myspace->get_friends;

# Advanced form
@friends = $myspace->(
   source => 'group',  # 'profile', 'group', 'inbox', or ''
   id => $group_id,    # friendID or groupID as appropriate
   end_page => $end_page,  # Stop on this page. All pages if not included.
   max_count => 300,   # Number of friends to return
   exclude => \%exclude_hash,  # Don't include these friendIDs
);

Accepts the following options:

source:    "profile", "inbox", or "group"
           If not specified, gets your friends.
           profile: Get friends from the profile specified by the "id" option.
           inbox: Get friends from your inbox (see the
                 "friends_who_emailed" method below)
           group: Get the friends from the group specified by the "id" option.
id:        The friendID or groupID (depending on "source").
           "id" is only needed for "profile" or "group".
           (See the "friends_in_group" method for more info).
end_page:  Stop on this page.
           $myspace->get_friends( end_page => 5 );
           If not specified, gets all pages.
           See note below about interaction with other options.
max_count: Return this many friendIDs.
           $myspace->get_friends( max_count => 300 );
           Stops searching and returns when max_count is reached.
           (See note below).
exclude:   Exclude these friends, passed as a HASHREF
           containing friendIDs as its keys.
           If the "value" side of the pair is a true value,
           the friendID will be excluded.
           $myspace->get_friends( exclude => { 12345 => 1 };
           $myspace->get_friends( exclude => \%exclude_friends );
           
           You can also pass a reference to an array for convenience,
           but it will be turned into a hash, so it's a bit slower.
           $myspace->get_friends( exclude => [ 12345, 123456 ] );
           $myspace->get_friends( exclude => \@exclude_list );

Combine max_count and exclude for handy functionality: # This gets 300 friends, excluding those in the %exclude_friends # hash. $myspace->get_friends( source => 'group', id => $group_id, exclude => \%exclude_friends, max_count => 300 );

If you specify max_count and end_page, get_friends will stop when it hits the earliest condition that matches.

max_count may return up to 40 more friends than you specify. This is because it reads each friend page, and returns when it's gathered max_count or more friends (and there are 40 per page).

As of version 0.37, get_friends is context sensitive and returns additional information about each friend if called in a hashref context. Currently the only information is the page number on which the friend was found. This is handy if, say, you have a lot of friends and you want to add one to your top 8 but you don't know what page they're on.

# Find a friend lost in your friends list
$lost_friend=12345;
$friends = $myspace->get_friends;
print "Found friend $lost_friend on page " .
   $friends->{"$lost_friend"}->{page_no} . "!\n";

Myspace trivia: The friends on friends lists are sorted by friendID.

Croaks if called with no arguments (i.e. to get your friends) and you're not logged in.

friends_from_profile( %options )

Returns a list of the friends of the profile(s) specified by the "id" option. id can be a friendID or a reference to an array of friendIDs. If passed a list of friend IDs, scans each profile and returns a sorted, unique list of friendIDs. Yes, that means if you pass 5 friendIDs and they have friends in common, you'll only get each friendID once. You're welcome.

Also accepts the same options as the get_friends method (end_page, max_count, etc).

Examples:

# Band 12345 and 54366 sound like us, get their friends list
@similar_bands_friends=
  $myspace->friends_from_profile( id => [ 12345, 54366 ] );

# Get the first 500 friends from profile 12345
@friends = $myspace->friends_from_profile(
               id => 12345,
               max_count => 500
           );

# A further example:
# Before you do anything with these ids, make sure you don't already
# have them as friends (uses the "exclude" option in get_friends,
# which is very efficient as friends are excluded as they're read
# instead of afterwards):
my @current_friends = $myspace->get_friends;
die $self->error if $self->error;
my @potential_friends = $myspace->friends_from_profile(
   id => [ 12345, 54366 ],
   exclude => \@current_friends
);

friends_in_group( group_id );

Convenience method: Same as calling "get_friends( source => 'group', id => $group_id )".

Returns a list of the friend IDs of all people in the group identified by group_id. Tom is disincluded as in get_friends (because the same routine is used to get the friendIDs).

Example:

my @hilary_fans = $myspace->friends_in_group( 100011592 );

@hilary_fans now contains the friendID of everyone in the HIlary
Duff Fan Club group (group ID 100011592 ).

To get the group ID, go to the group page in WWW::Myspace and look at the URL: http://groups.myspace.com/index.cfm?fuseaction=groups.viewMembers&GroupID=100011592&adTopicId=&page=3

The group ID is the number after "GroupID=".

friends_who_emailed

Convenience method, same as calling "get_friends( source => 'inbox' )".

Returns, as a list of friend IDs, all friends with messages in your inbox (mail). Note that this only tells you who you have mail from, not how many messages, nor does it contain any method to link to those messages. This is primarily designed to aid in auto-responding programs that want to not contact (comment or email) people who have sent messages so someone can attend to them personally. This routine also disincludes Tom, mainly because it uses the same routine as "get_friends". Croaks if you're not logged in.

@friends = $myspace->friends_who_emailed;

search_music

Search for bands using the search music form.

Takes a hashref containing field => value pairs that are passed directly to submit_form to set the search criteria.

http://musicsearch.myspace.com/index.cfm?fuseaction=music.search

The easiest way I've found to get your values is to fill them in on the search form, click "Update", then look at the page source. Scroll to the botton where "PageForm" is and you'll see the values you selected. Put the pertinent ones (i.e. things you changed) into your script. Note that the field *names* are different, so just take the values, and use the names as described below.

Any value the form can take (present or future) can be passed, so in theory you could write a CGI front-end also that just had the form, posted the values to itself, then used those values to call this method (i.e. do what I suggested above automatically).

Here are the currently available form labels/values (looking at the form helps):

genreID: See the form for values

search_term:
   0: Band Name
   1: Band Bio
   2: Band Members
   3: Influences
   4: Sounds like

keywords: text field. Use it if you're searching by band name, etc.

Country: Labeled "Location" in the form. See the form source for values.

localType: The radio buttons. Set to:
  countryState: To search by Country / State
  distanceZip: To search by distance and zip code.

if localType is "countryState", set this:
  state: State code (like the post office uses, thankfully. See form code
         if you have any questions).

If localType is "distanceZip", set these:
  zip: The 5-digit zip code.
  distance: Distance from zip code [0|5|10|20|50|100|500]. 0="Any" and is the
            default.

OrderBy: [ 5 = Plays | 4 = Friends |3 = New | 2 = Alphabetical ]
         Default is 2.

IMPORTANT: Results are currently sorted by friendID regardless of the OrderBy setting.

For those who care about details, here's how the Search Music page works:

There are three forms on the page, the generic "search" form in the nav bar, a second form called "myForm" that is the user-modified update form, and a third form called "PageForm" that is actually used to pass the values. PageForm is updated with the values after "update" is clicked in myForm. Clicking "Next" just sets (using JavaScript in Myspace) the page value in PageForm and submits PageForm. Oddly enough, PageForm ends up being a "GET", so you could theoretically just loop through using URLs. But we don't, we fill in the form like a browser would.

CONTACT PEOPLE

These methods interact with other users.

post_comment( $friend_id, $message )

Post $message as a comment for the friend identified by $friend_id. The routine confirms success or failure by reading the resulting page. It returns a status string as follows:

P   =>  'Passed! Verification string received.'
PA  =>  'Passed, requires approval.'
FF  =>  'Failed, you must be someone\'s friend to post a comment about them.'
FN  =>  'Failed, network error (couldn\'t get the page, etc).'
FC  =>  'Failed, CAPTCHA response requested.'
FI  =>  'Failed, Invalid friendID.',
F   =>  'Failed, verification string not found on page after posting.'

Warning: It is possible for the status code to return a false "Failed" if the form post is successful but the resulting page fails to load.

If called in scalar context, it returns the status code. If called in list context, returns the status code and the description.

EXAMPLE: use WWW::Myspace; my $myspace = new WWW::Myspace;

foreach $id ( $myspace->friends_who_emailed ) {
    $status = $myspace->post_comment( $id, "Thanks for the message!" )
}

# Get a printable status (and print it)
( $status, $desc ) = $myspace->post_comment(
    $id, "Thanks for being my friend!"
);
print "Status of post: $desc\n";

post_comment loads $friend_id's profile page, clicks the "Add Comment" link, fills in, posts, and confirms a comment. If $friend_id is a non-true value (i.e. "0" or ''), post_comment will search for and click an "Add Comment" link on the last page loaded. This lets you do this without double-loading the profile page wasting time and bandwidth:

$myspace->get_profile( $friend_id );
if ( $myspace->current_page->content =~ /something special/ ) {
    $myspace->post_comment( 0, "Your page is special!" );
}

If called when you're not logged in, post_comment croaks to make you look stupid.

See also the WWW::Myspace::Comment module that installs with the distribution.

captcha

If post_comment returns "FC", the "captcha" method will return the URL to the CAPTCHA image that contains the text that the user must enter to post the comment.

Psuedo-code example of how you can use this in a CGI script:

my $response = $myspace->post_comment( 12345, 'This is a message' );
if ( $response eq 'FC' ) {
   # Get and display the image
   print '<form>\n'.
     "<img src='" . $myspace->captcha . "'>\n".
     '<input type=text name=\'CAPTCHAResponse\'>' .
     '<input type=submit>' .
     '</form>';
}

# Post the comment
$myspace->post_comment( 12345, 'This is a message', $captcha_response );

(Use in a CGI script is currently problematic since you'll lose the
Myspace object. I'll try to write a better example later. You could
try doing a YAML Dump and Load of the $myspace object...)

comment_friends( $message )

comment_friends( $message, { 'ignore_dup' => 1 } )

This convenience method sends the message in $message to all of your friends. (Since you can only comment friends, it sends the comment to everyone you can).

By default it will scan the user's profile page for a previous comment (by searching for your profile URL on the page, which also detects you if you're in their top 8 or otherwise linked to from their page).

If called in the second form, it forgoes this duplicate checking (ignores duplicates), and posts anyway.

Note that you'll probably want to use the WWW::Myspace::Comment module as if the process is interrupted (which is likely), this routine doesn't offer a way to recover. The WWW::Myspace::Comment module logs where comments have been left, scans for previous comments we've left on the user's page, and can stop after a specified number of posts to avoid triggering security measures. It can also be re-run without leaving duplicate comments.

Of course, if you just want to whip off a quick comment to a few (less than 50) friends, this method's for you.

EXAMPLE: A simple script to leave a comment saying "Merry Christmas" to everyone on your friends list:

use WWW::Myspace;
my $myspace = new WWW::Myspace;
$myspace->comment_friends( "Merry Christmas!" );

already_commented

Returns true if there is a link to our profile on "$friend_id"'s page. (If we've left a comment, there'll be a link).

Note that if you're friends with this person and they have another link to your profile on their page, this will return true, even though you may not have left a comment.

EXAMPLE

my WWW::Myspace;
my $myspace = new WWW::Myspace;

foreach $friend_id ( $myspace->get_friends ) {
    unless ( $myspace->already_commented( $friend_id ) ) {
      $myspace->post_comment(
          $friend_id,
          "Hi, I haven't commented you before!"
      )
    }
}

already_commented croaks if called when you're not logged in.

inbox

Returns a reference to an array of hash references that contain data about the messages in your Myspace message inbox. The hashes contain:

sender (friendID)
status (Read, Unread, Sent, Replied)
message_id (The unique ID of the message)
subject (The subject of the message)

The messages are returned IN ORDER with the newest first to oldest last (that is, the same order in which they'd appear if you were looking through your inbox).

I'm sure reading that first line made you as dizzy as it made me typing it. I think this says it all much more clearly:

EXAMPLE

# This script displays the contents of your inbox.
use WWW::Myspace;

$myspace = new WWW::Myspace;

print "Getting inbox...\n";
my $messages = $myspace->inbox;

# Display data for each message 
foreach $message ( @{$messages} ) {
  print "Sender: " . $message->{sender} . "\n";
  print "Status: " . $message->{status} . "\n";
  print "messageID: " . $message->{message_id} . "\n";
  print "Subject: " . $message->{subject} . "\n\n";
}

(This script is in the sample_scripts directory, named "get_inbox").

"inbox" croaks if called when you're not logged in.

read_message( message_id )

Returns a hashref containing the message identified by message_id.

my $message_ref = $myspace->read_message( 123456 );

print 'From: ' . $message_ref->{'from'} . .'\n' . # Friend ID of sender
      'Date: ' . $message_ref->{'date'} . .'\n' . # Date (as formatted on Myspace)
      'Subject: ' . $message_ref->{'subject'} .'\n' .
      'Body: ' . $message_ref->{'body'} . '\n';   # Message body

Croaks if you're not logged in.

reply_message( $message_id, $reply_message )

Warning: This is a new, un-tested method. If you're reading this, it means I had to release a new version for some reason before I got to complete the testing and documentation of this method. It "should" work fine. Let me know if it does or not.

Reply to message $message_id using the text in the string $reply_message.

Returns a status code:

 P: Posted. Verified by HTTP response code and reading a regexp
   from the resulting page saying the message was sent.
FC: Failed. A CAPTCHA response was requested.
FF: Failed. The person's profile is set to private. You must
    be their friend to message them.
FA: Failed. The person has set their status to "away".
FE: Failed. The account has exceeded its daily usage.
FN: Failed. The POST returned an unsuccessful HTTP response code.
F:  Failed. Post went through, but we didn't see the regexp on the
   resulting page (message may or may not have been sent).


Example:
my $status = $myspace->reply_message( 1234567, "Thanks for emailing me!" );

If you're not logged in? Croaks.

send_message( $friend_id, $subject, $message, $add_friend_button )

send_message( %options )

Options are friend_id, subject, message, atf.

Example:
$status = $myspace->send_message(
    friend_id => 12345,
    subject => 'Hi there',
    message => 'This is the bestest message ever!',
    atf => 0,
    skip_re => 'i hate everyone', # Skip negative people
);

The %options hash is the "correct" method of passing arguments as of version 0.53. The parameter based method is here for backwards-compatibility.

send_message sends a message to the user identified by "friend_id". If "atf" is a true value, HTML code for a "View My Profile" link will be added at the end of the message. (This was an Add To Friends button until Myspace started munging that code). If "skip_re" is defined, friend_id's profile will be matched against the RE. Whitespace will be compressed and the match will NOT be case-sensitive.

So you can do this:
skip_re => 'i hate everyone!* ?(<br>)?'

And it will match:
I Hate EVERYONE!!!!
I hate everyone<br>
I Hate EvEryone!!! <BR>
etc.

If "friend_id" is an untrue value (i.e. 0 or ''), send_message will look for a Send Message button (identified by a "fuseaction=mail.message" URL if you're curious) on the current page. This lets you do this efficiently:

# Send a message only if the profile has "fancy regex" on their page
$myspace->get_profile( $friend_id );
if ( $myspace->current_page =~ /fancy regex/ ) {
   $myspace->send_message(
       subject => "Hello",
       message => "I'm messaging you"
   );
}

$status = $myspace->send_message(
    friend_id => 6221,
    subject => 'Hi Tom!',
    message => 'Just saying hi!',
    atf => 0
);

if ( $status eq "P" ) { print "Sent!\n" } else { print "Oops\n" }

Returns a status code:

P   =>  Passed! Verification string received.
FF  =>  Failed, profile set to private. You must be their
        friend to message them.
FN  =>  Failed, network error (couldn't get the page, etc).
FA  =>  Failed, this person's status is set to "away".
FS  =>  Failed, skipped. Profile doesn't match RE.
FE  =>  Failed, you have exceeded your daily usage.
FC  =>  Failed, CAPTCHA response requested.
FI  =>  Failed, Invalid friend ID.
F   =>  Failed, verification string not found on page after posting.

If called in list context, returns the status code and text description.

( $status, $desc ) = $myspace->send_message( $friend_id, $subject, $message );
print $desc . "\n";

See also WWW::Myspace::Message, which installs along with the distribution.

(Croaks if called when you're not logged in).

delete_message( @message_ids )

Deletes the message(s) identified by @message_ids. Takes a list of messageIDs or of hashrefs with a message_id subcomponent (such as one gets from the "inbox" method). Croaks if called when not logged in.

Deletes all messages in a single post. Returns true if it worked, false if not, and sets the "error" method to the error encountered.

Example:

# Delete message 12345
$myspace->delete_message( 12345 );

# File myspace mail where it belongs.
$all_messages = $myspace->inbox;

$myspace->delete_message( @{ $messages } );     

approve_friend_requests( [ "message" ] )

Looks for any new friend requests and approves them. Returns a list of friendIDs that were approved. If "message" is given, it will be posted as a comment to the new friends. If called when you're not logged in, approve_friend_requests will croak.

If approve_friend_requests runs into a CAPTCHA response when posting comments, it will set $myspace->captcha to the URL of the CAPTCHA image. If no CAPTCHA was encountered, $myspace->captcha will be 0. So you can say:

if ( $myspace->captcha ) { print "oh no!\n" }

approve_friend_requests will approve all friends whether or not it can comment them as it approves first, then comments the list of approved friends.

EXAMPLES

 # Approve any friend requests
 @friends_added = $myspace->approve_friend_requests;

 # Print the number of friends added and their friend IDs.
 print "Added " . @friends_added . " friends: @friends_added.";

 # Approve new frieds and leave them a thank you comment.
 @friends_added = $myspace->approve_friend_requests(
   "Thanks for adding me!\n\n- Your nww friend" );

Run it as a cron job. :)

Note that "\n" is properly handled if you pass it literally also (i.e. from the command line). That is if you write this "approve_friends" script:

#!/usr/bin/perl -w
# usage: approve_friends [ "message" ]

use WWW::Myspace;
my $myspace = new WWW::Myspace;

$myspace->approve_friend_requests( @ARGV );

And run it as:

approve_friends "Thanks for adding me\!\!\n\n- Me"

You'll get newlines and not "\n" in the message. There, I even gave you your script.

send_friend_request( $friend_id )

IMPORTANT: THIS METHOD'S BEHAVIOR HAS CHANGED SINCE VERSION 0.25!

Sorry, I hate to break backwards-compatibility, but to keep this method in line with the rest, I had to. The changes are: 1) It takes only one friend, it will DIE if you give it more (mainly to let you know that #2 has changed so your scripts don't think they're succeeding when they're not). 2) It no longer returns pass/fail, it returns a status code like post_comment.

Send a friend request to the friend identified by $friend_id. Croaks if not logged in.

This is the same as going to their profile page and clicking the "add as friend" button and confirming that you want to add them.

Returns a status code and a human-readable error message:

FF: Failed, this person is already your friend.
FN: Failed, network error (couldn't get the page, etc).
FP: Failed, you already have a pending friend request for this person
FC: Failed, CAPTCHA response requested.
P:  Passed! Verification string received.
F: Failed, verification string not found on page after posting.

After send_friend_request posts a friend request, it searches for various Regular Expressions on the resulting page and sets the status code accordingly. The "F" response is of particular interest because it means that the request went through fine, but none of the known failure messages were received, but the verification message wasn't seen either. This means it -might- have gone through, but probably not. Of course, worst case here is you try again.

EXAMPLES

# Send a friend request and get the response
my $status = $myspace->send_friend_request( 12345 );

# Send a friend request and print the result
my ( $status, $desc ) = $myspace->send_friend_request( 12345 );
print "Received code $status: $desc\n";

# Send a friend request and check for some status responses.
my $status = $myspace->send_friend_request( 12345 );
if ( $status =~ /^P/ ) {
   print "Friend request sent\n";
} else {
   if ( $status eq 'FF' ) {
       print "This person is already your friend\n";
   } elsif ( $status eq 'FC' ) {
       print "Received CAPTCHA image request\n";
   }
}

# Send a bunch of friend requests
my @posted = ();
my @failed = ();
foreach my $friend ( @friends ) {
  print "Posting to $friend: ";
  my $status = $myspace->send_friend_request( $friend )
  
  if ( $status =~ /^P/ ) {
      print "Succeeded\n";
      push ( @posted, $friend );
  } else {
      print "Failed with code $status\n";
      push ( @failed, $friend );
  }
  
  # Stop if we got a CAPTCHA request.
  last if $status eq 'FC';
}
# Do what you want with @posted and @failed.

Also see the WWW::Myspace::FriendAdder module, which adds multiple friends and lets you enter CAPTCHA codes.

send_friend_requests( @friend_ids )

Send friend requests to multiple friends. Stops if it hits a CAPTCHA request. Doesn't currently give any indication of which requests succeeded or failed. Use the code example above for that. Croaks if you're not logged in.

add_to_friends

Convenience method - same as send_friend_request. This method's here because the button on Myspace's site that the method emulates is usually labeled "Add to Friends".

add_as_friend

Convenience method - same as send_friend_request. This method's here Solely for backwards compatibility. Use add_to_friends or send_friend_request in new code.

delete_friend( @friend_ids )

Deletes the list of friend_ids passed from your list of friends.

$myspace->delete_friend( 12345, 151133 );

Returns true if it posted ok, false if it didn't. Croaks if you're not logged in.

CORE INTERNAL METHODS

These are methods used internally to maintain or handle basic stuff (page retreival, error handling, cache file handling, etc) that you probably won't need to use (and probably shouldn't use unless you're submitting a code patch :).

get_page( $url, [ $regexp ] )

get_page returns a referece to a HTTP::Response object that contains the web page specified by $url.

Use this method if you need to get a page that's not available via some other method. You could include the URL to a picture page for example then search that page for friendIDs using get_friends_on_page.

get_page will try up to 20 times until it gets the page, with a 2-second delay between attempts. It checks for invalid HTTP response codes, and known Myspace error pages. If called with the optional regexp, it will consider the page an error unless the page content matches the regexp. This is designed to get past network problems and such.

EXAMPLE

The following displays the HTML source of MySpace.com's home
page.
my $res=get_page( "http://www.myspace.com/" );

print $res->content;

_cache_page( $url, $res )

Stores $res in a cache.

_read_cache( $url )

Check the cache for this page.

_clean_cache

Cleans any non-"fresh" page from the cache.

_check_login

Checks for "You must be logged in to do that". If found, tries to log in again and returns 0, otherwise returns 1.

submit_form( $url, $form_no, $button, $fields_ref, [ $regexp1 ], [ $regexp2 ] )

This format is being deprecated. Please use the format below if you use this method (which you shouldn't need unless you're writing more methods). Be aware that I might make this method private at some point.

submit_form( $options_hashref )

Valid options:
$myspace->submit_form( {
   page => "http://some.url.org/formpage.html",
   form_no => 1,
   form_name => "myform",  # Use this OR form_no...
   button => "mybutton",
   no_click => 0,  # 0 or 1.
   fields_ref => { field => 'value', field2 => 'value' },
   re1 => 'something unique.?about this[ \t\n]+page',
   re2 => 'something unique about the submitted page',
   action => 'http://some.url.org/newpostpage.cgi', # Only needed in weird occasions
} );

This powerful little method reads the web page specified by "page", finds the form specified by "form_no" or "form_name", fills in the values specified in "fields_ref", and clicks the button named "button".

You may or may not need this method - it's used internally by any method that needs to fill in and post a form. I made it public just in case you need to fill in and post a form that's not handled by another method (in which case, see CONTRIBUTING below :).

"page" can either be a text string that is a URL or a reference to an HTTP::Response object that contains the source of the page that contains the form. If it is an empty string or not specified, the current page ( $myspace->current_page ) is used.

"form_no" is used to numerically identify the form on the page. It's a simple counter starting from 0. If there are 3 forms on the page and you want to fill in and submit the second form, set "form_no => 1". For the first form, use "form_no => 0".

"form_name" is used to indentify the form by name. In actuality, submit_form simply uses "form_name" to iterate through the forms and sets "form_no" for you.

"button" is the name of the button to submit. This will frequently be "submit", but if they've named the button something clever like "Submit22" (as MySpace did in their login form), then you may have to use that. If no button is specified (either by button => '' or by not specifying button at all), the first button on the form is clicked.

If "no_click" is set to 1, the form willl be submitted without clicking any button. This is used to simulate the JavaScript form submits Myspace does on the browse pages.

"fields_ref" is a reference to a hash that contains field names and values you want to fill in on the form.

"re1" is an optional Regular Expression that will be used to make sure the proper form page has been loaded. The page content will be matched to the RE, and will be treated as an error page and retried until it matches. See get_page for more info.

"re2" is an optional RE that will me used to make sure that the post was successful. USE THIS CAREFULLY! If your RE breaks, you could end up repeatedly posting a form. This is used by post_comemnts to make sure that the Verify Comment page is actually shown.

"action" is the post action for the form, as in:

<form action="http://www.mysite.com/process.cgi">

This is here because Myspace likes to do weird things like reset form actions with Javascript then post them without clicking form buttons.

EXAMPLE

This is how post_comment actually posts the comment:

# Submit the comment to $friend_id's page
$self->submit_form( "${VIEW_COMMENT_FORM}${friend_id}", 1, "submit",
                    { 'f_comments' => "$message" }, '', 'f_comments'
                );

# Confirm it
$self->submit_form( "", 1, "submit", {} );

_add_to_form

Internal method to add a hidden field to a form. HTML::Form thinks we don't want to change hidden fields, and if a hidden field has no value, it won't even create an input object for it. If that's way over your head don't worry, it just means we're fixing things with this method, ad submit_form will call this method for you if you pass it a field that doesn't show up on the form.

Returns a form object that is the old form with the new field in it.

# Add field $fieldname to form $form (a HTML::Form object) and
# set it's value to $value.
$self->_add_to_form( $form, $fieldname, $value )

get_friends_on_page( $friends_page );

This routine takes the SOURCE CODE of an HTML page and returns a list of friendIDs for which there are profile links on the page. This routine is used internally by "get_friends" to scan each of the user's "View my friends" pages.

Notes: - It does not return our friendID. - friendIDs are filtered so they are unique (i.e. no duplicates). - We filter out 6221, Tom's ID.

EXAMPLE:

List the friendIDs mentioned on Tom's profile:

use WWW::Myspace;
my $myspace = new WWW::Myspace;

$res = $myspace->get_profile( 6221 );

@friends = $myspace->get_friends_on_page( $res->content );
print "These people have left comments or have links on Tom's page:\n";
foreach $id ( @friends ) {
    print "$id\n";
}

remove_cache

Remove the login cache file. Call this after creating the object if you don't want the login data stored:

my $myspace = new WWW::Myspace( qw( myaccount, mypassword ) );
$myspace->remove_cache;

make_cache_dir

Creates the cache directory in cache_dir. Only creates the top-level directory, croaks if it can't create it.

$myspace->cache_dir("/path/to/dir");
$myspace->make_cache_dir;

This function mainly exists for the internal login method to use, and for related sub-modules that store their cache files by default in WWW:Myspace's cache directory.

_next_button

Takes the source code of a page, or nothing. If nothing is passed, uses $self->current_page->content.

Returns true if there is a next button on the page. This is so we can say:

last unless ( $self->_next_button( $page_source ) );

or:

while ( $self->_next_button ) { do stuff }
or
while ( $self->_next_button ) { do stuff and click next }

One of these days I'm going write a "stuff" subroutine so I can actually type that.

EXAMPLES

_previous_button

As you might guess, returns true if there's a "Previous" link on the page. This is used to sanity-check functions like get_friends. If there isn't a "Next" button, this method can be used to make sure there is a "Previous" button.

# Exit the loop if we're on the last page
last unless (
  $self->_next_button( $page_source ) &&
  $self->_previous_button( $page_source )
);

IN PROGRESS

Methods that aren't quite working yet.

browse

XXX - NOT YET FUNCTIONAL

XXX - More debugging needs to be done to ensure accurate results, and tests need to be added to the test suite for it.

And now back to your normal docs:

Call browse with a hashref of your search criteria and it returns a list of friendIDs that match your criteria.

my @friends = $myspace->browse( {
                  'zipCode' => '91000',
                  'zipRadius' => '20',
                  'Gender' => 'genderWomen', # Pick one of these
                  'Gender' => 'genderMen',
                  'Gender' => 'genderBoth'
                } );

I'm not sure how I'm going to make the criteria passing easier. I'm also concerned about your script breaking if they change the browse form variable names. So maybe I'll add a mapping later.

For now, you have to look at the code for the browse page:

http://browseusers.myspace.com/browse/Browse.aspx

Switch to Advanced more and get the form variables and possible values from there.

Note that depending on any defaults is dangerous, as this is a strange form indeed.

_browse_next( $page )

The browse form's Next button calls a JavaScript function that sets "action" and "page" in the browse form and "clicks" submit. So we do the same here. Called by browse to simulate clicking "next".

_browse_action( $function_name )

Gets the action set by the specificied function on the Browse page.

AUTHOR

Grant Grueninger, <grantg at cpan.org>

Thanks to:

Tom Kerswill (http://tomkerswill.co.uk) for the friend_url method, which also inspired the friend_user_name method.

Olaf Alders (http://www.wundersolutions.com) for the human-readable status codes in send_friend request, for the excellent sample code which provides a workaround for CAPTCHA responses, and for the friends_from_profile idea.

KNOWN ISSUES

-

delete_friend will probably only delete the first friendID passed.

-

Some myspace error pages are not accounted for, such as their new Server Application error page. If you know enough about web development to identify an error page that would return a successful HTTP response code (i.e. returns 200 OK), but then displays an error message, please keep an eye out for such pages. If you get such an error message page, PLEASE EMAIL ME (see BUGS below) the page content so I can account for it.

-

post_comment dies if it is told to post to a friendID that is not a friend of the logged-in user. (MySpace displays an error instead of a form). (probably fixed, 0.52).

-

If the text used to verify that the profile page has been loaded changes in the future, get_profile and post_comments will report that the page hasn't been loaded when in fact it has.

-

Something (probably UserAgent getting bad cookie data) is generating the following warnings when logging in: Day too big - 2238936 > 24855 Sec too big - 2238936 > 11647 Day too big - 2238936 > 24855 Sec too big - 2238936 > 11647

These are annoying but don't seem to affect the module.

-

site_login will give up after the first try when initialy logging in if it encounters the "You must be logged-in" page. This is a "feature" used to check for invalid username/password, but should probably check a couple times to make sure it isn't a Myspace problem.

TODO

Have 'approve_friends' method check GUIDS after first submit to make sure the current page of GUIDS doesn't contain any duplicates. This is to prevent a possible infinite loop that could occur if the submission of the friend requests fails, and also to signal a warning if myspace changes in a way that breaks the method.

Add checks to all methods to self-diagnose to detect changes in myspace site that break this module.

Add methods to FriendAdder.pm to: 1-exlude friends, 2-exclude pending friends, 3-cache like Comment.pm, 4-exclude friends in the "messaged" cache file.

get_friends needs to throw an error, or at least set error, if it can't return the full list of friends (i.e. if either of the "warn" statements are triggered)

Review and possibly rework code to properly use (, abuse, or replace) WWW::Mechanize.

See: - delete_friends - "proper" forced handling of a passed form.

Add tests for get_comments.

CONTRIBUTING

If you would like to contribute to this module, you can email me and/or post patches at the RT bug links below. There are many methods that could be added to this module (profile editing, for example). If you find yourself using the "submit_form" method, it probably means you should write whatever you're editing into a method and post it on RT.

See the TODO section above for starters.

BUGS

Please report any bugs or feature requests, or send any patches, to bug-www-myspace at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=WWW-Myspace. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

IF YOU USE A MAIL SERVICE (or program) WITH JUNK MAIL FILTERING, especially HOTMAIL or YAHOO, add the bug reporting email address above to your address book so that you can receive status updates.

Bug reports are nice, patches are nicer.

SUPPORT

You can find documentation for this module with the perldoc command.

perldoc WWW::Myspace

You can also look for information at:

COPYRIGHT & LICENSE

Copyright 2005-2006 Grant Grueninger, all rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.