/
net-twitter-lite.tt2
1363 lines (987 loc) · 40.8 KB
/
net-twitter-lite.tt2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Net::Twitter::Lite;
use 5.005;
use warnings;
use strict;
our $VERSION = '[% VERSION %]';
$VERSION = eval { $VERSION };
use Carp;
use URI::Escape;
use JSON;
use HTTP::Request::Common;
use Net::Twitter::Lite::Error;
use Encode qw/encode_utf8/;
my $json_handler = JSON->new->utf8;
sub new {
my ($class, %args) = @_;
my $netrc = delete $args{netrc};
my $new = bless {
apiurl => 'http://api.twitter.com/1',
searchapiurl => 'http://search.twitter.com',
search_trends_api_url => 'http://api.twitter.com/1',
lists_api_url => 'http://api.twitter.com/1',
apirealm => 'Twitter API',
$args{identica} ? ( apiurl => 'http://identi.ca/api' ) : (),
useragent => __PACKAGE__ . "/$VERSION (Perl)",
clientname => __PACKAGE__,
clientver => $VERSION,
clienturl => 'http://search.cpan.org/dist/Net-Twitter-Lite/',
source => 'twitterpm',
useragent_class => 'LWP::UserAgent',
useragent_args => {},
oauth_urls => {
request_token_url => "https://twitter.com/oauth/request_token",
authentication_url => "https://twitter.com/oauth/authenticate",
authorization_url => "https://twitter.com/oauth/authorize",
access_token_url => "https://twitter.com/oauth/access_token",
xauth_url => "https://twitter.com/oauth/access_token",
},
netrc_machine => 'api.twitter.com',
%args
}, $class;
unless ( exists $new->{legacy_lists_api} ) {
$new->{legacy_lists_api} = 1;
carp
"For backwards compatibility @{[ __PACKAGE__ ]} uses the deprecated Lists API
endpoints and semantics. This default will be changed in a future version.
Please update your code to use the new lists semantics and pass
(legacy_lists_api => 0) to new.
You can disable this warning, and keep backwards compatibility by passing
(legacy_lists_api => 1) to new. Be warned, however, that support for the
legacy endpoints will be removed in a future version and the default will
change to (legacy_lists_api => 0).";
}
if ( delete $args{ssl} ) {
$new->{$_} =~ s/^http:/https:/
for qw/apiurl searchapiurl search_trends_api_url lists_api_url/;
}
# get username and password from .netrc
if ( $netrc ) {
eval { require Net::Netrc; 1 }
|| croak "Net::Netrc is required for the netrc option";
my $host = $netrc eq '1' ? $new->{netrc_machine} : $netrc;
my $nrc = Net::Netrc->lookup($host)
|| croak "No .netrc entry for $host";
@{$new}{qw/username password/} = $nrc->lpa;
}
$new->{ua} ||= do {
eval "use $new->{useragent_class}";
croak $@ if $@;
$new->{useragent_class}->new(%{$new->{useragent_args}});
};
$new->{ua}->agent($new->{useragent});
$new->{ua}->default_header('X-Twitter-Client' => $new->{clientname});
$new->{ua}->default_header('X-Twitter-Client-Version' => $new->{clientver});
$new->{ua}->default_header('X-Twitter-Client-URL' => $new->{clienturl});
$new->{ua}->env_proxy;
$new->{_authenticator} = exists $new->{consumer_key}
? '_oauth_authenticated_request'
: '_basic_authenticated_request';
$new->credentials(@{$new}{qw/username password/})
if exists $new->{username} && exists $new->{password};
return $new;
}
sub credentials {
my $self = shift;
my ($username, $password) = @_;
croak "exected a username and password" unless @_ == 2;
croak "OAuth authentication is in use" if exists $self->{consumer_key};
$self->{username} = $username;
$self->{password} = $password;
my $uri = URI->new($self->{apiurl});
my $netloc = join ':', $uri->host, $uri->port;
$self->{ua}->credentials($netloc, $self->{apirealm}, $username, $password);
}
# This is a hack. Rather than making Net::OAuth an install requirement for
# Net::Twitter::Lite, require it at runtime if any OAuth methods are used. It
# simply returns the string 'Net::OAuth' after successfully requiring
# Net::OAuth.
sub _oauth {
my $self = shift;
return $self->{_oauth} ||= do {
eval "use Net::OAuth 0.25";
croak "Install Net::OAuth 0.25 or later for OAuth support" if $@;
eval '$Net::OAuth::PROTOCOL_VERSION = Net::OAuth::PROTOCOL_VERSION_1_0A';
die $@ if $@;
'Net::OAuth';
};
}
# simple check to see if we have access tokens; does not check to see if they are valid
sub authorized {
my $self = shift;
return defined $self->{access_token} && $self->{access_token_secret};
}
# OAuth token accessors
for my $method ( qw/
access_token
access_token_secret
request_token
request_token_secret
/ ) {
no strict 'refs';
*{__PACKAGE__ . "::$method"} = sub {
my $self = shift;
$self->{$method} = shift if @_;
return $self->{$method};
};
}
# OAuth url accessors
for my $method ( qw/
request_token_url
authentication_url
authorization_url
access_token_url
xauth_url
/ ) {
no strict 'refs';
*{__PACKAGE__ . "::$method"} = sub {
my $self = shift;
$self->{oauth_urls}{$method} = shift if @_;
return URI->new($self->{oauth_urls}{$method});
};
}
# get the athorization or authentication url
sub _get_auth_url {
my ($self, $which_url, %params ) = @_;
$self->_request_request_token(%params);
my $uri = $self->$which_url;
$uri->query_form(oauth_token => $self->request_token);
return $uri;
}
# get the authentication URL from Twitter
sub get_authentication_url { return shift->_get_auth_url(authentication_url => @_) }
# get the authorization URL from Twitter
sub get_authorization_url { return shift->_get_auth_url(authorization_url => @_) }
# common portion of all oauth requests
sub _make_oauth_request {
my ($self, $type, %params) = @_;
my $request = $self->_oauth->request($type)->new(
version => '1.0',
consumer_key => $self->{consumer_key},
consumer_secret => $self->{consumer_secret},
request_method => 'GET',
signature_method => 'HMAC-SHA1',
timestamp => time,
nonce => time ^ $$ ^ int(rand 2**32),
%params,
);
$request->sign;
return $request;
}
# called by get_authorization_url to obtain request tokens
sub _request_request_token {
my ($self, %params) = @_;
my $uri = $self->request_token_url;
$params{callback} ||= 'oob';
my $request = $self->_make_oauth_request(
'request token',
request_url => $uri,
%params,
);
my $res = $self->{ua}->get($request->to_url);
die "GET $uri failed: ".$res->status_line
unless $res->is_success;
# reuse $uri to extract parameters from the response content
$uri->query($res->content);
my %res_param = $uri->query_form;
$self->request_token($res_param{oauth_token});
$self->request_token_secret($res_param{oauth_token_secret});
}
# exchange request tokens for access tokens; call with (verifier => $verifier)
sub request_access_token {
my ($self, %params ) = @_;
my $uri = $self->access_token_url;
my $request = $self->_make_oauth_request(
'access token',
request_url => $uri,
token => $self->request_token,
token_secret => $self->request_token_secret,
%params, # verifier => $verifier
);
my $res = $self->{ua}->get($request->to_url);
die "GET $uri failed: ".$res->status_line
unless $res->is_success;
# discard request tokens, they're no longer valid
delete $self->{request_token};
delete $self->{request_token_secret};
# reuse $uri to extract parameters from content
$uri->query($res->content);
my %res_param = $uri->query_form;
return (
$self->access_token($res_param{oauth_token}),
$self->access_token_secret($res_param{oauth_token_secret}),
$res_param{user_id},
$res_param{screen_name},
);
}
# exchange username and password for access tokens
sub xauth {
my ( $self, $username, $password ) = @_;
my $uri = $self->xauth_url;
my $request = $self->_make_oauth_request(
'XauthAccessToken',
request_url => $uri,
x_auth_username => $username,
x_auth_password => $password,
x_auth_mode => 'client_auth',
);
my $res = $self->{ua}->get($request->to_url);
die "GET $uri failed: ".$res->status_line
unless $res->is_success;
# reuse $uri to extract parameters from content
$uri->query($res->content);
my %res_param = $uri->query_form;
return (
$self->access_token($res_param{oauth_token}),
$self->access_token_secret($res_param{oauth_token_secret}),
$res_param{user_id},
$res_param{screen_name},
);
}
# common call for both Basic Auth and OAuth
sub _authenticated_request {
my $self = shift;
my $authenticator = $self->{_authenticator};
$self->$authenticator(@_);
}
sub _encode_args {
my $args = shift;
# Values need to be utf-8 encoded. Because of a perl bug, exposed when
# client code does "use utf8", keys must also be encoded.
# see: http://www.perlmonks.org/?node_id=668987
# and: http://perl5.git.perl.org/perl.git/commit/eaf7a4d2
return { map { utf8::upgrade($_) unless ref($_); $_ } %$args };
}
sub _oauth_authenticated_request {
my ($self, $http_method, $uri, $args, $authenticate) = @_;
delete $args->{source}; # not necessary with OAuth requests
my $is_multipart = grep { ref } %$args;
my $msg;
if ( $authenticate && $self->authorized ) {
local $Net::OAuth::SKIP_UTF8_DOUBLE_ENCODE_CHECK = 1;
my $request = $self->_make_oauth_request(
'protected resource',
request_url => $uri,
request_method => $http_method,
token => $self->access_token,
token_secret => $self->access_token_secret,
extra_params => $is_multipart ? {} : $args,
);
if ( $http_method =~ /^(?:GET|DELETE)$/ ) {
$msg = HTTP::Request->new($http_method, $request->to_url);
}
elsif ( $http_method eq 'POST' ) {
$msg = $is_multipart
? POST($request->request_url,
Authorization => $request->to_authorization_header,
Content_Type => 'form-data',
Content => [ %$args ],
)
: POST($$uri, Content => $request->to_post_body)
;
}
else {
croak "unexpected http_method: $http_method";
}
}
elsif ( $http_method eq 'GET' ) {
$uri->query_form($args);
$args = {};
$msg = GET($uri);
}
elsif ( $http_method eq 'POST' ) {
my $encoded_args = { %$args };
_encode_args($encoded_args);
$msg = $self->_mk_post_msg($uri, $args);
}
else {
croak "unexpected http_method: $http_method";
}
return $self->{ua}->request($msg);
}
sub _basic_authenticated_request {
my ($self, $http_method, $uri, $args, $authenticate) = @_;
_encode_args($args);
my $msg;
if ( $http_method =~ /^(?:GET|DELETE)$/ ) {
$uri->query_form($args);
$msg = HTTP::Request->new($http_method, $uri);
}
elsif ( $http_method eq 'POST' ) {
$msg = $self->_mk_post_msg($uri, $args);
}
else {
croak "unexpected HTTP method: $http_method";
}
if ( $authenticate && $self->{username} && $self->{password} ) {
$msg->headers->authorization_basic(@{$self}{qw/username password/});
}
return $self->{ua}->request($msg);
}
sub _mk_post_msg {
my ($self, $uri, $args) = @_;
# if any of the arguments are (array) refs, use form-data
return (grep { ref } values %$args)
? POST($uri, Content_Type => 'form-data', Content => [ %$args ])
: POST($uri, $args);
}
{ ### scope $api_def
my $api_def = [
[% FOREACH api IN [ [ 'Lists', '^legacy_' ], [ 'REST' ], [ 'Search' ] ] -%]
[ [% api.0 %] => [
[% FOREACH method IN get_methods_for(api.0, api.1) -%]
[ '[% method.name %]', {
aliases => [ qw/[% method.aliases.join(' ') %]/ ],
path => '[% method.path %]',
method => '[% method.method %]',
params => [ qw/[% method.params.join(' ') %]/ ],
required => [ qw/[% method.required.join(' ') %]/ ],
add_source => [% method.add_source %],
deprecated => [% method.deprecated %],
authenticate => [% method.authenticate %],
booleans => [ qw/[% method.booleans.join(' ') %]/ ],
base_url_method => '[% method.base_url_method %]',
} ],
[% END -%]
] ],
[% END -%]
];
my $with_url_arg = sub {
my ($path, $args) = @_;
if ( defined(my $id = delete $args->{id}) ) {
$path .= uri_escape($id);
}
else {
chop($path);
}
return $path;
};
while ( @$api_def ) {
my $api = shift @$api_def;
my $api_name = shift @$api;
my $methods = shift @$api;
for my $method ( @$methods ) {
my $name = shift @$method;
my %options = %{ shift @$method };
my ($arg_names, $path) = @options{qw/required path/};
$arg_names = $options{params} if @$arg_names == 0 && @{$options{params}} == 1;
my $modify_path = $path =~ s,/id$,/, ? $with_url_arg : sub { $_[0] };
my $code = sub {
my $self = shift;
# copy callers args since we may add ->{source}
my $args = ref $_[-1] eq 'HASH' ? { %{pop @_} } : {};
if ( (my $legacy_method = $self->can("legacy_$name")) && (
exists $$args{-legacy_lists_api} ? delete $$args{-legacy_lists_api}
: $self->{legacy_lists_api} ) ) {
return $self->$legacy_method(@_, $args);
}
# just in case it's included where it shouldn't be:
delete $args->{-legacy_lists_api};
croak sprintf "$name expected %d args", scalar @$arg_names if @_ > @$arg_names;
# promote positional args to named args
for ( my $i = 0; @_; ++$i ) {
my $param = $arg_names->[$i];
croak "duplicate param $param: both positional and named"
if exists $args->{$param};
$args->{$param} = shift;
}
$args->{source} ||= $self->{source} if $options{add_source};
my $authenticate = exists $args->{authenticate} ? delete $args->{authenticate}
: $options{authenticate}
;
# promote boolean parameters
for my $boolean_arg ( @{ $options{booleans} } ) {
if ( exists $args->{$boolean_arg} ) {
next if $args->{$boolean_arg} =~ /^true|false$/;
$args->{$boolean_arg} = $args->{$boolean_arg} ? 'true' : 'false';
}
}
# Workaround Twitter bug: any value passed for skip_user is treated as true.
# The only way to get 'false' is to not pass the skip_user at all.
delete $args->{skip_user} if exists $args->{skip_user} && $args->{skip_user} eq 'false';
# replace placeholder arguments
my $local_path = $path;
$local_path =~ s,/:id$,, unless exists $args->{id}; # remove optional trailing id
$local_path =~ s/:(\w+)/delete $args->{$1} or croak "required arg '$1' missing"/eg;
# stringify lists
for ( qw/screen_name user_id/ ) {
$args->{$_} = join(',' => @{ $args->{$_} }) if ref $args->{$_} eq 'ARRAY';
}
my $uri = URI->new($self->{$options{base_url_method}} . "/$local_path.json");
return $self->_parse_result(
$self->_authenticated_request($options{method}, $uri, $args, $authenticate)
);
};
no strict 'refs';
$name = $_, *{__PACKAGE__ . "::$_"} = $code for $name, @{$options{aliases}};
}
}
# catch expected error and promote it to an undef
for ( qw/list_members is_list_member list_subscribers is_list_subscriber
legacy_list_members legacy_is_list_member legacy_list_subscribers legacy_is_list_subscriber/ ) {
my $orig = __PACKAGE__->can($_) or die;
my $code = sub {
my $r = eval { $orig->(@_) };
if ( $@ ) {
return if $@ =~ /The specified user is not a (?:memb|subscrib)er of this list/;
die $@;
}
return $r;
};
no strict 'refs';
no warnings 'redefine';
*{__PACKAGE__ . "::$_"} = $code;
}
} ### end scope for $api_def
sub _from_json {
my ($self, $json) = @_;
return eval { $json_handler->decode($json) };
}
sub _parse_result {
my ($self, $res) = @_;
# workaround for Laconica API returning bools as strings
# (Fixed in Laconi.ca 0.7.4)
my $content = $res->content;
$content =~ s/^"(true|false)"$/$1/;
my $obj = $self->_from_json($content);
# Twitter sometimes returns an error with status code 200
if ( $obj && ref $obj eq 'HASH' && exists $obj->{error} ) {
die Net::Twitter::Lite::Error->new(twitter_error => $obj, http_response => $res);
}
return $obj if $res->is_success && defined $obj;
my $error = Net::Twitter::Lite::Error->new(http_response => $res);
$error->twitter_error($obj) if ref $obj;
die $error;
}
1;
__END__
=head1 NAME
Net::Twitter::Lite - A perl interface to the Twitter API
=head1 VERSION
This document describes Net::Twitter::Lite version [% VERSION %]
=head1 SYNOPSIS
use Net::Twitter::Lite;
my $nt = Net::Twitter::Lite->new(
username => $user,
password => $password
legacy_lists_api => 0,
);
my $result = eval { $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";
}
};
warn "$@\n" if $@;
=head1 DESCRIPTION
This module provides a perl interface to the Twitter APIs. It uses the same API definitions
as L<Net::Twitter>, but without the extra bells and whistles and without the additional dependencies.
Same great taste, less filling.
This module is related to, but is not part of the C<Net::Twitter>
distribution. It's API methods and API method documentation are generated
from C<Net::Twitter>'s internals. It exists for those who cannot, or prefer
not to install L<Moose> and its dependencies.
You should consider upgrading to C<Net::Twitter> for additional functionality,
finer grained control over features, full backwards compatibility with older
versions of C<Net::Twitter>, and additional error handling options.
=head1 CLIENT CODE CHANGES REQUIRED
=head2 Legacy Lists API
Twitter re-implemented the Lists API using new endpoints and semantics. For backwards
compatibility, this version of C<Net::Twitter::Lite> defaults to the deprecated, legacy
endpoints and semantics. It issues a warning if the C<legacy_lists_api> option to new
is not provided.
To enable the new Lists endpoints and semantics, pass C<(legacy_lists_api => 0)> to
C<new>. To disable the warning, and keep the backwards compatible endpoints and
semantics, pass C<(legacy_lists_api => 1)> to C<new>.
The C<legacy_lists_api> option to C<new> sets the default for all lists API method
calls. You can override the default an each API call by passing a C<-legacy_lists_api>
option set to 1 or 0.
Support for C<legacy_lists_api> option will be removed in a future version and the
option to C<new> will be silently ignored.
=head2 netrc option
The default C<apiurl> changed in version 0.08006. The change should be
transparent to client code, unless you're using the C<netrc> option. If so,
you'll need to either update the C<.netrc> entry and change the C<machine>
value from C<twitter.com> to C<api.twitter.com>, or set either the C<netrc>
or C<netrc_machine> options to C<twitter.com>.
$nt = Net::Twitter::Lite->new(netrc_machine => 'twitter.com', netrc => 1);
# -or-
$nt = Net::Twitter::Lite->new(netrc => 'twitter.com');
=head2 OAuth requires callback parameter
Beginning with version 0.03, it is necessary for web applications using OAuth
authentication to pass the C<callback> parameter to C<get_authorization_url>.
In the absence of a callback parameter, when the user authorizes the
application a PIN number is displayed rather than redirecting the user back to
your site.
=head1 MIGRATING FROM NET::TWITTER 2.x
If you are migrating from Net::Twitter 2.12 (or an earlier version), you may
need to make some minor changes to your application code in order to user
Net::Twitter::Lite successfully.
The primary difference is in error handling. Net::Twitter::Lite throws
exceptions on error. It does not support the C<get_error>, C<http_code>, and
C<http_message> methods used in Net::Twitter 2.12 and prior versions.
Instead of
# DON'T!
my $friends = $nt->friends();
if ( $friends ) {
# process $friends
}
wrap the API call in an eval block:
# DO!
my $friends = eval { $nt->friends() };
if ( $friends ) {
# process $friends
}
Here's a much more complex example taken from application code using
Net::Twitter 2.12:
# DON'T!
my $friends = $nt->friends();
if ( $friends ) {
# process $friends
}
else {
my $error = $nt->get_error;
if ( ref $error ) {
if ( ref($error) eq 'HASH' && exists $error->{error} ) {
$error = $error->{error};
}
else {
$error = 'Unexpected error type ' . ref($error);
}
}
else {
$error = $nt->http_code() . ": " . $nt->http_message;
}
warn "$error\n";
}
The Net::Twitter::Lite equivalent is:
# DO!
eval {
my $friends = $nt->friends();
# process $friends
};
warn "$@\n" if $@;
return;
In Net::Twitter::Lite, an error can always be treated as a string. See
L<Net::Twitter::Lite::Error>. The HTTP Status Code and HTTP Message are both
available. Rather than accessing them via the Net::Twitter::Lite instance,
you access them via the Net::Twitter::Lite::Error instance thrown as an error.
For example:
# DO!
eval {
my $friends = $nt->friends();
# process $friends
};
if ( my $error = $@ ) {
if ( blessed $error && $error->isa("Net::Twitter::Lite::Error)
&& $error->code() == 502 ) {
$error = "Fail Whale!";
}
warn "$error\n";
}
=head2 Unsupported Net::Twitter 2.12 options to C<new>
Net::Twitter::Lite does not support the following Net::Twitter 2.12 options to
C<new>. It silently ignores them:
=over 4
=item no_fallback
If Net::Twitter::Lite is unable to create an instance of the class specified in
the C<useragent_class> option to C<new>, it dies, rather than falling back to
an LWP::UserAgent object. You really don't want a failure to create the
C<useragent_class> you specified to go unnoticed.
=item twittervision
Net::Twitter::Lite does not support the TwitterVision API. Use Net::Twitter,
instead, if you need it.
=item skip_arg_validation
Net::Twitter::Lite does not API parameter validation. This is a feature. If
Twitter adds a new option to an API method, you can use it immediately by
passing it in the HASH ref to the API call.
Net::Twitter::Lite relies on Twitter to validate its own parameters. An
appropriate exception will be thrown if Twitter reports a parameter error.
=item die_on_validation
See L</skip_arg_validation>. If Twitter returns an bad parameter error, an
appropriate exception will be thrown.
=item arrayref_on_error
This option allowed the following idiom in Net::Twitter 2.12:
# DON'T!
for my $friend ( @{ $nt->friends() } ) {
# process $friend
}
The equivalent Net::Twitter::Lite code is:
# DO!
eval {
for my $friend ( @{ $nt->friends() } ) {
# process $friend
}
};
=back
=head2 Unsupported Net::Twitter 2.12 methods
=over 4
=item clone
The C<clone> method was added to Net::Twitter 2.x to allow safe error handling
in an environment where concurrent requests are handled, for example, when
using LWP::UserAgent::POE as the C<useragent_class>. Since Net::Twitter::Lite
throws exceptions instead of stashing them in the Net::Twitter::Lite instance,
it is safe in a current request environment, obviating the need for C<clone>.
=item get_error
=item http_code
=item http_message
These methods are replaced by Net::Twitter::Lite::Error. An instance of that
class is thrown errors are encountered.
=back
=head1 METHODS AND ARGUMENTS
=over 4
=item new
This constructs a C<Net::Twitter::Lite> object. It takes several named parameters,
all of them optional:
=over 4
=item username
This is the screen name or email used to authenticate with Twitter. Use this
option for Basic Authentication, only.
=item password
This is the password used to authenticate with Twitter. Use this option for
Basic Authentication, only.
=item consumer_key
A string containing the OAuth consumer key provided by Twitter when an application
is registered. Use this option for OAuth authentication, only.
=item consumer_secret
A string containing the OAuth consumer secret. Use this option for OAuth authentication, only.
the C<OAuth> trait is included.
=item oauth_urls
A HASH ref of URLs to be used with OAuth authentication. Defaults to:
{
request_token_url => "http://twitter.com/oauth/request_token",
authorization_url => "http://twitter.com/oauth/authorize",
access_token_url => "http://twitter.com/oauth/access_token",
xauth_url => "https://twitter.com/oauth/access_token",
}
=item clientname
The value for the C<X-Twitter-Client-Name> HTTP header. It defaults to "Perl
Net::Twitter::Lite".
=item clientver
The value for the C<X-Twitter-Client-Version> HTTP header. It defaults to
current version of the C<Net::Twitter::Lite> module.
=item clienturl
The value for the C<X-Twitter-Client-URL> HTTP header. It defaults to the
search.cpan.org page for the C<Net::Twitter::Lite> distribution.
=item useragent_class
The C<LWP::UserAgent> compatible class used internally by C<Net::Twitter::Lite>. It
defaults to "LWP::UserAgent". For L<POE> 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<useragent_class>, above. It defaults to {} (an empty HASH ref).
=item useragent
The value for C<User-Agent> HTTP header. It defaults to
"Net::Twitter::Lite/[% VERSION %] (Perl)".
=item source
The value used in the C<source> parameter of API method calls. It is currently
only used in the C<update> method in the REST API. It defaults to
"twitterpm". This results in the text "from Net::Twitter" rather than "from
web" for status messages posted from C<Net::Twitter::Lite> when displayed via the
Twitter web interface. The value for this parameter is provided by Twitter
when a Twitter application is registered. See
L<http://apiwiki.twitter.com/FAQ#HowdoIget%E2%80%9CfromMyApp%E2%80%9DappendedtoupdatessentfrommyAPIapplication>.
=item apiurl
The URL for the Twitter API. This defaults to "http://twitter.com".
=item identica
If set to 1 (or any value that evaluates to true), apiurl defaults to
"http://identi.ca/api".
=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<machine> key to look up in C<.netrc> to obtain
credentials. If set to 1, Net::Twitter::Lite will use the value of the C<netrc_machine>
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::Lite->new(netrc => 1);
$nt = Net::Twitter::Lite->new(netrc => 'semifor.twitter.com');
=item netrc_machine
(Optional) Sets the C<machine> entry to look up in C<.netrc> when C<<netrc => 1>>
is used. Defaults to C<api.twitter.com>.
=item legacy_lists_api
If set to 1, this option enables backwards compatibility by using the now deprecated
endpoints and semantics for lists API methods. If set to 0, the new endpoints and
semantics will be used. Only the new lists API methods are documented here.
If you do not provide this option to C<new> a warning is issued. Support for
this option and the legacy lists API methods will be removed in a future version.
=back
=back
=head2 BASIC AUTHENTICATION METHODS
=over 4
=item credentials($username, $password)
Set the credentials for Basic Authentication. This is helpful for managing
multiple accounts.
=back
=head2 OAUTH METHODS
=over 4
=item authorized
Whether the client has the necessary credentials to be authorized.
Note that the credentials may be wrong and so the request may fail.
=item request_access_token
Returns list including the access token, access token secret, user_id, and
screen_name for this user. Takes a HASH of arguments. The C<verifier> argument
is required. See L</OAUTH EXAMPLES>.
The user must have authorized this app at the url given by C<get_authorization_url> first.
For desktop applications, the Twitter authorization page will present the user
with a PIN number. Prompt the user for the PIN number, and pass it as the
C<verifier> argument to request_access_token.
Returns the access token and access token secret but also sets them internally
so that after calling this method, you can immediately call API methods
requiring authentication.
=item get_authorization_url(callback => $callback_url)
Get the URL used to authorize the user. Returns a C<URI> object. For web
applications, pass your applications callback URL as the C<callback> parameter.
No arguments are required for desktop applications (C<callback> defaults to
C<oob>, out-of-band).
=item get_authentication_url(callback => $callback_url)
Get the URL used to authenticate the user with "Sign in with Twitter"
authentication flow. Returns a C<URI> object. For web applications, pass your
applications callback URL as the C<callback> parameter. No arguments are
required for desktop applications (C<callback> defaults to C<oob>, out-of-band).
=item xauth($username, $password)
Exchanges a username and password for OAuth tokens. Your application must be