8 # When Net::Twitter::Lite encounters a Twitter API error or a network error,
9 # it throws a Net::Twitter::Lite::Error object.
10 # You can catch and process these exceptions by using eval blocks and testing $@
11 ## from http://search.cpan.org/perldoc?Net::Twitter::Lite#ERROR_HANDLING
12 use Net::Twitter::Lite;
16 my $conf = loadconf("$Bin/config.yml");
17 if (! defined $conf) {
18 die "$0: cannot parse config file.\n";
20 my $stat = loadconf("$Bin/status.yml");
21 if (! defined $stat) {
25 my $bot = login($conf);
26 if (! $bot->authorized) {
27 die "$0: this client is not yet authorized.\n";
33 $tweet = or_search($bot, $conf->{hashtag}, $stat->{search});
35 %tweets = (%tweets, %$tweet);
38 $tweet = mentions_ids($bot, $stat->{mention});
40 %tweets = (%tweets, %$tweet);
43 foreach my $id (sort keys %tweets) {
44 if ($tweets{$id} eq 'retweet') {
47 sleep($conf->{sleep});
49 # $tweets->{$id} eq 'search' => found by search API
50 # eq 'mention' => found by mention API
53 $res = $bot->retweet($id);
57 warn "status_id => $id\n";
61 $stat->{$tweets{$id}} = $id;
65 # save last status to yaml file
66 YAML::Tiny::DumpFile("$Bin/status.yml", $stat);
71 # load configration data from yaml formatted file
72 # param => scalar string of filename
73 # ret => hash object of yaml data
77 my $yaml = YAML::Tiny->read($file);
80 warn "$0: '$file' $!\n";
87 # make Net::Twitter::Lite object and login
88 # param => hash object of configration
89 # ret => Net::Twitter::Lite object
93 my $bot = Net::Twitter::Lite->new(
94 consumer_key => $conf->{consumer_key},
95 consumer_secret => $conf->{consumer_secret},
98 $bot->access_token($conf->{access_token});
99 $bot->access_token_secret($conf->{access_token_secret});
105 # search tweets containing keywords
106 # param => Net::Twitter::Lite object, ArrayRef of keywords, since_id
107 # ret => HashRef of status_id (timeline order is destroyed)
108 # or undef (none is found)
111 my $keywords = shift @_;
112 my $since_id = shift @_ || 1;
115 foreach my $word (@$keywords) {
131 since_id => $since_id,
135 if ($res->{results}) {
136 foreach my $tweet (@{$res->{results}}) {
137 my $res = $bot->show_status($tweet->{id});
138 if ($res->{retweeted_status}) {
139 $ids->{$tweet->{id}} = 'retweet';
142 $ids->{$tweet->{id}} = 'search';
155 # return status_ids mentioned to me
156 # param => Net::Twitter::Lite object, since_id
157 # ret => HashRef of status_id (timeline order is destroyed)
158 # or undef (none is found)
161 my $since_id = shift @_ || 1;
165 $res = $bot->mentions(
167 since_id => $since_id,
176 if ($res && @{$res}) {
178 map { $_->{id} => 'mention' } @{$res}
186 # output error message at eval error
188 use Scalar::Util qw(blessed);
190 if (blessed $@ && $@->isa('Net::Twitter::Lite::Error')) {
192 if ($@->twitter_error) {
193 my %twitter_error = %{$@->twitter_error};
195 $twitter_error{"$_ => "} = $twitter_error{$_} . "\n";
196 delete $twitter_error{$_}
197 } keys %twitter_error;
198 warn join("", %twitter_error);