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

release-1.10release-1.7release-1.8release-1.9
Last change on this file since b25b5a4 was b25b5a4, checked in by Nelson Elhage <nelhage@mit.edu>, 15 years ago
Let verify_credentials take as long as it likes. Move the $twitter->{ua}->timeout(1); call to after the initial login. This seems to help with bogus login failures on startup.
  • Property mode set to 100644
File size: 8.6 KB
RevLine 
[e54f2fa]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;
[8618438]21use BarnOwl::Message::Twitter;
22use HTML::Entities;
[e54f2fa]23
[f0550c5]24our $twitter;
[9bedca0]25my $user     = BarnOwl::zephyr_getsender();
26my ($class)  = ($user =~ /(^[^@]+)/);
27my $instance = "status";
28my $opcode   = "twitter";
29
[e54f2fa]30sub fail {
31    my $msg = shift;
[9bedca0]32    undef $twitter;
[e54f2fa]33    BarnOwl::admin_message('Twitter Error', $msg);
[4cf4067]34    die("Twitter Error: $msg\n");
[e54f2fa]35}
36
[d689fc7]37my $desc = <<'END_DESC';
[d1bb4f3]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
[d689fc7]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);
[e54f2fa]69
[927c186]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
[d775050]80my $conffile = BarnOwl::get_config_dir() . "/twitter";
81open(my $fh, "<", "$conffile") || fail("Unable to read $conffile");
[e54f2fa]82my $cfg = do {local $/; <$fh>};
83close($fh);
84eval {
85    $cfg = from_json($cfg);
86};
[9bedca0]87if($@) {
88    fail("Unable to parse ~/.owl/twitter: $@");
[e54f2fa]89}
90
[9bedca0]91$twitter  = Net::Twitter->new(username   => $cfg->{user} || $user,
92                              password   => $cfg->{password},
[104f7d9]93                              source => 'barnowl');
[e54f2fa]94
95if(!defined($twitter->verify_credentials())) {
[d775050]96    fail("Invalid twitter credentials");
[e54f2fa]97}
98
[b25b5a4]99eval {
100    $twitter->{ua}->timeout(1);
101};
102
[d1bb4f3]103sub match {
104    my $val = shift;
105    my $pat = shift;
106    return $pat eq "*" || ($val eq $pat);
107}
108
[e54f2fa]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
[d1bb4f3]113       && match($m->class, $class)
114       && match($m->instance, $instance)
115       && match($m->opcode, $opcode)
[e54f2fa]116       && $m->auth eq 'YES') {
117        twitter($m->body);
118    }
119}
120
[927c186]121our $last_poll        = 0;
122our $last_direct_poll = 0;
123our $last_id          = undef;
124our $last_direct      = undef;
125
[8618438]126unless(defined($last_id)) {
[927c186]127    eval {
128        $last_id = $twitter->friends_timeline({count => 1})->[0]{id};
129    };
[706ff88]130    $last_id = 0 unless defined($last_id);
[927c186]131}
132
133unless(defined($last_direct)) {
134    eval {
135        $last_direct = $twitter->direct_messages()->[0]{id};
136    };
[706ff88]137    $last_direct = 0 unless defined($last_direct);
[8618438]138}
139
140sub poll_messages {
[927c186]141    poll_twitter();
142    poll_direct();
143}
144
145sub twitter_error {
146    my $ratelimit = $twitter->rate_limit_status;
[f0550c5]147    unless(defined($ratelimit) && ref($ratelimit) eq 'HASH') {
[927c186]148        # Twitter's just sucking, sleep for 5 minutes
149        $last_direct_poll = $last_poll = time + 60*5;
[bab79f8]150        # die("Twitter seems to be having problems.\n");
151        return;
[927c186]152    }
[f0550c5]153    if(exists($ratelimit->{remaining_hits})
154       && $ratelimit->{remaining_hits} <= 0) {
[927c186]155        $last_direct_poll = $last_poll = $ratelimit->{reset_time_in_seconds};
156        die("Twitter: ratelimited until " . $ratelimit->{reset_time} . "\n");
[f0550c5]157    } elsif(exists($ratelimit->{error})) {
158        die("Twitter: ". $ratelimit->{error} . "\n");
159        $last_direct_poll = $last_poll = time + 60*20;
[927c186]160    }
161}
162
163sub poll_twitter {
164    return unless ( time - $last_poll ) >= 60;
[8618438]165    $last_poll = time;
[927c186]166    return unless BarnOwl::getvar('twitter:poll') eq 'on';
167
[8618438]168    my $timeline = $twitter->friends_timeline( { since_id => $last_id } );
[f0550c5]169    unless(defined($timeline) && ref($timeline) eq 'ARRAY') {
[927c186]170        twitter_error();
[8618438]171        return;
172    };
173    if ( scalar @$timeline ) {
174        for my $tweet ( reverse @$timeline ) {
175            if ( $tweet->{id} <= $last_id ) {
176                next;
177            }
178            my $msg = BarnOwl::Message->new(
179                type      => 'Twitter',
180                sender    => $tweet->{user}{screen_name},
181                recipient => $cfg->{user} || $user,
182                direction => 'in',
183                source    => decode_entities($tweet->{source}),
[d689fc7]184                location  => decode_entities($tweet->{user}{location}||""),
[8618438]185                body      => decode_entities($tweet->{text})
186               );
187            BarnOwl::queue_message($msg);
188        }
189        $last_id = $timeline->[0]{id};
190    } else {
191        # BarnOwl::message("No new tweets...");
192    }
193}
194
[927c186]195sub poll_direct {
196    return unless ( time - $last_direct_poll) >= 120;
197    $last_direct_poll = time;
198    return unless BarnOwl::getvar('twitter:poll') eq 'on';
199
200    my $direct = $twitter->direct_messages( { since_id => $last_direct } );
[f0550c5]201    unless(defined($direct) && ref($direct) eq 'ARRAY') {
[927c186]202        twitter_error();
203        return;
204    };
205    if ( scalar @$direct ) {
206        for my $tweet ( reverse @$direct ) {
207            if ( $tweet->{id} <= $last_direct ) {
208                next;
209            }
210            my $msg = BarnOwl::Message->new(
211                type      => 'Twitter',
212                sender    => $tweet->{sender}{screen_name},
213                recipient => $cfg->{user} || $user,
214                direction => 'in',
215                location  => decode_entities($tweet->{sender}{location}||""),
216                body      => decode_entities($tweet->{text}),
217                isprivate => 'true'
218               );
219            BarnOwl::queue_message($msg);
220        }
221        $last_direct = $direct->[0]{id};
222    } else {
223        # BarnOwl::message("No new tweets...");
224    }
225}
226
[e54f2fa]227sub twitter {
228    my $msg = shift;
[927c186]229    if($msg =~ m{\Ad\s+([^\s])+(.*)}sm) {
230        twitter_direct($1, $2);
231    } elsif(defined $twitter) {
[9bedca0]232        $twitter->update($msg);
233    }
[e54f2fa]234}
235
[927c186]236sub twitter_direct {
237    my $who = shift;
238    my $msg = shift;
239    if(defined $twitter) {
240        $twitter->new_direct_message({
241            user => $who,
242            text => $msg
243           });
[c1e5316]244        if(BarnOwl::getvar("displayoutgoing") eq 'on') {
245            my $tweet = BarnOwl::Message->new(
246                type      => 'Twitter',
247                sender    => $cfg->{user} || $user,
248                recipient => $who, 
249                direction => 'out',
250                body      => $msg,
251                isprivate => 'true'
252               );
253            BarnOwl::queue_message($tweet);
254        }
[927c186]255    }
256}
257
[6babb75]258sub twitter_atreply {
259    my $to  = shift;
260    my $msg = shift;
261    twitter("@".$to." ".$msg);
262}
263
[4cf4067]264BarnOwl::new_command(twitter => \&cmd_twitter, {
265    summary     => 'Update Twitter from BarnOwl',
266    usage       => 'twitter [message]',
267    description => 'Update Twitter. If MESSAGE is provided, use it as your status.'
268    . "\nOtherwise, prompt for a status message to use."
269   });
270
[927c186]271BarnOwl::new_command('twitter-direct' => \&cmd_twitter_direct, {
272    summary     => 'Send a Twitter direct message',
273    usage       => 'twitter-direct USER',
274    description => 'Send a Twitter Direct Message to USER'
275   });
276
[6babb75]277BarnOwl::new_command( 'twitter-atreply' => sub { cmd_twitter_atreply(@_); },
278    {
279    summary     => 'Send a Twitter @ message',
280    usage       => 'twitter-atreply USER',
281    description => 'Send a Twitter @reply Message to USER'
282    }
283);
284
285
[4cf4067]286sub cmd_twitter {
287    my $cmd = shift;
288    if(@_) {
289        my $status = join(" ", @_);
290        twitter($status);
291    } else {
292      BarnOwl::start_edit_win('What are you doing?', \&twitter);
293    }
294}
295
[927c186]296sub cmd_twitter_direct {
297    my $cmd = shift;
298    my $user = shift;
299    die("Usage: $cmd USER\n") unless $user;
300    BarnOwl::start_edit_win("$cmd $user", sub{twitter_direct($user, shift)});
301}
302
[6babb75]303sub cmd_twitter_atreply {
304    my $cmd  = shift;
305    my $user = shift;
306    BarnOwl::start_edit_win("Reply to \@" . $user, sub { twitter_atreply($user, shift) });
307}
308
[72b61dd]309eval {
310    $BarnOwl::Hooks::receiveMessage->add("BarnOwl::Module::Twitter::handle_message");
[8618438]311    $BarnOwl::Hooks::mainLoop->add("BarnOwl::Module::Twitter::poll_messages");
[72b61dd]312};
313if($@) {
314    $BarnOwl::Hooks::receiveMessage->add(\&handle_message);
[8618438]315    $BarnOwl::Hooks::mainLoop->add(\&poll_messages);
[72b61dd]316}
[e54f2fa]317
[5aabe2d7]318BarnOwl::filter('twitter type ^twitter$');
[8618438]319
[e54f2fa]3201;
Note: See TracBrowser for help on using the repository browser.