Net::Twitter — Perl interface to the Twitter APIs
| Use Case | Command | Description |
|---|---|---|
| Post a tweet | $nt->update('Hello, world!') | Update authenticating user's status |
| Get home timeline | $nt->home_timeline() | Retrieve 20 most recent statuses from friends |
| Search tweets | $nt->search({ q => $term }) | Search public tweets |
| Follow a user | $nt->create_friend($screen_name) | Follow a user by screen name |
| Upload an image | $nt->upload($file) | Upload media without posting |
| Verify credentials | $nt->verify_credentials() | Test if authentication is valid |
| Show a user | $nt->show_user({ screen_name => $name }) | Get extended user information |
| List followers | $nt->followers_ids() | Get array of follower IDs |
| Send direct message | $nt->new_direct_message($text) | Send DM to a user |
| Get trending topics | $nt->trends_place(1) | Global trending topics (WOEID=1) |
version 4.01043
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";
}
This version of Net::Twitter provides Twitter API v1.1 support. Enable it by including the API::RESTv1_1 trait instead of API::REST. Using Twitter API v1.1 may require changes to your code! It is not completely backwards compatible with v1.
For help migrating your application to Twitter API v1.1, see Net::Twitter::Manual::MigratingToV1_1.
This module has been superseded by Twitter::API. Please update as soon as you possibly can to use new features and the new API versions. This module will no longer be supported.
This module provides a perl interface to the Twitter APIs. See http://dev.twitter.com/docs for a full description of the Twitter APIs.
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 Net::Twitter::Role::API::REST.
To use Twitter API version 1.1, simply replace API::REST in the traits argument to new with API::RESTv1_1. The Net::Twitter API is backwards compatible to the extent possible. If Twitter does not provide a 1.1 endpoint for a version 1 call, Net::Twitter 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 its 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 https://dev.twitter.com/docs/rate-limiting/1.1/limits.
Net::Twitter is Moose based. Moose provides some advantages, including the ability for the maintainer of this module to respond quickly to Twitter API changes.
See Net::Twitter::Lite 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.
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 http://dev.twitter.com/doc.
To inspect the data, use Data::Dumper 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 perlreftut, perldsc, and perllol.
This constructs a Net::Twitter object. It takes several named parameters, all of them optional:
An ARRAY ref of traits used to control which APIs the constructed Net::Twitter object will support and how it handles errors. Possible values are:
API::RESTv1_1 — Provides support for the Twitter REST API version 1.1 methods.API::Search — Deprecated. Use search in API::RESTv1_1 instead.AppAuth — Provides Application-Only Authentication with methods request_access_token and invalidate_token. See Net::Twitter::Role::AppAuth.AutoCursor — Parameterized trait providing automatic loop for cursored calls. See Net::Twitter::Role::AutoCursor.InflateObjects — Inflates HASH refs into objects with read accessors, DateTime objects, URI objects, and relative time methods.Legacy — Provides backwards compatibility to Net::Twitter versions prior to 3.00. Implies API::REST, API::Search, API::TwitterVision, and API::WrapError.OAuth — Provides OAuth authentication. See Net::Twitter::Role::OAuth.RateLimit — Adds utility methods for rate limit status. See Net::Twitter::Role::RateLimit.RetryOnError — Automatically retries API calls with temporary failures. See Net::Twitter::Role::RetryOnError.WrapError — Returns undef on error and makes error available through get_error.Examples:
$nt = Net::Twitter->new(traits => ['API::RESTv1_1']);
$nt = Net::Twitter->new(traits => [qw/API::RESTv1_1 API::Search WrapError/]);
$nt = Net::Twitter->new(traits => ['Legacy']);
A boolean. If set to 0, constructs a Net::Twitter object implementing the REST API and throwing exceptions. If set to 1, uses the Legacy trait.
Credentials for Basic Authentication (deprecated by Twitter, but supported for compatible services).
Values for HTTP headers X-Twitter-Client-Name, X-Twitter-Client-Version, X-Twitter-Client-URL.
Specify LWP::UserAgent compatible class and configuration. Default: LWP::UserAgent and "Net::Twitter/4.01043 (Perl)".
No longer used by Twitter; retained for compatible services.
Configuration for API endpoint, realm, identi.ca support, SSL, and .netrc credentials.
OAuth consumer credentials (available when OAuth trait is included).
If set to 1, HTML entities in the "text" field of statuses are automatically decoded. Default 0.
Set credentials for Basic Authentication. Useful for managing multiple accounts.
Provides access to the constructed user agent object. Use with caution.
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, Net::Twitter provides support for both.
To set up OAuth, include consumer_key and consumer_secret options to new. When provided, the OAuth trait is automatically included. See Net::Twitter::Role::OAuth for more information on using OAuth, including examples.
To set up Basic Authentication, provide username and password options to new or call the credentials method.
In addition to the arguments specified for each API method, an additional -authenticate parameter can be passed to request or suppress an Authorization header.
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 methods accept simple positional arguments. See full documentation for details.
Some methods return partial results a page at a time. Originally used page parameter; newer methods use cursor parameter. Examples:
# Paging example
for ( my $page = 1; ; ++$page ) {
my $r = $nt->favorites({ page => $page });
last unless @$r;
push @favs, @$r;
}
# Cursor example
for ( my $cursor = -1; $cursor; $cursor = $r->{next_cursor} ) {
$r = $nt->followers_ids({ cursor => $cursor });
push @ids, @{ $r->{ids} };
}
-authenticate — Override authentication behavior for a call.-since — Accept a DateTime object, epoch, or date string for filtering by creation time.-legacy_lists_api — When using API::Lists trait, allows switching to new endpoints for individual calls.These methods are provided when trait API::RESTv1_1 is included in the traits option to new.
id — Accepts screen name or numeric ID. Use screen_name or user_id for disambiguation.skip_user — When true, timeline statuses omit full user object, only include an "id".account_settings — Returns trend, geo and sleep time info. Returns: HashRefaccount_totals (DEPRECATED) — Returns counts of friends, followers, updates, favorites. Returns: HashRefadd_list_member — Add member to a list. Returns: Useradd_place(name, contained_within, token, lat, long) — Create a new place. Returns: Placeblock_exists(id) (DEPRECATED) — Check if user is blocked. Returns: BasicUserblocking / blocks_list — Array of blocked users. Returns: ArrayRef[BasicUser]blocking_ids / blocks_ids — Array of blocked user IDs. Returns: ArrayRef[Int]contributees (DEPRECATED) — Users the specified user can contribute to. Returns: ArrayRef[User]contributors (DEPRECATED) — Users who can contribute to the account. Returns: ArrayRef[User]create_block(id) — Block a user. Returns: BasicUsercreate_favorite(id) — Favorite a status. Returns: Statuscreate_friend / follow / follow_new / create_friendship — Follow a user. Returns: BasicUsercreate_list(name) — Create a new list. Returns: Listcreate_media_metadata(media_id) — Add alt text to uploaded media. Returns: HashRefcreate_mute(id) — Mute a user. Returns: BasicUsercreate_saved_search(query) — Save a search query. Returns: SavedSearchdelete_list — Destroy a list. Returns: Listdelete_list_member / remove_list_member — Remove member from list. Returns: Userdestroy_block(id) — Un-block a user. Returns: BasicUserdestroy_direct_message(id) — Destroy a direct message. Returns: DirectMessagedestroy_favorite(id) — Un-favorite a status. Returns: Statusdestroy_friend(id) / unfollow / destroy_friendship — Unfollow user. Returns: BasicUserdestroy_mute(id) — Un-mute a user. Returns: BasicUserdestroy_saved_search(id) / delete_saved_search — Destroy saved search. Returns: SavedSearchdestroy_status(id) — Delete a status. Returns: Statusdirect_messages — 20 most recent DMs received. Returns: ArrayRef[DirectMessage]disable_notifications(id) (DEPRECATED) — Disable notifications from user. Returns: BasicUserenable_notifications(id) (DEPRECATED) — Enable notifications from user. Returns: BasicUserend_session (DEPRECATED) — End user session. Returns: Errorfavorites — 20 most recent favorites. Returns: ArrayRef[Status]followers / followers_list — Cursored collection of followers. Returns: HashReffollowers_ids — Array of follower IDs (with cursor). Returns: HashRef | ArrayRef[Int]friends / friends_list — Cursored collection of friends. Returns: HashReffriends_ids / following_ids — Array of friend IDs. Returns: HashRef | ArrayRef[Int]friends_timeline / following_timeline (DEPRECATED) — 20 most recent statuses. Returns: ArrayRef[Status]friendship_exists(user_a, user_b) (DEPRECATED) — Check if user_a follows user_b. Returns: Boolfriendships_incoming / incoming_friendships — Pending follow requests to authenticating user. Returns: HashReffriendships_outgoing / outgoing_friendships — Pending follow requests from authenticating user. Returns: HashRefgeo_id(place_id) — Details of a place. Returns: HashRefgeo_search — Search for places. Returns: HashRefget_configuration — Twitter configuration. Returns: HashRefget_languages — List of supported languages. Returns: ArrayRef[Language]get_list / show_list — Show a list. Returns: Listget_lists / list_lists / all_subscriptions — All lists user subscribes to. Returns: Hashrefget_privacy_policy — Twitter privacy policy. Returns: HashRefget_tos — Terms of Service. Returns: HashRefhome_timeline — 20 most recent statuses from friends. Returns: ArrayRef[Status]list_members — Members of a list. Returns: Hashreflist_memberships — Lists user has been added to. Returns: Hashreflist_ownerships — Lists owned by user. Returns: ArrayRef[List]list_statuses — Tweet timeline for list members. Returns: ArrayRef[Status]list_subscribers — Subscribers of a list. Returns: Hashreflist_subscriptions / subscriptions — Lists user is subscribed to. Returns: ArrayRef[List]lookup_friendships — Relationships of authenticating user to up to 100 users. Returns: ArrayReflookup_statuses(id) — Tweets from arbitrary set of IDs. Returns: HashReflookup_users — Extended info for up to 100 users. Returns: ArrayRef[User]members_create_all / add_list_members — Add multiple members to list. Returns: Listmembers_destroy_all / remove_list_members — Remove multiple members. Returns: Listmentions / replies / mentions_timeline — 20 most recent mentions. Returns: ArrayRef[Status]mutes(cursor) / muting_ids / muted_ids — IDs of muted users. Returns: ArrayRef[Int]muting / mutes_list — Muted user objects. Returns: ArrayRef[BasicUser]new_direct_message(text) — Send a direct message. Returns: DirectMessageno_retweet_ids / no_retweets_ids — User IDs for which no retweets are desired. Returns: ArrayRef[UserIDs]oembed — Embed representation of a Tweet. Returns: Statusprofile_banner — Available banner sizes. Returns: HashRefrate_limit_status(resources) — Remaining API requests. Returns: RateLimitStatusrelated_results(id) (DEPRECATED) — Replies and mentions related to a status. Returns: ArrayRef[Status]remove_profile_banner — Remove profile banner. Returns: Nothingreport_spam(id) — Block and report user as spammer. Returns: Userretweet(id) — Retweet a tweet. Returns: Statusretweeted_by(id) (DEPRECATED) — Users who retweeted a status. Returns: ArrayRef[User]retweeted_by_ids(id) (DEPRECATED) — IDs of users who retweeted. Returns: ArrayRef[User]retweeted_by_me (DEPRECATED) — Recent retweets by authenticating user. Returns: ArrayRef[Status]retweeted_by_user(id) (DEPRECATED) — Retweets by specific user. Returns: ArrayRefretweeted_to_me (DEPRECATED) — Retweets by friends. Returns: ArrayRef[Status]retweeted_to_user(id) (DEPRECATED) — Retweets to specific user. Returns: ArrayRefretweeters_ids(id) — IDs of users who retweeted. Returns: HashRefretweets(id) — First 100 retweets of a tweet. Returns: Arrayref[Status]retweets_of_me / retweeted_of_me — Recent retweets of your tweets. Returns: ArrayRef[Status]reverse_geocode(lat, long) — Search for places by coordinates. Returns: HashRefsaved_searches — Saved searches of authenticating user. Returns: ArrayRef[SavedSearch]search(q) — Search tweets. Returns: HashRefsent_direct_messages / direct_messages_sent — 20 most recent DMs sent. Returns: ArrayRef[DirectMessage]show_direct_message(id) — Single direct message. Returns: HashRefshow_friendship / show_relationship — Relationship between two users. Returns: Relationshipshow_list_member / is_list_member — Check if user is list member. Returns: Maybe[User]show_list_subscriber / is_list_subscriber — Check if user is subscriber. Returns: Usershow_saved_search(id) — Retrieve saved search data. Returns: SavedSearchshow_status(id) — Single status. Returns: Statusshow_user — Extended user information. Returns: ExtendedUsersimilar_places(lat, long, name) — Find places with similar name. Returns: HashRefsubscribe_list — Subscribe to a list. Returns: Listsuggestion_categories — List of suggested user categories. Returns: ArrayReftest (DEPRECATED) — Returns "ok". Returns: Hashtrends_available — Locations with trending topics. Returns: ArrayRef[Location]trends_closest — Nearest trending locations. Returns: ArrayRef[Location]trends_current(exclude) (DEPRECATED) — Top 10 trending topics. Returns: HashReftrends_daily (DEPRECATED) — Top 20 per hour. Returns: HashReftrends_place(id) / trends_location — Top 10 trends for a WOEID. Returns: ArrayRef[Trend]trends_weekly (DEPRECATED) — Top 30 per day. Returns: HashRefunsubscribe_list — Unsubscribe from a list. Returns: Listupdate(status) — Update status. Returns: Statusupdate_account_settings — Update user settings. Returns: HashRefupdate_delivery_device(device) — Set SMS delivery device. Returns: BasicUserupdate_friendship — Enable/disable retweets and device notifications. Returns: HashRefupdate_list — Update list details. Returns: Listupdate_location(location) (DEPRECATED) — Update location. Returns: BasicUserupdate_profile — Set account profile values. Returns: ExtendedUserupdate_profile_background_image — Upload background image. Returns: ExtendedUserupdate_profile_banner(banner) — Upload profile banner. Returns: Nothingupdate_profile_colors — Set color scheme. Returns: ExtendedUserupdate_profile_image(image) — Upload profile image. Returns: ExtendedUserupdate_with_media(status, media[]) (DEPRECATED) — Post status with media. Returns: Statusupload(media) — Upload media without posting. Returns: HashRefupload_status(media_id, command) — Check status of async video upload. Returns: statususer_suggestions(slug) / follow_suggestions — Users in a suggested category. Returns: ArrayRefuser_suggestions_for(slug) / follow_suggestions_for — Category details. Returns: ArrayRefuser_timeline — 20 most recent statuses from user. Returns: ArrayRef[Status]users_search(q) / find_people / search_users — Search for users. Returns: ArrayRef[Users]verify_credentials — Test validity of credentials. Returns: ExtendedUserThese methods are provided when trait API::Search is included.
search(q) — Same as REST search but returns results in "results" key. Returns: HashRefThe original Lists API methods are deprecated. See Net::Twitter::Role::API::Lists for backwards compatibility.
Provided when trait API::TwitterVision is included.
current_status(id) — Get current location and status. Returns: HashRefupdate_twittervision(location) — Update location. Returns: HashRefThis version of Net::Twitter automatically includes the Legacy trait if no traits option is provided to new. Therefore, these two calls are currently equivalent:
$nt = Net::Twitter->new(username => $user, password => $passwd);
$nt = Net::Twitter->new( username => $user, password => $passwd, traits => ['Legacy']);
Existing applications written for a prior version of Net::Twitter should continue to run without modification. In a future release, the default traits may change, and a warning will be added if no traits option is provided.
There are two strategies for handling errors: throwing exceptions and wrapping errors. Exception handling is the recommended strategy.
When trait WrapError (or Legacy) is specified, Net::Twitter returns undef on error. Retrieve error info via http_code, http_message, and get_error. See Net::Twitter::Role::WrapError.
if ( my $followers = $nt->followers ) {
for my $follower ( @$followers ) { ... }
}
else {
warn "HTTP message: ", $nt->http_message, "\n";
}
When Net::Twitter encounters an error, it throws a Net::Twitter::Error object. Use eval blocks:
eval {
my $statuses = $nt->friends_timeline();
for my $status ( @$statuses ) { ... }
};
if ( $@ ) {
if ( blessed $@ && $@->isa('Net::Twitter::Error') ) {
warn $@->error;
}
else {
die $@;
}
}
Net::Twitter::Error stringifies reasonably:
eval { $nt->update($status) };
if ( $@ ) {
warn "update failed because: $@\n";
}
->followers({ screen_name => $friend }) return my followers instead of $friend's? — Check the spelling of screen_name. Twitter may discard unrecognized parameters.$r = $nt->search({ geocode => "45.511795,-122.675629,25mi" });source parameter to 'api' or '' for "from API" or "from web". Register an application with OAuth to use a custom source name.Report bugs to bug-net-twitter AT rt.org or via web at https://rt.cpan.org/Dist/Display.html?Queue=Net-Twitter.
Join the Net::Twitter IRC channel at irc://irc.perl.org/net-twitter.
Follow perl_api.
Track development at http://github.com/semifor/Net-Twitter.
Many thanks to Chris Thompson (cpan AT cthompson.com), the original author of Net::Twitter and all versions prior to 3.00.
Also thanks to Chris Prather (perigrin) for answering many design and implementation questions.
Marc Mims (marc AT questright.com) (@semifor on Twitter)
Roberto Etcheverry, KATOU Akira, Francisco Pecorella, Doug Bell, Justin Hunter, Allen Haim, Joe Papperello, Samuel Kaufman, AnnMary Mathew, Olaf Alders
Copyright (c) 2009-2016 Marc Mims. The Twitter API itself and the description text used in this module is Copyright (c) 2016 Twitter. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
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.
Generated by phpman v4.9.29 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-07-21 00:33 @2600:1f28:365:80b0:d8a5:c3c6:bf94:28c0
CrawledBy CCBot/2.0 (https://commoncrawl.org/faq/)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format