source: lib/BarnOwl/Module/Twitter.pm @ bab79f8

release-1.10release-1.7release-1.8release-1.9
Last change on this file since bab79f8 was bab79f8, checked in by Nelson Elhage <nelhage@mit.edu>, 15 years ago
Don't spew error messages when Twitter sucks.
  • Property mode set to 100644
File size: 8.3 KB
Line 
1use warnings;
2use strict;
3
4=head1 NAME
5
6BarnOwl::Module::Twitter
7
8=head1 DESCRIPTION
9
10Post outgoing zephyrs from -c $USER -i status -O TWITTER to Twitter
11
12=cut
13
14package BarnOwl::Module::Twitter;
15
16use Net::Twitter;
17use JSON;
18
19use BarnOwl;
20use BarnOwl::Hooks;
21use BarnOwl::Message::Twitter;
22use HTML::Entities;
23
24my $twitter;
25my $user     = BarnOwl::zephyr_getsender();
26my ($class)  = ($user =~ /(^[^@]+)/);
27my $instance = "status";
28my $opcode   = "twitter";
29
30sub fail {
31    my $msg = shift;
32    undef $twitter;
33    BarnOwl::admin_message('Twitter Error', $msg);
34    die("Twitter Error: $msg\n");
35}
36
37my $desc = <<'END_DESC';
38BarnOwl::Module::Twitter will watch for authentic zephyrs to
39-c $twitter:class -i $twitter:instance -O $twitter:opcode
40from your sender and mirror them to Twitter.
41
42A value of '*' in any of these fields acts a wildcard, accepting
43messages with any value of that field.
44END_DESC
45BarnOwl::new_variable_string(
46    'twitter:class',
47    {
48        default     => $class,
49        summary     => 'Class to watch for Twitter messages',
50        description => $desc
51    }
52);
53BarnOwl::new_variable_string(
54    'twitter:instance',
55    {
56        default => $instance,
57        summary => 'Instance on twitter:class to watch for Twitter messages.',
58        description => $desc
59    }
60);
61BarnOwl::new_variable_string(
62    'twitter:opcode',
63    {
64        default => $opcode,
65        summary => 'Opcode for zephyrs that will be sent as twitter updates',
66        description => $desc
67    }
68);
69
70BarnOwl::new_variable_bool(
71    'twitter:poll',
72    {
73        default => 1,
74        summary => 'Poll Twitter for incoming messages',
75        description => "If set, will poll Twitter every minute for normal updates,\n"
76        . 'and every two minutes for direct message'
77     }
78 );
79
80my $conffile = BarnOwl::get_config_dir() . "/twitter";
81open(my $fh, "<", "$conffile") || fail("Unable to read $conffile");
82my $cfg = do {local $/; <$fh>};
83close($fh);
84eval {
85    $cfg = from_json($cfg);
86};
87if($@) {
88    fail("Unable to parse ~/.owl/twitter: $@");
89}
90
91$twitter  = Net::Twitter->new(username   => $cfg->{user} || $user,
92                              password   => $cfg->{password},
93                              source => 'barnowl');
94
95eval {
96    $twitter->{ua}->timeout(1);
97};
98
99if(!defined($twitter->verify_credentials())) {
100    fail("Invalid twitter credentials");
101}
102
103sub match {
104    my $val = shift;
105    my $pat = shift;
106    return $pat eq "*" || ($val eq $pat);
107}
108
109sub handle_message {
110    my $m = shift;
111    ($class, $instance, $opcode) = map{BarnOwl::getvar("twitter:$_")} qw(class instance opcode);
112    if($m->sender eq $user
113       && match($m->class, $class)
114       && match($m->instance, $instance)
115       && match($m->opcode, $opcode)
116       && $m->auth eq 'YES') {
117        twitter($m->body);
118    }
119}
120
121our $last_poll        = 0;
122our $last_direct_poll = 0;
123our $last_id          = undef;
124our $last_direct      = undef;
125
126unless(defined($last_id)) {
127    eval {
128        $last_id = $twitter->friends_timeline({count => 1})->[0]{id};
129    };
130    $last_id = 0 unless defined($last_id);
131}
132
133unless(defined($last_direct)) {
134    eval {
135        $last_direct = $twitter->direct_messages()->[0]{id};
136    };
137    $last_direct = 0 unless defined($last_direct);
138}
139
140sub poll_messages {
141    poll_twitter();
142    poll_direct();
143}
144
145sub twitter_error {
146    my $ratelimit = $twitter->rate_limit_status;
147    unless(defined($ratelimit)) {
148        # Twitter's just sucking, sleep for 5 minutes
149        $last_direct_poll = $last_poll = time + 60*5;
150        # die("Twitter seems to be having problems.\n");
151        return;
152    }
153    if($ratelimit->{remaining_hits} <= 0) {
154        $last_direct_poll = $last_poll = $ratelimit->{reset_time_in_seconds};
155        die("Twitter: ratelimited until " . $ratelimit->{reset_time} . "\n");
156    }
157}
158
159sub poll_twitter {
160    return unless ( time - $last_poll ) >= 60;
161    $last_poll = time;
162    return unless BarnOwl::getvar('twitter:poll') eq 'on';
163
164    my $timeline = $twitter->friends_timeline( { since_id => $last_id } );
165    unless(defined($timeline)) {
166        twitter_error();
167        return;
168    };
169    if ( scalar @$timeline ) {
170        for my $tweet ( reverse @$timeline ) {
171            if ( $tweet->{id} <= $last_id ) {
172                next;
173            }
174            my $msg = BarnOwl::Message->new(
175                type      => 'Twitter',
176                sender    => $tweet->{user}{screen_name},
177                recipient => $cfg->{user} || $user,
178                direction => 'in',
179                source    => decode_entities($tweet->{source}),
180                location  => decode_entities($tweet->{user}{location}||""),
181                body      => decode_entities($tweet->{text})
182               );
183            BarnOwl::queue_message($msg);
184        }
185        $last_id = $timeline->[0]{id};
186    } else {
187        # BarnOwl::message("No new tweets...");
188    }
189}
190
191sub poll_direct {
192    return unless ( time - $last_direct_poll) >= 120;
193    $last_direct_poll = time;
194    return unless BarnOwl::getvar('twitter:poll') eq 'on';
195
196    my $direct = $twitter->direct_messages( { since_id => $last_direct } );
197    unless(defined($direct)) {
198        twitter_error();
199        return;
200    };
201    if ( scalar @$direct ) {
202        for my $tweet ( reverse @$direct ) {
203            if ( $tweet->{id} <= $last_direct ) {
204                next;
205            }
206            my $msg = BarnOwl::Message->new(
207                type      => 'Twitter',
208                sender    => $tweet->{sender}{screen_name},
209                recipient => $cfg->{user} || $user,
210                direction => 'in',
211                location  => decode_entities($tweet->{sender}{location}||""),
212                body      => decode_entities($tweet->{text}),
213                isprivate => 'true'
214               );
215            BarnOwl::queue_message($msg);
216        }
217        $last_direct = $direct->[0]{id};
218    } else {
219        # BarnOwl::message("No new tweets...");
220    }
221}
222
223sub twitter {
224    my $msg = shift;
225    if($msg =~ m{\Ad\s+([^\s])+(.*)}sm) {
226        twitter_direct($1, $2);
227    } elsif(defined $twitter) {
228        $twitter->update($msg);
229    }
230}
231
232sub twitter_direct {
233    my $who = shift;
234    my $msg = shift;
235    if(defined $twitter) {
236        $twitter->new_direct_message({
237            user => $who,
238            text => $msg
239           });
240        if(BarnOwl::getvar("displayoutgoing") eq 'on') {
241            my $tweet = BarnOwl::Message->new(
242                type      => 'Twitter',
243                sender    => $cfg->{user} || $user,
244                recipient => $who, 
245                direction => 'out',
246                body      => $msg,
247                isprivate => 'true'
248               );
249            BarnOwl::queue_message($tweet);
250        }
251    }
252}
253
254sub twitter_atreply {
255    my $to  = shift;
256    my $msg = shift;
257    twitter("@".$to." ".$msg);
258}
259
260BarnOwl::new_command(twitter => \&cmd_twitter, {
261    summary     => 'Update Twitter from BarnOwl',
262    usage       => 'twitter [message]',
263    description => 'Update Twitter. If MESSAGE is provided, use it as your status.'
264    . "\nOtherwise, prompt for a status message to use."
265   });
266
267BarnOwl::new_command('twitter-direct' => \&cmd_twitter_direct, {
268    summary     => 'Send a Twitter direct message',
269    usage       => 'twitter-direct USER',
270    description => 'Send a Twitter Direct Message to USER'
271   });
272
273BarnOwl::new_command( 'twitter-atreply' => sub { cmd_twitter_atreply(@_); },
274    {
275    summary     => 'Send a Twitter @ message',
276    usage       => 'twitter-atreply USER',
277    description => 'Send a Twitter @reply Message to USER'
278    }
279);
280
281
282sub cmd_twitter {
283    my $cmd = shift;
284    if(@_) {
285        my $status = join(" ", @_);
286        twitter($status);
287    } else {
288      BarnOwl::start_edit_win('What are you doing?', \&twitter);
289    }
290}
291
292sub cmd_twitter_direct {
293    my $cmd = shift;
294    my $user = shift;
295    die("Usage: $cmd USER\n") unless $user;
296    BarnOwl::start_edit_win("$cmd $user", sub{twitter_direct($user, shift)});
297}
298
299sub cmd_twitter_atreply {
300    my $cmd  = shift;
301    my $user = shift;
302    BarnOwl::start_edit_win("Reply to \@" . $user, sub { twitter_atreply($user, shift) });
303}
304
305eval {
306    $BarnOwl::Hooks::receiveMessage->add("BarnOwl::Module::Twitter::handle_message");
307    $BarnOwl::Hooks::mainLoop->add("BarnOwl::Module::Twitter::poll_messages");
308};
309if($@) {
310    $BarnOwl::Hooks::receiveMessage->add(\&handle_message);
311    $BarnOwl::Hooks::mainLoop->add(\&poll_messages);
312}
313
314BarnOwl::filter('twitter type ^twitter$');
315
3161;
Note: See TracBrowser for help on using the repository browser.