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

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