#!/usr/bin/env perl =head1 NAME Net::Twitter - A perl interface to the Twitter API =head1 VERSION This document describes Net::Twitter version [% VERSION %] =head1 SYNOPSIS use Net::Twitter; use Scalar::Util 'blessed'; # When no authentication is required: my $nt = Net::Twitter->new(legacy => 0); # As of 13-Aug-2010, Twitter requires OAuth for authenticated requests my $nt = Net::Twitter->new( traits => [qw/API::RESTv1_1/], consumer_key => $consumer_key, consumer_secret => $consumer_secret, access_token => $token, access_token_secret => $token_secret, ); my $result = $nt->update('Hello, world!'); eval { my $statuses = $nt->friends_timeline({ since_id => $high_water, count => 100 }); for my $status ( @$statuses ) { print "$status->{created_at} <$status->{user}{screen_name}> $status->{text}\n"; } }; if ( my $err = $@ ) { die $@ unless blessed $err && $err->isa('Net::Twitter::Error'); warn "HTTP Response Code: ", $err->code, "\n", "HTTP Message......: ", $err->message, "\n", "Twitter error.....: ", $err->error, "\n"; } =head1 TWITTER API V1.1 SUPPORT This version of Net::Twitter provides Twitter API v1.1 support. Enable it by including the C trait instead of C. Using Twitter API v1.1 may require changes to you code! It is not completely backwards compatible with v1. For help migrating your application to Twitter API v1.1, see L. =head1 DESCRIPTION This module provides a perl interface to the Twitter APIs. See L for a full description of the Twitter APIs. =head1 TWITTER API VERSION 1.1 Twitter will (perhaps has by the time you read this) deprecated version 1 of the API. Documentation, here, assumes version 1.1 of the API. For version 1 documentation, see L. To use Twitter API version 1.1, simply replace C in the C argument to C with C. The C API is backwards compatible to the extent possible. If Twitter does not provide a 1.1 endpoint for a version 1 call, C cannot support it, of course. Twitter API version 1.1 requires OAuth authentication for all calls. There is no longer an IP address limit and a per-user limit. Each API call has it's own rate limit. Most are 15 calls reset every 15 minutes. Others are 180 calls, reset every 15 minutes. These limits may change. For current rate limits, see L. =head1 OMG! THE MOOSE! Net::Twitter is L based. Moose provides some advantages, including the ability for the maintainer of this module to respond quickly to Twitter API changes. See L if you need an alternative without Moose and its dependencies. Net::Twitter::Lite's API method definitions and documentation are generated from Net::Twitter. It is a related module, but does not depend on Net::Twitter or Moose for installation. =head1 RETURN VALUES Net::Twitter decodes the data structures returned by the Twitter API into native perl data structures (HASH references and ARRAY references). The full layout of those data structures are not documented, here. They change often, usually with the addition of new elements, and documenting all of those changes would be a significant challenge. Instead, rely on the online Twitter API documentation and inspection of the returned data. The Twitter API online documentation is located at L. To inspect the data, use L or similar module of your choice. Here's a simple example using Data::Dumper: use Data::Dumper; my $r = $nt->search($search_term); print Dumper $r; For more information on perl data structures, see L, L, and L. =head1 METHODS AND ARGUMENTS =over 4 =item new This constructs a C object. It takes several named parameters, all of them optional: =over 4 =item traits An ARRAY ref of traits used to control which APIs the constructed C object will support and how it handles errors. Possible values are: =over 4 =item API::RESTv1_1 Provides support for the Twitter REST API version 1.1 methods. =item API::Search Provides support for the Twitter Search API methods. =item AutoCursor C is a parameterized trait that provides an automatic loop for cursored calls, returning an ARRAY reference to the combined results. By default, it handles C and C. See L for details. =item InflateObjects When this optional trait is included, Net::Twitter inflates HASH refs returned by Twitter into objects with read accessors for each element. In addition, it inflates dates to L objects and URLs to L objects. Objects that include a C attribute also have a C method. For example, with C applied, the method returns an array of status objects: $r = $nt->friends_timeline; for my $status ( @$r ) { $r->user->screen_name; # same as $r->{user}{screen_name} # $created_at is a DateTime; $age is a DateTime::Duration my $age = DateTime->now - $r->created_at; # print an age in a similar style to the Twitter web site, e.g.: # less than a minute ago # about a minute ago # 6 minutes ago # 1 day ago # etc. print $r->relative_created_at; =item Legacy This trait provides backwards compatibility to C versions prior to 3.00. It implies the traits C, C, C, and C. It also provides additional functionality to ensure consistent behavior for applications written for use with legacy versions of C. In the current version, this trait is automatically included if the C option is not specified. This ensures backwards compatibility for existing applications using C versions prior to 3.00. See section L for more details. =item OAuth The C trait provides OAuth authentication rather than the default Basic Authentication for Twitter API method calls. See the L section and L for full documentation. =item RateLimit The C trait adds utility methods that return information about the current rate limit status. See L for details. =item RetryOnError The C trait automatically retries Twitter API calls with temporary failures. See L for details. =item WrapError C normally throws exceptions on error. When this trait is included, C returns undef when a method fails and makes the error available through method C. This is the way all errors were handled in Net::Twitter versions prior to version 3.00. =back Some examples of using the C parameter in C: # provide support for *only* the REST API; throw exceptions on error $nt = Net::Twitter->new(traits => ['API::RESTv1_1']); # provide support for both the REST and Search APIs; wrap errors $nt = Net::Twitter->new(traits => [qw/API::RESTv1_1 API::Search WrapError/]); # Provide legacy support for applications written with Net::Twitter # prior to version 3.0. $nt = Net::Twitter->new(traits => ['Legacy']); =item legacy A boolean. If set to 0, C constructs a C object implementing the REST API and throws exceptions on API method errors. Net::Twitter->new(legacy => 0); is a shortcut for: Net::Twitter->new(traits => ['API::RESTv1_1']); If set to 1, C constructs a C object with the C trait. Net::Twitter->new(legacy => 1); is a shortcut for: Net::Twitter->new(traits => ['Legacy']); =item username This is the username for Basic Authentication. NOTE: as of 31-Aug-2010, Twitter no longer supports Basic Authentication. Use OAuth instead. Other Twitter compatible services may, however, accept Basic Authentication, so support for it remains in C. =item password This is the password used for Basic Authentication. =item clientname The value for the C HTTP header. It defaults to "Perl Net::Twitter". Note: This option has nothing to do with the "via" application byline. =item clientver The value for the C HTTP header. It defaults to current version of the C module. =item clienturl The value for the C HTTP header. It defaults to the search.cpan.org page for the C distribution. =item useragent_class The C compatible class used internally by C. It defaults to "LWP::UserAgent". For L based applications, consider using "LWP::UserAgent::POE". =item useragent_args An HASH ref of arguments to pass to constructor of the class specified with C, above. It defaults to {} (an empty HASH ref). =item useragent The value for C HTTP header. It defaults to "Net::Twitter/$VERSION (Perl)", where C<$VERSION> is the current version of C. =item source Twitter on longer uses the C parameter. Support for it remains in C for any compatible services that may use it. It was originally used by Twitter to provide an "via" application byline. =item apiurl The URL for the Twitter API. This defaults to "http://api.twitter.com/1". This option is available when the C trait is included. =item apihost DEPRECATED - Setting the C is sufficient. =item apirealm A string containing the Twitter API realm used for Basic Authentication. It defaults to "Twitter API". This option is available when the C trait is included. =item identica If set to 1, C overrides the defaults for C, C, and C to "http://identi.ca/api", "identi.ca:80", and "Laconica API" respectively. It defaults to 0. This option is available when the C trait is included. =item consumer_key A string containing the OAuth consumer key provided by Twitter when an application is registered. This option is available when the C trait is included. =item consumer_secret A string containing the OAuth consumer secret. This option is available when the C trait is included. =item ssl If set to 1, an SSL connection will be used for all API calls. Defaults to 0. =item netrc (Optional) Sets the I key to look up in C<.netrc> to obtain credentials. If set to 1, Net::Twitter will use the value of the C option (below). # in .netrc machine api.twitter.com login YOUR_TWITTER_USER_NAME password YOUR_TWITTER_PASSWORD machine semifor.twitter.com login semifor password SUPERSECRET # in your perl program $nt = Net::Twitter->new(netrc => 1); $nt = Net::Twitter->new(netrc => 'semifor.twitter.com'); =item netrc_machine (Optional) Sets the C entry to look up in C<.netrc> when C< 1>> is used. Defaults to C. =item decode_html_entities Twitter encodes HTML entities in the C field of statuses. Set this option to 1 to have them automatically decoded. Default 0. =back =item credentials($username, $password) Set the credentials for Basic Authentication. This is helpful for managing multiple accounts. =item ua Provides access to the constructed user agent object used internally by C. Use it with caution. =back =head1 AUTHENTICATION With REST API version 1.1, all API calls require OAuth. Since 31-Aug-2010, version 1 required OAuth requests requiring authentication. Other Twitter compatible services, like Identi.ca, accept Basic Authentication. So, C provides support for both. To set up OAuth, include the C and C options to L. When they are provided, the C trait will be automatically included. See L for more information on using OAuth, including examples. To set up Basic Authentication in C, provide the C and C options to L or call the L method. In addition to the arguments specified for each API method described below, an additional C<-authenticate> parameter can be passed. To request an C header, pass C<< -authenticate => 1 >>; to suppress an authentication header, pass C<< -authenticate => 0 >>. Even if requested, an Authorization header will not be added if there are no user credentials (username and password for Basic Authentication; access tokens for OAuth). This is probably only useful for non-Twitter sites that use the Twitter API and support unauthenticated calls. =head1 API METHODS AND ARGUMENTS Most Twitter API methods take parameters. All Net::Twitter API methods will accept a HASH ref of named parameters as specified in the Twitter API documentation. For convenience, many Net::Twitter methods accept simple positional arguments. The positional parameter passing style is optional; you can always use the named parameters in a HASH reference if you prefer. You may pass any number of required parameters as positional parameters. You must pass them in the order specified in the documentation for each method. Optional parameters must be passed as named parameters in a HASH reference. The HASH reference containing the named parameters must be the final parameter to the method call. Any required parameters not passed as positional parameters, must be included in the named parameter HASH reference. For example, the REST API method C has one required parameter, C. You can call C with a HASH ref argument: $nt->update({ status => 'Hello world!' }); Or, you can use the convenient, positional parameter form: $nt->update('Hello world!'); The C method also has an optional parameter, C. To use it, you B use the HASH ref form: $nt->update({ status => 'Hello world!', in_reply_to_status_id => $reply_to }); You may use the convenient positional form for the required C parameter with the optional parameters specified in the named parameter HASH reference: $nt->update('Hello world!', { in_reply_to_status_id => $reply_to }); Convenience form is provided for the required parameters of all API methods. So, these two calls are equivalent: $nt->friendship_exists({ user_a => $fred, user_b => $barney }); $nt->friendship_exists($fred, $barney); Many API methods have aliases. You can use the API method name, or any of its aliases, as you prefer. For example, these calls are all equivalent: $nt->friendship_exists($fred, $barney); $nt->relationship_exists($fred, $barney); $nt->follows($fred, $barney); Aliases support both the HASH ref and convenient forms: $nt->follows({ user_a => $fred, user_b => $barney }); =head2 Cursors and Paging Some methods return partial results a page at a time. Originally, methods that returned partial results used a C parameter. A more recent addition to the Twitter API for retrieving multiple pages uses the C parameter. Usually, a method uses either the C parameter or the C parameter, but not both. There have been exceptions to this rule when Twitter deprecates the use of C for a method in favor of C. In that case, both methods may work during a transition period. So, if a method supports both, you should always use the C parameter. =head3 Paging For methods that support paging, the first page is returned by passing C<< page => 1 >>, the second page by passing C<< page => 2 >>, etc. If no C parameter is passed, the first page is returned. Here's an example that demonstrates how to obtain all favorites in a loop: my @favs; for ( my $page = 1; ; ++$page ) { my $r = $nt->favorites({ page => $page }); last unless @$r; push @favs, @$r; } =head3 Cursors Cursoring employs a different strategy. To obtain the first page of results, pass C<< cursor => -1 >>. Twitter returns a reference to a hash that includes entries C, C, and an entry with a reference to an array containing a page of the requested items. The key for the array reference will be named C, C, or something similar depending upon the type of returned items. For example, when C parameter is used with the C method, the returned in hash entry C. The C value can be used in a subsequent call to obtain the next page of results. When you have obtained the last page of results, C will be 0. Likewise, you can use the value for C to obtain the previous page of results. When you have obtained the first page, C will be 0. Here's an example that demonstrates how to obtain all follower IDs in a loop using the C parameter: my @ids; for ( my $cursor = -1, my $r; $cursor; $cursor = $r->{next_cursor} ) { $r = $nt->followers_ids({ cursor => $cursor }); push @ids, @{ $r->{ids} }; } =head2 Synthetic Arguments In addition to the arguments described in the Twitter API Documentation for each API method, Net::Twitter supports additional I arguments. =over 4 =item -authenticate When set to 1, Net::Twitter will provide an Authorization header for the API call; when set to 0, it will suppress the Authentication header. This argument overrides the defined authentication behavior for the API method. It is probably only useful for the C method which returns different values for authenticated and unauthenticated calls. See L for more details. =item -since API methods that accept the C argument will also accept the synthetic C<-since> argument, instead. C<-since> may be a C object, an epoch time (the number of seconds since the system epoch), or a string in the same format returned by Twitter for the C attribute. Only statuses with a C time greater than C<-since> will be returned by the API call. =item -legacy_lists_api This option is only effective when the legacy C trait is applied. Passing C<-legacy_lists_api> set to 0 for lists methods will use the new lists endpoints and semantics. This will facilitate upgrading an application to use the new lists api methods. When the C trait is not applied, this option is ignored. =back =head1 REST API Methods These methods are provided when trait C is included in the C option to C. =head2 Common Parameters =over 4 =item id Several of these methods accept a user ID as the C parameter. The user ID can be either a screen name, or the users numeric ID. To disambiguate, use the C or C parameters, instead. For example, These calls are equivalent: $nt->create_friend('perl_api'); # screen name $nt->create_friend(1564061); # numeric ID $nt->create_friend({ id => 'perl_api' }); $nt->create_friend({ screen_name => 'perl_api' }); $nt->create_friend({ user_id => 1564061 }); However user_id 911 and screen_name 911 are separate Twitter accounts. These calls are NOT equivalent: $nt->create_friend(911); # interpreted as screen name $nt->create_friend({ user_id => 911 }); # screen name: richellis Whenever the C parameter is required and C and C are also parameters, using any one of them satisfies the requirement. =item skip_user The timeline methods all accept an optional C parameter. When set to a true value, the statuses returned in a timeline will not contain an entire embedded user HASH. Instead, the user node will contain only an C element to indicate the numerical ID of the Twitter user that sent the status. =back =head2 Methods [% INCLUDE APIDOC class='API::RESTv1_1' %] [% INCLUDE APIDOC class='API::Upload' %] =head1 Search API Methods These methods are provided when trait C is included in the C option to C. [% INCLUDE APIDOC class='API::Search' %] =head1 Lists API Methods The original Lists API methods have been deprecated. L provides backwards compatibility for code written using those deprecated methods. If you're not already using the C trait, don't! Use the lists methods described above. If you are using the C trait, you should remove it from your code and change the arguments in your list API method calls to match those described above. Also, if using the C trait, you can pass synthetic argument C<-legacy_lists_api> set to 0 for individual calls to use the new endpoints semantics. =head1 TwitterVision API Methods These methods are provided when trait C is included in the C option to C. [% INCLUDE APIDOC class='API::TwitterVision' %] =head1 LEGACY COMPATIBILITY This version of C automatically includes the C trait if no C option is provided to C. Therefore, these 2 calls are currently equivalent: $nt = Net::Twitter->new(username => $user, password => $passwd); $nt = Net::Twitter->new( username => $user, password => $passwd, traits => ['Legacy'], ); Thus, existing applications written for a prior version of C should continue to run, without modification, with this version. In a future release, the default traits may change. Prior to that change, however, a nearer future version will add a warning if no C option is provided to C. To avoid this warning, add an appropriate C option to your existing application code. =head1 ERROR HANDLING There are currently two strategies for handling errors: throwing exceptions and wrapping errors. Exception handling is the newer, recommended strategy. =head2 Wrapping Errors When trait C is specified (or C, which includes trait C), C returns undef on error. To retrieve information about the error, use methods C, C, and C. These methods are described in the L. if ( my $followers = $nt->followers ) { for my $follower ( @$followers ) { #... } } else { warn "HTTP message: ", $nt->http_message, "\n"; } Since an error is stored in the object instance, this error handling strategy is problematic when using a user agent like C that provides concurrent requests. The error for one request can be overwritten by a concurrent request before you have an opportunity to access it. =head2 Exception Handling When C encounters a Twitter API error or a network error, it throws a C object. You can catch and process these exceptions by using C blocks and testing $@: eval { my $statuses = $nt->friends_timeline(); # this might die! for my $status ( @$statuses ) { #... } }; if ( $@ ) { # friends_timeline encountered an error if ( blessed $@ && $@->isa('Net::Twitter::Error') ) { #... use the thrown error obj warn $@->error; } else { # something bad happened! die $@; } } C stringifies to something reasonable, so if you don't need detailed error information, you can simply treat $@ as a string: eval { $nt->update($status) }; if ( $@ ) { warn "update failed because: $@\n"; } =head1 FAQ =over 4 =item Why does C<< ->followers({ screen_name => $friend }) >> return I followers instead of C<$friends>'s? First, check carefully to make sure you've spelled "screen_name" correctly. Twitter sometimes discards parameters it doesn't recognize. In this case, the result is a list of your own followers---the same thing that would happen if you called C without the C parameter. =item How do I use the C parameter in the Search API? The C parameter value includes a latitude, longitude, and radius separated with commas. $r = $nt->search({ geocode => "45.511795,-122.675629,25mi" }); =item How do I get Twitter to display something other than "from Perl Net::Twitter"? If you set the source parameter to C, twitter will display "from API", and if you set it to the empty string, twitter will display, "from web". $nt = Net::Twitter->new(netrc => 1,legacy => 0,ssl => 1,source => 'api'); $nt->update('A post with the source parameter overridden.'); # result: http://twitter.com/semifor_test/status/6541105458 $nt = Net::Twitter->new(netrc => 1,legacy => 0,ssl => 1,source => ''); $nt->update('A post with the source parameter overridden.'); # result: http://twitter.com/semifor_test/status/6541257224 If you want something other than "Net::Twitter", "API", or "web", you need to register an application and use OAuth authentication. If you do that, you can have any name you choose for the application printed as the source. Since rolling out OAuth, Twitter has stopped issuing new registered source parameters, only existing register source parameters are valid. =back =head1 SEE ALSO =over 4 =item L The C exception object. =item L This is the official Twitter API documentation. It describes the methods and their parameters in more detail and may be more current than the documentation provided with this module. =item L This LWP::UserAgent compatible class can be used in L based application along with Net::Twitter to provide concurrent, non-blocking requests. =item L This module, by Jesse Stay, provides Twitter OAuth authentication support for the popular L web application framework. =back =head1 SUPPORT Please report bugs to C, or through the web interface at L. Join the Net::Twitter IRC channel at L. Follow perl_api: L. Track Net::Twitter development at L. =head1 ACKNOWLEDGEMENTS Many thanks to Chris Thompson , the original author of C and all versions prior to 3.00. Also, thanks to Chris Prather (perigrin) for answering many design and implementation questions, especially with regards to Moose. =head1 AUTHOR Marc Mims (@semifor on Twitter) =head1 CONTRIBUTORS Roberto Etcheverry (@retcheverry on Twitter) KATOU Akira Francisco Pecorella Doug Bell Justin Hunter Allen Haim =head1 LICENSE Copyright (c) 2009-2011 Marc Mims The Twitter API itself, and the description text used in this module is: Copyright (c) 2009 Twitter This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 DISCLAIMER OF WARRANTY BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENSE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. [% BLOCK APIDOC %] =over 4 [% FOREACH method IN get_methods_for(class) -%] =item B<[% method.name %]>[% IF method.deprecated %] B[% END %] [% IF method.required.size > 0; pos_params = method.required; ELSIF method.params.size == 1; pos_params = method.params; ELSE; pos_params = []; END; IF pos_params.size -%] =item B<[% method.name %]([% pos_params.join(", ") %])> [% END -%] [% FOREACH alias IN method.aliases -%] =item alias: [% alias %] [% END -%] =over 4 =item Parameters: [% IF method.params.size %][% method.params.join(", ") %][% ELSE %]I[% END %] =item Required: [% IF method.required.size %][% method.required.join(", ") %][% ELSE %]I[% END %] =back [% method.description %] Returns: [% method.returns %] [% END -%] =back [% END %]